From 19d6111c44b7194837ed092308abb4c6d0cb2308 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 18 Jul 2016 11:58:39 +0800 Subject: [PATCH 001/268] add WebView --- cocos2d/core/components/index.js | 1 + cocos2d/core/webview/CCSGWebView.js | 390 ++++++++++++++++++++++++++++ cocos2d/core/webview/CCWebView.js | 83 ++++++ gulp/tasks/modular.js | 4 + 4 files changed, 478 insertions(+) create mode 100644 cocos2d/core/webview/CCSGWebView.js create mode 100644 cocos2d/core/webview/CCWebView.js diff --git a/cocos2d/core/components/index.js b/cocos2d/core/components/index.js index 84ae107c59..882a958c13 100644 --- a/cocos2d/core/components/index.js +++ b/cocos2d/core/components/index.js @@ -44,6 +44,7 @@ module.exports = [ require('./CCLayout'), require('./CCEditBox'), require('./CCVideoPlayer'), + require('../webview/CCWebView'), require('./CCSpriteDistortion'), require('./CCLabelOutline'), ]; diff --git a/cocos2d/core/webview/CCSGWebView.js b/cocos2d/core/webview/CCSGWebView.js new file mode 100644 index 0000000000..4bd8d38094 --- /dev/null +++ b/cocos2d/core/webview/CCSGWebView.js @@ -0,0 +1,390 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + http://www.cocos.com + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + The software or tools in this License Agreement are licensed, not sold. + Chukong Aipu reserves all rights not expressly granted to you. + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +_ccsg.WebView = _ccsg.Node.extend(/** @lends _ccsg.VideoPlayer# */{ + + ctor: function (path) { + _ccsg.Node.prototype.ctor.call(this); + this._EventList = {}; + if(path) + this.loadURL(path); + }, + + setJavascriptInterfaceScheme: function(scheme){}, + loadData: function(data, MIMEType, encoding, baseURL){}, + loadHTMLString: function(string, baseURL){}, + /** + * Load an URL + * @param {String} url + */ + loadURL: function(url){ + this._renderCmd.updateURL(url); + this._dispatchEvent(_ccsg.WebView.EventType.LOADING); + }, + + /** + * Stop loading + */ + stopLoading: function(){ + cc.log("Web does not support loading"); + }, + + /** + * Reload the WebView + */ + reload: function(){ + var iframe = this._renderCmd._iframe; + if(iframe){ + var win = iframe.contentWindow; + if(win && win.location) + win.location.reload(); + } + }, + + /** + * Determine whether to go back + */ + canGoBack: function(){ + cc.log("Web does not support query history"); + return true; + }, + + /** + * Determine whether to go forward + */ + canGoForward: function(){ + cc.log("Web does not support query history"); + return true; + }, + + /** + * go back + */ + goBack: function(){ + try{ + if(_ccsg.WebView._polyfill.closeHistory) + return cc.log("The current browser does not support the GoBack"); + var iframe = this._renderCmd._iframe; + if(iframe){ + var win = iframe.contentWindow; + if(win && win.location) + win.history.back.call(win); + } + }catch(err){ + cc.log(err); + } + }, + + /** + * go forward + */ + goForward: function(){ + try{ + if(_ccsg.WebView._polyfill.closeHistory) + return cc.log("The current browser does not support the GoForward"); + var iframe = this._renderCmd._iframe; + if(iframe){ + var win = iframe.contentWindow; + if(win && win.location) + win.history.forward.call(win); + } + }catch(err){ + cc.log(err); + } + }, + + /** + * In the webview execution within a period of js string + * @param {String} str + */ + evaluateJS: function(str){ + var iframe = this._renderCmd._iframe; + if(iframe){ + var win = iframe.contentWindow; + try{ + win.eval(str); + this._dispatchEvent(_ccsg.WebView.EventType.JS_EVALUATED); + }catch(err){ + console.error(err); + } + } + }, + + /** + * Limited scale + */ + setScalesPageToFit: function(){ + cc.log("Web does not support zoom"); + }, + + /** + * The binding event + * @param {_ccsg.WebView.EventType} event + * @param {Function} callback + */ + setEventListener: function(event, callback){ + this._EventList[event] = callback; + }, + + /** + * Delete events + * @param {_ccsg.WebView.EventType} event + */ + removeEventListener: function(event){ + this._EventList[event] = null; + }, + + _dispatchEvent: function(event) { + var callback = this._EventList[event]; + if (callback) + callback.call(this, this, this._renderCmd._iframe.src); + }, + + _createRenderCmd: function(){ + return new _ccsg.WebView.RenderCmd(this); + }, + + /** + * Set the contentSize + * @param {Number} w + * @param {Number} h + */ + setContentSize: function(w, h){ + _ccsg.Widget.prototype.setContentSize.call(this, w, h); + if(h === undefined){ + h = w.height; + w = w.width; + } + this._renderCmd.changeSize(w, h); + }, + + /** + * remove node + */ + cleanup: function(){ + this._renderCmd.removeDom(); + this.stopAllActions(); + this.unscheduleAllCallbacks(); + } +}); + +/** + * The WebView support list of events + * @type {{LOADING: string, LOADED: string, ERROR: string}} + */ +_ccsg.WebView.EventType = { + LOADING: "loading", + LOADED: "load", + ERROR: "error", + JS_EVALUATED: "js" +}; + +(function(){ + + var polyfill = _ccsg.WebView._polyfill = { + devicePixelRatio: false, + enableDiv: false + }; + + if(cc.sys.os === cc.sys.OS_IOS) + polyfill.enableDiv = true; + + if(cc.sys.isMobile){ + if(cc.sys.browserType === cc.sys.BROWSER_TYPE_FIREFOX){ + polyfill.enableBG = true; + } + }else{ + if(cc.sys.browserType === cc.sys.BROWSER_TYPE_IE){ + polyfill.closeHistory = true; + } + } + + +})(); + +(function(polyfill){ + + var RenderCmd; + if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) { + RenderCmd = _ccsg.Node.CanvasRenderCmd; + } else { + RenderCmd = _ccsg.Node.WebGLRenderCmd; + } + + _ccsg.WebView.RenderCmd = function(node){ + RenderCmd.call(this, node); + + this._div = null; + this._iframe = null; + + if(polyfill.enableDiv){ + this._div = document.createElement("div"); + this._div.style["-webkit-overflow"] = "auto"; + this._div.style["-webkit-overflow-scrolling"] = "touch"; + this._iframe = document.createElement("iframe"); + this._div.appendChild(this._iframe); + }else{ + this._div = this._iframe = document.createElement("iframe"); + } + + if(polyfill.enableBG) + this._div.style["background"] = "#FFF"; + + this._iframe.addEventListener("load", function(){ + node._dispatchEvent(_ccsg.WebView.EventType.LOADED); + }); + this._iframe.addEventListener("error", function(){ + node._dispatchEvent(_ccsg.WebView.EventType.ERROR); + }); + this._div.style["background"] = "#FFF"; + this._div.style.height = "200px"; + this._div.style.width = "300px"; + this._div.style.overflow = "scroll"; + this._listener = null; + this.initStyle(); + }; + + var proto = _ccsg.WebView.RenderCmd.prototype = Object.create(RenderCmd.prototype); + proto.constructor = _ccsg.WebView.RenderCmd; + + proto.transform = function (parentCmd, recursive) { + RenderCmd.prototype.transform.call(this, parentCmd, recursive); + this.updateMatrix(); + }; + + proto.updateStatus = function(){ + polyfill.devicePixelRatio = cc.view.isRetinaEnabled(); + var flags = _ccsg.Node._dirtyFlags, locFlag = this._dirtyFlag; + if(locFlag & flags.transformDirty){ + //update the transform + this.transform(this.getParentRenderCmd(), true); + this.updateMatrix(); + this._dirtyFlag = this._dirtyFlag & _ccsg.Node._dirtyFlags.transformDirty ^ this._dirtyFlag; + } + }; + + 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, + eventManager = cc.eventManager; + if(node._parent && node._visible) + this.updateMatrix(); + else{ + var list = eventManager._listenersMap[cc.game.EVENT_RESIZE].getFixedPriorityListeners(); + eventManager._removeListenerInVector(list, this._listener); + this._listener = null; + } + }; + + proto.updateMatrix = function(){ + var node = this._node, scaleX = cc.view._scaleX, scaleY = cc.view._scaleY; + + if(polyfill.devicePixelRatio && scaleX !== 1 && scaleX !== 1){ + var dpr = cc.view._devicePixelRatio; + scaleX /= dpr; + scaleY /= dpr; + } + var t = node.getNodeToWorldTransform(); + if (!t) return; + + var container = cc.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; + + var matrix = "matrix(" + a + "," + -b + "," + -c + "," + d + "," + tx + "," + -ty + ")"; + this._div.style['transform'] = matrix; + this._div.style['-webkit-transform'] = matrix; + this._div.style['transform-origin'] = '0px 100% 0px'; + this._div.style['-webkit-transform-origin'] = '0px 100% 0px'; + }; + + proto.initStyle = function(){ + if(!this._div) return; + var div = this._div; + div.style.position = "absolute"; + div.style.bottom = "0px"; + div.style.left = "0px"; + }; + + proto.updateURL = function(url){ + var iframe = this._iframe; + iframe.src = url; + var self = this; + var cb = function(){ + self._loaded = true; + iframe.removeEventListener("load", cb); + }; + iframe.addEventListener("load", cb); + }; + + proto.changeSize = function(w, h){ + var div = this._div; + if(div){ + div.style["width"] = w+"px"; + div.style["height"] = h+"px"; + } + }; + + proto.removeDom = function(){ + var div = this._div; + if(div){ + var hasChild = false; + if('contains' in cc.container) { + hasChild = cc.container.contains(div); + }else { +hasChild = cc.container.compareDocumentPosition(div) % 16; +} +if(hasChild) + cc.container.removeChild(div); +} +}; + +})(_ccsg.WebView._polyfill); \ No newline at end of file diff --git a/cocos2d/core/webview/CCWebView.js b/cocos2d/core/webview/CCWebView.js new file mode 100644 index 0000000000..69e7cb53ad --- /dev/null +++ b/cocos2d/core/webview/CCWebView.js @@ -0,0 +1,83 @@ +/*global _ccsg */ + +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + http://www.cocos.com + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + The software or tools in this License Agreement are licensed, not sold. + Chukong Aipu reserves all rights not expressly granted to you. + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + + + +/** + * !#en cc.VideoPlayer is a component for playing videos, you can use it for showing videos in your game. + * !#zh Video 组件,用于在游戏中播放视频 + * @class VideoPlayer + * @extends _RendererUnderSG + */ +var WebView = cc.Class({ + name: 'cc.WebView', + extends: cc._RendererUnderSG, + + editor: CC_EDITOR && { + menu: 'i18n:MAIN_MENU.component.ui/WebView' + }, + + properties: { + + _url: '', + + url: { + type: String, + get: function () { + return this._url; + }, + set: function (url) { + this._url = url; + var sgNode = this._sgNode; + if (!sgNode) return; + sgNode.loadURL(url); + } + } + }, + + // statics: { + // EventType: EventType, + // ResourceType: ResourceType + // }, + + _createSgNode: function () { + return new _ccsg.WebView(); + }, + + _initSgNode: function () { + var sgNode = this._sgNode; + if (!sgNode) return; + sgNode.loadURL(this._url); + }, + + onLoad: function () { + + }, + + reload: function () { + + } + +}); + +cc.WebView = module.exports = WebView; diff --git a/gulp/tasks/modular.js b/gulp/tasks/modular.js index 7da5d47983..5d0718eccd 100644 --- a/gulp/tasks/modular.js +++ b/gulp/tasks/modular.js @@ -111,6 +111,10 @@ var modules = { './cocos2d/core/videoplayer/CCSGVideoPlayer.js' ], + 'WebView': [ + './cocos2d/core/webview/CCSGWebView.js' + ], + 'MotionStreak': [ './cocos2d/motion-streak/CCSGMotionStreak.js', './cocos2d/motion-streak/CCSGMotionStreakWebGLRenderCmd.js', From dc6ceeecf40c187a1a342b7f17e066c63737c86d Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Mon, 18 Jul 2016 21:23:55 +0800 Subject: [PATCH 002/268] should not disable widget if it is not a child of current editing animation --- cocos2d/core/base-ui/CCWidgetManager.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/base-ui/CCWidgetManager.js b/cocos2d/core/base-ui/CCWidgetManager.js index 5ea2b125b7..f216a1b251 100644 --- a/cocos2d/core/base-ui/CCWidgetManager.js +++ b/cocos2d/core/base-ui/CCWidgetManager.js @@ -183,11 +183,12 @@ function refreshScene () { } else { var i, node, nodes = widgetManager._nodesWithWidget, len = nodes.length; if (CC_EDITOR && _Scene.AnimUtils.curAnimState) { + var editingNode = _Scene.AnimUtils.curRootNode; // always check isAlignOnce because animation mode maybe changed for (i = len - 1; i >= 0; i--) { node = nodes[i]; var widget = node._widget; - if (widget.isAlignOnce) { + if (widget.isAlignOnce && node.isChildOf(editingNode)) { // widget contains in _nodesWithWidget should aligned at least once widget.enabled = false; } From 25e5576b231586159f83c04c4373d548c7bc0550 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 19 Jul 2016 15:07:14 +0800 Subject: [PATCH 003/268] Modify comment --- cocos2d/core/webview/CCSGWebView.js | 2 +- cocos2d/core/webview/CCWebView.js | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/cocos2d/core/webview/CCSGWebView.js b/cocos2d/core/webview/CCSGWebView.js index 4bd8d38094..996dd7f976 100644 --- a/cocos2d/core/webview/CCSGWebView.js +++ b/cocos2d/core/webview/CCSGWebView.js @@ -19,7 +19,7 @@ THE SOFTWARE. ****************************************************************************/ -_ccsg.WebView = _ccsg.Node.extend(/** @lends _ccsg.VideoPlayer# */{ +_ccsg.WebView = _ccsg.Node.extend(/** @lends _ccsg.WebView# */{ ctor: function (path) { _ccsg.Node.prototype.ctor.call(this); diff --git a/cocos2d/core/webview/CCWebView.js b/cocos2d/core/webview/CCWebView.js index 69e7cb53ad..5081a62e60 100644 --- a/cocos2d/core/webview/CCWebView.js +++ b/cocos2d/core/webview/CCWebView.js @@ -24,9 +24,9 @@ /** - * !#en cc.VideoPlayer is a component for playing videos, you can use it for showing videos in your game. - * !#zh Video 组件,用于在游戏中播放视频 - * @class VideoPlayer + * !#en cc.WebView is a component for display web pages in the game + * !#zh WebView 组件,用于在游戏中显示网页 + * @class WebView * @extends _RendererUnderSG */ var WebView = cc.Class({ From ae8f7abebf9f58965a587bf171c94ee4a1d6350e Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Wed, 20 Jul 2016 11:10:09 +0800 Subject: [PATCH 004/268] fix Bezier node's coordinates when no sync bug for #fireball/issues/3660 --- jsb/jsb-action.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/jsb/jsb-action.js b/jsb/jsb-action.js index f2f0659f6f..46cc8761d8 100644 --- a/jsb/jsb-action.js +++ b/jsb/jsb-action.js @@ -332,7 +332,8 @@ var actionUpdate = { 'FadeOut': syncOpacityUpdate, 'FadeTo': syncOpacityUpdate, 'TintTo': syncColorUpdate, - 'TintBy': syncColorUpdate + 'TintBy': syncColorUpdate, + 'BezierBy': syncPositionUpdate }; for (var key in actionUpdate) { From abc7cf9e058ddbdb4560f8861f5936679d6a3c10 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 20 Jul 2016 18:36:29 +0800 Subject: [PATCH 005/268] Fixed a bug about WebView position --- cocos2d/core/webview/CCSGWebView.js | 115 ++++++++++++---------------- 1 file changed, 49 insertions(+), 66 deletions(-) diff --git a/cocos2d/core/webview/CCSGWebView.js b/cocos2d/core/webview/CCSGWebView.js index 996dd7f976..3ce1efe5e5 100644 --- a/cocos2d/core/webview/CCSGWebView.js +++ b/cocos2d/core/webview/CCSGWebView.js @@ -168,12 +168,12 @@ _ccsg.WebView = _ccsg.Node.extend(/** @lends _ccsg.WebView# */{ * @param {Number} h */ setContentSize: function(w, h){ - _ccsg.Widget.prototype.setContentSize.call(this, w, h); + _ccsg.Node.prototype.setContentSize.call(this, w, h); if(h === undefined){ h = w.height; w = w.width; } - this._renderCmd.changeSize(w, h); + this._renderCmd.updateSize(w, h); }, /** @@ -234,39 +234,18 @@ _ccsg.WebView.EventType = { this._div = null; this._iframe = null; - - if(polyfill.enableDiv){ - this._div = document.createElement("div"); - this._div.style["-webkit-overflow"] = "auto"; - this._div.style["-webkit-overflow-scrolling"] = "touch"; - this._iframe = document.createElement("iframe"); - this._div.appendChild(this._iframe); - }else{ - this._div = this._iframe = document.createElement("iframe"); - } - - if(polyfill.enableBG) - this._div.style["background"] = "#FFF"; - - this._iframe.addEventListener("load", function(){ - node._dispatchEvent(_ccsg.WebView.EventType.LOADED); - }); - this._iframe.addEventListener("error", function(){ - node._dispatchEvent(_ccsg.WebView.EventType.ERROR); - }); - this._div.style["background"] = "#FFF"; - this._div.style.height = "200px"; - this._div.style.width = "300px"; - this._div.style.overflow = "scroll"; this._listener = null; + + this.createDom(); this.initStyle(); + this.initEvent(); }; var proto = _ccsg.WebView.RenderCmd.prototype = Object.create(RenderCmd.prototype); proto.constructor = _ccsg.WebView.RenderCmd; proto.transform = function (parentCmd, recursive) { - RenderCmd.prototype.transform.call(this, parentCmd, recursive); + this.originTransform(parentCmd, recursive); this.updateMatrix(); }; @@ -281,31 +260,14 @@ _ccsg.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.initEvent = function () { + var node = this._node; + this._iframe.addEventListener("load", function(){ + node._dispatchEvent(_ccsg.WebView.EventType.LOADED); + }); + this._iframe.addEventListener("error", function(){ + node._dispatchEvent(_ccsg.WebView.EventType.ERROR); + }); }; proto.resize = function(view){ @@ -322,15 +284,13 @@ _ccsg.WebView.EventType = { }; proto.updateMatrix = function(){ + if (!this._div) return; var node = this._node, scaleX = cc.view._scaleX, scaleY = cc.view._scaleY; + var dpr = cc.view._devicePixelRatio; + var t = this._worldTransform; - if(polyfill.devicePixelRatio && scaleX !== 1 && scaleX !== 1){ - var dpr = cc.view._devicePixelRatio; - scaleX /= dpr; - scaleY /= dpr; - } - var t = node.getNodeToWorldTransform(); - if (!t) return; + scaleX /= dpr; + scaleY /= dpr; var container = cc.container; var a = t.a * scaleX, b = t.b, c = t.c, d = t.d * scaleY; @@ -365,7 +325,7 @@ _ccsg.WebView.EventType = { iframe.addEventListener("load", cb); }; - proto.changeSize = function(w, h){ + proto.updateSize = function(w, h){ var div = this._div; if(div){ div.style["width"] = w+"px"; @@ -373,6 +333,29 @@ _ccsg.WebView.EventType = { } }; + proto.createDom = function () { + if(polyfill.enableDiv){ + this._div = document.createElement("div"); + this._div.style["-webkit-overflow"] = "auto"; + this._div.style["-webkit-overflow-scrolling"] = "touch"; + this._iframe = document.createElement("iframe"); + this._div.appendChild(this._iframe); + }else{ + this._div = this._iframe = document.createElement("iframe"); + } + + if(polyfill.enableBG) + this._div.style["background"] = "#FFF"; + + this._div.style["background"] = "#FFF"; + var contentSize = this._node._contentSize; + this._div.style.height = contentSize.height + "px"; + this._div.style.width = contentSize.width + "px"; + this._div.style.overflow = "scroll"; + this._div.style.border = "none"; + cc.container.appendChild(this._div); + }; + proto.removeDom = function(){ var div = this._div; if(div){ @@ -380,11 +363,11 @@ _ccsg.WebView.EventType = { if('contains' in cc.container) { hasChild = cc.container.contains(div); }else { -hasChild = cc.container.compareDocumentPosition(div) % 16; -} -if(hasChild) - cc.container.removeChild(div); -} -}; + hasChild = cc.container.compareDocumentPosition(div) % 16; + } + if(hasChild) + cc.container.removeChild(div); + } + }; })(_ccsg.WebView._polyfill); \ No newline at end of file From 55e880b666fabe23c027debecbd0a2c1e97fe277 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 21 Jul 2016 11:55:13 +0800 Subject: [PATCH 006/268] Fixed a bug about WebView contentSize --- cocos2d/core/webview/CCSGWebView.js | 16 ++++++++-------- cocos2d/core/webview/CCWebView.js | 1 + 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/cocos2d/core/webview/CCSGWebView.js b/cocos2d/core/webview/CCSGWebView.js index 3ce1efe5e5..44a51e6020 100644 --- a/cocos2d/core/webview/CCSGWebView.js +++ b/cocos2d/core/webview/CCSGWebView.js @@ -164,16 +164,16 @@ _ccsg.WebView = _ccsg.Node.extend(/** @lends _ccsg.WebView# */{ /** * Set the contentSize - * @param {Number} w - * @param {Number} h + * @param {Number} width + * @param {Number} height */ - setContentSize: function(w, h){ - _ccsg.Node.prototype.setContentSize.call(this, w, h); - if(h === undefined){ - h = w.height; - w = w.width; + setContentSize: function(width, height){ + if (width.width !== undefined && width.height !== undefined) { + height = width.height; + width = width.width; } - this._renderCmd.updateSize(w, h); + _ccsg.Node.prototype.setContentSize.call(this, width, height); + this._renderCmd.updateSize(width, height); }, /** diff --git a/cocos2d/core/webview/CCWebView.js b/cocos2d/core/webview/CCWebView.js index 5081a62e60..3a2b6209eb 100644 --- a/cocos2d/core/webview/CCWebView.js +++ b/cocos2d/core/webview/CCWebView.js @@ -68,6 +68,7 @@ var WebView = cc.Class({ var sgNode = this._sgNode; if (!sgNode) return; sgNode.loadURL(this._url); + sgNode.setContentSize(this.node.getContentSize()); }, onLoad: function () { From dc2cb64549d75c9e43a1cd3521c579500cd2631d Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 21 Jul 2016 17:53:44 +0800 Subject: [PATCH 007/268] Improve Scale9Sprite SLICED mode uv calculation --- cocos2d/core/sprites/CCScale9Sprite.js | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/cocos2d/core/sprites/CCScale9Sprite.js b/cocos2d/core/sprites/CCScale9Sprite.js index 52e1a20362..bd90a198f1 100644 --- a/cocos2d/core/sprites/CCScale9Sprite.js +++ b/cocos2d/core/sprites/CCScale9Sprite.js @@ -294,13 +294,13 @@ var scale9QuadGenerator = { if (spriteFrame._rotated) { u[0] = (textureRect.x + texelCorrect) / atlasWidth; - u[1] = (bottomHeight + textureRect.x - texelCorrect) / atlasWidth; - u[2] = (bottomHeight + centerHeight + 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 - texelCorrect) / atlasHeight; - v[1] = (leftWidth + centerWidth + 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++) { @@ -313,13 +313,13 @@ var scale9QuadGenerator = { } else { u[0] = (textureRect.x + texelCorrect) / atlasWidth; - u[1] = (leftWidth + textureRect.x - texelCorrect) / atlasWidth; - u[2] = (leftWidth + centerWidth + 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 - texelCorrect) / atlasHeight; - v[1] = (topHeight + centerHeight + 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++) { From 7814b3fda638d7227aa80c19ad3bc25bdef0997b Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 21 Jul 2016 17:54:11 +0800 Subject: [PATCH 008/268] Fix black border for Tilemap --- cocos2d/tilemap/CCSGTMXLayer.js | 11 ++++++----- cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js | 16 +++++++++------- cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js | 17 +++++++++-------- 3 files changed, 24 insertions(+), 20 deletions(-) diff --git a/cocos2d/tilemap/CCSGTMXLayer.js b/cocos2d/tilemap/CCSGTMXLayer.js index 701a866f18..8920109113 100644 --- a/cocos2d/tilemap/CCSGTMXLayer.js +++ b/cocos2d/tilemap/CCSGTMXLayer.js @@ -145,7 +145,8 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ maxGid = tileset.firstGid + count, grids = this._texGrids, grid = null, - override = grids[gid] ? true : false; + override = grids[gid] ? true : false, + texelCorrect = cc.macro.FIX_ARTIFACTS_BY_STRECHING_TEXEL ? 0.5 : 0; for (; gid < maxGid; ++gid) { // Avoid overlapping @@ -162,10 +163,10 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ t: 0, l: 0, r: 0, b: 0 }; tileset.rectForGID(gid, grid); - grid.t = grid.y / imageH; - grid.l = grid.x / imageW; - grid.r = (grid.x + grid.width) / imageW; - grid.b = (grid.y + grid.height) / imageH; + grid.t = (grid.y + texelCorrect) / imageH; + grid.l = (grid.x + texelCorrect) / imageW; + grid.r = (grid.x + grid.width - texelCorrect) / imageW; + grid.b = (grid.y + grid.height - texelCorrect) / imageH; grids[gid] = grid; } }, diff --git a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js index fad0e201b3..43a0867603 100644 --- a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js +++ b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js @@ -167,14 +167,16 @@ proto.rendering = function (ctx, scaleX, scaleY) { wrapper.setTransform(wt, scaleX, scaleY); wrapper.setGlobalAlpha(alpha); + var axis, tileOffset, odd_even, diffX1, diffY1; + if (layerOrientation === Orientation.HEX) { - var axis = node._staggerAxis, - index = node._staggerIndex, - hexSideLength = node._hexSideLength, - tileOffset = node.tileset.tileOffset; - var odd_even = (index === StaggerIndex.STAGGERINDEX_ODD) ? 1 : -1; - var diffX1 = (axis === StaggerAxis.STAGGERAXIS_X) ? ((maptw - hexSideLength)/2) : 0; - var diffY1 = (axis === StaggerAxis.STAGGERAXIS_Y) ? ((mapth - hexSideLength)/2) : 0; + var index = node._staggerIndex, + hexSideLength = node._hexSideLength; + axis = node._staggerAxis; + tileOffset = node.tileset.tileOffset; + odd_even = (index === StaggerIndex.STAGGERINDEX_ODD) ? 1 : -1; + diffX1 = (axis === StaggerAxis.STAGGERAXIS_X) ? ((maptw - hexSideLength)/2) : 0; + diffY1 = (axis === StaggerAxis.STAGGERAXIS_Y) ? ((mapth - hexSideLength)/2) : 0; } for (row = startRow; row < maxRow; ++row) { diff --git a/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js b/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js index ea94ebe8e4..a26f45bc5e 100644 --- a/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js +++ b/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js @@ -121,16 +121,17 @@ proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset) { w = tilew * a, h = tileh * d, gt, gl, gb, gr, wa = a, wb = b, wc = c, wd = d, wtx = tx, wty = ty, // world flagged = false, flippedX = false, flippedY = false, - vertices = this._vertices; + vertices = this._vertices, + axis, tileOffset, diffX1, diffY1, odd_even; if (layerOrientation === Orientation.HEX) { - var axis = node._staggerAxis, - index = node._staggerIndex, - hexSideLength = node._hexSideLength, - tileOffset = node.tileset.tileOffset; - var odd_even = (index === StaggerIndex.STAGGERINDEX_ODD) ? 1 : -1; - var diffX1 = (axis === StaggerAxis.STAGGERAXIS_X) ? ((maptw - hexSideLength)/2) : 0; - var diffY1 = (axis === StaggerAxis.STAGGERAXIS_Y) ? ((mapth - hexSideLength)/2) : 0; + var index = node._staggerIndex, + hexSideLength = node._hexSideLength; + axis = node._staggerAxis; + tileOffset = node.tileset.tileOffset; + odd_even = (index === StaggerIndex.STAGGERINDEX_ODD) ? 1 : -1; + diffX1 = (axis === StaggerAxis.STAGGERAXIS_X) ? ((maptw - hexSideLength)/2) : 0; + diffY1 = (axis === StaggerAxis.STAGGERAXIS_Y) ? ((mapth - hexSideLength)/2) : 0; } for (row = startRow; row < maxRow; ++row) { From b521d6165035a43889dcce09b991c8d7ca5c6dd0 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Wed, 20 Jul 2016 17:47:11 +0800 Subject: [PATCH 009/268] avoid reference error about _Scene.AssetsWatcher --- cocos2d/core/components/CCButton.js | 2 +- cocos2d/core/components/CCComponent.js | 13 ++++++------- cocos2d/core/platform/CCClass.js | 4 ++-- gulp/tasks/utils.js | 4 ++-- 4 files changed, 11 insertions(+), 12 deletions(-) diff --git a/cocos2d/core/components/CCButton.js b/cocos2d/core/components/CCButton.js index b6e8a7996d..dd7b2d5680 100644 --- a/cocos2d/core/components/CCButton.js +++ b/cocos2d/core/components/CCButton.js @@ -216,7 +216,7 @@ var Button = cc.Class({ disabledColor: { default: cc.color(124, 124, 124), displayName: 'Disabled', - tooltip: 'i18n:COMPONENT.button.diabled_color', + tooltip: 'i18n:COMPONENT.button.disabled_color', notify: function () { this._updateState(); } diff --git a/cocos2d/core/components/CCComponent.js b/cocos2d/core/components/CCComponent.js index 11af567b87..9d396c560e 100644 --- a/cocos2d/core/components/CCComponent.js +++ b/cocos2d/core/components/CCComponent.js @@ -25,7 +25,7 @@ require('../platform/CCObject'); require('../CCNode'); -var IdGenerater = require('../platform/id-generater'); +var idGenerater = new (require('../platform/id-generater'))('Comp'); var Misc = require('../utils/misc'); var Flags = cc.Object.Flags; @@ -216,8 +216,6 @@ function _callPreloadOnComponent (component) { } } -var idGenerater = new IdGenerater('Comp'); - /** * !#en * Base class for everything attached to Node(Entity).
@@ -237,11 +235,12 @@ var Component = cc.Class({ name: 'cc.Component', extends: cc.Object, - ctor: function () { - if (CC_EDITOR && !CC_TEST && window._Scene) { - _Scene.AssetsWatcher.initComponent(this); - } + ctor: (CC_EDITOR && window._Scene && _Scene.AssetsWatcher) ? function () { + _Scene.AssetsWatcher.initComponent(this); + // Support for Scheduler + this.__instanceId = cc.ClassManager.getNewInstanceId(); + } : function () { // Support for Scheduler this.__instanceId = cc.ClassManager.getNewInstanceId(); }, diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index 8111c78d98..b5fb1343e5 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -416,7 +416,7 @@ function define (className, baseClasses, mixins, constructor, options) { var frame = cc._RFpeek(); if (frame) { if (CC_DEV && constructor) { - cc.warn('cc.Class: Should not define constructor for cc.Component.'); + cc.warn('Should not define constructor for cc.Component %s.', className); } if (frame.beh) { cc.error('Each script can have at most one Component.'); @@ -425,7 +425,7 @@ function define (className, baseClasses, mixins, constructor, options) { var uuid = frame.uuid; if (uuid) { if (CC_EDITOR && className) { - cc.warn('Should not specify class name for Component which defines in project.'); + cc.warn('Should not specify class name %s for Component which defines in project.', className); } } //else { diff --git a/gulp/tasks/utils.js b/gulp/tasks/utils.js index 6aa4955eea..582df58946 100644 --- a/gulp/tasks/utils.js +++ b/gulp/tasks/utils.js @@ -26,8 +26,8 @@ exports.uglifyOptions = function (minify, global_defs) { //dead_code: true, // discard unreachable code drop_debugger: false, // discard “debugger” statements unsafe: false, // some unsafe optimizations (see below) - conditionals: false, // optimize if-s and conditional expressions - comparisons: false, // optimize comparisons + //conditionals: false, // optimize if-s and conditional expressions + //comparisons: false, // optimize comparisons //evaluate: true, // evaluate constant expressions booleans: false, // optimize boolean expressions loops: false, // optimize loops From 9cb440197ca4a5fc3b9287c6cd0f46d4d6b29740 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Fri, 22 Jul 2016 11:33:02 +0800 Subject: [PATCH 010/268] fix schedule bug for #fireball/issues/3686 --- jsb/jsb-etc.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/jsb/jsb-etc.js b/jsb/jsb-etc.js index 726e9fc8c4..d4acc79518 100644 --- a/jsb/jsb-etc.js +++ b/jsb/jsb-etc.js @@ -71,6 +71,9 @@ cc.js.mixin(cc.path, { // cc.Scheduler cc.Scheduler.prototype.schedule = function (callback, target, interval, repeat, delay, paused) { + repeat = repeat || cc.macro.REPEAT_FOREVER; + delay = delay || 0; + paused = paused || false; this.scheduleCallbackForTarget(target, callback, interval, repeat, delay, paused); }; cc.Scheduler.prototype.scheduleUpdate = cc.Scheduler.prototype.scheduleUpdateForTarget; From 51c4a0756d9ffa7c390a21dbdbb73e5190dbbc4a Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Fri, 22 Jul 2016 11:44:26 +0800 Subject: [PATCH 011/268] remove cc.isEditor, use CC_EDITOR instead to reduce engine size --- CCBoot.js | 2 -- cocos2d/core/platform/CCSys.js | 4 +-- cocos2d/core/platform/deserialize.js | 53 ++++++++++------------------ gulp/tasks/engine.js | 2 +- 4 files changed, 22 insertions(+), 39 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index c23be52534..959953192a 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -87,8 +87,6 @@ cc._canvas = null; cc.container = null; cc._gameDiv = null; -cc.isEditor = typeof Editor !== 'undefined'; - require('./cocos2d/core/utils'); require('./cocos2d/core/platform/CCSys'); diff --git a/cocos2d/core/platform/CCSys.js b/cocos2d/core/platform/CCSys.js index 73c3eaff0d..19f2edf221 100644 --- a/cocos2d/core/platform/CCSys.js +++ b/cocos2d/core/platform/CCSys.js @@ -459,7 +459,7 @@ sys.isNative = false; */ sys.isBrowser = typeof window === 'object' && typeof document === 'object'; -if (typeof Editor !== 'undefined' && Editor.isMainProcess) { +if (CC_EDITOR && Editor.isMainProcess) { sys.isMobile = false; sys.platform = sys.EDITOR_CORE; sys.language = sys.LANGUAGE_UNKNOWN; @@ -481,7 +481,7 @@ else { var win = window, nav = win.navigator, doc = document, docEle = doc.documentElement; var ua = nav.userAgent.toLowerCase(); - if (cc.isEditor) { + if (CC_EDITOR) { sys.isMobile = false; sys.platform = sys.EDITOR_PAGE; } diff --git a/cocos2d/core/platform/deserialize.js b/cocos2d/core/platform/deserialize.js index 76b5d66d11..f9da036042 100644 --- a/cocos2d/core/platform/deserialize.js +++ b/cocos2d/core/platform/deserialize.js @@ -27,8 +27,7 @@ var JS = require('./js'); var CCObject = require('./CCObject'); var Attr = require('./attribute'); -var EDITOR = CC_DEV; -var ENABLE_TARGET = EDITOR; +var ENABLE_TARGET = CC_DEV; // HELPERS @@ -67,7 +66,7 @@ var Details = function () { */ this.rawProp = ''; - if (EDITOR) { + if (CC_DEV) { /** * 用户可以指定一个在反序列化结束时会被触发的回调,该回调会传回反序列化时统计到的所有解析过的字段。 * NOTE: @@ -96,17 +95,25 @@ Details.prototype.reset = function () { //this.rawObjList.length = 0; //this.rawPropList.length = 0; - if (EDITOR) { + if (CC_DEV) { this.visitorInEditor = null; this.visitObjList.length = 0; this.visitPropList.length = 0; } }; -if (EDITOR) { +if (CC_DEV) { Details.prototype.visitLater = function (obj, propName) { this.visitObjList.push(obj); this.visitPropList.push(propName); }; + Details.prototype.assignAssetsBy = function (getter) { + for (var i = 0, len = this.uuidList.length; i < len; i++) { + var uuid = this.uuidList[i]; + var obj = this.uuidObjList[i]; + var prop = this.uuidPropList[i]; + obj[prop] = getter(uuid); + } + }; } /** * @method getUuidOf @@ -122,28 +129,6 @@ Details.prototype.getUuidOf = function (obj, propName) { } return ""; }; -/** - * @method assignAssetsBy - * @param {Function} getter - * @return {Boolean} success - */ -Details.prototype.assignAssetsBy = function (getter) { - var success = true; - for (var i = 0, len = this.uuidList.length; i < len; i++) { - var uuid = this.uuidList[i]; - var asset = getter(uuid); - if (asset) { - var obj = this.uuidObjList[i]; - var prop = this.uuidPropList[i]; - obj[prop] = asset; - } - else { - cc.error('Failed to assign asset: ' + uuid); - success = false; - } - } - return success; -}; /** * @method push * @param {Object} obj @@ -211,7 +196,7 @@ var _Deserializer = (function () { _dereference(this); // call visitor after all properties initialized - if (EDITOR) { + if (CC_DEV) { this._callVisitorInEditor(); } } @@ -229,7 +214,7 @@ var _Deserializer = (function () { } }; - if (EDITOR) { + if (CC_DEV) { _Deserializer.prototype._callVisitorInEditor = function () { var result = this.result; if (result.visitorInEditor) { @@ -264,7 +249,7 @@ var _Deserializer = (function () { else { obj[propName] = _deserializeObject(this, jsonObj); } - if (this.result.visitorInEditor && EDITOR) { + if (CC_DEV && this.result.visitorInEditor) { this.result.visitLater(obj, propName); } } @@ -279,7 +264,7 @@ var _Deserializer = (function () { this._idObjList.push(obj); this._idPropList.push(propName); } - if (this.result.visitorInEditor && EDITOR) { + if (CC_DEV && this.result.visitorInEditor) { this.result.visitLater(obj, propName); } } @@ -292,7 +277,7 @@ var _Deserializer = (function () { if (typeof prop !== 'object') { if (propName !== '__type__'/* && k != '__id__'*/) { instance[propName] = prop; - if (self.result.visitorInEditor && EDITOR) { + if (CC_DEV && self.result.visitorInEditor) { self.result.visitLater(instance, propName); } } @@ -353,7 +338,7 @@ var _Deserializer = (function () { // assume all prop in __props__ must have attr var rawType = attrs[propName + DELIMETER + 'rawType']; if (!rawType) { - if (!EDITOR && attrs[propName + DELIMETER + 'editorOnly']) { + if (!CC_DEV && attrs[propName + DELIMETER + 'editorOnly']) { var mayUsedInPersistRoot = (obj instanceof cc.Node && propName === '_id'); if ( !mayUsedInPersistRoot ) { continue; // skip editor only if not editor @@ -484,7 +469,7 @@ var _Deserializer = (function () { else { obj[i] = prop; - if (self.result.visitorInEditor && EDITOR) { + if (CC_DEV && self.result.visitorInEditor) { self.result.visitLater(obj, '' + i); } } diff --git a/gulp/tasks/engine.js b/gulp/tasks/engine.js index 9c4f69b30e..c793eb6d04 100644 --- a/gulp/tasks/engine.js +++ b/gulp/tasks/engine.js @@ -108,7 +108,7 @@ exports.buildCocosJsMin = function (sourceFile, outputFile, excludes, callback, var raw = rawSize.size; var zipped = zippedSize.size; var percent = ((zipped / raw) * 100).toFixed(2); - console.log(`Size of ${outputFile}: minimized: ${Chalk.cyan(raw + 'B')} zipped: ${Chalk.cyan(zipped + 'B')}, compression ratio: ${percent}%`); + console.log(`Size of ${outputFile}: minimized: ${Chalk.cyan(raw)}B zipped: ${Chalk.cyan(zipped)}B, compression ratio: ${percent}%`); this.emit('end'); })); } From bbbb38dc80695b1fcb7cd89add465cf0aacde3f0 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Fri, 22 Jul 2016 11:54:58 +0800 Subject: [PATCH 012/268] try to fix unit test --- test/qunit/lib/polyfill-for-phantom.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/test/qunit/lib/polyfill-for-phantom.js b/test/qunit/lib/polyfill-for-phantom.js index b6ef60c60b..2321a0e717 100644 --- a/test/qunit/lib/polyfill-for-phantom.js +++ b/test/qunit/lib/polyfill-for-phantom.js @@ -115,3 +115,7 @@ if (isPhantomJS) { }); })(); } + +if (typeof WebGLRenderingContext === 'undefined') { + window.WebGLRenderingContext = function () {}; +} From 24690d9b3d800ef055b9623916fe819ccd0a5be7 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Fri, 22 Jul 2016 13:54:39 +0800 Subject: [PATCH 013/268] fix editbox window popup issue on iOS9 --- cocos2d/core/editbox/CCSGEditBox.js | 32 ++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/editbox/CCSGEditBox.js b/cocos2d/core/editbox/CCSGEditBox.js index f8d275f832..d772531066 100644 --- a/cocos2d/core/editbox/CCSGEditBox.js +++ b/cocos2d/core/editbox/CCSGEditBox.js @@ -26,6 +26,30 @@ THE SOFTWARE. ****************************************************************************/ +// https://segmentfault.com/q/1010000002914610 +var SCROLLY = 40; +var TIMER_NAME = 400; + +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); + } +} + var capitalize = function(string) { return string.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); }); }; @@ -571,11 +595,14 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; cc._canvas.focus(); } }); + tmpEdTxt.addEventListener('focus', function () { var editBox = thisPointer._editBox; this.style.fontSize = thisPointer._edFontSize + 'px'; this.style.color = cc.colorToHex(editBox._textColor); + scrollWindowUp(editBox); + if (editBox._delegate && editBox._delegate.editBoxEditingDidBegan) { editBox._delegate.editBoxEditingDidBegan(editBox); } @@ -584,7 +611,7 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; var editBox = thisPointer._editBox; editBox._text = this.value; thisPointer._updateEditBoxContentStyle(); - + window.scrollY = 0; if (editBox._delegate && editBox._delegate.editBoxEditingDidEnded) { editBox._delegate.editBoxEditingDidEnded(editBox); } @@ -635,6 +662,8 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; this.style.fontSize = thisPointer._edFontSize + 'px'; this.style.color = cc.colorToHex(editBox._textColor); + scrollWindowUp(editBox); + if (editBox._delegate && editBox._delegate.editBoxEditingDidBegan) { editBox._delegate.editBoxEditingDidBegan(editBox); } @@ -655,6 +684,7 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; var editBox = thisPointer._editBox; editBox._text = this.value; thisPointer._updateEditBoxContentStyle(); + window.scrollY = 0; if (editBox._delegate && editBox._delegate.editBoxEditingDidEnded) { editBox._delegate.editBoxEditingDidEnded(editBox); From abd2d5aea5c971f2600c9e453f7157a97ffe8da6 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Fri, 22 Jul 2016 14:00:06 +0800 Subject: [PATCH 014/268] fix update opacity for fireball/issues/2578 --- cocos2d/core/base-nodes/CCSGNode.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/base-nodes/CCSGNode.js b/cocos2d/core/base-nodes/CCSGNode.js index f3697ee4a4..d910e429a5 100644 --- a/cocos2d/core/base-nodes/CCSGNode.js +++ b/cocos2d/core/base-nodes/CCSGNode.js @@ -867,7 +867,8 @@ _ccsg.Node = cc.Class({ */ setParent: function (parent) { this._parent = parent; - this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.transformDirty); + var dirtyFlags = _ccsg.Node._dirtyFlags; + this._renderCmd.setDirtyFlag(dirtyFlags.transformDirty | dirtyFlags.opacityDirty); }, /** From c27dd8f28037d47965c7f5f5e7c5f3c7859114b8 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 22 Jul 2016 14:05:38 +0800 Subject: [PATCH 015/268] Add video event description --- cocos2d/core/components/CCVideoPlayer.js | 25 ++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/cocos2d/core/components/CCVideoPlayer.js b/cocos2d/core/components/CCVideoPlayer.js index 178f30b419..332cad9338 100644 --- a/cocos2d/core/components/CCVideoPlayer.js +++ b/cocos2d/core/components/CCVideoPlayer.js @@ -21,6 +21,31 @@ THE SOFTWARE. ****************************************************************************/ +/** + * !#en Video event type + * !#zh 视频事件类型 + * @enum VideoPlayer.EventType + */ +/** + * !#en play + * !#zh 播放 + * @property {Number} PLAYING + */ +/** + * !#en pause + * !#zh 暂停 + * @property {Number} PAUSED + */ +/** + * !#en stop + * !#zh 停止 + * @property {Number} STOPPED + */ +/** + * !#en play end + * !#zh 播放结束 + * @property {Number} COMPLETED + */ var EventType = _ccsg.VideoPlayer.EventType; From 7f35eaaaabd59b2b91f4079cafb60ff5509a693c Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 22 Jul 2016 14:15:36 +0800 Subject: [PATCH 016/268] video event --- cocos2d/core/videoplayer/CCSGVideoPlayer.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/cocos2d/core/videoplayer/CCSGVideoPlayer.js b/cocos2d/core/videoplayer/CCSGVideoPlayer.js index 4dc4b8bfe2..5b184097ff 100644 --- a/cocos2d/core/videoplayer/CCSGVideoPlayer.js +++ b/cocos2d/core/videoplayer/CCSGVideoPlayer.js @@ -188,10 +188,10 @@ cc.game.on(cc.game.EVENT_SHOW, function () { * @type {{PLAYING: string, PAUSED: string, STOPPED: string, COMPLETED: string}} */ _ccsg.VideoPlayer.EventType = { - PLAYING: "play", - PAUSED: "pause", - STOPPED: "stop", - COMPLETED: "complete" + PLAYING: 0, + PAUSED: 1, + STOPPED: 2, + COMPLETED: 3 }; (function (video) { From 98ebc6762cb8e7647ff6a99b7dfba314edfd023e Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Fri, 22 Jul 2016 14:16:24 +0800 Subject: [PATCH 017/268] move CCWebView to components directory --- cocos2d/core/{webview => components}/CCWebView.js | 0 cocos2d/core/components/index.js | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) rename cocos2d/core/{webview => components}/CCWebView.js (100%) diff --git a/cocos2d/core/webview/CCWebView.js b/cocos2d/core/components/CCWebView.js similarity index 100% rename from cocos2d/core/webview/CCWebView.js rename to cocos2d/core/components/CCWebView.js diff --git a/cocos2d/core/components/index.js b/cocos2d/core/components/index.js index 882a958c13..cf89692912 100644 --- a/cocos2d/core/components/index.js +++ b/cocos2d/core/components/index.js @@ -44,7 +44,7 @@ module.exports = [ require('./CCLayout'), require('./CCEditBox'), require('./CCVideoPlayer'), - require('../webview/CCWebView'), + require('./CCWebView'), require('./CCSpriteDistortion'), require('./CCLabelOutline'), ]; From 7595644bfd2873ac31a8424eccbae138a1832159 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 22 Jul 2016 14:38:28 +0800 Subject: [PATCH 018/268] video event --- cocos2d/core/videoplayer/CCSGVideoPlayer.js | 4 ---- 1 file changed, 4 deletions(-) diff --git a/cocos2d/core/videoplayer/CCSGVideoPlayer.js b/cocos2d/core/videoplayer/CCSGVideoPlayer.js index 5b184097ff..a38132f352 100644 --- a/cocos2d/core/videoplayer/CCSGVideoPlayer.js +++ b/cocos2d/core/videoplayer/CCSGVideoPlayer.js @@ -183,10 +183,6 @@ cc.game.on(cc.game.EVENT_SHOW, function () { } }); -/** - * The VideoPlayer support list of events - * @type {{PLAYING: string, PAUSED: string, STOPPED: string, COMPLETED: string}} - */ _ccsg.VideoPlayer.EventType = { PLAYING: 0, PAUSED: 1, From befac0ef1bf982af791d321f192a4025d811a0af Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Fri, 22 Jul 2016 14:41:43 +0800 Subject: [PATCH 019/268] fix webview initialize size --- cocos2d/core/components/CCWebView.js | 10 ++++++++-- cocos2d/core/webview/CCSGWebView.js | 3 ++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/components/CCWebView.js b/cocos2d/core/components/CCWebView.js index 3a2b6209eb..3736d404eb 100644 --- a/cocos2d/core/components/CCWebView.js +++ b/cocos2d/core/components/CCWebView.js @@ -38,9 +38,9 @@ var WebView = cc.Class({ }, properties: { + _useOriginalSize: true, _url: '', - url: { type: String, get: function () { @@ -68,7 +68,13 @@ var WebView = cc.Class({ var sgNode = this._sgNode; if (!sgNode) return; sgNode.loadURL(this._url); - sgNode.setContentSize(this.node.getContentSize()); + + if (CC_EDITOR && this._useOriginalSize) { + this.node.setContentSize(sgNode.getContentSize()); + this._useOriginalSize = false; + } else { + sgNode.setContentSize(this.node.getContentSize()); + } }, onLoad: function () { diff --git a/cocos2d/core/webview/CCSGWebView.js b/cocos2d/core/webview/CCSGWebView.js index 44a51e6020..7261fe22bb 100644 --- a/cocos2d/core/webview/CCSGWebView.js +++ b/cocos2d/core/webview/CCSGWebView.js @@ -23,6 +23,7 @@ _ccsg.WebView = _ccsg.Node.extend(/** @lends _ccsg.WebView# */{ ctor: function (path) { _ccsg.Node.prototype.ctor.call(this); + this.setContentSize(cc.size(300, 200)); this._EventList = {}; if(path) this.loadURL(path); @@ -370,4 +371,4 @@ _ccsg.WebView.EventType = { } }; -})(_ccsg.WebView._polyfill); \ No newline at end of file +})(_ccsg.WebView._polyfill); From bfd3e854d40dd847796e84d3826e69ce8ca96717 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 22 Jul 2016 14:50:05 +0800 Subject: [PATCH 020/268] Fix tile map black border in canvas render mode too --- cocos2d/tilemap/CCSGTMXLayer.js | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/cocos2d/tilemap/CCSGTMXLayer.js b/cocos2d/tilemap/CCSGTMXLayer.js index 8920109113..e3872ae055 100644 --- a/cocos2d/tilemap/CCSGTMXLayer.js +++ b/cocos2d/tilemap/CCSGTMXLayer.js @@ -163,10 +163,14 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ t: 0, l: 0, r: 0, b: 0 }; tileset.rectForGID(gid, grid); - grid.t = (grid.y + texelCorrect) / imageH; - grid.l = (grid.x + texelCorrect) / imageW; - grid.r = (grid.x + grid.width - texelCorrect) / imageW; - grid.b = (grid.y + grid.height - texelCorrect) / imageH; + grid.x += texelCorrect; + grid.y += texelCorrect; + grid.width -= texelCorrect*2; + grid.height -= texelCorrect*2; + grid.t = (grid.y) / imageH; + grid.l = (grid.x) / imageW; + grid.r = (grid.x + grid.width) / imageW; + grid.b = (grid.y + grid.height) / imageH; grids[gid] = grid; } }, From fa0cd9081f08764d47cbc4b5654021d085e15882 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 22 Jul 2016 14:51:10 +0800 Subject: [PATCH 021/268] Fix scale9sprite unit test --- test/qunit/unit/test-spriteRenderer.js | 244 ++++++++++++------------- 1 file changed, 114 insertions(+), 130 deletions(-) diff --git a/test/qunit/unit/test-spriteRenderer.js b/test/qunit/unit/test-spriteRenderer.js index 6e5c743108..69fc2035b0 100644 --- a/test/qunit/unit/test-spriteRenderer.js +++ b/test/qunit/unit/test-spriteRenderer.js @@ -44,19 +44,20 @@ test('simple spriteQuad trimmed', function () { s9Sprite.enableTrimmedContentSize(isTrimmed); s9Sprite.setRenderingType(cc.Scale9Sprite.RenderingType.SIMPLE); s9Sprite._rebuildQuads(); - var quads = s9Sprite._quads; - strictEqual(quads.length, 1, 'quads number[1] success'); - strictEqual(quads[0]._bl.vertices.x, 0, 'vertex-bl-x test success'); - strictEqual(quads[0]._bl.vertices.y, 0, 'vertex-bl-y test success'); + var vertices = s9Sprite._vertices; + var uvs = s9Sprite._uvs; + strictEqual(vertices.length >= 8 && uvs >= 8, true, 'vertices have at least 8 floats'); + strictEqual(vertices[0], 0, 'vertex-bl-x test success'); + strictEqual(vertices[1], 0, 'vertex-bl-y test success'); - strictEqual(quads[0]._tr.vertices.x, contentSize.width, 'vertex-tr-x test success'); - strictEqual(quads[0]._tr.vertices.y, contentSize.height, 'vertex-tr-y test success'); + strictEqual(vertices[6], contentSize.width, 'vertex-tr-x test success'); + strictEqual(vertices[7], contentSize.height, 'vertex-tr-y test success'); - deepClose(quads[0]._bl.texCoords.u, 10 / 100, 0.0001, 'texCoords-bl-x test success'); - deepClose(quads[0]._bl.texCoords.v, 70 / 100, 0.0001, 'texCoords-bl-y test success'); + deepClose(uvs[0], 10 / 100, 0.0001, 'texCoords-bl-x test success'); + deepClose(uvs[1], 70 / 100, 0.0001, 'texCoords-bl-y test success'); - deepClose(quads[0]._tr.texCoords.u, 50 / 100, 0.0001, 'texCoords-tr-x test success'); - deepClose(quads[0]._tr.texCoords.v, 10 / 100, 0.0001, 'texCoords-tr-y test success'); + deepClose(uvs[6], 50 / 100, 0.0001, 'texCoords-tr-x test success'); + deepClose(uvs[7], 10 / 100, 0.0001, 'texCoords-tr-y test success'); }; if (spriteFrame.textureLoaded()) { testCallBack(); @@ -76,19 +77,20 @@ test('simple spriteQuad no trimmed', function () { s9Sprite.enableTrimmedContentSize(isTrimmed); s9Sprite.setRenderingType(cc.Scale9Sprite.RenderingType.SIMPLE); s9Sprite._rebuildQuads(); - var quads = s9Sprite._quads; - strictEqual(quads.length, 1, 'quads number[1] success'); - strictEqual(quads[0]._bl.vertices.x, 10, 'vertex-bl-x test success'); - strictEqual(quads[0]._bl.vertices.y, 30, 'vertex-bl-y test success'); + var vertices = s9Sprite._vertices; + var uvs = s9Sprite._uvs; + strictEqual(vertices.length >= 8 && uvs >= 8, true, 'vertices have at least 8 floats'); + strictEqual(vertices[0], 10, 'vertex-bl-x test success'); + strictEqual(vertices[1], 30, 'vertex-bl-y test success'); - strictEqual(quads[0]._tr.vertices.x, 50, 'vertex-tr-x test success'); - strictEqual(quads[0]._tr.vertices.y, 90, 'vertex-tr-y test success'); + strictEqual(vertices[6], 50, 'vertex-tr-x test success'); + strictEqual(vertices[7], 90, 'vertex-tr-y test success'); - deepClose(quads[0]._bl.texCoords.u, 10 / 100, 0.0001, 'texCoords-bl-x test success'); - deepClose(quads[0]._bl.texCoords.v, 70 / 100, 0.0001, 'texCoords-bl-y test success'); + deepClose(uvs[0], 10 / 100, 0.0001, 'texCoords-bl-x test success'); + deepClose(uvs[1], 70 / 100, 0.0001, 'texCoords-bl-y test success'); - deepClose(quads[0]._tr.texCoords.u, 50 / 100, 0.0001, 'texCoords-tr-x test success'); - deepClose(quads[0]._tr.texCoords.v, 10 / 100, 0.0001, 'texCoords-tr-y test success'); + deepClose(uvs[6], 50 / 100, 0.0001, 'texCoords-tr-x test success'); + deepClose(uvs[7], 10 / 100, 0.0001, 'texCoords-tr-y test success'); }; if (spriteFrame.textureLoaded()) { testCallBack(); @@ -114,31 +116,26 @@ test('scale9 spriteQuad trimmed', function () { s9Sprite.enableTrimmedContentSize(isTrimmed); s9Sprite.setRenderingType(cc.Scale9Sprite.RenderingType.SLICED); s9Sprite._rebuildQuads(); - var quads = s9Sprite._quads; - strictEqual(quads.length, 9, 'quads number[9] success'); - strictEqual(quads[0]._bl.vertices.x, 0, 'x0 test success'); - strictEqual(quads[0]._bl.vertices.y, 0, 'y0 test success'); + var vertices = s9Sprite._vertices; + var uvs = s9Sprite._uvs; + strictEqual(vertices.length >= 32 && uvs >= 32, true, 'vertices have at least 32 floats'); + strictEqual(vertices[0], 0, 'x0 test success'); + strictEqual(vertices[1], 0, 'y0 test success'); + strictEqual(vertices[10], 5, 'x1 test success'); + strictEqual(vertices[11], 7, 'y1 test success'); + strictEqual(vertices[20], 94, 'x2 test success'); + strictEqual(vertices[21], 92, 'y2 test success'); + strictEqual(vertices[30], 100, 'x3 test success'); + strictEqual(vertices[31], 100, 'y3 test success'); - strictEqual(quads[4]._bl.vertices.x, 5, 'x1 test success'); - strictEqual(quads[4]._bl.vertices.y, 7, 'y1 test success'); - - strictEqual(quads[8]._bl.vertices.x, 94, 'x2 test success'); - strictEqual(quads[8]._bl.vertices.y, 92, 'y2 test success'); - - strictEqual(quads[8]._tr.vertices.x, 100, 'x3 test success'); - strictEqual(quads[8]._tr.vertices.y, 100, 'y3 test success'); - - deepClose(quads[0]._bl.texCoords.u, 10 / 100, 0.0001, 'u0 test success'); - deepClose(quads[0]._bl.texCoords.v, 70 / 100, 0.0001, 'v0 test success'); - - deepClose(quads[4]._bl.texCoords.u, 15 / 100, 0.0001, 'u1 test success'); - deepClose(quads[4]._bl.texCoords.v, 63 / 100, 0.0001, 'v1 test success'); - - deepClose(quads[8]._bl.texCoords.u, 44 / 100, 0.0001, 'u2 test success'); - deepClose(quads[8]._bl.texCoords.v, 18 / 100, 0.0001, 'v2 test success'); - - deepClose(quads[8]._tr.texCoords.u, 50 / 100, 0.0001, 'u3 test success'); - deepClose(quads[8]._tr.texCoords.v, 10 / 100, 0.0001, 'v3 test success'); + deepClose(uvs[0], 10 / 100, 0.0001, 'u0 test success'); + deepClose(uvs[1], 70 / 100, 0.0001, 'v0 test success'); + deepClose(uvs[10], 15 / 100, 0.0001, 'u1 test success'); + deepClose(uvs[11], 63 / 100, 0.0001, 'v1 test success'); + deepClose(uvs[20], 44 / 100, 0.0001, 'u2 test success'); + deepClose(uvs[21], 18 / 100, 0.0001, 'v2 test success'); + deepClose(uvs[30], 50 / 100, 0.0001, 'u3 test success'); + deepClose(uvs[31], 10 / 100, 0.0001, 'v3 test success'); }; if (spriteFrame.textureLoaded()) { testCallBack(); @@ -158,33 +155,26 @@ test('tiled spriteQuad trimmed', function () { s9Sprite.enableTrimmedContentSize(isTrimmed); s9Sprite.setRenderingType(cc.Scale9Sprite.RenderingType.TILED); s9Sprite._rebuildQuads(); - var quads = s9Sprite._quads; - strictEqual(quads.length, 6, 'quads number[6] success'); - strictEqual(quads[0]._bl.vertices.x, 0, 'x0 test success'); - strictEqual(quads[2]._bl.vertices.x, 40, 'x1 test success'); - strictEqual(quads[4]._bl.vertices.x, 80, 'x2 test success'); - strictEqual(quads[4]._tr.vertices.x, 100, 'x3 test success'); + var vertices = s9Sprite._vertices; + var uvs = s9Sprite._uvs; + strictEqual(vertices.length >= 48, true, 'vertices have at least 48 floats'); + strictEqual(vertices[0], 0, 'x0 test success'); + strictEqual(vertices[16], 40, 'x1 test success'); + strictEqual(vertices[32], 80, 'x2 test success'); + strictEqual(vertices[38], 100, 'x3 test success'); - strictEqual(quads[0]._bl.vertices.y, 0, 'y0 test success'); - strictEqual(quads[5]._bl.vertices.y, 60, 'y1 test success'); - strictEqual(quads[5]._tr.vertices.y, 100, 'y2 test success'); - - strictEqual(quads[2]._bl.vertices.x, 40, 'x1 test success'); - strictEqual(quads[2]._bl.vertices.x, 40, 'x1 test success'); - strictEqual(quads[2]._bl.vertices.x, 40, 'x1 test success'); - strictEqual(quads[2]._bl.vertices.x, 40, 'x1 test success'); + strictEqual(vertices[1], 0, 'y0 test success'); + strictEqual(vertices[41], 60, 'y1 test success'); + strictEqual(vertices[47], 100, 'y2 test success'); // - deepClose(quads[2]._bl.texCoords.u, 10 / 100, 0.0001, 'full quad u0 test success'); - deepClose(quads[2]._bl.texCoords.v, 70 / 100, 0.0001, 'full quad v0 test success'); - - deepClose(quads[2]._tr.texCoords.u, 50 / 100, 0.0001, 'full quad u1 test success'); - deepClose(quads[2]._tr.texCoords.v, 10 / 100, 0.0001, 'full quad v1 test success'); - - deepClose(quads[5]._bl.texCoords.u, 10 / 100, 0.0001, 'part quad u0 test success'); - deepClose(quads[5]._bl.texCoords.v, 70 / 100, 0.0001, 'part quad v0 test success'); - - deepClose(quads[5]._tr.texCoords.u, 30 / 100, 0.0001, 'part quad u1 test success'); - deepClose(quads[5]._tr.texCoords.v, 30 / 100, 0.0001, 'part quad v1 test success'); + deepClose(uvs[16], 10 / 100, 0.0001, 'full quad u0 test success'); + deepClose(uvs[17], 70 / 100, 0.0001, 'full quad v0 test success'); + deepClose(uvs[22], 50 / 100, 0.0001, 'full quad u1 test success'); + deepClose(uvs[23], 10 / 100, 0.0001, 'full quad v1 test success'); + deepClose(uvs[40], 10 / 100, 0.0001, 'part quad u0 test success'); + deepClose(uvs[41], 70 / 100, 0.0001, 'part quad v0 test success'); + deepClose(uvs[46], 30 / 100, 0.0001, 'part quad u1 test success'); + deepClose(uvs[47], 30 / 100, 0.0001, 'part quad v1 test success'); }; if (spriteFrame.textureLoaded()) { testCallBack(); @@ -208,36 +198,34 @@ test('filled-bar-horizontal spriteQuad trimmed', function () { s9Sprite.setFillStart(0.1); s9Sprite.setFillRange(0.3); s9Sprite._rebuildQuads(); - var quads = s9Sprite._quads; - strictEqual(quads.length, 1, 'quads number[1] success'); - strictEqual(quads[0]._bl.vertices.x, 10, 'vertex-bl-x test success'); - strictEqual(quads[0]._bl.vertices.y, 0, 'vertex-bl-y test success'); + var vertices = s9Sprite._vertices; + var uvs = s9Sprite._uvs; + strictEqual(vertices.length >= 8 && uvs >= 8, true, 'vertices have at least 8 floats'); + strictEqual(vertices[0], 10, 'vertex-bl-x test success'); + strictEqual(vertices[1], 0, 'vertex-bl-y test success'); + strictEqual(vertices[6], 40, 'vertex-tr-x test success'); + strictEqual(vertices[7], 100, 'vertex-tr-y test success'); - strictEqual(quads[0]._tr.vertices.x, 40, 'vertex-tr-x test success'); - strictEqual(quads[0]._tr.vertices.y, 100, 'vertex-tr-y test success'); - - deepClose(quads[0]._bl.texCoords.u, 14 / 100, 0.0001, 'texCoords-bl-x test success'); - deepClose(quads[0]._bl.texCoords.v, 70 / 100, 0.0001, 'texCoords-bl-y test success'); - - deepClose(quads[0]._tr.texCoords.u, 26 / 100, 0.0001, 'texCoords-tr-x test success'); - deepClose(quads[0]._tr.texCoords.v, 10 / 100, 0.0001, 'texCoords-tr-y test success'); + deepClose(uvs[0], 14 / 100, 0.0001, 'texCoords-bl-x test success'); + deepClose(uvs[1], 70 / 100, 0.0001, 'texCoords-bl-y test success'); + deepClose(uvs[6], 26 / 100, 0.0001, 'texCoords-tr-x test success'); + deepClose(uvs[7], 10 / 100, 0.0001, 'texCoords-tr-y test success'); s9Sprite.setFillStart(0.3); s9Sprite.setFillRange(-0.4); s9Sprite._rebuildQuads(); - quads = s9Sprite._quads; - strictEqual(quads.length, 1, 'quads number[1] success'); - strictEqual(quads[0]._bl.vertices.x, 0, 'vertex-bl-x test success'); - strictEqual(quads[0]._bl.vertices.y, 0, 'vertex-bl-y test success'); + vertices = s9Sprite._vertices; + uvs = s9Sprite._uvs; + strictEqual(vertices.length >= 8 && uvs >= 8, true, 'vertices have at least 8 floats'); + strictEqual(vertices[0]._bl.vertices.x, 0, 'vertex-bl-x test success'); + strictEqual(vertices[1]._bl.vertices.y, 0, 'vertex-bl-y test success'); + strictEqual(vertices[6]._tr.vertices.x, 30, 'vertex-tr-x test success'); + strictEqual(vertices[7]._tr.vertices.y, 100, 'vertex-tr-y test success'); - strictEqual(quads[0]._tr.vertices.x, 30, 'vertex-tr-x test success'); - strictEqual(quads[0]._tr.vertices.y, 100, 'vertex-tr-y test success'); - - deepClose(quads[0]._bl.texCoords.u, 10 / 100, 0.0001, 'texCoords-bl-x test success'); - deepClose(quads[0]._bl.texCoords.v, 70 / 100, 0.0001, 'texCoords-bl-y test success'); - - deepClose(quads[0]._tr.texCoords.u, 22 / 100, 0.0001, 'texCoords-tr-x test success'); - deepClose(quads[0]._tr.texCoords.v, 10 / 100, 0.0001, 'texCoords-tr-y test success'); + deepClose(uvs[0]._bl.texCoords.u, 10 / 100, 0.0001, 'texCoords-bl-x test success'); + deepClose(uvs[1]._bl.texCoords.v, 70 / 100, 0.0001, 'texCoords-bl-y test success'); + deepClose(uvs[6]._tr.texCoords.u, 22 / 100, 0.0001, 'texCoords-tr-x test success'); + deepClose(uvs[7]._tr.texCoords.v, 10 / 100, 0.0001, 'texCoords-tr-y test success'); }; if (spriteFrame.textureLoaded()) { testCallBack(); @@ -260,36 +248,34 @@ test('filled-bar-vertical spriteQuad trimmed', function () { s9Sprite.setFillStart(0.1); s9Sprite.setFillRange(0.3); s9Sprite._rebuildQuads(); - var quads = s9Sprite._quads; - strictEqual(quads.length, 1, 'quads number[1] success'); - strictEqual(quads[0]._bl.vertices.x, 0, 'vertex-bl-x test success'); - strictEqual(quads[0]._bl.vertices.y, 10, 'vertex-bl-y test success'); + var vertices = s9Sprite._vertices; + var uvs = s9Sprite._uvs; + strictEqual(vertices.length >= 8 && uvs >= 8, true, 'vertices have at least 8 floats'); + strictEqual(vertices[0], 0, 'vertex-bl-x test success'); + strictEqual(vertices[1], 10, 'vertex-bl-y test success'); + strictEqual(vertices[6], 100, 'vertex-tr-x test success'); + strictEqual(vertices[7], 40, 'vertex-tr-y test success'); - strictEqual(quads[0]._tr.vertices.x, 100, 'vertex-tr-x test success'); - strictEqual(quads[0]._tr.vertices.y, 40, 'vertex-tr-y test success'); - - deepClose(quads[0]._bl.texCoords.u, 10 / 100, 0.0001, 'texCoords-bl-x test success'); - deepClose(quads[0]._bl.texCoords.v, 64 / 100, 0.0001, 'texCoords-bl-y test success'); - - deepClose(quads[0]._tr.texCoords.u, 50 / 100, 0.0001, 'texCoords-tr-x test success'); - deepClose(quads[0]._tr.texCoords.v, 46 / 100, 0.0001, 'texCoords-tr-y test success'); + deepClose(uvs[0], 10 / 100, 0.0001, 'texCoords-bl-x test success'); + deepClose(uvs[1], 64 / 100, 0.0001, 'texCoords-bl-y test success'); + deepClose(uvs[6], 50 / 100, 0.0001, 'texCoords-tr-x test success'); + deepClose(uvs[7], 46 / 100, 0.0001, 'texCoords-tr-y test success'); s9Sprite.setFillStart(0.3); s9Sprite.setFillRange(-0.4); s9Sprite._rebuildQuads(); - quads = s9Sprite._quads; - strictEqual(quads.length, 1, 'quads number[1] success'); - strictEqual(quads[0]._bl.vertices.x, 0, 'vertex-bl-x test success'); - strictEqual(quads[0]._bl.vertices.y, 0, 'vertex-bl-y test success'); + vertices = s9Sprite._vertices; + uvs = s9Sprite._uvs; + strictEqual(vertices.length >= 8 && uvs >= 8, true, 'vertices have at least 8 floats'); + strictEqual(vertices[0], 0, 'vertex-bl-x test success'); + strictEqual(vertices[1], 0, 'vertex-bl-y test success'); + strictEqual(vertices[6], 100, 'vertex-tr-x test success'); + strictEqual(vertices[7], 30, 'vertex-tr-y test success'); - strictEqual(quads[0]._tr.vertices.x, 100, 'vertex-tr-x test success'); - strictEqual(quads[0]._tr.vertices.y, 30, 'vertex-tr-y test success'); - - deepClose(quads[0]._bl.texCoords.u, 10 / 100, 0.0001, 'texCoords-bl-x test success'); - deepClose(quads[0]._bl.texCoords.v, 70 / 100, 0.0001, 'texCoords-bl-y test success'); - - deepClose(quads[0]._tr.texCoords.u, 50 / 100, 0.0001, 'texCoords-tr-x test success'); - deepClose(quads[0]._tr.texCoords.v, 52 / 100, 0.0001, 'texCoords-tr-y test success'); + deepClose(uvs[0], 10 / 100, 0.0001, 'texCoords-bl-x test success'); + deepClose(uvs[1], 70 / 100, 0.0001, 'texCoords-bl-y test success'); + deepClose(uvs[6], 50 / 100, 0.0001, 'texCoords-tr-x test success'); + deepClose(uvs[7], 52 / 100, 0.0001, 'texCoords-tr-y test success'); }; if (spriteFrame.textureLoaded()) { testCallBack(); @@ -313,26 +299,24 @@ test('filled-bar-radial spriteQuad trimmed', function () { s9Sprite.setFillStart(0.0); s9Sprite.setFillRange(1 / 4); s9Sprite._rebuildQuads(); - var quads = s9Sprite._quads; + var vertices = s9Sprite._vertices; + var uvs = s9Sprite._uvs; strictEqual(s9Sprite._isTriangle, true, "Triangles used"); - strictEqual(quads.length, 2, 'triangles number[2] success'); + strictEqual(vertices.length >= 30 && uvs >= 30, true, 'vertices have at least 30 floats'); var center = cc.v2(50, 50); var p0 = cc.v2(100, 50); var p1 = cc.v2(100, 100); var p2 = cc.v2(50, 100); - deepClose(quads[1]._tl.vertices.x, center.x, 0.0001, 'center test success'); - deepClose(quads[1]._tl.vertices.y, center.y, 0.0001, 'center test success'); - - deepClose(quads[0]._bl.vertices.x, p0.x, 0.0001, 'p0 test success'); - deepClose(quads[0]._bl.vertices.y, p0.y, 0.0001, 'p0 test success'); - - deepClose(quads[1]._bl.vertices.x, p1.x, 0.0001, 'p1 test success'); - deepClose(quads[1]._bl.vertices.y, p1.y, 0.0001, 'p1 test success'); - - deepClose(quads[1]._tr.vertices.x, p2.x, 0.0001, 'p2 test success'); - deepClose(quads[1]._tr.vertices.y, p2.y, 0.0001, 'p2 test success'); + deepClose(vertices[6], center.x, 0.0001, 'center test success'); + deepClose(vertices[7], center.y, 0.0001, 'center test success'); + deepClose(vertices[2], p0.x, 0.0001, 'p0 test success'); + deepClose(vertices[3], p0.y, 0.0001, 'p0 test success'); + deepClose(vertices[8], p1.x, 0.0001, 'p1 test success'); + deepClose(vertices[9], p1.y, 0.0001, 'p1 test success'); + deepClose(vertices[10], p2.x, 0.0001, 'p2 test success'); + deepClose(vertices[11], p2.y, 0.0001, 'p2 test success'); }; if (spriteFrame.textureLoaded()) { testCallBack(); From 3454b5506a9e0567cfe5ab70f975a88b5d567280 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 22 Jul 2016 14:52:28 +0800 Subject: [PATCH 022/268] Fix culling for tile sprite --- cocos2d/core/sprites/CCScale9Sprite.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/sprites/CCScale9Sprite.js b/cocos2d/core/sprites/CCScale9Sprite.js index bd90a198f1..cd6d7ae0c4 100644 --- a/cocos2d/core/sprites/CCScale9Sprite.js +++ b/cocos2d/core/sprites/CCScale9Sprite.js @@ -437,9 +437,9 @@ var tiledQuadGenerator = { } cornerId[0] = 0; - cornerId[1] = 2; - cornerId[2] = 4; - cornerId[3] = 6; + cornerId[1] = col * 8 + 2; + cornerId[2] = dataLength - col * 8 + 4; + cornerId[3] = dataLength - 2; } }; From ceadbdbfa38061e0b78f9e2791c12d7efb938d7e Mon Sep 17 00:00:00 2001 From: 2youyouo2 <501251991@qq.com> Date: Fri, 22 Jul 2016 15:10:14 +0800 Subject: [PATCH 023/268] support animation callback --- cocos2d/animation/animation-animator.js | 17 ++++ cocos2d/animation/animation-state.js | 4 + cocos2d/animation/types.js | 78 ++++++++++++++-- cocos2d/core/components/CCAnimation.js | 113 +++++++++++++++++++++++- test/qunit/unit/test-animation.js | 98 ++++++++++++++++++++ 5 files changed, 302 insertions(+), 8 deletions(-) diff --git a/cocos2d/animation/animation-animator.js b/cocos2d/animation/animation-animator.js index b095a8f911..580e498307 100644 --- a/cocos2d/animation/animation-animator.js +++ b/cocos2d/animation/animation-animator.js @@ -37,8 +37,25 @@ p.playState = function (state, startTime) { this.play(); }; +p.addAnimation = function (anim) { + Animator.prototype.addAnimation.call(this, anim); + + var listeners = this.animation._listeners; + for (var i = 0, l = listeners.length; i < l; i++) { + var listener = listeners[i]; + anim.on(listener[0], listener[1], listener[2], listener[3]); + } +}; + p.removeAnimation = function (anim) { + var listeners = this.animation._listeners; + for (var i = 0, l = listeners.length; i < l; i++) { + var listener = listeners[i]; + anim.off(listener[0], listener[1], listener[2], listener[3]); + } + Animator.prototype.removeAnimation.call(this, anim); + anim.animator = null; }; diff --git a/cocos2d/animation/animation-state.js b/cocos2d/animation/animation-state.js index a1f8d08926..fc2ecc0306 100644 --- a/cocos2d/animation/animation-state.js +++ b/cocos2d/animation/animation-state.js @@ -68,9 +68,13 @@ JS.getset(state, 'curveLoaded', state.onPlay = function () { // replay this.setTime(0); + + AnimationNode.prototype.onPlay.call(this); }; state.onStop = function () { + AnimationNode.prototype.onStop.call(this); + if (this.animator) { this.animator.removeAnimation(this); } diff --git a/cocos2d/animation/types.js b/cocos2d/animation/types.js index 146499e5bf..5d8ec77cda 100644 --- a/cocos2d/animation/types.js +++ b/cocos2d/animation/types.js @@ -79,7 +79,6 @@ cc.WrapMode = WrapMode; * @class AnimationNodeBase * @constructor * @extends Playable - * @private */ var AnimationNodeBase = function () { Playable.call(this); @@ -94,7 +93,7 @@ JS.extend(AnimationNodeBase, Playable); AnimationNodeBase.prototype.update = function (deltaTime) {}; -/* +/** * !#en The collection and instance of playing animations. * !#zh 动画曲线的集合,根据当前时间计算出每条曲线的状态。 * @class AnimationNode @@ -167,8 +166,12 @@ function AnimationNode (animator, curves, timingInput) { this.speed = 1; /** - * !#en Wrapping mode of the playing animation. - * !#zh 动画循环方式。 + * !#en + * Wrapping mode of the playing animation. + * Notice : dynamic change wrapMode will reset time and repeatCount property + * !#zh + * 动画循环方式。 + * 需要注意的是,动态修改 wrapMode 时,会重置 time 以及 repeatCount * * @property wrapMode * @type {WrapMode} @@ -262,10 +265,32 @@ JS.mixin(AnimationNode.prototype, { } // sample + var info = this.sample(); - if (this.sample()) { + if (!this._lastWrappedInfo) { + this._lastWrappedInfo = info; + } + + var anotherIteration = (info.iterations | 0) > (this._lastWrappedInfo.iterations | 0); + if (this.repeatCount > 1 && anotherIteration) { + if ((this.wrapMode & WrapModeMask.Reverse) === WrapModeMask.Reverse) { + if (this._lastWrappedInfo.direction < 0) { + this.emit('lastframe', this); + } + } + else { + if (this._lastWrappedInfo.direction > 0) { + this.emit('lastframe', this); + } + } + } + + if (info.stopped) { + this.emit('finished', this); this.stop(); } + + this._lastWrappedInfo = info; }, _needRevers: function (currentIterations) { @@ -337,7 +362,7 @@ JS.mixin(AnimationNode.prototype, { direction: direction, stopped: stopped, iterations: currentIterations - } + }; }, sample: function () { @@ -352,10 +377,49 @@ JS.mixin(AnimationNode.prototype, { curve.sample(info.time, info.ratio, this); } - return info.stopped; + return info; + }, + + onStop: function () { + this.emit('stop', this); + }, + + onPlay: function () { + this.emit('play', this); + }, + + onPause: function () { + this.emit('pause', this); + }, + + onResume: function () { + this.emit('resume', this); } }); +cc.defineGetterSetter(AnimationNode.prototype, 'wrapMode', + function () { + return this._wrapMode; + }, + function (value) { + this._wrapMode = value; + + if (CC_EDITOR) return; + + // dynamic change wrapMode will need reset time to 0 + this.time = 0; + + if (value & WrapModeMask.Loop) { + this.repeatCount = Infinity; + } + else { + this.repeatCount = 1; + } + } +); + +cc.js.mixin(AnimationNode.prototype, cc.EventTarget.prototype); + cc.AnimationNode = AnimationNode; module.exports = { diff --git a/cocos2d/core/components/CCAnimation.js b/cocos2d/core/components/CCAnimation.js index 86e66b3a6b..a0325137c5 100644 --- a/cocos2d/core/components/CCAnimation.js +++ b/cocos2d/core/components/CCAnimation.js @@ -36,7 +36,25 @@ function equalClips (clip1, clip2) { /** * !#en The animation component is used to play back animations. + * + * Animation provide several events to register: + * - play : Emit when egine playing animation + * - stop : Emit when stop playing animation + * - pause : Emit when pause animation + * - resume : Emit when resume animation + * - lastframe : If animation repeat coutn is larger than 1, emit when animation play to the last frame + * - finished : Emit when finish playing animation + * * !#zh Animation 组件用于播放动画。你能指定动画剪辑到动画组件并从脚本控制播放。 + * + * Animation 提供了一系列可注册的事件: + * - play : 开始播放时 + * - stop : 停止播放时 + * - pause : 暂停播放时 + * - resume : 恢复播放时 + * - lastframe : 假如动画循环次数大于 1,当动画播放到最后一帧时 + * - finished : 动画播放完成时 + * * @class Animation * @extends CCComponent */ @@ -58,6 +76,8 @@ var Animation = cc.Class({ this._didInit = false; this._currentClip = null; + + this._listeners = []; }, properties: { @@ -471,6 +491,98 @@ var Animation = cc.Class({ this._animator.sample(); }, + + /** + * !#en + * Register animation event callback. + * The event argumetns will provide the AnimationState which emit the event. + * When play an animation, will auto register the event callback to the AnimationState, and unregister the event callback from the AnimationState when animation stopped. + * !#zh + * 注册动画事件回调。 + * 回调的事件里将会附上发送事件的 AnimationState。 + * 当播放一个动画时,会自动将事件注册到对应的 AnimationState 上,停止播放时会将事件从这个 AnimationState 上取消注册。 + * @method on + * @param {String} type - A string representing the event type to listen for. + * @param {Function} callback - The callback that will be invoked when the event is dispatched. + * The callback is ignored if it is a duplicate (the callbacks are unique). + * @param {Event} callback.param event + * @param {Object} target - The target to invoke the callback, can be null + * @param {Boolean} useCapture - When set to true, the capture argument prevents callback + * from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. + * When false, callback will NOT be invoked when event's eventPhase attribute value is CAPTURING_PHASE. + * Either way, callback will be invoked when event's eventPhase attribute value is AT_TARGET. + * + * @example + * onPlay: function (event) { + * var state = event.detail; // state instanceof cc.AnimationState + * var type = event.type; // type === 'play'; + * } + * + * // register event to all animation + * animation.on('', 'play', this.onPlay, this); + */ + on: function (type, callback, target, useCapture) { + this._init(); + var listeners = this._listeners; + + for (var i = 0, l = listeners.length; i < l; i++) { + var listener = listeners[i]; + if (listener[0] === type && + listener[1] === callback && + listener[2] === target && + listener[3] === useCapture) { + return; + } + } + + var anims = this._animator.playingAnims; + for (var j = 0, jj = anims.length; j < jj; j++) { + anims[j].on(type, callback, target, useCapture); + } + + listeners.push([type, callback, target, useCapture]); + }, + + + /** + * !#en + * Unregister animation event callback. + * !#zh + * 取消注册动画事件回调。 + * @method off + * @param {String} type - A string representing the event type being removed. + * @param {Function} callback - The callback to remove. + * @param {Object} target - The target to invoke the callback, if it's not given, only callback without target will be removed + * @param {Boolean} useCapture - Specifies whether the callback being removed was registered as a capturing callback or not. + * If not specified, useCapture defaults to false. If a callback was registered twice, + * one with capture and one without, each must be removed separately. Removal of a capturing callback + * does not affect a non-capturing version of the same listener, and vice versa. + * + * @example + * // unregister event to all animation + * animation.off('', 'play', this.onPlay, this); + */ + off: function (type, callback, target, useCapture) { + this._init(); + var listeners = this._listeners; + + for (var i = listeners.length - 1; i >= 0; i--) { + var listener = listeners[i]; + if (listener[0] === type && + listener[1] === callback && + listener[2] === target && + listener[3] === useCapture) { + + var anims = this._animator.playingAnims; + for (var j = 0, jj = anims.length; j < jj; j++) { + anims[j].off(type, callback, target, useCapture); + } + + listeners.splice(i, 1); + } + } + }, + /////////////////////////////////////////////////////////////////////////////// // Internal Methods /////////////////////////////////////////////////////////////////////////////// @@ -520,5 +632,4 @@ var Animation = cc.Class({ } }); - cc.Animation = module.exports = Animation; diff --git a/test/qunit/unit/test-animation.js b/test/qunit/unit/test-animation.js index 25668bd08b..4a168c81f0 100644 --- a/test/qunit/unit/test-animation.js +++ b/test/qunit/unit/test-animation.js @@ -1226,3 +1226,101 @@ test('animation removeClip', function () { strictEqual(animation._clips.indexOf(clip2), -1, 'clip2 will be removed even clip2 is playing if force is true'); }); +test('animation callback', function () { + var type; + + function callback (event) { + var state = event.detail; + + strictEqual(state instanceof cc.AnimationState, true); + strictEqual(state.name === 'move', true); + + type = event.type; + } + + var entity = new cc.Node(); + var animation = entity.addComponent(cc.Animation); + + var clip = new cc.AnimationClip(); + clip._name = 'move'; + clip._duration = 1; + clip.curveData = { + props: { + x: [ + {frame: 0, value: 0}, + {frame: 1, value: 100} + ] + } + }; + animation.addClip(clip); + + var state = animation.getAnimationState('move'); + + animation.on('play', callback); + animation.on('pause', callback); + animation.on('resume', callback); + animation.on('finished', callback); + + animation.play('move'); + strictEqual(type === 'play', true, 'should trigger play callback'); + + animation.pause('move'); + strictEqual(type === 'pause', true, 'should trigger pause callback'); + + animation.resume('move'); + strictEqual(type === 'resume', true, 'should trigger resume callback'); + + state.update(0); + state.update(1); + strictEqual(type === 'finished', true, 'should trigger finished callback'); + + type = ''; + + animation.off('play', callback); + + animation.play('move'); + strictEqual(type === '', true, 'should not trigger callback'); + + animation.off('pause', callback); + animation.off('resume', callback); + + animation.pause('move'); + strictEqual(type === 'pause', false, 'should not trigger pause callback'); + + animation.on('resume', callback); + animation.resume('move'); + strictEqual(type === 'resume', true, 'should trigger resume callback'); + + animation.on('stop', callback); + state.update(1); + strictEqual(type === 'stop', true, 'should trigger stop callback'); + + + clip = new cc.AnimationClip(); + clip._name = 'move2'; + clip._duration = 1; + clip.curveData = { + props: { + x: [ + {frame: 0, value: 0}, + {frame: 1, value: 100} + ] + } + }; + animation.addClip(clip); + + var list = []; + function callback2 (event) { + list.push([event.detail.name, event.type]); + } + + animation.play('move'); + + animation.on('play', callback2); + animation.on('stop', callback2); + + animation.play('move2'); + + deepEqual(list, [['move2', 'play'], ['move', 'stop']]); +}); + From fd7daf3440eac61e58b0a64f145302760c47ca92 Mon Sep 17 00:00:00 2001 From: 2youyouo2 <501251991@qq.com> Date: Fri, 22 Jul 2016 15:11:08 +0800 Subject: [PATCH 024/268] should not auto play default animation if it is disabled --- cocos2d/core/components/CCAnimation.js | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/cocos2d/core/components/CCAnimation.js b/cocos2d/core/components/CCAnimation.js index a0325137c5..6743b41b2b 100644 --- a/cocos2d/core/components/CCAnimation.js +++ b/cocos2d/core/components/CCAnimation.js @@ -167,9 +167,7 @@ var Animation = cc.Class({ }, __preload: function () { - if (CC_EDITOR) return; - - this._init(); + if (CC_EDITOR || !this.enabled) return; if (this.playOnLoad && this._defaultClip) { var state = this.getAnimationState(this._defaultClip.name); From a5deddc3b37063bc665e1943c91fd929f2f7b107 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Fri, 22 Jul 2016 18:30:16 +0800 Subject: [PATCH 025/268] improve webivew --- cocos2d/core/components/CCWebView.js | 53 ++++++++++++++++++++-------- jsb/jsb-etc.js | 1 + jsb/jsb-webview.js | 26 ++++++++++++++ 3 files changed, 66 insertions(+), 14 deletions(-) create mode 100644 jsb/jsb-webview.js diff --git a/cocos2d/core/components/CCWebView.js b/cocos2d/core/components/CCWebView.js index 3736d404eb..06fbf2fc77 100644 --- a/cocos2d/core/components/CCWebView.js +++ b/cocos2d/core/components/CCWebView.js @@ -21,7 +21,19 @@ THE SOFTWARE. ****************************************************************************/ +var EventType = _ccsg.WebView.EventType; +/* + * !#en WebView event type + * !#zh WebView 事件类型 + * @enum WebView.EventType + */ + +/* + * !#en Web page Load completed. + * !#zh 网页加载完成 + * @property {String} LOADED + */ /** * !#en cc.WebView is a component for display web pages in the game @@ -41,7 +53,12 @@ var WebView = cc.Class({ _useOriginalSize: true, _url: '', - url: { + /** + * !#en A given URL to be loaded by the WebView, it should have a http or https prefix. + * !#zh 指定 WebView 加载的网址,它应该是一个 http 或者 https 开头的字符串 + * @property {String} URL + */ + URL: { type: String, get: function () { return this._url; @@ -49,16 +66,26 @@ var WebView = cc.Class({ set: function (url) { this._url = url; var sgNode = this._sgNode; - if (!sgNode) return; - sgNode.loadURL(url); + if (sgNode) { + sgNode.loadURL(url); + } } + }, + + /** + * !#en The webview's event callback , it will be triggered when web page finished loading. + * !#zh WebView 的回调事件,当网页加载完成之后会回调此函数 + * @property {cc.Component.EventHandler[]} webViewEvent + */ + webViewEvent: { + default: [], + type: cc.Component.EventHandler, } }, - // statics: { - // EventType: EventType, - // ResourceType: ResourceType - // }, + statics: { + EventType: EventType, + }, _createSgNode: function () { return new _ccsg.WebView(); @@ -66,7 +93,9 @@ var WebView = cc.Class({ _initSgNode: function () { var sgNode = this._sgNode; - if (!sgNode) return; + + sgNode.setEventListener(EventType.LOADED , this._onWebViewLoaded.bind(this)); + sgNode.loadURL(this._url); if (CC_EDITOR && this._useOriginalSize) { @@ -77,12 +106,8 @@ var WebView = cc.Class({ } }, - onLoad: function () { - - }, - - reload: function () { - + _onWebViewLoaded: function () { + cc.Component.EventHandler.emitEvents(this.webViewEvent, this, EventType.LOADED); } }); diff --git a/jsb/jsb-etc.js b/jsb/jsb-etc.js index 726e9fc8c4..63bf35c983 100644 --- a/jsb/jsb-etc.js +++ b/jsb/jsb-etc.js @@ -204,6 +204,7 @@ window._ccsg = { Label: cc.Label, EditBox: cc.EditBox, VideoPlayer: cc.VideoPlayer, + WebView: cc.WebView, TMXTiledMap: cc.TMXTiledMap, TMXLayer: cc.TMXLayer, MotionStreak: cc.MotionStreak diff --git a/jsb/jsb-webview.js b/jsb/jsb-webview.js new file mode 100644 index 0000000000..8b8c1cd1b9 --- /dev/null +++ b/jsb/jsb-webview.js @@ -0,0 +1,26 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Chukong Aipu reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +cc.WebView = ccui.WebView; From 380bc05666be06b04fb8b5026761f9d8cc643829 Mon Sep 17 00:00:00 2001 From: Nan Wang Date: Mon, 25 Jul 2016 10:52:01 +0800 Subject: [PATCH 026/268] update engine version --- CCBoot.js | 2 +- CCDebugger.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index 959953192a..fa37f80cb1 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -58,7 +58,7 @@ _p = null; * @name cc.ENGINE_VERSION */ var engineVersion; -engineVersion = '1.2.0-beta.1'; +engineVersion = '1.2.0-beta.2'; window['CocosEngine'] = cc.ENGINE_VERSION = engineVersion; /** diff --git a/CCDebugger.js b/CCDebugger.js index 3a54773167..62c1669203 100644 --- a/CCDebugger.js +++ b/CCDebugger.js @@ -333,7 +333,7 @@ cc.DebugMode = Enum({ /** * !#en The debug mode none. * !#zh 禁止模式,禁止显示任何日志信息。 - * @property NONE. + * @property NONE * @type {Number} * @static */ From f738204e1b6ba4bd88359207e9c493c95165ab41 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Mon, 25 Jul 2016 15:46:26 +0800 Subject: [PATCH 027/268] fix a few webview related issues --- cocos2d/core/components/CCWebView.js | 28 +++++++++++++++++ cocos2d/core/editbox/CCSGEditBox.js | 4 +-- cocos2d/core/videoplayer/CCSGVideoPlayer.js | 1 - cocos2d/core/webview/CCSGWebView.js | 34 ++++++++++++--------- jsb/index.js | 1 + 5 files changed, 50 insertions(+), 18 deletions(-) diff --git a/cocos2d/core/components/CCWebView.js b/cocos2d/core/components/CCWebView.js index 06fbf2fc77..582ee63e51 100644 --- a/cocos2d/core/components/CCWebView.js +++ b/cocos2d/core/components/CCWebView.js @@ -87,14 +87,34 @@ var WebView = cc.Class({ EventType: EventType, }, + onLoad: function() { + if(CC_JSB) { + if (cc.sys.os === cc.sys.OS_OSX || cc.sys.os === cc.sys.OS_WINDOWS) { + this.enabled = false; + } + } + }, + _createSgNode: function () { + if(CC_JSB) { + if (cc.sys.os === cc.sys.OS_OSX || cc.sys.os === cc.sys.OS_WINDOWS) { + console.log('WebView is not supported on Mac and Windows!'); + return null; + } + } return new _ccsg.WebView(); }, _initSgNode: function () { var sgNode = this._sgNode; + if (!sgNode) return; + if(!CC_JSB) { + sgNode.createDomElementIfNeeded(); + } sgNode.setEventListener(EventType.LOADED , this._onWebViewLoaded.bind(this)); + sgNode.setEventListener(EventType.LOADING , this._onWebViewLoading.bind(this)); + sgNode.setEventListener(EventType.ERROR , this._onWebViewLoadError.bind(this)); sgNode.loadURL(this._url); @@ -108,6 +128,14 @@ var WebView = cc.Class({ _onWebViewLoaded: function () { cc.Component.EventHandler.emitEvents(this.webViewEvent, this, EventType.LOADED); + }, + + _onWebViewLoading: function () { + cc.Component.EventHandler.emitEvents(this.webViewEvent, this, EventType.LOADING); + }, + + _onWebViewLoadError: function () { + cc.Component.EventHandler.emitEvents(this.webViewEvent, this, EventType.ERROR); } }); diff --git a/cocos2d/core/editbox/CCSGEditBox.js b/cocos2d/core/editbox/CCSGEditBox.js index d772531066..522d128799 100644 --- a/cocos2d/core/editbox/CCSGEditBox.js +++ b/cocos2d/core/editbox/CCSGEditBox.js @@ -247,7 +247,6 @@ _ccsg.EditBox = _ccsg.Node.extend({ this._placeholderColor = cc.Color.GRAY; this.initWithSizeAndBackgroundSprite(size, normal9SpriteBg); - this._renderCmd.createNativeControl(); }, _createRenderCmd: function () { @@ -549,6 +548,7 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; }; proto._createDomInput = function () { + this._removeDomInputControl(); var thisPointer = this; var tmpEdTxt = this._edTxt = document.createElement('input'); tmpEdTxt.type = 'text'; @@ -626,6 +626,7 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; }; proto._createDomTextArea = function () { + this._removeDomInputControl(); var thisPointer = this; var tmpEdTxt = this._edTxt = document.createElement('textarea'); tmpEdTxt.type = 'text'; @@ -985,7 +986,6 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; this._editBox = node; //it's a dom node, may be assigned with Input or TextArea. - this._edTxt = null; this._edFontSize = 14; this._edFontName = 'Arial'; this._textLabel = null; diff --git a/cocos2d/core/videoplayer/CCSGVideoPlayer.js b/cocos2d/core/videoplayer/CCSGVideoPlayer.js index a38132f352..3c6d984182 100644 --- a/cocos2d/core/videoplayer/CCSGVideoPlayer.js +++ b/cocos2d/core/videoplayer/CCSGVideoPlayer.js @@ -35,7 +35,6 @@ _ccsg.VideoPlayer = _ccsg.Node.extend(/** @lends _ccsg.VideoPlayer# */{ _ccsg.Node.prototype.ctor.call(this); // 播放结束等事件处理的队列 this._EventList = {}; - this._renderCmd.createDom(); }, _createRenderCmd: function(){ diff --git a/cocos2d/core/webview/CCSGWebView.js b/cocos2d/core/webview/CCSGWebView.js index 7261fe22bb..f869d7a151 100644 --- a/cocos2d/core/webview/CCSGWebView.js +++ b/cocos2d/core/webview/CCSGWebView.js @@ -21,12 +21,16 @@ _ccsg.WebView = _ccsg.Node.extend(/** @lends _ccsg.WebView# */{ - ctor: function (path) { + ctor: function () { _ccsg.Node.prototype.ctor.call(this); this.setContentSize(cc.size(300, 200)); this._EventList = {}; - if(path) - this.loadURL(path); + }, + + createDomElementIfNeeded: function () { + if (!this._renderCmd._div) { + this._renderCmd.createNativeControl(); + } }, setJavascriptInterfaceScheme: function(scheme){}, @@ -187,15 +191,11 @@ _ccsg.WebView = _ccsg.Node.extend(/** @lends _ccsg.WebView# */{ } }); -/** - * The WebView support list of events - * @type {{LOADING: string, LOADED: string, ERROR: string}} - */ _ccsg.WebView.EventType = { - LOADING: "loading", - LOADED: "load", - ERROR: "error", - JS_EVALUATED: "js" + LOADING: 0, + LOADED: 1, + ERROR: 2, + JS_EVALUATED: 3 }; (function(){ @@ -236,10 +236,6 @@ _ccsg.WebView.EventType = { this._div = null; this._iframe = null; this._listener = null; - - this.createDom(); - this.initStyle(); - this.initEvent(); }; var proto = _ccsg.WebView.RenderCmd.prototype = Object.create(RenderCmd.prototype); @@ -286,6 +282,7 @@ _ccsg.WebView.EventType = { proto.updateMatrix = function(){ if (!this._div) return; + var node = this._node, scaleX = cc.view._scaleX, scaleY = cc.view._scaleY; var dpr = cc.view._devicePixelRatio; var t = this._worldTransform; @@ -357,6 +354,12 @@ _ccsg.WebView.EventType = { cc.container.appendChild(this._div); }; + proto.createNativeControl = function () { + this.createDom(); + this.initStyle(); + this.initEvent(); + }; + proto.removeDom = function(){ var div = this._div; if(div){ @@ -369,6 +372,7 @@ _ccsg.WebView.EventType = { if(hasChild) cc.container.removeChild(div); } + this._div = null; }; })(_ccsg.WebView._polyfill); diff --git a/jsb/index.js b/jsb/index.js index 18f61b6f61..a840eab77a 100644 --- a/jsb/index.js +++ b/jsb/index.js @@ -98,6 +98,7 @@ require('./jsb-scale9sprite'); require('./jsb-label'); require('./jsb-editbox'); require('./jsb-videoplayer'); +require('./jsb-webview.js'); require('./jsb-particle'); require('./jsb-spine'); require('./jsb-enums'); From 2dd8112de1e6ed87a79645c9b6e3e8f0d0791946 Mon Sep 17 00:00:00 2001 From: 2youyouo2 <501251991@qq.com> Date: Mon, 25 Jul 2016 16:27:29 +0800 Subject: [PATCH 028/268] fixed animatingInEditMode --- cocos2d/core/CCNode.js | 16 ++++++++++++++++ cocos2d/core/components/CCComponent.js | 4 ++++ 2 files changed, 20 insertions(+) diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index c5910124e6..8811fc3df7 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -752,6 +752,10 @@ var Node = cc.Class({ component.__onNodeActivated(true); } + if (CC_EDITOR) { + cc.engine.updateAnimatingInEditMode(); + } + return component; }, @@ -802,6 +806,10 @@ var Node = cc.Class({ // call onLoad/onEnable comp.__onNodeActivated(true); } + + if (CC_EDITOR) { + cc.engine.updateAnimatingInEditMode(); + } }, /** @@ -830,6 +838,10 @@ var Node = cc.Class({ if (component) { component.destroy(); } + + if (CC_EDITOR) { + cc.engine.updateAnimatingInEditMode(); + } }, /** @@ -867,6 +879,10 @@ var Node = cc.Class({ cc.error('Component not owned by this entity'); } } + + if (CC_EDITOR) { + cc.engine.updateAnimatingInEditMode(); + } }, // INTERNAL diff --git a/cocos2d/core/components/CCComponent.js b/cocos2d/core/components/CCComponent.js index 9d396c560e..58ec687c06 100644 --- a/cocos2d/core/components/CCComponent.js +++ b/cocos2d/core/components/CCComponent.js @@ -358,6 +358,10 @@ var Component = cc.Class({ callOnEnable(this, value); } } + + if (CC_EDITOR) { + cc.engine.updateAnimatingInEditMode(); + } }, visible: false }, From 216204220209a217dfe47088ec44868fac860c20 Mon Sep 17 00:00:00 2001 From: 2youyouo2 <501251991@qq.com> Date: Mon, 25 Jul 2016 17:18:06 +0800 Subject: [PATCH 029/268] refine code --- cocos2d/core/CCNode.js | 16 ----- cocos2d/core/components/CCComponent.js | 87 +++++++++++++------------- 2 files changed, 42 insertions(+), 61 deletions(-) diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index 8811fc3df7..c5910124e6 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -752,10 +752,6 @@ var Node = cc.Class({ component.__onNodeActivated(true); } - if (CC_EDITOR) { - cc.engine.updateAnimatingInEditMode(); - } - return component; }, @@ -806,10 +802,6 @@ var Node = cc.Class({ // call onLoad/onEnable comp.__onNodeActivated(true); } - - if (CC_EDITOR) { - cc.engine.updateAnimatingInEditMode(); - } }, /** @@ -838,10 +830,6 @@ var Node = cc.Class({ if (component) { component.destroy(); } - - if (CC_EDITOR) { - cc.engine.updateAnimatingInEditMode(); - } }, /** @@ -879,10 +867,6 @@ var Node = cc.Class({ cc.error('Component not owned by this entity'); } } - - if (CC_EDITOR) { - cc.engine.updateAnimatingInEditMode(); - } }, // INTERNAL diff --git a/cocos2d/core/components/CCComponent.js b/cocos2d/core/components/CCComponent.js index 58ec687c06..8ea95a835d 100644 --- a/cocos2d/core/components/CCComponent.js +++ b/cocos2d/core/components/CCComponent.js @@ -52,6 +52,48 @@ var callOnFocusInTryCatch = CC_EDITOR && eval(ExecInTryCatchTmpl.replace(/_FUNC_ var callOnLostFocusInTryCatch = CC_EDITOR && eval(ExecInTryCatchTmpl.replace(/_FUNC_/g, 'onLostFocusInEditor')); function callOnEnable (self, enable) { + + if (!CC_EDITOR || (cc.engine.isPlaying || self.constructor._executeInEditMode) ) { + var enableCalled = self._objFlags & IsOnEnableCalled; + if (enable) { + if (!enableCalled) { + if (self.onEnable) { + if (CC_EDITOR) { + callOnEnableInTryCatch(self); + } + else { + self.onEnable(); + } + } + + var deactivatedDuringOnEnable = !self.node._activeInHierarchy; + if (deactivatedDuringOnEnable) { + return; + } + + cc.director.getScheduler().resumeTarget(self); + _registerEvent(self, true); + + self._objFlags |= IsOnEnableCalled; + } + } + else if (enableCalled) { + if (self.onDisable) { + if (CC_EDITOR) { + callOnDisableInTryCatch(self); + } + else { + self.onDisable(); + } + } + + cc.director.getScheduler().pauseTarget(self); + _registerEvent(self, false); + + self._objFlags &= ~IsOnEnableCalled; + } + } + if (CC_EDITOR) { if (enable) { if ( !(self._objFlags & IsEditorOnEnableCalled) ) { @@ -65,47 +107,6 @@ function callOnEnable (self, enable) { self._objFlags &= ~IsEditorOnEnableCalled; } } - if ( !(cc.engine.isPlaying || self.constructor._executeInEditMode) ) { - return; - } - } - var enableCalled = self._objFlags & IsOnEnableCalled; - if (enable) { - if (!enableCalled) { - if (self.onEnable) { - if (CC_EDITOR) { - callOnEnableInTryCatch(self); - } - else { - self.onEnable(); - } - } - - var deactivatedDuringOnEnable = !self.node._activeInHierarchy; - if (deactivatedDuringOnEnable) { - return; - } - - cc.director.getScheduler().resumeTarget(self); - _registerEvent(self, true); - - self._objFlags |= IsOnEnableCalled; - } - } - else if (enableCalled) { - if (self.onDisable) { - if (CC_EDITOR) { - callOnDisableInTryCatch(self); - } - else { - self.onDisable(); - } - } - - cc.director.getScheduler().pauseTarget(self); - _registerEvent(self, false); - - self._objFlags &= ~IsOnEnableCalled; } } @@ -358,10 +359,6 @@ var Component = cc.Class({ callOnEnable(this, value); } } - - if (CC_EDITOR) { - cc.engine.updateAnimatingInEditMode(); - } }, visible: false }, From bf082642ffcbcd6054914ab1f0711d5f51678436 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Mon, 25 Jul 2016 16:13:07 +0800 Subject: [PATCH 030/268] fix web enum on Mac and Windows 1. add more events to webview --- cocos2d/core/components/CCWebView.js | 29 +++++++++++++++++++++++----- jsb/jsb-enums.js | 20 +++++++++++++++---- 2 files changed, 40 insertions(+), 9 deletions(-) diff --git a/cocos2d/core/components/CCWebView.js b/cocos2d/core/components/CCWebView.js index 582ee63e51..38c9164dec 100644 --- a/cocos2d/core/components/CCWebView.js +++ b/cocos2d/core/components/CCWebView.js @@ -75,9 +75,27 @@ var WebView = cc.Class({ /** * !#en The webview's event callback , it will be triggered when web page finished loading. * !#zh WebView 的回调事件,当网页加载完成之后会回调此函数 - * @property {cc.Component.EventHandler[]} webViewEvent + * @property {cc.Component.EventHandler[]} webViewLoadedEvent */ - webViewEvent: { + webViewLoadedEvent: { + default: [], + type: cc.Component.EventHandler, + }, + /** + * !#en The webview's event callback , it will be triggered when web page is loading. + * !#zh WebView 的回调事件,当网页加载时会回调此函数 + * @property {cc.Component.EventHandler[]} webViewLoadingEvent + */ + webViewLoadingEvent: { + default: [], + type: cc.Component.EventHandler, + }, + /** + * !#en The webview's event callback , it will be triggered when there are errors when loading. + * !#zh WebView 的回调事件,当网页加载出错时会回调此函数 + * @property {cc.Component.EventHandler[]} webViewErrorEvent + */ + webViewErrorEvent: { default: [], type: cc.Component.EventHandler, } @@ -127,15 +145,16 @@ var WebView = cc.Class({ }, _onWebViewLoaded: function () { - cc.Component.EventHandler.emitEvents(this.webViewEvent, this, EventType.LOADED); + cc.Component.EventHandler.emitEvents(this.webViewLoadedEvent, this, EventType.LOADED); }, _onWebViewLoading: function () { - cc.Component.EventHandler.emitEvents(this.webViewEvent, this, EventType.LOADING); + cc.Component.EventHandler.emitEvents(this.webViewLoadingEvent, this, EventType.LOADING); + return true; }, _onWebViewLoadError: function () { - cc.Component.EventHandler.emitEvents(this.webViewEvent, this, EventType.ERROR); + cc.Component.EventHandler.emitEvents(this.webViewErrorEvent, this, EventType.ERROR); } }); diff --git a/jsb/jsb-enums.js b/jsb/jsb-enums.js index 891ba149ec..c1e23d720c 100644 --- a/jsb/jsb-enums.js +++ b/jsb/jsb-enums.js @@ -38,11 +38,23 @@ if (cc.sys.os === cc.sys.OS_OSX || cc.sys.os === cc.sys.OS_WINDOWS) { cc.VideoPlayer = {}; } +//FIXME: should delete this line after implementing the VideoPlayer on Mac and Windows +if (cc.sys.os === cc.sys.OS_OSX || cc.sys.os === cc.sys.OS_WINDOWS) { + cc.WebView = {}; +} + cc.VideoPlayer.EventType = { - PLAYING: "play", - PAUSED: "pause", - STOPPED: "stop", - COMPLETED: "complete" + PLAYING: 0, + PAUSED: 1, + STOPPED: 2, + COMPLETED: 3 +}; + +cc.WebView.EventType = { + LOADING: 0, + LOADED: 1, + ERROR: 2, + JS_EVALUATED: 3 }; cc.EditBox.InputMode = cc.Enum({ From a9c123ef5e1f9ce75beef903a2859e16ac8ed29b Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Mon, 25 Jul 2016 18:04:40 +0800 Subject: [PATCH 031/268] fix scale9sprite not draw when dirty region is enabled --- cocos2d/core/base-nodes/CCSGNodeCanvasRenderCmd.js | 6 ++++++ cocos2d/core/sprites/CCScale9Sprite.js | 12 ++++++++++++ 2 files changed, 18 insertions(+) diff --git a/cocos2d/core/base-nodes/CCSGNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCSGNodeCanvasRenderCmd.js index 9ec836d821..1bd2bf5a2c 100644 --- a/cocos2d/core/base-nodes/CCSGNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCSGNodeCanvasRenderCmd.js @@ -448,6 +448,12 @@ _ccsg.Node.RenderCmd.prototype = { 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(); diff --git a/cocos2d/core/sprites/CCScale9Sprite.js b/cocos2d/core/sprites/CCScale9Sprite.js index 52e1a20362..e721582ed1 100644 --- a/cocos2d/core/sprites/CCScale9Sprite.js +++ b/cocos2d/core/sprites/CCScale9Sprite.js @@ -1076,6 +1076,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ this._blendFunc.src = blendFunc || cc.macro.BLEND_SRC; this._blendFunc.dst = dst || cc.macro.BLEND_DST; } + this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); }, /** @@ -1106,6 +1107,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ if (this._isTrimmedContentSize !== isTrimmed) { this._isTrimmedContentSize = isTrimmed; this._quadsDirty = true; + this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); } }, @@ -1120,6 +1122,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ setState: function (state) { this._brightState = state; this._renderCmd.setState(state); + this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); }, /** @@ -1138,6 +1141,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ if (this._renderingType === type) return; this._renderingType = type; this._quadsDirty = true; + this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); }, /** * get the rendering type, could be simple or slice @@ -1153,6 +1157,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ setInsetLeft: function (insetLeft) { this._insetLeft = insetLeft; this._quadsDirty = true; + this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); }, /** * get the left border of 9 slice sprite, the result is specified before trimmed. @@ -1168,6 +1173,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ setInsetTop: function (insetTop) { this._insetTop = insetTop; this._quadsDirty = true; + this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); }, /** @@ -1185,6 +1191,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ setInsetRight: function (insetRight) { this._insetRight = insetRight; this._quadsDirty = true; + this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); }, /** @@ -1202,6 +1209,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ setInsetBottom: function (insetBottom) { this._insetBottom = insetBottom; this._quadsDirty = true; + this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); }, /** * get the bottom border of 9 slice sprite, the result is specified before trimmed. @@ -1217,6 +1225,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ this._fillType = value; if(this._renderingType === cc.Scale9Sprite.RenderingType.FILLED) { this._quadsDirty = true; + this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); } }, @@ -1228,6 +1237,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ this._fillCenter = cc.v2(value,y); if(this._renderingType === cc.Scale9Sprite.RenderingType.FILLED && this._fillType === cc.Scale9Sprite.FillType.RADIAL) { this._quadsDirty = true; + this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); } }, @@ -1261,6 +1271,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ this._fillStart = value; if(this._renderingType === cc.Scale9Sprite.RenderingType.FILLED) { this._quadsDirty = true; + this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); } }, @@ -1274,6 +1285,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ this._fillRange = value; if(this._renderingType === cc.Scale9Sprite.RenderingType.FILLED ) { this._quadsDirty = true; + this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); } }, From 628e6c2962c42b587f3429a923b6b7f16c126919 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Tue, 26 Jul 2016 11:19:27 +0800 Subject: [PATCH 032/268] refine webview --- cocos2d/core/components/CCWebView.js | 30 +++++++++++++--------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/cocos2d/core/components/CCWebView.js b/cocos2d/core/components/CCWebView.js index 38c9164dec..7286b0952b 100644 --- a/cocos2d/core/components/CCWebView.js +++ b/cocos2d/core/components/CCWebView.js @@ -56,9 +56,9 @@ var WebView = cc.Class({ /** * !#en A given URL to be loaded by the WebView, it should have a http or https prefix. * !#zh 指定 WebView 加载的网址,它应该是一个 http 或者 https 开头的字符串 - * @property {String} URL + * @property {String} url */ - URL: { + url: { type: String, get: function () { return this._url; @@ -75,27 +75,27 @@ var WebView = cc.Class({ /** * !#en The webview's event callback , it will be triggered when web page finished loading. * !#zh WebView 的回调事件,当网页加载完成之后会回调此函数 - * @property {cc.Component.EventHandler[]} webViewLoadedEvent + * @property {cc.Component.EventHandler[]} webViewLoadedEvents */ - webViewLoadedEvent: { + webViewLoadedEvents: { default: [], type: cc.Component.EventHandler, }, /** * !#en The webview's event callback , it will be triggered when web page is loading. * !#zh WebView 的回调事件,当网页加载时会回调此函数 - * @property {cc.Component.EventHandler[]} webViewLoadingEvent + * @property {cc.Component.EventHandler[]} webViewLoadingEvents */ - webViewLoadingEvent: { + webViewLoadingEvents: { default: [], type: cc.Component.EventHandler, }, /** * !#en The webview's event callback , it will be triggered when there are errors when loading. * !#zh WebView 的回调事件,当网页加载出错时会回调此函数 - * @property {cc.Component.EventHandler[]} webViewErrorEvent + * @property {cc.Component.EventHandler[]} webViewErrorEvents */ - webViewErrorEvent: { + webViewErrorEvents: { default: [], type: cc.Component.EventHandler, } @@ -105,11 +105,9 @@ var WebView = cc.Class({ EventType: EventType, }, - onLoad: function() { - if(CC_JSB) { - if (cc.sys.os === cc.sys.OS_OSX || cc.sys.os === cc.sys.OS_WINDOWS) { - this.enabled = false; - } + onLoad: CC_JSB && function() { + if (cc.sys.os === cc.sys.OS_OSX || cc.sys.os === cc.sys.OS_WINDOWS) { + this.enabled = false; } }, @@ -145,16 +143,16 @@ var WebView = cc.Class({ }, _onWebViewLoaded: function () { - cc.Component.EventHandler.emitEvents(this.webViewLoadedEvent, this, EventType.LOADED); + cc.Component.EventHandler.emitEvents(this.webViewLoadedEvents, this, EventType.LOADED); }, _onWebViewLoading: function () { - cc.Component.EventHandler.emitEvents(this.webViewLoadingEvent, this, EventType.LOADING); + cc.Component.EventHandler.emitEvents(this.webViewLoadingEvents, this, EventType.LOADING); return true; }, _onWebViewLoadError: function () { - cc.Component.EventHandler.emitEvents(this.webViewErrorEvent, this, EventType.ERROR); + cc.Component.EventHandler.emitEvents(this.webViewErrorEvents, this, EventType.ERROR); } }); From ba64d5ac7ad68c6990f17e2fe5b07912338dd115 Mon Sep 17 00:00:00 2001 From: 2youyouo2 <501251991@qq.com> Date: Tue, 26 Jul 2016 11:42:20 +0800 Subject: [PATCH 033/268] add math polypill --- polyfill/math.js | 8 ++++++++ predefine.js | 1 + 2 files changed, 9 insertions(+) create mode 100644 polyfill/math.js diff --git a/polyfill/math.js b/polyfill/math.js new file mode 100644 index 0000000000..0cee3c9abc --- /dev/null +++ b/polyfill/math.js @@ -0,0 +1,8 @@ + +Math.sign = Math.sign || function(x) { + x = +x; // convert to a number + if (x === 0 || isNaN(x)) { + return x; + } + return x > 0 ? 1 : -1; +}; diff --git a/predefine.js b/predefine.js index fbe631c426..e9e38a00ee 100644 --- a/predefine.js +++ b/predefine.js @@ -51,6 +51,7 @@ cc._initDebugSetting(cc.DebugMode.INFO); // polyfills /* require('./polyfill/bind'); */ require('./polyfill/string'); +require('./polyfill/math'); // predefine some modules for cocos require('./cocos2d/core/platform/js'); From 7bd018aa94ff9bdd0d72fa31f8c10f6cbd5efb9d Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 26 Jul 2016 11:51:31 +0800 Subject: [PATCH 034/268] clear .cache --- gulpfile.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/gulpfile.js b/gulpfile.js index b3be965f30..2309cec13d 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -49,7 +49,9 @@ gulp.task('build-cut-modular', function (done) { Modular.buildModular('modular-cocos2d-cut.js', './bin', [], done); }); -gulp.task('build-modular-cocos2d', ['build-all-modular', 'build-cut-modular']); +gulp.task('build-modular-cocos2d', ['build-all-modular', 'build-cut-modular'], function (done) { + Del(['./bin/.cache'], done); +}); ///////////// From 69b6032686d02f53372b797ac53c5b34f9a13ef4 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 22 Jul 2016 16:51:53 +0800 Subject: [PATCH 035/268] Improve Scale9Sprite calculation performance --- cocos2d/core/sprites/CCScale9Sprite.js | 140 +++++++++--------- .../sprites/CCScale9SpriteWebGLRenderCmd.js | 50 +++---- 2 files changed, 99 insertions(+), 91 deletions(-) diff --git a/cocos2d/core/sprites/CCScale9Sprite.js b/cocos2d/core/sprites/CCScale9Sprite.js index 4a8980decf..f0adf4dffe 100644 --- a/cocos2d/core/sprites/CCScale9Sprite.js +++ b/cocos2d/core/sprites/CCScale9Sprite.js @@ -84,13 +84,6 @@ var FIX_ARTIFACTS_BY_STRECHING_TEXEL = cc.macro.FIX_ARTIFACTS_BY_STRECHING_TEXEL var simpleQuadGenerator = { _rebuildQuads_base: function (sprite, spriteFrame, contentSize, isTrimmedContentSize) { //build vertices - this._calculateVertices(sprite, spriteFrame, contentSize, isTrimmedContentSize); - //build uvs - this._calculateUVs(sprite, spriteFrame); - sprite._vertCount = 4; - }, - - _calculateVertices: function (sprite, spriteFrame, contentSize, isTrimmedContentSize) { var vertices = sprite._vertices, wt = sprite._renderCmd._worldTransform, l, b, r, t; @@ -100,9 +93,9 @@ var simpleQuadGenerator = { r = contentSize.width; t = contentSize.height; } else { - var originalSize = spriteFrame.getOriginalSize(); + var originalSize = spriteFrame._originalSize; var rect = spriteFrame._rect; - var offset = spriteFrame.getOffset(); + 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; @@ -147,12 +140,19 @@ var simpleQuadGenerator = { 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.getPixelWidth(); - var atlasHeight = spriteFrame._texture.getPixelHeight(); + var atlasWidth = spriteFrame._texture._pixelsWide; + var atlasHeight = spriteFrame._texture._pixelsHigh; var textureRect = spriteFrame._rect; if (uvs.length < 8) { @@ -189,24 +189,19 @@ var simpleQuadGenerator = { }; var scale9QuadGenerator = { + x: new Array(4), + y: new Array(4), _rebuildQuads_base: function (sprite, spriteFrame, contentSize, insetLeft, insetRight, insetTop, insetBottom) { //build vertices - this._calculateVertices(sprite, spriteFrame, contentSize, insetLeft, insetRight, insetTop, insetBottom); - //build uvs - this._calculateUVs(sprite, spriteFrame, insetLeft, insetRight, insetTop, insetBottom); - }, - - _calculateVertices: function (sprite, spriteFrame, contentSize, insetLeft, insetRight, insetTop, insetBottom) { var vertices = sprite._vertices; var wt = sprite._renderCmd._worldTransform; var leftWidth, centerWidth, rightWidth; var topHeight, centerHeight, bottomHeight; - var rect = spriteFrame._rect; + leftWidth = insetLeft; rightWidth = insetRight; centerWidth = rect.width - leftWidth - rightWidth; - topHeight = insetTop; bottomHeight = insetBottom; centerHeight = rect.height - topHeight - bottomHeight; @@ -220,8 +215,8 @@ var scale9QuadGenerator = { yScale = yScale > 1 ? 1 : yScale; sizableWidth = sizableWidth < 0 ? 0 : sizableWidth; sizableHeight = sizableHeight < 0 ? 0 : sizableHeight; - var x = new Array(4); - var y = new Array(4); + var x = this.x; + var y = this.y; x[0] = 0; x[1] = leftWidth * xScale; x[2] = x[1] + sizableWidth; @@ -260,25 +255,30 @@ var scale9QuadGenerator = { cornerId[1] = 6; cornerId[2] = 24; cornerId[3] = 30; + + //build uvs + if (this._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.getPixelWidth(); - var atlasHeight = spriteFrame._texture.getPixelHeight(); + 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; - var textureRect = spriteFrame._rect; if (uvs.length < 32) { dataPool.put(uvs); @@ -287,10 +287,10 @@ var scale9QuadGenerator = { } //uv computation should take spritesheet into account. - var u = new Array(4); - var v = new Array(4); - var offset = 0, row, col; + 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; @@ -339,8 +339,8 @@ var tiledQuadGenerator = { wt = sprite._renderCmd._worldTransform, uvs = sprite._uvs; //build uvs - var atlasWidth = spriteFrame._texture.getPixelWidth(); - var atlasHeight = spriteFrame._texture.getPixelHeight(); + var atlasWidth = spriteFrame._texture._pixelsWide; + var atlasHeight = spriteFrame._texture._pixelsHigh; var textureRect = spriteFrame._rect; //uv computation should take spritesheet into account. @@ -454,8 +454,8 @@ var fillQuadGeneratorBar = { var l = 0, b = 0, r = contentSize.width, t = contentSize.height; //build uvs - var atlasWidth = spriteFrame._texture.getPixelWidth(); - var atlasHeight = spriteFrame._texture.getPixelHeight(); + var atlasWidth = spriteFrame._texture._pixelsWide; + var atlasHeight = spriteFrame._texture._pixelsHigh; var textureRect = spriteFrame._rect; //uv computation should take spritesheet into account. var ul, vb, ur, vt; @@ -532,7 +532,7 @@ var fillQuadGeneratorBar = { // tr : 6, 7 var progressStart, progressEnd; switch (fillType) { - case cc.Scale9Sprite.FillType.HORIZONTAL: + case FillType.HORIZONTAL: progressStart = vertices[0] + (vertices[2] - vertices[0]) * fillStart; progressEnd = vertices[0] + (vertices[2] - vertices[0]) * fillEnd; @@ -550,7 +550,7 @@ var fillQuadGeneratorBar = { uvs[6] = quadUV[4] + (quadUV[6] - quadUV[4]) * fillEnd; uvs[7] = quadUV[7]; break; - case cc.Scale9Sprite.FillType.VERTICAL: + case FillType.VERTICAL: progressStart = vertices[1] + (vertices[5] - vertices[1]) * fillStart; progressEnd = vertices[1] + (vertices[5] - vertices[1]) * fillEnd; @@ -894,8 +894,8 @@ var fillQuadGeneratorRadial = { }, _calculateUVs : function (spriteFrame) { - var atlasWidth = spriteFrame._texture.getPixelWidth(); - var atlasHeight = spriteFrame._texture.getPixelHeight(); + var atlasWidth = spriteFrame._texture._pixelsWide; + var atlasHeight = spriteFrame._texture._pixelsHigh; var textureRect = spriteFrame._rect; //uv computation should take spritesheet into account. @@ -946,6 +946,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ _uvs: null, _vertCount: 0, _quadsDirty: true, + _uvsDirty: true, _isTriangle: false, _isTrimmedContentSize: true, //fill type @@ -1045,6 +1046,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ if (spriteFrame) { this._spriteFrame = spriteFrame; this._quadsDirty = true; + this._uvsDirty = true; this._renderCmd._needDraw = false; var self = this; var onResourceDataLoaded = function () { @@ -1141,6 +1143,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ if (this._renderingType === type) return; this._renderingType = type; this._quadsDirty = true; + this._uvsDirty = true; this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); }, /** @@ -1157,6 +1160,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ setInsetLeft: function (insetLeft) { this._insetLeft = insetLeft; this._quadsDirty = true; + this._uvsDirty = true; this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); }, /** @@ -1173,6 +1177,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ setInsetTop: function (insetTop) { this._insetTop = insetTop; this._quadsDirty = true; + this._uvsDirty = true; this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); }, @@ -1191,6 +1196,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ setInsetRight: function (insetRight) { this._insetRight = insetRight; this._quadsDirty = true; + this._uvsDirty = true; this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); }, @@ -1209,6 +1215,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ setInsetBottom: function (insetBottom) { this._insetBottom = insetBottom; this._quadsDirty = true; + this._uvsDirty = true; this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); }, /** @@ -1223,7 +1230,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ if(this._fillType === value) return; this._fillType = value; - if(this._renderingType === cc.Scale9Sprite.RenderingType.FILLED) { + if(this._renderingType === RenderingType.FILLED) { this._quadsDirty = true; this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); } @@ -1235,7 +1242,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ setFillCenter: function(value, y) { this._fillCenter = cc.v2(value,y); - if(this._renderingType === cc.Scale9Sprite.RenderingType.FILLED && this._fillType === cc.Scale9Sprite.FillType.RADIAL) { + if(this._renderingType === RenderingType.FILLED && this._fillType === FillType.RADIAL) { this._quadsDirty = true; this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); } @@ -1269,7 +1276,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ if(this._fillStart === value) return; this._fillStart = value; - if(this._renderingType === cc.Scale9Sprite.RenderingType.FILLED) { + if(this._renderingType === RenderingType.FILLED) { this._quadsDirty = true; this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); } @@ -1283,7 +1290,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ if(this._fillRange === value) return; this._fillRange = value; - if(this._renderingType === cc.Scale9Sprite.RenderingType.FILLED ) { + if(this._renderingType === RenderingType.FILLED ) { this._quadsDirty = true; this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); } @@ -1299,24 +1306,24 @@ cc.Scale9Sprite = _ccsg.Node.extend({ return; } this._isTriangle = false; - var vert; - if (this._renderingType === cc.Scale9Sprite.RenderingType.SIMPLE) { - simpleQuadGenerator._rebuildQuads_base(this, this._spriteFrame, this.getContentSize(), this._isTrimmedContentSize); - vert = this._vertices; - } else if (this._renderingType === cc.Scale9Sprite.RenderingType.SLICED) { - scale9QuadGenerator._rebuildQuads_base(this, this._spriteFrame, this.getContentSize(), this._insetLeft, this._insetRight, this._insetTop, this._insetBottom); - vert = this._vertices; - } else if (this._renderingType === cc.Scale9Sprite.RenderingType.TILED) { - tiledQuadGenerator._rebuildQuads_base(this, this._spriteFrame, this.getContentSize()); - vert = this._vertices; - } else if (this._renderingType === cc.Scale9Sprite.RenderingType.FILLED) { + 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; + case RenderingType.TILED: + tiledQuadGenerator._rebuildQuads_base(this, this._spriteFrame, this._contentSize); + break; + case RenderingType.FILLED: var fillstart = this._fillStart; var fillRange = this._fillRange; if(fillRange < 0) { fillstart += fillRange; fillRange = -fillRange; } - if (this._fillType !== cc.Scale9Sprite.FillType.RADIAL) { + if (this._fillType !== FillType.RADIAL) { fillRange = fillstart + fillRange; fillstart = fillstart > 1.0 ? 1.0 : fillstart; fillstart = fillstart < 0.0 ? 0.0 : fillstart; @@ -1324,20 +1331,19 @@ cc.Scale9Sprite = _ccsg.Node.extend({ fillRange = fillRange > 1.0 ? 1.0 : fillRange; fillRange = fillRange < 0.0 ? 0.0 : fillRange; fillRange = fillRange - fillstart; - fillQuadGeneratorBar._rebuildQuads_base(this, this._spriteFrame, this.getContentSize(), this._fillType, fillstart, fillRange); - vert = this._vertices; + fillQuadGeneratorBar._rebuildQuads_base(this, this._spriteFrame, this._contentSize, this._fillType, fillstart, fillRange); } else { this._isTriangle = true; if (!this._rawVerts) { this._rawVerts = dataPool.get(8) || new Float32Array(8); this._rawUvs = dataPool.get(8) || new Float32Array(8); } - fillQuadGeneratorRadial._rebuildQuads_base(this, this._spriteFrame, this.getContentSize(), this._fillCenter,fillstart, fillRange); - vert = this._rawVerts; + fillQuadGeneratorRadial._rebuildQuads_base(this, this._spriteFrame, this._contentSize, this._fillCenter,fillstart, fillRange); } - } else { - this._quads = []; + break; + default: this._quadsDirty = false; + this._uvsDirty = false; this._renderCmd._needDraw = false; cc.error('Can not generate quad'); return; @@ -1345,12 +1351,13 @@ cc.Scale9Sprite = _ccsg.Node.extend({ // Culling if (webgl) { - var x0 = cornerId[0], x1 = cornerId[1], x2 = cornerId[2], x3 = cornerId[3], - y0 = cornerId[0]+1, y1 = cornerId[1]+1, y2 = cornerId[2]+1, y3 = cornerId[3]+1; - if (((vert[x0]-vl.x) & (vert[x1]-vl.x) & (vert[x2]-vl.x) & (vert[x3]-vl.x)) >> 31 || // All outside left - ((vr.x-vert[x0]) & (vr.x-vert[x1]) & (vr.x-vert[x2]) & (vr.x-vert[x3])) >> 31 || // All outside right - ((vert[y0]-vb.y) & (vert[y1]-vb.y) & (vert[y2]-vb.y) & (vert[y3]-vb.y)) >> 31 || // All outside bottom - ((vt.y-vert[y0]) & (vt.y-vert[y1]) & (vt.y-vert[y2]) & (vt.y-vert[y3])) >> 31) // All outside top + var vert = this._isTriangle ? this._rawVerts : this._vertices, + x0 = vert[cornerId[0]], x1 = vert[cornerId[1]], x2 = vert[cornerId[2]], x3 = vert[cornerId[3]], + y0 = vert[cornerId[0]+1], y1 = vert[cornerId[1]+1], y2 = vert[cornerId[2]+1], y3 = vert[cornerId[3]+1]; + if (((x0-vl.x) & (x1-vl.x) & (x2-vl.x) & (x3-vl.x)) >> 31 || // All outside left + ((vr.x-x0) & (vr.x-x1) & (vr.x-x2) & (vr.x-x3)) >> 31 || // All outside right + ((y0-vb.y) & (y1-vb.y) & (y2-vb.y) & (y3-vb.y)) >> 31 || // All outside bottom + ((vt.y-y0) & (vt.y-y1) & (vt.y-y2) & (vt.y-y3)) >> 31) // All outside top { this._renderCmd._needDraw = false; } @@ -1370,6 +1377,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ } this._quadsDirty = false; + this._uvsDirty = false; }, _createRenderCmd: function () { if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) @@ -1394,7 +1402,7 @@ cc.Scale9Sprite.state = {NORMAL: 0, GRAY: 1, DISTORTION: 2}; * Enum for sprite type * @enum SpriteType */ -cc.Scale9Sprite.RenderingType = cc.Enum({ +var RenderingType = cc.Scale9Sprite.RenderingType = cc.Enum({ /** * @property {Number} SIMPLE */ @@ -1413,7 +1421,7 @@ cc.Scale9Sprite.RenderingType = cc.Enum({ FILLED: 3 }); -cc.Scale9Sprite.FillType = cc.Enum({ +var FillType = cc.Scale9Sprite.FillType = cc.Enum({ HORIZONTAL: 0, VERTICAL: 1, RADIAL:2, diff --git a/cocos2d/core/sprites/CCScale9SpriteWebGLRenderCmd.js b/cocos2d/core/sprites/CCScale9SpriteWebGLRenderCmd.js index d34298c50c..9346fab5f8 100644 --- a/cocos2d/core/sprites/CCScale9SpriteWebGLRenderCmd.js +++ b/cocos2d/core/sprites/CCScale9SpriteWebGLRenderCmd.js @@ -39,8 +39,9 @@ cc.Scale9Sprite.WebGLRenderCmd = function (renderable) { this._shaderProgram = cc.shaderCache.programForKey(cc.macro.SHADER_SPRITE_POSITION_TEXTURECOLOR); }; -var proto = cc.Scale9Sprite.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype); -proto.constructor = cc.Scale9Sprite.WebGLRenderCmd; +var Scale9Sprite = cc.Scale9Sprite; +var proto = Scale9Sprite.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype); +proto.constructor = Scale9Sprite.WebGLRenderCmd; proto._uploadSliced = function (vertices, uvs, color, z, f32buffer, ui32buffer, offset) { var off; @@ -106,7 +107,7 @@ proto.transform = function (parentCmd, recursive) { proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset){ var node = this._node; - if (!node._spriteFrame || !node._spriteFrame.textureLoaded() || this._displayedOpacity === 0) { + if (this._displayedOpacity === 0) { return 0; } @@ -115,15 +116,14 @@ proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset){ node._rebuildQuads(); } - // this._shaderProgram.use(); - if (this._shaderProgram === cc.Scale9Sprite.WebGLRenderCmd._distortionProgram && this._node._distortionOffset) { + if (node._distortionOffset && this._shaderProgram === Scale9Sprite.WebGLRenderCmd._distortionProgram) { this._shaderProgram.setUniformLocationWith2f( - cc.Scale9Sprite.WebGLRenderCmd._distortionOffset, - this._node._distortionOffset.x, this._node._distortionOffset.y + Scale9Sprite.WebGLRenderCmd._distortionOffset, + node._distortionOffset.x, node._distortionOffset.y ); this._shaderProgram.setUniformLocationWith2f( - cc.Scale9Sprite.WebGLRenderCmd._distortionTiling, - this._node._distortionTiling.x, this._node._distortionTiling.y + Scale9Sprite.WebGLRenderCmd._distortionTiling, + node._distortionTiling.x, node._distortionTiling.y ); } @@ -144,7 +144,7 @@ proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset){ // Upload data var vertices = node._vertices; var uvs = node._uvs; - var types = cc.Scale9Sprite.RenderingType; + var types = Scale9Sprite.RenderingType; var offset = vertexDataOffset; var len = 0; switch (node._renderingType) { @@ -157,7 +157,7 @@ proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset){ len = this._uploadSliced(vertices, uvs, this._color, z, f32buffer, ui32buffer, offset); break; } - if (node._renderingType === types.FILLED && node._fillType === cc.Scale9Sprite.FillType.RADIAL) { + if (node._renderingType === types.FILLED && node._fillType === Scale9Sprite.FillType.RADIAL) { this.vertexType = cc.renderer.VertexType.TRIANGLE; } else { @@ -167,18 +167,18 @@ proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset){ }; proto.setState = function (state) { - if (state === cc.Scale9Sprite.state.NORMAL) { + if (state === Scale9Sprite.state.NORMAL) { this._shaderProgram = cc.shaderCache.programForKey(cc.macro.SHADER_SPRITE_POSITION_TEXTURECOLOR); - } else if (state === cc.Scale9Sprite.state.GRAY) { + } else if (state === Scale9Sprite.state.GRAY) { this._shaderProgram = cc.Scale9Sprite.WebGLRenderCmd._getGrayShaderProgram(); - } else if (state === cc.Scale9Sprite.state.DISTORTION) { + } else if (state === Scale9Sprite.state.DISTORTION) { this._shaderProgram = cc.Scale9Sprite.WebGLRenderCmd._getDistortionProgram(); } }; -cc.Scale9Sprite.WebGLRenderCmd._grayShaderProgram = null; -cc.Scale9Sprite.WebGLRenderCmd._getGrayShaderProgram = function(){ - var grayShader = cc.Scale9Sprite.WebGLRenderCmd._grayShaderProgram; +Scale9Sprite.WebGLRenderCmd._grayShaderProgram = null; +Scale9Sprite.WebGLRenderCmd._getGrayShaderProgram = function(){ + var grayShader = Scale9Sprite.WebGLRenderCmd._grayShaderProgram; if (grayShader) return grayShader; @@ -190,11 +190,11 @@ cc.Scale9Sprite.WebGLRenderCmd._getGrayShaderProgram = function(){ grayShader.link(); grayShader.updateUniforms(); - cc.Scale9Sprite.WebGLRenderCmd._grayShaderProgram = grayShader; + Scale9Sprite.WebGLRenderCmd._grayShaderProgram = grayShader; return grayShader; }; -cc.Scale9Sprite.WebGLRenderCmd._grayShaderFragment = +Scale9Sprite.WebGLRenderCmd._grayShaderFragment = "precision lowp float;\n" + "varying vec4 v_fragmentColor; \n" + "varying vec2 v_texCoord; \n" @@ -205,9 +205,9 @@ cc.Scale9Sprite.WebGLRenderCmd._grayShaderFragment = +" gl_FragColor.w = c.w ; \n" + "}"; -cc.Scale9Sprite.WebGLRenderCmd._distortionProgram = null; -cc.Scale9Sprite.WebGLRenderCmd._getDistortionProgram = function(){ - var shader = cc.Scale9Sprite.WebGLRenderCmd._distortionProgram; +Scale9Sprite.WebGLRenderCmd._distortionProgram = null; +Scale9Sprite.WebGLRenderCmd._getDistortionProgram = function(){ + var shader = Scale9Sprite.WebGLRenderCmd._distortionProgram; if(shader) return shader; @@ -219,9 +219,9 @@ cc.Scale9Sprite.WebGLRenderCmd._getDistortionProgram = function(){ shader.link(); shader.updateUniforms(); - cc.Scale9Sprite.WebGLRenderCmd._distortionProgram = shader; - cc.Scale9Sprite.WebGLRenderCmd._distortionOffset = shader.getUniformLocationForName('u_offset'); - cc.Scale9Sprite.WebGLRenderCmd._distortionTiling = shader.getUniformLocationForName('u_offset_tiling'); + Scale9Sprite.WebGLRenderCmd._distortionProgram = shader; + Scale9Sprite.WebGLRenderCmd._distortionOffset = shader.getUniformLocationForName('u_offset'); + Scale9Sprite.WebGLRenderCmd._distortionTiling = shader.getUniformLocationForName('u_offset_tiling'); return shader; }; From 786aae553ed289727d1150662bd68385bbccbfba Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 22 Jul 2016 16:52:42 +0800 Subject: [PATCH 036/268] Slightly improve instantiateProps --- cocos2d/core/platform/CCClass.js | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index b5fb1343e5..0b59b81fde 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -291,24 +291,22 @@ function instantiateProps (instance, itsClass) { for (var i = 0; i < propList.length; i++) { var prop = propList[i]; var attrKey = prop + DELIMETER + 'default'; - if (attrKey in attrs) { // getter does not have default - var def = attrs[attrKey]; + var def = attrs[attrKey]; + if (def !== undefined) { // getter does not have default // default maybe 0 - if (def) { - if (typeof def === 'object' && def) { - if (typeof def.clone === 'function') { - def = def.clone(); - } - else if (Array.isArray(def)) { - def = []; - } - else { - def = {}; - } + if (typeof def === 'object' && def) { + if (typeof def.clone === 'function') { + def = def.clone(); } - else if (typeof def === 'function') { - def = getDefault(def); + else if (Array.isArray(def)) { + def = []; } + else { + def = {}; + } + } + else if (typeof def === 'function') { + def = getDefault(def); } instance[prop] = def; } From 9c2aff5e5950b89de86a1d4130b07b9986ed91a4 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 25 Jul 2016 19:28:59 +0800 Subject: [PATCH 037/268] Fix scale 9 sprite unit test --- cocos2d/core/sprites/CCScale9Sprite.js | 6 +- test/qunit/unit/test-spriteRenderer.js | 126 ++++++++++++------------- 2 files changed, 66 insertions(+), 66 deletions(-) diff --git a/cocos2d/core/sprites/CCScale9Sprite.js b/cocos2d/core/sprites/CCScale9Sprite.js index f0adf4dffe..99f23ecfd6 100644 --- a/cocos2d/core/sprites/CCScale9Sprite.js +++ b/cocos2d/core/sprites/CCScale9Sprite.js @@ -257,7 +257,7 @@ var scale9QuadGenerator = { cornerId[3] = 30; //build uvs - if (this._uvsDirty) { + if (sprite._uvsDirty) { this._calculateUVs(sprite, spriteFrame, insetLeft, insetRight, insetTop, insetBottom); } }, @@ -681,12 +681,12 @@ var fillQuadGeneratorRadial = { if (vertices.length < dataLength) { dataPool.put(vertices); vertices = dataPool.get(dataLength) || new Float32Array(dataLength); - sprite._vertices = vertices; + this.outVerts = sprite._vertices = vertices; } if (uvs.length < dataLength) { dataPool.put(uvs); uvs = dataPool.get(dataLength) || new Float32Array(dataLength); - sprite._uvs = uvs; + this.outUvs = sprite._uvs = uvs; } var offset = 0, count = 0; diff --git a/test/qunit/unit/test-spriteRenderer.js b/test/qunit/unit/test-spriteRenderer.js index 69fc2035b0..7a3bd1596f 100644 --- a/test/qunit/unit/test-spriteRenderer.js +++ b/test/qunit/unit/test-spriteRenderer.js @@ -46,18 +46,18 @@ test('simple spriteQuad trimmed', function () { s9Sprite._rebuildQuads(); var vertices = s9Sprite._vertices; var uvs = s9Sprite._uvs; - strictEqual(vertices.length >= 8 && uvs >= 8, true, 'vertices have at least 8 floats'); + strictEqual(vertices.length >= 8 && uvs.length >= 8, true, 'vertices have at least 8 floats'); strictEqual(vertices[0], 0, 'vertex-bl-x test success'); strictEqual(vertices[1], 0, 'vertex-bl-y test success'); strictEqual(vertices[6], contentSize.width, 'vertex-tr-x test success'); strictEqual(vertices[7], contentSize.height, 'vertex-tr-y test success'); - deepClose(uvs[0], 10 / 100, 0.0001, 'texCoords-bl-x test success'); - deepClose(uvs[1], 70 / 100, 0.0001, 'texCoords-bl-y test success'); + deepClose(uvs[0], 10 / 100, 0.01, 'texCoords-bl-x test success'); + deepClose(uvs[1], 70 / 100, 0.01, 'texCoords-bl-y test success'); - deepClose(uvs[6], 50 / 100, 0.0001, 'texCoords-tr-x test success'); - deepClose(uvs[7], 10 / 100, 0.0001, 'texCoords-tr-y test success'); + deepClose(uvs[6], 50 / 100, 0.01, 'texCoords-tr-x test success'); + deepClose(uvs[7], 10 / 100, 0.01, 'texCoords-tr-y test success'); }; if (spriteFrame.textureLoaded()) { testCallBack(); @@ -79,18 +79,18 @@ test('simple spriteQuad no trimmed', function () { s9Sprite._rebuildQuads(); var vertices = s9Sprite._vertices; var uvs = s9Sprite._uvs; - strictEqual(vertices.length >= 8 && uvs >= 8, true, 'vertices have at least 8 floats'); + strictEqual(vertices.length >= 8 && uvs.length >= 8, true, 'vertices have at least 8 floats'); strictEqual(vertices[0], 10, 'vertex-bl-x test success'); strictEqual(vertices[1], 30, 'vertex-bl-y test success'); strictEqual(vertices[6], 50, 'vertex-tr-x test success'); strictEqual(vertices[7], 90, 'vertex-tr-y test success'); - deepClose(uvs[0], 10 / 100, 0.0001, 'texCoords-bl-x test success'); - deepClose(uvs[1], 70 / 100, 0.0001, 'texCoords-bl-y test success'); + deepClose(uvs[0], 10 / 100, 0.01, 'texCoords-bl-x test success'); + deepClose(uvs[1], 70 / 100, 0.01, 'texCoords-bl-y test success'); - deepClose(uvs[6], 50 / 100, 0.0001, 'texCoords-tr-x test success'); - deepClose(uvs[7], 10 / 100, 0.0001, 'texCoords-tr-y test success'); + deepClose(uvs[6], 50 / 100, 0.01, 'texCoords-tr-x test success'); + deepClose(uvs[7], 10 / 100, 0.01, 'texCoords-tr-y test success'); }; if (spriteFrame.textureLoaded()) { testCallBack(); @@ -118,7 +118,7 @@ test('scale9 spriteQuad trimmed', function () { s9Sprite._rebuildQuads(); var vertices = s9Sprite._vertices; var uvs = s9Sprite._uvs; - strictEqual(vertices.length >= 32 && uvs >= 32, true, 'vertices have at least 32 floats'); + strictEqual(vertices.length >= 32 && uvs.length >= 32, true, 'vertices have at least 32 floats'); strictEqual(vertices[0], 0, 'x0 test success'); strictEqual(vertices[1], 0, 'y0 test success'); strictEqual(vertices[10], 5, 'x1 test success'); @@ -128,14 +128,14 @@ test('scale9 spriteQuad trimmed', function () { strictEqual(vertices[30], 100, 'x3 test success'); strictEqual(vertices[31], 100, 'y3 test success'); - deepClose(uvs[0], 10 / 100, 0.0001, 'u0 test success'); - deepClose(uvs[1], 70 / 100, 0.0001, 'v0 test success'); - deepClose(uvs[10], 15 / 100, 0.0001, 'u1 test success'); - deepClose(uvs[11], 63 / 100, 0.0001, 'v1 test success'); - deepClose(uvs[20], 44 / 100, 0.0001, 'u2 test success'); - deepClose(uvs[21], 18 / 100, 0.0001, 'v2 test success'); - deepClose(uvs[30], 50 / 100, 0.0001, 'u3 test success'); - deepClose(uvs[31], 10 / 100, 0.0001, 'v3 test success'); + deepClose(uvs[0], 10 / 100, 0.01, 'u0 test success'); + deepClose(uvs[1], 70 / 100, 0.01, 'v0 test success'); + deepClose(uvs[10], 15 / 100, 0.01, 'u1 test success'); + deepClose(uvs[11], 63 / 100, 0.01, 'v1 test success'); + deepClose(uvs[20], 44 / 100, 0.01, 'u2 test success'); + deepClose(uvs[21], 18 / 100, 0.01, 'v2 test success'); + deepClose(uvs[30], 50 / 100, 0.01, 'u3 test success'); + deepClose(uvs[31], 10 / 100, 0.01, 'v3 test success'); }; if (spriteFrame.textureLoaded()) { testCallBack(); @@ -159,22 +159,22 @@ test('tiled spriteQuad trimmed', function () { var uvs = s9Sprite._uvs; strictEqual(vertices.length >= 48, true, 'vertices have at least 48 floats'); strictEqual(vertices[0], 0, 'x0 test success'); - strictEqual(vertices[16], 40, 'x1 test success'); - strictEqual(vertices[32], 80, 'x2 test success'); - strictEqual(vertices[38], 100, 'x3 test success'); + strictEqual(vertices[8], 40, 'x1 test success'); + strictEqual(vertices[16], 80, 'x2 test success'); + strictEqual(vertices[18], 100, 'x3 test success'); strictEqual(vertices[1], 0, 'y0 test success'); strictEqual(vertices[41], 60, 'y1 test success'); strictEqual(vertices[47], 100, 'y2 test success'); // - deepClose(uvs[16], 10 / 100, 0.0001, 'full quad u0 test success'); - deepClose(uvs[17], 70 / 100, 0.0001, 'full quad v0 test success'); - deepClose(uvs[22], 50 / 100, 0.0001, 'full quad u1 test success'); - deepClose(uvs[23], 10 / 100, 0.0001, 'full quad v1 test success'); - deepClose(uvs[40], 10 / 100, 0.0001, 'part quad u0 test success'); - deepClose(uvs[41], 70 / 100, 0.0001, 'part quad v0 test success'); - deepClose(uvs[46], 30 / 100, 0.0001, 'part quad u1 test success'); - deepClose(uvs[47], 30 / 100, 0.0001, 'part quad v1 test success'); + deepClose(uvs[8], 10 / 100, 0.01, 'full quad u0 test success'); + deepClose(uvs[9], 70 / 100, 0.01, 'full quad v0 test success'); + deepClose(uvs[14], 50 / 100, 0.01, 'full quad u1 test success'); + deepClose(uvs[15], 10 / 100, 0.01, 'full quad v1 test success'); + deepClose(uvs[40], 10 / 100, 0.01, 'part quad u0 test success'); + deepClose(uvs[41], 70 / 100, 0.01, 'part quad v0 test success'); + deepClose(uvs[46], 30 / 100, 0.01, 'part quad u1 test success'); + deepClose(uvs[47], 30 / 100, 0.01, 'part quad v1 test success'); }; if (spriteFrame.textureLoaded()) { testCallBack(); @@ -200,32 +200,32 @@ test('filled-bar-horizontal spriteQuad trimmed', function () { s9Sprite._rebuildQuads(); var vertices = s9Sprite._vertices; var uvs = s9Sprite._uvs; - strictEqual(vertices.length >= 8 && uvs >= 8, true, 'vertices have at least 8 floats'); + strictEqual(vertices.length >= 8 && uvs.length >= 8, true, 'vertices have at least 8 floats'); strictEqual(vertices[0], 10, 'vertex-bl-x test success'); strictEqual(vertices[1], 0, 'vertex-bl-y test success'); strictEqual(vertices[6], 40, 'vertex-tr-x test success'); strictEqual(vertices[7], 100, 'vertex-tr-y test success'); - deepClose(uvs[0], 14 / 100, 0.0001, 'texCoords-bl-x test success'); - deepClose(uvs[1], 70 / 100, 0.0001, 'texCoords-bl-y test success'); - deepClose(uvs[6], 26 / 100, 0.0001, 'texCoords-tr-x test success'); - deepClose(uvs[7], 10 / 100, 0.0001, 'texCoords-tr-y test success'); + deepClose(uvs[0], 14 / 100, 0.01, 'texCoords-bl-x test success'); + deepClose(uvs[1], 70 / 100, 0.01, 'texCoords-bl-y test success'); + deepClose(uvs[6], 26 / 100, 0.01, 'texCoords-tr-x test success'); + deepClose(uvs[7], 10 / 100, 0.01, 'texCoords-tr-y test success'); s9Sprite.setFillStart(0.3); s9Sprite.setFillRange(-0.4); s9Sprite._rebuildQuads(); vertices = s9Sprite._vertices; uvs = s9Sprite._uvs; - strictEqual(vertices.length >= 8 && uvs >= 8, true, 'vertices have at least 8 floats'); - strictEqual(vertices[0]._bl.vertices.x, 0, 'vertex-bl-x test success'); - strictEqual(vertices[1]._bl.vertices.y, 0, 'vertex-bl-y test success'); - strictEqual(vertices[6]._tr.vertices.x, 30, 'vertex-tr-x test success'); - strictEqual(vertices[7]._tr.vertices.y, 100, 'vertex-tr-y test success'); + strictEqual(vertices.length >= 8 && uvs.length >= 8, true, 'vertices have at least 8 floats'); + strictEqual(vertices[0], 0, 'vertex-bl-x test success'); + strictEqual(vertices[1], 0, 'vertex-bl-y test success'); + strictEqual(vertices[6], 30, 'vertex-tr-x test success'); + strictEqual(vertices[7], 100, 'vertex-tr-y test success'); - deepClose(uvs[0]._bl.texCoords.u, 10 / 100, 0.0001, 'texCoords-bl-x test success'); - deepClose(uvs[1]._bl.texCoords.v, 70 / 100, 0.0001, 'texCoords-bl-y test success'); - deepClose(uvs[6]._tr.texCoords.u, 22 / 100, 0.0001, 'texCoords-tr-x test success'); - deepClose(uvs[7]._tr.texCoords.v, 10 / 100, 0.0001, 'texCoords-tr-y test success'); + deepClose(uvs[0], 10 / 100, 0.01, 'texCoords-bl-x test success'); + deepClose(uvs[1], 70 / 100, 0.01, 'texCoords-bl-y test success'); + deepClose(uvs[6], 22 / 100, 0.01, 'texCoords-tr-x test success'); + deepClose(uvs[7], 10 / 100, 0.01, 'texCoords-tr-y test success'); }; if (spriteFrame.textureLoaded()) { testCallBack(); @@ -250,32 +250,32 @@ test('filled-bar-vertical spriteQuad trimmed', function () { s9Sprite._rebuildQuads(); var vertices = s9Sprite._vertices; var uvs = s9Sprite._uvs; - strictEqual(vertices.length >= 8 && uvs >= 8, true, 'vertices have at least 8 floats'); + strictEqual(vertices.length >= 8 && uvs.length >= 8, true, 'vertices have at least 8 floats'); strictEqual(vertices[0], 0, 'vertex-bl-x test success'); strictEqual(vertices[1], 10, 'vertex-bl-y test success'); strictEqual(vertices[6], 100, 'vertex-tr-x test success'); strictEqual(vertices[7], 40, 'vertex-tr-y test success'); - deepClose(uvs[0], 10 / 100, 0.0001, 'texCoords-bl-x test success'); - deepClose(uvs[1], 64 / 100, 0.0001, 'texCoords-bl-y test success'); - deepClose(uvs[6], 50 / 100, 0.0001, 'texCoords-tr-x test success'); - deepClose(uvs[7], 46 / 100, 0.0001, 'texCoords-tr-y test success'); + deepClose(uvs[0], 10 / 100, 0.01, 'texCoords-bl-x test success'); + deepClose(uvs[1], 64 / 100, 0.01, 'texCoords-bl-y test success'); + deepClose(uvs[6], 50 / 100, 0.01, 'texCoords-tr-x test success'); + deepClose(uvs[7], 46 / 100, 0.01, 'texCoords-tr-y test success'); s9Sprite.setFillStart(0.3); s9Sprite.setFillRange(-0.4); s9Sprite._rebuildQuads(); vertices = s9Sprite._vertices; uvs = s9Sprite._uvs; - strictEqual(vertices.length >= 8 && uvs >= 8, true, 'vertices have at least 8 floats'); + strictEqual(vertices.length >= 8 && uvs.length >= 8, true, 'vertices have at least 8 floats'); strictEqual(vertices[0], 0, 'vertex-bl-x test success'); strictEqual(vertices[1], 0, 'vertex-bl-y test success'); strictEqual(vertices[6], 100, 'vertex-tr-x test success'); strictEqual(vertices[7], 30, 'vertex-tr-y test success'); - deepClose(uvs[0], 10 / 100, 0.0001, 'texCoords-bl-x test success'); - deepClose(uvs[1], 70 / 100, 0.0001, 'texCoords-bl-y test success'); - deepClose(uvs[6], 50 / 100, 0.0001, 'texCoords-tr-x test success'); - deepClose(uvs[7], 52 / 100, 0.0001, 'texCoords-tr-y test success'); + deepClose(uvs[0], 10 / 100, 0.01, 'texCoords-bl-x test success'); + deepClose(uvs[1], 70 / 100, 0.01, 'texCoords-bl-y test success'); + deepClose(uvs[6], 50 / 100, 0.01, 'texCoords-tr-x test success'); + deepClose(uvs[7], 52 / 100, 0.01, 'texCoords-tr-y test success'); }; if (spriteFrame.textureLoaded()) { testCallBack(); @@ -302,21 +302,21 @@ test('filled-bar-radial spriteQuad trimmed', function () { var vertices = s9Sprite._vertices; var uvs = s9Sprite._uvs; strictEqual(s9Sprite._isTriangle, true, "Triangles used"); - strictEqual(vertices.length >= 30 && uvs >= 30, true, 'vertices have at least 30 floats'); + strictEqual(vertices.length >= 30 && uvs.length >= 30, true, 'vertices have at least 30 floats'); var center = cc.v2(50, 50); var p0 = cc.v2(100, 50); var p1 = cc.v2(100, 100); var p2 = cc.v2(50, 100); - deepClose(vertices[6], center.x, 0.0001, 'center test success'); - deepClose(vertices[7], center.y, 0.0001, 'center test success'); - deepClose(vertices[2], p0.x, 0.0001, 'p0 test success'); - deepClose(vertices[3], p0.y, 0.0001, 'p0 test success'); - deepClose(vertices[8], p1.x, 0.0001, 'p1 test success'); - deepClose(vertices[9], p1.y, 0.0001, 'p1 test success'); - deepClose(vertices[10], p2.x, 0.0001, 'p2 test success'); - deepClose(vertices[11], p2.y, 0.0001, 'p2 test success'); + deepClose(vertices[6], center.x, 0.01, 'center test success'); + deepClose(vertices[7], center.y, 0.01, 'center test success'); + deepClose(vertices[2], p0.x, 0.01, 'p0 test success'); + deepClose(vertices[3], p0.y, 0.01, 'p0 test success'); + deepClose(vertices[8], p1.x, 0.01, 'p1 test success'); + deepClose(vertices[9], p1.y, 0.01, 'p1 test success'); + deepClose(vertices[10], p2.x, 0.01, 'p2 test success'); + deepClose(vertices[11], p2.y, 0.01, 'p2 test success'); }; if (spriteFrame.textureLoaded()) { testCallBack(); From e73e54f5ffdc90fcd22a21f0e7975de7cae94d1d Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 26 Jul 2016 12:12:58 +0800 Subject: [PATCH 038/268] Reverse changes to instantiateProps --- cocos2d/core/platform/CCClass.js | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index 0b59b81fde..b5fb1343e5 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -291,22 +291,24 @@ function instantiateProps (instance, itsClass) { for (var i = 0; i < propList.length; i++) { var prop = propList[i]; var attrKey = prop + DELIMETER + 'default'; - var def = attrs[attrKey]; - if (def !== undefined) { // getter does not have default + if (attrKey in attrs) { // getter does not have default + var def = attrs[attrKey]; // default maybe 0 - if (typeof def === 'object' && def) { - if (typeof def.clone === 'function') { - def = def.clone(); + if (def) { + if (typeof def === 'object' && def) { + if (typeof def.clone === 'function') { + def = def.clone(); + } + else if (Array.isArray(def)) { + def = []; + } + else { + def = {}; + } } - else if (Array.isArray(def)) { - def = []; + else if (typeof def === 'function') { + def = getDefault(def); } - else { - def = {}; - } - } - else if (typeof def === 'function') { - def = getDefault(def); } instance[prop] = def; } From 7d903a1f932ca9f8ae8222d721f783b157774eed Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Tue, 26 Jul 2016 12:57:24 +0800 Subject: [PATCH 039/268] set max download concurrent for all platforms --- cocos2d/core/load-pipeline/downloader.js | 23 +++++++++-------------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/cocos2d/core/load-pipeline/downloader.js b/cocos2d/core/load-pipeline/downloader.js index c570eed262..9d87143d74 100644 --- a/cocos2d/core/load-pipeline/downloader.js +++ b/cocos2d/core/load-pipeline/downloader.js @@ -310,7 +310,7 @@ var Downloader = function (extMap) { this.id = ID; this.async = true; this.pipeline = null; - this.maxConcurrent = 2; + this.maxConcurrent = cc.sys.isMobile ? 2 : 512; this._curConcurrent = 0; this._loadQueue = []; @@ -331,21 +331,16 @@ JS.mixin(Downloader.prototype, { var self = this; var downloadFunc = this.extMap[item.type] || this.extMap['default']; if (this._curConcurrent < this.maxConcurrent) { - if (cc.sys.isMobile) { - this._curConcurrent++; - } + this._curConcurrent++; downloadFunc.call(this, item, function (err, result) { - if (cc.sys.isMobile) { - // Concurrent logic - self._curConcurrent = Math.max(0, self._curConcurrent - 1); - - while (self._curConcurrent < self.maxConcurrent) { - var nextOne = self._loadQueue.shift(); - if (!nextOne) { - break; - } - self.handle(nextOne.item, nextOne.callback); + // Concurrent logic + self._curConcurrent = Math.max(0, self._curConcurrent - 1); + while (self._curConcurrent < self.maxConcurrent) { + var nextOne = self._loadQueue.shift(); + if (!nextOne) { + break; } + self.handle(nextOne.item, nextOne.callback); } callback && callback(err, result); From b1fadcc04e411fee6091dd307c872e9532b921fa Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Fri, 22 Jul 2016 16:38:21 +0800 Subject: [PATCH 040/268] add ignoreEditorOnly mode for deserialization --- .../components/CCComponentEventHandler.js | 3 +- cocos2d/core/platform/deserialize.js | 40 +++++++++---------- 2 files changed, 21 insertions(+), 22 deletions(-) diff --git a/cocos2d/core/components/CCComponentEventHandler.js b/cocos2d/core/components/CCComponentEventHandler.js index cbaf23cbe7..85275a290c 100644 --- a/cocos2d/core/components/CCComponentEventHandler.js +++ b/cocos2d/core/components/CCComponentEventHandler.js @@ -80,6 +80,7 @@ cc.Component.EventHandler = cc.Class({ /** * @method emitEvents * @param {Component.EventHandler[]} events + * @param {Any} ...params * @statics */ emitEvents: function(events) { @@ -88,7 +89,7 @@ cc.Component.EventHandler = cc.Class({ var event = events[i]; if (! event instanceof cc.Component.EventHandler) continue; - event.emit(Array.prototype.slice.call(arguments,1)); + event.emit(Array.prototype.slice.call(arguments, 1)); } } }, diff --git a/cocos2d/core/platform/deserialize.js b/cocos2d/core/platform/deserialize.js index f9da036042..ff3a003489 100644 --- a/cocos2d/core/platform/deserialize.js +++ b/cocos2d/core/platform/deserialize.js @@ -27,8 +27,6 @@ var JS = require('./js'); var CCObject = require('./CCObject'); var Attr = require('./attribute'); -var ENABLE_TARGET = CC_DEV; - // HELPERS /** @@ -144,13 +142,11 @@ Details.prototype.push = function (obj, propName, uuid) { // IMPLEMENT OF DESERIALIZATION var _Deserializer = (function () { - ///** - // * @param {Boolean} isEditor - if false, "editorOnly" properties will be discarded - // */ - function _Deserializer(jsonObj, result, target, classFinder, customEnv) { + function _Deserializer(jsonObj, result, target, classFinder, customEnv, ignoreEditorOnly) { this._classFinder = classFinder; - if (ENABLE_TARGET) { + if (CC_DEV) { this._target = target; + this._ignoreEditorOnly = ignoreEditorOnly; } this._idList = []; this._idObjList = []; @@ -166,7 +162,7 @@ var _Deserializer = (function () { for (var i = 0; i < refCount; i++) { if (jsonArray[i]) { var mainTarget; - if (ENABLE_TARGET) { + if (CC_DEV) { mainTarget = (i === 0 && target); } this.deserializedList[i] = _deserializeObject(this, jsonArray[i], mainTarget); @@ -243,7 +239,7 @@ var _Deserializer = (function () { this.result.uuidPropList.push(propName); } else { - if (ENABLE_TARGET) { + if (CC_DEV) { obj[propName] = _deserializeObject(this, jsonObj, target && target[propName]); } else { @@ -284,7 +280,7 @@ var _Deserializer = (function () { } else { if (prop) { - if (ENABLE_TARGET) { + if (CC_DEV) { self._deserializeObjField(instance, prop, propName, self._target && instance); } else { @@ -313,7 +309,7 @@ var _Deserializer = (function () { } else { if (prop) { - if (ENABLE_TARGET) { + if (CC_DEV) { self._deserializeObjField(instance, prop, propName, self._target && instance); } else { @@ -338,10 +334,11 @@ var _Deserializer = (function () { // assume all prop in __props__ must have attr var rawType = attrs[propName + DELIMETER + 'rawType']; if (!rawType) { - if (!CC_DEV && attrs[propName + DELIMETER + 'editorOnly']) { + if (((CC_EDITOR && self._ignoreEditorOnly) || (!CC_EDITOR && CC_DEV)) + && attrs[propName + DELIMETER + 'editorOnly']) { var mayUsedInPersistRoot = (obj instanceof cc.Node && propName === '_id'); if ( !mayUsedInPersistRoot ) { - continue; // skip editor only if not editor + continue; // skip editor only if in preview } } if (attrs[propName + DELIMETER + 'serializable'] === false) { @@ -356,7 +353,7 @@ var _Deserializer = (function () { } else { if (prop) { - if (ENABLE_TARGET) { + if (CC_DEV) { self._deserializeObjField(obj, prop, propName, target && obj); } else { @@ -409,7 +406,7 @@ var _Deserializer = (function () { return null; } - if (ENABLE_TARGET && target) { + if (CC_DEV && target) { // use target if ( !(target instanceof klass) ) { cc.warn('Type of target to deserialize not matched with data: target is %s, data is %s', @@ -441,14 +438,14 @@ var _Deserializer = (function () { // embedded primitive javascript object - obj = (ENABLE_TARGET && target) || {}; + obj = (CC_DEV && target) || {}; _deserializePrimitiveObject(self, obj, serialized); } else { // Array - if (ENABLE_TARGET && target) { + if (CC_DEV && target) { target.length = serialized.length; obj = target; } @@ -459,7 +456,7 @@ var _Deserializer = (function () { for (var i = 0; i < serialized.length; i++) { prop = serialized[i]; if (typeof prop === 'object' && prop) { - if (ENABLE_TARGET) { + if (CC_DEV) { self._deserializeObjField(obj, prop, '' + i, target && obj); } else { @@ -504,8 +501,9 @@ cc.deserialize = function (data, result, options) { var classFinder = (options && options.classFinder) || JS._getClassById; // 启用 createAssetRefs 后,如果有 url 属性则会被统一强制设置为 { uuid: 'xxx' },必须后面再特殊处理 var createAssetRefs = (options && options.createAssetRefs) || cc.sys.platform === cc.sys.EDITOR_CORE; - var target = ENABLE_TARGET && (options && options.target); - var customEnv = (options && options.customEnv); + var target = CC_DEV && (options && options.target); + var customEnv = options && options.customEnv; + var ignoreEditorOnly = options && options.ignoreEditorOnly; if (CC_EDITOR && Buffer.isBuffer(data)) { data = data.toString(); @@ -521,7 +519,7 @@ cc.deserialize = function (data, result, options) { result = new Details(); } cc.game._isCloning = true; - var deserializer = new _Deserializer(data, result, target, classFinder, customEnv); + var deserializer = new _Deserializer(data, result, target, classFinder, customEnv, ignoreEditorOnly); cc.game._isCloning = false; if (createAssetRefs) { From 2cd4b08e681caafa36da3a3d419091e81673521f Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Sun, 24 Jul 2016 11:28:25 +0800 Subject: [PATCH 041/268] make missing script behavior customizable --- cocos2d/core/components/missing-script.js | 7 ++++++ cocos2d/core/platform/deserialize.js | 26 ++++++++++++----------- 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/cocos2d/core/components/missing-script.js b/cocos2d/core/components/missing-script.js index 82bafac5bf..f91283c8e0 100644 --- a/cocos2d/core/components/missing-script.js +++ b/cocos2d/core/components/missing-script.js @@ -90,6 +90,13 @@ var MissingScript = cc.Class({ return cls; } if (id) { + if (CC_EDITOR && Editor.UuidUtils.isUuid(id)) { + id = Editor.UuidUtils.decompressUuid(id); + cc.warn('Can not find script "%s"', id); + } + else { + cc.warn('Can not find class "%s"', id); + } return MissingScript; } return null; diff --git a/cocos2d/core/platform/deserialize.js b/cocos2d/core/platform/deserialize.js index ff3a003489..c935b8d528 100644 --- a/cocos2d/core/platform/deserialize.js +++ b/cocos2d/core/platform/deserialize.js @@ -197,7 +197,7 @@ var _Deserializer = (function () { } } - var _dereference = function (self) { + function _dereference (self) { // 这里不采用遍历反序列化结果的方式,因为反序列化的结果如果引用到复杂的外部库,很容易堆栈溢出。 var deserializedList = self.deserializedList; var idPropList = self._idPropList; @@ -208,7 +208,7 @@ var _Deserializer = (function () { var id = idList[i]; idObjList[i][propName] = deserializedList[id]; } - }; + } if (CC_DEV) { _Deserializer.prototype._callVisitorInEditor = function () { @@ -386,8 +386,8 @@ var _Deserializer = (function () { // * @param {Object} serialized - The obj to deserialize, must be non-nil // * @param {Object} [target=null] // */ - var _deserializeObject = function (self, serialized, target) { - var propName, prop; + function _deserializeObject (self, serialized, target) { + var prop; var obj = null; // the obj to return var klass = null; if (serialized.__type__) { @@ -397,12 +397,16 @@ var _Deserializer = (function () { var type = serialized.__type__; klass = self._classFinder(type); if (!klass) { - if (CC_EDITOR && Editor.UuidUtils.isUuid(type)) { - type = Editor.UuidUtils.decompressUuid(type); - cc.warn('Can not find script "%s"', type); - return null; + var noLog = self._classFinder === JS._getClassById; + if (noLog) { + if (CC_EDITOR && Editor.UuidUtils.isUuid(type)) { + type = Editor.UuidUtils.decompressUuid(type); + cc.warn('Can not find script "%s"', type); + } + else { + cc.warn('Can not find class "%s"', type); + } } - cc.warn('Can not find class "%s"', type); return null; } @@ -473,13 +477,11 @@ var _Deserializer = (function () { } } return obj; - }; + } return _Deserializer; })(); -// FACADE - /** * @module cc */ From 1a7b909ed0fa009870758a3125b78a33d945a752 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Sun, 24 Jul 2016 19:58:31 +0800 Subject: [PATCH 042/268] simplify deserialization visitor --- cocos2d/core/components/missing-script.js | 8 +-- cocos2d/core/platform/deserialize.js | 76 ++++++++--------------- 2 files changed, 26 insertions(+), 58 deletions(-) diff --git a/cocos2d/core/components/missing-script.js b/cocos2d/core/components/missing-script.js index f91283c8e0..07fe2f6d9a 100644 --- a/cocos2d/core/components/missing-script.js +++ b/cocos2d/core/components/missing-script.js @@ -90,13 +90,7 @@ var MissingScript = cc.Class({ return cls; } if (id) { - if (CC_EDITOR && Editor.UuidUtils.isUuid(id)) { - id = Editor.UuidUtils.decompressUuid(id); - cc.warn('Can not find script "%s"', id); - } - else { - cc.warn('Can not find class "%s"', id); - } + cc.deserialize.reportMissingClass(id); return MissingScript; } return null; diff --git a/cocos2d/core/platform/deserialize.js b/cocos2d/core/platform/deserialize.js index c935b8d528..0ab799f7ba 100644 --- a/cocos2d/core/platform/deserialize.js +++ b/cocos2d/core/platform/deserialize.js @@ -66,20 +66,16 @@ var Details = function () { if (CC_DEV) { /** - * 用户可以指定一个在反序列化结束时会被触发的回调,该回调会传回反序列化时统计到的所有解析过的字段。 + * 用户可以指定一个在反序列化过程中会被触发的回调,该回调会在反序列化之前调用,并且传回反序列化时解析到的字段。 * NOTE: + * - only available in editor * - 会被传回的字段仅限于非 Asset 类型,并且如果字段值为 null 或 undefined,则可能不会被传回。 - * - 该回调在 DeserializeInfo 第一次调用 reset 时就会被清空。 - * @callback visitorInEditor - * @param {Object[]} objs - * @param {String[]} propNames - * @param {Object} _Deserializer + * @callback visit + * @param {Object} obj + * @param {String} propName * @private */ - this.visitorInEditor = null; - - this.visitObjList = []; - this.visitPropList = []; + this.visit = null; } }; /** @@ -92,18 +88,8 @@ Details.prototype.reset = function () { this.rawProp = ''; //this.rawObjList.length = 0; //this.rawPropList.length = 0; - - if (CC_DEV) { - this.visitorInEditor = null; - this.visitObjList.length = 0; - this.visitPropList.length = 0; - } }; if (CC_DEV) { - Details.prototype.visitLater = function (obj, propName) { - this.visitObjList.push(obj); - this.visitPropList.push(propName); - }; Details.prototype.assignAssetsBy = function (getter) { for (var i = 0, len = this.uuidList.length; i < len; i++) { var uuid = this.uuidList[i]; @@ -190,11 +176,6 @@ var _Deserializer = (function () { // dereference _dereference(this); - - // call visitor after all properties initialized - if (CC_DEV) { - this._callVisitorInEditor(); - } } function _dereference (self) { @@ -210,16 +191,7 @@ var _Deserializer = (function () { } } - if (CC_DEV) { - _Deserializer.prototype._callVisitorInEditor = function () { - var result = this.result; - if (result.visitorInEditor) { - result.visitorInEditor(result.visitObjList, result.visitPropList, this); - } - }; - } - - // 和 _deserializeObject 不同的地方在于会判断 id 和 uuid + // 和 _deserializeObject 不同的地方在于会判断 id 和 uuid _Deserializer.prototype._deserializeObjField = function (obj, jsonObj, propName, target) { var id = jsonObj.__id__; if (typeof id === 'undefined') { @@ -245,8 +217,8 @@ var _Deserializer = (function () { else { obj[propName] = _deserializeObject(this, jsonObj); } - if (CC_DEV && this.result.visitorInEditor) { - this.result.visitLater(obj, propName); + if (CC_DEV && this.result.visit) { + this.result.visit(obj, propName); } } } @@ -260,8 +232,8 @@ var _Deserializer = (function () { this._idObjList.push(obj); this._idPropList.push(propName); } - if (CC_DEV && this.result.visitorInEditor) { - this.result.visitLater(obj, propName); + if (CC_DEV && this.result.visit) { + this.result.visit(obj, propName); } } }; @@ -273,8 +245,8 @@ var _Deserializer = (function () { if (typeof prop !== 'object') { if (propName !== '__type__'/* && k != '__id__'*/) { instance[propName] = prop; - if (CC_DEV && self.result.visitorInEditor) { - self.result.visitLater(instance, propName); + if (CC_DEV && self.result.visit) { + self.result.visit(instance, propName); } } } @@ -399,13 +371,7 @@ var _Deserializer = (function () { if (!klass) { var noLog = self._classFinder === JS._getClassById; if (noLog) { - if (CC_EDITOR && Editor.UuidUtils.isUuid(type)) { - type = Editor.UuidUtils.decompressUuid(type); - cc.warn('Can not find script "%s"', type); - } - else { - cc.warn('Can not find class "%s"', type); - } + cc.deserialize.reportMissingClass(type); } return null; } @@ -469,9 +435,8 @@ var _Deserializer = (function () { } else { obj[i] = prop; - - if (CC_DEV && self.result.visitorInEditor) { - self.result.visitLater(obj, '' + i); + if (CC_DEV && self.result.visit) { + self.result.visit(obj, '' + i); } } } @@ -537,3 +502,12 @@ cc.deserialize = function (data, result, options) { }; cc.deserialize.Details = Details; +cc.deserialize.reportMissingClass = function (id) { + if (CC_EDITOR && Editor.UuidUtils.isUuid(id)) { + id = Editor.UuidUtils.decompressUuid(id); + cc.warn('Can not find script "%s"', id); + } + else { + cc.warn('Can not find class "%s"', id); + } +}; From e9b07c435b9d648b09432c75781ea94af0f96e3f Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Mon, 25 Jul 2016 23:24:17 +0800 Subject: [PATCH 043/268] minor tweaks --- cocos2d/core/components/CCComponent.js | 2 +- cocos2d/core/components/missing-script.js | 26 +++++++++++++++++++---- cocos2d/core/platform/CCObject.js | 10 ++++----- cocos2d/core/platform/deserialize.js | 16 ++++++++------ cocos2d/core/utils/find.js | 12 ++++++++++- 5 files changed, 48 insertions(+), 18 deletions(-) diff --git a/cocos2d/core/components/CCComponent.js b/cocos2d/core/components/CCComponent.js index 8ea95a835d..27a27790aa 100644 --- a/cocos2d/core/components/CCComponent.js +++ b/cocos2d/core/components/CCComponent.js @@ -374,7 +374,7 @@ var Component = cc.Class({ */ enabledInHierarchy: { get: function () { - return this._objFlags & IsOnEnableCalled; + return (this._objFlags & IsOnEnableCalled) > 0; }, visible: false }, diff --git a/cocos2d/core/components/missing-script.js b/cocos2d/core/components/missing-script.js index 07fe2f6d9a..23e947db3e 100644 --- a/cocos2d/core/components/missing-script.js +++ b/cocos2d/core/components/missing-script.js @@ -25,10 +25,23 @@ var JS = cc.js; +/* + * A temp fallback to contain the original serialized data which can not be loaded. + */ +var MissingClass = cc.Class({ + name: 'cc.MissingClass', + properties: { + // the serialized data for original object + _$erialized: { + default: null, + visible: false, + editorOnly: true + } + }, +}); + /* * A temp fallback to contain the original component which can not be loaded. - * Actually, this class will be used whenever a class failed to deserialize, - * regardless of whether it is child class of component. */ var MissingScript = cc.Class({ name: 'cc.MissingScript', @@ -84,14 +97,19 @@ var MissingScript = cc.Class({ * @param {string} id * @return {function} constructor */ - safeFindClass: function (id) { + safeFindClass: function (id, data) { var cls = JS._getClassById(id); if (cls) { return cls; } if (id) { cc.deserialize.reportMissingClass(id); - return MissingScript; + if (data.node && (CC_EDITOR && Editor.UuidUtils.isUuid(id))) { + return MissingScript; + } + else { + return MissingClass; + } } return null; } diff --git a/cocos2d/core/platform/CCObject.js b/cocos2d/core/platform/CCObject.js index ac25c74b5f..7abf85d342 100644 --- a/cocos2d/core/platform/CCObject.js +++ b/cocos2d/core/platform/CCObject.js @@ -245,14 +245,14 @@ var deferredDestroyTimer = null; /** * !#en * Destroy this Object, and release all its own references to other objects.
+ * Actual object destruction will delayed until before rendering. *
- * After destroy, this CCObject is not usable any more.
- * You can use cc.isValid(obj) (or obj.isValid if obj is non-nil) to check whether the object is destroyed before - * accessing it. + * After destroy, this CCObject is not usable any more. + * You can use cc.isValid(obj) to check whether the object is destroyed before accessing it. * !#zh * 销毁该对象,并释放所有它对其它对象的引用。
- * 销毁后,CCObject 不再可用。
- * 您可以在访问对象之前使用 cc.isValid(obj)(或 obj.isValid 如果 obj 不为 null)来检查对象是否已被销毁。 + * 销毁后,CCObject 不再可用。您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。 + * 实际销毁操作会延迟到当前帧渲染前执行。 * @method destroy * @return {Boolean} whether it is the first time the destroy being called * @example diff --git a/cocos2d/core/platform/deserialize.js b/cocos2d/core/platform/deserialize.js index 0ab799f7ba..d0ac823e65 100644 --- a/cocos2d/core/platform/deserialize.js +++ b/cocos2d/core/platform/deserialize.js @@ -297,23 +297,25 @@ var _Deserializer = (function () { //--self.stackCounter; } + var RAW_TYPE = Attr.DELIMETER + 'rawType'; + var EDITOR_ONLY = Attr.DELIMETER + 'editorOnly'; + var SERIALIZABLE = Attr.DELIMETER + 'serializable'; + function _deserializeFireClass(self, obj, serialized, klass, target) { - var DELIMETER = Attr.DELIMETER; var props = klass.__props__; var attrs = Attr.getClassAttrs(klass); for (var p = 0; p < props.length; p++) { var propName = props[p]; - // assume all prop in __props__ must have attr - var rawType = attrs[propName + DELIMETER + 'rawType']; + var rawType = attrs[propName + RAW_TYPE]; if (!rawType) { - if (((CC_EDITOR && self._ignoreEditorOnly) || (!CC_EDITOR && CC_DEV)) - && attrs[propName + DELIMETER + 'editorOnly']) { + if (((CC_EDITOR && self._ignoreEditorOnly) || (!CC_EDITOR && CC_DEV && !CC_TEST)) + && attrs[propName + EDITOR_ONLY]) { var mayUsedInPersistRoot = (obj instanceof cc.Node && propName === '_id'); if ( !mayUsedInPersistRoot ) { continue; // skip editor only if in preview } } - if (attrs[propName + DELIMETER + 'serializable'] === false) { + if (attrs[propName + SERIALIZABLE] === false) { continue; // skip nonSerialized } var prop = serialized[propName]; @@ -367,7 +369,7 @@ var _Deserializer = (function () { // Type Object (including CCClass) var type = serialized.__type__; - klass = self._classFinder(type); + klass = self._classFinder(type, serialized); if (!klass) { var noLog = self._classFinder === JS._getClassById; if (noLog) { diff --git a/cocos2d/core/utils/find.js b/cocos2d/core/utils/find.js index 986b1b9dff..fbcdd94df7 100644 --- a/cocos2d/core/utils/find.js +++ b/cocos2d/core/utils/find.js @@ -43,11 +43,21 @@ cc.find = module.exports = function (path, referenceNode) { if (!referenceNode) { var scene = cc.director.getScene(); if (!scene) { - cc.warn('Can not get current scene.'); + if (CC_DEV) { + cc.warn('Can not get current scene.'); + } + return null; + } + else if (CC_DEV && !scene.isValid) { + cc.warn('Scene is destroyed'); return null; } referenceNode = scene; } + else if (CC_DEV && !referenceNode.isValid) { + cc.warn('reference node is destroyed'); + return null; + } var match = referenceNode; var startIndex = (path[0] !== '/') ? 0 : 1; // skip first '/' From ad26127da74785674a035cd80ec6a29a12d4eaa5 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Tue, 26 Jul 2016 16:48:55 +0800 Subject: [PATCH 044/268] fix scrollview content jump in editor ticket: https://github.com/cocos-creator/fireball/issues/3737 --- cocos2d/core/components/CCScrollView.js | 80 +++++++++++++------------ 1 file changed, 43 insertions(+), 37 deletions(-) diff --git a/cocos2d/core/components/CCScrollView.js b/cocos2d/core/components/CCScrollView.js index 660e27173a..41aafc378a 100644 --- a/cocos2d/core/components/CCScrollView.js +++ b/cocos2d/core/components/CCScrollView.js @@ -762,6 +762,47 @@ var ScrollView = cc.Class({ return moveDelta; }, + _moveContentToTopLeft: function (scrollViewSize) { + var contentSize = this.content.getContentSize(); + + var bottomDeta = this._getContentBottomBoundary() - this._bottomBoundary; + bottomDeta = -bottomDeta; + var moveDelta = cc.p(0, 0); + var totalScrollDelta = 0; + + var leftDeta = this._getContentLeftBoundary() - this._leftBoundary; + leftDeta = -leftDeta; + + if (contentSize.height < scrollViewSize.height) { + totalScrollDelta = contentSize.height - scrollViewSize.height; + moveDelta.y = bottomDeta - totalScrollDelta; + + if (this.verticalScrollBar) { + this.verticalScrollBar.hide(); + } + } else { + if (this.verticalScrollBar) { + this.verticalScrollBar.show(); + } + } + + if (contentSize.width < scrollViewSize.width) { + totalScrollDelta = contentSize.width - scrollViewSize.width; + moveDelta.x = leftDeta; + + if (this.horizontalScrollBar) { + this.horizontalScrollBar.hide(); + } + + } else { + if (this.horizontalScrollBar) { + this.horizontalScrollBar.show(); + } + } + + this._moveContent(moveDelta); + }, + _calculateBoundary: function() { if (this.content) { //refresh content size @@ -779,44 +820,9 @@ var ScrollView = cc.Class({ this._rightBoundary = topRightPosition.x; this._topBoundary = topRightPosition.y; - var contentSize = this.content.getContentSize(); - - var bottomDeta = this._getContentBottomBoundary() - this._bottomBoundary; - bottomDeta = -bottomDeta; - var moveDelta = cc.p(0, 0); - var totalScrollDelta = 0; - - var leftDeta = this._getContentLeftBoundary() - this._leftBoundary; - leftDeta = -leftDeta; - - if (contentSize.height < scrollViewSize.height) { - totalScrollDelta = contentSize.height - scrollViewSize.height; - moveDelta.y = bottomDeta - totalScrollDelta; - - if (this.verticalScrollBar) { - this.verticalScrollBar.hide(); - } - } else { - if (this.verticalScrollBar) { - this.verticalScrollBar.show(); - } + if(!CC_EDITOR) { + this._moveContentToTopLeft(scrollViewSize); } - - if (contentSize.width < scrollViewSize.width) { - totalScrollDelta = contentSize.width - scrollViewSize.width; - moveDelta.x = leftDeta; - - if (this.horizontalScrollBar) { - this.horizontalScrollBar.hide(); - } - - } else { - if (this.horizontalScrollBar) { - this.horizontalScrollBar.show(); - } - } - - this._moveContent(moveDelta); } }, From f3c3dc00d174a619b4df1bbb40d8e801edbf9efe Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Tue, 26 Jul 2016 17:16:51 +0800 Subject: [PATCH 045/268] still checking class inheritance by using $super in JSB --- cocos2d/core/platform/CCClass.js | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index b5fb1343e5..a1e9220408 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -338,9 +338,14 @@ cc.isChildClassOf = function (subclass, superclass) { return true; } for (;;) { - var proto = subclass.prototype; // binded function do not have prototype - var dunderProto = proto && Object.getPrototypeOf(proto); - subclass = dunderProto && dunderProto.constructor; + if (CC_JSB && subclass.$super) { + subclass = subclass.$super; + } + else { + var proto = subclass.prototype; // binded function do not have prototype + var dunderProto = proto && Object.getPrototypeOf(proto); + subclass = dunderProto && dunderProto.constructor; + } if (!subclass) { return false; } @@ -356,8 +361,13 @@ cc.isChildClassOf = function (subclass, superclass) { function getInheritanceChain (klass) { var chain = []; for (;;) { - var dunderProto = Object.getPrototypeOf(klass.prototype); - klass = dunderProto && dunderProto.constructor; + if (CC_JSB && klass.$super) { + klass = klass.$super; + } + else { + var dunderProto = Object.getPrototypeOf(klass.prototype); + klass = dunderProto && dunderProto.constructor; + } if (!klass) { break; } From d975e36d3c2692965aea406c4ea75ea559648e98 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 26 Jul 2016 17:20:51 +0800 Subject: [PATCH 046/268] Fix _pixelWidth not exist in Canvas render mode issue --- cocos2d/core/CCDirector.js | 2 +- cocos2d/core/CCGame.js | 10 +++--- cocos2d/core/sprites/CCScale9Sprite.js | 20 +++++------ .../sprites/CCScale9SpriteCanvasRenderCmd.js | 4 +-- cocos2d/core/textures/CCTexture2D.js | 35 ++++++++----------- 5 files changed, 32 insertions(+), 39 deletions(-) diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js index 55e45ddc3f..823368e23f 100644 --- a/cocos2d/core/CCDirector.js +++ b/cocos2d/core/CCDirector.js @@ -268,7 +268,7 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ renderer.clearRenderCommands(); cc.renderer.assignedZ = 0; this._runningScene._renderCmd._curLevel = 0; //level start from 0; - this._runningScene.visit(); + this._runningScene._renderCmd.visit(); renderer.resetFlag(); } else if (renderer.transformDirty()) { diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index 15b7f5d507..e7c7dad0d2 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -39,7 +39,7 @@ var game = /** @lends cc.game# */{ /** * Event triggered when game hide to background. * Please note that this event is not 100% guaranteed to be fired. - * @constant + * @property * @type {String} * @example * cc.game.on(cc.game.EVENT_HIDE, function () { @@ -52,21 +52,21 @@ var game = /** @lends cc.game# */{ /** * Event triggered when game back to foreground * Please note that this event is not 100% guaranteed to be fired. - * @constant + * @property * @type {String} */ EVENT_SHOW: "game_on_show", /** * Event triggered after game inited, at this point all engine objects and game scripts are loaded - * @constant + * @property * @type {String} */ EVENT_GAME_INITED: "game_inited", /** * Event triggered after renderer inited, at this point you will be able to use the render context - * @constant + * @property * @type {String} */ EVENT_RENDERER_INITED: "renderer_inited", @@ -80,7 +80,7 @@ var game = /** @lends cc.game# */{ /** * Key of config - * @constant + * @property * @type {Object} */ CONFIG_KEY: { diff --git a/cocos2d/core/sprites/CCScale9Sprite.js b/cocos2d/core/sprites/CCScale9Sprite.js index 99f23ecfd6..35faf7052c 100644 --- a/cocos2d/core/sprites/CCScale9Sprite.js +++ b/cocos2d/core/sprites/CCScale9Sprite.js @@ -151,8 +151,8 @@ var simpleQuadGenerator = { _calculateUVs: function (sprite, spriteFrame) { var uvs = sprite._uvs; - var atlasWidth = spriteFrame._texture._pixelsWide; - var atlasHeight = spriteFrame._texture._pixelsHigh; + var atlasWidth = spriteFrame._texture._pixelWidth; + var atlasHeight = spriteFrame._texture._pixelHeight; var textureRect = spriteFrame._rect; if (uvs.length < 8) { @@ -265,8 +265,8 @@ var scale9QuadGenerator = { _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; + var atlasWidth = spriteFrame._texture._pixelWidth; + var atlasHeight = spriteFrame._texture._pixelHeight; //caculate texture coordinate var leftWidth, centerWidth, rightWidth; @@ -339,8 +339,8 @@ var tiledQuadGenerator = { wt = sprite._renderCmd._worldTransform, uvs = sprite._uvs; //build uvs - var atlasWidth = spriteFrame._texture._pixelsWide; - var atlasHeight = spriteFrame._texture._pixelsHigh; + var atlasWidth = spriteFrame._texture._pixelWidth; + var atlasHeight = spriteFrame._texture._pixelHeight; var textureRect = spriteFrame._rect; //uv computation should take spritesheet into account. @@ -454,8 +454,8 @@ var fillQuadGeneratorBar = { var l = 0, b = 0, r = contentSize.width, t = contentSize.height; //build uvs - var atlasWidth = spriteFrame._texture._pixelsWide; - var atlasHeight = spriteFrame._texture._pixelsHigh; + var atlasWidth = spriteFrame._texture._pixelWidth; + var atlasHeight = spriteFrame._texture._pixelHeight; var textureRect = spriteFrame._rect; //uv computation should take spritesheet into account. var ul, vb, ur, vt; @@ -894,8 +894,8 @@ var fillQuadGeneratorRadial = { }, _calculateUVs : function (spriteFrame) { - var atlasWidth = spriteFrame._texture._pixelsWide; - var atlasHeight = spriteFrame._texture._pixelsHigh; + var atlasWidth = spriteFrame._texture._pixelWidth; + var atlasHeight = spriteFrame._texture._pixelHeight; var textureRect = spriteFrame._rect; //uv computation should take spritesheet into account. diff --git a/cocos2d/core/sprites/CCScale9SpriteCanvasRenderCmd.js b/cocos2d/core/sprites/CCScale9SpriteCanvasRenderCmd.js index 8329cf238d..448fd5eb2a 100644 --- a/cocos2d/core/sprites/CCScale9SpriteCanvasRenderCmd.js +++ b/cocos2d/core/sprites/CCScale9SpriteCanvasRenderCmd.js @@ -83,8 +83,8 @@ proto.rendering = function (ctx, scaleX, scaleY) { } var sx,sy,sw,sh; var x, y, w,h; - var textureWidth = this._textureToRender.getPixelWidth(); - var textureHeight = this._textureToRender.getPixelHeight(); + var textureWidth = this._textureToRender._pixelWidth; + var textureHeight = this._textureToRender._pixelHeight; var image = this._textureToRender._htmlElementObj; var vertices = node._vertices; var uvs = node._uvs; diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index 859c5d646a..3f6a17b485 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -85,6 +85,8 @@ var Texture2D = cc.Class(/** @lends cc.Texture2D# */{ this._textureLoaded = false; this._htmlElementObj = null; this._contentSize = cc.size(0, 0); + this._pixelWidth = 0; + this._pixelHeight = 0; if (cc._renderType === game.RENDER_TYPE_CANVAS) { this._pattern = ""; @@ -96,8 +98,6 @@ var Texture2D = cc.Class(/** @lends cc.Texture2D# */{ else if (cc._renderType === game.RENDER_TYPE_WEBGL) { this._hasPremultipliedAlpha = false; this._pixelFormat = Texture2D.defaultPixelFormat; - this._pixelsWide = 0; - this._pixelsHigh = 0; this._hasPremultipliedAlpha = false; this._hasMipmaps = false; @@ -111,7 +111,7 @@ var Texture2D = cc.Class(/** @lends cc.Texture2D# */{ * @return {Number} */ getPixelWidth: function () { - return this._contentSize.width; + return this._pixelWidth; }, /** @@ -120,7 +120,7 @@ var Texture2D = cc.Class(/** @lends cc.Texture2D# */{ * @return {Number} */ getPixelHeight: function () { - return this._contentSize.height; + return this._pixelHeight; }, /** @@ -162,8 +162,8 @@ var Texture2D = cc.Class(/** @lends cc.Texture2D# */{ if (!element) return; this._htmlElementObj = element; - this._contentSize.width = element.width; - this._contentSize.height = element.height; + this._pixelWidth = this._contentSize.width = element.width; + this._pixelHeight = this._contentSize.height = element.height; this._textureLoaded = true; }, @@ -229,8 +229,8 @@ var Texture2D = cc.Class(/** @lends cc.Texture2D# */{ return; var locElement = self._htmlElementObj; - self._contentSize.width = locElement.width; - self._contentSize.height = locElement.height; + self._pixelWidth = self._contentSize.width = locElement.width; + self._pixelHeight = self._contentSize.height = locElement.height; self._textureLoaded = true; //dispatch load event to listener. @@ -716,13 +716,6 @@ game.once(game.EVENT_RENDERER_INITED, function () { } else if (cc._renderType === game.RENDER_TYPE_WEBGL) { JS.mixin(Texture2D.prototype, { - getPixelWidth: function () { - return this._pixelsWide; - }, - - getPixelHeight: function () { - return this._pixelsHigh; - }, initWithData: function (data, pixelFormat, pixelsWide, pixelsHigh, contentSize) { var self = this, tex2d = Texture2D; @@ -784,8 +777,8 @@ game.once(game.EVENT_RENDERER_INITED, function () { self._contentSize.width = contentSize.width; self._contentSize.height = contentSize.height; - self._pixelsWide = pixelsWide; - self._pixelsHigh = pixelsHigh; + self._pixelWidth = pixelsWide; + self._pixelHeight = pixelsHigh; self._pixelFormat = pixelFormat; self._hasPremultipliedAlpha = false; @@ -863,8 +856,8 @@ game.once(game.EVENT_RENDERER_INITED, function () { var pixelsWide = self._htmlElementObj.width; var pixelsHigh = self._htmlElementObj.height; - self._pixelsWide = self._contentSize.width = pixelsWide; - self._pixelsHigh = self._contentSize.height = pixelsHigh; + self._pixelWidth = self._contentSize.width = pixelsWide; + self._pixelHeight = self._contentSize.height = pixelsHigh; self._pixelFormat = Texture2D.PIXEL_FORMAT_RGBA8888; self._hasPremultipliedAlpha = premultiplied; @@ -882,7 +875,7 @@ game.once(game.EVENT_RENDERER_INITED, function () { if(magFilter !== undefined) texParams = {minFilter: texParams, magFilter: magFilter, wrapS: wrapS, wrapT: wrapT}; - cc.assert((_t._pixelsWide === misc.NextPOT(_t._pixelsWide) && _t._pixelsHigh === misc.NextPOT(_t._pixelsHigh)) || + cc.assert((_t._pixelWidth === misc.NextPOT(_t._pixelWidth) && _t._pixelHeight === misc.NextPOT(_t._pixelHeight)) || (texParams.wrapS === gl.CLAMP_TO_EDGE && texParams.wrapT === gl.CLAMP_TO_EDGE), "WebGLRenderingContext.CLAMP_TO_EDGE should be used in NPOT textures"); @@ -917,7 +910,7 @@ game.once(game.EVENT_RENDERER_INITED, function () { generateMipmap: function () { var _t = this; - cc.assert(_t._pixelsWide === misc.NextPOT(_t._pixelsWide) && _t._pixelsHigh === misc.NextPOT(_t._pixelsHigh), "Mimpap texture only works in POT textures"); + cc.assert(_t._pixelWidth === misc.NextPOT(_t._pixelWidth) && _t._pixelHeight === misc.NextPOT(_t._pixelHeight), "Mimpap texture only works in POT textures"); cc.gl.bindTexture2D(_t); cc._renderContext.generateMipmap(cc._renderContext.TEXTURE_2D); From 269cf15fb0f335771c6d492ea31dd5320e50a163 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Tue, 26 Jul 2016 18:11:03 +0800 Subject: [PATCH 047/268] add tooltip and fix api docs --- cocos2d/core/components/CCWebView.js | 41 ++++++++++++++++++---------- 1 file changed, 27 insertions(+), 14 deletions(-) diff --git a/cocos2d/core/components/CCWebView.js b/cocos2d/core/components/CCWebView.js index 7286b0952b..015add668f 100644 --- a/cocos2d/core/components/CCWebView.js +++ b/cocos2d/core/components/CCWebView.js @@ -21,20 +21,32 @@ THE SOFTWARE. ****************************************************************************/ -var EventType = _ccsg.WebView.EventType; - -/* +/** * !#en WebView event type - * !#zh WebView 事件类型 + * !#zh 网页视图加载事件类型 * @enum WebView.EventType */ +var EventType = _ccsg.WebView.EventType; -/* + +/** * !#en Web page Load completed. * !#zh 网页加载完成 * @property {String} LOADED */ +/** + * !#en Web page is loading. + * !#zh 网页加载中 + * @property {String} LOADING + */ + +/** + * !#en Web page error occurs when loading. + * !#zh 网页加载出错 + * @property {String} ERROR + */ + /** * !#en cc.WebView is a component for display web pages in the game * !#zh WebView 组件,用于在游戏中显示网页 @@ -60,6 +72,7 @@ var WebView = cc.Class({ */ url: { type: String, + tooltip: 'i18n:COMPONENT.webview.url', get: function () { return this._url; }, @@ -75,27 +88,27 @@ var WebView = cc.Class({ /** * !#en The webview's event callback , it will be triggered when web page finished loading. * !#zh WebView 的回调事件,当网页加载完成之后会回调此函数 - * @property {cc.Component.EventHandler[]} webViewLoadedEvents + * @property {cc.Component.EventHandler[]} webviewLoadedEvents */ - webViewLoadedEvents: { + webviewLoadedEvents: { default: [], type: cc.Component.EventHandler, }, /** * !#en The webview's event callback , it will be triggered when web page is loading. * !#zh WebView 的回调事件,当网页加载时会回调此函数 - * @property {cc.Component.EventHandler[]} webViewLoadingEvents + * @property {cc.Component.EventHandler[]} webviewLoadingEvents */ - webViewLoadingEvents: { + webviewLoadingEvents: { default: [], type: cc.Component.EventHandler, }, /** * !#en The webview's event callback , it will be triggered when there are errors when loading. * !#zh WebView 的回调事件,当网页加载出错时会回调此函数 - * @property {cc.Component.EventHandler[]} webViewErrorEvents + * @property {cc.Component.EventHandler[]} webviewErrorEvents */ - webViewErrorEvents: { + webviewErrorEvents: { default: [], type: cc.Component.EventHandler, } @@ -143,16 +156,16 @@ var WebView = cc.Class({ }, _onWebViewLoaded: function () { - cc.Component.EventHandler.emitEvents(this.webViewLoadedEvents, this, EventType.LOADED); + cc.Component.EventHandler.emitEvents(this.webviewLoadedEvents, this, EventType.LOADED); }, _onWebViewLoading: function () { - cc.Component.EventHandler.emitEvents(this.webViewLoadingEvents, this, EventType.LOADING); + cc.Component.EventHandler.emitEvents(this.webviewLoadingEvents, this, EventType.LOADING); return true; }, _onWebViewLoadError: function () { - cc.Component.EventHandler.emitEvents(this.webViewErrorEvents, this, EventType.ERROR); + cc.Component.EventHandler.emitEvents(this.webviewErrorEvents, this, EventType.ERROR); } }); From 2036a6e99b515a7acd6e2794fbdbcf7bae18e2cf Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Tue, 26 Jul 2016 18:29:19 +0800 Subject: [PATCH 048/268] simplify webview event handler --- cocos2d/core/components/CCWebView.js | 36 +++++++--------------------- 1 file changed, 9 insertions(+), 27 deletions(-) diff --git a/cocos2d/core/components/CCWebView.js b/cocos2d/core/components/CCWebView.js index 015add668f..6049f31c35 100644 --- a/cocos2d/core/components/CCWebView.js +++ b/cocos2d/core/components/CCWebView.js @@ -86,32 +86,14 @@ var WebView = cc.Class({ }, /** - * !#en The webview's event callback , it will be triggered when web page finished loading. - * !#zh WebView 的回调事件,当网页加载完成之后会回调此函数 + * !#en The webview's event callback , it will be triggered when certain webview event occurs. + * !#zh WebView 的回调事件,当网页加载过程中,加载完成后或者加载出错时都会回调此函数 * @property {cc.Component.EventHandler[]} webviewLoadedEvents */ - webviewLoadedEvents: { + webviewEvents: { default: [], type: cc.Component.EventHandler, }, - /** - * !#en The webview's event callback , it will be triggered when web page is loading. - * !#zh WebView 的回调事件,当网页加载时会回调此函数 - * @property {cc.Component.EventHandler[]} webviewLoadingEvents - */ - webviewLoadingEvents: { - default: [], - type: cc.Component.EventHandler, - }, - /** - * !#en The webview's event callback , it will be triggered when there are errors when loading. - * !#zh WebView 的回调事件,当网页加载出错时会回调此函数 - * @property {cc.Component.EventHandler[]} webviewErrorEvents - */ - webviewErrorEvents: { - default: [], - type: cc.Component.EventHandler, - } }, statics: { @@ -156,16 +138,16 @@ var WebView = cc.Class({ }, _onWebViewLoaded: function () { - cc.Component.EventHandler.emitEvents(this.webviewLoadedEvents, this, EventType.LOADED); - }, - - _onWebViewLoading: function () { - cc.Component.EventHandler.emitEvents(this.webviewLoadingEvents, this, EventType.LOADING); + cc.Component.EventHandler.emitEvents(this.webviewEvents, this, EventType.LOADED); return true; }, + _onWebViewLoading: function () { + cc.Component.EventHandler.emitEvents(this.webviewEvents, this, EventType.LOADING); + }, + _onWebViewLoadError: function () { - cc.Component.EventHandler.emitEvents(this.webviewErrorEvents, this, EventType.ERROR); + cc.Component.EventHandler.emitEvents(this.webviewEvents, this, EventType.ERROR); } }); From c35c13e60dcb3b7c4bd8cf34fcd9ae2c3f48527d Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Tue, 26 Jul 2016 22:35:57 +0800 Subject: [PATCH 049/268] add slide and step attribute --- cocos2d/core/components/CCProgressBar.js | 1 + cocos2d/core/platform/CCClass.js | 3 ++- cocos2d/core/platform/attribute.js | 5 ----- 3 files changed, 3 insertions(+), 6 deletions(-) diff --git a/cocos2d/core/components/CCProgressBar.js b/cocos2d/core/components/CCProgressBar.js index 39945f2c7d..ef2e34cecc 100644 --- a/cocos2d/core/components/CCProgressBar.js +++ b/cocos2d/core/components/CCProgressBar.js @@ -244,6 +244,7 @@ var ProgressBar = cc.Class({ default: 1, type: 'Float', range: [0, 1, 0.1], + slide: true, tooltip: 'i18n:COMPONENT.progress.progress', notify: function() { this._updateBarStatus(); diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index a1e9220408..14a509e95e 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -1078,6 +1078,7 @@ function parseAttributes (attrs, className, propName) { parseSimpleAttr('multiline', 'boolean', {multiline: true}); parseSimpleAttr('readonly', 'boolean', {readonly: true}); parseSimpleAttr('tooltip', 'string'); + parseSimpleAttr('slide', 'boolean'); } if (attrs.url) { @@ -1115,7 +1116,7 @@ function parseAttributes (attrs, className, propName) { if (range) { if (Array.isArray(range)) { if (range.length >= 2) { - result.push(Attr.Range(range[0], range[1])); + result.push({ min: range[0], max: range[1], step: range[2] }); } else if (CC_DEV) { cc.error('The length of range array must be 2'); diff --git a/cocos2d/core/platform/attribute.js b/cocos2d/core/platform/attribute.js index cefd57fac9..ec6625a082 100644 --- a/cocos2d/core/platform/attribute.js +++ b/cocos2d/core/platform/attribute.js @@ -351,10 +351,6 @@ function RawType (typename) { }; } -function Range (min, max) { - return { min: min, max: max }; -} - module.exports = { attr: attr, getClassAttrs: getClassAttrs, @@ -366,5 +362,4 @@ module.exports = { ObjectType: ObjectType, RawType: RawType, ScriptUuid: {}, // the value will be represented as a uuid string - Range: Range }; From c48e18cd5f70c1b00679d4af08d4728e2590f8f1 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Wed, 27 Jul 2016 10:02:51 +0800 Subject: [PATCH 050/268] fix load prefab bug for fireball/issues/3749 --- cocos2d/core/load-pipeline/loading-items.js | 8 +++++--- cocos2d/core/load-pipeline/pipeline.js | 10 +++++----- cocos2d/core/load-pipeline/uuid-loader.js | 2 +- test/qunit/unit/test-loader.js | 2 +- 4 files changed, 12 insertions(+), 10 deletions(-) diff --git a/cocos2d/core/load-pipeline/loading-items.js b/cocos2d/core/load-pipeline/loading-items.js index 11751add22..915661533f 100644 --- a/cocos2d/core/load-pipeline/loading-items.js +++ b/cocos2d/core/load-pipeline/loading-items.js @@ -100,9 +100,11 @@ JS.mixin(LoadingItems.prototype, CallbacksInvoker.prototype, { var item = items[i]; var id = item.id; // No duplicated url - if (!this.map[id]) { - this.map[item.id] = item; - list.push(item); + if (!this.completed[id]) { + if (!this.map[id]) { + this.map[id] = item; + } + list.push(this.map[id]); } } this.totalCount += list.length; diff --git a/cocos2d/core/load-pipeline/pipeline.js b/cocos2d/core/load-pipeline/pipeline.js index 27e962969d..b4be3f11c7 100644 --- a/cocos2d/core/load-pipeline/pipeline.js +++ b/cocos2d/core/load-pipeline/pipeline.js @@ -351,7 +351,7 @@ JS.mixin(Pipeline.prototype, { * @param {Function} callback * @return {Array} Items accepted by the pipeline */ - flowInDeps: function (urlList, callback) { + flowInDeps: function (owner, urlList, callback) { var checker = {}; var items = this._items; @@ -375,12 +375,12 @@ JS.mixin(Pipeline.prototype, { continue; } var item = items.map[url]; - if ( !item ) { - items.addListener(url, loadedCheck); - checker[url] = null; + if ( item && (url === owner || item.complete) ) { + checker[url] = item; } else { - checker[url] = item; + items.addListener(url, loadedCheck); + checker[url] = null; } } var accepted = this.flowIn(urlList); diff --git a/cocos2d/core/load-pipeline/uuid-loader.js b/cocos2d/core/load-pipeline/uuid-loader.js index a074f4e931..91aad4f303 100644 --- a/cocos2d/core/load-pipeline/uuid-loader.js +++ b/cocos2d/core/load-pipeline/uuid-loader.js @@ -97,7 +97,7 @@ function loadDepends (pipeline, item, asset, tdInfo, deferredLoadRawAssetsInRunt return callback(null, asset); } - pipeline.flowInDeps(depends, function (items) { + pipeline.flowInDeps(uuid, depends, function (items) { var item; for (var src in items) { item = items[src]; diff --git a/test/qunit/unit/test-loader.js b/test/qunit/unit/test-loader.js index e0631a6b89..92be410e25 100644 --- a/test/qunit/unit/test-loader.js +++ b/test/qunit/unit/test-loader.js @@ -83,7 +83,7 @@ asyncTest('Load with dependencies', function () { dep2, dep3 ]; - this.pipeline.flowInDeps(resources, function (deps) { + this.pipeline.flowInDeps(item.id, resources, function (deps) { callback(null, result); }); } From ca07275bb4ff05096d2ede35bd2ee55e9fd3ff3e Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Wed, 27 Jul 2016 11:07:20 +0800 Subject: [PATCH 051/268] add eslint --- .eslintrc.json | 24 ++++++++++++++++++++++++ cocos2d/core/components/CCWebView.js | 2 +- 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 .eslintrc.json diff --git a/.eslintrc.json b/.eslintrc.json new file mode 100644 index 0000000000..acc0572d31 --- /dev/null +++ b/.eslintrc.json @@ -0,0 +1,24 @@ +{ + "extends": "eslint:recommended", + "rules": { + "comma-dangle": 0, + "no-console": 0, + "no-constant-condition": 0, + "semi": 1 + }, + "env": { + "browser": true, + "node": true, + "es6": true, + "mocha": true + }, + "plugins": [ + ], + "globals": { + "cc": false, + "CC_EDITOR": false, + "CC_DEV": false, + "CC_JSB": false, + "_ccsg": false + } +} diff --git a/cocos2d/core/components/CCWebView.js b/cocos2d/core/components/CCWebView.js index 6049f31c35..cddc3c8274 100644 --- a/cocos2d/core/components/CCWebView.js +++ b/cocos2d/core/components/CCWebView.js @@ -23,7 +23,7 @@ /** * !#en WebView event type - * !#zh 网页视图加载事件类型 + * !#zh 网页视图事件类型 * @enum WebView.EventType */ var EventType = _ccsg.WebView.EventType; From 9ecc4d226ba083fb189b5ad074387188e3a25693 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Wed, 27 Jul 2016 12:51:08 +0800 Subject: [PATCH 052/268] =?UTF-8?q?fix=20cc.hide=E3=80=81cc.show=E3=80=81c?= =?UTF-8?q?c.toggleVisibility=20Web=20no=20effect=20for=20issues/3698?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos2d/actions/CCActionInstant.js | 18 ++++++++++++++--- cocos2d/core/CCNode.js | 1 + cocos2d/core/components/CCComponent.js | 4 ++-- jsb/jsb-action.js | 27 ++++++++++++++++++++++++++ test/qunit/unit/test-node.js | 23 ++++++++++++++++++++-- 5 files changed, 66 insertions(+), 7 deletions(-) diff --git a/cocos2d/actions/CCActionInstant.js b/cocos2d/actions/CCActionInstant.js index 4c324b92ba..37b3686aa2 100644 --- a/cocos2d/actions/CCActionInstant.js +++ b/cocos2d/actions/CCActionInstant.js @@ -75,7 +75,11 @@ cc.ActionInstant = cc.FiniteTimeAction.extend({ cc.Show = cc.ActionInstant.extend({ update:function (dt) { - this.target.visible = true; + var _renderComps = this.target.getComponentsInChildren(cc._SGComponent); + for (var i = 0; i < _renderComps.length; ++i) { + var render = _renderComps[i]; + render.enabled = true; + } }, reverse:function () { @@ -108,7 +112,11 @@ cc.show = function () { cc.Hide = cc.ActionInstant.extend({ update:function (dt) { - this.target.visible = false; + var _renderComps = this.target.getComponentsInChildren(cc._SGComponent); + for (var i = 0; i < _renderComps.length; ++i) { + var render = _renderComps[i]; + render.enabled = false; + } }, reverse:function () { @@ -141,7 +149,11 @@ cc.hide = function () { cc.ToggleVisibility = cc.ActionInstant.extend({ update:function (dt) { - this.target.visible = !this.target.visible; + var _renderComps = this.target.getComponentsInChildren(cc._SGComponent); + for (var i = 0; i < _renderComps.length; ++i) { + var render = _renderComps[i]; + render.enabled = !render.enabled; + } }, reverse:function () { diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index c5910124e6..026a5dcb6c 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -645,6 +645,7 @@ var Node = cc.Class({ getComponentsInChildren: function (typeOrClassName) { var constructor = getConstructor(typeOrClassName), components = []; if (constructor) { + findComponents(this, constructor, components); findChildComponents(this._children, constructor, components); } return components; diff --git a/cocos2d/core/components/CCComponent.js b/cocos2d/core/components/CCComponent.js index 27a27790aa..ecb86cfd9c 100644 --- a/cocos2d/core/components/CCComponent.js +++ b/cocos2d/core/components/CCComponent.js @@ -550,8 +550,8 @@ var Component = cc.Class({ }, /** - * !#en Returns the components of supplied type in any of its children using depth first search. - * !#zh 递归查找所有子节点中指定类型的组件。 + * !#en Returns the components of supplied type in self and any of its children using depth first search. + * !#zh 递归查找所有子节点中指定类型的组件(包含自身)。 * * @method getComponentsInChildren * @param {Function|String} typeOrClassName diff --git a/jsb/jsb-action.js b/jsb/jsb-action.js index f2f0659f6f..a7f4cddaad 100644 --- a/jsb/jsb-action.js +++ b/jsb/jsb-action.js @@ -123,6 +123,33 @@ cc.Follow.prototype.update = function(dt) { } }; +cc.Show.prototype.update = function (dt) { + var target = this.getTarget(); + var _renderComps = target._owner.getComponentsInChildren(); + for (var i = 0; i < _renderComps.length; ++i) { + var render = _renderComps[i]; + render.enabled = true; + } +}; + +cc.Hide.prototype.update = function (dt) { + var target = this.getTarget(); + var _renderComps = target._owner.getComponentsInChildren(); + for (var i = 0; i < _renderComps.length; ++i) { + var render = _renderComps[i]; + render.enabled = false; + } +}; + +cc.ToggleVisibility.prototype.update = function (dt) { + var target = this.getTarget(); + var _renderComps = target._owner.getComponentsInChildren(); + for (var i = 0; i < _renderComps.length; ++i) { + var render = _renderComps[i]; + render.enabled = true; + } +}; + // Special call func cc.callFunc = function (selector, selectorTarget, data) { var callback = function (sender, data) { diff --git a/test/qunit/unit/test-node.js b/test/qunit/unit/test-node.js index cd36278ad8..03b75e519d 100644 --- a/test/qunit/unit/test-node.js +++ b/test/qunit/unit/test-node.js @@ -183,7 +183,7 @@ test('get self components', function () { ok(obj.getComponents(MyComponent).length === 3, 'getComponents: can get my component array'); ok(obj.getComponentInChildren(MyComponent) === comp, 'getComponentInChildren: can get my component in children'); - ok(obj.getComponentsInChildren(MyComponent).length === 2, 'getComponentsInChildren: can get my components in children'); + ok(obj.getComponentsInChildren(MyComponent).length === 5, 'getComponentsInChildren: can get my components in children and self'); cc.js.unregisterClass(MyComponent); }); @@ -205,7 +205,26 @@ test('should not include self component', function () { obj1.parent = obj; ok(obj.getComponentInChildren(MyComponent) === null, 'getComponentInChildren should not include self component'); - ok(obj.getComponentsInChildren(MyComponent).length === 0, 'getComponentsInChildren should not include self component'); + + cc.js.unregisterClass(MyComponent); +}); + +test('should include self component', function () { + var MyComponent = cc.Class({ + name: 'MyComponent', + extends: cc.Component + }); + + var obj = new cc.Node("New Node"); + cc.director.getScene().addChild(obj); + obj.addComponent(MyComponent); + obj.addComponent(MyComponent); + obj.addComponent(MyComponent); + + var obj1 = new cc.Node("New Node 1"); + obj1.parent = obj; + + ok(obj.getComponentsInChildren(MyComponent).length === 3, 'getComponentsInChildren should include self component'); cc.js.unregisterClass(MyComponent); }); From 049987b3e22ab0a645642937667e23be3671b2d7 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Wed, 27 Jul 2016 13:48:08 +0800 Subject: [PATCH 053/268] update getComponentsInChildren API --- cocos2d/core/CCNode.js | 4 ++-- cocos2d/core/components/CCComponent.js | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index 026a5dcb6c..a0ff8c0fb1 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -633,8 +633,8 @@ var Node = cc.Class({ }, /** - * !#en Returns all components of supplied type in any of its children. - * !#zh 递归查找所有子节点中指定类型的组件。 + * !#en Returns all components of supplied type in self or any of its children. + * !#zh 递归查找自身或所有子节点中指定类型的组件 * @method getComponentsInChildren * @param {Function|String} typeOrClassName * @return {Component[]} diff --git a/cocos2d/core/components/CCComponent.js b/cocos2d/core/components/CCComponent.js index ecb86cfd9c..0c0d70444c 100644 --- a/cocos2d/core/components/CCComponent.js +++ b/cocos2d/core/components/CCComponent.js @@ -550,8 +550,8 @@ var Component = cc.Class({ }, /** - * !#en Returns the components of supplied type in self and any of its children using depth first search. - * !#zh 递归查找所有子节点中指定类型的组件(包含自身)。 + * !#en Returns the components of supplied type in self or any of its children using depth first search. + * !#zh 递归查找自身或所有子节点中指定类型的组件 * * @method getComponentsInChildren * @param {Function|String} typeOrClassName From 6bcc1154a8e63d274bf45d5e1e5e1e44d3d74165 Mon Sep 17 00:00:00 2001 From: 2youyouo2 <501251991@qq.com> Date: Wed, 27 Jul 2016 14:23:52 +0800 Subject: [PATCH 054/268] fixed crash on runtime --- cocos2d/core/graphics/graphics.js | 15 +++++++++++++++ cocos2d/core/graphics/index.js | 6 ++++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/graphics/graphics.js b/cocos2d/core/graphics/graphics.js index d9af550be5..fa064ad0b9 100644 --- a/cocos2d/core/graphics/graphics.js +++ b/cocos2d/core/graphics/graphics.js @@ -26,6 +26,17 @@ var LineCap = require('./types').LineCap; var LineJoin = require('./types').LineJoin; +var func = function () {}; + +function createEmptyGraphicsNode () { + var sgNode = new _ccsg.Node(); + ['moveTo', 'lineTo', 'bezierCurveTo', 'quadraticCurveTo', 'arc', 'ellipse', 'circle', 'rect', 'roundRect', 'fillRect', 'clear', 'close', 'stroke', 'fill'].forEach(function (funcName) { + sgNode[funcName] = func; + }); + + return sgNode; +} + /** * @class Graphics * @extends _RendererUnderSG @@ -157,6 +168,10 @@ var Graphics = cc.Class({ }, _createSgNode: function () { + if (!_ccsg.GraphicsNode) { + return createEmptyGraphicsNode(); + } + return new _ccsg.GraphicsNode(); }, diff --git a/cocos2d/core/graphics/index.js b/cocos2d/core/graphics/index.js index fbe7f1d045..1568a23953 100644 --- a/cocos2d/core/graphics/index.js +++ b/cocos2d/core/graphics/index.js @@ -33,7 +33,9 @@ else { GraphicsNode = _ccsg.GraphicsNode = cc.GraphicsNode; } -var misc = require('../utils/misc'); -misc.propertyDefine(GraphicsNode, ['lineWidth', 'lineCap', 'lineJoin', 'miterLimit', 'deviceRatio', 'strokeColor', 'fillColor'], {}); +if (GraphicsNode) { + var misc = require('../utils/misc'); + misc.propertyDefine(GraphicsNode, ['lineWidth', 'lineCap', 'lineJoin', 'miterLimit', 'deviceRatio', 'strokeColor', 'fillColor'], {}); +} require('./graphics'); From 13e57288c4b2427a0ecbb30ac993989c00c5e9b3 Mon Sep 17 00:00:00 2001 From: 2youyouo2 <501251991@qq.com> Date: Wed, 27 Jul 2016 15:25:03 +0800 Subject: [PATCH 055/268] refine code --- cocos2d/core/graphics/graphics.js | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/cocos2d/core/graphics/graphics.js b/cocos2d/core/graphics/graphics.js index fa064ad0b9..3b803ca37f 100644 --- a/cocos2d/core/graphics/graphics.js +++ b/cocos2d/core/graphics/graphics.js @@ -26,13 +26,11 @@ var LineCap = require('./types').LineCap; var LineJoin = require('./types').LineJoin; -var func = function () {}; + function createEmptyGraphicsNode () { var sgNode = new _ccsg.Node(); - ['moveTo', 'lineTo', 'bezierCurveTo', 'quadraticCurveTo', 'arc', 'ellipse', 'circle', 'rect', 'roundRect', 'fillRect', 'clear', 'close', 'stroke', 'fill'].forEach(function (funcName) { - sgNode[funcName] = func; - }); + return sgNode; } @@ -168,8 +166,13 @@ var Graphics = cc.Class({ }, _createSgNode: function () { - if (!_ccsg.GraphicsNode) { - return createEmptyGraphicsNode(); + if (CC_JSB && !_ccsg.GraphicsNode) { + var sgNode = new _ccsg.Node(); + var func = function () {}; + ['moveTo', 'lineTo', 'bezierCurveTo', 'quadraticCurveTo', 'arc', 'ellipse', 'circle', 'rect', 'roundRect', 'fillRect', 'clear', 'close', 'stroke', 'fill'].forEach(function (funcName) { + sgNode[funcName] = func; + }); + return sgNode; } return new _ccsg.GraphicsNode(); From 382c1f1014eb76b60b9581f8e4363679adb9869d Mon Sep 17 00:00:00 2001 From: 2youyouo2 <501251991@qq.com> Date: Wed, 27 Jul 2016 15:25:57 +0800 Subject: [PATCH 056/268] refine code --- cocos2d/core/graphics/graphics.js | 8 -------- 1 file changed, 8 deletions(-) diff --git a/cocos2d/core/graphics/graphics.js b/cocos2d/core/graphics/graphics.js index 3b803ca37f..726b22c6da 100644 --- a/cocos2d/core/graphics/graphics.js +++ b/cocos2d/core/graphics/graphics.js @@ -27,14 +27,6 @@ var LineCap = require('./types').LineCap; var LineJoin = require('./types').LineJoin; - -function createEmptyGraphicsNode () { - var sgNode = new _ccsg.Node(); - - - return sgNode; -} - /** * @class Graphics * @extends _RendererUnderSG From 408519bbace671e46937cea8ff361a219a858f7a Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Wed, 27 Jul 2016 15:12:30 +0800 Subject: [PATCH 057/268] fix ttf dynamic load issue on jsb --- jsb/jsb-label.js | 32 +++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/jsb/jsb-label.js b/jsb/jsb-label.js index c24c112478..f8ef6d264b 100644 --- a/jsb/jsb-label.js +++ b/jsb/jsb-label.js @@ -119,6 +119,16 @@ jsbLabel.prototype.setFontFileOrFamily = function (fontHandle) { } else { if (extName === '.ttf') { + if(!this._ttfConfig) { + this._ttfConfig = { + fontFilePath: fontHandle, + fontSize: 40, + outlineSize: 0, + glyphs: 0, + customGlyphs: "", + distanceFieldEnable: false + }; + } this._labelType = _ccsg.Label.Type.TTF; this._ttfConfig.fontFilePath = fontHandle; this.setTTFConfig(this._ttfConfig); @@ -133,8 +143,8 @@ jsbLabel.prototype.setFontFileOrFamily = function (fontHandle) { }; jsbLabel.prototype.setOutlined = function(value) { - this._outlined = value; - if(!!this._outlined) { + this._outlined = !!value; + if(this._outlined) { this.enableOutline(this.getOutlineColor(), this.getOutlineWidth()); } else { //1 equals cpp outline effect @@ -144,31 +154,31 @@ jsbLabel.prototype.setOutlined = function(value) { jsbLabel.prototype.setOutlineWidth = function(value) { this._outlineWidth = value; - if(!!this._outlined) { + if(this._outlined) { this.enableOutline(this.getOutlineColor(), this.getOutlineWidth()); } }; jsbLabel.prototype.setOutlineColor = function(value) { this._outlineColor = cc.color(value); - if(!!this._outlined) { + if(this._outlined) { this.enableOutline(this.getOutlineColor(), this.getOutlineWidth()); } }; -jsbLabel.prototype.setMargin = function(value) { +jsbLabel.prototype.setMargin = function() { //add an empty here, needed to be implemented by native -} - -jsbLabel.prototype.isOutlined = function(value) { - return !!this._outlined; }; -jsbLabel.prototype.getOutlineWidth = function(value) { +jsbLabel.prototype.isOutlined = function() { + return this._outlined; +}; + +jsbLabel.prototype.getOutlineWidth = function() { return this._outlineWidth || 1; }; -jsbLabel.prototype.getOutlineColor = function(value) { +jsbLabel.prototype.getOutlineColor = function() { return this._outlineColor || cc.color(255,255,255,255); }; From 51c52d5cc88666b2563a26e250747914243f5b10 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 27 Jul 2016 16:29:25 +0800 Subject: [PATCH 058/268] Create jsb_polyfill.js --- gulpfile.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/gulpfile.js b/gulpfile.js index 2309cec13d..2403c2b698 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -50,7 +50,7 @@ gulp.task('build-cut-modular', function (done) { }); gulp.task('build-modular-cocos2d', ['build-all-modular', 'build-cut-modular'], function (done) { - Del(['./bin/.cache'], done); + Del(['./bin/cocos2d-js.js', './bin/cocos2d-js-min.js', './bin/.cache'], done); }); @@ -142,12 +142,12 @@ gulp.task('test-no-build', function (done) { // global // //////////// -gulp.task('build-dev', ['build-preview', 'build-jsb-extends-dev'], function (done) { +gulp.task('build-dev', ['build-preview', 'build-jsb'], function (done) // make dist version dirty - Del(['./bin/cocos2d-js.js', './bin/cocos2d-js-min.js', './bin/jsb_polyfill.js', './bin/.cache'], done); + Del(['./bin/.cache'], done); }); -gulp.task('build', ['build-html5', 'build-preview', 'build-jsb-extends-min', 'build-jsb-extends-dev'], function (done) { +gulp.task('build', ['build-html5', 'build-preview', 'build-jsb'], function (done) { Del(['./bin/.cache'], done); }); From 55f688df557e8eedca79bcb4a9e617c3ff727baf Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 27 Jul 2016 16:51:12 +0800 Subject: [PATCH 059/268] unexpected identifier... --- gulpfile.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gulpfile.js b/gulpfile.js index 2403c2b698..7da5a86c95 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -142,7 +142,7 @@ gulp.task('test-no-build', function (done) { // global // //////////// -gulp.task('build-dev', ['build-preview', 'build-jsb'], function (done) +gulp.task('build-dev', ['build-preview', 'build-jsb'], function (done) { // make dist version dirty Del(['./bin/.cache'], done); }); From 3bbecf49b50c2f48191fc818fac3302c871031da Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Wed, 27 Jul 2016 17:40:27 +0800 Subject: [PATCH 060/268] fix JSB scheduleOnce will repeat for #fireball/issues/3768 --- jsb/jsb-etc.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jsb/jsb-etc.js b/jsb/jsb-etc.js index 96ee3674be..13036ea748 100644 --- a/jsb/jsb-etc.js +++ b/jsb/jsb-etc.js @@ -71,9 +71,9 @@ cc.js.mixin(cc.path, { // cc.Scheduler cc.Scheduler.prototype.schedule = function (callback, target, interval, repeat, delay, paused) { - repeat = repeat || cc.macro.REPEAT_FOREVER; + repeat = isFinite(repeat) ? repeat : cc.macro.REPEAT_FOREVER; delay = delay || 0; - paused = paused || false; + paused = !!paused; this.scheduleCallbackForTarget(target, callback, interval, repeat, delay, paused); }; cc.Scheduler.prototype.scheduleUpdate = cc.Scheduler.prototype.scheduleUpdateForTarget; From f605874747d816021bd9702b55702f17ac943130 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Wed, 27 Jul 2016 18:07:27 +0800 Subject: [PATCH 061/268] backing out loader code, Later refactoring --- cocos2d/core/load-pipeline/loading-items.js | 8 +++----- cocos2d/core/load-pipeline/pipeline.js | 10 +++++----- cocos2d/core/load-pipeline/uuid-loader.js | 2 +- test/qunit/unit/test-loader.js | 2 +- 4 files changed, 10 insertions(+), 12 deletions(-) diff --git a/cocos2d/core/load-pipeline/loading-items.js b/cocos2d/core/load-pipeline/loading-items.js index 915661533f..11751add22 100644 --- a/cocos2d/core/load-pipeline/loading-items.js +++ b/cocos2d/core/load-pipeline/loading-items.js @@ -100,11 +100,9 @@ JS.mixin(LoadingItems.prototype, CallbacksInvoker.prototype, { var item = items[i]; var id = item.id; // No duplicated url - if (!this.completed[id]) { - if (!this.map[id]) { - this.map[id] = item; - } - list.push(this.map[id]); + if (!this.map[id]) { + this.map[item.id] = item; + list.push(item); } } this.totalCount += list.length; diff --git a/cocos2d/core/load-pipeline/pipeline.js b/cocos2d/core/load-pipeline/pipeline.js index b4be3f11c7..27e962969d 100644 --- a/cocos2d/core/load-pipeline/pipeline.js +++ b/cocos2d/core/load-pipeline/pipeline.js @@ -351,7 +351,7 @@ JS.mixin(Pipeline.prototype, { * @param {Function} callback * @return {Array} Items accepted by the pipeline */ - flowInDeps: function (owner, urlList, callback) { + flowInDeps: function (urlList, callback) { var checker = {}; var items = this._items; @@ -375,13 +375,13 @@ JS.mixin(Pipeline.prototype, { continue; } var item = items.map[url]; - if ( item && (url === owner || item.complete) ) { - checker[url] = item; - } - else { + if ( !item ) { items.addListener(url, loadedCheck); checker[url] = null; } + else { + checker[url] = item; + } } var accepted = this.flowIn(urlList); // No new resources, complete directly diff --git a/cocos2d/core/load-pipeline/uuid-loader.js b/cocos2d/core/load-pipeline/uuid-loader.js index 91aad4f303..a074f4e931 100644 --- a/cocos2d/core/load-pipeline/uuid-loader.js +++ b/cocos2d/core/load-pipeline/uuid-loader.js @@ -97,7 +97,7 @@ function loadDepends (pipeline, item, asset, tdInfo, deferredLoadRawAssetsInRunt return callback(null, asset); } - pipeline.flowInDeps(uuid, depends, function (items) { + pipeline.flowInDeps(depends, function (items) { var item; for (var src in items) { item = items[src]; diff --git a/test/qunit/unit/test-loader.js b/test/qunit/unit/test-loader.js index 92be410e25..e0631a6b89 100644 --- a/test/qunit/unit/test-loader.js +++ b/test/qunit/unit/test-loader.js @@ -83,7 +83,7 @@ asyncTest('Load with dependencies', function () { dep2, dep3 ]; - this.pipeline.flowInDeps(item.id, resources, function (deps) { + this.pipeline.flowInDeps(resources, function (deps) { callback(null, result); }); } From a66ffa103787f3b769c62ea110f8f6856c2e40f4 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 27 Jul 2016 18:43:35 +0800 Subject: [PATCH 062/268] Inline director.render function to improve performance --- cocos2d/core/CCDirector.js | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js index 823368e23f..4ef8ead898 100644 --- a/cocos2d/core/CCDirector.js +++ b/cocos2d/core/CCDirector.js @@ -296,16 +296,6 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ this._afterVisitScene(); }, - render: function (deltaTime) { - cc.g_NumberOfDraws = 0; - cc.renderer.clear(); - - cc.renderer.rendering(cc._renderContext); - this._totalFrames++; - - this.emit(cc.Director.EVENT_AFTER_DRAW); - }, - _beforeVisitScene: null, _afterVisitScene: null, @@ -1389,7 +1379,16 @@ cc.DisplayLinkDirector = cc.Director.extend(/** @lends cc.Director# */{ } this.visit(); - this.render(); + + // Render + cc.g_NumberOfDraws = 0; + cc.renderer.clear(); + + cc.renderer.rendering(cc._renderContext); + this._totalFrames++; + + this.emit(cc.Director.EVENT_AFTER_DRAW); + } : function () { if (this._purgeDirectorInNextLoop) { this._purgeDirectorInNextLoop = false; @@ -1421,7 +1420,15 @@ cc.DisplayLinkDirector = cc.Director.extend(/** @lends cc.Director# */{ } this.visit(this._deltaTime); - this.render(this._deltaTime); + + // Render + cc.g_NumberOfDraws = 0; + cc.renderer.clear(); + + cc.renderer.rendering(cc._renderContext); + this._totalFrames++; + + this.emit(cc.Director.EVENT_AFTER_DRAW); this._calculateMPF(); } From 4a26532dfe91efcd76e44512bac0ebde6c806447 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 27 Jul 2016 18:44:00 +0800 Subject: [PATCH 063/268] Inline Scale9Sprite.WebGLRenderCmd._uploadVertices --- .../sprites/CCScale9SpriteWebGLRenderCmd.js | 27 ++++++++----------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/cocos2d/core/sprites/CCScale9SpriteWebGLRenderCmd.js b/cocos2d/core/sprites/CCScale9SpriteWebGLRenderCmd.js index 9346fab5f8..202e755255 100644 --- a/cocos2d/core/sprites/CCScale9SpriteWebGLRenderCmd.js +++ b/cocos2d/core/sprites/CCScale9SpriteWebGLRenderCmd.js @@ -85,21 +85,6 @@ proto._uploadSliced = function (vertices, uvs, color, z, f32buffer, ui32buffer, return 36; }; -proto._uploadVertices = function (vertices, uvs, color, z, f32buffer, ui32buffer, offset) { - // src: bl, br, tl, tr - var count = this._node._vertCount; - for (var i = 0, srcOff = 0; i < count; i++, srcOff += 2) { - f32buffer[offset] = vertices[srcOff]; - f32buffer[offset + 1] = vertices[srcOff+1]; - f32buffer[offset + 2] = z; - ui32buffer[offset + 3] = color[0]; - f32buffer[offset + 4] = uvs[srcOff]; - f32buffer[offset + 5] = uvs[srcOff+1]; - offset += 6; - } - return count; -}; - proto.transform = function (parentCmd, recursive) { this.originTransform(parentCmd, recursive); this._node._rebuildQuads(); @@ -151,7 +136,17 @@ proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset){ case types.SIMPLE: case types.TILED: case types.FILLED: - len = this._uploadVertices(vertices, uvs, this._color, z, f32buffer, ui32buffer, offset); + // Inline for performance + len = this._node._vertCount; + for (var i = 0, srcOff = 0; i < len; i++, srcOff += 2) { + f32buffer[offset] = vertices[srcOff]; + f32buffer[offset + 1] = vertices[srcOff+1]; + f32buffer[offset + 2] = z; + ui32buffer[offset + 3] = this._color[0]; + f32buffer[offset + 4] = uvs[srcOff]; + f32buffer[offset + 5] = uvs[srcOff+1]; + offset += 6; + } break; case types.SLICED: len = this._uploadSliced(vertices, uvs, this._color, z, f32buffer, ui32buffer, offset); From 5dc8655eff921a3fd0162f0a933561520bbc9f26 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 27 Jul 2016 18:44:33 +0800 Subject: [PATCH 064/268] Inline EventTarget _doSendEvent and reuse EventCustom --- cocos2d/core/event/event-target.js | 50 ++++++++++++++++++------------ cocos2d/core/event/event.js | 13 +++++++- 2 files changed, 43 insertions(+), 20 deletions(-) diff --git a/cocos2d/core/event/event-target.js b/cocos2d/core/event/event-target.js index 7e825896e6..dc5d55772b 100644 --- a/cocos2d/core/event/event-target.js +++ b/cocos2d/core/event/event-target.js @@ -29,6 +29,9 @@ var JS = cc.js; var cachedArray = new Array(16); cachedArray.length = 0; +var eventPool = new Array(8); +eventPool.length = 0; + var _doDispatchEvent = function (owner, event) { var target, i; event.target = owner; @@ -56,7 +59,15 @@ var _doDispatchEvent = function (owner, event) { // Event.AT_TARGET // checks if destroyed in capturing callbacks if (owner._isTargetActive(event.type)) { - _doSendEvent(owner, event); + // Event.AT_TARGET + event.eventPhase = 2; + event.currentTarget = owner; + if (owner._capturingListeners) { + owner._capturingListeners.invoke(event); + } + if (!event._propagationImmediateStopped && owner._bubblingListeners) { + owner._bubblingListeners.invoke(event); + } } if (!event._propagationStopped && event.bubbles) { @@ -81,22 +92,6 @@ var _doDispatchEvent = function (owner, event) { cachedArray.length = 0; }; - -var _doSendEvent = function (owner, event) { - // Event.AT_TARGET - event.eventPhase = 2; - event.currentTarget = owner; - if (owner._capturingListeners) { - owner._capturingListeners.invoke(event); - if (event._propagationImmediateStopped) { - return; - } - } - if (owner._bubblingListeners) { - owner._bubblingListeners.invoke(event); - } -}; - /** * !#en * EventTarget is an object to which an event is dispatched when something has occurred. @@ -335,9 +330,26 @@ JS.mixin(EventTarget.prototype, { return; } - var event = new cc.Event.EventCustom(message); + var event = eventPool.pop() || new cc.Event.EventCustom(message); + event.type = message; event.detail = detail; - _doSendEvent(this, event); + + // Event.AT_TARGET + event.eventPhase = 2; + event.currentTarget = this; + if (caplisteners) { + this._capturingListeners.invoke(event); + } + if (bublisteners && !event._propagationImmediateStopped) { + this._bubblingListeners.invoke(event); + } + + // Reuse custom event + if (!event.keep) { + event.type = ''; + event.detail = null; + eventPool.push(event); + } }, /* diff --git a/cocos2d/core/event/event.js b/cocos2d/core/event/event.js index 47e887084b..875a68f30e 100644 --- a/cocos2d/core/event/event.js +++ b/cocos2d/core/event/event.js @@ -53,7 +53,7 @@ cc.Event = function(type, bubbles) { * @property bubbles * @type {Boolean} */ - this.bubbles = bubbles || false; + this.bubbles = !!bubbles; /** * !#en A reference to the target to which the event was originally dispatched. @@ -261,6 +261,17 @@ var EventCustom = function (type, bubbles) { * @type {Object} */ this.detail = null; + + /** + * !#en Flag to indicate whether keep the event object alive after processing, + * value is false by default, the event shouldn't be used outside event handler logic, + * because it will be cached and reused for other event handling process. + * !#zh 用于标记是否在事件处理结束后保持事件对象可用,默认值是 false, + * 表示事件处理完成后,会立即回收事件对象并留待后续复用。如果设置为 true,则不会回收。 + * @property keep + * @type {Boolean} + */ + this.keep = false; }; JS.extend(EventCustom, cc.Event); From 88481c0853ac17c84155ada2276a08171aec937e Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 27 Jul 2016 19:01:17 +0800 Subject: [PATCH 065/268] Revert reuse EventCustom --- cocos2d/core/event/event-target.js | 13 +------------ cocos2d/core/event/event.js | 11 ----------- 2 files changed, 1 insertion(+), 23 deletions(-) diff --git a/cocos2d/core/event/event-target.js b/cocos2d/core/event/event-target.js index dc5d55772b..dc0b3a82ac 100644 --- a/cocos2d/core/event/event-target.js +++ b/cocos2d/core/event/event-target.js @@ -29,9 +29,6 @@ var JS = cc.js; var cachedArray = new Array(16); cachedArray.length = 0; -var eventPool = new Array(8); -eventPool.length = 0; - var _doDispatchEvent = function (owner, event) { var target, i; event.target = owner; @@ -330,8 +327,7 @@ JS.mixin(EventTarget.prototype, { return; } - var event = eventPool.pop() || new cc.Event.EventCustom(message); - event.type = message; + var event = new cc.Event.EventCustom(message); event.detail = detail; // Event.AT_TARGET @@ -343,13 +339,6 @@ JS.mixin(EventTarget.prototype, { if (bublisteners && !event._propagationImmediateStopped) { this._bubblingListeners.invoke(event); } - - // Reuse custom event - if (!event.keep) { - event.type = ''; - event.detail = null; - eventPool.push(event); - } }, /* diff --git a/cocos2d/core/event/event.js b/cocos2d/core/event/event.js index 875a68f30e..73c30d686f 100644 --- a/cocos2d/core/event/event.js +++ b/cocos2d/core/event/event.js @@ -261,17 +261,6 @@ var EventCustom = function (type, bubbles) { * @type {Object} */ this.detail = null; - - /** - * !#en Flag to indicate whether keep the event object alive after processing, - * value is false by default, the event shouldn't be used outside event handler logic, - * because it will be cached and reused for other event handling process. - * !#zh 用于标记是否在事件处理结束后保持事件对象可用,默认值是 false, - * 表示事件处理完成后,会立即回收事件对象并留待后续复用。如果设置为 true,则不会回收。 - * @property keep - * @type {Boolean} - */ - this.keep = false; }; JS.extend(EventCustom, cc.Event); From e525cb827c9d3cf9567229ed51a71dc6022f7704 Mon Sep 17 00:00:00 2001 From: Nan Wang Date: Wed, 27 Jul 2016 19:02:53 +0800 Subject: [PATCH 066/268] update engine version --- CCBoot.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CCBoot.js b/CCBoot.js index fa37f80cb1..ea96f5e13c 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -58,7 +58,7 @@ _p = null; * @name cc.ENGINE_VERSION */ var engineVersion; -engineVersion = '1.2.0-beta.2'; +engineVersion = '1.2.0-beta.3'; window['CocosEngine'] = cc.ENGINE_VERSION = engineVersion; /** From f0573d764e434f9b89a0dc1725f1b481f7d45c1b Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Thu, 28 Jul 2016 12:04:43 +0800 Subject: [PATCH 067/268] fix update color bug in _syncStatus --- cocos2d/core/base-nodes/CCSGNodeCanvasRenderCmd.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/base-nodes/CCSGNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCSGNodeCanvasRenderCmd.js index 1bd2bf5a2c..8b39908c18 100644 --- a/cocos2d/core/base-nodes/CCSGNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCSGNodeCanvasRenderCmd.js @@ -487,7 +487,7 @@ _ccsg.Node.RenderCmd.prototype = { //update the opacity this._syncDisplayOpacity(); - if(colorDirty) + if(colorDirty || opacityDirty) this._updateColor(); if (transformDirty) From b7c182181d583bdc3d0c466a099bb7ae552fedb5 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Thu, 28 Jul 2016 13:50:21 +0800 Subject: [PATCH 068/268] fix web spine Color has no effect --- extensions/spine/SGSkeletonCanvasRenderCmd.js | 5 +++-- extensions/spine/SGSkeletonWebGLRenderCmd.js | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/extensions/spine/SGSkeletonCanvasRenderCmd.js b/extensions/spine/SGSkeletonCanvasRenderCmd.js index c1bc03ab05..21081a582f 100644 --- a/extensions/spine/SGSkeletonCanvasRenderCmd.js +++ b/extensions/spine/SGSkeletonCanvasRenderCmd.js @@ -162,6 +162,7 @@ proto._createSprite = function(slot, attachment){ 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; @@ -218,8 +219,8 @@ proto._updateChild = function(){ } //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.a); + var r = 0 | (color.r * slot.r), g = 0 | (color.g * slot.g), b = 0 | (color.b * slot.b); selSprite.setColor(cc.color(r,g,b)); selSprite._renderCmd._updateColor(); } else if (type === spine.AttachmentType.skinnedmesh) { diff --git a/extensions/spine/SGSkeletonWebGLRenderCmd.js b/extensions/spine/SGSkeletonWebGLRenderCmd.js index 657806792c..979c321bed 100644 --- a/extensions/spine/SGSkeletonWebGLRenderCmd.js +++ b/extensions/spine/SGSkeletonWebGLRenderCmd.js @@ -39,7 +39,7 @@ proto.constructor = sp._SGSkeleton.WebGLRenderCmd; proto.rendering = function (ctx) { var node = this._node, tmpQuad = this._tmpQuad; - var color = node.getColor(), locSkeleton = node._skeleton; + var color = this._displayedColor, locSkeleton = node._skeleton; var textureAtlas, attachment, slot, i, n; var locBlendFunc = node._blendFunc; @@ -60,7 +60,7 @@ proto.rendering = function (ctx) { locSkeleton.r = color.r / 255; locSkeleton.g = color.g / 255; locSkeleton.b = color.b / 255; - locSkeleton.a = node.getOpacity() / 255; + locSkeleton.a = this._displayedOpacity / 255; if (premultiAlpha) { locSkeleton.r *= locSkeleton.a; locSkeleton.g *= locSkeleton.a; From 03af8f3be3d2efda7179c972348f918f781e8e09 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Thu, 28 Jul 2016 13:51:03 +0800 Subject: [PATCH 069/268] fix undo node.active --- cocos2d/core/utils/base-node.js | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/cocos2d/core/utils/base-node.js b/cocos2d/core/utils/base-node.js index 43e078f206..17270cb1e6 100644 --- a/cocos2d/core/utils/base-node.js +++ b/cocos2d/core/utils/base-node.js @@ -2055,6 +2055,13 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ } } + // check activity state + var shouldActiveInHierarchy = (this._parent && this._parent._activeInHierarchy && this._active); + if (shouldActiveInHierarchy !== this._activeInHierarchy) { + this._onActivatedInHierarchy(shouldActiveInHierarchy); + this.emit('active-in-hierarchy-changed', this); + } + if (this._activeInHierarchy) { cc.director.getActionManager().resumeTarget(this); cc.eventManager.resumeTarget(this); From 241f528c53565bfceef0ed7d9b7579b6df55cb08 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Thu, 28 Jul 2016 11:37:54 +0800 Subject: [PATCH 070/268] add 2px left padding to editbox --- cocos2d/core/editbox/CCSGEditBox.js | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/cocos2d/core/editbox/CCSGEditBox.js b/cocos2d/core/editbox/CCSGEditBox.js index 522d128799..8f5699f9a7 100644 --- a/cocos2d/core/editbox/CCSGEditBox.js +++ b/cocos2d/core/editbox/CCSGEditBox.js @@ -29,6 +29,7 @@ // 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) { @@ -565,7 +566,7 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; tmpEdTxt.style.display = 'none'; tmpEdTxt.style.position = "absolute"; tmpEdTxt.style.bottom = "0px"; - tmpEdTxt.style.left = "0px"; + tmpEdTxt.style.left = LEFT_PADDING + "px"; tmpEdTxt.style.className = "cocosEditBox"; tmpEdTxt.addEventListener('input', function () { @@ -645,7 +646,7 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; tmpEdTxt.style.display = 'none'; tmpEdTxt.style.position = "absolute"; tmpEdTxt.style.bottom = "0px"; - tmpEdTxt.style.left = "0px"; + tmpEdTxt.style.left = LEFT_PADDING + "px"; tmpEdTxt.style.className = "cocosEditBox"; tmpEdTxt.addEventListener('input', function () { @@ -719,21 +720,22 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; }; proto._updateLabelPosition = function (editBoxSize) { - this._textLabel.setContentSize(editBoxSize); + var labelContentSize = cc.size(editBoxSize.width - LEFT_PADDING, editBoxSize.height); + this._textLabel.setContentSize(labelContentSize); this._placeholderLabel.setLineHeight(editBoxSize.height); var placeholderLabelSize = this._placeholderLabel.getContentSize(); if (this._editBox._editBoxInputMode === InputMode.ANY){ - this._textLabel.setPosition(0, editBoxSize.height); - this._placeholderLabel.setPosition(0, editBoxSize.height); + this._textLabel.setPosition(LEFT_PADDING, editBoxSize.height); + this._placeholderLabel.setPosition(LEFT_PADDING, editBoxSize.height); this._placeholderLabel.setVerticalAlign(cc.VerticalTextAlignment.TOP); this._textLabel.setVerticalAlign(cc.VerticalTextAlignment.TOP); this._textLabel.enableWrapText(true); } else { this._textLabel.enableWrapText(false); - this._textLabel.setPosition(0, editBoxSize.height); - this._placeholderLabel.setPosition(0, (editBoxSize.height + placeholderLabelSize.height) / 2); + this._textLabel.setPosition(LEFT_PADDING, editBoxSize.height); + this._placeholderLabel.setPosition(LEFT_PADDING, (editBoxSize.height + placeholderLabelSize.height) / 2); this._placeholderLabel.setVerticalAlign(cc.VerticalTextAlignment.CENTER); this._textLabel.setVerticalAlign(cc.VerticalTextAlignment.CENTER); } From 99f6c6721abc789feb2f13a633555c509d2f0360 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Thu, 28 Jul 2016 16:51:33 +0800 Subject: [PATCH 071/268] fix editbox can't input when fullscreen --- cocos2d/core/editbox/CCSGEditBox.js | 20 ++++++++++++++++++++ cocos2d/core/platform/CCScreen.js | 2 +- cocos2d/core/platform/CCView.js | 1 - 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/editbox/CCSGEditBox.js b/cocos2d/core/editbox/CCSGEditBox.js index 522d128799..35fda217d6 100644 --- a/cocos2d/core/editbox/CCSGEditBox.js +++ b/cocos2d/core/editbox/CCSGEditBox.js @@ -600,6 +600,13 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; var editBox = thisPointer._editBox; 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); @@ -611,6 +618,9 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; var editBox = thisPointer._editBox; editBox._text = this.value; thisPointer._updateEditBoxContentStyle(); + if(thisPointer.__fullscreen) { + cc.view.enableAutoFullScreen(true); + } window.scrollY = 0; if (editBox._delegate && editBox._delegate.editBoxEditingDidEnded) { editBox._delegate.editBoxEditingDidEnded(editBox); @@ -662,6 +672,13 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; 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); @@ -686,6 +703,9 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; 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); diff --git a/cocos2d/core/platform/CCScreen.js b/cocos2d/core/platform/CCScreen.js index ebfbbb0fff..8af9cc3a92 100644 --- a/cocos2d/core/platform/CCScreen.js +++ b/cocos2d/core/platform/CCScreen.js @@ -80,7 +80,7 @@ cc.screen = /** @lends cc.screen# */{ */ init: function () { this._fn = {}; - var i, val, map = this._fnMap, valL; + var i, l, val, map = this._fnMap, valL; for (i = 0, l = map.length; i < l; i++) { val = map[i]; if (val && val[1] in document) { diff --git a/cocos2d/core/platform/CCView.js b/cocos2d/core/platform/CCView.js index b667c6f7ca..d8cb4cf851 100644 --- a/cocos2d/core/platform/CCView.js +++ b/cocos2d/core/platform/CCView.js @@ -171,7 +171,6 @@ var View = cc._Class.extend({ 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 From fba23137e0318a633357038b9b39b60085214994 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 28 Jul 2016 14:18:43 +0800 Subject: [PATCH 072/268] ScrollView send touch cancel when block inner content's touch event --- cocos2d/core/components/CCScrollView.js | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/cocos2d/core/components/CCScrollView.js b/cocos2d/core/components/CCScrollView.js index 41aafc378a..7fbf42afaa 100644 --- a/cocos2d/core/components/CCScrollView.js +++ b/cocos2d/core/components/CCScrollView.js @@ -846,17 +846,20 @@ var ScrollView = cc.Class({ if (this.content) { this._handleMoveLogic(touch); } - var deltaMove = touch.getDelta(); + var deltaMove = cc.pSub(touch.getLocation(), touch.getStartLocation()); //FIXME: touch move delta should be calculated by DPI. if (cc.pLength(deltaMove) > 7) { this._touchMoved = true; - var buttonComponent = event.target.getComponent(cc.Button); - if (buttonComponent) { - buttonComponent._onTouchCancel(); + if (event.target !== this.node) { + // Simulate touch cancel for target node + var cancelEvent = new cc.Event.EventTouch(event.getTouches(), event.bubbles); + cancelEvent.type = cc.Node.EventType.TOUCH_CANCEL; + cancelEvent.touch = event.touch; + cancelEvent.simulate = true; + event.target.dispatchEvent(cancelEvent); } + event.stopPropagation(); } - // TODO: detect move distance, if distance greater than a seuil, then stop propagation. - event.stopPropagation(); }, _onTouchEnded: function(event) { @@ -869,9 +872,12 @@ var ScrollView = cc.Class({ } }, _onTouchCancelled: function(event) { - var touch = event.touch; - if(this.content){ - this._handleReleaseLogic(touch); + // Filte touch cancel event send from self + if (!event.simulate) { + var touch = event.touch; + if(this.content){ + this._handleReleaseLogic(touch); + } } }, From 78f152477300ce7607327b289cc77a977a7a9c6d Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 28 Jul 2016 17:32:09 +0800 Subject: [PATCH 073/268] WebView visible --- cocos2d/core/webview/CCSGWebView.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/cocos2d/core/webview/CCSGWebView.js b/cocos2d/core/webview/CCSGWebView.js index f869d7a151..93b68907e1 100644 --- a/cocos2d/core/webview/CCSGWebView.js +++ b/cocos2d/core/webview/CCSGWebView.js @@ -188,6 +188,11 @@ _ccsg.WebView = _ccsg.Node.extend(/** @lends _ccsg.WebView# */{ this._renderCmd.removeDom(); this.stopAllActions(); this.unscheduleAllCallbacks(); + }, + + setVisible: function ( visible ) { + _ccsg.Node.prototype.setVisible.call(this, visible); + this._renderCmd.updateVisibility(); } }); @@ -318,6 +323,7 @@ _ccsg.WebView.EventType = { var self = this; var cb = function(){ self._loaded = true; + self.updateVisibility(); iframe.removeEventListener("load", cb); }; iframe.addEventListener("load", cb); @@ -375,4 +381,15 @@ _ccsg.WebView.EventType = { this._div = null; }; + proto.updateVisibility = function () { + var node = this._node; + if (!this._div) return; + var div = this._div; + if (node.visible) { + div.style.visibility = 'visible'; + } else { + div.style.visibility = 'hidden'; + } + }; + })(_ccsg.WebView._polyfill); From 522b695ee8fdbf189f1afb33284483d8041e3208 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Thu, 28 Jul 2016 17:48:42 +0800 Subject: [PATCH 074/268] fix webview loading error on iOS and Android --- cocos2d/core/components/CCWebView.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/components/CCWebView.js b/cocos2d/core/components/CCWebView.js index cddc3c8274..aa639de9a1 100644 --- a/cocos2d/core/components/CCWebView.js +++ b/cocos2d/core/components/CCWebView.js @@ -139,11 +139,11 @@ var WebView = cc.Class({ _onWebViewLoaded: function () { cc.Component.EventHandler.emitEvents(this.webviewEvents, this, EventType.LOADED); - return true; }, _onWebViewLoading: function () { cc.Component.EventHandler.emitEvents(this.webviewEvents, this, EventType.LOADING); + return true; }, _onWebViewLoadError: function () { From 31e7000d8e506d6bd12383542054be456ceebcbe Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 28 Jul 2016 18:21:54 +0800 Subject: [PATCH 075/268] Remove dom element --- cocos2d/core/editbox/CCSGEditBox.js | 9 +++++++++ cocos2d/core/videoplayer/CCSGVideoPlayer.js | 11 +++++++++++ cocos2d/core/webview/CCSGWebView.js | 12 ++++++++++++ 3 files changed, 32 insertions(+) diff --git a/cocos2d/core/editbox/CCSGEditBox.js b/cocos2d/core/editbox/CCSGEditBox.js index 522d128799..517d76ce8f 100644 --- a/cocos2d/core/editbox/CCSGEditBox.js +++ b/cocos2d/core/editbox/CCSGEditBox.js @@ -542,8 +542,17 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; var editBox = this._edTxt; if (node.visible) { editBox.style.visibility = 'visible'; + cc.container.appendChild(editBox); } else { editBox.style.visibility = 'hidden'; + var hasChild = false; + if('contains' in cc.container) { + hasChild = cc.container.contains(editBox); + }else { + hasChild = cc.container.compareDocumentPosition(editBox) % 16; + } + if(hasChild) + cc.container.removeChild(editBox); } }; diff --git a/cocos2d/core/videoplayer/CCSGVideoPlayer.js b/cocos2d/core/videoplayer/CCSGVideoPlayer.js index 3c6d984182..dcbbcd26ed 100644 --- a/cocos2d/core/videoplayer/CCSGVideoPlayer.js +++ b/cocos2d/core/videoplayer/CCSGVideoPlayer.js @@ -383,9 +383,20 @@ _ccsg.VideoPlayer.EventType = { var video = this._video; if (node.visible) { video.style.visibility = 'visible'; + cc.container.appendChild(video); } else { video.style.visibility = 'hidden'; video.pause(); + if(video){ + var hasChild = false; + if('contains' in cc.container) { + hasChild = cc.container.contains(video); + }else { + hasChild = cc.container.compareDocumentPosition(video) % 16; + } + if(hasChild) + cc.container.removeChild(video); + } } }; diff --git a/cocos2d/core/webview/CCSGWebView.js b/cocos2d/core/webview/CCSGWebView.js index 93b68907e1..d58c7bb983 100644 --- a/cocos2d/core/webview/CCSGWebView.js +++ b/cocos2d/core/webview/CCSGWebView.js @@ -238,6 +238,7 @@ _ccsg.WebView.EventType = { _ccsg.WebView.RenderCmd = function(node){ RenderCmd.call(this, node); + this._parent = null; this._div = null; this._iframe = null; this._listener = null; @@ -387,8 +388,19 @@ _ccsg.WebView.EventType = { var div = this._div; if (node.visible) { div.style.visibility = 'visible'; + cc.container.appendChild(div); } else { div.style.visibility = 'hidden'; + if(div){ + var hasChild = false; + if('contains' in cc.container) { + hasChild = cc.container.contains(div); + }else { + hasChild = cc.container.compareDocumentPosition(div) % 16; + } + if(hasChild) + cc.container.removeChild(div); + } } }; From d2fb320618f600eebc1a86757fc9d3ff3183c63a Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 28 Jul 2016 18:33:30 +0800 Subject: [PATCH 076/268] Block touch for ellipse mask and Improve rectApplyAffineTransform performance --- cocos2d/core/CCNode.js | 2 +- cocos2d/core/components/CCMask.js | 34 ++++++++++ cocos2d/core/value-types/CCAffineTransform.js | 63 ++++++++++--------- 3 files changed, 69 insertions(+), 30 deletions(-) diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index a0ff8c0fb1..37f0ac5661 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -1212,7 +1212,7 @@ var Node = cc.Class({ // find mask parent, should hit test it if (parent === mask.node) { var comp = parent.getComponent(cc.Mask); - return (comp && comp.enabledInHierarchy) ? parent._hitTest(point) : true; + return (comp && comp.enabledInHierarchy) ? comp._hitTest(point) : true; } // mask parent no longer exists else { diff --git a/cocos2d/core/components/CCMask.js b/cocos2d/core/components/CCMask.js index 4b93e78e17..3d6f28b019 100644 --- a/cocos2d/core/components/CCMask.js +++ b/cocos2d/core/components/CCMask.js @@ -120,6 +120,40 @@ var Mask = cc.Class({ _initSgNode: function () {}, + _hitTest: function (point) { + var size = this.node.getContentSize(), + w = size.width, + h = size.height, + trans = this.node.getNodeToWorldTransform(); + + if (this._type === MaskType.RECT) { + var rect = cc.rect(0, 0, w, h); + cc._rectApplyAffineTransformIn(rect, trans); + var left = point.x - rect.x, + right = rect.x + rect.width - point.x, + bottom = point.y - rect.y, + top = rect.y + rect.height - point.y; + if (left >= 0 && right >= 0 && top >= 0 && bottom >= 0) { + return true; + } + else { + return false; + } + } + else { + var a = w/2, b = h/2; + var cx = trans.a * a + trans.c * b + trans.tx; + var cy = trans.b * a + trans.d * b + trans.ty; + var px = point.x - cx, py = point.y - cy; + if (px * px / (a * a) + py * py / (b * b) < 1) { + return true; + } + else { + return false; + } + } + }, + onEnable: function () { this._refreshStencil(); this._super(); diff --git a/cocos2d/core/value-types/CCAffineTransform.js b/cocos2d/core/value-types/CCAffineTransform.js index 0dcd42023b..243bea76fb 100644 --- a/cocos2d/core/value-types/CCAffineTransform.js +++ b/cocos2d/core/value-types/CCAffineTransform.js @@ -154,40 +154,45 @@ cc.affineTransformIdentity = function () { * @param {AffineTransform} anAffineTransform * @return {Rect} */ -cc.rectApplyAffineTransform = function (rect, anAffineTransform) { - var top = cc.rectGetMinY(rect); - var left = cc.rectGetMinX(rect); - var right = cc.rectGetMaxX(rect); - var bottom = cc.rectGetMaxY(rect); - - var topLeft = cc.pointApplyAffineTransform(left, top, anAffineTransform); - var topRight = cc.pointApplyAffineTransform(right, top, anAffineTransform); - var bottomLeft = cc.pointApplyAffineTransform(left, bottom, anAffineTransform); - var bottomRight = cc.pointApplyAffineTransform(right, bottom, anAffineTransform); - - var minX = Math.min(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x); - var maxX = Math.max(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x); - var minY = Math.min(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y); - var maxY = Math.max(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y); +cc.rectApplyAffineTransform = function (rect, t) { + var ol = rect.x; + var ob = rect.y; + var or = ol + rect.width; + var ot = ob + rect.height; + var lbx = t.a * ol + t.c * ob + t.tx; + var lby = t.b * ol + t.d * ob + t.ty; + var rbx = t.a * or + t.c * ob + t.tx; + var rby = t.b * or + t.d * ob + t.ty; + var ltx = t.a * ol + t.c * ot + t.tx; + var lty = t.b * ol + t.d * ot + t.ty; + var rtx = t.a * or + t.c * ot + t.tx; + var rty = t.b * or + t.d * ot + t.ty; + var minX = Math.min(lbx, rbx, ltx, rtx); + var maxX = Math.max(lbx, rbx, ltx, rtx); + var minY = Math.min(lby, rby, lty, rty); + var maxY = Math.max(lby, rby, lty, rty); return cc.rect(minX, minY, (maxX - minX), (maxY - minY)); }; -cc._rectApplyAffineTransformIn = function(rect, anAffineTransform){ - var top = cc.rectGetMinY(rect); - var left = cc.rectGetMinX(rect); - var right = cc.rectGetMaxX(rect); - var bottom = cc.rectGetMaxY(rect); +cc._rectApplyAffineTransformIn = function(rect, t){ + var ol = rect.x; + var ob = rect.y; + var or = ol + rect.width; + var ot = ob + rect.height; + var lbx = t.a * ol + t.c * ob + t.tx; + var lby = t.b * ol + t.d * ob + t.ty; + var rbx = t.a * or + t.c * ob + t.tx; + var rby = t.b * or + t.d * ob + t.ty; + var ltx = t.a * ol + t.c * ot + t.tx; + var lty = t.b * ol + t.d * ot + t.ty; + var rtx = t.a * or + t.c * ot + t.tx; + var rty = t.b * or + t.d * ot + t.ty; - var topLeft = cc.pointApplyAffineTransform(left, top, anAffineTransform); - var topRight = cc.pointApplyAffineTransform(right, top, anAffineTransform); - var bottomLeft = cc.pointApplyAffineTransform(left, bottom, anAffineTransform); - var bottomRight = cc.pointApplyAffineTransform(right, bottom, anAffineTransform); - - var minX = Math.min(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x); - var maxX = Math.max(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x); - var minY = Math.min(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y); - var maxY = Math.max(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y); + var minX = Math.min(lbx, rbx, ltx, rtx); + var maxX = Math.max(lbx, rbx, ltx, rtx); + var minY = Math.min(lby, rby, lty, rty); + var maxY = Math.max(lby, rby, lty, rty); rect.x = minX; rect.y = minY; From 94c695faf2d1616609d8beaf952ec55f28c127ae Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 29 Jul 2016 13:38:33 +0800 Subject: [PATCH 077/268] cc.container -> cc.game.container; --- cocos2d/core/editbox/CCSGEditBox.js | 22 ++++++++++----------- cocos2d/core/videoplayer/CCSGVideoPlayer.js | 22 ++++++++++----------- cocos2d/core/webview/CCSGWebView.js | 22 ++++++++++----------- 3 files changed, 33 insertions(+), 33 deletions(-) diff --git a/cocos2d/core/editbox/CCSGEditBox.js b/cocos2d/core/editbox/CCSGEditBox.js index 517d76ce8f..1ce15d927d 100644 --- a/cocos2d/core/editbox/CCSGEditBox.js +++ b/cocos2d/core/editbox/CCSGEditBox.js @@ -515,7 +515,7 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; scaleX /= dpr; scaleY /= dpr; - var container = cc.container; + 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); @@ -542,17 +542,17 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; var editBox = this._edTxt; if (node.visible) { editBox.style.visibility = 'visible'; - cc.container.appendChild(editBox); + cc.game.container.appendChild(editBox); } else { editBox.style.visibility = 'hidden'; var hasChild = false; - if('contains' in cc.container) { - hasChild = cc.container.contains(editBox); + if('contains' in cc.game.container) { + hasChild = cc.game.container.contains(editBox); }else { - hasChild = cc.container.compareDocumentPosition(editBox) % 16; + hasChild = cc.game.container.compareDocumentPosition(editBox) % 16; } if(hasChild) - cc.container.removeChild(editBox); + cc.game.container.removeChild(editBox); } }; @@ -973,20 +973,20 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; }; proto._addDomInputControl = function () { - cc.container.appendChild(this._edTxt); + cc.game.container.appendChild(this._edTxt); }; proto._removeDomInputControl = function () { var editBox = this._edTxt; if(editBox){ var hasChild = false; - if('contains' in cc.container) { - hasChild = cc.container.contains(editBox); + if('contains' in cc.game.container) { + hasChild = cc.game.container.contains(editBox); }else { - hasChild = cc.container.compareDocumentPosition(editBox) % 16; + hasChild = cc.game.container.compareDocumentPosition(editBox) % 16; } if(hasChild) - cc.container.removeChild(editBox); + cc.game.container.removeChild(editBox); } this._edTxt = null; }; diff --git a/cocos2d/core/videoplayer/CCSGVideoPlayer.js b/cocos2d/core/videoplayer/CCSGVideoPlayer.js index dcbbcd26ed..9ec0d6287f 100644 --- a/cocos2d/core/videoplayer/CCSGVideoPlayer.js +++ b/cocos2d/core/videoplayer/CCSGVideoPlayer.js @@ -270,7 +270,7 @@ _ccsg.VideoPlayer.EventType = { scaleX /= dpr; scaleY /= dpr; - var container = cc.container; + 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); @@ -383,19 +383,19 @@ _ccsg.VideoPlayer.EventType = { var video = this._video; if (node.visible) { video.style.visibility = 'visible'; - cc.container.appendChild(video); + cc.game.container.appendChild(video); } else { video.style.visibility = 'hidden'; video.pause(); if(video){ var hasChild = false; - if('contains' in cc.container) { - hasChild = cc.container.contains(video); + if('contains' in cc.game.container) { + hasChild = cc.game.container.contains(video); }else { - hasChild = cc.container.compareDocumentPosition(video) % 16; + hasChild = cc.game.container.compareDocumentPosition(video) % 16; } if(hasChild) - cc.container.removeChild(video); + cc.game.container.removeChild(video); } } }; @@ -408,20 +408,20 @@ _ccsg.VideoPlayer.EventType = { video.className = "cocosVideo"; video.setAttribute('preload', true); this._video = video; - cc.container.appendChild(video); + cc.game.container.appendChild(video); }; proto.removeDom = function () { var video = this._video; if(video){ var hasChild = false; - if('contains' in cc.container) { - hasChild = cc.container.contains(video); + if('contains' in cc.game.container) { + hasChild = cc.game.container.contains(video); }else { - hasChild = cc.container.compareDocumentPosition(video) % 16; + hasChild = cc.game.container.compareDocumentPosition(video) % 16; } if(hasChild) - cc.container.removeChild(video); + cc.game.container.removeChild(video); } this._video = null; this._url = ""; diff --git a/cocos2d/core/webview/CCSGWebView.js b/cocos2d/core/webview/CCSGWebView.js index d58c7bb983..7973a86a1f 100644 --- a/cocos2d/core/webview/CCSGWebView.js +++ b/cocos2d/core/webview/CCSGWebView.js @@ -296,7 +296,7 @@ _ccsg.WebView.EventType = { scaleX /= dpr; scaleY /= dpr; - var container = cc.container; + 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); @@ -358,7 +358,7 @@ _ccsg.WebView.EventType = { this._div.style.width = contentSize.width + "px"; this._div.style.overflow = "scroll"; this._div.style.border = "none"; - cc.container.appendChild(this._div); + cc.game.container.appendChild(this._div); }; proto.createNativeControl = function () { @@ -371,13 +371,13 @@ _ccsg.WebView.EventType = { var div = this._div; if(div){ var hasChild = false; - if('contains' in cc.container) { - hasChild = cc.container.contains(div); + if('contains' in cc.game.container) { + hasChild = cc.game.container.contains(div); }else { - hasChild = cc.container.compareDocumentPosition(div) % 16; + hasChild = cc.game.container.compareDocumentPosition(div) % 16; } if(hasChild) - cc.container.removeChild(div); + cc.game.container.removeChild(div); } this._div = null; }; @@ -388,18 +388,18 @@ _ccsg.WebView.EventType = { var div = this._div; if (node.visible) { div.style.visibility = 'visible'; - cc.container.appendChild(div); + cc.game.container.appendChild(div); } else { div.style.visibility = 'hidden'; if(div){ var hasChild = false; - if('contains' in cc.container) { - hasChild = cc.container.contains(div); + if('contains' in cc.game.container) { + hasChild = cc.game.container.contains(div); }else { - hasChild = cc.container.compareDocumentPosition(div) % 16; + hasChild = cc.game.container.compareDocumentPosition(div) % 16; } if(hasChild) - cc.container.removeChild(div); + cc.game.container.removeChild(div); } } }; From 2a4e2ddb79f8d3a2e161f830565d1a74f3a3a65b Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Fri, 29 Jul 2016 13:56:56 +0800 Subject: [PATCH 078/268] fix rotated sprite Frame for canvas rendering --- cocos2d/core/sprites/CCSpriteFrame.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/sprites/CCSpriteFrame.js b/cocos2d/core/sprites/CCSpriteFrame.js index 50d886fbbd..33b1964107 100644 --- a/cocos2d/core/sprites/CCSpriteFrame.js +++ b/cocos2d/core/sprites/CCSpriteFrame.js @@ -298,8 +298,9 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ var tempTexture = new cc.Texture2D(); tempTexture.initWithElement(tempElement); tempTexture.handleLoadedTexture(); - // _refreshTexture will be recalled in setTexture - self.setTexture(tempTexture); + self._texture = tempTexture; + self._rotated = false; + self.setRect(cc.rect(0, 0, self._texture.width, self._texture.height)); return; } var w = texture.width, h = texture.height; From dff3f74ddb9c9ffd4bef9b8715410d34f95198be Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Fri, 29 Jul 2016 10:28:42 +0800 Subject: [PATCH 079/268] make scrollview brake more aggressive --- cocos2d/core/components/CCScrollView.js | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/cocos2d/core/components/CCScrollView.js b/cocos2d/core/components/CCScrollView.js index 7fbf42afaa..4d1602b29d 100644 --- a/cocos2d/core/components/CCScrollView.js +++ b/cocos2d/core/components/CCScrollView.js @@ -1105,7 +1105,6 @@ var ScrollView = cc.Class({ _startAttenuatingAutoScroll: function(deltaMove, initialVelocity) { var time = this._calculateAutoScrollTimeByInitalSpeed(cc.pLength(initialVelocity)); - var originalMoveLength = cc.pLength(deltaMove); var targetDelta = cc.pNormalize(deltaMove); var contentSize = this.content.getContentSize(); @@ -1119,10 +1118,23 @@ var ScrollView = cc.Class({ targetDelta = cc.p(targetDelta.x * totalMoveWidth * (1 - this.brake) * attenuatedFactorX, targetDelta.y * totalMoveHeight * attenuatedFactorY * (1 - this.brake)); - targetDelta = cc.pAdd(deltaMove, targetDelta); + var originalMoveLength = cc.pLength(deltaMove); var factor = cc.pLength(targetDelta) / originalMoveLength; + targetDelta = cc.pAdd(targetDelta, deltaMove); - time = time * factor; + if(this.brake > 0 && factor > 7) { + factor = Math.sqrt(factor); + targetDelta = cc.pAdd(cc.pMult(deltaMove, factor), deltaMove); + } + + if(this.brake > 0 && factor > 3) { + factor = 3; + time = time * factor; + } + + if(this.brake === 0 && factor > 1) { + time = time * factor; + } this._startAutoScroll(targetDelta, time, true); }, @@ -1171,7 +1183,8 @@ var ScrollView = cc.Class({ return cc.pAdd(a, b); }, totalMovement); - return cc.p(totalMovement.x / totalTime, totalMovement.y / totalTime); + return cc.p(totalMovement.x * (1 - this.brake) / totalTime, + totalMovement.y * (1 - this.brake) / totalTime); }, _flattenVectorByDirection: function(vector) { From 66da2e03f51229a95a31350831b087ed4a214f41 Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Fri, 29 Jul 2016 14:23:56 +0800 Subject: [PATCH 080/268] bug fix for rotated sprite frame on canvas --- cocos2d/core/sprites/CCSpriteFrame.js | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/cocos2d/core/sprites/CCSpriteFrame.js b/cocos2d/core/sprites/CCSpriteFrame.js index 33b1964107..8065abc8ba 100644 --- a/cocos2d/core/sprites/CCSpriteFrame.js +++ b/cocos2d/core/sprites/CCSpriteFrame.js @@ -292,6 +292,8 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ this._texture = texture; function textureLoadedCallback () { self._textureLoaded = true; + var w = texture.width, h = texture.height; + if (self._rotated && cc._renderType === cc.game.RENDER_TYPE_CANVAS) { var tempElement = texture.getHtmlElementObj(); tempElement = _ccsg.Sprite.CanvasRenderCmd._cutRotateImageToCanvas(tempElement, self.getRect()); @@ -300,13 +302,13 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ tempTexture.handleLoadedTexture(); self._texture = tempTexture; self._rotated = false; - self.setRect(cc.rect(0, 0, self._texture.width, self._texture.height)); - return; + w = self._texture.width; + h = self._texture.height; + self.setRect(cc.rect(0, 0, w, h)); } - var w = texture.width, h = texture.height; if (self._rect) { - self._checkRect(texture); + self._checkRect(self._texture); } else { self.setRect(cc.rect(0, 0, w, h)); From 4af42b0e443c7a845bd737c4935b349bc37288e4 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Fri, 29 Jul 2016 16:52:54 +0800 Subject: [PATCH 081/268] fix editbox placeholder change error --- cocos2d/core/editbox/CCSGEditBox.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/editbox/CCSGEditBox.js b/cocos2d/core/editbox/CCSGEditBox.js index 2c772bcecb..4e6f82e24d 100644 --- a/cocos2d/core/editbox/CCSGEditBox.js +++ b/cocos2d/core/editbox/CCSGEditBox.js @@ -248,6 +248,7 @@ _ccsg.EditBox = _ccsg.Node.extend({ this._placeholderColor = cc.Color.GRAY; this.initWithSizeAndBackgroundSprite(size, normal9SpriteBg); + this._renderCmd._createLabels(); }, _createRenderCmd: function () { @@ -991,7 +992,6 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; proto.createNativeControl = function() { this._createDomTextArea(); this._addDomInputControl(); - this._createLabels(); }; proto._addDomInputControl = function () { From 713ca1ee39a940f154ae49b1bb33e7fb1f7e1a3d Mon Sep 17 00:00:00 2001 From: Nan Wang Date: Fri, 29 Jul 2016 16:57:23 +0800 Subject: [PATCH 082/268] update engine version --- CCBoot.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CCBoot.js b/CCBoot.js index ea96f5e13c..b612109be6 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -58,7 +58,7 @@ _p = null; * @name cc.ENGINE_VERSION */ var engineVersion; -engineVersion = '1.2.0-beta.3'; +engineVersion = '1.2.0-rc.1'; window['CocosEngine'] = cc.ENGINE_VERSION = engineVersion; /** From f932ce0a2e06e1b68d3e542a668174182ee1aac1 Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Fri, 29 Jul 2016 17:45:34 +0800 Subject: [PATCH 083/268] fix graphics node canvas rendering bug with hacking --- cocos2d/core/graphics/graphics-canvas-cmd.js | 13 ++++++++++++- cocos2d/core/renderer/RendererCanvas.js | 9 +-------- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/cocos2d/core/graphics/graphics-canvas-cmd.js b/cocos2d/core/graphics/graphics-canvas-cmd.js index d55d57bb7b..311731717d 100644 --- a/cocos2d/core/graphics/graphics-canvas-cmd.js +++ b/cocos2d/core/graphics/graphics-canvas-cmd.js @@ -47,12 +47,19 @@ var CanvasRenderCmd = function (renderable) { var _p = CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype); _p.constructor = CanvasRenderCmd; +_p._updateCurrentRegions = function() { + var temp = this._currentRegion; + this._currentRegion = this._oldRegion; + this._oldRegion = temp; + this._currentRegion.setTo(0,0, cc.visibleRect.width, cc.visibleRect.height); +}; + _p.rendering = function (ctx, scaleX, scaleY) { var wrapper = ctx || cc._renderContext, context = wrapper.getContext(); wrapper.setTransform(this._worldTransform, scaleX, scaleY); context.save(); - context.scale(scaleX, -scaleY); + context.scale(1, -1); var endPath = true; var cmds = this.cmds; @@ -246,6 +253,7 @@ Js.mixin(_p, { fillRect: function (x, y, w, h) { this.cmds.push(['fillRect', arguments]); + this.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); }, close: function () { @@ -254,14 +262,17 @@ Js.mixin(_p, { stroke: function () { this.cmds.push(['stroke', arguments]); + this.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); }, fill: function () { this.cmds.push(['fill', arguments]); + this.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); }, clear: function () { this.cmds.push(['clear']); + this.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); } }); diff --git a/cocos2d/core/renderer/RendererCanvas.js b/cocos2d/core/renderer/RendererCanvas.js index af6676b101..15c6467d30 100644 --- a/cocos2d/core/renderer/RendererCanvas.js +++ b/cocos2d/core/renderer/RendererCanvas.js @@ -390,14 +390,7 @@ cc.rendererCanvas = { }; proto.setFillStyle = function(fillStyle){ - if (this._saveCount > 0) { - this._context.fillStyle = fillStyle; - } else { - if (this._currentFillStyle !== fillStyle) { - this._currentFillStyle = fillStyle; - this._context.fillStyle = fillStyle; - } - } + this._context.fillStyle = fillStyle; }; proto.setStrokeStyle = function(strokeStyle){ From 3b75a0ab9d78fe5e5609d9de71907fea8ae2d627 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 29 Jul 2016 18:48:50 +0800 Subject: [PATCH 084/268] Fix memory leak caused by event listener --- cocos2d/core/CCNode.js | 5 ++ cocos2d/core/components/CCRendererInSG.js | 5 +- cocos2d/core/utils/base-node.js | 9 ++-- cocos2d/core/utils/scene-graph-helper.js | 4 ++ jsb/jsb-event.js | 65 +++++++++-------------- 5 files changed, 43 insertions(+), 45 deletions(-) diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index 37f0ac5661..92e4d625c9 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -530,10 +530,14 @@ var Node = cc.Class({ // Remove all listeners if (CC_JSB && this._touchListener) { this._touchListener.release(); + this._touchListener.owner = null; + this._touchListener.mask = null; this._touchListener = null; } if (CC_JSB && this._mouseListener) { this._mouseListener.release(); + this._mouseListener.owner = null; + this._mouseListener.mask = null; this._mouseListener = null; } cc.eventManager.removeListeners(this); @@ -566,6 +570,7 @@ var Node = cc.Class({ } else if (CC_JSB) { this._sgNode.release(); + this._sgNode._entity = null; this._sgNode = null; } }, diff --git a/cocos2d/core/components/CCRendererInSG.js b/cocos2d/core/components/CCRendererInSG.js index 0629445317..a61e5b397e 100644 --- a/cocos2d/core/components/CCRendererInSG.js +++ b/cocos2d/core/components/CCRendererInSG.js @@ -83,6 +83,7 @@ var RendererInSG = cc.Class({ var releasedByNode = this.node._sgNode; if (this._plainNode !== releasedByNode) { this._plainNode.release(); + this._plainNode = null; } } }, @@ -94,6 +95,7 @@ var RendererInSG = cc.Class({ var node = this.node; var replaced = node._sgNode; + replaced._entity = null; if (CC_EDITOR && replaced === sgNode) { cc.warn('The same sgNode'); @@ -125,10 +127,11 @@ var RendererInSG = cc.Class({ cc.renderer.childrenOrderDirty = parentNode._reorderChildDirty = true; } } + replaced.release(); // apply node's property - node._sgNode = sgNode; + node._sgNode._entity = node; node._updateSgNode(); }, }); diff --git a/cocos2d/core/utils/base-node.js b/cocos2d/core/utils/base-node.js index 17270cb1e6..e102ee02ae 100644 --- a/cocos2d/core/utils/base-node.js +++ b/cocos2d/core/utils/base-node.js @@ -755,10 +755,10 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ var sgNode = this._sgNode = new _ccsg.Node(); if (CC_JSB) { sgNode.retain(); - var entity = this; + sgNode._entity = this; sgNode.onEnter = function () { _ccsg.Node.prototype.onEnter.call(this); - if (!entity._active) { + if (this._entity && !this._entity._active) { cc.director.getActionManager().pauseTarget(this); cc.eventManager.pauseTarget(this); } @@ -797,6 +797,7 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ _onPreDestroy: function () { if (CC_JSB) { this._sgNode.release(); + this._sgNode._entity = null; this._sgNode = null; } cc.eventManager.removeListeners(this); @@ -843,7 +844,7 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ } }, - /** + /* * !#en * Defines the oder in which the nodes are renderer. * Nodes that have a Global Z Order lower, are renderer first. @@ -880,7 +881,7 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ this._sgNode.setGlobalZOrder(globalZOrder); }, - /** + /* * !#en Return the Node's Global Z Order. * !#zh 获取节点的全局 Z 顺序。 * @method getGlobalZOrder diff --git a/cocos2d/core/utils/scene-graph-helper.js b/cocos2d/core/utils/scene-graph-helper.js index 5b6d2ffcb7..6eaa768b06 100644 --- a/cocos2d/core/utils/scene-graph-helper.js +++ b/cocos2d/core/utils/scene-graph-helper.js @@ -34,6 +34,10 @@ var SceneGraphUtils = { parent.removeChild(node); } node.release(); + if (this._sgNode._entity) { + this._sgNode._entity = null; + } + this._sgNode = null; } }, }; diff --git a/jsb/jsb-event.js b/jsb/jsb-event.js index d47255cd09..c41b4da8b3 100644 --- a/jsb/jsb-event.js +++ b/jsb/jsb-event.js @@ -32,23 +32,24 @@ cc.Event.CAPTURING_PHASE = 1; cc.Event.AT_TARGET = 2; cc.Event.BUBBLING_PHASE = 3; -cc.Event.prototype._getCurrentTarget = cc.Event.prototype.getCurrentTarget; -cc.Event.prototype.getCurrentTarget = function () { - return this.currentTarget || this._getCurrentTarget(); +var proto = cc.Event.prototype; +proto._getCurrentTarget = proto.getCurrentTarget; +proto.getCurrentTarget = function () { + return this._currentTarget || this._getCurrentTarget(); }; -cc.Event.prototype._stopPropagation = cc.Event.prototype.stopPropagation; -cc.Event.prototype.stopPropagation = function () { +proto._stopPropagation = proto.stopPropagation; +proto.stopPropagation = function () { this._propagationStopped = true; this._stopPropagation(); }; -cc.Event.prototype._isStopped = cc.Event.prototype.isStopped; -cc.Event.prototype.isStopped = function () { +proto._isStopped = proto.isStopped; +proto.isStopped = function () { return this._propagationStopped || this._propagationImmediateStopped || this._isStopped(); }; -cc.js.mixin(cc.Event.prototype, { +cc.js.mixin(proto, { type: 'no_type', - target: null, - currentTarget: null, + _target: null, + _currentTarget: null, eventPhase: 0, bubbles: false, _propagationStopped: false, @@ -56,8 +57,8 @@ cc.js.mixin(cc.Event.prototype, { unuse: function () { this.type = cc.Event.NO_TYPE; - this.target = null; - this.currentTarget = null; + this._target = null; + this._currentTarget = null; this.eventPhase = cc.Event.NONE; this._propagationStopped = false; this._propagationImmediateStopped = false; @@ -70,6 +71,18 @@ cc.js.mixin(cc.Event.prototype, { this._propagationImmediateStopped = true; }, }); +cc.js.getset(proto, 'target', function () { + if (!this._target) { + var currentTarget = this._currentTarget || this._getCurrentTarget(); + this._target = currentTarget._entity || currentTarget; + } + return this._target; +}, function (value) { + this._target = value; +}); +cc.js.getset(proto, 'currentTarget', proto.getCurrentTarget, function (value) { + this._currentTarget = value; +}); // cc.Event.EventCustom cc.Event.EventCustom = function (type, bubbles) { @@ -128,34 +141,6 @@ cc.eventManager.addListener = function(listener, nodeOrPriority) { if (nodeOrPriority instanceof cc.Node) { node = nodeOrPriority._sgNode; } - // rebind target - if (node !== nodeOrPriority) { - var keys = Object.keys(listener); - // Overwrite all functions - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - var value = listener[key]; - if (typeof value === 'function') { - // var _value = value; - listener[key] = (function (realCallback) { - return function (event1, event2) { - // event must be the last argument, and arguments count could be 1 or 2 - var event = event2 || event1; - // Augment event object to fit cc.Event - if (event) { - event.target = nodeOrPriority; - event.currentTarget = nodeOrPriority; - event.bubbles = false; - event.eventPhase = 0; - event._propagationStopped = false; - event._propagationImmediateStopped = false; - } - return realCallback.call(this, event1, event2); - }; - })(value); - } - } - } cc.eventManager.addEventListenerWithSceneGraphPriority(listener, node); } From c70058964d65fc24f901987c6ec84a400340c6fb Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 29 Jul 2016 18:49:19 +0800 Subject: [PATCH 085/268] Fix Event.EventTouch is undefined issue in JSB --- cocos2d/core/event-manager/CCSystemEvent.js | 4 ++-- jsb/jsb-event.js | 5 +++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/event-manager/CCSystemEvent.js b/cocos2d/core/event-manager/CCSystemEvent.js index 505cccbf30..8c88214d71 100644 --- a/cocos2d/core/event-manager/CCSystemEvent.js +++ b/cocos2d/core/event-manager/CCSystemEvent.js @@ -536,7 +536,7 @@ EventTouch.CANCELED = 3; * @param {Object} acc - The acceleration * @param {Boolean} bubbles - A boolean indicating whether the event bubbles up through the tree or not */ -EventAcceleration = function (acc, bubbles) { +var EventAcceleration = function (acc, bubbles) { cc.Event.call(this, Event.ACCELERATION, bubbles); this._acc = acc; }; @@ -552,7 +552,7 @@ JS.extend(EventAcceleration, cc.Event); * @param {Boolean} isPressed - A boolean indicating whether the key have been pressed * @param {Boolean} bubbles - A boolean indicating whether the event bubbles up through the tree or not */ -EventKeyboard = function (keyCode, isPressed, bubbles) { +var EventKeyboard = function (keyCode, isPressed, bubbles) { cc.Event.call(this, Event.KEYBOARD, bubbles); this._keyCode = keyCode; this._isPressed = isPressed; diff --git a/jsb/jsb-event.js b/jsb/jsb-event.js index c41b4da8b3..eb24fdf266 100644 --- a/jsb/jsb-event.js +++ b/jsb/jsb-event.js @@ -32,6 +32,11 @@ cc.Event.CAPTURING_PHASE = 1; cc.Event.AT_TARGET = 2; cc.Event.BUBBLING_PHASE = 3; +cc.Event.EventMouse = cc.EventMouse; +cc.Event.EventTouch = cc.EventTouch; +cc.Event.EventAcceleration = cc.EventAcceleration; +cc.Event.EventKeyboard = cc.EventKeyboard; + var proto = cc.Event.prototype; proto._getCurrentTarget = proto.getCurrentTarget; proto.getCurrentTarget = function () { From edd0d5d6ec66d815fdfb7e62523a6624ff3630bf Mon Sep 17 00:00:00 2001 From: Nan Wang Date: Sat, 30 Jul 2016 11:33:11 +0800 Subject: [PATCH 086/268] remove replaced.release to fix node.parent invalid native object issue when switching scenes --- cocos2d/core/components/CCRendererInSG.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/components/CCRendererInSG.js b/cocos2d/core/components/CCRendererInSG.js index a61e5b397e..c349c8f6ab 100644 --- a/cocos2d/core/components/CCRendererInSG.js +++ b/cocos2d/core/components/CCRendererInSG.js @@ -127,7 +127,7 @@ var RendererInSG = cc.Class({ cc.renderer.childrenOrderDirty = parentNode._reorderChildDirty = true; } } - replaced.release(); + // replaced.release(); // apply node's property node._sgNode = sgNode; From 48c8fa6422535ab4fb04a036bd184b68629ad089 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Fri, 29 Jul 2016 10:57:22 +0800 Subject: [PATCH 087/268] should not reset _sgNode in #986 --- cocos2d/core/components/missing-script.js | 2 +- cocos2d/core/utils/scene-graph-helper.js | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/cocos2d/core/components/missing-script.js b/cocos2d/core/components/missing-script.js index 23e947db3e..6b0ebad064 100644 --- a/cocos2d/core/components/missing-script.js +++ b/cocos2d/core/components/missing-script.js @@ -115,7 +115,7 @@ var MissingScript = cc.Class({ } }, onLoad: function () { - cc.warn('The referenced component script on node "%s" is missing!', this.node.name); + cc.warn('Script attached to "%s" is missing or invalid.', this.node.name); } }); diff --git a/cocos2d/core/utils/scene-graph-helper.js b/cocos2d/core/utils/scene-graph-helper.js index 6eaa768b06..1b0fc22a10 100644 --- a/cocos2d/core/utils/scene-graph-helper.js +++ b/cocos2d/core/utils/scene-graph-helper.js @@ -37,7 +37,6 @@ var SceneGraphUtils = { if (this._sgNode._entity) { this._sgNode._entity = null; } - this._sgNode = null; } }, }; From 701aff13f9fcd910b23cce25b2cdec25c634ce38 Mon Sep 17 00:00:00 2001 From: Nan Wang Date: Sat, 30 Jul 2016 16:33:19 +0800 Subject: [PATCH 088/268] update engine version --- CCBoot.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CCBoot.js b/CCBoot.js index b612109be6..1b3eaaf497 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -58,7 +58,7 @@ _p = null; * @name cc.ENGINE_VERSION */ var engineVersion; -engineVersion = '1.2.0-rc.1'; +engineVersion = '1.2.0-rc.2'; window['CocosEngine'] = cc.ENGINE_VERSION = engineVersion; /** From 8f01758fa958735696d6ff9d67d5bb633ea48ed5 Mon Sep 17 00:00:00 2001 From: Nan Wang Date: Mon, 1 Aug 2016 11:15:07 +0800 Subject: [PATCH 089/268] update version --- CCBoot.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CCBoot.js b/CCBoot.js index 1b3eaaf497..5ef52c827a 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -58,7 +58,7 @@ _p = null; * @name cc.ENGINE_VERSION */ var engineVersion; -engineVersion = '1.2.0-rc.2'; +engineVersion = '1.2.0-rc.3'; window['CocosEngine'] = cc.ENGINE_VERSION = engineVersion; /** From 09e0b0506791e550fb0f2dd9499db132c45b6f29 Mon Sep 17 00:00:00 2001 From: zhangbin Date: Mon, 1 Aug 2016 11:30:09 +0800 Subject: [PATCH 090/268] Add interface for set the tiles opacity of TiledLayer. --- cocos2d/tilemap/CCTiledLayer.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/cocos2d/tilemap/CCTiledLayer.js b/cocos2d/tilemap/CCTiledLayer.js index 117ae1fcca..8442904f0d 100644 --- a/cocos2d/tilemap/CCTiledLayer.js +++ b/cocos2d/tilemap/CCTiledLayer.js @@ -349,6 +349,24 @@ var TiledLayer = cc.Class({ } }, + /** + * !#en Set the opacity of all tiles + * !#zh 设置所有 Tile 的透明度 + * @method setTileOpacity + * @param {Number} opacity + * @example + * tiledLayer.setTileOpacity(128); + */ + setTileOpacity: function(opacity) { + if (this._sgNode) { + if (CC_JSB) { + this._sgNode.setTileOpacity(opacity); + } else { + this._sgNode._opacity = opacity; + } + } + }, + /** * !#en Gets layer size. * !#zh 获得层大小。 From 34b0f529c92e94ceadb4469a8db0aea8b47bd1fa Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Mon, 1 Aug 2016 09:41:11 +0800 Subject: [PATCH 091/268] remove setVisible from api --- cocos2d/core/components/CCSprite.js | 9 --------- 1 file changed, 9 deletions(-) diff --git a/cocos2d/core/components/CCSprite.js b/cocos2d/core/components/CCSprite.js index 3dcfef3575..28d7c9616e 100644 --- a/cocos2d/core/components/CCSprite.js +++ b/cocos2d/core/components/CCSprite.js @@ -379,15 +379,6 @@ var Sprite = cc.Class({ SizeMode: SizeMode, }, - /** - * !#en Sets whether the sprite is visible or not. - * !#zh 设置精灵是否可见 - * @method setVisible - * @param {Boolean} visible - * @override - * @example - * sprite.setVisible(false); - */ setVisible: function (visible) { this.enabled = visible; }, From 1f80aa329162b45a50fcb29d24e1d2c78d8ac279 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Mon, 1 Aug 2016 12:01:10 +0800 Subject: [PATCH 092/268] make widget's enable state persist when animation editor not changed --- cocos2d/core/base-ui/CCWidgetManager.js | 39 ++++++++++++++++++++++--- cocos2d/core/platform/deserialize.js | 11 +++---- 2 files changed, 41 insertions(+), 9 deletions(-) diff --git a/cocos2d/core/base-ui/CCWidgetManager.js b/cocos2d/core/base-ui/CCWidgetManager.js index 5ea2b125b7..24eea32e55 100644 --- a/cocos2d/core/base-ui/CCWidgetManager.js +++ b/cocos2d/core/base-ui/CCWidgetManager.js @@ -156,7 +156,7 @@ function visitNode (node) { var widget = node._widget; if (widget) { alignToParent(node, widget); - if ((!CC_EDITOR || _Scene.AnimUtils.curAnimState) && widget.isAlignOnce) { + if ((!CC_EDITOR || animationState.animatedSinceLastFrame) && widget.isAlignOnce) { widget.enabled = false; } else { @@ -172,7 +172,34 @@ function visitNode (node) { } } +if (CC_EDITOR) { + var animationState = { + previewing: false, + time: 0, + animatedSinceLastFrame: false, + }; +} + function refreshScene () { + // check animation editor + if (CC_EDITOR) { + var nowPreviewing = !!_Scene.AnimUtils.curAnimState; + if (nowPreviewing !== animationState.previewing) { + animationState.previewing = nowPreviewing; + if (nowPreviewing) { + animationState.animatedSinceLastFrame = true; + animationState.time = _Scene.AnimUtils.curAnimState.time; + } + else { + animationState.animatedSinceLastFrame = false; + } + } + else if (nowPreviewing && animationState.time !== _Scene.AnimUtils.curAnimState.time) { + animationState.animatedSinceLastFrame = true; + animationState.time = _Scene.AnimUtils.curAnimState.time; + } + } + var scene = cc.director.getScene(); if (scene) { widgetManager.isAligning = true; @@ -180,14 +207,14 @@ function refreshScene () { widgetManager._nodesWithWidget.length = 0; visitNode(scene); widgetManager._nodesOrderDirty = false; - } else { + } + else { var i, node, nodes = widgetManager._nodesWithWidget, len = nodes.length; if (CC_EDITOR && _Scene.AnimUtils.curAnimState) { - // always check isAlignOnce because animation mode maybe changed for (i = len - 1; i >= 0; i--) { node = nodes[i]; var widget = node._widget; - if (widget.isAlignOnce) { + if (widget.isAlignOnce && animationState.animatedSinceLastFrame) { // widget contains in _nodesWithWidget should aligned at least once widget.enabled = false; } @@ -206,6 +233,10 @@ function refreshScene () { widgetManager.isAligning = false; } + // check animation editor + if (CC_EDITOR) { + animationState.animatedSinceLastFrame = false; + } } var adjustWidgetToAllowMovingInEditor = CC_EDITOR && function (event) { diff --git a/cocos2d/core/platform/deserialize.js b/cocos2d/core/platform/deserialize.js index d0ac823e65..d94ef033ff 100644 --- a/cocos2d/core/platform/deserialize.js +++ b/cocos2d/core/platform/deserialize.js @@ -467,12 +467,13 @@ var _Deserializer = (function () { * @return {object} the main data(asset) */ cc.deserialize = function (data, result, options) { - var classFinder = (options && options.classFinder) || JS._getClassById; + options = options || {}; + var classFinder = options.classFinder || JS._getClassById; // 启用 createAssetRefs 后,如果有 url 属性则会被统一强制设置为 { uuid: 'xxx' },必须后面再特殊处理 - var createAssetRefs = (options && options.createAssetRefs) || cc.sys.platform === cc.sys.EDITOR_CORE; - var target = CC_DEV && (options && options.target); - var customEnv = options && options.customEnv; - var ignoreEditorOnly = options && options.ignoreEditorOnly; + var createAssetRefs = options.createAssetRefs || cc.sys.platform === cc.sys.EDITOR_CORE; + var target = CC_DEV && options.target; + var customEnv = options.customEnv; + var ignoreEditorOnly = options.ignoreEditorOnly; if (CC_EDITOR && Buffer.isBuffer(data)) { data = data.toString(); From 15670df9ec9b97cada58085720dfceabbbcb994b Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 1 Aug 2016 12:26:35 +0800 Subject: [PATCH 093/268] Improve pause & resume logic --- cocos2d/core/CCDirector.js | 12 ++++++++---- cocos2d/core/CCGame.js | 33 +++++++++++++++++++++++++++------ 2 files changed, 35 insertions(+), 10 deletions(-) diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js index 4ef8ead898..c3549d6ed1 100644 --- a/cocos2d/core/CCDirector.js +++ b/cocos2d/core/CCDirector.js @@ -389,8 +389,12 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ getZEye: null, /** - * !#en Pause the director's ticker. - * !#zh 暂停正在运行的场景,该暂停只会停止 Scheduler,但是不会停止渲染和 UI 响应。 + * !#en Pause the director's ticker, only involve the game logic execution. + * It won't pause the rendering process nor the event manager. + * If you want to pause the entier game including rendering, audio and event, + * please use {{#crossLink "Game.pause"}}cc.game.pause{{/crossLink}} + * !#zh 暂停正在运行的场景,该暂停只会停止游戏逻辑执行,但是不会停止渲染和 UI 响应。 + * 如果想要更彻底得暂停游戏,包含渲染,音频和事件,请使用 {{#crossLink "Game.pause"}}cc.game.pause{{/crossLink}}。 * @method pause */ pause: function () { @@ -818,8 +822,8 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ }, /** - * !#en Resume director after pause, if the current scene is not paused, nothing will happen. - * !#zh 恢复暂停场景,恢复 Scheduler,如果当前场景没有暂停将没任何事情发生。 + * !#en Resume game logic execution after pause, if the current scene is not paused, nothing will happen. + * !#zh 恢复暂停场景的游戏逻辑,如果当前场景没有暂停将没任何事情发生。 * @method resume */ resume: function () { diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index e7c7dad0d2..2bbbafd0b8 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -29,6 +29,8 @@ if (!(CC_EDITOR && Editor.isMainProcess)) { View = require('./platform/CCView'); } +var _isMusicPlaying = false; + /** * !#en An object to boot the game. * !#zh 包含游戏主体信息并负责驱动游戏的游戏对象。 @@ -241,15 +243,26 @@ var game = /** @lends cc.game# */{ }, /** - * !#en Pause the game,pause main loop. - * !#zh 暂停游戏,暂停的是整个主循环。 + * !#en Pause the game main loop. This will pause: + * game logic execution, rendering process, event manager, background music and all audio effects. + * This is different with cc.director.pause which only pause the game logic execution. + * !#zh 暂停游戏主循环。包含:游戏逻辑,渲染,事件处理,背景音乐和所有音效。这点和只暂停游戏逻辑的 cc.director.pause 不同。 * @method pause */ pause: function () { if (this._paused) return; this._paused = true; // Pause audio engine - cc.audioEngine && cc.audioEngine._pausePlaying(); + if (cc.audioEngine) { + _isMusicPlaying = cc.audioEngine.isMusicPlaying(); + cc.audioEngine.stopAllEffects(); + cc.audioEngine.pauseMusic(); + } + // Pause event + var scene = cc.director.getScene() || cc.director.getRunningScene(); + if (scene) { + cc.eventManager.pauseTarget(scene, true); + } // Pause main loop if (this._intervalId) window.cancelAnimationFrame(this._intervalId); @@ -257,15 +270,23 @@ var game = /** @lends cc.game# */{ }, /** - * !#en Resume the game from pause. - * !#zh 继续游戏,继续的是整个主循环。 + * !#en Resume the game from pause. This will resume: + * game logic execution, rendering process, event manager, background music and all audio effects. + * !#zh 恢复游戏主循环。包含:游戏逻辑,渲染,事件处理,背景音乐和所有音效。 * @method resume */ resume: function () { if (!this._paused) return; this._paused = false; // Resume audio engine - cc.audioEngine && cc.audioEngine._resumePlaying(); + if (cc.audioEngine && _isMusicPlaying) { + cc.audioEngine.resumeMusic(); + } + // Resume event + var scene = cc.director.getScene() || cc.director.getRunningScene(); + if (scene) { + cc.eventManager.resumeTarget(scene, true); + } // Resume main loop this._runMainLoop(); }, From a57fcd251485aff4afe29408a9bd0398942f05cb Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 1 Aug 2016 14:23:01 +0800 Subject: [PATCH 094/268] Add async to package.json --- package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/package.json b/package.json index 8071bae5fc..09e8334775 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ "test": "gulp test" }, "devDependencies": { + "async": "1.5.2", "browserify": "13.0.0", "chalk": "1.1.0", "del": "1.2.0", From 4f8a6daf812787142906d63bb9c2798080136ba6 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 1 Aug 2016 14:41:40 +0800 Subject: [PATCH 095/268] Add back ActionCatmullRom --- cocos2d/actions/CCActionCatmullRom.js | 99 ++++----------- cocos2d/actions/CCActionTween.js | 166 -------------------------- cocos2d/actions/index.js | 3 +- 3 files changed, 23 insertions(+), 245 deletions(-) delete mode 100644 cocos2d/actions/CCActionTween.js diff --git a/cocos2d/actions/CCActionCatmullRom.js b/cocos2d/actions/CCActionCatmullRom.js index 123f62a528..22ea1adff3 100644 --- a/cocos2d/actions/CCActionCatmullRom.js +++ b/cocos2d/actions/CCActionCatmullRom.js @@ -69,36 +69,6 @@ cc.cardinalSplineAt = function (p0, p1, p2, p3, tension, t) { return cc.p(x, y); }; -/* - * returns a new copy of the array reversed. - * @method reverseControlPoints - * @param {Array} controlPoints - * @return {Array} - */ -cc.reverseControlPoints = function (controlPoints) { - var newArray = []; - for (var i = controlPoints.length - 1; i >= 0; i--) { - newArray.push(cc.p(controlPoints[i].x, controlPoints[i].y)); - } - return newArray; -}; - - -/* - * returns a new clone of the controlPoints - * @method cloneControlPoints - * @param {Array} controlPoints - * @returns {Array} - */ -cc.cloneControlPoints = function (controlPoints) { - var newArray = []; - for (var i = 0; i < controlPoints.length; i++) - newArray.push(cc.p(controlPoints[i].x, controlPoints[i].y)); - return newArray; -}; - -cc.copyControlPoints = cc.cloneControlPoints; - /* * returns a point from the array * @method getControlPointAt @@ -111,20 +81,20 @@ cc.getControlPointAt = function (controlPoints, pos) { return controlPoints[p]; }; -/* - * reverse the current control point array inline, without generating a new one
- * @method reverseControlPointsInline - * @param {Array} controlPoints - */ -cc.reverseControlPointsInline = function (controlPoints) { - var len = controlPoints.length; - var mid = 0 | (len / 2); - for (var i = 0; i < mid; ++i) { - var temp = controlPoints[i]; - controlPoints[i] = controlPoints[len - i - 1]; - controlPoints[len - i - 1] = temp; +function reverseControlPoints (controlPoints) { + var newArray = []; + for (var i = controlPoints.length - 1; i >= 0; i--) { + newArray.push(cc.p(controlPoints[i].x, controlPoints[i].y)); } -}; + return newArray; +} + +function cloneControlPoints (controlPoints) { + var newArray = []; + for (var i = 0; i < controlPoints.length; i++) + newArray.push(cc.p(controlPoints[i].x, controlPoints[i].y)); + return newArray; +} /* @@ -157,15 +127,6 @@ cc.CardinalSplineTo = cc.ActionInterval.extend({ tension !== undefined && this.initWithDuration(duration, points, tension); }, - /* - * initializes the action with a duration and an array of points - * @method initWithDuration - * @param {Number} duration - * @param {Array} points array of control points - * @param {Number} tension - * - * @return {Boolean} - */ initWithDuration:function (duration, points, tension) { if(!points || points.length === 0) throw new Error("Invalid configuration. It must at least have one control point"); @@ -180,7 +141,7 @@ cc.CardinalSplineTo = cc.ActionInterval.extend({ clone:function () { var action = new cc.CardinalSplineTo(); - action.initWithDuration(this._duration, cc.copyControlPoints(this._points), this._tension); + action.initWithDuration(this._duration, cloneControlPoints(this._points), this._tension); return action; }, @@ -234,7 +195,7 @@ cc.CardinalSplineTo = cc.ActionInterval.extend({ }, reverse:function () { - var reversePoints = cc.reverseControlPoints(this._points); + var reversePoints = reverseControlPoints(this._points); return cc.cardinalSplineTo(this._duration, reversePoints, this._tension); }, @@ -257,7 +218,7 @@ cc.CardinalSplineTo = cc.ActionInterval.extend({ return this._points; }, - /* + /** * Points setter * @method setPoints * @param {Array} points @@ -329,7 +290,7 @@ cc.CardinalSplineBy = cc.CardinalSplineTo.extend({ } // convert to "diffs" to "reverse absolute" - var reverseArray = cc.reverseControlPoints(copyConfig); + var reverseArray = reverseControlPoints(copyConfig); // 1st element (which should be 0,0) should be here too p = reverseArray[ reverseArray.length - 1 ]; @@ -351,7 +312,7 @@ cc.CardinalSplineBy = cc.CardinalSplineTo.extend({ return cc.cardinalSplineBy(this._duration, reverseArray, this._tension); }, - /* + /** * update position of target * @method updatePosition * @param {Vec2} newPos @@ -365,14 +326,9 @@ cc.CardinalSplineBy = cc.CardinalSplineTo.extend({ this.target.setPosition(posX, posY); }, - /* - * returns a new clone of the action - * @method clone - * @returns {CardinalSplineBy} - */ clone:function () { var a = new cc.CardinalSplineBy(); - a.initWithDuration(this._duration, cc.copyControlPoints(this._points), this._tension); + a.initWithDuration(this._duration, cloneControlPoints(this._points), this._tension); return a; } }); @@ -412,19 +368,13 @@ cc.CatmullRomTo = cc.CardinalSplineTo.extend({ points && this.initWithDuration(dt, points); }, - /* - * Initializes the action with a duration and an array of points - * @method initWithDuration - * @param {Number} dt - * @param {Array} points - */ initWithDuration:function (dt, points) { return cc.CardinalSplineTo.prototype.initWithDuration.call(this, dt, points, 0.5); }, clone:function () { var action = new cc.CatmullRomTo(); - action.initWithDuration(this._duration, cc.copyControlPoints(this._points)); + action.initWithDuration(this._duration, cloneControlPoints(this._points)); return action; } }); @@ -466,20 +416,13 @@ cc.CatmullRomBy = cc.CardinalSplineBy.extend({ points && this.initWithDuration(dt, points); }, - /* - * initializes the action with a duration and an array of points - * - * @method initWithDuration - * @param {Number} dt - * @param {Array} points - */ initWithDuration:function (dt, points) { return cc.CardinalSplineTo.prototype.initWithDuration.call(this, dt, points, 0.5); }, clone:function () { var action = new cc.CatmullRomBy(); - action.initWithDuration(this._duration, cc.copyControlPoints(this._points)); + action.initWithDuration(this._duration, cloneControlPoints(this._points)); return action; } }); diff --git a/cocos2d/actions/CCActionTween.js b/cocos2d/actions/CCActionTween.js deleted file mode 100644 index 530d4b091f..0000000000 --- a/cocos2d/actions/CCActionTween.js +++ /dev/null @@ -1,166 +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. - ****************************************************************************/ - -/** - * - * @class ActionTweenDelegate - * @extends _Class - */ -cc.ActionTweenDelegate = cc._Class.extend(/** @lends cc.ActionTweenDelegate */{ - - /** - * Update Tween Action. - * @param value - * @param key - */ - updateTweenAction:function(value, key){} -}); - -/** - * cc.ActionTween - * cc.ActionTween is an action that lets you update any property of an object. - * - * @class - * @extends ActionInterval - * @example - * //For example, if you want to modify the "width" property of a target from 200 to 300 in 2 seconds, then: - * var modifyWidth = cc.actionTween(2,"width",200,300) - * target.runAction(modifyWidth); - * - * //Another example: cc.ScaleTo action could be rewriten using cc.PropertyAction: - * // scaleA and scaleB are equivalents - * var scaleA = cc.scaleTo(2,3); - * var scaleB = cc.actionTween(2,"scale",1,3); - * @param {Number} duration - * @param {String} key - * @param {Number} from - * @param {Number} to - */ -cc.ActionTween = cc.ActionInterval.extend(/** @lends cc.ActionTween */{ - 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){ - cc.ActionInterval.prototype.ctor.call(this); - this.key = ""; - - to !== undefined && this.initWithDuration(duration, key, from, to); - }, - - /** - * 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 - * @return {Boolean} - */ - initWithDuration:function (duration, key, from, to) { - if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { - this.key = key; - this.to = to; - this.from = from; - return true; - } - return false; - }, - - /** - * Start this tween with target. - * @param {ActionTweenDelegate} target - */ - 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; - }, - - /** - * Called once per frame. Time is the number of seconds of a frame interval. - * - * @param {Number} dt - */ - update:function (dt) { - this.target.updateTweenAction(this.to - this.delta * (1 - dt), this.key); - }, - - /** - * returns a reversed action. - * @return {ActionTween} - */ - reverse:function () { - return new cc.ActionTween(this.duration, this.key, this.to, this.from); - }, - - /** - * to copy object with deep copy. - * returns a clone of action. - * - * @return {ActionTween} - */ - clone:function(){ - var action = new cc.ActionTween(); - action.initWithDuration(this._duration, this.key, this.from, this.to); - return action; - } -}); - -/** - * Creates an initializes the action with the property name (key), and the from and to parameters. - * @method - * @param {Number} duration - * @param {String} key - * @param {Number} from - * @param {Number} to - * @return {ActionTween} - */ -cc.actionTween = function (duration, key, from, to) { - return new cc.ActionTween(duration, key, from, to); -}; - -/** - * Please use cc.actionTween instead. - * Creates an initializes the action with the property name (key), and the from and to parameters. - * @static - * @deprecated since v3.0
Please use cc.actionTween instead. - * @param {Number} duration - * @param {String} key - * @param {Number} from - * @param {Number} to - * @return {ActionTween} - */ -cc.ActionTween.create = cc.actionTween; \ No newline at end of file diff --git a/cocos2d/actions/index.js b/cocos2d/actions/index.js index beed958d32..31b45fdcf8 100644 --- a/cocos2d/actions/index.js +++ b/cocos2d/actions/index.js @@ -1,4 +1,5 @@ require('./CCAction.js'); require('./CCActionInterval.js'); require('./CCActionInstant.js'); -require('./CCActionEase.js'); \ No newline at end of file +require('./CCActionEase.js'); +require('./CCActionCatmullRom.js'); \ No newline at end of file From 3dfc574f4dcd2c2127c637f6ee6812077b86b97c Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 1 Aug 2016 16:20:39 +0800 Subject: [PATCH 096/268] Fix game EVENT_HIDE&SHOW not working in JSB --- jsb/jsb-game.js | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/jsb/jsb-game.js b/jsb/jsb-game.js index 60321f0599..78f75bd92e 100644 --- a/jsb/jsb-game.js +++ b/jsb/jsb-game.js @@ -259,6 +259,12 @@ cc.js.mixin(cc.game, { } }); - cc.EventTarget.call(cc.game); -cc.js.addon(cc.game, cc.EventTarget.prototype); \ No newline at end of file +cc.js.addon(cc.game, cc.EventTarget.prototype); + +cc.eventManager.addCustomListener(cc.game.EVENT_HIDE, function () { + cc.game.emit(cc.game.EVENT_HIDE, cc.game); +}); +cc.eventManager.addCustomListener(cc.game.EVENT_SHOW, function () { + cc.game.emit(cc.game.EVENT_SHOW, cc.game); +}); \ No newline at end of file From 4ccfb04a2f3595cb6e3817757e51120441092828 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Mon, 1 Aug 2016 16:21:39 +0800 Subject: [PATCH 097/268] fix build --- cocos2d/core/base-ui/CCWidgetManager.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/base-ui/CCWidgetManager.js b/cocos2d/core/base-ui/CCWidgetManager.js index 24eea32e55..7cbcc15638 100644 --- a/cocos2d/core/base-ui/CCWidgetManager.js +++ b/cocos2d/core/base-ui/CCWidgetManager.js @@ -182,7 +182,7 @@ if (CC_EDITOR) { function refreshScene () { // check animation editor - if (CC_EDITOR) { + if (CC_EDITOR && window._Scene && _Scene.AnimUtils) { var nowPreviewing = !!_Scene.AnimUtils.curAnimState; if (nowPreviewing !== animationState.previewing) { animationState.previewing = nowPreviewing; @@ -210,7 +210,7 @@ function refreshScene () { } else { var i, node, nodes = widgetManager._nodesWithWidget, len = nodes.length; - if (CC_EDITOR && _Scene.AnimUtils.curAnimState) { + if (CC_EDITOR && window._Scene && _Scene.AnimUtils && _Scene.AnimUtils.curAnimState) { for (i = len - 1; i >= 0; i--) { node = nodes[i]; var widget = node._widget; From 6a1322b5724571e1a440831f08db2818c66b6677 Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Mon, 1 Aug 2016 16:46:15 +0800 Subject: [PATCH 098/268] fix dirty region not updated correctly for label --- cocos2d/core/label/CCSGLabel.js | 2 +- cocos2d/core/label/CCSGLabelCanvasRenderCmd.js | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/label/CCSGLabel.js b/cocos2d/core/label/CCSGLabel.js index eb2704d396..e8684f722a 100644 --- a/cocos2d/core/label/CCSGLabel.js +++ b/cocos2d/core/label/CCSGLabel.js @@ -484,7 +484,7 @@ _ccsg.Label = _ccsg.Node.extend({ if (CC_EDITOR) { this._updateLabel(); } else { - this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.textDirty); + this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.textDirty|_ccsg.Node._dirtyFlags.contentDirty); } }, _createRenderCmd: function() { diff --git a/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js b/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js index af49a464e5..9bcba7236f 100644 --- a/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js +++ b/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js @@ -39,6 +39,11 @@ if (opacityDirty) this._updateDisplayOpacity(); + if(locFlag & dirtyFlags.contentDirty) { + this._notifyRegionStatus && this._notifyRegionStatus(_ccsg.Node.CanvasRenderCmd.RegionStatus.Dirty); + this._dirtyFlag &= ~dirtyFlags.contentDirty; + } + if (colorDirty || opacityDirty || (locFlag & flags.textDirty)) { this._notifyRegionStatus && this._notifyRegionStatus(_ccsg.Node.CanvasRenderCmd.RegionStatus.Dirty); this._rebuildLabelSkin(); From 05624e7f28ddfda21074bf99ac70befb91d7c37b Mon Sep 17 00:00:00 2001 From: 2youyouo2 <501251991@qq.com> Date: Mon, 1 Aug 2016 16:52:59 +0800 Subject: [PATCH 099/268] fixed graphics canvas commands --- cocos2d/core/graphics/graphics-canvas-cmd.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/graphics/graphics-canvas-cmd.js b/cocos2d/core/graphics/graphics-canvas-cmd.js index 311731717d..2236def510 100644 --- a/cocos2d/core/graphics/graphics-canvas-cmd.js +++ b/cocos2d/core/graphics/graphics-canvas-cmd.js @@ -70,7 +70,8 @@ _p.rendering = function (ctx, scaleX, scaleY) { if (ctxCmd === 'clear') { cmds.splice(0, i+1); i = 0; - return; + l = cmds.length; + continue; } else if (ctxCmd === 'moveTo' && endPath) { context.beginPath(); From a2766c3f7736be289d2f974b0405ece237c4873f Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 1 Aug 2016 18:16:17 +0800 Subject: [PATCH 100/268] Fix touch start point haven't been scaled issue --- cocos2d/core/event-manager/CCTouch.js | 1 + cocos2d/core/platform/CCView.js | 38 +++++++++++++-------------- 2 files changed, 19 insertions(+), 20 deletions(-) diff --git a/cocos2d/core/event-manager/CCTouch.js b/cocos2d/core/event-manager/CCTouch.js index 821f16f342..8261bd1cd8 100644 --- a/cocos2d/core/event-manager/CCTouch.js +++ b/cocos2d/core/event-manager/CCTouch.js @@ -163,6 +163,7 @@ cc.Touch = cc._Class.extend(/** @lends cc.Touch# */{ this._id = id; if(!this._startPointCaptured){ this._startPoint = cc.p(this._point); + cc.view._convertPointWithScale(this._startPoint); this._startPointCaptured = true; } }, diff --git a/cocos2d/core/platform/CCView.js b/cocos2d/core/platform/CCView.js index d8cb4cf851..c5703f7016 100644 --- a/cocos2d/core/platform/CCView.js +++ b/cocos2d/core/platform/CCView.js @@ -874,32 +874,30 @@ var View = cc._Class.extend({ 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; }, - _convertTouchesWithScale: function(touches){ - var locViewPortRect = this._viewPortRect, locScaleX = this._scaleX, locScaleY = this._scaleY, - selTouch, selPoint, selPrePoint, selStartPoint; - for( var i = 0; i < touches.length; i ++){ + _convertPointWithScale: function (point) { + var viewport = this._viewPortRect; + point.x = (point.x - viewport.x) / this._scaleX; + point.y = (point.y - viewport.y) / this._scaleY; + }, + + _convertTouchesWithScale: function (touches) { + var viewport = this._viewPortRect, scaleX = this._scaleX, scaleY = this._scaleY, + selTouch, selPoint, selPrePoint; + for( var i = 0; i < touches.length; i++){ selTouch = touches[i]; - hasStartPoint = selTouch._startPointCaptured; selPoint = selTouch._point; selPrePoint = selTouch._prevPoint; - selPoint.x = (selPoint.x - locViewPortRect.x) / locScaleX; - selPoint.y = (selPoint.y - locViewPortRect.y) / locScaleY; - selPrePoint.x = (selPrePoint.x - locViewPortRect.x) / locScaleX; - selPrePoint.y = (selPrePoint.y - locViewPortRect.y) / locScaleY; - - if (!hasStartPoint) { - selStartPoint = selTouch._startPoint; - selStartPoint.x = selPoint.x; - selStartPoint.y = selPoint.y; - selTouch._startPointCaptured = true; - } + selPoint.x = (selPoint.x - viewport.x) / scaleX; + selPoint.y = (selPoint.y - viewport.y) / scaleY; + selPrePoint.x = (selPrePoint.x - viewport.x) / scaleX; + selPrePoint.y = (selPrePoint.y - viewport.y) / scaleY; } } }); From 3f2cdbd8f000f643dda25beec9f3b289184d3ec0 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Mon, 1 Aug 2016 18:30:42 +0800 Subject: [PATCH 101/268] add enableAntiAlias for CCView fireball/issues/2836 --- cocos2d/core/platform/CCView.js | 53 ++++++++++++++++++++++++++++ cocos2d/core/textures/CCTexture2D.js | 10 ++++++ 2 files changed, 63 insertions(+) diff --git a/cocos2d/core/platform/CCView.js b/cocos2d/core/platform/CCView.js index d8cb4cf851..f04fcc921a 100644 --- a/cocos2d/core/platform/CCView.js +++ b/cocos2d/core/platform/CCView.js @@ -150,6 +150,8 @@ var View = cc._Class.extend({ _isAdjustViewPort: true, _targetDensityDPI: null, + _antiAliasEnabled: false, + /** * Constructor of View */ @@ -181,6 +183,7 @@ var View = cc._Class.extend({ _t._rpFixedWidth = new cc.ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.FIXED_WIDTH); _t._targetDensityDPI = cc.macro.DENSITYDPI_HIGH; + _t.enableAntiAlias(true); }, // Resize helper functions @@ -415,6 +418,56 @@ var View = cc._Class.extend({ return this._retinaEnabled; }, + /** + * !#en Whether to Enable on anti-alias + * !#zh 是否开启抗锯齿 + * @method enableAntiAlias + * @param {Boolean} enabled - Enable or not anti-alias + */ + enableAntiAlias: function (enabled) { + if (this._antiAliasEnabled === enabled) { + return; + } + this._antiAliasEnabled = enabled; + if(cc._renderType === cc.game.RENDER_TYPE_WEBGL) { + var map = cc.loader._items.map; + for (var key in map) { + var item = map[key]; + var tex = item && item.content instanceof cc.Texture2D ? item.content : null; + if (tex) { + if (enabled) { + tex.setAntiAliasTexParameters(); + } + else { + tex.setAliasTexParameters(); + } + } + } + } + else if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) { + var ctx = cc._canvas.getContext('2d'); + ctx.imageSmoothingEnabled = enabled; + ctx.mozImageSmoothingEnabled = enabled; + // refresh canvas + var dirtyRegion = cc.rendererCanvas._dirtyRegion; + if (dirtyRegion) { + var oldRegion = new cc.Region(); + oldRegion.setTo(0, 0, cc.visibleRect.width, cc.visibleRect.height); + dirtyRegion.addRegion(oldRegion); + } + } + }, + + /** + * !#en Returns whether the current enable on anti-alias + * !#zh 返回当前是否抗锯齿 + * @method isAntiAliasEnabled + * @param {Boolean} + */ + isAntiAliasEnabled: function () { + return this._antiAliasEnabled; + }, + /** * If enabled, the application will try automatically to enter full screen mode on mobile devices
* You can pass true as parameter to enable it and disable it by passing false.
diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index 3f6a17b485..7f1e7cf93b 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -233,6 +233,16 @@ var Texture2D = cc.Class(/** @lends cc.Texture2D# */{ self._pixelHeight = self._contentSize.height = locElement.height; self._textureLoaded = true; + // anti-alias + if(cc._renderType === cc.game.RENDER_TYPE_WEBGL) { + if (cc.view._antiAliasEnabled) { + self.setAntiAliasTexParameters(); + } + else { + self.setAliasTexParameters(); + } + } + //dispatch load event to listener. self.emit("load"); }, From 37132fd798e9074b35797bcff0f5ebbcb0015626 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 2 Aug 2016 10:27:55 +0800 Subject: [PATCH 102/268] WebGLRenderingContext does not exist --- cocos2d/shaders/CCGLStateCache.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/cocos2d/shaders/CCGLStateCache.js b/cocos2d/shaders/CCGLStateCache.js index c92b0a3623..7bfbde03a1 100644 --- a/cocos2d/shaders/CCGLStateCache.js +++ b/cocos2d/shaders/CCGLStateCache.js @@ -48,6 +48,9 @@ if (ENABLE_GL_STATE_CACHE) { var _currBuffers = {}; + // IE 10 WebGLRenderingContext does not exist + if (!window.WebGLRenderingContext) return; + WebGLRenderingContext.prototype.glBindBuffer = WebGLRenderingContext.prototype.bindBuffer; WebGLRenderingContext.prototype.bindBuffer = function (target, buffer) { if (_currBuffers[target] !== buffer) { From 862a8e9f0e4f62723ed95130ad8e3c7f6567ce1b Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 2 Aug 2016 11:31:14 +0800 Subject: [PATCH 103/268] Fix label color being applied twice --- cocos2d/core/label/CCSGLabelWebGLRenderCmd.js | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/cocos2d/core/label/CCSGLabelWebGLRenderCmd.js b/cocos2d/core/label/CCSGLabelWebGLRenderCmd.js index bf26a7144a..a3f54123c0 100644 --- a/cocos2d/core/label/CCSGLabelWebGLRenderCmd.js +++ b/cocos2d/core/label/CCSGLabelWebGLRenderCmd.js @@ -104,17 +104,8 @@ proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset) { return 0; // Fill in vertex data with quad information (4 vertices for sprite) - var opacity = this._displayedOpacity; - var r = this._displayedColor.r, - g = this._displayedColor.g, - b = this._displayedColor.b; - if (node._opacityModifyRGB) { - var a = opacity / 255; - r *= a; - g *= a; - b *= a; - } - this._color[0] = ((opacity<<24) | (b<<16) | (g<<8) | r); + // Use 255 because color has been set when baking label + this._color[0] = ((this._displayedOpacity<<24) | (255<<16) | (255<<8) | 255); var z = node._vertexZ; var vertices = this._vertices; From d185af11ac7092883de45f67c33c8988cf349677 Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Tue, 2 Aug 2016 14:28:48 +0800 Subject: [PATCH 104/268] fix filled bar sprite bug --- cocos2d/core/sprites/CCScale9Sprite.js | 64 ++++++++++++-------------- 1 file changed, 30 insertions(+), 34 deletions(-) diff --git a/cocos2d/core/sprites/CCScale9Sprite.js b/cocos2d/core/sprites/CCScale9Sprite.js index 35faf7052c..72e74da188 100644 --- a/cocos2d/core/sprites/CCScale9Sprite.js +++ b/cocos2d/core/sprites/CCScale9Sprite.js @@ -484,28 +484,6 @@ var fillQuadGeneratorBar = { sprite._uvs = uvs; } - //build quads - if (webgl) { - vertices[0] = l * wt.a + b * wt.c + wt.tx; - vertices[1] = l * wt.b + b * wt.d + wt.ty; - vertices[2] = r * wt.a + b * wt.c + wt.tx; - vertices[3] = r * wt.b + b * wt.d + wt.ty; - vertices[4] = l * wt.a + t * wt.c + wt.tx; - vertices[5] = l * wt.b + t * wt.d + wt.ty; - vertices[6] = r * wt.a + t * wt.c + wt.tx; - vertices[7] = r * wt.b + t * wt.d + wt.ty; - } - else { - vertices[0] = l; - vertices[1] = b; - vertices[2] = r; - vertices[3] = b; - vertices[4] = l; - vertices[5] = t; - vertices[6] = r; - vertices[7] = t; - } - var quadUV = new Array(8); if (!spriteFrame._rotated) { quadUV[0] = quadUV[4] = ul; @@ -533,13 +511,11 @@ var fillQuadGeneratorBar = { var progressStart, progressEnd; switch (fillType) { case FillType.HORIZONTAL: - progressStart = vertices[0] + (vertices[2] - vertices[0]) * fillStart; - progressEnd = vertices[0] + (vertices[2] - vertices[0]) * fillEnd; + progressStart = l + (r - l) * fillStart; + progressEnd = l + (r - l) * fillEnd; - vertices[0] = progressStart; - vertices[2] = progressEnd; - vertices[4] = progressStart; - vertices[6] = progressEnd; + l = progressStart; + r = progressEnd; uvs[0] = quadUV[0] + (quadUV[2] - quadUV[0]) * fillStart; uvs[1] = quadUV[1]; @@ -551,13 +527,11 @@ var fillQuadGeneratorBar = { uvs[7] = quadUV[7]; break; case FillType.VERTICAL: - progressStart = vertices[1] + (vertices[5] - vertices[1]) * fillStart; - progressEnd = vertices[1] + (vertices[5] - vertices[1]) * fillEnd; + progressStart = b + (t - b) * fillStart; + progressEnd = b + (t - b) * fillEnd; - vertices[1] = progressStart; - vertices[3] = progressStart; - vertices[5] = progressEnd; - vertices[7] = progressEnd; + b = progressStart; + t = progressEnd; uvs[0] = quadUV[0]; uvs[1] = quadUV[1] + (quadUV[5] - quadUV[1]) * fillStart; @@ -572,6 +546,28 @@ var fillQuadGeneratorBar = { cc.error('Unrecognized fill type in bar fill'); break; } + + //build vertices + 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; + } + sprite._vertCount = 4; cornerId[0] = 0; From 7781aff2ab2bb915ff8212b65e88269f1a76078a Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 2 Aug 2016 14:39:32 +0800 Subject: [PATCH 105/268] Fix tile map transform update issue under Canvas --- .../core/base-nodes/CCSGNodeCanvasRenderCmd.js | 12 ++++++------ cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js | 18 ++++++++++-------- 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/cocos2d/core/base-nodes/CCSGNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCSGNodeCanvasRenderCmd.js index 8b39908c18..68318b8943 100644 --- a/cocos2d/core/base-nodes/CCSGNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCSGNodeCanvasRenderCmd.js @@ -449,21 +449,21 @@ _ccsg.Node.RenderCmd.prototype = { var colorDirty = locFlag & dirtyFlags.colorDirty, opacityDirty = locFlag & dirtyFlags.opacityDirty; - if(locFlag & dirtyFlags.contentDirty) { + if (locFlag & dirtyFlags.contentDirty) { this._notifyRegionStatus && this._notifyRegionStatus(_ccsg.Node.CanvasRenderCmd.RegionStatus.Dirty); this._dirtyFlag &= ~dirtyFlags.contentDirty; } - if(colorDirty) + if (colorDirty) this._updateDisplayColor(); - if(opacityDirty) + if (opacityDirty) this._updateDisplayOpacity(); - if(colorDirty || opacityDirty) + if (colorDirty || opacityDirty) this._updateColor(); - if(locFlag & dirtyFlags.transformDirty){ + if (locFlag & dirtyFlags.transformDirty) { //update the transform this.transform(this.getParentRenderCmd(), true); this._dirtyFlag &= ~dirtyFlags.transformDirty; @@ -487,7 +487,7 @@ _ccsg.Node.RenderCmd.prototype = { //update the opacity this._syncDisplayOpacity(); - if(colorDirty || opacityDirty) + if (colorDirty || opacityDirty) this._updateColor(); if (transformDirty) diff --git a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js index 43a0867603..0d63c5d17c 100644 --- a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js +++ b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js @@ -46,14 +46,17 @@ proto.constructor = _ccsg.TMXLayer.CanvasRenderCmd; proto.visit = function (parentCmd) { var node = this._node, renderer = cc.renderer; + + parentCmd = parentCmd || this.getParentRenderCmd(); + if (parentCmd) { + this._curLevel = parentCmd._curLevel + 1; + } + this._propagateFlagsDown(parentCmd); + // quick return if not visible if (!node._visible) return; - parentCmd = parentCmd || this.getParentRenderCmd(); - if (parentCmd) - this._curLevel = parentCmd._curLevel + 1; - if (isNaN(node._customZ)) { node._vertexZ = renderer.assignedZ; renderer.assignedZ += renderer.assignedZStep; @@ -62,7 +65,7 @@ proto.visit = function (parentCmd) { this._syncStatus(parentCmd); // Visit children - var children = node._children, child, cmd, + var children = node._children, child, spTiles = node._spriteTiles, i, len = children.length; if (len > 0) { @@ -71,8 +74,7 @@ proto.visit = function (parentCmd) { for (i = 0; i < len; i++) { child = children[i]; if (child._localZOrder < 0) { - cmd = child._renderCmd; - cmd.visit(this); + child._renderCmd.visit(this); } else { break; @@ -87,7 +89,7 @@ proto.visit = function (parentCmd) { child._vertexZ = renderer.assignedZ; renderer.assignedZ += renderer.assignedZStep; } - child._renderCmd.updateStatus(this, true); + child._renderCmd.updateStatus(); continue; } child._renderCmd.visit(this); From 878a05fa02af1e80eca1531d4996bcb173b6212c Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Tue, 2 Aug 2016 15:03:01 +0800 Subject: [PATCH 106/268] fix filled radial sprite bug --- cocos2d/core/sprites/CCScale9Sprite.js | 53 +++++++++++++------------- 1 file changed, 27 insertions(+), 26 deletions(-) diff --git a/cocos2d/core/sprites/CCScale9Sprite.js b/cocos2d/core/sprites/CCScale9Sprite.js index 72e74da188..cb29379ebf 100644 --- a/cocos2d/core/sprites/CCScale9Sprite.js +++ b/cocos2d/core/sprites/CCScale9Sprite.js @@ -599,8 +599,7 @@ var fillQuadGeneratorRadial = { while (fillStart < 0.0) fillStart += 1.0; var cx = fillCenter.x * contentSize.width, cy = fillCenter.y * contentSize.height; - var center = cc.v2( webgl ? cx * wt.a + cy * wt.c + wt.tx : cx, - webgl ? cx * wt.b + cy * wt.d + wt.ty : cy); + var center = cc.v2( cx, cy); fillStart *= Math.PI * 2; fillRange *= Math.PI * 2; @@ -693,7 +692,7 @@ var fillQuadGeneratorRadial = { } //all in if(fillRange >= Math.PI * 2) { - this._generateTriangle(offset, center, this._vertPos[triangle[0]], this._vertPos[triangle[1]]); + this._generateTriangle(wt, offset, center, this._vertPos[triangle[0]], this._vertPos[triangle[1]]); offset += 6; count += 3; continue; @@ -711,10 +710,10 @@ var fillQuadGeneratorRadial = { } else if (startAngle >= fillStart) { if(endAngle >= fillEnd) { //startAngle to fillEnd - this._generateTriangle(offset, center, this._vertPos[triangle[0]], this._intersectPoint_2[triangleIndex]); + this._generateTriangle(wt, offset, center, this._vertPos[triangle[0]], this._intersectPoint_2[triangleIndex]); } else { //startAngle to endAngle - this._generateTriangle(offset, center, this._vertPos[triangle[0]], this._vertPos[triangle[1]]); + this._generateTriangle(wt, offset, center, this._vertPos[triangle[0]], this._vertPos[triangle[1]]); } offset += 6; count += 3; @@ -724,12 +723,12 @@ var fillQuadGeneratorRadial = { //all out } else if(endAngle <= fillEnd) { //fillStart to endAngle - this._generateTriangle(offset, center, this._intersectPoint_1[triangleIndex], this._vertPos[triangle[1]]); + this._generateTriangle(wt, offset, center, this._intersectPoint_1[triangleIndex], this._vertPos[triangle[1]]); offset += 6; count += 3; } else { //fillStart to fillEnd - this._generateTriangle(offset, center, this._intersectPoint_1[triangleIndex], this._intersectPoint_2[triangleIndex]); + this._generateTriangle(wt, offset, center, this._intersectPoint_1[triangleIndex], this._intersectPoint_2[triangleIndex]); offset += 6; count += 3; } @@ -747,7 +746,7 @@ var fillQuadGeneratorRadial = { cornerId[3] = 6; }, - _generateTriangle: function(offset, vert0, vert1, vert2) { + _generateTriangle: function(wt, offset, vert0, vert1, vert2) { var rawVerts = this.rawVerts; var rawUvs = this.rawUvs; var vertices = this.outVerts; @@ -759,12 +758,22 @@ var fillQuadGeneratorRadial = { // tl: 0, 1 // bl: 2, 3 // tr: 4, 5 - vertices[offset] = vert0.x; - vertices[offset+1] = vert0.y; - vertices[offset+2] = vert1.x; - vertices[offset+3] = vert1.y; - vertices[offset+4] = vert2.x; - vertices[offset+5] = vert2.y; + if(webgl) { + vertices[offset] = vert0.x * wt.a + vert0.y * wt.c + wt.tx; + vertices[offset+1] = vert0.x * wt.b + vert0.y * wt.d + wt.ty; + vertices[offset+2] = vert1.x * wt.a + vert1.y * wt.c + wt.tx; + vertices[offset+3] = vert1.x * wt.b + vert1.y * wt.d + wt.ty; + vertices[offset+4] = vert2.x * wt.a + vert2.y * wt.c + wt.tx; + vertices[offset+5] = vert2.x * wt.b + vert2.y * wt.d + wt.ty; + + } else { + vertices[offset] = vert0.x; + vertices[offset+1] = vert0.y; + vertices[offset+2] = vert1.x; + vertices[offset+3] = vert1.y; + vertices[offset+4] = vert2.x; + vertices[offset+5] = vert2.y; + } progressX = (vert0.x - v0x) / (v1x - v0x); progressY = (vert0.y - v0y) / (v1y - v0y); @@ -875,18 +884,10 @@ var fillQuadGeneratorRadial = { x3 = contentSize.width; y3 = contentSize.height; - if (webgl) { - this._vertices[0].x = x0 * wt.a + y0 * wt.c + wt.tx; - this._vertices[0].y = x0 * wt.b + y0 * wt.d + wt.ty; - this._vertices[1].x = x3 * wt.a + y3 * wt.c + wt.tx; - this._vertices[1].y = x3 * wt.b + y3 * wt.d + wt.ty; - } - else { - this._vertices[0].x = x0; - this._vertices[0].y = y0; - this._vertices[1].x = x3; - this._vertices[1].y = y3; - } + this._vertices[0].x = x0; + this._vertices[0].y = y0; + this._vertices[1].x = x3; + this._vertices[1].y = y3; }, _calculateUVs : function (spriteFrame) { From 67322b3f2aaf518491c03cd38135f75646ca98e6 Mon Sep 17 00:00:00 2001 From: Nan Wang Date: Tue, 2 Aug 2016 15:19:25 +0800 Subject: [PATCH 107/268] fixed api comment syntax error --- CCDebugger.js | 12 ++++++------ cocos2d/animation/animation-clip.js | 2 +- cocos2d/core/assets/CCSpriteAtlas.js | 4 ++-- cocos2d/core/components/CCComponentEventHandler.js | 2 +- cocos2d/tilemap/CCTMXObjectGroup.js | 9 +++++++-- 5 files changed, 17 insertions(+), 12 deletions(-) diff --git a/CCDebugger.js b/CCDebugger.js index 62c1669203..52ea74b18d 100644 --- a/CCDebugger.js +++ b/CCDebugger.js @@ -451,8 +451,8 @@ cc._initDebugSetting = function (mode) { * - 在 Chrome 中,错误信息有红色的图标以及红色的消息文本。
* * @method error - * @param {Any} obj - A JavaScript string containing zero or more substitution strings. - * @param {Any} ...subst - JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. + * @param {any} obj - A JavaScript string containing zero or more substitution strings. + * @param {any} ...subst - JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. */ if (CC_EDITOR) { cc.error = Editor.error; @@ -484,8 +484,8 @@ cc._initDebugSetting = function (mode) { * - 在 Cocos Creator 中,警告信息显示是黄色的。
* - 在 Chrome 中,警告信息有着黄色的图标以及黄色的消息文本。
* @method warn - * @param {Any} obj - A JavaScript string containing zero or more substitution strings. - * @param {Any} ...subst - JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. + * @param {any} obj - A JavaScript string containing zero or more substitution strings. + * @param {any} ...subst - JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. */ if (CC_EDITOR) { cc.warn = Editor.warn; @@ -509,8 +509,8 @@ cc._initDebugSetting = function (mode) { * !#en Outputs a message to the Cocos Creator Console (editor) or Web Console (runtime). * !#zh 输出一条消息到 Cocos Creator 编辑器的 Console 或运行时 Web 端的 Console 中。 * @method log - * @param {Any} obj - A JavaScript string containing zero or more substitution strings. - * @param {Any} ...subst - JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. + * @param {any} obj - A JavaScript string containing zero or more substitution strings. + * @param {any} ...subst - JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. */ if (CC_JSB) { cc.log = jsbLog; diff --git a/cocos2d/animation/animation-clip.js b/cocos2d/animation/animation-clip.js index 1fcbf8caf3..a7e4928972 100644 --- a/cocos2d/animation/animation-clip.js +++ b/cocos2d/animation/animation-clip.js @@ -86,7 +86,7 @@ var AnimationClip = cc.Class({ * !#en Crate clip with a set of sprite frames * !#zh 使用一组序列帧图片来创建动画剪辑 * @method createWithSpriteFrames - * @param {[cc.SpriteFrame]} spriteFrames + * @param {[SpriteFrame]} spriteFrames * @param {Number} sample * @return {AnimationClip} * @example diff --git a/cocos2d/core/assets/CCSpriteAtlas.js b/cocos2d/core/assets/CCSpriteAtlas.js index 74ad5f065d..ccd36701ba 100644 --- a/cocos2d/core/assets/CCSpriteAtlas.js +++ b/cocos2d/core/assets/CCSpriteAtlas.js @@ -59,7 +59,7 @@ var SpriteAtlas = cc.Class({ * Returns the sprite frame correspond to the given key in sprite atlas. * @method getSpriteFrame * @param {String} key - * @returns {cc.SpriteFrame} + * @returns {SpriteFrame} */ getSpriteFrame: function (key) { return this._spriteFrames[key]; @@ -68,7 +68,7 @@ var SpriteAtlas = cc.Class({ /** * Returns the sprite frames in sprite atlas. * @method getSpriteFrames - * @returns {[cc.SpriteFrame]} + * @returns {[SpriteFrame]} */ getSpriteFrames: function () { var frames = []; diff --git a/cocos2d/core/components/CCComponentEventHandler.js b/cocos2d/core/components/CCComponentEventHandler.js index 85275a290c..312c968d82 100644 --- a/cocos2d/core/components/CCComponentEventHandler.js +++ b/cocos2d/core/components/CCComponentEventHandler.js @@ -80,7 +80,7 @@ cc.Component.EventHandler = cc.Class({ /** * @method emitEvents * @param {Component.EventHandler[]} events - * @param {Any} ...params + * @param {any} ...params * @statics */ emitEvents: function(events) { diff --git a/cocos2d/tilemap/CCTMXObjectGroup.js b/cocos2d/tilemap/CCTMXObjectGroup.js index 4618b0368e..1986a93113 100644 --- a/cocos2d/tilemap/CCTMXObjectGroup.js +++ b/cocos2d/tilemap/CCTMXObjectGroup.js @@ -32,10 +32,15 @@ */ /** - * @property {Array} properties - Properties from the group. They can be added using tilemap editors + * Properties from the group. They can be added using tilemap editors. + * @property properties + * @type {Array} */ + /** - * @property {String} groupName - Name of the group + * Name of the group + * @property groupName + * @type {String} */ cc.TMXObjectGroup = cc._Class.extend(/** @lends cc.TMXObjectGroup# */{ properties: null, From e5f73f4bfe2eefca877e9e06485d815d40ea65fc Mon Sep 17 00:00:00 2001 From: Nan Wang Date: Wed, 3 Aug 2016 10:01:27 +0800 Subject: [PATCH 108/268] update engine version --- CCBoot.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CCBoot.js b/CCBoot.js index 5ef52c827a..d1f38ccde2 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -58,7 +58,7 @@ _p = null; * @name cc.ENGINE_VERSION */ var engineVersion; -engineVersion = '1.2.0-rc.3'; +engineVersion = '1.2.0'; window['CocosEngine'] = cc.ENGINE_VERSION = engineVersion; /** From 2d259d2f4df09de42b0635886dcf5f6c5a28cc3f Mon Sep 17 00:00:00 2001 From: "yanli.huang" Date: Wed, 3 Aug 2016 10:30:23 +0800 Subject: [PATCH 109/268] add anysdk api doc --- extensions/anysdk/jsb_anysdk.js | 2706 +++++++++++++++++++++++++++++++ 1 file changed, 2706 insertions(+) create mode 100644 extensions/anysdk/jsb_anysdk.js diff --git a/extensions/anysdk/jsb_anysdk.js b/extensions/anysdk/jsb_anysdk.js new file mode 100644 index 0000000000..51938640a4 --- /dev/null +++ b/extensions/anysdk/jsb_anysdk.js @@ -0,0 +1,2706 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + + http://www.cocos.com + + Permission is hereby granted, free of Stringge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Chukong Aipu reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +/** + * !#en + * AnySDK is a third party solution that offers game developers SDK integration without making changes to the SDK's features or parameters.It can do all of this while remaining invisible to your end user.Our goal is to handle all the tedious SDK integration work for you so that you can use your time to focus on the game itself.No matter if it’s the channel SDK, user system, payment system, ad system, statistics system, sharing system or any other type of SDK: we’ll take care of it for you. + * !#zh + * AnySDK 为 CP 提供一套第三方 SDK 接入解决方案,整个接入过程,不改变任何 SDK 的功能、特性、参数等,对于最终玩家而言是完全透明无感知的。 +目的是让 CP 商能有更多时间更专注于游戏本身的品质,所有 SDK 的接入工作统统交给我们吧。第三方 SDK 包括了渠道SDK、用户系统、支付系统、广告系统、统计系统、分享系统等等。 + * @module anysdk + * @main anysdk + */ +var anysdk = anysdk || {}; + +/** + * !#en + * agent manager of plugin + * !#zh + * 插件管理对象 + * @property {object} anysdk.agentManager + */ +anysdk.agentManager = anysdk.AgentManager.getInstance(); +/** + * @class AgentManager + */ +anysdk.AgentManager = { + /** + * !#en + * AppKey appSecret and privateKey are the only three parameters generated + * after the packing tool client finishes creating the game. + * The oauthLoginServer parameter is the API address provided by the game service + * to login verification + * !#zh + * appKey、appSecret、privateKey是通过 AnySDK 客户端工具创建游戏后生成的。 + * oauthLoginServer参数是游戏服务提供的用来做登陆验证转发的接口地址。 + * @method init + * @param {String} appKey + * @param {String} appSecret + * @param {String} privateKey + * @param {String} oauthLoginServer + */ + init: function(appKey, appSecret, privateKey, oauthLoginServer){ + }, + + /** + * !#en + * load all plugins, the operation includes SDK`s initialization + * !#zh + * 加载所有插件,该操作包含了 SDKs 初始化 + * @method loadAllPlugins + * @param {Function} callback + * @param {object} target The object to bind to. + */ + loadAllPlugins: function(callback, target){ + }, + + /** + * !#en + * unload all plugins + * !#zh + * 卸载插件 + * @method unloadAllPlugins + */ + unloadAllPlugins: function(){ + }, + + /** + * !#en + * get user system plugin + * !#zh + * 获取用户系统插件 + * @method getUserPlugin + * @return {anysdk.ProtocolUser} + */ + getUserPlugin: function(){ + return anysdk.ProtocolUser; + }, + + /** + * !#en + * get IAP system plugins + * !#zh + * 获取支付系统插件 + * @method getIAPPlugin + * @return {anysdk.ProtocolIAP} + */ + getIAPPlugins: function(){ + return {anysdk.ProtocolIAP}; + }, + + /** + * !#en + * get IAP system plugin + * !#zh + * 获取支付系统插件 + * @method getIAPPlugin + * @return {anysdk.ProtocolIAP} + */ + getIAPPlugin: function(){ + return anysdk.ProtocolIAP; + }, + + /** + * !#en + * get social system plugin + * !#zh + * 获取社交系统插件 + * @method getSocialPlugin + * @return {anysdk.ProtocolSocial} + */ + getSocialPlugin: function(){ + return anysdk.ProtocolSocial; + }, + + /** + * !#en + * get share system plugin + * !#zh + * 获取分享系统插件 + * @method getSharePlugin + * @return {anysdk.ProtocolShare} + */ + getSharePlugin: function(){ + return anysdk.ProtocolShare; + }, + + /** + * !#en + * get analytics system plugin + * !#zh + * 获取统计系统插件 + * @method getAnalyticsPlugin + * @return {anysdk.ProtocolAnalytics} + */ + getAnalyticsPlugin: function(){ + return anysdk.ProtocolAnalytics; + }, + + /** + * !#en + * get ads system plugin + * !#zh + * 获取广告系统插件 + * @method getAdsPlugin + * @return {anysdk.ProtocolAds} + */ + getAdsPlugin: function(){ + return anysdk.ProtocolAds; + }, + + /** + * !#en + * get push system plugin + * !#zh + * 获取推送系统插件 + * @method getPushPlugin + * @return {anysdk.ProtocolPush} + */ + getPushPlugin: function(){ + return anysdk.ProtocolPush; + }, + + /** + * !#en + * get REC system plugin + * !#zh + * 获取录屏系统插件 + * @method getRECPlugin + * @return {anysdk.ProtocolREC} + */ + getRECPlugin: function(){ + return anysdk.ProtocolREC; + }, + + /** + * !#en + * get crash system plugin + * !#zh + * 获取崩溃分析系统插件 + * @method getCrashPlugin + * @return {anysdk.ProtocolCrash} + */ + getCrashPlugin: function(){ + return anysdk.ProtocolCrash; + }, + + /** + * !#en + * get ad track system plugin + * !#zh + * 获取广告追踪系统插件 + * @method getAdTrackingPlugin + * @return {anysdk.ProtocolAdTracking} + */ + getAdTrackingPlugin: function(){ + return anysdk.ProtocolAdTracking; + }, + + /** + * !#en + * get custom system plugin + * !#zh + * 获取自定义系统插件 + * @method getCustomPlugin + * @return {anysdk.ProtocolCustom} + */ + getCustomPlugin: function(){ + return anysdk.ProtocolCustom; + }, + + /** + * !#en + * get custom parameter + * !#zh + * 获取自定义参数 + * @method getCustomParam + * @return {String} + */ + getCustomParam: function(){ + return String; + }, + + /** + * !#en + * get channel id + * !#zh + * 获取渠道唯一表示符 + * @method getChannelId + * @return {String} + */ + getChannelId: function(){ + return String; + }, + + /** + * !#en + * get status of analytics + * !#zh + * 获取统计状态 + * @method isAnaylticsEnabled + * @return {boolean} + */ + isAnaylticsEnabled: function(){ + return boolean; + }, + + /** + * !#en + * set whether to analytics + * !#zh + * 设置是否统计 + * @method setIsAnaylticsEnabled + * @param {boolean} enabled + */ + setIsAnaylticsEnabled: function(enabled) + { + }, + + /** + * !#en + * destory instance + * !#zh + * 销毁单例 + * @method end + */ + end: function() + { + }, + + /** + * !#en + * get instance + * !#zh + * 获取单例 + * @method getInstance + * @return {anysdk.AgentManager} + */ + getInstance: function() + { + return anysdk.AgentManager; + }, +}; + +/** + * !#en + * plugin protocol + * !#zh + * 插件协议 + * @class PluginProtocol + * @brief The super class for all plugins. + */ +anysdk.PluginProtocol = { + + /** + * !#en + * Check whether the function is supported + * !#zh + * 判断函数是否支持 + * @method isFunctionSupported + * @param {String} functionName + * @return {boolean} + */ + isFunctionSupported: function(functionName) + { + return boolean; + }, + + /** + * !#en + * get plugin name + * !#zh + * 获取插件名称 + * @method getPluginName + * @return {String} + */ + getPluginName: function(){ + return String; + }, + + /** + * !#en + * get plugin version + * !#zh + * 获取插件版本 + * @method getPluginVersion + * @return {String} + */ + getPluginVersion: function (){ + return String; + }, + + /** + * !#en + * get SDK version + * !#zh + * 获取 SDK 版本 + * @method getSDKVersion + * @return {String} + */ + getSDKVersion: function(){ + return String; + }, + + /** + * @brief methods for reflections + * !#en + * void methods for reflections with parameter + * !#zh + * 反射调用带参数的void方法 + * @method callFuncWithParam + * @param {String} funName + * @param {String} [...args] optional arguments + * @expose + */ + callFuncWithParam: function(funName){ + }, + + /** + * @brief methods for reflections + * !#en + * String methods for reflections with parameter + * !#zh + * 反射调用带参数的 String 方法 + * @method callStringFuncWithParam + * @param {String} funName + * @param {String} [...args] optional arguments + * @return {String} + * @expose + */ + callStringFuncWithParam: function(funName){ + return String; + }, + + /** + * @brief methods for reflections + * !#en + * int methods for reflections with parameter + * !#zh + * 反射调用带参数的 Int 方法 + * @method callIntFuncWithParam + * @param {String} funName + * @param {String} [...args] optional arguments + * @return {Number} Type:int + * @expose + */ + callIntFuncWithParam: function(funName){ + return int; + }, + + /** + * @brief methods for reflections + * !#en + * boolean methods for reflections with parameter + * !#zh + * 反射调用带参数的 boolean 方法 + * @method callBoolFuncWithParam + * @param {String} funName + * @param {String} [...args] optional arguments + * @return {boolean} + * @expose + */ + callBoolFuncWithParam: function(funName){ + return boolean; + }, + + /** + * @brief methods for reflections + * !#en + * float methods for reflections with parameter + * !#zh + * 反射调用带参数的 float 方法 + * @method callBoolFuncWithParam + * @param {String} funName + * @param {String} [...args] optional arguments + * @return {Number} Type:float + * @expose + */ + callFloatFuncWithParam: function(funName){ + return float; + }, +}; + +/** + * @class ProtocolUser + */ +anysdk.ProtocolUser = PluginProtocol.extend({ + + /** + * !#en + * login interface + * !#zh + * 登录接口 + * @method login + * @param {String} [...args] optional arguments + */ + login: function(){ + }, + + /** + * !#en + * get status of login + * !#zh + * 获取登录状态 + * @method isLogined + * @return {boolean} + */ + isLogined : function () + { + return boolean; + }, + + /** + * !#en + * get user ID + * !#zh + * 获取用户唯一标示符 + * @method getUserID + * @return {String} + */ + getUserID : function () + { + return String; + }, + + /** + * !#en + * get plugin ID + * !#zh + * 获取插件ID + * @method getPluginId + * @return {String} + */ + getPluginId: function (){ + return String; + }, + + /** + * !#en + * set listener + * !#zh + * 设置自定义系统的监听 + * @method setListener + * @param {Function} listener + * @param {Object} target + */ + setListener: function(listener, target) { + }, + + /** + * !#en + * get listener + * !#zh + * @method getListener + * 获取自定义系统的监听 + * @return {Function} listener + */ + getListener: function() { + return Function; + }, + + /** + * !#en + * logout + * Before to invoke, you need to verdict whether this properties existed + * !#zh + * 登出,调用前需要判断属性是否存在 + * @method logout + */ + logout: function(){ + }, + + /** + * !#en + * show toolbar + * Before to invoke, you need to verdict whether this properties existed + * !#zh + * 显示悬浮窗,调用前需要判断属性是否存在 + * @method showToolBar + * @param {anysdk.ToolBarPlace} place + */ + showToolBar: function(place){ + }, + + /** + * !#en + * hide toolbar + * Before to invoke, you need to verdict whether this properties existed + * !#zh + * 隐藏悬浮窗,调用前需要判断属性是否存在 + * @method hideToolBar + */ + hideToolBar: function(){ + }, + + /** + * !#en + * enter platform + * Before to invoke, you need to verdict whether this properties existed + * !#zh + * 显示平台中心,调用前需要判断属性是否存在 + * @method enterPlatform + */ + enterPlatform: function(){ + }, + + /** + * !#en + * show exit page + * Before to invoke, you need to verdict whether this properties existed + * !#zh + * 显示退出界面,调用前需要判断属性是否存在 + * @method exit + */ + exit: function(){ + }, + + /** + * !#en + * show pause page + * Before to invoke, you need to verdict whether this properties existed + * !#zh + * 显示暂停界面,调用前需要判断属性是否存在 + * @method pause + */ + pause: function(){ + }, + + /** + * !#en + * Real-name registration + * Before to invoke, you need to verdict whether this properties existed + * !#zh + * 实名注册,调用前需要判断属性是否存在 + * @method realNameRegister + */ + realNameRegister: function(){ + }, + + /** + * !#en + * Anti-addiction query + * Before to invoke, you need to verdict whether this properties existed + * !#zh + * 防沉迷查询,调用前需要判断属性是否存在 + * @method antiAddictionQuery + */ + antiAddictionQuery: function(){ + }, + + /** + * !#en + * submit game role information + * Before to invoke, you need to verdict whether this properties existed + * !#zh + * 提交角色信息,调用前需要判断属性是否存在 + * @method submitLoginGameRole + * @param {String} data + */ + submitLoginGameRole: function(data){ + }, + /** + * !#en + * get user information + * Before to invoke, you need to verdict whether this properties existed + * !#zh + * 获取用户信息,调用前需要判断属性是否存在 + * @method getUserInfo + * @param {String} info + */ + getUserInfo:function(info){ + }, + + /** + * !#en + * set login type + * Before to invoke, you need to verdict whether this properties existed + * !#zh + * 设置登录类型,调用前需要判断属性是否存在 + * @method getAvailableLoginType + * @param {String} info + */ + getAvailableLoginType:function(info){ + }, + + /** + * !#en + * set login type + * Before to invoke, you need to verdict whether this properties existed + * !#zh + * 设置登录类型,调用前需要判断属性是否存在 + * @method setLoginType + * @param {String} loginType + */ + setLoginType:function(loginType){ + }, + + + /** + * !#en + * send to desktop + * Before to invoke, you need to verdict whether this properties existed + * !#zh + * 发送到桌面,调用前需要判断属性是否存在 + * @method sendToDesktop + */ + sendToDesktop: function(){ + }, + + /** + * !#en + * open bbs + * Before to invoke, you need to verdict whether this properties existed + * !#zh + * 打开论坛,调用前需要判断属性是否存在 + * @method openBBS + */ + openBBS: function(){ + }, + +}); + + +/** + * @class ProtocolIAP + */ +anysdk.ProtocolIAP = PluginProtocol.extend({ + + /** + * !#en + * pay interface + * !#zh + * 支付接口 + * @method payForProduct + * @param {Object} info Type:map + */ + payForProduct: function(info){ + }, + + /** + * !#en + * get order ID + * !#zh + * 获取订单ID + * @method getOrderId + * @return {String} + */ + getOrderId: function(){ + return String; + }, + + /** + * !#en + * reset the pay status + * !#zh + * 重置支付状态 + * @static + * @method resetPayState + */ + resetPayState: function(){ + }, + + /** + * !#en + * get plugin ID + * !#zh + * 获取插件ID + * @method getPluginId + * @return {String} + */ + getPluginId: function (){ + return String; + }, + + /** + * !#en + * set listener + * !#zh + * 设置自定义系统的监听 + * @method setListener + * @param {Function} listener + * @param {Object} target + */ + setListener: function(listener, target) { + }, + + /** + * !#en + * get listener + * !#zh + * @method getListener + * 获取自定义系统的监听 + * @return {Function} listener + */ + getListener: function() { + return Function; + }, + +}); + +/** + * @class ProtocolAnalytics + */ +anysdk.ProtocolAnalytics = PluginProtocol.extend({ + + /** + * !#en + * Start a new session. + * !#zh + * 启动会话 + * @method startSession + */ + startSession: function(){ + }, + + /** + * !#en + * Stop a session. + * !#zh + * 关闭会话 + * @method stopSession + */ + stopSession: function(){ + }, + + /** + * !#en + * Set the timeout for expiring a session. + * !#zh + * 设置会话超时时间 + * @method setSessionContinueMillis + * @param {Number} millis Type: long + */ + setSessionContinueMillis: function(millis){ + }, + + /** + * !#en + * log an error + * !#zh + * 捕捉异常 + * @method logError + * @param {String} errorId + * @param {String} message + */ + logError: function(errorId, message){ + }, + + /** + * !#en + * log an event. + * !#zh + * 捕捉事件 + * @method logEvent + * @param {String} errorId + * @param {Object} [...args] optional arguments Type: map + */ + logEvent: function(errorId, paramMap){ + }, + + /** + * !#en + * Track an event begin. + * !#zh + * 统计事件开始 + * @method logTimedEventBegin + * @param {String} eventId + */ + logTimedEventBegin: function(eventId){ + }, + + /** + * !#en + * Track an event end. + * !#zh + * 统计事件结束 + * @method logTimedEventEnd + * @param {String} eventId + */ + logTimedEventEnd: function(eventId){ + }, + + /** + * !#en + * set Whether to catch uncaught exceptions to server. + * !#zh + * 设置是否开启自动异常捕捉 + * @method setCaptureUncaughtException + * @param {boolean} enabled + */ + setCaptureUncaughtException: function(enabled){ + }, + + /** + * !#en + * analytics account information + * !#zh + * 统计玩家帐户信息 + * @method setAccount + * @param {Object} paramMap Type: map + */ + setAccount: function(paramMap){ + }, + + /** + * !#en + * track user to request payment + * !#zh + * 跟踪用户支付请求 + * @method onChargeRequest + * @param {Object} paramMap Type: map + */ + onChargeRequest: function(paramMap){ + }, + + /** + * !#en + * track Successful payment + * !#zh + * 追踪用户支付成功 + * @method onChargeSuccess + * @param {String} orderID + */ + onChargeSuccess: function(orderID){ + }, + + /** + * !#en + * track failed payment + * !#zh + * 追踪用户支付失败 + * @method onChargeFail + * @param {Object} paramMap Type: map + */ + onChargeFail: function(paramMap){ + }, + + /** + * !#en + * track Successful payment + * !#zh + * 统计玩家支付成功 + * @method onChargeOnlySuccess + * @param {Object} paramMap Type: map + */ + onChargeOnlySuccess: function(paramMap){ + }, + + /** + * !#en + * track user purchase + * !#zh + * 统计玩家消费 + * @method onPurchase + * @param {Object} paramMap Type: map + */ + onPurchase: function(paramMap){ + }, + + /** + * !#en + * track user to use goods + * !#zh + * 统计玩家使用道具 + * @method onUse + * @param {Object} paramMap Type: map + */ + onUse: function(paramMap){ + }, + + /** + * !#en + * track user to reward goods + * !#zh + * 统计玩家获取奖励 + * @method onReward + * @param {Object} paramMap Type: map + */ + onReward: function(paramMap){ + }, + + /** + * !#en + * start level + * !#zh + * 开始关卡 + * @method startLevel + * @param {Object} paramMap Type: map + */ + startLevel: function(paramMap){ + }, + + /** + * !#en + * finish level + * !#zh + * 结束关卡 + * @method finishLevel + * @param {String} levelID + */ + finishLevel: function(levelID){ + }, + + /** + * !#en + * failed level + * !#zh + * 关卡失败 + * @method failLevel + * @param {Object} paramMap Type: map + */ + failLevel: function(paramMap){ + }, + + /** + * !#en + * start task + * !#zh + * 开始任务 + * @method startTask + * @param {Object} paramMap Type: map + */ + startTask: function(paramMap){ + }, + + /** + * !#en + * finish task + * !#zh + * 完成任务 + * @method finishTask + * @param {String} taskID + */ + finishTask: function(taskID){ + }, + + /** + * !#en + * failed task + * !#zh + * 任务失败 + * @method failTask + * @param {Object} paramMap Type: map + */ + failTask: function(paramMap){ + }, + + + +}); + +/** + * @class ProtocolShare + */ +anysdk.ProtocolShare = PluginProtocol.extend({ + + /** + * !#en + * share interface + * !#zh + * 分享 + * @method share + * @param {Object} info Type: map + */ + share: function(info){ + }, + /** + * !#en + * set listener + * !#zh + * 设置自定义系统的监听 + * @method setListener + * @param {Function} listener + * @param {Object} target + */ + setListener: function(listener, target) { + }, + + /** + * !#en + * get listener + * !#zh + * @method getListener + * 获取自定义系统的监听 + * @return {Function} listener + */ + getListener: function() { + return Function; + }, +}); + + +/** + * @class ProtocolAds + */ +anysdk.ProtocolAds = PluginProtocol.extend({ + /* + * !#en + * show ads view + * !#zh + * 显示广告 + * @param {anysdk.AdsType} adstype + * @param {Number} idx + */ + showAds: function(adstype, idx){ + }, + + /** + * !#en + * hide ads view + * !#zh + * 隐藏广告 + * @method hideAds + * @param {anysdk.AdsType} adstype + * @param {Number} idx + */ + hideAds: function (adstype, idx){ + }, + + /** + * !#en + * preload ads view + * !#zh + * 预加载广告 + * @method preloadAds + * @param {anysdk.AdsType} adstype + * @param {Number} idx + */ + preloadAds: function(adstype, idx){ + }, + + /** + * !#en + * query points + * !#zh + * 查询分数 + * @method queryPoints + * @return {Number} + */ + queryPoints : function (){ + return 0; + }, + + /** + * !#en + * get whether the ads type is supported + * !#zh + * 获取广告类型是否支持 + * @method isAdTypeSupported + * @param {anysdk.AdsType} arg0 + * @return {boolean} + */ + isAdTypeSupported: function (adstype){ + return false; + }, + + /** + * !#en + * spend point + * !#zh + * 消费分数 + * @method spendPoints + * @param {Number} points + */ + spendPoints: function(points){ + }, + + /** + * !#en + * set listener + * !#zh + * 设置自定义系统的监听 + * @method setListener + * @param {Function} listener + * @param {Object} target + */ + setListener: function(listener, target) { + }, + + /** + * !#en + * get listener + * !#zh + * @method getListener + * 获取自定义系统的监听 + * @return {Function} listener + */ + getListener: function() { + return Function; + }, + +}); + +/** + * @class ProtocolSocial + */ +anysdk.ProtocolSocial = PluginProtocol.extend({ + + /** + * !#en + * sign in + * !#zh + * 登录 + * @method signIn + */ + signIn: function(){ + }, + + /** + * !#en + * sign out + * !#zh + * 登出 + * @method signOut + */ + signOut: function(){ + }, + + /** + * !#en + * submit score + * !#zh + * 提交分数 + * @method submitScore + * @param {String} leadboardID + * @param {Number} score Type: long + */ + submitScore: function(leadboardID, score){ + }, + + /** + * !#en + * show the id of Leaderboard page + * !#zh + * 根据唯一标识符显示排行榜 + * @method showLeaderboard + * @param {String} leaderboardID + */ + showLeaderboard: function(leaderboardID){ + }, + + /** + * !#en + * show the page of achievements + * !#zh + * 显示成就榜 + * @method showAchievements + */ + showAchievements: function(){ + }, + + /** + * !#en + * unlock achievement + * !#zh + * 解锁成就 + * @method share + * @param {Object} info Type: map + */ + unlockAchievement: function (info){ + }, + + /** + * !#en + * set listener + * !#zh + * 设置自定义系统的监听 + * @method setListener + * @param {Function} listener + * @param {Object} target + */ + setListener: function(listener, target) { + }, + + /** + * !#en + * get listener + * !#zh + * @method getListener + * 获取自定义系统的监听 + * @return {Function} listener + */ + getListener: function() { + return Function; + }, + + + /** + * !#en + * get friends info + * Before to invoke, you need to verdict whether this properties existed + * !#zh + * 获取好友信息,调用前需要判断属性是否存在 + * @method pauseRecording + */ + getFriendsInfo: function(){ + }, + + /** + * !#en + * interact + * Before to invoke, you need to verdict whether this properties existed + * !#zh + * 订阅,调用前需要判断属性是否存在 + * @method interact + */ + interact: function(){ + }, + + /** + * !#en + * subscribe + * Before to invoke, you need to verdict whether this properties existed + * !#zh + * 关注,调用前需要判断属性是否存在 + * @method subscribe + */ + subscribe: function(){ + }, +}); + +/** + * @class ProtocolPush + */ +anysdk.ProtocolPush = PluginProtocol.extend({ + + /** + * !#en + * start Push services + * !#zh + * 启动推送服务 + * @method startPush + */ + startPush: function(){ + }, + + /** + * !#en + * close Push services + * !#zh + * 暂停推送服务 + * @method closePush + */ + closePush: function(){ + }, + + /** + * !#en + * delete alias + * !#zh + * 删除别名 + * @method delAlias + * @param {String} alias + */ + delAlias: function(alias){ + }, + + /** + * !#en + * set alias + * !#zh + * 设置别名 + * @method setAlias + * @param {String} alias + */ + setAlias: function(alias){ + }, + + /** + * !#en + * delete tags + * !#zh + * 删除标签 + * @method delTags + * @param {Object} tags Type: list + */ + delTags: function(tags){ + }, + + /** + * !#en + * set tags + * !#zh + * 设置标签 + * @method setTags + * @param {Object} tags Type: list + */ + setTags: function(tags){ + }, + + /** + * !#en + * set listener + * !#zh + * 设置自定义系统的监听 + * @method setListener + * @param {Function} listener + * @param {Object} target + */ + setListener: function(listener, target) { + }, + + /** + * !#en + * get listener + * !#zh + * @method getListener + * 获取自定义系统的监听 + * @return {Function} listener + */ + getListener: function() { + return Function; + }, + +}); + +/** + * @class ProtocolCrash + */ +anysdk.ProtocolCrash = PluginProtocol.extend({ + + /** + * !#en + * set user identifier + * !#zh + * 统计用户唯一标识符 + * @method setUserIdentifier + * @param {String} identifier + */ + setUserIdentifier: function(identifier) + { + }, + + /** + * !#en + * The uploader captured in exception information + * !#zh + * 上报异常信息 + * @method reportException + * @param {String} message + * @param {String} exception + */ + reportException: function(message, exception){ + }, + + /** + * !#en + * customize logging + * !#zh + * 自定义日志记录 + * @method leaveBreadcrumb + * @param {String} breadcrumb + */ + leaveBreadcrumb : function (breadcrumb) + { + }, + +}); + +/** + * @class ProtocolREC + */ +anysdk.ProtocolREC = PluginProtocol.extend({ + + /** + * !#en + * share video + * !#zh + * 分享视频 + * @method share + * @param {Object} info Type: map + */ + share: function (info){ + }, + + /** + * !#en + * Start to record video + * !#zh + * 开始录制视频 + * @method startRecording + */ + startRecording: function(){ + }, + + /** + * !#en + * Start to record video + * !#zh + * 结束录制视频 + * @method stopRecording + */ + stopRecording: function(){ + }, + + /** + * !#en + * set listener + * !#zh + * 设置自定义系统的监听 + * @method setListener + * @param {Function} listener + * @param {Object} target + */ + setListener: function(listener, target) { + }, + + /** + * !#en + * get listener + * !#zh + * @method getListener + * 获取自定义系统的监听 + * @return {Function} listener + */ + getListener: function() { + return Function; + }, + + /** + * !#en + * pause to record video + * Before to invoke, you need to verdict whether this properties existed + * !#zh + * 暂停录制视频,调用前需要判断属性是否存在 + * @method pauseRecording + */ + pauseRecording: function(){ + }, + + /** + * !#en + * resume to record video + * Before to invoke, you need to verdict whether this properties existed + * !#zh + * 恢复录制视频,调用前需要判断属性是否存在 + * @method resumeRecording + */ + resumeRecording: function(){ + }, + + /** + * !#en + * get whether the device is isAvailable + * Before to invoke, you need to verdict whether this properties existed + * !#zh + * 获取设备是否可用,调用前需要判断属性是否存在 + * @method isAvailable + * @return {boolean} + */ + isAvailable: function(){ + return boolean; + }, + + /** + * !#en + * get status of recording + * Before to invoke, you need to verdict whether this properties existed + * !#zh + * 获取录制状态,调用前需要判断属性是否存在 + * @method isRecording + * @return {boolean} + */ + isRecording: function(){ + return boolean; + }, + + /** + * !#en + * show toolbar + * Before to invoke, you need to verdict whether this properties existed + * !#zh + * 显示悬浮窗,调用前需要判断属性是否存在 + * @method showToolBar + */ + showToolBar: function(){ + }, + + /** + * !#en + * hide toolbar + * Before to invoke, you need to verdict whether this properties existed + * !#zh + * 隐藏悬浮窗,调用前需要判断属性是否存在 + * @method hideToolBar + */ + hideToolBar: function(){ + }, + + /** + * !#en + * show video center + * Before to invoke, you need to verdict whether this properties existed + * !#zh + * 显示视频中心,调用前需要判断属性是否存在 + * @method showVideoCenter + */ + showVideoCenter: function(){ + }, + + /** + * !#en + * enter platform + * Before to invoke, you need to verdict whether this properties existed + * !#zh + * 显示平台中心,调用前需要判断属性是否存在 + * @method enterPlatform + */ + enterPlatform: function(){ + }, + + /** + * !#en + * Set the video data, it is recommended to check whether are recorded firstly + * Before to invoke, you need to verdict whether this properties existed + * !#zh + * 设置视频相关数据,建议先检查是否是正在录制,调用前需要判断属性是否存在 + * @method setMetaData + * @param {Object} info Type: map + */ + setMetaData: function(info){ + }, + +}); + + + +/** + * @class ProtocolAdTracking + */ +anysdk.ProtocolAdTracking = PluginProtocol.extend({ + + /** + * !#en + * Call this method if you want to track register events as happening during a section. + * !#zh + * 统计用户注册信息 + * @method onPay + * @param {Object} productInfo Type: map + */ + onPay : function (productInfo){ + }, + + /** + * !#en + * Call this method if you want to track register events as happening during a section. + * !#zh + * 统计用户注册信息 + * @method onLogin + * @param {Object} userInfo Type: map + */ + onLogin: function(userInfo){ + }, + + /** + * !#en + * Call this method if you want to track register events as happening during a section. + * !#zh + * 统计用户注册信息 + * @method onRegister + * @param {String} userId + */ + onRegister: function(userId){ + }, + + /** + * !#en + * Call this method if you want to track custom events with parameters as happening during a section. + * !#zh + * 统计自定义事件 + * @method trackEvent + * @param {String} eventId + * @param {Object} paramMap Type: map + */ + trackEvent: function(eventId, paramMap){ + }, + + /** + * !#en + * Call this method with parameters if you want to create role as happening during a section. + * !#zh + * 统计创建角色事件,调用前需要判断属性是否存在 + * @method onCreateRole + * @param {Object} userInfo Type: map + */ + onCreateRole: function(userInfo){ + }, + + /** + * !#en + * Call this method if you want to track levelup events with parameters as happening during a section. + * Before to invoke, you need to verdict whether this properties existed + * !#zh + * 统计角色升级事件,调用前需要判断属性是否存在 + * @method onLevelUp + * @param {Object} info Type: map + */ + onLevelUp: function(info){ + }, + + /** + * !#en + * Invoke this method with parameters if you want to start to pay as happening during a section. + * Before to invoke, you need to verdict whether this properties existed + * !#zh + * 统计开始充值事件,调用前需要判断属性是否存在 + * @method onStartToPay + * @param {Object} info Type: map + */ + onStartToPay: function(info){ + }, + +}); + +/** + * @class ProtocolCustom + */ +anysdk.ProtocolCustom = PluginProtocol.extend({ + /** + * !#en + * set listener + * !#zh + * 设置自定义系统的监听 + * @method setListener + * @param {Function} listener + * @param {Object} target + */ + setListener: function(listener, target) { + }, + + /** + * !#en + * get listener + * !#zh + * 获取自定义系统的监听 + * @method getListener + * @return {Function} listener + */ + getListener: function() { + return Function; + }, +}); + +/** + * !#en The callback of user system + * !#zh 用户系统回调 + * @enum UserActionResultCode + */ +anysdk.UserActionResultCode = { + /** + * !#en The callback of succeeding in initing sdk + * !#zh 用户系统的初始化成功回调 + * @property {Number} kInitSuccess + */ + kInitSuccess: 0, + + /** + * !#en The callback of failing to init sdk + * !#zh 用户系统的初始化失败回调 + * @property {Number} kInitFail + */ + kInitFail: 1, + + /** + * !#en The callback of succeeding in login. + * !#zh 用户系统的登录成功回调 + * @property {Number} kLoginSuccess + */ + kLoginSuccess: 2, + + /** + * !#en The callback of network error + * !#zh 用户系统的初始化成功回调 + * @property {Number} kLoginNetworkError + */ + kLoginNetworkError: 3, + + /** + * !#en The callback of no need login. + * !#zh 用户系统的无需登录回调 + * @property {Number} kLoginNoNeed + */ + kLoginNoNeed: 4, + + /** + * !#en The callback of failing to login + * !#zh 用户系统的登录失败回调 + * @property {Number} kLoginFail + */ + kLoginFail: 5, + + /** + * !#en The callback of canceling to login. + * !#zh 用户系统的登录取消回调 + * @property {Number} kLoginCancel + */ + kLoginCancel: 6, + + /** + * !#en The callback of succeeding in logout + * !#zh 用户系统的登出成功回调 + * @property {Number} kLogoutSuccess + */ + kLogoutSuccess: 7, + + /** + * !#en The callback of failing to logout + * !#zh 用户系统的登出失败回调 + * @property {Number} kLogoutFail + */ + kLogoutFail: 8, + + /** + * !#en The callback after enter platform.. + * !#zh 用户系统的进入平台回调 + * @property {Number} kPlatformEnter + */ + kPlatformEnter: 9, + + /** + * !#en The callback after exit antiAddiction + * !#zh 用户系统的退出平台回调 + * @property {Number} kPlatformBack + */ + kPlatformBack: 10, + + /** + * !#en The callback after exit pause page + * !#zh 用户系统的暂停界面回调 + * @property {Number} kPausePage + */ + kPausePage: 11, + + /** + * !#en The callback after exit page + * !#zh 用户系统的退出界面回调 + * @property {Number} kExitPage + */ + kExitPage: 12, + + /** + * !#en The callback after querying antiAddiction + * !#zh 用户系统的实名认证回调 + * @property {Number} kAntiAddictionQuery + */ + kAntiAddictionQuery: 13, + + /** + * !#en The callback after registering realname + * !#zh 用户系统的注册账号回调 + * @property {Number} kRealNameRegister + */ + kRealNameRegister: 14, + + /** + * !#en The callback of succeeding in switching account + * !#zh 用户系统的切换账号成功回调 + * @property {Number} kAccountSwitchSuccess + */ + kAccountSwitchSuccess: 15, + + /** + * !#en The callback of failing to switch account + * !#zh 用户系统的切换账号失败回调 + * @property {Number} kAccountSwitchFail + */ + kAccountSwitchFail: 16, + + /** + * !#en The callback of opening the shop + * !#zh 用户系统的打开商店回调 + * @property {Number} kOpenShop + */ + kOpenShop: 17, + + /** + * !#en The callback of canceling to switch account. + * !#zh 用户系统的取消切换账号回调 + * @property {Number} kAccountSwitchCancel + */ + kAccountSwitchCancel: 18, + + /** + * !#en extension code of user type + * !#zh 用户系统的扩展回调 + * @property {Number} kUserExtension + */ + kUserExtension: 50000, + + /** + * !#en The callback of succeeding in sending to desktop + * !#zh 用户系统的发送到桌面成功回调 + * @property {Number} kSendToDesktopSuccess + */ + kSendToDesktopSuccess: 51001, + /** + * !#en The callback of failing to sending to desktop + * !#zh 用户系统的发送到桌面失败回调 + * @property {Number} kSendToDesktopFail + */ + kSendToDesktopFail: 51002, + + /** + * !#en The callback of succeeding in getting available login type + * !#zh 用户系统的获取可登录类型成功回调 + * @property {Number} kGetAvailableLoginTypeSuccess + */ + kGetAvailableLoginTypeSuccess: 51003, + + /** + * !#en The callback of failing to get available login type + * !#zh 用户系统的获取可登录类型失败回调 + * @property {Number} kGetAvailableLoginTypeFail + */ + kGetAvailableLoginTypeFail: 51004 , + + /** + * !#en The callback of succeeding in getting user info + * !#zh 用户系统的获取用户信息成功回调 + * @property {Number} kGetUserInfoSuccess + */ + kGetUserInfoSuccess: 51005, + + /** + * !#en The callback of failing in getting user`s info + * !#zh 用户系统的获取用户信息失败回调 + * @property {Number} kGetUserInfoFail + */ + kGetUserInfoFail: 51006 , + + /** + * !#en The callback of succeeding in opening BBS. + * !#zh 用户系统的进入论坛成功回调 + * @property {Number} kOpenBBSSuccess + */ + kOpenBBSSuccess: 51007, + + /** + * !#en The callback of failing in opening BBS + * !#zh 用户系统的进入论坛失败回调 + * @property {Number} kOpenBBSFail + */ + kOpenBBSFail: 51008 + +}; + +/** + * !#en The toolbar position of user type + * !#zh 用户系统悬浮窗位置 + * @enum ToolBarPlace + */ +anysdk.ToolBarPlace = { + /** + * !#en The upper left corner + * !#zh 左上方 + * @property {Number} kToolBarTopLeft + */ + kToolBarTopLeft: 1, + + /** + * !#en the upper right corner + * !#zh 右上方 + * @property {Number} kToolBarTopRight + */ + kToolBarTopRight: 2, + + /** + * !#en at the left of the center + * !#zh 中间偏左 + * @property {Number} kToolBarMidLeft + */ + kToolBarMidLeft: 3, + + /** + * !#en At the right of the center + * !#zh 中间偏右 + * @property {Number} kToolBarMidRight + */ + kToolBarMidRight: 4, + + /** + * !#en The lower left corner + * !#zh 左下方 + * @property {Number} kToolBarBottomLeft + */ + kToolBarBottomLeft: 5, + + /** + * !#en The lower right corner + * !#zh 右下方 + * @property {Number} kToolBarBottomRight + */ + kToolBarBottomRight: 6 +}; + +/** + * !#en The callback of IAP type + * !#zh 支付系统回调 + * @enum PayResultCode + */ +anysdk.PayResultCode = { + /** + * !#en The callback of succeeding in paying + * !#zh 支付系统的支付成功回调 + * @property {Number} kPaySuccess + */ + kPaySuccess: 0, + + /** + * !#en The callback of failing to pay + * !#zh 支付系统的支付失败回调 + * @property {Number} kPayFail + */ + kPayFail: 1, + + /** + * !#en The callback of canceling to pay + * !#zh 支付系统的支付取消回调 + * @property {Number} kPayCancel + */ + kPayCancel: 2, + + /** + * !#en The callback of network error + * !#zh 支付系统的网络失败回调 + * @property {Number} kPayNetworkError + */ + kPayNetworkError: 3, + + /** + * !#en The callback of incompleting info + * !#zh 支付系统的支付信息不完整回调 + * @property {Number} kPayProductionInforIncomplete + */ + kPayProductionInforIncomplete: 4, + + /** + * !#en callback of succeeding in initing sdk . + * !#zh 支付系统的初始化成功回调 + * @property {Number} kPayInitSuccess + */ + kPayInitSuccess: 5, + + /** + * !#en The callback of failing to init sdk + * !#zh 支付系统的初始化失败回调 + * @property {Number} kPayInitFail + */ + kPayInitFail: 6, + + /** + * !#en The callback of paying now + * !#zh 支付系统的正在支付回调 + * @property {Number} kPayNowPaying + */ + kPayNowPaying: 7, + + /** + * !#en The callback of succeeding in reStringging + * !#zh 支付系统的充值成功回调 + * @property {Number} kPayReStringgeSuccess + */ + kPayReStringgeSuccess: 8, + + /** + * !#en extension code of user type + * !#zh 支付系统的扩展回调 + * @property {Number} kPayExtension + */ + kPayExtension: 30000, + + /** + * !#en The callback of re-logining . + * !#zh 支付系统的重登陆回调 + * @property {Number} kPayNeedLoginAgain + */ + kPayNeedLoginAgain: 31002 +}; + +/** + * !#en The callback of requesting reStringge + * !#zh 支付系统支付请求回调 + * @enum PayResultCode + */ +anysdk.RequestResultCode = { + /** + * !#en The callback of succeeding in requesting . + * !#zh 支付系统的请求成功回调 + * @property {Number} kRequestSuccess + */ + kRequestSuccess: 31000, + + /** + * !#en The callback of failing to requesting . + * !#zh 支付系统的请求失败回调 + * @property {Number} kRequestFail + */ + kRequestFail: 31001 +}; + +/** + * !#en The enum of account type + * !#zh 统计系统的账号类型 + * @enum AccountType + */ +anysdk.AccountType = { + /** + * !#en The source of account is anonymous + * !#zh 账号来源:匿名 + * @property {Number} ANONYMOUS + */ + ANONYMOUS: 0, + + /** + * !#en The source of account is Registered + * !#zh 账号来源:注册 + * @property {Number} REGISTED + */ + REGISTED: 1, + + /** + * !#en The source of account is Sina weibo + * !#zh 账号来源:新浪微博 + * @property {Number} SINA_WEIBO + */ + SINA_WEIBO: 2, + + /** + * !#en The source of account is Tencent weibo + * !#zh 账号来源:腾讯微博 + * @property {Number} TENCENT_WEIBO + */ + TENCENT_WEIBO: 3, + + /** + * !#en The source of account is QQ + * !#zh 账号来源:QQ + * @property {Number} QQ + */ + QQ: 4, + + /** + * !#en The source of account is ND91 + * !#zh 账号来源:ND91 + * @property {Number} ND91 + */ + ND91: 5 +}; + +/** + * !#en The enum of account operation + * !#zh 统计系统的账号操作 + * @enum AccountOperate + */ +anysdk.AccountOperate = { + /** + * !#en Login + * !#zh 登录 + * @property {Number} LOGIN + */ + LOGIN: 0, + + /** + * !#en Logout + * !#zh 登出 + * @property {Number} LOGOUT + */ + LOGOUT: 1, + + /** + * !#en Register + * !#zh 注册 + * @property {Number} REGISTER + */ + REGISTER: 2 +}; + +/** + * !#en The enum of gender + * !#zh 统计系统的账号性别 + * @enum AccountGender + */ +anysdk.AccountGender = { + /** + * !#en Male + * !#zh 男性 + * @property {Number} MALE + */ + MALE: 0, + /** + * !#en Female + * !#zh 女性 + * @property {Number} FEMALE + */ + FEMALE: 1, + + /** + * !#en Unknow + * !#zh 未知 + * @property {Number} UNKNOWN + */ + UNKNOWN: 2 +}; + +/** + * !#en The enum of task type + * !#zh 统计系统的任务类型 + * @enum TaskType + */ +anysdk.TaskType = { + /** + * !#en Guide line + * !#zh 新手引导 + * @property {Number} GUIDE_LINE + */ + GUIDE_LINE: 0, + + /** + * !#en Main line + * !#zh 主线 + * @property {Number} MAIN_LINE + */ + MAIN_LINE: 1, + + /** + * !#en Branch line + * !#zh 支线 + * @property {Number} BRANCH_LINE + */ + BRANCH_LINE: 2, + + /** + * !#en Daily + * !#zh 日常 + * @property {Number} DAILY + */ + DAILY: 3, + + /** + * !#en Activity + * !#zh 活动 + * @property {Number} ACTIVITY + */ + ACTIVITY: 4, + + /** + * !#en Other + * !#zh 其他 + * @property {Number} OTHER + */ + OTHER: 5 +}; + +/** + * !#en The callback of share system + * !#zh 分享系统回调 + * @enum ShareResultCode + */ +anysdk.ShareResultCode = { + /** + * !#en The callback of failing to sharing + * !#zh 分享系统的分享成功回调 + * @property {Number} kShareSuccess + */ + kShareSuccess: 0, + + /** + * !#en The callback of failing to share + * !#zh 分享系统的分享失败回调 + * @property {Number} kShareFail + */ + kShareFail: 1, + + /** + * !#en The callback of canceling to share + * !#zh 分享系统的分享取消回调 + * @property {Number} kShareCancel + */ + kShareCancel: 2, + + /** + * !#en The callback of network error + * !#zh 分享系统的网络错误回调 + * @property {Number} kShareNetworkError + */ + kShareNetworkError: 3, + + /** + * !#en The extension code of share system + * !#zh 分享系统的扩展回调 + * @property {Number} kShareExtension + */ + kShareExtension: 10000 +}; + +/** + * !#en The callback of social system + * !#zh 社交系统回调 + * @enum SocialRetCode + */ +anysdk.SocialRetCode = { + + /** + * !#en The callback of succeeding in submiting. + * !#zh 社交系统的成功提交回调 + * @property {Number} kScoreSubmitSucceed + */ + kScoreSubmitSucceed: 1, + + /** + * !#en The callback of failing to submit. + * !#zh 社交系统的提交失败回调 + * @property {Number} kScoreSubmitfail + */ + kScoreSubmitfail: 2, + + /** + * !#en The is callback of succeeding in unlocking + * !#zh 社交系统的解锁成功回调 + * @property {Number} kAchUnlockSucceed + */ + kAchUnlockSucceed: 3, + + /** + * !#en The callback of failing to unlock. + * !#zh 社交系统的解锁失败回调 + * @property {Number} kAchUnlockFail + */ + kAchUnlockFail: 4, + + /** + * !#en The callback of succeeding to login. + * !#zh 社交系统的登录成功回调 + * @property {Number} kSocialSignInSucceed + */ + kSocialSignInSucceed: 5, + + /** + * !#en The callback of failing to login + * !#zh 社交系统的登录失败回调 + * @property {Number} kSocialSignInFail + */ + kSocialSignInFail: 6, + + /** + * !#en The callback of succeeding to logout. + * !#zh 社交系统的登出成功回调 + * @property {Number} kSocialSignOutSucceed + */ + kSocialSignOutSucceed: 7, + + /** + * !#en The callback of failing to logout. + * !#zh 社交系统的登出失败回调 + * @property {Number} kSocialSignOutFail + */ + kSocialSignOutFail: 8, + + /** + * !#en The callback of getting friends`s . + * !#zh 社交系统的获取好友回调 + * @property {Number} kSocialGetGameFriends + */ + kSocialGetGameFriends: 9, + + /** + * !#en The extension code of social system + * !#zh 社交系统的扩展回调 + * @property {Number} kSocialExtensionCode + */ + kSocialExtensionCode:20000, + + /** + * !#en The callback of succeeding in getting friends`s info + * !#zh 社交系统的获取好友信息成功回调 + * @property {Number} kSocialGetFriendsInfoSuccess + */ + kSocialGetFriendsInfoSuccess: 21001, + + /** + * !#en The callback of failing in getting friends`s info. + * !#zh 社交系统的获取好友信息失败回调 + * @property {Number} kSocialGetFriendsInfoFail + */ + kSocialGetFriendsInfoFail: 21002, + + /** + * !#en The callback of subscription + * !#zh 社交系统的订阅回调 + * @property {Number} kSocialAlreadySubscription + */ + kSocialAlreadySubscription: 21003, + + /** + * !#en The callback No subscription. + * !#zh 社交系统的无需订阅回调 + * @property {Number} kSocialNoSubscription + */ + kSocialNoSubscription: 21004, + + /** + * !#en The callback of failing in subscription + * !#zh 社交系统的订阅失败回调 + * @property {Number} kSocialSubscriptionFail + */ + kSocialSubscriptionFail: 21005, +}; + +/** + * !#en The callback of ads system + * !#zh 广告系统回调 + * @enum AdsResultCode + */ +anysdk.AdsResultCode = { + + /** + * !#en The callback : the ad is received + * !#zh 广告系统的接受广告回调 + * @property {Number} kAdsReceived + */ + kAdsReceived: 0, + + /** + * !#en The callback: the advertisement dismissed. + * !#zh 广告系统的显示广告回调 + * @property {Number} kAdsShown + */ + kAdsShown: 1, + + /** + * !#en The callback: the advertisement dismissed. + * !#zh 广告系统的广告消失回调 + * @property {Number} kAdsDismissed + */ + kAdsDismissed: 2, + + /** + * !#en The callback: the points spend succeed. + * !#zh 广告系统的花费积分成功回调 + * @property {Number} kPointsSpendSucceed + */ + kPointsSpendSucceed: 3, + + /** + * !#en The callback: the points spend failed. + * !#zh 广告系统的花费积分失败回调 + * @property {Number} kPointsSpendFailed + */ + kPointsSpendFailed: 4, + + /** + * !#en The callback of network error + * !#zh 广告系统的网络错误回调 + * @property {Number} kNetworkError + */ + kNetworkError: 5, + + /** + * !#en The callback of Unknown error. + * !#zh 广告系统的未知错误回调 + * @property {Number} kUnknownError + */ + kUnknownError: 6, + + /** + * !#en The callback of Changing the point of offerwall. + * !#zh 广告系统的积金墙积金变化回调 + * @property {Number} kOfferWallOnPointsChanged + */ + kOfferWallOnPointsChanged: 7, + + /** + * !#en The callback of receive the reward of rewardedvideo + * !#zh 广告系统的激励视频奖励回调 + * @property {Number} kRewardedVideoWithReward + */ + kRewardedVideoWithReward: 8, + + /** + * !#en The callback of finishing IAP ad + * !#zh 广告系统的应用内支付广告回调 + * @property {Number} kInAppPurchaseFinished + */ + kInAppPurchaseFinished: 9, + + /** + * !#en The callback of the advertisement clicked + * !#zh 广告系统的广告被点击回调 + * @property {Number} kAdsClicked + */ + kAdsClicked: 10, + + /** + * !#en The extension code + * !#zh 广告系统的扩展回调 + * @property {Number} kAdsExtension + */ + kAdsExtension: 40000 +}; + +/** + * !#en The enum of ads position + * !#zh 广告位置 + * @enum AdsPos + */ +anysdk.AdsPos = { + + /** + * !#en In the center + * !#zh 中间 + * @property {Number} kPosCenter + */ + kPosCenter:0, + + /** + * !#en at the top of center + * !#zh 上方 + * @property {Number} kPosTop + */ + kPosTop:1, + + /** + * !#en the upper left corner + * !#zh 左上方 + * @property {Number} kPosTopLeft + */ + kPosTopLeft:2, + + /** + * !#en the upper right corner + * !#zh 右上方 + * @property {Number} kPosTopRight + */ + kPosTopRight:3, + + /** + * !#en at the bottom of the center + * !#zh 底部 + * @property {Number} kPosBottom + */ + kPosBottom: 4, + + /** + * !#en the lower left corner + * !#zh 左下方 + * @property {Number} kPosBottomLeft + */ + kPosBottomLeft: 5, + + /** + * !#en the lower right corner + * !#zh 右下方 + * @property {Number} kPosBottomRight + */ + kPosBottomRight: 6 +}; + +/** + * !#en The enum of ads type + * !#zh 广告类型 + * @enum AdsType + */ +anysdk.AdsType = { + + /** + * !#en Banner Ads + * !#zh 横幅广告 + * @property {Number} AD_TYPE_BANNER + */ + AD_TYPE_BANNER: 0, + + /** + * !#en Full Screen Ads + * !#zh 插屏广告 + * @property {Number} AD_TYPE_FULLSCREEN + */ + AD_TYPE_FULLSCREEN: 1, + + /** + * !#en Move APP Ads + * !#zh 精品广告 + * @property {Number} AD_TYPE_MOREAPP + */ + AD_TYPE_MOREAPP: 2, + + /** + * !#en Offer Wall Ads + * !#zh 积金墙 + * @property {Number} AD_TYPE_OFFERWALL + */ + AD_TYPE_OFFERWALL: 3, + + /** + * !#en Reward Video Ads + * !#zh 激励视频 + * @property {Number} AD_TYPE_REWARDEDVIDEOc + */ + AD_TYPE_REWARDEDVIDEO: 4, + + /** + * !#en Native Express Ads + * !#zh 原生广告 + * @property {Number} AD_TYPE_NATIVEEXPRESS + */ + AD_TYPE_NATIVEEXPRESS: 5, + + /** + * !#en Native Advanced Ads + * !#zh 改进版原生广告 + * @property {Number} AD_TYPE_NATIVEADVANCED + */ + AD_TYPE_NATIVEADVANCED: 6 +}; + +/** + * !#en The callback of push system + * !#zh 推送系统回调 + * @enum PushActionResultCode + */ +anysdk.PushActionResultCode = { + /** + * !#en The callback of Receiving Message + * !#zh 推送系统的接受消息回调 + * @property {Number} kPushReceiveMessage + */ + kPushReceiveMessage: 0, + + /** + * !#en The extension code + * !#zh 推送系统的扩展回调 + * @property {Number} kPushExtensionCode + */ + kPushExtensionCode: 60000 +}; + +/** + * !#en The callback of custom system + * !#zh 自定义系统回调 + * @enum CustomResultCode + */ +anysdk.CustomResultCode = { + /** + * !#en The extension code of custom system + * !#zh 自定义系统扩展回调 + * @property {Number} kCustomExtension + */ + kCustomExtension:80000 +} ; + +/** + * !#en The callback of REC system + * !#zh 录屏系统回调 + * @enum RECResultCode + */ +anysdk.RECResultCode = { + + /** + * !#en The callback of succeeding in initing sdk + * !#zh 录屏系统的初始化成功回调 + * @property {Number} kRECInitSuccess + */ + kRECInitSuccess: 0, + + /** + * !#en The callback of failing to init sdk. + * !#zh 录屏系统的初始化失败回调 + * @property {Number} kRECInitFail + */ + kRECInitFail: 1, + + /** + * !#en The callback of starting to record. + * !#zh 录屏系统的开始录屏回调 + * @property {Number} kRECStartRecording + */ + kRECStartRecording: 2, + + /** + * !#en The callback of stoping to record. + * !#zh 录屏系统的停止录屏回调 + * @property {Number} kRECStopRecording + */ + kRECStopRecording: 3, + + /** + * !#en The callback of pausing to record. + * !#zh 录屏系统的暂停录屏回调 + * @property {Number} kRECPauseRecording + */ + kRECPauseRecording: 4, + + /** + * !#en The callback of resuming to record. + * !#zh 录屏系统的恢复录屏回调 + * @property {Number} kRECResumeRecording + */ + kRECResumeRecording: 5, + + /** + * !#en The callback of entering SDK`s page. + * !#zh 录屏系统的初进入SDK界面回调 + * @property {Number} kRECEnterSDKPage + */ + kRECEnterSDKPage: 6, + + /** + * !#en The callback of quiting SDK`s page. + * !#zh 录屏系统的退出SDK界面回调 + * @property {Number} kRECQuitSDKPage + */ + kRECQuitSDKPage: 7, + + /** + * !#en The callback of succeeding in initing sdk + * !#zh 录屏系统的分享成功回调 + * @property {Number} kRECShareSuccess + */ + kRECShareSuccess: 8, + + /** + * !#en The callback of failing to share. + * !#zh 录屏系统的分享失败回调 + * @property {Number} kRECShareFail + */ + kRECShareFail: 9,/**< enum value is callback of failing to share. */ + + /** + * !#en The extension code of REC system + * !#zh 录屏系统的扩展回调 + * @property {Number} kRECExtension + */ + kRECExtension: 90000 +}; + + + + + + + + + + + + From 72accea8ccc30c59d81ba5be70fe4e2dbc4488ff Mon Sep 17 00:00:00 2001 From: "yanli.huang" Date: Wed, 3 Aug 2016 16:09:05 +0800 Subject: [PATCH 110/268] modify anysdk api doc --- extensions/anysdk/jsb_anysdk.js | 158 ++++++++++++++++++++++++-------- 1 file changed, 118 insertions(+), 40 deletions(-) diff --git a/extensions/anysdk/jsb_anysdk.js b/extensions/anysdk/jsb_anysdk.js index 51938640a4..dbb669b151 100644 --- a/extensions/anysdk/jsb_anysdk.js +++ b/extensions/anysdk/jsb_anysdk.js @@ -33,17 +33,22 @@ * @main anysdk */ var anysdk = anysdk || {}; - /** * !#en * agent manager of plugin * !#zh * 插件管理对象 - * @property {object} anysdk.agentManager + * @property {anysdk.AgentManager} agentManager */ anysdk.agentManager = anysdk.AgentManager.getInstance(); + /** + * !#en + * agent manager of plugin + * !#zh + * 插件管理类 * @class AgentManager + * @constructor */ anysdk.AgentManager = { /** @@ -103,7 +108,7 @@ anysdk.AgentManager = { * get IAP system plugins * !#zh * 获取支付系统插件 - * @method getIAPPlugin + * @method getIAPPlugins * @return {anysdk.ProtocolIAP} */ getIAPPlugins: function(){ @@ -274,8 +279,7 @@ anysdk.AgentManager = { * @method setIsAnaylticsEnabled * @param {boolean} enabled */ - setIsAnaylticsEnabled: function(enabled) - { + setIsAnaylticsEnabled: function(enabled){ }, /** @@ -284,9 +288,9 @@ anysdk.AgentManager = { * !#zh * 销毁单例 * @method end + * @static */ - end: function() - { + end: function(){ }, /** @@ -296,13 +300,15 @@ anysdk.AgentManager = { * 获取单例 * @method getInstance * @return {anysdk.AgentManager} + * @static */ - getInstance: function() - { + getInstance: function(){ return anysdk.AgentManager; }, }; + + /** * !#en * plugin protocol @@ -364,28 +370,26 @@ anysdk.PluginProtocol = { }, /** - * @brief methods for reflections * !#en * void methods for reflections with parameter * !#zh * 反射调用带参数的void方法 * @method callFuncWithParam * @param {String} funName - * @param {String} [...args] optional arguments + * @param {Object|anysdk.PluginParam} [...args] optional arguments * @expose */ callFuncWithParam: function(funName){ }, /** - * @brief methods for reflections * !#en * String methods for reflections with parameter * !#zh * 反射调用带参数的 String 方法 * @method callStringFuncWithParam * @param {String} funName - * @param {String} [...args] optional arguments + * @param {Object|anysdk.PluginParam} [...args] optional arguments * @return {String} * @expose */ @@ -394,14 +398,13 @@ anysdk.PluginProtocol = { }, /** - * @brief methods for reflections * !#en * int methods for reflections with parameter * !#zh * 反射调用带参数的 Int 方法 * @method callIntFuncWithParam * @param {String} funName - * @param {String} [...args] optional arguments + * @param {Object|anysdk.PluginParam} [...args] optional arguments * @return {Number} Type:int * @expose */ @@ -410,14 +413,13 @@ anysdk.PluginProtocol = { }, /** - * @brief methods for reflections * !#en * boolean methods for reflections with parameter * !#zh * 反射调用带参数的 boolean 方法 * @method callBoolFuncWithParam * @param {String} funName - * @param {String} [...args] optional arguments + * @param {Object|anysdk.PluginParam} [...args] optional arguments * @return {boolean} * @expose */ @@ -426,14 +428,13 @@ anysdk.PluginProtocol = { }, /** - * @brief methods for reflections * !#en * float methods for reflections with parameter * !#zh * 反射调用带参数的 float 方法 - * @method callBoolFuncWithParam + * @method callFloatFuncWithParam * @param {String} funName - * @param {String} [...args] optional arguments + * @param {Object|anysdk.PluginParam} [...args] optional arguments * @return {Number} Type:float * @expose */ @@ -443,7 +444,12 @@ anysdk.PluginProtocol = { }; /** + * !#en + * user protocol + * !#zh + * 用户系统协议接口 * @class ProtocolUser + * @extends PluginProtocol */ anysdk.ProtocolUser = PluginProtocol.extend({ @@ -453,7 +459,7 @@ anysdk.ProtocolUser = PluginProtocol.extend({ * !#zh * 登录接口 * @method login - * @param {String} [...args] optional arguments + * @param {String|Objcet} [...args] optional arguments */ login: function(){ }, @@ -500,7 +506,7 @@ anysdk.ProtocolUser = PluginProtocol.extend({ * !#en * set listener * !#zh - * 设置自定义系统的监听 + * 设置用户系统的监听 * @method setListener * @param {Function} listener * @param {Object} target @@ -512,8 +518,8 @@ anysdk.ProtocolUser = PluginProtocol.extend({ * !#en * get listener * !#zh + * 获取用户系统的监听 * @method getListener - * 获取自定义系统的监听 * @return {Function} listener */ getListener: function() { @@ -616,7 +622,7 @@ anysdk.ProtocolUser = PluginProtocol.extend({ * !#zh * 提交角色信息,调用前需要判断属性是否存在 * @method submitLoginGameRole - * @param {String} data + * @param {Object} data */ submitLoginGameRole: function(data){ }, @@ -627,7 +633,7 @@ anysdk.ProtocolUser = PluginProtocol.extend({ * !#zh * 获取用户信息,调用前需要判断属性是否存在 * @method getUserInfo - * @param {String} info + * @param {Object} info */ getUserInfo:function(info){ }, @@ -639,7 +645,7 @@ anysdk.ProtocolUser = PluginProtocol.extend({ * !#zh * 设置登录类型,调用前需要判断属性是否存在 * @method getAvailableLoginType - * @param {String} info + * @param {Object} info */ getAvailableLoginType:function(info){ }, @@ -683,7 +689,12 @@ anysdk.ProtocolUser = PluginProtocol.extend({ /** + * !#en + * IAP protocol + * !#zh + * 支付系统协议接口 * @class ProtocolIAP + * @extends PluginProtocol */ anysdk.ProtocolIAP = PluginProtocol.extend({ @@ -737,7 +748,7 @@ anysdk.ProtocolIAP = PluginProtocol.extend({ * !#en * set listener * !#zh - * 设置自定义系统的监听 + * 设置支付系统的监听 * @method setListener * @param {Function} listener * @param {Object} target @@ -749,8 +760,8 @@ anysdk.ProtocolIAP = PluginProtocol.extend({ * !#en * get listener * !#zh + * 获取支付系统的监听 * @method getListener - * 获取自定义系统的监听 * @return {Function} listener */ getListener: function() { @@ -760,7 +771,12 @@ anysdk.ProtocolIAP = PluginProtocol.extend({ }); /** + * !#en + * analytics protocol + * !#zh + * 统计系统协议接口 * @class ProtocolAnalytics + * @extends PluginProtocol */ anysdk.ProtocolAnalytics = PluginProtocol.extend({ @@ -1011,7 +1027,12 @@ anysdk.ProtocolAnalytics = PluginProtocol.extend({ }); /** + * !#en + * share protocol + * !#zh + * 分享系统协议接口 * @class ProtocolShare + * @extends PluginProtocol */ anysdk.ProtocolShare = PluginProtocol.extend({ @@ -1029,7 +1050,7 @@ anysdk.ProtocolShare = PluginProtocol.extend({ * !#en * set listener * !#zh - * 设置自定义系统的监听 + * 设置分享系统的监听 * @method setListener * @param {Function} listener * @param {Object} target @@ -1041,8 +1062,8 @@ anysdk.ProtocolShare = PluginProtocol.extend({ * !#en * get listener * !#zh + * 获取分享系统的监听 * @method getListener - * 获取自定义系统的监听 * @return {Function} listener */ getListener: function() { @@ -1052,7 +1073,12 @@ anysdk.ProtocolShare = PluginProtocol.extend({ /** + * !#en + * ads protocol + * !#zh + * 广告系统协议接口 * @class ProtocolAds + * @extends PluginProtocol */ anysdk.ProtocolAds = PluginProtocol.extend({ /* @@ -1130,7 +1156,7 @@ anysdk.ProtocolAds = PluginProtocol.extend({ * !#en * set listener * !#zh - * 设置自定义系统的监听 + * 设置广告系统的监听 * @method setListener * @param {Function} listener * @param {Object} target @@ -1142,8 +1168,8 @@ anysdk.ProtocolAds = PluginProtocol.extend({ * !#en * get listener * !#zh + * 获取广告系统的监听 * @method getListener - * 获取自定义系统的监听 * @return {Function} listener */ getListener: function() { @@ -1153,7 +1179,12 @@ anysdk.ProtocolAds = PluginProtocol.extend({ }); /** + * !#en + * social protocol + * !#zh + * 社交系统协议接口 * @class ProtocolSocial + * @extends PluginProtocol */ anysdk.ProtocolSocial = PluginProtocol.extend({ @@ -1225,7 +1256,7 @@ anysdk.ProtocolSocial = PluginProtocol.extend({ * !#en * set listener * !#zh - * 设置自定义系统的监听 + * 设置社交系统的监听 * @method setListener * @param {Function} listener * @param {Object} target @@ -1237,8 +1268,8 @@ anysdk.ProtocolSocial = PluginProtocol.extend({ * !#en * get listener * !#zh + * 获取社交系统的监听 * @method getListener - * 获取自定义系统的监听 * @return {Function} listener */ getListener: function() { @@ -1281,7 +1312,12 @@ anysdk.ProtocolSocial = PluginProtocol.extend({ }); /** + * !#en + * push protocol + * !#zh + * 推送系统协议接口 * @class ProtocolPush + * @extends PluginProtocol */ anysdk.ProtocolPush = PluginProtocol.extend({ @@ -1353,7 +1389,7 @@ anysdk.ProtocolPush = PluginProtocol.extend({ * !#en * set listener * !#zh - * 设置自定义系统的监听 + * 设置推送系统的监听 * @method setListener * @param {Function} listener * @param {Object} target @@ -1365,8 +1401,8 @@ anysdk.ProtocolPush = PluginProtocol.extend({ * !#en * get listener * !#zh + * 获取推送系统的监听 * @method getListener - * 获取自定义系统的监听 * @return {Function} listener */ getListener: function() { @@ -1376,7 +1412,12 @@ anysdk.ProtocolPush = PluginProtocol.extend({ }); /** + * !#en + * crash protocol + * !#zh + * 崩溃分析系统协议接口 * @class ProtocolCrash + * @extends PluginProtocol */ anysdk.ProtocolCrash = PluginProtocol.extend({ @@ -1419,7 +1460,12 @@ anysdk.ProtocolCrash = PluginProtocol.extend({ }); /** + * !#en + * REC protocol + * !#zh + * 录屏系统协议接口 * @class ProtocolREC + * @extends PluginProtocol */ anysdk.ProtocolREC = PluginProtocol.extend({ @@ -1458,7 +1504,7 @@ anysdk.ProtocolREC = PluginProtocol.extend({ * !#en * set listener * !#zh - * 设置自定义系统的监听 + * 设置录屏系统的监听 * @method setListener * @param {Function} listener * @param {Object} target @@ -1470,8 +1516,8 @@ anysdk.ProtocolREC = PluginProtocol.extend({ * !#en * get listener * !#zh + * 获取录屏系统的监听 * @method getListener - * 获取自定义系统的监听 * @return {Function} listener */ getListener: function() { @@ -1587,7 +1633,12 @@ anysdk.ProtocolREC = PluginProtocol.extend({ /** + * !#en + * ad tracking protocol + * !#zh + * 广告追踪系统协议接口 * @class ProtocolAdTracking + * @extends PluginProtocol */ anysdk.ProtocolAdTracking = PluginProtocol.extend({ @@ -1674,7 +1725,12 @@ anysdk.ProtocolAdTracking = PluginProtocol.extend({ }); /** + * !#en + * custom protocol + * !#zh + * 自定义系统协议接口 * @class ProtocolCustom + * @extends PluginProtocol */ anysdk.ProtocolCustom = PluginProtocol.extend({ /** @@ -1702,6 +1758,30 @@ anysdk.ProtocolCustom = PluginProtocol.extend({ }, }); +/** + * !#en + * Data structure class + * !#zh + * 数据结构类 + * @constructor + * @class PluginParam + */ +anysdk.PluginParam = { + /** + * !#en + * create plugin parameters + * !#zh + * 创建对象 + * @method create + * @static + * @param {Number|String|Object} parameters + * @return {anysdk.PluginParam} + */ + create: function(parameters) { + return anysdk.PluginParam + }, +}; + /** * !#en The callback of user system * !#zh 用户系统回调 @@ -2702,5 +2782,3 @@ anysdk.RECResultCode = { - - From 46fc08c8fe58df5c7cf76c7ff2b2e4245c7e4eb8 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Wed, 3 Aug 2016 17:29:56 +0800 Subject: [PATCH 111/268] fix button color transition interactive=false --- cocos2d/core/components/CCButton.js | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/cocos2d/core/components/CCButton.js b/cocos2d/core/components/CCButton.js index dd7b2d5680..b9a69d0d17 100644 --- a/cocos2d/core/components/CCButton.js +++ b/cocos2d/core/components/CCButton.js @@ -103,6 +103,12 @@ var Button = cc.Class({ ctor: function () { this._resetState(); + + this._fromColor = null; + this._toColor = null; + this._time = 0; + this._transitionFinished = true; + this._sprite = null; if(CC_EDITOR) { @@ -114,10 +120,6 @@ var Button = cc.Class({ this._pressed = false; this._hovered = false; - this._fromColor = null; - this._toColor = null; - this._time = 0; - this._transitionFinished = true; }, editor: CC_EDITOR && { From ce3382ed3b5749547fa124bf1a14788f04c77554 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Wed, 3 Aug 2016 17:42:14 +0800 Subject: [PATCH 112/268] add async decencies to package.json --- package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/package.json b/package.json index 8071bae5fc..e506a21978 100644 --- a/package.json +++ b/package.json @@ -27,6 +27,7 @@ "gulp-rename": "1.2.2", "gulp-shell": "0.4.1", "gulp-size": "2.1.0", + "async": "1.5.2", "gulp-sourcemaps": "1.5.2", "gulp-uglify": "1.5.3", "gulp-util": "3.0.6", From 2e671e1d803ae2911dc5c14b1a9cd5530b2107d2 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Thu, 4 Aug 2016 16:17:38 +0800 Subject: [PATCH 113/268] Uniform SocketIO emit interfaces parameter for fireball/issues/3872 --- jsb/jsb-etc.js | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/jsb/jsb-etc.js b/jsb/jsb-etc.js index 13036ea748..853258faa5 100644 --- a/jsb/jsb-etc.js +++ b/jsb/jsb-etc.js @@ -198,6 +198,14 @@ if (window.SocketIO) { window.io = window.SocketIO; } +SocketIO.prototype._jsbEmit = SocketIO.prototype.emit; +SocketIO.prototype.emit = function (uri, delegate) { + if (typeof delegate === 'object') { + delegate = JSON.stringify(delegate); + } + this._jsbEmit(uri, delegate); +}; + // ccsg window._ccsg = { Node: cc.Node, From 42ffe1b521bc2569f1a1514e9d5e8e46d913d8fe Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Thu, 4 Aug 2016 17:46:06 +0800 Subject: [PATCH 114/268] fix scrollbar opacity issue --- cocos2d/core/components/CCScrollBar.js | 2 +- cocos2d/core/components/CCScrollView.js | 16 +++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/components/CCScrollBar.js b/cocos2d/core/components/CCScrollBar.js index 4f5da41e32..ff46963aeb 100644 --- a/cocos2d/core/components/CCScrollBar.js +++ b/cocos2d/core/components/CCScrollBar.js @@ -333,7 +333,7 @@ var Scrollbar = cc.Class({ }, show: function() { - this._autoHideRemainingTime = 0; + this._autoHideRemainingTime = this.autoHideTime; this._setOpacity(this._opacity); }, diff --git a/cocos2d/core/components/CCScrollView.js b/cocos2d/core/components/CCScrollView.js index 4d1602b29d..e389942140 100644 --- a/cocos2d/core/components/CCScrollView.js +++ b/cocos2d/core/components/CCScrollView.js @@ -1328,11 +1328,25 @@ var ScrollView = cc.Class({ } }, - onDisable: function() { + _showScrollbar: function () { + if (this.horizontalScrollBar) { + this.horizontalScrollBar.show(); + } + + if (this.verticalScrollBar) { + this.verticalScrollBar.show(); + } + }, + + onDisable: function () { this._hideScrollbar(); this.stopAutoScroll(); }, + onEnable: function () { + this._showScrollbar(); + }, + update: function(dt) { if (this._autoScrolling) { this._processAutoScrolling(dt); From 7d4f8400708396c4424906e77d9ad71a2712aed2 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Fri, 5 Aug 2016 10:16:09 +0800 Subject: [PATCH 115/268] Integrate lgtm.co --- MAINTAINERS | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 MAINTAINERS diff --git a/MAINTAINERS b/MAINTAINERS new file mode 100644 index 0000000000..558eaca9cf --- /dev/null +++ b/MAINTAINERS @@ -0,0 +1,10 @@ + +2youyou2 +dabingnn +jareguo +knoxHuang +nantas +natural-law +pandamicro +VisualSJ +zilongshanren From 17734ed8749212562b0696c61091cf660b7325f5 Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Fri, 5 Aug 2016 10:35:31 +0800 Subject: [PATCH 116/268] fix label ttf webGL rendering --- cocos2d/core/label/CCSGLabel.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/cocos2d/core/label/CCSGLabel.js b/cocos2d/core/label/CCSGLabel.js index e8684f722a..34c6ca0545 100644 --- a/cocos2d/core/label/CCSGLabel.js +++ b/cocos2d/core/label/CCSGLabel.js @@ -358,6 +358,7 @@ _ccsg.Label = _ccsg.Node.extend({ if (!extName) { this._fontHandle = fontHandle; this._labelType = _ccsg.Label.Type.SystemFont; + this._blendFunc = cc.BlendFunc._alphaPremultiplied(); this._notifyLabelSkinDirty(); this.emit('load'); return; @@ -365,10 +366,12 @@ _ccsg.Label = _ccsg.Node.extend({ if (extName === ".ttf") { this._labelType = _ccsg.Label.Type.TTF; + this._blendFunc = cc.BlendFunc._alphaPremultiplied(); this._fontHandle = this._loadTTFFont(fontHandle); } else if (extName === ".fnt") { //todo add bmfont here this._labelType = _ccsg.Label.Type.BMFont; + this._blendFunc = cc.BlendFunc._alphaNonPremultiplied(); this._initBMFontWithString(this._string, fontHandle, textureUrl); } this._notifyLabelSkinDirty(); From dd85de6cbb3d36e7fb38bbdff7147671faed00e4 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Thu, 4 Aug 2016 17:46:06 +0800 Subject: [PATCH 117/268] fix scrollbar opacity issue --- cocos2d/core/components/CCScrollBar.js | 2 +- cocos2d/core/components/CCScrollView.js | 16 +++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/components/CCScrollBar.js b/cocos2d/core/components/CCScrollBar.js index 4f5da41e32..ff46963aeb 100644 --- a/cocos2d/core/components/CCScrollBar.js +++ b/cocos2d/core/components/CCScrollBar.js @@ -333,7 +333,7 @@ var Scrollbar = cc.Class({ }, show: function() { - this._autoHideRemainingTime = 0; + this._autoHideRemainingTime = this.autoHideTime; this._setOpacity(this._opacity); }, diff --git a/cocos2d/core/components/CCScrollView.js b/cocos2d/core/components/CCScrollView.js index 4d1602b29d..e389942140 100644 --- a/cocos2d/core/components/CCScrollView.js +++ b/cocos2d/core/components/CCScrollView.js @@ -1328,11 +1328,25 @@ var ScrollView = cc.Class({ } }, - onDisable: function() { + _showScrollbar: function () { + if (this.horizontalScrollBar) { + this.horizontalScrollBar.show(); + } + + if (this.verticalScrollBar) { + this.verticalScrollBar.show(); + } + }, + + onDisable: function () { this._hideScrollbar(); this.stopAutoScroll(); }, + onEnable: function () { + this._showScrollbar(); + }, + update: function(dt) { if (this._autoScrolling) { this._processAutoScrolling(dt); From 7ba3dd91bdd05881df0c726faa98c07d364e3f08 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Wed, 3 Aug 2016 17:29:56 +0800 Subject: [PATCH 118/268] fix button color transition interactive=false --- cocos2d/core/components/CCButton.js | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/cocos2d/core/components/CCButton.js b/cocos2d/core/components/CCButton.js index dd7b2d5680..b9a69d0d17 100644 --- a/cocos2d/core/components/CCButton.js +++ b/cocos2d/core/components/CCButton.js @@ -103,6 +103,12 @@ var Button = cc.Class({ ctor: function () { this._resetState(); + + this._fromColor = null; + this._toColor = null; + this._time = 0; + this._transitionFinished = true; + this._sprite = null; if(CC_EDITOR) { @@ -114,10 +120,6 @@ var Button = cc.Class({ this._pressed = false; this._hovered = false; - this._fromColor = null; - this._toColor = null; - this._time = 0; - this._transitionFinished = true; }, editor: CC_EDITOR && { From 76b969dc4afe12b4ff8e30002e1dd3bb17a0a4ad Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Wed, 3 Aug 2016 17:42:14 +0800 Subject: [PATCH 119/268] add async decencies to package.json --- package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/package.json b/package.json index 09e8334775..d4488879b5 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,7 @@ "gulp-rename": "1.2.2", "gulp-shell": "0.4.1", "gulp-size": "2.1.0", + "async": "1.5.2", "gulp-sourcemaps": "1.5.2", "gulp-uglify": "1.5.3", "gulp-util": "3.0.6", From 65f37bf8fa4b89385d7288db87d4c0760d85953d Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Mon, 8 Aug 2016 15:30:25 +0800 Subject: [PATCH 120/268] if hoverSprite is null, don't process hover event --- cocos2d/core/components/CCButton.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/components/CCButton.js b/cocos2d/core/components/CCButton.js index dd7b2d5680..a4ff4e1eca 100644 --- a/cocos2d/core/components/CCButton.js +++ b/cocos2d/core/components/CCButton.js @@ -446,7 +446,7 @@ var Button = cc.Class({ }, _onMouseMoveIn: function () { - if (this._pressed || !this.interactable || !this.enabledInHierarchy) return; + if (!this.hoverSprite || this._pressed || !this.interactable || !this.enabledInHierarchy) return; if (!this._hovered) { this._hovered = true; From 40c4b12a54a8d796a107f62a8471aba031535185 Mon Sep 17 00:00:00 2001 From: 2youyouo2 <501251991@qq.com> Date: Tue, 9 Aug 2016 10:13:09 +0800 Subject: [PATCH 121/268] init graphics sgNode size with node size --- cocos2d/core/graphics/graphics.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cocos2d/core/graphics/graphics.js b/cocos2d/core/graphics/graphics.js index 726b22c6da..e7b5968899 100644 --- a/cocos2d/core/graphics/graphics.js +++ b/cocos2d/core/graphics/graphics.js @@ -178,6 +178,8 @@ var Graphics = cc.Class({ sgNode.strokeColor = this._strokeColor; sgNode.fillColor = this._fillColor; sgNode.miterLimit = this._miterLimit; + + sgNode.setContentSize(this.node.getContentSize(true)); }, /** From c38a8489316d46b18252acae4d120bf776021b55 Mon Sep 17 00:00:00 2001 From: zhangbin Date: Tue, 9 Aug 2016 10:30:29 +0800 Subject: [PATCH 122/268] Solve the error interface name in _ccsg.TMXLayer. --- cocos2d/tilemap/CCSGTMXLayer.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos2d/tilemap/CCSGTMXLayer.js b/cocos2d/tilemap/CCSGTMXLayer.js index 07729a7cbf..d676751c5a 100644 --- a/cocos2d/tilemap/CCSGTMXLayer.js +++ b/cocos2d/tilemap/CCSGTMXLayer.js @@ -326,7 +326,7 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ * Tile set information for the layer * @return {cc.TMXTilesetInfo} */ - getTileset:function () { + getTileSet:function () { return this.tileset; }, @@ -334,7 +334,7 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ * Tile set information for the layer * @param {cc.TMXTilesetInfo} Var */ - setTileset:function (Var) { + setTileSet:function (Var) { this.tileset = Var; }, From 08f5810fd26ce04f05bf3a1d266c22eaf15e061d Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Tue, 9 Aug 2016 14:26:11 +0800 Subject: [PATCH 123/268] =?UTF-8?q?fix=20runAction=20=E2=80=9Ctoo=20much?= =?UTF-8?q?=20recursion=E2=80=9D=20error=20for=20fireball/issues/3922?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- jsb/jsb-action.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/jsb/jsb-action.js b/jsb/jsb-action.js index a7f4cddaad..56f4db93be 100644 --- a/jsb/jsb-action.js +++ b/jsb/jsb-action.js @@ -350,10 +350,8 @@ var actionUpdate = { 'RotateTo': syncRotationUpdate, 'RotateBy': syncRotationUpdate, 'ScaleTo': syncScaleUpdate, - 'ScaleBy': syncScaleUpdate, 'RemoveSelf': syncRemoveSelfUpdate, 'SkewTo': syncSkewUpdate, - 'SkewBy': syncSkewUpdate, 'Blink': syncOpacityUpdate, 'FadeIn': syncOpacityUpdate, 'FadeOut': syncOpacityUpdate, From af69c2ae3ca9932e4669a84731c7dee8818c3e41 Mon Sep 17 00:00:00 2001 From: zhangbin Date: Tue, 9 Aug 2016 15:56:52 +0800 Subject: [PATCH 124/268] Solve the logic error in _ccsg.TMXLayer. It's caused by code merging. --- cocos2d/tilemap/CCSGTMXLayer.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos2d/tilemap/CCSGTMXLayer.js b/cocos2d/tilemap/CCSGTMXLayer.js index d676751c5a..da8dacb4a9 100644 --- a/cocos2d/tilemap/CCSGTMXLayer.js +++ b/cocos2d/tilemap/CCSGTMXLayer.js @@ -439,7 +439,7 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ return tile; } - var z = Math.floor(pos.x) + Math.floor(pos.y) * this._layerSize.width; + var z = Math.floor(x) + Math.floor(y) * this._layerSize.width; tile = this._spriteTiles[z]; // tile not created yet. create it if (!tile) { @@ -482,7 +482,7 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ return null; } - var idx = Math.floor(pos.x) + Math.floor(pos.y) * this._layerSize.width; + var idx = Math.floor(x) + Math.floor(y) * this._layerSize.width; // Bits on the far end of the 32-bit global tile ID are used for tile flags var tile = this.tiles[idx]; From d0c177f8f24fb4492eb9dee576f90e865b68915c Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Tue, 9 Aug 2016 16:41:46 +0800 Subject: [PATCH 125/268] fix node transform bug --- cocos2d/core/base-nodes/CCSGNodeCanvasRenderCmd.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/cocos2d/core/base-nodes/CCSGNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCSGNodeCanvasRenderCmd.js index 68318b8943..151cc1facd 100644 --- a/cocos2d/core/base-nodes/CCSGNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCSGNodeCanvasRenderCmd.js @@ -208,10 +208,10 @@ _ccsg.Node.RenderCmd.prototype = { skx = 99999999; if (sky === Infinity) sky = 99999999; - t.a = a + b * sky; - t.b = b + a * sky; - t.c = c + d * skx; - t.d = d + c * skx; + t.a = a + c * sky; + t.b = b + d * sky; + t.c = c + a * skx; + t.d = d + b * skx; } if (appX || appY) { From 17e31566c1e9427b5fd9e1df4443c338d2d4d2a4 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Tue, 9 Aug 2016 16:57:16 +0800 Subject: [PATCH 126/268] fix runAction error for fireball/issues/3891 --- cocos2d/core/CCNode.js | 11 ++++++++--- jsb/jsb-action.js | 1 + 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index 92e4d625c9..b743b5bb83 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -1264,17 +1264,22 @@ var Node = cc.Class({ /** * !#en * Executes an action, and returns the action that is executed.
- * The node becomes the action's target. Refer to cc.Action's getTarget()
- * Calling runAction while the node is not active won't have any effect. + * The node becomes the action's target. Refer to cc.Action's getTarget()
+ * Calling runAction while the node is not active won't have any effect.
+ * Note:You shouldn't modify the action after runAction, that won't take any effect.
+ * if you want to modify, when you define action plus. * !#zh * 执行并返回该执行的动作。该节点将会变成动作的目标。
- * 调用 runAction 时,节点自身处于不激活状态将不会有任何效果。 + * 调用 runAction 时,节点自身处于不激活状态将不会有任何效果。
+ * 注意:你不应该修改 runAction 后的动作,将无法发挥作用,如果想进行修改,请在定义 action 时加入。 * @method runAction * @param {Action} action * @return {Action} An Action pointer * @example * var action = cc.scaleTo(0.2, 1, 0.6); * node.runAction(action); + * node.runAction(action).repeatForever(); // fail + * node.runAction(action.repeatForever()); // right */ runAction: function (action) { if (!this.active) diff --git a/jsb/jsb-action.js b/jsb/jsb-action.js index 56f4db93be..f8f915f803 100644 --- a/jsb/jsb-action.js +++ b/jsb/jsb-action.js @@ -205,6 +205,7 @@ cc.Node.prototype.runAction = function (action) { action.release(); action._retained = false; } + return action; }; function getSGTarget (target) { From d6c05b93b421e7bd0caf98406e5fee0636342146 Mon Sep 17 00:00:00 2001 From: Nan Wang Date: Wed, 10 Aug 2016 09:41:26 +0800 Subject: [PATCH 127/268] update engine version --- CCBoot.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CCBoot.js b/CCBoot.js index d1f38ccde2..14522bf10a 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -58,7 +58,7 @@ _p = null; * @name cc.ENGINE_VERSION */ var engineVersion; -engineVersion = '1.2.0'; +engineVersion = '1.2.1-beta.1'; window['CocosEngine'] = cc.ENGINE_VERSION = engineVersion; /** From 4e2da1610367945eabb88c44130b118d4742024b Mon Sep 17 00:00:00 2001 From: 2youyouo2 <501251991@qq.com> Date: Wed, 10 Aug 2016 13:55:19 +0800 Subject: [PATCH 128/268] animation playOnLoad should handle in onEnable --- cocos2d/core/components/CCAnimation.js | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/cocos2d/core/components/CCAnimation.js b/cocos2d/core/components/CCAnimation.js index 6743b41b2b..643857ccd8 100644 --- a/cocos2d/core/components/CCAnimation.js +++ b/cocos2d/core/components/CCAnimation.js @@ -166,16 +166,14 @@ var Animation = cc.Class({ } }, - __preload: function () { - if (CC_EDITOR || !this.enabled) return; - - if (this.playOnLoad && this._defaultClip) { + onEnable: function () { + if (!CC_EDITOR && this.playOnLoad && this._defaultClip) { + this.playOnLoad = false; + var state = this.getAnimationState(this._defaultClip.name); this._animator.playState(state); } - }, - onEnable: function () { this.resume(); }, From e04b69e55df243e73352b0cbbfb6e6ed85d652c4 Mon Sep 17 00:00:00 2001 From: 2youyouo2 <501251991@qq.com> Date: Wed, 10 Aug 2016 14:06:16 +0800 Subject: [PATCH 129/268] refine code --- cocos2d/core/components/CCAnimation.js | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/components/CCAnimation.js b/cocos2d/core/components/CCAnimation.js index 643857ccd8..fbb01027ff 100644 --- a/cocos2d/core/components/CCAnimation.js +++ b/cocos2d/core/components/CCAnimation.js @@ -169,12 +169,13 @@ var Animation = cc.Class({ onEnable: function () { if (!CC_EDITOR && this.playOnLoad && this._defaultClip) { this.playOnLoad = false; - + var state = this.getAnimationState(this._defaultClip.name); this._animator.playState(state); } - - this.resume(); + else { + this.resume(); + } }, onDisable: function () { From 775963c5da40d1bf1e44a31e31c64fb6aa556a89 Mon Sep 17 00:00:00 2001 From: 2youyouo2 <501251991@qq.com> Date: Wed, 10 Aug 2016 15:15:46 +0800 Subject: [PATCH 130/268] fixed CollisionManager --- cocos2d/core/collider/CCCollisionManager.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/collider/CCCollisionManager.js b/cocos2d/core/collider/CCCollisionManager.js index e24c170593..be35bed8df 100644 --- a/cocos2d/core/collider/CCCollisionManager.js +++ b/cocos2d/core/collider/CCCollisionManager.js @@ -400,7 +400,7 @@ cc.js.getset(CollisionManager.prototype, 'enabledDebugDraw', } else if (!value && this._enabledDebugDraw) { this._debugDrawer.clear(); - cc.director.getScene()._sgNode.removeChild(this._debugDrawer); + this._debugDrawer.removeFromParent(false); cc.director.off(cc.Director.EVENT_AFTER_SCENE_LAUNCH, this.onSceneLaunched, this); } From a8b80b2cae718856eb855972502d20c157ab09c4 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Wed, 10 Aug 2016 15:51:53 +0800 Subject: [PATCH 131/268] fix editbox maxLength on PC --- cocos2d/core/editbox/CCSGEditBox.js | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/cocos2d/core/editbox/CCSGEditBox.js b/cocos2d/core/editbox/CCSGEditBox.js index 4e6f82e24d..caf364f57c 100644 --- a/cocos2d/core/editbox/CCSGEditBox.js +++ b/cocos2d/core/editbox/CCSGEditBox.js @@ -581,10 +581,18 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; 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) { - editBox._text = this.value; - thisPointer._updateEditBoxContentStyle(); - editBox._delegate.editBoxTextChanged(editBox, editBox._text); + if (editBox._text.toLowerCase() !== this.value.toLowerCase()) { + editBox._text = this.value; + thisPointer._updateEditBoxContentStyle(); + editBox._delegate.editBoxTextChanged(editBox, editBox._text); + } } }); tmpEdTxt.addEventListener('keypress', function (e) { @@ -597,6 +605,7 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; this.style.fontSize = editBox._placeholderFontSize + 'px'; this.style.color = cc.colorToHex(editBox._placeholderColor); } + editBox._text = this.value; thisPointer._updateEditBoxContentStyle(); thisPointer.hidden(); @@ -670,11 +679,17 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; tmpEdTxt.style.className = "cocosEditBox"; 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) { - editBox._text = this.value; - thisPointer._updateEditBoxContentStyle(); - editBox._delegate.editBoxTextChanged(editBox, editBox._text); + if(editBox._text.toLowerCase() !== this.value.toLowerCase()) { + editBox._text = this.value; + thisPointer._updateEditBoxContentStyle(); + editBox._delegate.editBoxTextChanged(editBox, editBox._text); + } } }); From 7e8c1a0cd849c3bfa89206bf32dfbd3941d6bd7c Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Thu, 11 Aug 2016 10:08:17 +0800 Subject: [PATCH 132/268] add syncPositionUpdate for CardinalSplineTo fireball/issues/3956 --- jsb/jsb-action.js | 1 + 1 file changed, 1 insertion(+) diff --git a/jsb/jsb-action.js b/jsb/jsb-action.js index f8f915f803..c89043a22c 100644 --- a/jsb/jsb-action.js +++ b/jsb/jsb-action.js @@ -348,6 +348,7 @@ var actionUpdate = { 'JumpTo': syncPositionUpdate, 'JumpBy': syncPositionUpdate, 'Place': syncPositionUpdate, + 'CardinalSplineTo': syncPositionUpdate, 'RotateTo': syncRotationUpdate, 'RotateBy': syncRotationUpdate, 'ScaleTo': syncScaleUpdate, From 8bcc91e590b0f409136ba7f919765599162d9fe8 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 11 Aug 2016 15:39:05 +0800 Subject: [PATCH 133/268] Fix mouse hovered node access issue during scene switch --- cocos2d/core/CCNode.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index 92e4d625c9..23b8670a7a 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -527,6 +527,11 @@ var Node = cc.Class({ this.stopAllActions(); this._releaseAllActions(); + // Remove Node.currentHovered + if (currentHovered === this) { + currentHovered = null; + } + // Remove all listeners if (CC_JSB && this._touchListener) { this._touchListener.release(); From b50454d8cdd13a64072027ec6af4816b7186f21d Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 11 Aug 2016 15:42:06 +0800 Subject: [PATCH 134/268] Fix event.target not set in emit --- cocos2d/core/event/event-target.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/event/event-target.js b/cocos2d/core/event/event-target.js index dc0b3a82ac..265040f88d 100644 --- a/cocos2d/core/event/event-target.js +++ b/cocos2d/core/event/event-target.js @@ -332,7 +332,7 @@ JS.mixin(EventTarget.prototype, { // Event.AT_TARGET event.eventPhase = 2; - event.currentTarget = this; + event.target = event.currentTarget = this; if (caplisteners) { this._capturingListeners.invoke(event); } From 7851c97a32513259fd0c60ca5b52679b3d0ffceb Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 11 Aug 2016 15:43:42 +0800 Subject: [PATCH 135/268] break batch for scale9sprite with distortion --- cocos2d/core/renderer/RendererWebGL.js | 9 ++++++++- cocos2d/core/sprites/CCScale9SpriteWebGLRenderCmd.js | 9 +++++---- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/cocos2d/core/renderer/RendererWebGL.js b/cocos2d/core/renderer/RendererWebGL.js index a380424668..8d14db05fc 100644 --- a/cocos2d/core/renderer/RendererWebGL.js +++ b/cocos2d/core/renderer/RendererWebGL.js @@ -38,6 +38,7 @@ var _batchedInfo = { shader: null }, + _batchBroken = false, _indexBuffer = null, _vertexBuffer = null, // Total vertex size @@ -302,6 +303,10 @@ cc.rendererWebGL = { _batchingSize += increment; }, + _breakBatch: function () { + _batchBroken = true; + }, + _uploadBufferData: function (cmd) { if (_batchingSize >= _maxVertexSize) { this._batchRendering(); @@ -313,7 +318,8 @@ cc.rendererWebGL = { var blendSrc = cmd._node._blendFunc.src; var blendDst = cmd._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) { @@ -324,6 +330,7 @@ cc.rendererWebGL = { _batchedInfo.blendSrc = blendSrc; _batchedInfo.blendDst = blendDst; _batchedInfo.shader = shader; + _batchBroken = false; } // Upload vertex data diff --git a/cocos2d/core/sprites/CCScale9SpriteWebGLRenderCmd.js b/cocos2d/core/sprites/CCScale9SpriteWebGLRenderCmd.js index 202e755255..0c7ed638bd 100644 --- a/cocos2d/core/sprites/CCScale9SpriteWebGLRenderCmd.js +++ b/cocos2d/core/sprites/CCScale9SpriteWebGLRenderCmd.js @@ -103,13 +103,14 @@ proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset){ if (node._distortionOffset && this._shaderProgram === Scale9Sprite.WebGLRenderCmd._distortionProgram) { this._shaderProgram.setUniformLocationWith2f( - Scale9Sprite.WebGLRenderCmd._distortionOffset, - node._distortionOffset.x, node._distortionOffset.y + Scale9Sprite.WebGLRenderCmd._distortionOffset, + node._distortionOffset.x, node._distortionOffset.y ); this._shaderProgram.setUniformLocationWith2f( - Scale9Sprite.WebGLRenderCmd._distortionTiling, - node._distortionTiling.x, node._distortionTiling.y + Scale9Sprite.WebGLRenderCmd._distortionTiling, + node._distortionTiling.x, node._distortionTiling.y ); + cc.renderer._breakBatch(); } // Color & z From aa4d23076c6ba7c056f47f0b3b0e7000c44b686b Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 11 Aug 2016 15:44:40 +0800 Subject: [PATCH 136/268] Only send one touch cancel event when ScrollView scrolled --- cocos2d/core/components/CCScrollView.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/components/CCScrollView.js b/cocos2d/core/components/CCScrollView.js index 4d1602b29d..1bd2546a52 100644 --- a/cocos2d/core/components/CCScrollView.js +++ b/cocos2d/core/components/CCScrollView.js @@ -849,14 +849,14 @@ var ScrollView = cc.Class({ var deltaMove = cc.pSub(touch.getLocation(), touch.getStartLocation()); //FIXME: touch move delta should be calculated by DPI. if (cc.pLength(deltaMove) > 7) { - this._touchMoved = true; - if (event.target !== this.node) { + if (!this._touchMoved && event.target !== this.node) { // Simulate touch cancel for target node var cancelEvent = new cc.Event.EventTouch(event.getTouches(), event.bubbles); cancelEvent.type = cc.Node.EventType.TOUCH_CANCEL; cancelEvent.touch = event.touch; cancelEvent.simulate = true; event.target.dispatchEvent(cancelEvent); + this._touchMoved = true; } event.stopPropagation(); } From 6b1c8bb5686c372649802cf8ecb23cce3ada86ce Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 11 Aug 2016 15:44:50 +0800 Subject: [PATCH 137/268] Fix small API issues --- cocos2d/core/textures/CCTextureCache.js | 2 +- jsb/jsb-tex-sprite-frame.js | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/textures/CCTextureCache.js b/cocos2d/core/textures/CCTextureCache.js index 657c66a408..54bd675522 100644 --- a/cocos2d/core/textures/CCTextureCache.js +++ b/cocos2d/core/textures/CCTextureCache.js @@ -85,7 +85,7 @@ var textureCache = /** @lends cc.textureCache# */{ return this._textures[textureKeyName]; }, - /** + /* * @method getKeyByTexture * @param {Image} texture * @return {String|Null} diff --git a/jsb/jsb-tex-sprite-frame.js b/jsb/jsb-tex-sprite-frame.js index 0da03497f3..448e46e983 100644 --- a/jsb/jsb-tex-sprite-frame.js +++ b/jsb/jsb-tex-sprite-frame.js @@ -56,8 +56,10 @@ var prototype = cc.Texture2D.prototype; prototype.isLoaded = function () { return true; }; +prototype.releaseTexture = prototype.releaseGLTexture; prototype.getPixelWidth = prototype.getPixelsWide; prototype.getPixelHeight = prototype.getPixelsHigh; +prototype.description = prototype.getDescription; cc.js.get(prototype, 'pixelWidth', prototype.getPixelWidth); cc.js.get(prototype, 'pixelHeight', prototype.getPixelHeight); From b542c68b9956013e72ded0894dd28df35bbc6c1f Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Thu, 4 Aug 2016 15:45:08 +0800 Subject: [PATCH 138/268] house keeping --- cocos2d/core/assets/CCSceneAsset.js | 9 ++++++++- cocos2d/core/load-pipeline/uuid-loader.js | 6 +++--- cocos2d/core/platform/prefab-info.js | 15 ++++++--------- cocos2d/deprecated.js | 5 +++++ 4 files changed, 22 insertions(+), 13 deletions(-) diff --git a/cocos2d/core/assets/CCSceneAsset.js b/cocos2d/core/assets/CCSceneAsset.js index d27b61a3c3..8284548a4f 100644 --- a/cocos2d/core/assets/CCSceneAsset.js +++ b/cocos2d/core/assets/CCSceneAsset.js @@ -42,7 +42,14 @@ var Scene = cc.Class({ * @property {Boolean} asyncLoadAssets * @default undefined */ - asyncLoadAssets: undefined + asyncLoadAssets: undefined, + + //// backup prefab assets in editor + //// {string} assetUuid: {cc.Node} rootInPrefab + //_prefabDatas: { + // default: null, + // editorOnly: true + //} }, }); diff --git a/cocos2d/core/load-pipeline/uuid-loader.js b/cocos2d/core/load-pipeline/uuid-loader.js index a074f4e931..a0e1e9b521 100644 --- a/cocos2d/core/load-pipeline/uuid-loader.js +++ b/cocos2d/core/load-pipeline/uuid-loader.js @@ -159,9 +159,9 @@ function canDeferredLoad (asset, item, isScene) { else if (isScene) { if (asset instanceof cc.SceneAsset) { res = asset.asyncLoadAssets; - if (res) { - cc.log('deferred load raw assets for ' + item.id); - } + //if (res) { + // cc.log('deferred load raw assets for ' + item.id); + //} } //else if (asset instanceof cc.Scene) { // deferredLoadRawAssetsInRuntime = asset._asyncLoadAssets; diff --git a/cocos2d/core/platform/prefab-info.js b/cocos2d/core/platform/prefab-info.js index 626f06fd37..c238dc65a7 100644 --- a/cocos2d/core/platform/prefab-info.js +++ b/cocos2d/core/platform/prefab-info.js @@ -33,20 +33,17 @@ var PrefabInfo = cc.Class({ //}, // the most top node of this prefab in the scene - root: { - default: null, - }, + root: null, // 所属的 prefab 资源对象 (cc.Prefab) // (这个属性在场景中是会保存的,但是不会保存在 prefab 里面,因为创建 prefab 时还不知道自己的 uuid 是多少。) - asset: { - default: null, - }, + asset: null, // 用来标识别该节点在 prefab 资源中的位置,因此这个 ID 只需要保证在 Assets 里不重复就行 - fileId: { - default: '' - }, + fileId: '', + + //// Indicates whether this node should always synchronize with the prefab asset. + //sync: false, } }); diff --git a/cocos2d/deprecated.js b/cocos2d/deprecated.js index 9cc425071f..b41737652f 100644 --- a/cocos2d/deprecated.js +++ b/cocos2d/deprecated.js @@ -210,6 +210,11 @@ if (CC_DEV) { return cc.js.array.copy; }); + js.get(cc, 'PI', function () { + cc.warn(INFO, 'cc.PI', 'Math.PI'); + return Math.PI; + }); + /** * Get the Tile set information for the layer. * @memberof cc.TiledLayer From f04a119e9481560d9d4909ec46c43fd2e7137519 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Tue, 9 Aug 2016 15:04:34 +0800 Subject: [PATCH 139/268] working on auto release --- cocos2d/core/CCDirector.js | 10 ++- cocos2d/core/CCScene.js | 3 + cocos2d/core/load-pipeline/CCLoader.js | 84 ++++++++++++++++--- .../core/load-pipeline/auto-release-utils.js | 80 ++++++++++++++++++ cocos2d/core/load-pipeline/uuid-loader.js | 5 ++ cocos2d/core/platform/CCAssetLibrary.js | 60 ++++++------- 6 files changed, 194 insertions(+), 48 deletions(-) create mode 100644 cocos2d/core/load-pipeline/auto-release-utils.js diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js index c3549d6ed1..9f0361fd5a 100644 --- a/cocos2d/core/CCDirector.js +++ b/cocos2d/core/CCDirector.js @@ -26,6 +26,7 @@ var EventTarget = require('./event/event-target'); var Class = require('./platform/_CCClass'); +var AutoReleaseUtils = require('./load-pipeline/auto-release-utils'); cc.g_NumberOfDraws = 0; @@ -540,8 +541,7 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ var persistNodes = game._persistRootNodes; if (scene instanceof cc.Scene) { - // ensure scene initialized - scene._load(); + scene._load(); // ensure scene initialized } // detach persist nodes @@ -552,8 +552,12 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ game._ignoreRemovePersistNode = null; } - // unload scene var oldScene = this._scene; + + // auto release assets + AutoReleaseUtils.autoRelease(cc.loader, oldScene && oldScene.dependAssets, scene.dependAssets); + + // unload scene if (cc.isValid(oldScene)) { oldScene.destroy(); } diff --git a/cocos2d/core/CCScene.js b/cocos2d/core/CCScene.js index d717379369..8b2a7d8b3a 100644 --- a/cocos2d/core/CCScene.js +++ b/cocos2d/core/CCScene.js @@ -59,6 +59,9 @@ cc.Scene = cc.Class({ this._activeInHierarchy = false; this._inited = !cc.game._isCloning; + + // cache all depend assets for auto release + this.dependAssets = null; }, destroy: function () { diff --git a/cocos2d/core/load-pipeline/CCLoader.js b/cocos2d/core/load-pipeline/CCLoader.js index 6f21df201c..f5e693e22e 100644 --- a/cocos2d/core/load-pipeline/CCLoader.js +++ b/cocos2d/core/load-pipeline/CCLoader.js @@ -29,9 +29,8 @@ var Downloader = require('./downloader'); var Loader = require('./loader'); var AssetTable = require('./asset-table'); var callInNextTick = require('../platform/utils').callInNextTick; +var AutoReleaseUtils = require('./auto-release-utils'); -var downloader = new Downloader(); -var loader = new Loader(); var resources = new AssetTable(); /** @@ -40,13 +39,15 @@ var resources = new AssetTable(); * @extends Pipeline * @static */ -cc.loader = new Pipeline([ - downloader, - loader -]); +function CCLoader () { + var downloader = new Downloader(); + var loader = new Loader(); + Pipeline.call(this, [ + downloader, + loader + ]); -JS.mixin(cc.loader, { /** * The downloader in cc.loader's pipeline, it's by default the first pipe. * It's used to download files with several handlers: pure text, image, script, audio, font, uuid. @@ -54,7 +55,7 @@ JS.mixin(cc.loader, { * @property downloader * @type {Object} */ - downloader: downloader, + this.downloader = downloader; /** * The downloader in cc.loader's pipeline, it's by default the second pipe. @@ -63,7 +64,13 @@ JS.mixin(cc.loader, { * @property loader * @type {Object} */ - loader: loader, + this.loader = loader; + + // assets to release automatically + this._autoReleaseSetting = {}; +} +JS.extend(CCLoader, Pipeline); +JS.mixin(CCLoader.prototype, { /** * Get XMLHttpRequest. @@ -82,7 +89,7 @@ JS.mixin(cc.loader, { * @param {Object} extMap Custom supported types with corresponded handler */ addDownloadHandlers: function (extMap) { - downloader.addHandlers(extMap); + this.downloader.addHandlers(extMap); }, /** @@ -96,7 +103,7 @@ JS.mixin(cc.loader, { * @param {Object} extMap Custom supported types with corresponded handler */ addLoadHandlers: function (extMap) { - loader.addHandlers(extMap); + this.loader.addHandlers(extMap); }, /** @@ -489,9 +496,62 @@ JS.mixin(cc.loader, { */ releaseAll: function () { this.clear(); - } + }, + + // AUTO RELEASE + + _baseRemoveItem: Pipeline.prototype.removeItem, + + // override + removeItem: function (key) { + this._baseRemoveItem(key); + delete this._autoReleaseSetting[key]; + }, + + /** + * Release the asset automatically when loading a new scene. + * When loading a new scene all assets in the scene are destroyed, then the assets in the new scene are loaded. + * In order to preserve an asset during scene loading call this method and pass in false. + * + * @method autoRelease + * @param {cc.Asset|String} assetOrUrl - asset object or the raw asset's url + * @param {Boolean} autoRelease - indicates whether should release automatically + */ + autoRelease: function (assetOrUrl, autoRelease) { + var key = AutoReleaseUtils.getKey(this, assetOrUrl); + if (key) { + this._autoReleaseSetting[key] = !!autoRelease; + } + else if (CC_DEV) { + cc.warn('No need to release non-cached asset.'); + } + }, + + /** + * @method autoReleaseRecursively + * @param {cc.Asset|String} assetOrUrl - asset object or the raw asset's url + * @param {Boolean} autoRelease - indicates whether should release automatically + */ + autoReleaseRecursively: function (assetOrUrl, autoRelease) { + // TODO + }, + + /** + * @method isAutoRelease + * @param {cc.Asset|String} assetOrUrl - asset object or the raw asset's url + * @returns {Boolean} + */ + isAutoRelease: function (assetOrUrl) { + var key = AutoReleaseUtils.getKey(this, assetOrUrl); + if (key) { + return !!this._autoReleaseSetting[key]; + } + return false; + }, }); +cc.loader = new CCLoader(); + if (CC_EDITOR) { cc.loader.refreshUrl = function (uuid, oldUrl, newUrl) { this._items.refreshItemUrl(uuid, oldUrl, newUrl); diff --git a/cocos2d/core/load-pipeline/auto-release-utils.js b/cocos2d/core/load-pipeline/auto-release-utils.js new file mode 100644 index 0000000000..a384923359 --- /dev/null +++ b/cocos2d/core/load-pipeline/auto-release-utils.js @@ -0,0 +1,80 @@ + +function parseDepends (key, parsed) { + parsed[key] = true; + var item = cc.loader.getItem(key); + if (item) { + var depends = item.dependKeys; + if (depends) { + for (var i = 0; i < depends.length; i++) { + var depend = depends[i]; + if ( !parsed[depend] ) { + parseDepends(depend, parsed); + } + } + } + } +} + +module.exports = { + + // get asset url or uuid + getKey: function (loader, assetOrUrl) { + if (assetOrUrl) { + if (typeof assetOrUrl === 'string') { + return assetOrUrl; + } + else if (assetOrUrl instanceof cc.Asset) { + return assetOrUrl._uuid; + } + else if (assetOrUrl instanceof cc.Texture2D) { + return assetOrUrl.url; + } + else if (assetOrUrl instanceof cc.Audio) { + return assetOrUrl.src; + } + else if (CC_DEV) { + cc.warn('unknown asset type'); + } + } + return ''; + }, + + // do auto release + autoRelease: function (loader, oldSceneAssets, nextSceneAssets) { + var releaseSettings = loader._autoReleaseSetting; + var i, key; + + // remove ununsed scene assets + if (oldSceneAssets) { + for (i = 0; i < oldSceneAssets.length; i++) { + key = oldSceneAssets[i]; + if (releaseSettings[key] !== false) { + if (!nextSceneAssets || nextSceneAssets.indexOf(key) === -1) { + loader.removeItem(key); + //console.log('auto release: ' + key); + } + } + } + } + + // remove auto release assets + var keys = Object.keys(releaseSettings); + // releasing asset will change _autoReleaseSetting, so don't use enumerator + for (i = 0; i < keys.length; i++) { + key = keys[i]; + if (releaseSettings[key] === true) { + if (!nextSceneAssets || nextSceneAssets.indexOf(key) === -1) { + loader.removeItem(key); + //console.log('auto release: ' + key); + } + } + } + }, + + // + parseDepends: function (key) { + var depends = {}; + parseDepends(key, depends); + return Object.keys(depends); + } +}; \ No newline at end of file diff --git a/cocos2d/core/load-pipeline/uuid-loader.js b/cocos2d/core/load-pipeline/uuid-loader.js index a0e1e9b521..d113d6538a 100644 --- a/cocos2d/core/load-pipeline/uuid-loader.js +++ b/cocos2d/core/load-pipeline/uuid-loader.js @@ -97,6 +97,9 @@ function loadDepends (pipeline, item, asset, tdInfo, deferredLoadRawAssetsInRunt return callback(null, asset); } + // cache dependencies for auto release + var dependKeys = item.dependKeys = []; + pipeline.flowInDeps(depends, function (items) { var item; for (var src in items) { @@ -114,12 +117,14 @@ function loadDepends (pipeline, item, asset, tdInfo, deferredLoadRawAssetsInRunt if (item.complete) { var value = item.isRawAsset ? item.url : item.content; dependObj[dependProp] = value; + dependKeys.push(item.isRawAsset ? item.url : dependSrc); } else { // item was removed from cache, but ready in pipeline actually var loadCallback = function (item) { var value = item.isRawAsset ? item.url : item.content; this.obj[this.prop] = value; + dependKeys.push(item.isRawAsset ? item.url : item.uuid); }; var target = { obj: dependObj, diff --git a/cocos2d/core/platform/CCAssetLibrary.js b/cocos2d/core/platform/CCAssetLibrary.js index 6601c11166..59a114be9d 100644 --- a/cocos2d/core/platform/CCAssetLibrary.js +++ b/cocos2d/core/platform/CCAssetLibrary.js @@ -27,6 +27,7 @@ var Asset = require('../assets/CCAsset'); var callInNextTick = require('./utils').callInNextTick; var Loader = require('../load-pipeline/CCLoader'); var PackDownloader = require('../load-pipeline/pack-downloader'); +var AutoReleaseUtils = require('../load-pipeline/auto-release-utils'); /** * The asset library which managing loading/unloading assets in project. @@ -67,6 +68,9 @@ var AssetLibrary = { * @private */ loadAsset: function (uuid, callback, options) { + if (typeof uuid !== 'string') { + return callInNextTick(callback, new Error('[AssetLibrary] uuid must be string'), null); + } // var readMainCache = typeof (options && options.readMainCache) !== 'undefined' ? readMainCache : true; // var writeMainCache = typeof (options && options.writeMainCache) !== 'undefined' ? writeMainCache : true; var item = { @@ -79,7 +83,22 @@ var AssetLibrary = { if (options && options.existingAsset) { item.existingAsset = options.existingAsset; } - this._loadAssetByUuid(item, callback); + Loader.load(item, function (error, asset) { + if (error || !asset) { + error = new Error('[AssetLibrary] loading JSON or dependencies failed: ' + error.message); + } + else { + if (asset.constructor === cc.SceneAsset) { + asset.scene.dependAssets = AutoReleaseUtils.parseDepends(uuid); + } + if (CC_EDITOR || isScene(asset)) { + Loader.removeItem(uuid); + } + } + if (callback) { + callback(error, asset); + } + }); }, getImportedDir: function (uuid) { @@ -170,36 +189,6 @@ var AssetLibrary = { } }, - /** - * !#zh uuid加载流程: - * 1. 查找_uuidToAsset,如果已经加载过,直接返回 - * 2. 查找_uuidToCallbacks,如果已经在加载,则注册回调,直接返回 - * 3. 如果没有url,则将uuid直接作为路径 - * 4. 递归加载Asset及其引用到的其它Asset - * - * @method _loadAssetByUuid - * @param {Object} item - loading item including uuid, type and extra infos - * @param {loadCallback} callback - the callback to receive the asset, can be null - * @private - */ - _loadAssetByUuid: function (item, callback) { - var uuid = item.id; - if (typeof uuid !== 'string') { - return callInNextTick(callback, new Error('[AssetLibrary] uuid must be string'), null); - } - Loader.load(item, function (error, asset) { - if (error || !asset) { - error = new Error('[AssetLibrary] loading JSON or dependencies failed: ' + error.message); - } - else if (CC_EDITOR || isScene(asset)) { - Loader.removeItem(uuid); - } - if (callback) { - callback(error, asset); - } - }); - }, - /** * @method loadJson * @param {String} json @@ -219,8 +208,13 @@ var AssetLibrary = { if (error) { error = new Error('[AssetLibrary] loading JSON or dependencies failed: ' + error.message); } - else if (CC_EDITOR || isScene(asset)) { - Loader.removeItem(randomUuid); + else { + if (asset.constructor === cc.SceneAsset) { + asset.scene.dependAssets = AutoReleaseUtils.parseDepends(randomUuid); + } + if (CC_EDITOR || isScene(asset)) { + Loader.removeItem(randomUuid); + } } asset._uuid = ''; if (callback) { From 0a03ec658c2985cf444ab212ffca2a1c9e098160 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Tue, 9 Aug 2016 16:27:38 +0800 Subject: [PATCH 140/268] should release texture specially --- .../core/load-pipeline/auto-release-utils.js | 25 ++++++++++++------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/cocos2d/core/load-pipeline/auto-release-utils.js b/cocos2d/core/load-pipeline/auto-release-utils.js index a384923359..ff5e585671 100644 --- a/cocos2d/core/load-pipeline/auto-release-utils.js +++ b/cocos2d/core/load-pipeline/auto-release-utils.js @@ -15,6 +15,19 @@ function parseDepends (key, parsed) { } } +function release (loader, key, nextSceneAssets) { + if (!nextSceneAssets || nextSceneAssets.indexOf(key) === -1) { + var item = loader.getItem(key); + if (item) { + loader.removeItem(key); + //console.log('auto release: ' + key); + if (item.content instanceof cc.Texture2D) { + cc.textureCache.removeTextureForKey(item.url); + } + } + } +} + module.exports = { // get asset url or uuid @@ -49,10 +62,7 @@ module.exports = { for (i = 0; i < oldSceneAssets.length; i++) { key = oldSceneAssets[i]; if (releaseSettings[key] !== false) { - if (!nextSceneAssets || nextSceneAssets.indexOf(key) === -1) { - loader.removeItem(key); - //console.log('auto release: ' + key); - } + release(loader, key, nextSceneAssets); } } } @@ -63,10 +73,7 @@ module.exports = { for (i = 0; i < keys.length; i++) { key = keys[i]; if (releaseSettings[key] === true) { - if (!nextSceneAssets || nextSceneAssets.indexOf(key) === -1) { - loader.removeItem(key); - //console.log('auto release: ' + key); - } + release(loader, key, nextSceneAssets); } } }, @@ -77,4 +84,4 @@ module.exports = { parseDepends(key, depends); return Object.keys(depends); } -}; \ No newline at end of file +}; From 5477ba9bd920572be7ef6a180c81a09cccbd4aaa Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Tue, 9 Aug 2016 17:29:51 +0800 Subject: [PATCH 141/268] implement autoReleaseRecursively --- cocos2d/core/load-pipeline/CCLoader.js | 15 ++++++++++++++- cocos2d/core/load-pipeline/auto-release-utils.js | 6 +++--- cocos2d/core/platform/CCAssetLibrary.js | 4 ++-- 3 files changed, 19 insertions(+), 6 deletions(-) diff --git a/cocos2d/core/load-pipeline/CCLoader.js b/cocos2d/core/load-pipeline/CCLoader.js index f5e693e22e..fabae6028f 100644 --- a/cocos2d/core/load-pipeline/CCLoader.js +++ b/cocos2d/core/load-pipeline/CCLoader.js @@ -533,7 +533,20 @@ JS.mixin(CCLoader.prototype, { * @param {Boolean} autoRelease - indicates whether should release automatically */ autoReleaseRecursively: function (assetOrUrl, autoRelease) { - // TODO + autoRelease = !!autoRelease; + var key = AutoReleaseUtils.getKey(this, assetOrUrl); + if (key) { + this._autoReleaseSetting[key] = autoRelease; + + var depends = AutoReleaseUtils.getDependsRecursively(key); + for (var i = 0; i < depends.length; i++) { + var depend = depends[i]; + this._autoReleaseSetting[depend] = autoRelease; + } + } + else if (CC_DEV) { + cc.warn('No need to release non-cached asset.'); + } }, /** diff --git a/cocos2d/core/load-pipeline/auto-release-utils.js b/cocos2d/core/load-pipeline/auto-release-utils.js index ff5e585671..1b5781038b 100644 --- a/cocos2d/core/load-pipeline/auto-release-utils.js +++ b/cocos2d/core/load-pipeline/auto-release-utils.js @@ -1,6 +1,5 @@ function parseDepends (key, parsed) { - parsed[key] = true; var item = cc.loader.getItem(key); if (item) { var depends = item.dependKeys; @@ -8,6 +7,7 @@ function parseDepends (key, parsed) { for (var i = 0; i < depends.length; i++) { var depend = depends[i]; if ( !parsed[depend] ) { + parsed[depend] = true; parseDepends(depend, parsed); } } @@ -78,8 +78,8 @@ module.exports = { } }, - // - parseDepends: function (key) { + // get dependencies not including self + getDependsRecursively: function (key) { var depends = {}; parseDepends(key, depends); return Object.keys(depends); diff --git a/cocos2d/core/platform/CCAssetLibrary.js b/cocos2d/core/platform/CCAssetLibrary.js index 59a114be9d..ccab1468ff 100644 --- a/cocos2d/core/platform/CCAssetLibrary.js +++ b/cocos2d/core/platform/CCAssetLibrary.js @@ -89,7 +89,7 @@ var AssetLibrary = { } else { if (asset.constructor === cc.SceneAsset) { - asset.scene.dependAssets = AutoReleaseUtils.parseDepends(uuid); + asset.scene.dependAssets = AutoReleaseUtils.getDependsRecursively(uuid); } if (CC_EDITOR || isScene(asset)) { Loader.removeItem(uuid); @@ -210,7 +210,7 @@ var AssetLibrary = { } else { if (asset.constructor === cc.SceneAsset) { - asset.scene.dependAssets = AutoReleaseUtils.parseDepends(randomUuid); + asset.scene.dependAssets = AutoReleaseUtils.getDependsRecursively(randomUuid); } if (CC_EDITOR || isScene(asset)) { Loader.removeItem(randomUuid); From b09203e4fb652d9bbf85d9c55c26a38a40e5cd2a Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Wed, 10 Aug 2016 10:23:57 +0800 Subject: [PATCH 142/268] do not release assets loaded by loadRes --- cocos2d/core/load-pipeline/CCLoader.js | 35 ++++++++++++++++++++------ 1 file changed, 28 insertions(+), 7 deletions(-) diff --git a/cocos2d/core/load-pipeline/CCLoader.js b/cocos2d/core/load-pipeline/CCLoader.js index fabae6028f..20c6fe5899 100644 --- a/cocos2d/core/load-pipeline/CCLoader.js +++ b/cocos2d/core/load-pipeline/CCLoader.js @@ -302,7 +302,8 @@ JS.mixin(CCLoader.prototype, { completeCallback = type; type = null; } - var uuid = this._getResUuid(url, type); + var self = this; + var uuid = self._getResUuid(url, type); if (uuid) { this.load( { @@ -310,7 +311,15 @@ JS.mixin(CCLoader.prototype, { type: 'uuid', uuid: uuid }, - completeCallback + function (err, asset) { + if (asset) { + // should not release these assets, even if they are static referenced in the scene. + self.autoReleaseRecursively(asset, false); + } + if (completeCallback) { + completeCallback(err, asset); + } + } ); } else { @@ -322,7 +331,9 @@ JS.mixin(CCLoader.prototype, { else { info = 'Resources url "' + url + '" does not exist.'; } - completeCallback(new Error(info), null); + if (completeCallback) { + completeCallback(new Error(info), null); + } }); } }, @@ -367,6 +378,7 @@ JS.mixin(CCLoader.prototype, { completeCallback = type; type = null; } + var self = this; var uuids = resources.getUuidArray(url, type); var remain = uuids.length; if (remain > 0) { @@ -378,18 +390,25 @@ JS.mixin(CCLoader.prototype, { } if (err) { aborted = true; - completeCallback(err, null); + if (completeCallback) { + completeCallback(err, null); + } return; } results.push(res); --remain; if (remain === 0) { - completeCallback(null, results); + for (var i = 0; i < results.length; i++) { + self.autoReleaseRecursively(results[i], false); + } + if (completeCallback) { + completeCallback(null, results); + } } } for (var i = 0, len = remain; i < len; ++i) { var uuid = uuids[i]; - this.load( + self.load( { id: uuid, type: 'uuid', @@ -401,7 +420,9 @@ JS.mixin(CCLoader.prototype, { } else { callInNextTick(function () { - completeCallback(null, []); + if (completeCallback) { + completeCallback(null, []); + } }); } }, From 05f3ce563a8b6fb4ad19d8922106096e77b384d5 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Wed, 10 Aug 2016 10:34:00 +0800 Subject: [PATCH 143/268] rename autoRelease to setAutoRelease --- cocos2d/core/load-pipeline/CCLoader.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/cocos2d/core/load-pipeline/CCLoader.js b/cocos2d/core/load-pipeline/CCLoader.js index 20c6fe5899..7683df95ed 100644 --- a/cocos2d/core/load-pipeline/CCLoader.js +++ b/cocos2d/core/load-pipeline/CCLoader.js @@ -314,7 +314,7 @@ JS.mixin(CCLoader.prototype, { function (err, asset) { if (asset) { // should not release these assets, even if they are static referenced in the scene. - self.autoReleaseRecursively(asset, false); + self.setAutoReleaseRecursively(asset, false); } if (completeCallback) { completeCallback(err, asset); @@ -399,7 +399,7 @@ JS.mixin(CCLoader.prototype, { --remain; if (remain === 0) { for (var i = 0; i < results.length; i++) { - self.autoReleaseRecursively(results[i], false); + self.setAutoReleaseRecursively(results[i], false); } if (completeCallback) { completeCallback(null, results); @@ -534,11 +534,11 @@ JS.mixin(CCLoader.prototype, { * When loading a new scene all assets in the scene are destroyed, then the assets in the new scene are loaded. * In order to preserve an asset during scene loading call this method and pass in false. * - * @method autoRelease + * @method setAutoRelease * @param {cc.Asset|String} assetOrUrl - asset object or the raw asset's url * @param {Boolean} autoRelease - indicates whether should release automatically */ - autoRelease: function (assetOrUrl, autoRelease) { + setAutoRelease: function (assetOrUrl, autoRelease) { var key = AutoReleaseUtils.getKey(this, assetOrUrl); if (key) { this._autoReleaseSetting[key] = !!autoRelease; @@ -549,11 +549,11 @@ JS.mixin(CCLoader.prototype, { }, /** - * @method autoReleaseRecursively + * @method setAutoReleaseRecursively * @param {cc.Asset|String} assetOrUrl - asset object or the raw asset's url * @param {Boolean} autoRelease - indicates whether should release automatically */ - autoReleaseRecursively: function (assetOrUrl, autoRelease) { + setAutoReleaseRecursively: function (assetOrUrl, autoRelease) { autoRelease = !!autoRelease; var key = AutoReleaseUtils.getKey(this, assetOrUrl); if (key) { From 8f3001c289590577145cb1f52e142bd1601c7584 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Wed, 10 Aug 2016 14:41:23 +0800 Subject: [PATCH 144/268] add Scene.autoReleaseAssets --- cocos2d/core/CCDirector.js | 3 ++- cocos2d/core/CCScene.js | 20 +++++++++++--------- cocos2d/core/assets/CCSceneAsset.js | 8 +++++++- cocos2d/core/platform/CCClass.js | 10 +++++----- 4 files changed, 25 insertions(+), 16 deletions(-) diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js index 9f0361fd5a..bc9b1039c0 100644 --- a/cocos2d/core/CCDirector.js +++ b/cocos2d/core/CCDirector.js @@ -555,7 +555,8 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ var oldScene = this._scene; // auto release assets - AutoReleaseUtils.autoRelease(cc.loader, oldScene && oldScene.dependAssets, scene.dependAssets); + var autoReleaseAssets = oldScene && oldScene.autoReleaseAssets && oldScene.dependAssets; + AutoReleaseUtils.autoRelease(cc.loader, autoReleaseAssets, scene.dependAssets); // unload scene if (cc.isValid(oldScene)) { diff --git a/cocos2d/core/CCScene.js b/cocos2d/core/CCScene.js index 8b2a7d8b3a..7f2277d114 100644 --- a/cocos2d/core/CCScene.js +++ b/cocos2d/core/CCScene.js @@ -38,15 +38,17 @@ cc.Scene = cc.Class({ name: 'cc.Scene', extends: require('./utils/base-node'), - //properties: { - // /** - // * !#en Indicates the raw assets of this scene can be load after scene launched. - // * !#zh 指示该场景依赖的资源可否在场景切换后再延迟加载。 - // * @property {Boolean} _asyncLoadAssets - // * @default false - // */ - // _asyncLoadAssets: false - //}, + properties: { + + /** + * !#en Indicates whether all (directly or indirectly) static referenced assets of this scene are releasable by default after scene unloading. + * !#zh 指示该场景中直接或间接静态引用到的所有资源是否默认在场景切换后自动释放。 + * @property {Boolean} autoReleaseAssets + * @default false + */ + autoReleaseAssets: undefined, + + }, ctor: function () { var sgNode = this._sgNode = new _ccsg.Scene(); diff --git a/cocos2d/core/assets/CCSceneAsset.js b/cocos2d/core/assets/CCSceneAsset.js index 8284548a4f..bb6109c6f7 100644 --- a/cocos2d/core/assets/CCSceneAsset.js +++ b/cocos2d/core/assets/CCSceneAsset.js @@ -35,12 +35,18 @@ var Scene = cc.Class({ extends: cc.Asset, properties: { + + /** + * @property {cc.Scene} scene + * @default null + */ scene: null, + /** * !#en Indicates the raw assets of this scene can be load after scene launched. * !#zh 指示该场景依赖的资源可否在场景切换后再延迟加载。 * @property {Boolean} asyncLoadAssets - * @default undefined + * @default false */ asyncLoadAssets: undefined, diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index 14a509e95e..953be36160 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -458,21 +458,21 @@ function define (className, baseClasses, mixins, constructor, options) { return doDefine(className, baseClasses, mixins, constructor, options); } -function _checkCtor (ctor) { +function _checkCtor (ctor, className) { if (CC_DEV) { if (CCClass._isCCClass(ctor)) { - cc.error("Constructor can not be another CCClass"); + cc.error('ctor of "%s" can not be another CCClass', className); return; } if (typeof ctor !== 'function') { - cc.error("Constructor of CCClass must be function type"); + cc.error('ctor of "%s" must be function type', className); return; } if (ctor.length > 0) { // fireball-x/dev#138: To make a unified CCClass serialization process, // we don't allow parameters for constructor when creating instances of CCClass. // For advance user, construct arguments can still get from 'arguments'. - cc.warn("Can not instantiate CCClass with arguments."); + cc.warn('Can not instantiate CCClass "%s" with arguments.', className); return; } } @@ -530,7 +530,7 @@ function _createCtor (ctor, baseClass, mixins, className, options) { var superCallBounded = options && baseClass && boundSuperCalls(baseClass, options); if (ctor && CC_DEV) { - _checkCtor(ctor); + _checkCtor(ctor, className); } // get base user constructors var ctors = []; From af30ff6f7b8ef08ae93309616d6533ecee6367b1 Mon Sep 17 00:00:00 2001 From: Nan Wang Date: Fri, 12 Aug 2016 11:13:52 +0800 Subject: [PATCH 145/268] fix api doc typo --- cocos2d/audio/CCAudio.js | 2 +- cocos2d/core/base-nodes/CCAtlasNode.js | 2 +- cocos2d/core/platform/CCSys.js | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index 9eff41ffa2..bdf919d4b6 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -249,7 +249,7 @@ JS.mixin(cc.Audio.prototype, { /** * !#en cc.audioEngine is the singleton object, it provide simple audio APIs. - * !#zn + * !#zh * cc.audioengine是单例对象。
* 主要用来播放背景音乐和音效,背景音乐同一时间只能播放一个,而音效则可以同时播放多个。
* 注意:
diff --git a/cocos2d/core/base-nodes/CCAtlasNode.js b/cocos2d/core/base-nodes/CCAtlasNode.js index a1fc727ab8..7d4f37997c 100644 --- a/cocos2d/core/base-nodes/CCAtlasNode.js +++ b/cocos2d/core/base-nodes/CCAtlasNode.js @@ -286,7 +286,7 @@ cc.js.addon(_p, EventTarget.prototype); /** * Creates a cc.AtlasNode with an Atlas file the width and height of each item and the quantity of items to render * @deprecated since v3.0, please use new construction instead - * @function + * @method create * @static * @param {String} tile * @param {Number} tileWidth diff --git a/cocos2d/core/platform/CCSys.js b/cocos2d/core/platform/CCSys.js index 19f2edf221..0c4463e89f 100644 --- a/cocos2d/core/platform/CCSys.js +++ b/cocos2d/core/platform/CCSys.js @@ -232,7 +232,7 @@ sys.MACOS = 2; */ sys.ANDROID = 3; /** - * @property {Number} IOS + * @property {Number} IPHONE * @readOnly * @default 4 */ From 788b48852a0fa3ddd1c56325f721965730f930b3 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Thu, 11 Aug 2016 16:20:18 +0800 Subject: [PATCH 146/268] improve api document for auto release --- cocos2d/core/load-pipeline/CCLoader.js | 67 +++++++++++++++++-- .../core/load-pipeline/auto-release-utils.js | 3 +- jsb/jsb-director.js | 12 +++- 3 files changed, 72 insertions(+), 10 deletions(-) diff --git a/cocos2d/core/load-pipeline/CCLoader.js b/cocos2d/core/load-pipeline/CCLoader.js index 7683df95ed..b3a6a7bc39 100644 --- a/cocos2d/core/load-pipeline/CCLoader.js +++ b/cocos2d/core/load-pipeline/CCLoader.js @@ -530,12 +530,33 @@ JS.mixin(CCLoader.prototype, { }, /** - * Release the asset automatically when loading a new scene. - * When loading a new scene all assets in the scene are destroyed, then the assets in the new scene are loaded. - * In order to preserve an asset during scene loading call this method and pass in false. + * !#en + * Indicates whether to release the asset when loading a new scene.
+ * By default, when loading a new scene, all assets in the previous scene will be released or preserved + * according to whether the previous scene checked the "Auto Release Assets" option. + * On the other hand, assets dynamically loaded by using `cc.loader.loadRes` or `cc.loader.loadResAll` + * will not be affected by that option, remain not released by default.
+ * Use this API to change the default behavior on a single asset, to force preserve or release specified asset when scene switching.
+ *
+ * See: {{#crossLink "loader/setAutoReleaseRecursively:method"}}cc.loader.setAutoReleaseRecursively{{/crossLink}}, {{#crossLink "loader/isAutoRelease:method"}}cc.loader.isAutoRelease{{/crossLink}} + * !#zh + * 设置当场景切换时是否自动释放资源。
+ * 默认情况下,当加载新场景时,旧场景的资源根据旧场景是否勾选“Auto Release Assets”,将会被释放或者保留。 + * 而使用 `cc.loader.loadRes` 或 `cc.loader.loadResAll` 动态加载的资源,则不受场景设置的影响,默认不自动释放。
+ * 使用这个 API 可以在单个资源上改变这个默认行为,强制在切换场景时保留或者释放指定资源。
+ *
+ * 参考:{{#crossLink "loader/setAutoReleaseRecursively:method"}}cc.loader.setAutoReleaseRecursively{{/crossLink}},{{#crossLink "loader/isAutoRelease:method"}}cc.loader.isAutoRelease{{/crossLink}} + * + * @example + * // auto release the texture event if "Auto Release Assets" disabled in current scene + * cc.loader.setAutoRelease(texture2d, true); + * // don't release the texture even if "Auto Release Assets" enabled in current scene + * cc.loader.setAutoRelease(texture2d, false); + * // first parameter can be url + * cc.loader.setAutoRelease(audioUrl, false); * * @method setAutoRelease - * @param {cc.Asset|String} assetOrUrl - asset object or the raw asset's url + * @param {Asset|String} assetOrUrl - asset object or the raw asset's url * @param {Boolean} autoRelease - indicates whether should release automatically */ setAutoRelease: function (assetOrUrl, autoRelease) { @@ -549,8 +570,33 @@ JS.mixin(CCLoader.prototype, { }, /** + * !#en + * Indicates whether to release the asset and its referenced other assets when loading a new scene.
+ * By default, when loading a new scene, all assets in the previous scene will be released or preserved + * according to whether the previous scene checked the "Auto Release Assets" option. + * On the other hand, assets dynamically loaded by using `cc.loader.loadRes` or `cc.loader.loadResAll` + * will not be affected by that option, remain not released by default.
+ * Use this API to change the default behavior on the specified asset and its recursively referenced assets, to force preserve or release specified asset when scene switching.
+ *
+ * See: {{#crossLink "loader/setAutoRelease:method"}}cc.loader.setAutoRelease{{/crossLink}}, {{#crossLink "loader/isAutoRelease:method"}}cc.loader.isAutoRelease{{/crossLink}} + * !#zh + * 设置当场景切换时是否自动释放资源及资源引用的其它资源。
+ * 默认情况下,当加载新场景时,旧场景的资源根据旧场景是否勾选“Auto Release Assets”,将会被释放或者保留。 + * 而使用 `cc.loader.loadRes` 或 `cc.loader.loadResAll` 动态加载的资源,则不受场景设置的影响,默认不自动释放。
+ * 使用这个 API 可以在指定资源及资源递归引用到的所有资源上改变这个默认行为,强制在切换场景时保留或者释放指定资源。
+ *
+ * 参考:{{#crossLink "loader/setAutoRelease:method"}}cc.loader.setAutoRelease{{/crossLink}},{{#crossLink "loader/isAutoRelease:method"}}cc.loader.isAutoRelease{{/crossLink}} + * + * @example + * // auto release the SpriteFrame and its Texture event if "Auto Release Assets" disabled in current scene + * cc.loader.setAutoReleaseRecursively(spriteFrame, true); + * // don't release the SpriteFrame and its Texture even if "Auto Release Assets" enabled in current scene + * cc.loader.setAutoReleaseRecursively(spriteFrame, false); + * // don't release the Prefab and all the referenced assets + * cc.loader.setAutoReleaseRecursively(prefab, false); + * * @method setAutoReleaseRecursively - * @param {cc.Asset|String} assetOrUrl - asset object or the raw asset's url + * @param {Asset|String} assetOrUrl - asset object or the raw asset's url * @param {Boolean} autoRelease - indicates whether should release automatically */ setAutoReleaseRecursively: function (assetOrUrl, autoRelease) { @@ -571,8 +617,17 @@ JS.mixin(CCLoader.prototype, { }, /** + * !#en + * Returns whether the asset is configured as auto released, despite how "Auto Release Assets" property is set on scene asset.
+ *
+ * See: {{#crossLink "loader/setAutoRelease:method"}}cc.loader.setAutoRelease{{/crossLink}}, {{#crossLink "loader/setAutoReleaseRecursively:method"}}cc.loader.setAutoReleaseRecursively{{/crossLink}} + * + * !#zh + * 返回指定的资源是否有被设置为自动释放,不论场景的“Auto Release Assets”如何设置。
+ *
+ * 参考:{{#crossLink "loader/setAutoRelease:method"}}cc.loader.setAutoRelease{{/crossLink}},{{#crossLink "loader/setAutoReleaseRecursively:method"}}cc.loader.setAutoReleaseRecursively{{/crossLink}} * @method isAutoRelease - * @param {cc.Asset|String} assetOrUrl - asset object or the raw asset's url + * @param {Asset|String} assetOrUrl - asset object or the raw asset's url * @returns {Boolean} */ isAutoRelease: function (assetOrUrl) { diff --git a/cocos2d/core/load-pipeline/auto-release-utils.js b/cocos2d/core/load-pipeline/auto-release-utils.js index 1b5781038b..43a947c3a0 100644 --- a/cocos2d/core/load-pipeline/auto-release-utils.js +++ b/cocos2d/core/load-pipeline/auto-release-utils.js @@ -20,7 +20,8 @@ function release (loader, key, nextSceneAssets) { var item = loader.getItem(key); if (item) { loader.removeItem(key); - //console.log('auto release: ' + key); + console.log('auto release: ' + key); + // TODO: Audio if (item.content instanceof cc.Texture2D) { cc.textureCache.removeTextureForKey(item.url); } diff --git a/jsb/jsb-director.js b/jsb/jsb-director.js index 691b65ef70..88a5463a10 100644 --- a/jsb/jsb-director.js +++ b/jsb/jsb-director.js @@ -25,6 +25,8 @@ 'use strict'; +var AutoReleaseUtils = require('../cocos2d/core/load-pipeline/auto-release-utils'); + // cc.director cc.js.mixin(cc.director, { /** @@ -122,8 +124,7 @@ cc.js.mixin(cc.director, { var persistNodes = game._persistRootNodes; if (scene instanceof cc.Scene) { - // ensure scene initialized - scene._load(); + scene._load(); // ensure scene initialized } // detach persist nodes @@ -134,8 +135,13 @@ cc.js.mixin(cc.director, { game._ignoreRemovePersistNode = null; } - // unload scene var oldScene = this._scene; + + // auto release assets + var autoReleaseAssets = oldScene && oldScene.autoReleaseAssets && oldScene.dependAssets; + AutoReleaseUtils.autoRelease(cc.loader, autoReleaseAssets, scene.dependAssets); + + // unload scene if (cc.isValid(oldScene)) { oldScene.destroy(); } From 130b8449b2f42e3b38ab68ca46ac2ba615e6ab67 Mon Sep 17 00:00:00 2001 From: Nan Wang Date: Fri, 12 Aug 2016 12:02:00 +0800 Subject: [PATCH 147/268] update engine version --- CCBoot.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CCBoot.js b/CCBoot.js index 14522bf10a..3e505421b2 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -58,7 +58,7 @@ _p = null; * @name cc.ENGINE_VERSION */ var engineVersion; -engineVersion = '1.2.1-beta.1'; +engineVersion = '1.2.1-beta.2'; window['CocosEngine'] = cc.ENGINE_VERSION = engineVersion; /** From ecf8f8ce655a3037b9bca12a55f5efc305721f8b Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 12 Aug 2016 12:46:45 +0800 Subject: [PATCH 148/268] Add cancelInnerEvents property in ScrollView --- cocos2d/core/components/CCScrollView.js | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/cocos2d/core/components/CCScrollView.js b/cocos2d/core/components/CCScrollView.js index 1bd2546a52..212810ca9b 100644 --- a/cocos2d/core/components/CCScrollView.js +++ b/cocos2d/core/components/CCScrollView.js @@ -160,7 +160,7 @@ var ScrollView = cc.Class({ * @property {Node} content */ content: { - default: null, + default: undefined, type: cc.Node, tooltip: 'i18n:COMPONENT.scrollview.content', }, @@ -240,7 +240,7 @@ var ScrollView = cc.Class({ * @property {Scrollbar} horizontalScrollBar */ horizontalScrollBar: { - default: null, + default: undefined, type: cc.Scrollbar, tooltip: 'i18n:COMPONENT.scrollview.horizontal_bar', notify: function() { @@ -258,7 +258,7 @@ var ScrollView = cc.Class({ * @property {Scrollbar} verticalScrollBar */ verticalScrollBar: { - default: null, + default: undefined, type: cc.Scrollbar, tooltip: 'i18n:COMPONENT.scrollview.vertical_bar', notify: function() { @@ -272,12 +272,24 @@ var ScrollView = cc.Class({ /** * !#en Scrollview events callback - * !#zh 滚动视图的事件回调函数 + * !#zh 滚动过程中的事件回调函数 * @property {Component.EventHandler[]} scrollEvents */ scrollEvents: { default: [], type: cc.Component.EventHandler + }, + + /** + * !#en If cancel inner events is set to true, the scroll behavior will cancel touch events on inner content nodes of the scroll view + * It's set to true by default. + * !#zh 如果这个属性被设置为 true,那么滚动行为会取消 ScrollView 的子节点上注册的触摸事件,默认被设置为 true。 + * 注意,子节点上的 touchstart 事件仍然会触发,触点移动距离非常短的情况下 touchmove 和 touchend 也不会受影响。 + * @property {Boolean} cancelInnerEvents + */ + cancelInnerEvents: { + default: true, + animatable: false, } }, @@ -846,6 +858,11 @@ var ScrollView = cc.Class({ if (this.content) { this._handleMoveLogic(touch); } + // Do not prevent touch events in inner nodes + if (!this.cancelInnerEvents) { + return; + } + var deltaMove = cc.pSub(touch.getLocation(), touch.getStartLocation()); //FIXME: touch move delta should be calculated by DPI. if (cc.pLength(deltaMove) > 7) { From afda122d299466f42b305c07afc2e1f1e7c78b2b Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Fri, 12 Aug 2016 15:08:03 +0800 Subject: [PATCH 149/268] add widget horizontal center and vertical center offset for fireball/issues/3967 --- cocos2d/core/base-ui/CCWidgetManager.js | 18 +++---- cocos2d/core/components/CCWidget.js | 72 +++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 10 deletions(-) diff --git a/cocos2d/core/base-ui/CCWidgetManager.js b/cocos2d/core/base-ui/CCWidgetManager.js index 7cbcc15638..1136dfba9e 100644 --- a/cocos2d/core/base-ui/CCWidgetManager.js +++ b/cocos2d/core/base-ui/CCWidgetManager.js @@ -91,8 +91,9 @@ function alignToParent (node, widget) { else { width = node.width * scaleX; if (widget.isAlignHorizontalCenter) { - var parentCenter = (0.5 - parentAnchor.x) * parentWidth; // no offset - x = parentCenter + (anchorX - 0.5) * width; + var horizontalCenter = widget._isAbsHorizontalCenter ? widget._horizontalCenter : widget._horizontalCenter * parentWidth; + var parentCenter = (0.5 - parentAnchor.x) * parentWidth; + x = parentCenter + (anchorX - 0.5) * width + horizontalCenter; } else if (widget.isAlignLeft) { x = localLeft + anchorX * width; @@ -137,8 +138,9 @@ function alignToParent (node, widget) { else { height = node.height * scaleY; if (widget.isAlignVerticalCenter) { - var parentMiddle = (0.5 - parentAnchor.y) * parentHeight; // no offset - y = parentMiddle + (anchorY - 0.5) * height; + var verticalCenter = widget._isAbsVerticalCenter ? widget._verticalCenter : widget._verticalCenter * parentHeight; + var parentMiddle = (0.5 - parentAnchor.y) * parentHeight; + y = parentMiddle + (anchorY - 0.5) * height + verticalCenter; } else if (widget.isAlignBottom) { y = localBottom + anchorY * height; @@ -268,14 +270,10 @@ var adjustWidgetToAllowMovingInEditor = CC_EDITOR && function (event) { this.right -= (this.isAbsoluteRight ? delta.x : deltaInPercent.x); } if (this.isAlignHorizontalCenter) { - if (oldPos.x !== newPos.x) { - this.isAlignHorizontalCenter = false; - } + this.horizontalCenter += (this.isAbsoluteHorizontalCenter ? delta.x : deltaInPercent.x); } if (this.isAlignVerticalCenter) { - if (oldPos.y !== newPos.y) { - this.isAlignVerticalCenter = false; - } + this.verticalCenter += (this.isAbsoluteVerticalCenter ? delta.y : deltaInPercent.y); } }; diff --git a/cocos2d/core/components/CCWidget.js b/cocos2d/core/components/CCWidget.js index 4c4c739bcf..6fdaec20c1 100644 --- a/cocos2d/core/components/CCWidget.js +++ b/cocos2d/core/components/CCWidget.js @@ -301,8 +301,76 @@ var Widget = cc.Class({ tooltip: 'i18n:COMPONENT.widget.right', }, + /** + * !#en TODO + * !#zh 水平居中的偏移值,可填写负值,只有在 isAlignHorizontalCenter 开启时才有作用。 + * @property horizontalCenter + * @type {Number} + * @default 0 + */ + horizontalCenter: { + get: function () { + return this._horizontalCenter; + }, + set: function (value) { + this._horizontalCenter = value; + }, + tooltip: 'i18n:COMPONENT.widget.horizontal_center', + }, + + /** + * !#en TODO + * !#zh 垂直居中的偏移值,可填写负值,只有在 isAlignVerticalCenter 开启时才有作用。 + * @property verticalCenter + * @type {Number} + * @default 0 + */ + verticalCenter: { + get: function () { + return this._verticalCenter; + }, + set: function (value) { + this._verticalCenter = value; + }, + tooltip: 'i18n:COMPONENT.widget.vertical_center', + }, + // PARCENTAGE OR ABSOLUTE + /** + * !#en TODO + * !#zh 如果为 true,"horizontalCenter" 将会以像素作为偏移值,反之为百分比。 + * @property isAbsoluteHorizontalCenter + * @type {Boolean} + * @default true + */ + isAbsoluteHorizontalCenter: { + get: function () { + return this._isAbsHorizontalCenter; + }, + set: function (value) { + this._isAbsHorizontalCenter = value; + }, + animatable: false + }, + + /** + * !#en TODO + * !#zh 如果为 true,"verticalCenter" 将会以像素作为偏移值,反之为百分比。 + * @property isAbsoluteHorizontalCenter + * @type {Boolean} + * @default true + */ + isAbsoluteVerticalCenter: { + get: function () { + return this._isAbsVerticalCenter; + }, + set: function (value) { + this._isAbsVerticalCenter = value; + }, + animatable: false + }, + /** * !#en * If true, top is pixel margin, otherwise is percentage (0 - 1) margin relative to the parent's height. @@ -411,10 +479,14 @@ var Widget = cc.Class({ _right: 0, _top: 0, _bottom: 0, + _verticalCenter: 0, + _horizontalCenter: 0, _isAbsLeft: true, _isAbsRight: true, _isAbsTop: true, _isAbsBottom: true, + _isAbsHorizontalCenter: true, + _isAbsVerticalCenter: true, // original size before align _originalWidth: 0, From f4a0cfba9369c154628aee65c807320ccc5d05a8 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Fri, 12 Aug 2016 16:24:08 +0800 Subject: [PATCH 150/268] update widget horizontal center and vertical center offset for fireball/issues/3967 --- cocos2d/core/base-ui/CCWidgetManager.js | 16 ++++++---------- cocos2d/core/components/CCWidget.js | 16 ++++++++++------ 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/cocos2d/core/base-ui/CCWidgetManager.js b/cocos2d/core/base-ui/CCWidgetManager.js index 1136dfba9e..7264eb18cb 100644 --- a/cocos2d/core/base-ui/CCWidgetManager.js +++ b/cocos2d/core/base-ui/CCWidgetManager.js @@ -91,9 +91,9 @@ function alignToParent (node, widget) { else { width = node.width * scaleX; if (widget.isAlignHorizontalCenter) { - var horizontalCenter = widget._isAbsHorizontalCenter ? widget._horizontalCenter : widget._horizontalCenter * parentWidth; + var localHorizontalCenter = widget._isAbsHorizontalCenter ? widget._horizontalCenter : widget._horizontalCenter * parentWidth; var parentCenter = (0.5 - parentAnchor.x) * parentWidth; - x = parentCenter + (anchorX - 0.5) * width + horizontalCenter; + x = parentCenter + (anchorX - 0.5) * width + localHorizontalCenter; } else if (widget.isAlignLeft) { x = localLeft + anchorX * width; @@ -138,9 +138,9 @@ function alignToParent (node, widget) { else { height = node.height * scaleY; if (widget.isAlignVerticalCenter) { - var verticalCenter = widget._isAbsVerticalCenter ? widget._verticalCenter : widget._verticalCenter * parentHeight; + var localVerticalCenter = widget._isAbsVerticalCenter ? widget._verticalCenter : widget._verticalCenter * parentHeight; var parentMiddle = (0.5 - parentAnchor.y) * parentHeight; - y = parentMiddle + (anchorY - 0.5) * height + verticalCenter; + y = parentMiddle + (anchorY - 0.5) * height + localVerticalCenter; } else if (widget.isAlignBottom) { y = localBottom + anchorY * height; @@ -309,14 +309,10 @@ var adjustWidgetToAllowResizingInEditor = CC_EDITOR && function (event) { this.right -= (this.isAbsoluteRight ? delta.x : deltaInPercent.x) * (1 - anchor.x); } if (this.isAlignHorizontalCenter) { - if (delta.x !== 0 && anchor.x !== 0.5) { - this.isAlignHorizontalCenter = false; - } + this.horizontalCenter -= (this.isAbsoluteHorizontalCenter ? delta.x : deltaInPercent.x); } if (this.isAlignVerticalCenter) { - if (delta.y !== 0 && anchor.y !== 0.5) { - this.isAlignVerticalCenter = false; - } + this.verticalCenter -= (this.isAbsoluteVerticalCenter ? delta.y : deltaInPercent.y); } }; diff --git a/cocos2d/core/components/CCWidget.js b/cocos2d/core/components/CCWidget.js index 6fdaec20c1..6063ec7088 100644 --- a/cocos2d/core/components/CCWidget.js +++ b/cocos2d/core/components/CCWidget.js @@ -302,7 +302,9 @@ var Widget = cc.Class({ }, /** - * !#en TODO + * !#en + * Horizontal aligns the midpoint offset value, + * the value can be negative, Only available in 'isAlignHorizontalCenter' open. * !#zh 水平居中的偏移值,可填写负值,只有在 isAlignHorizontalCenter 开启时才有作用。 * @property horizontalCenter * @type {Number} @@ -319,7 +321,9 @@ var Widget = cc.Class({ }, /** - * !#en TODO + * !#en + * Vertical aligns the midpoint offset value, + * the value can be negative, Only available in 'isAlignVerticalCenter' open. * !#zh 垂直居中的偏移值,可填写负值,只有在 isAlignVerticalCenter 开启时才有作用。 * @property verticalCenter * @type {Number} @@ -338,8 +342,8 @@ var Widget = cc.Class({ // PARCENTAGE OR ABSOLUTE /** - * !#en TODO - * !#zh 如果为 true,"horizontalCenter" 将会以像素作为偏移值,反之为百分比。 + * !#en If true, horizontalCenter is pixel margin, otherwise is percentage (0 - 1) margin. + * !#zh 如果为 true,"horizontalCenter" 将会以像素作为偏移值,反之为百分比(0 到 1)。 * @property isAbsoluteHorizontalCenter * @type {Boolean} * @default true @@ -355,8 +359,8 @@ var Widget = cc.Class({ }, /** - * !#en TODO - * !#zh 如果为 true,"verticalCenter" 将会以像素作为偏移值,反之为百分比。 + * !#en If true, verticalCenter is pixel margin, otherwise is percentage (0 - 1) margin. + * !#zh 如果为 true,"verticalCenter" 将会以像素作为偏移值,反之为百分比(0 到 1)。 * @property isAbsoluteHorizontalCenter * @type {Boolean} * @default true From 61dcd9d68a602e10ba05fdf33a8d6dd90eecf2a7 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Fri, 12 Aug 2016 18:01:49 +0800 Subject: [PATCH 151/268] working on fixing memleak in JSB --- CCDebugger.js | 8 ++++- cocos2d/core/components/CCMask.js | 20 ++++++++----- cocos2d/core/components/CCRendererInSG.js | 1 + cocos2d/core/components/CCRendererUnderSG.js | 1 + cocos2d/core/components/CCSGComponent.js | 1 + cocos2d/core/components/CCSprite.js | 29 ++++++++++++------- .../core/load-pipeline/auto-release-utils.js | 10 ++++++- cocos2d/core/load-pipeline/uuid-loader.js | 3 +- cocos2d/core/platform/CCClass.js | 9 ++++++ 9 files changed, 61 insertions(+), 21 deletions(-) diff --git a/CCDebugger.js b/CCDebugger.js index 52ea74b18d..73f672db61 100644 --- a/CCDebugger.js +++ b/CCDebugger.js @@ -543,7 +543,13 @@ cc._initDebugSetting = function (mode) { } } cc._throw = CC_EDITOR ? Editor.error : function (error) { - cc.error(error.stack || error); + var stack = error.stack; + if (stack) { + cc.error(CC_JSB ? (error + '\n' + stack) : stack); + } + else { + cc.error(error); + } }; }; //+++++++++++++++++++++++++something about log end+++++++++++++++++++++++++++++ diff --git a/cocos2d/core/components/CCMask.js b/cocos2d/core/components/CCMask.js index 3d6f28b019..bc5aaf1cc5 100644 --- a/cocos2d/core/components/CCMask.js +++ b/cocos2d/core/components/CCMask.js @@ -23,6 +23,8 @@ THE SOFTWARE. ****************************************************************************/ +var Base = cc._RendererInSG; + /** * @class Mask * @extends _RendererInSG @@ -51,7 +53,7 @@ var MaskType = cc.Enum({ var Mask = cc.Class({ name: 'cc.Mask', - extends: cc._RendererInSG, + extends: Base, editor: CC_EDITOR && { menu: 'i18n:MAIN_MENU.component.renderers/Mask', @@ -167,12 +169,6 @@ var Mask = cc.Class({ this.node.off('anchor-changed', this._refreshStencil, this); }, - onDestroy: CC_JSB && function () { - this._super(); - this._clippingStencil.release(); - this._clippingStencil = null; - }, - _calculateCircle: function(center, radius, segements) { var polies =[]; var anglePerStep = Math.PI * 2 / segements; @@ -208,4 +204,14 @@ var Mask = cc.Class({ } }); +if (CC_JSB) { + // override onDestroy + Mask.prototype.__superOnDestroy = Base.prototype.onDestroy; + Mask.prototype.onDestroy = function () { + this.__superOnDestroy(); + this._clippingStencil.release(); + this._clippingStencil = null; + }; +} + cc.Mask = module.exports = Mask; diff --git a/cocos2d/core/components/CCRendererInSG.js b/cocos2d/core/components/CCRendererInSG.js index c349c8f6ab..57476afe85 100644 --- a/cocos2d/core/components/CCRendererInSG.js +++ b/cocos2d/core/components/CCRendererInSG.js @@ -33,6 +33,7 @@ */ var RendererInSG = cc.Class({ extends: require('./CCSGComponent'), + name: 'cc._RendererInSG', ctor: function () { /** diff --git a/cocos2d/core/components/CCRendererUnderSG.js b/cocos2d/core/components/CCRendererUnderSG.js index 12c424d248..fbbee4c901 100644 --- a/cocos2d/core/components/CCRendererUnderSG.js +++ b/cocos2d/core/components/CCRendererUnderSG.js @@ -32,6 +32,7 @@ */ var RendererUnderSG = cc.Class({ extends: require('./CCSGComponent'), + name: 'cc._RendererUnderSG', ctor: function () { /** diff --git a/cocos2d/core/components/CCSGComponent.js b/cocos2d/core/components/CCSGComponent.js index 0499d695de..01ca05a92c 100644 --- a/cocos2d/core/components/CCSGComponent.js +++ b/cocos2d/core/components/CCSGComponent.js @@ -38,6 +38,7 @@ var SceneGraphHelper = require('../utils/scene-graph-helper'); */ var SGComponent = cc.Class({ extends: require('./CCComponent'), + name: 'cc._SGComponent', editor: CC_EDITOR && { executeInEditMode: true, diff --git a/cocos2d/core/components/CCSprite.js b/cocos2d/core/components/CCSprite.js index 28d7c9616e..055b2fffbe 100644 --- a/cocos2d/core/components/CCSprite.js +++ b/cocos2d/core/components/CCSprite.js @@ -23,6 +23,8 @@ THE SOFTWARE. ****************************************************************************/ +var Base = require('./CCRendererUnderSG'); + /** * !#en Enum for sprite type. * !#zh Sprite 类型 @@ -113,7 +115,7 @@ var SizeMode = cc.Enum({ */ var Sprite = cc.Class({ name: 'cc.Sprite', - extends: require('./CCRendererUnderSG'), + extends: Base, editor: CC_EDITOR && { menu: 'i18n:MAIN_MENU.component.renderers/Sprite', @@ -483,11 +485,6 @@ var Sprite = cc.Class({ return this._sgNode.getInsetBottom(); }, - __preload: CC_EDITOR && function () { - this._super(); - this.node.on('size-changed', this._resized, this); - }, - onEnable: function () { if (this._sgNode) { if (this._spriteFrame && this._spriteFrame.textureLoaded()) { @@ -496,11 +493,6 @@ var Sprite = cc.Class({ } }, - onDestroy: CC_EDITOR && function () { - this._super(); - this.node.off('size-changed', this._resized, this); - }, - _applyAtlas: CC_EDITOR && function (spriteFrame) { // Set atlas if (spriteFrame && spriteFrame._atlasUuid) { @@ -623,6 +615,21 @@ var Sprite = cc.Class({ }, }); +if (CC_EDITOR) { + // override __preload + Sprite.prototype.__superPreload = Base.prototype.__preload; + Sprite.prototype.__preload = function () { + this.__superPreload(); + this.node.on('size-changed', this._resized, this); + }; + // override onDestroy + Sprite.prototype.__superOnDestroy = Base.prototype.onDestroy; + Sprite.prototype.onDestroy = function () { + this.__superOnDestroy(); + this.node.off('size-changed', this._resized, this); + }; +} + var misc = require('../utils/misc'); var SameNameGetSets = ['atlas', 'capInsets', 'insetLeft', 'insetTop', 'insetRight', 'insetBottom']; var DiffNameGetSets = { diff --git a/cocos2d/core/load-pipeline/auto-release-utils.js b/cocos2d/core/load-pipeline/auto-release-utils.js index 43a947c3a0..60af8f90f7 100644 --- a/cocos2d/core/load-pipeline/auto-release-utils.js +++ b/cocos2d/core/load-pipeline/auto-release-utils.js @@ -22,9 +22,17 @@ function release (loader, key, nextSceneAssets) { loader.removeItem(key); console.log('auto release: ' + key); // TODO: Audio - if (item.content instanceof cc.Texture2D) { + var asset = item.content; + if (asset instanceof cc.Texture2D) { cc.textureCache.removeTextureForKey(item.url); } + //else if (asset instanceof cc.SpriteFrame) { + // // for the "Temporary solution" in deserialize.js + // console.log('release sprite frame: ' + key); + // if (CC_JSB) { + // asset.release(); + // } + //} } } } diff --git a/cocos2d/core/load-pipeline/uuid-loader.js b/cocos2d/core/load-pipeline/uuid-loader.js index d113d6538a..ebc3db3669 100644 --- a/cocos2d/core/load-pipeline/uuid-loader.js +++ b/cocos2d/core/load-pipeline/uuid-loader.js @@ -215,7 +215,8 @@ function loadUuid (item, callback) { }); } catch (e) { - callback( new Error('Uuid Loader: Deserialize asset [' + item.id + '] failed : ' + e.stack) ); + var err = CC_JSB ? (e + '\n' + e.stack) : e.stack; + callback( new Error('Uuid Loader: Deserialize asset [' + item.id + '] failed : ' + err) ); return; } diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index 953be36160..cfc522cc92 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -906,6 +906,15 @@ function CCClass (options) { }); } else if (CC_DEV) { + if (func === false && base && base.prototype) { + // check override + var overrided = base.prototype[funcName]; + if (typeof overrided === 'function') { + var baseFuc = JS.getClassName(base) + '.' + funcName; + var subFuc = name + '.' + funcName; + cc.warn('"%s" overrided "%s" but "%s" is defined as "false" so the super method will not be called. You can set "%s" to null to disable this warning.', subFuc, baseFuc, subFuc, subFuc); + } + } var correct = TYPO_TO_CORRECT[funcName]; if (correct) { cc.warn('Unknown type of %s.%s, maybe you want is "%s".', name, funcName, correct); From 80ca28144c47413fb58251690a950a5cd077fa3f Mon Sep 17 00:00:00 2001 From: Nan Wang Date: Fri, 12 Aug 2016 19:29:25 +0800 Subject: [PATCH 152/268] update ccclass editor attributes --- cocos2d/core/platform/CCClass.js | 100 +++++++------------------------ extensions/ccpool/CCPool.js | 1 + 2 files changed, 22 insertions(+), 79 deletions(-) diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index 953be36160..b2721cad08 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -614,21 +614,21 @@ function _boundSuperCall (func, funcName, base) { var pd = JS.getPropertyDescriptor(base.prototype, funcName); if (pd) { superFunc = pd.value; - // ignore pd.get, assume that function defined by getter is just for warnings + // ignore pd.get, assume that function defined by getter is just for warnings if (typeof superFunc === 'function') { var hasSuperCall = SuperCallReg.test(func); if (hasSuperCall) { return function () { var tmp = this._super; - + // Add a new ._super() method that is the same method but on the super-Class this._super = superFunc; - + var ret = func.apply(this, arguments); - + // The method only need to be bound temporarily, so we remove it when we're done executing this._super = tmp; - + return ret; }; } @@ -689,72 +689,6 @@ function declareProperties (cls, className, properties, baseClass, mixins) { } } -/** - * @class _ComponentAttributes - * @constructor - */ -/** - * Automatically add required component as a dependency. - * - * @property requireComponent - * @type {Component} - * @default null - */ -/** - * If specified to a type, prevents Component of the same type (or subtype) to be added more than once to a Node. - * - * @property disallowMultiple - * @type {Component} - * @default null - */ -/** - * The menu path to register a component to the editors "Component" menu. Eg. "Rendering/Camera". - * - * @property menu - * @type {String} - * @default "" - */ -/** - * Makes a component execute in edit mode. - * By default, all components are only executed in play mode, - * which means they will not have their callback functions executed while the Editor is in edit mode. - * - * @property executeInEditMode - * @type {Boolean} - * @default false - */ -/** - * This property is only available if executeInEditMode is true. - * If specified, the editor's scene view will keep updating this node in 60 fps when it is selected, - * otherwise, it will update only if necessary. - * - * @property playOnFocus - * @type {Boolean} - * @default false - */ -/** - * Specifying the url of the custom html to draw the component in inspector. - * - * @property inspector - * @type {String} - * @default "" - */ -/** - * Specifying the url of the icon to display in inspector. - * - * @property icon - * @type {String} - * @default "" - */ - -/** - * The custom documentation URL - * - * @property help - * @type {String} - * @default "" - */ - /** * @module cc */ @@ -762,9 +696,9 @@ function declareProperties (cls, className, properties, baseClass, mixins) { /** * !#en Defines a CCClass using the given specification, please see [Class](/en/scripting/class/) for details. * !#zh 定义一个 CCClass,传入参数必须是一个包含类型参数的字面量对象,具体用法请查阅[类型定义](/zh/scripting/class/)。 - * + * * @method Class - * + * * @param {Object} [options] * @param {String} [options.name] - The class name used for serialization. * @param {Function} [options.extends] - The base class. @@ -772,9 +706,17 @@ function declareProperties (cls, className, properties, baseClass, mixins) { * @param {Object} [options.properties] - The property definitions. * @param {Object} [options.statics] - The static members. * @param {Function[]} [options.mixins] - * - * @param {Object} [options.editor] - attributes for Component, see {{#crossLink "_ComponentAttributes"}}ComponentAttributes{{/crossLink}}. - * + * + * @param {Object} [options.editor] - attributes for Component listed below. + * @param {Component} [options.editor.requireComponent] - Automatically add required component as a dependency. + * @param {Component} [options.editor.disallowMultiple] - If specified to a type, prevents Component of the same type (or subtype) to be added more than once to a Node. + * @param {String} [options.editor.menu] - The menu path to register a component to the editors "Component" menu. Eg. "Rendering/Camera". + * @param {Boolean} [options.editor.executeInEditMode] - Makes a component execute in edit mode. By default, all components are only executed in play mode, which means they will not have their callback functions executed while the Editor is in edit mode. + * @param {Boolean} [options.editor.playOnFocus] - This property is only available if executeInEditMode is true. If specified, the editor's scene view will keep updating this node in 60 fps when it is selected, otherwise, it will update only if necessary. + * @param {String} [options.editor.inspector] - Specifying the url of the custom html to draw the component in inspector. + * @param {String} [options.editor.icon] - Specifying the url of the icon to display in inspector. + * @param {String} [options.editor.help] - The custom documentation UR + * * @param {Function} [options.update] - lifecycle method for Component, see {{#crossLink "Component/update:method"}}{{/crossLink}} * @param {Function} [options.lateUpdate] - lifecycle method for Component, see {{#crossLink "Component/lateUpdate:method"}}{{/crossLink}} * @param {Function} [options.onLoad] - lifecycle method for Component, see {{#crossLink "Component/onLoad:method"}}{{/crossLink}} @@ -786,9 +728,9 @@ function declareProperties (cls, className, properties, baseClass, mixins) { * @param {Function} [options.onLostFocusInEditor] - lifecycle method for Component, see {{#crossLink "Component/onLostFocusInEditor:method"}}{{/crossLink}} * @param {Function} [options.onRestore] - for Component only, see {{#crossLink "Component/onRestore:method"}}{{/crossLink}} * @param {Function} [options._getLocalBounds] - for Component only, see {{#crossLink "Component/_getLocalBounds:method"}}{{/crossLink}} - * + * * @return {Function} - the created class - * + * * @example // define base class var Node = cc.Class(); @@ -1142,5 +1084,5 @@ module.exports = { }; if (CC_EDITOR) { - module.exports.getDefault = getDefault; + module.exports.getDefault = getDefault; } diff --git a/extensions/ccpool/CCPool.js b/extensions/ccpool/CCPool.js index 384dac278e..a39b9f56db 100644 --- a/extensions/ccpool/CCPool.js +++ b/extensions/ccpool/CCPool.js @@ -38,6 +38,7 @@ * cc.pool 是一个单例对象,用作为对象缓存池。
* 它可以帮助您提高游戏性能,适用于优化对象的反复创建和销毁
* @class pool + * @deprecated !#en Please use cc.NodePool instead !#zh 请使用 cc.NodePool 代替 */ cc.pool = /** @lends cc.pool# */{ _pool: {}, From f92c3c61272049dcd539c293ea84571c31c663cd Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Sun, 14 Aug 2016 13:54:35 +0800 Subject: [PATCH 153/268] fix api --- cocos2d/core/utils/base-node.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/utils/base-node.js b/cocos2d/core/utils/base-node.js index e102ee02ae..2e727fd3b3 100644 --- a/cocos2d/core/utils/base-node.js +++ b/cocos2d/core/utils/base-node.js @@ -1610,7 +1610,7 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ * treating the returned/received node point as anchor relative. * !#zh * 将一个点转换到世界空间坐标系。结果以 Vec2 为单位。
- * 返回值将基于节点坐标。 + * 返回值将基于世界坐标。 * @method convertToWorldSpaceAR * @param {Vec2} nodePoint * @return {Vec2} From 54149c7c3364ea3662fbe19448e56b0b38117189 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 15 Aug 2016 01:15:43 +0800 Subject: [PATCH 154/268] Fix API docs --- cocos2d/core/components/CCScrollView.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/components/CCScrollView.js b/cocos2d/core/components/CCScrollView.js index 212810ca9b..0f8456e3d1 100644 --- a/cocos2d/core/components/CCScrollView.js +++ b/cocos2d/core/components/CCScrollView.js @@ -272,7 +272,7 @@ var ScrollView = cc.Class({ /** * !#en Scrollview events callback - * !#zh 滚动过程中的事件回调函数 + * !#zh 滚动视图的事件回调函数 * @property {Component.EventHandler[]} scrollEvents */ scrollEvents: { @@ -281,7 +281,7 @@ var ScrollView = cc.Class({ }, /** - * !#en If cancel inner events is set to true, the scroll behavior will cancel touch events on inner content nodes of the scroll view + * !#en If cancelInnerEvents is set to true, the scroll behavior will cancel touch events on inner content nodes of the scroll view * It's set to true by default. * !#zh 如果这个属性被设置为 true,那么滚动行为会取消 ScrollView 的子节点上注册的触摸事件,默认被设置为 true。 * 注意,子节点上的 touchstart 事件仍然会触发,触点移动距离非常短的情况下 touchmove 和 touchend 也不会受影响。 From be1d4140d23004af8ac179cdb355f3eda8eae588 Mon Sep 17 00:00:00 2001 From: Nan Wang Date: Mon, 15 Aug 2016 09:33:20 +0800 Subject: [PATCH 155/268] update engine version --- CCBoot.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CCBoot.js b/CCBoot.js index 3e505421b2..3f1f5dbadf 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -58,7 +58,7 @@ _p = null; * @name cc.ENGINE_VERSION */ var engineVersion; -engineVersion = '1.2.1-beta.2'; +engineVersion = '1.2.1-beta.3'; window['CocosEngine'] = cc.ENGINE_VERSION = engineVersion; /** From 7bab9fc148ae60481e6df34856ee763e79fdd4e9 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Mon, 15 Aug 2016 11:02:13 +0800 Subject: [PATCH 156/268] auto release cached SpriteFrame --- cocos2d/core/load-pipeline/CCLoader.js | 3 ++- cocos2d/core/load-pipeline/auto-release-utils.js | 13 +++++-------- cocos2d/core/load-pipeline/pipeline.js | 1 + jsb/jsb-tex-sprite-frame.js | 2 +- 4 files changed, 9 insertions(+), 10 deletions(-) diff --git a/cocos2d/core/load-pipeline/CCLoader.js b/cocos2d/core/load-pipeline/CCLoader.js index b3a6a7bc39..5f72dc5ec2 100644 --- a/cocos2d/core/load-pipeline/CCLoader.js +++ b/cocos2d/core/load-pipeline/CCLoader.js @@ -525,8 +525,9 @@ JS.mixin(CCLoader.prototype, { // override removeItem: function (key) { - this._baseRemoveItem(key); + var removed = this._baseRemoveItem(key); delete this._autoReleaseSetting[key]; + return removed; }, /** diff --git a/cocos2d/core/load-pipeline/auto-release-utils.js b/cocos2d/core/load-pipeline/auto-release-utils.js index 60af8f90f7..491463dd2d 100644 --- a/cocos2d/core/load-pipeline/auto-release-utils.js +++ b/cocos2d/core/load-pipeline/auto-release-utils.js @@ -19,20 +19,17 @@ function release (loader, key, nextSceneAssets) { if (!nextSceneAssets || nextSceneAssets.indexOf(key) === -1) { var item = loader.getItem(key); if (item) { - loader.removeItem(key); + var removed = loader.removeItem(key); console.log('auto release: ' + key); // TODO: Audio var asset = item.content; if (asset instanceof cc.Texture2D) { cc.textureCache.removeTextureForKey(item.url); } - //else if (asset instanceof cc.SpriteFrame) { - // // for the "Temporary solution" in deserialize.js - // console.log('release sprite frame: ' + key); - // if (CC_JSB) { - // asset.release(); - // } - //} + else if (CC_JSB && asset instanceof cc.SpriteFrame && removed) { + // for the "Temporary solution" in deserialize.js + asset.release(); + } } } } diff --git a/cocos2d/core/load-pipeline/pipeline.js b/cocos2d/core/load-pipeline/pipeline.js index 27e962969d..5358ed4f2b 100644 --- a/cocos2d/core/load-pipeline/pipeline.js +++ b/cocos2d/core/load-pipeline/pipeline.js @@ -509,6 +509,7 @@ JS.mixin(Pipeline.prototype, { this.flowOut(item); } this._items.removeItem(url); + return true; } else { return false; diff --git a/jsb/jsb-tex-sprite-frame.js b/jsb/jsb-tex-sprite-frame.js index 448e46e983..769d1704fc 100644 --- a/jsb/jsb-tex-sprite-frame.js +++ b/jsb/jsb-tex-sprite-frame.js @@ -32,6 +32,7 @@ require('../cocos2d/core/assets/CCAsset'); // cc.SpriteFrameAnimation = cc.Animation; // cc.textureCache.cacheImage + cc.textureCache._textures = {}; cc.textureCache.cacheImage = function (key, texture) { if (texture instanceof cc.Texture2D) { @@ -75,7 +76,6 @@ prototype.textureLoaded = function () { return this.getTexture() !== null; }; -// cc.SpriteFrame prototype._ctor = function (filename, rect, rotated, offset, originalSize) { this._name = ''; if (filename !== undefined) { From 8605cf4d8f137c7fa7c768e8194f7add7623fb86 Mon Sep 17 00:00:00 2001 From: 2youyouo2 <501251991@qq.com> Date: Mon, 15 Aug 2016 11:45:12 +0800 Subject: [PATCH 157/268] fixed graphics arc --- cocos2d/core/graphics/graphics-canvas-cmd.js | 95 ++--------------- cocos2d/core/graphics/graphics-webgl-cmd.js | 103 ++----------------- cocos2d/core/graphics/helper.js | 100 ++++++++++++++++++ 3 files changed, 116 insertions(+), 182 deletions(-) create mode 100644 cocos2d/core/graphics/helper.js diff --git a/cocos2d/core/graphics/graphics-canvas-cmd.js b/cocos2d/core/graphics/graphics-canvas-cmd.js index 311731717d..3425e3d1e3 100644 --- a/cocos2d/core/graphics/graphics-canvas-cmd.js +++ b/cocos2d/core/graphics/graphics-canvas-cmd.js @@ -27,16 +27,7 @@ var Js = cc.js; var LineCap = require('./types').LineCap; var LineJoin = require('./types').LineJoin; -var PI = 3.14159265358979323846264338327; - -var min = Math.min; -var max = Math.max; -var cos = Math.cos; -var sin = Math.sin; -var abs = Math.abs; -var sign = Math.sign; - -var KAPPA90 = 0.5522847493; +var Helper = require('./helper'); var CanvasRenderCmd = function (renderable) { _ccsg.Node.CanvasRenderCmd.call(this, renderable); @@ -94,12 +85,12 @@ _p.rendering = function (ctx, scaleX, scaleY) { // draw api Js.mixin(_p, { setStrokeColor: function (v) { - var fillStyle = "rgba(" + (0 | v.r) + "," + (0 | v.g) + "," + (0 | v.b) + "," + v.a / 255 + ")"; + var fillStyle = 'rgba(' + (0 | v.r) + ',' + (0 | v.g) + ',' + (0 | v.b) + ',' + v.a / 255 + ')'; this.cmds.push(['strokeStyle', fillStyle]); }, setFillColor: function (v) { - var fillStyle = "rgba(" + (0 | v.r) + "," + (0 | v.g) + "," + (0 | v.b) + "," + v.a / 255 + ")"; + var fillStyle = 'rgba(' + (0 | v.r) + ',' + (0 | v.g) + ',' + (0 | v.b) + ',' + v.a / 255 + ')'; this.cmds.push(['fillStyle', fillStyle]); }, @@ -157,69 +148,16 @@ Js.mixin(_p, { }, // - arc: function (cx, cy, r, a0, a1, counterclockwise) { - // this.cmds.push(['arc', arguments]); - var a = 0, da = 0, hda = 0, kappa = 0; - var dx = 0, dy = 0, x = 0, y = 0, tanx = 0, tany = 0; - var px = 0, py = 0, ptanx = 0, ptany = 0; - var i, ndivs; - - // Clamp angles - da = a1 - a0; - if (!counterclockwise) { - if (abs(da) >= PI * 2) { - da = PI * 2; - } else { - while (da < 0) da += PI * 2; - } - } else { - if (abs(da) >= PI * 2) { - da = -PI * 2; - } else { - while (da > 0) da -= PI * 2; - } - } - - // Split arc into max 90 degree segments. - ndivs = max(1, min(abs(da) / (PI * 0.5) + 0.5, 5)) | 0; - hda = da / ndivs / 2.0; - kappa = abs(4.0 / 3.0 * (1 - cos(hda)) / sin(hda)); - - if (counterclockwise) kappa = -kappa; - - for (i = 0; i <= ndivs; i++) { - a = a0 + da * (i / ndivs); - dx = cos(a); - dy = sin(a); - x = cx + dx * r; - y = cy + dy * r; - tanx = -dy * r * kappa; - tany = dx * r * kappa; - - if (i === 0) { - this.moveTo(x, y); - } else { - this.bezierCurveTo(px + ptanx, py + ptany, x - tanx, y - tany, x, y); - } - px = x; - py = y; - ptanx = tanx; - ptany = tany; - } + arc: function (cx, cy, r, startAngle, endAngle, counterclockwise) { + Helper.arc(this, cx, cy, r, startAngle, endAngle, counterclockwise); }, ellipse: function (cx, cy, rx, ry) { - this.moveTo(cx - rx, cy); - this.bezierCurveTo(cx - rx, cy + ry * KAPPA90, cx - rx * KAPPA90, cy + ry, cx, cy + ry); - this.bezierCurveTo(cx + rx * KAPPA90, cy + ry, cx + rx, cy + ry * KAPPA90, cx + rx, cy); - this.bezierCurveTo(cx + rx, cy - ry * KAPPA90, cx + rx * KAPPA90, cy - ry, cx, cy - ry); - this.bezierCurveTo(cx - rx * KAPPA90, cy - ry, cx - rx, cy - ry * KAPPA90, cx - rx, cy); - this.close(); + Helper.ellipse(this, cx, cy, rx, ry); }, circle: function (cx, cy, r) { - this.ellipse(cx, cy, r, r); - this.close(); + Helper.ellipse(this, cx, cy, r, r); }, rect: function (x, y, w, h) { @@ -231,24 +169,7 @@ Js.mixin(_p, { }, roundRect: function (x, y, w, h, r) { - if (r < 0.1) { - this.rect(x, y, w, h); - return; - } else { - var rx = min(r, abs(w) * 0.5) * sign(w), - ry = min(r, abs(h) * 0.5) * sign(h); - - this.moveTo(x, y + ry); - this.lineTo(x, y + h - ry); - this.bezierCurveTo(x, y + h - ry * (1 - KAPPA90), x + rx * (1 - KAPPA90), y + h, x + rx, y + h); - this.lineTo(x + w - rx, y + h); - this.bezierCurveTo(x + w - rx * (1 - KAPPA90), y + h, x + w, y + h - ry * (1 - KAPPA90), x + w, y + h - ry); - this.lineTo(x + w, y + ry); - this.bezierCurveTo(x + w, y + ry * (1 - KAPPA90), x + w - rx * (1 - KAPPA90), y, x + w - rx, y); - this.lineTo(x + rx, y); - this.bezierCurveTo(x + rx * (1 - KAPPA90), y, x, y + ry * (1 - KAPPA90), x, y + ry); - this.close(); - } + Helper.roundRect(this, x, y, w, h, r); }, fillRect: function (x, y, w, h) { diff --git a/cocos2d/core/graphics/graphics-webgl-cmd.js b/cocos2d/core/graphics/graphics-webgl-cmd.js index a8f7f4bf0b..ed72a464e6 100644 --- a/cocos2d/core/graphics/graphics-webgl-cmd.js +++ b/cocos2d/core/graphics/graphics-webgl-cmd.js @@ -30,14 +30,14 @@ var LineJoin = require('./types').LineJoin; var Earcut = require('./earcut'); +var Helper = require('./Helper'); + var Vec2 = cc.Vec2; var Js = cc.js; // Math var PI = 3.14159265358979323846264338327; -var PI_2 = PI*2; var INIT_VERTS_SIZE = 32; -var KAPPA90 = 0.5522847493; var VERTS_FLOAT_LENGTH = 2; var VERTS_BYTE_LENGTH = 8; @@ -50,7 +50,6 @@ var cos = Math.cos; var sin = Math.sin; var atan2 = Math.atan2; var abs = Math.abs; -var sign = Math.sign; function clamp (v, min, max) { if (v < min) { @@ -206,86 +205,17 @@ Js.mixin(_p, { }, // - arc: function (cx, cy, r, a0, a1, counterclockwise) { - var a = 0, da = 0, hda = 0, kappa = 0; - var dx = 0, dy = 0, x = 0, y = 0, tanx = 0, tany = 0; - var px = 0, py = 0, ptanx = 0, ptany = 0; - var i, ndivs; - - // Clamp angles - da = a1 - a0; - if (!counterclockwise) { - if (abs(da) >= PI * 2) { - da = PI * 2; - } else { - while (da < 0) da += PI * 2; - } - } else { - if (abs(da) >= PI * 2) { - da = -PI * 2; - } else { - while (da > 0) da -= PI * 2; - } - } - - // Split arc into max 90 degree segments. - ndivs = max(1, min(abs(da) / (PI * 0.5) + 0.5, 5)) | 0; - hda = da / ndivs / 2.0; - kappa = abs(4.0 / 3.0 * (1 - cos(hda)) / sin(hda)); - - if (counterclockwise) kappa = -kappa; - - for (i = 0; i <= ndivs; i++) { - a = a0 + da * (i / ndivs); - dx = cos(a); - dy = sin(a); - x = cx + dx * r; - y = cy + dy * r; - tanx = -dy * r * kappa; - tany = dx * r * kappa; - - if (i === 0) { - this.moveTo(x, y); - } else { - this.bezierCurveTo(px + ptanx, py + ptany, x - tanx, y - tany, x, y); - } - px = x; - py = y; - ptanx = tanx; - ptany = tany; - } - - // this.close(); - // this._curPath.complex = false; + arc: function (cx, cy, r, startAngle, endAngle, counterclockwise) { + Helper.arc(this, cx, cy, r, startAngle, endAngle, counterclockwise); }, ellipse: function (cx, cy, rx, ry) { - this.moveTo(cx - rx, cy); - this.bezierCurveTo(cx - rx, cy + ry * KAPPA90, cx - rx * KAPPA90, cy + ry, cx, cy + ry); - this.bezierCurveTo(cx + rx * KAPPA90, cy + ry, cx + rx, cy + ry * KAPPA90, cx + rx, cy); - this.bezierCurveTo(cx + rx, cy - ry * KAPPA90, cx + rx * KAPPA90, cy - ry, cx, cy - ry); - this.bezierCurveTo(cx - rx * KAPPA90, cy - ry, cx - rx, cy - ry * KAPPA90, cx - rx, cy); - - this.close(); + Helper.ellipse(this, cx, cy, rx, ry); this._curPath.complex = false; }, circle: function (cx, cy, r) { - // this.ellipse(cx, cy, r, r); - var divs = this._curveDivs(r, PI_2, this._tessTol); - var step = PI_2 / divs; - - this.moveTo(cx, cy + r); - - for (var i = 1; i < divs; i++) { - var angle = step * i; - var x = r * sin(angle); - var y = r * cos(angle); - - this.lineTo(cx + x, cy + y); - } - - this.close(); + Helper.ellipse(this, cx, cy, r, r); this._curPath.complex = false; }, @@ -299,25 +229,8 @@ Js.mixin(_p, { }, roundRect: function (x, y, w, h, r) { - if (r < 0.1) { - this.rect(x, y, w, h); - return; - } else { - var rx = min(r, abs(w) * 0.5) * sign(w), - ry = min(r, abs(h) * 0.5) * sign(h); - - this.moveTo(x, y + ry); - this.lineTo(x, y + h - ry); - this.bezierCurveTo(x, y + h - ry * (1 - KAPPA90), x + rx * (1 - KAPPA90), y + h, x + rx, y + h); - this.lineTo(x + w - rx, y + h); - this.bezierCurveTo(x + w - rx * (1 - KAPPA90), y + h, x + w, y + h - ry * (1 - KAPPA90), x + w, y + h - ry); - this.lineTo(x + w, y + ry); - this.bezierCurveTo(x + w, y + ry * (1 - KAPPA90), x + w - rx * (1 - KAPPA90), y, x + w - rx, y); - this.lineTo(x + rx, y); - this.bezierCurveTo(x + rx * (1 - KAPPA90), y, x, y + ry * (1 - KAPPA90), x, y + ry); - this.close(); - this._curPath.complex = false; - } + Helper.roundRect(this, x, y, w, h, r); + this._curPath.complex = false; }, fillRect: function (x, y, w, h) { diff --git a/cocos2d/core/graphics/helper.js b/cocos2d/core/graphics/helper.js new file mode 100644 index 0000000000..a073e0348f --- /dev/null +++ b/cocos2d/core/graphics/helper.js @@ -0,0 +1,100 @@ + +var PI = 3.14159265358979323846264338327; + +var min = Math.min; +var max = Math.max; +var cos = Math.cos; +var sin = Math.sin; +var abs = Math.abs; +var sign = Math.sign; + +var KAPPA90 = 0.5522847493; + +function arc (ctx, cx, cy, r, startAngle, endAngle, counterclockwise) { + counterclockwise = counterclockwise || false; + + var a = 0, da = 0, hda = 0, kappa = 0; + var dx = 0, dy = 0, x = 0, y = 0, tanx = 0, tany = 0; + var px = 0, py = 0, ptanx = 0, ptany = 0; + var i, ndivs; + + // Clamp angles + da = endAngle - startAngle; + if (counterclockwise) { + if (abs(da) >= PI * 2) { + da = PI * 2; + } else { + while (da < 0) da += PI * 2; + } + } else { + if (abs(da) >= PI * 2) { + da = -PI * 2; + } else { + while (da > 0) da -= PI * 2; + } + } + + // Split arc into max 90 degree segments. + ndivs = max(1, min(abs(da) / (PI * 0.5) + 0.5, 5)) | 0; + hda = da / ndivs / 2.0; + kappa = abs(4.0 / 3.0 * (1 - cos(hda)) / sin(hda)); + + if (!counterclockwise) kappa = -kappa; + + for (i = 0; i <= ndivs; i++) { + a = startAngle + da * (i / ndivs); + dx = cos(a); + dy = sin(a); + x = cx + dx * r; + y = cy + dy * r; + tanx = -dy * r * kappa; + tany = dx * r * kappa; + + if (i === 0) { + ctx.moveTo(x, y); + } else { + ctx.bezierCurveTo(px + ptanx, py + ptany, x - tanx, y - tany, x, y); + } + px = x; + py = y; + ptanx = tanx; + ptany = tany; + } +} + +function ellipse (ctx, cx, cy, rx, ry) { + ctx.moveTo(cx - rx, cy); + ctx.bezierCurveTo(cx - rx, cy + ry * KAPPA90, cx - rx * KAPPA90, cy + ry, cx, cy + ry); + ctx.bezierCurveTo(cx + rx * KAPPA90, cy + ry, cx + rx, cy + ry * KAPPA90, cx + rx, cy); + ctx.bezierCurveTo(cx + rx, cy - ry * KAPPA90, cx + rx * KAPPA90, cy - ry, cx, cy - ry); + ctx.bezierCurveTo(cx - rx * KAPPA90, cy - ry, cx - rx, cy - ry * KAPPA90, cx - rx, cy); + ctx.close(); +} + +function roundRect (ctx, x, y, w, h, r) { + if (r < 0.1) { + ctx.rect(x, y, w, h); + return; + } else { + var rx = min(r, abs(w) * 0.5) * sign(w), + ry = min(r, abs(h) * 0.5) * sign(h); + + ctx.moveTo(x, y + ry); + ctx.lineTo(x, y + h - ry); + ctx.bezierCurveTo(x, y + h - ry * (1 - KAPPA90), x + rx * (1 - KAPPA90), y + h, x + rx, y + h); + ctx.lineTo(x + w - rx, y + h); + ctx.bezierCurveTo(x + w - rx * (1 - KAPPA90), y + h, x + w, y + h - ry * (1 - KAPPA90), x + w, y + h - ry); + ctx.lineTo(x + w, y + ry); + ctx.bezierCurveTo(x + w, y + ry * (1 - KAPPA90), x + w - rx * (1 - KAPPA90), y, x + w - rx, y); + ctx.lineTo(x + rx, y); + ctx.bezierCurveTo(x + rx * (1 - KAPPA90), y, x, y + ry * (1 - KAPPA90), x, y + ry); + ctx.close(); + } +} + + +module.exports = { + arc: arc, + ellipse: ellipse, + roundRect: roundRect, +}; From 32f92efa8ecb0debf8a16bfdb09ab54684bce8e9 Mon Sep 17 00:00:00 2001 From: 2youyouo2 <501251991@qq.com> Date: Mon, 15 Aug 2016 14:02:51 +0800 Subject: [PATCH 158/268] refine code --- cocos2d/core/graphics/graphics-webgl-cmd.js | 2 +- cocos2d/core/graphics/helper.js | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/graphics/graphics-webgl-cmd.js b/cocos2d/core/graphics/graphics-webgl-cmd.js index ed72a464e6..18c79e62f8 100644 --- a/cocos2d/core/graphics/graphics-webgl-cmd.js +++ b/cocos2d/core/graphics/graphics-webgl-cmd.js @@ -36,12 +36,12 @@ var Vec2 = cc.Vec2; var Js = cc.js; // Math -var PI = 3.14159265358979323846264338327; var INIT_VERTS_SIZE = 32; var VERTS_FLOAT_LENGTH = 2; var VERTS_BYTE_LENGTH = 8; +var PI = Math.PI; var min = Math.min; var max = Math.max; var ceil = Math.ceil; diff --git a/cocos2d/core/graphics/helper.js b/cocos2d/core/graphics/helper.js index a073e0348f..e21bfd6879 100644 --- a/cocos2d/core/graphics/helper.js +++ b/cocos2d/core/graphics/helper.js @@ -1,6 +1,5 @@ -var PI = 3.14159265358979323846264338327; - +var PI = Math.PI; var min = Math.min; var max = Math.max; var cos = Math.cos; From ebc0d2047c4949e81bd74be3d0f4b3b91faf3e23 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Mon, 15 Aug 2016 18:17:08 +0800 Subject: [PATCH 159/268] fix auto-release-utils error JSB not cc.Audio --- cocos2d/core/load-pipeline/auto-release-utils.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/load-pipeline/auto-release-utils.js b/cocos2d/core/load-pipeline/auto-release-utils.js index 60af8f90f7..3520b0fd8b 100644 --- a/cocos2d/core/load-pipeline/auto-release-utils.js +++ b/cocos2d/core/load-pipeline/auto-release-utils.js @@ -51,7 +51,7 @@ module.exports = { else if (assetOrUrl instanceof cc.Texture2D) { return assetOrUrl.url; } - else if (assetOrUrl instanceof cc.Audio) { + else if (!CC_JSB && assetOrUrl instanceof cc.Audio) { return assetOrUrl.src; } else if (CC_DEV) { From e8479d2509b9d3af3018b628349ccddbdf60182e Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Tue, 16 Aug 2016 01:30:50 +0800 Subject: [PATCH 160/268] fix eruda --- cocos2d/core/CCScene.js | 37 --------------------- cocos2d/core/components/CCWidget.js | 2 ++ cocos2d/deprecated.js | 50 +++++++++++++++++++++++++---- package.json | 1 - 4 files changed, 46 insertions(+), 44 deletions(-) diff --git a/cocos2d/core/CCScene.js b/cocos2d/core/CCScene.js index 7f2277d114..9f5d73efc2 100644 --- a/cocos2d/core/CCScene.js +++ b/cocos2d/core/CCScene.js @@ -117,40 +117,3 @@ cc.Scene = cc.Class({ }); module.exports = cc.Scene; - -if (CC_DEV) { - var ERR = '"%s" is not defined in the Scene, it is only defined in child nodes.'; - Object.defineProperties(cc.Scene.prototype, { - active: { - get: function () { - cc.error(ERR, 'active'); - return true; - }, - set: function () { - cc.error(ERR, 'active'); - } - }, - activeInHierarchy: { - get: function () { - cc.error(ERR, 'activeInHierarchy'); - return true; - }, - }, - getComponent: { - get: function () { - cc.error(ERR, 'getComponent'); - return function () { - return null; - }; - } - }, - addComponent: { - get: function () { - cc.error(ERR, 'addComponent'); - return function () { - return null; - }; - } - }, - }); -} \ No newline at end of file diff --git a/cocos2d/core/components/CCWidget.js b/cocos2d/core/components/CCWidget.js index 4c4c739bcf..4d076a1a19 100644 --- a/cocos2d/core/components/CCWidget.js +++ b/cocos2d/core/components/CCWidget.js @@ -38,8 +38,10 @@ var LEFT_RIGHT = LEFT | RIGHT; * !#en * Stores and manipulate the anchoring based on its parent. * Widget are used for GUI but can also be used for other things. + * Widget will adjust current node's position and size automatically, but the results after adjustment can not be obtained until the next frame. * !#zh * Widget 组件,用于设置和适配其相对于父节点的边距,Widget 通常被用于 UI 界面,也可以用于其他地方。 + * Widget 会自动调整当前节点的坐标和宽高,不过目前调整后的结果要到下一帧才能在脚本里获取到。 * @class Widget * @extends Component */ diff --git a/cocos2d/deprecated.js b/cocos2d/deprecated.js index b41737652f..c36d786f4f 100644 --- a/cocos2d/deprecated.js +++ b/cocos2d/deprecated.js @@ -1,11 +1,12 @@ -var js = cc.js; -// Label -if (cc.Label) { - js.obsolete(cc.Label.prototype, 'cc.Label.file', 'font', true); -} +if (CC_DEV && typeof eruda === 'undefined') { -if (CC_DEV) { + var js = cc.js; + + // Label + if (cc.Label) { + js.obsolete(cc.Label.prototype, 'cc.Label.file', 'font', true); + } var INFO = cc._LogInfos.deprecated; @@ -617,4 +618,41 @@ if (CC_DEV) { '*etTimeScale': 'timeScale', }); } + + // SCENE + + var ERR = '"%s" is not defined in the Scene, it is only defined in normal nodes.'; + Object.defineProperties(cc.Scene.prototype, { + active: { + get: function () { + cc.error(ERR, 'active'); + return true; + }, + set: function () { + cc.error(ERR, 'active'); + } + }, + activeInHierarchy: { + get: function () { + cc.error(ERR, 'activeInHierarchy'); + return true; + }, + }, + getComponent: { + get: function () { + cc.error(ERR, 'getComponent'); + return function () { + return null; + }; + } + }, + addComponent: { + get: function () { + cc.error(ERR, 'addComponent'); + return function () { + return null; + }; + } + }, + }); } diff --git a/package.json b/package.json index d4488879b5..09e8334775 100644 --- a/package.json +++ b/package.json @@ -28,7 +28,6 @@ "gulp-rename": "1.2.2", "gulp-shell": "0.4.1", "gulp-size": "2.1.0", - "async": "1.5.2", "gulp-sourcemaps": "1.5.2", "gulp-uglify": "1.5.3", "gulp-util": "3.0.6", From 0f97a7d476841048bbc421cff8842ea72864a9d3 Mon Sep 17 00:00:00 2001 From: Nan Wang Date: Tue, 16 Aug 2016 10:10:55 +0800 Subject: [PATCH 161/268] fix cc.game api typo --- cocos2d/core/CCGame.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index 2bbbafd0b8..46c36da7ac 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -36,12 +36,12 @@ var _isMusicPlaying = false; * !#zh 包含游戏主体信息并负责驱动游戏的游戏对象。 * @class Game */ -var game = /** @lends cc.game# */{ +var game = { /** * Event triggered when game hide to background. * Please note that this event is not 100% guaranteed to be fired. - * @property + * @property EVENT_HIDE * @type {String} * @example * cc.game.on(cc.game.EVENT_HIDE, function () { @@ -54,21 +54,21 @@ var game = /** @lends cc.game# */{ /** * Event triggered when game back to foreground * Please note that this event is not 100% guaranteed to be fired. - * @property + * @property EVENT_SHOW * @type {String} */ EVENT_SHOW: "game_on_show", /** * Event triggered after game inited, at this point all engine objects and game scripts are loaded - * @property + * @property EVENT_GAME_INITED * @type {String} */ EVENT_GAME_INITED: "game_inited", /** * Event triggered after renderer inited, at this point you will be able to use the render context - * @property + * @property EVENT_RENDERER_INITED * @type {String} */ EVENT_RENDERER_INITED: "renderer_inited", @@ -82,7 +82,7 @@ var game = /** @lends cc.game# */{ /** * Key of config - * @property + * @property CONFIG_KEY * @type {Object} */ CONFIG_KEY: { From ccf41f1fd1e97d0cd57bd824bc8a382ba445c8ae Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Tue, 16 Aug 2016 10:43:09 +0800 Subject: [PATCH 162/268] fix label rendering bug --- cocos2d/core/label/CCSGLabelCanvasRenderCmd.js | 2 +- cocos2d/core/label/CCSGLabelWebGLRenderCmd.js | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js b/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js index 9bcba7236f..370f696a09 100644 --- a/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js +++ b/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js @@ -471,7 +471,7 @@ } this._texture._textureLoaded = false; - this._texture.handleLoadedTexture(); + this._texture.handleLoadedTexture(true); }; proto._rebuildLabelSkin = function () { diff --git a/cocos2d/core/label/CCSGLabelWebGLRenderCmd.js b/cocos2d/core/label/CCSGLabelWebGLRenderCmd.js index a3f54123c0..541e2f3c11 100644 --- a/cocos2d/core/label/CCSGLabelWebGLRenderCmd.js +++ b/cocos2d/core/label/CCSGLabelWebGLRenderCmd.js @@ -105,7 +105,10 @@ proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset) { // Fill in vertex data with quad information (4 vertices for sprite) // Use 255 because color has been set when baking label - this._color[0] = ((this._displayedOpacity<<24) | (255<<16) | (255<<8) | 255); + // premultiplied alpha is used for labelTTF and system font + var opacity = this._displayedOpacity; + this._color[0] = ((opacity<<24) | (opacity<<16) | (opacity<<8) | opacity); + var z = node._vertexZ; var vertices = this._vertices; From c7a5aecaef7e4ff51b02724f28e12be189188904 Mon Sep 17 00:00:00 2001 From: Nan Wang Date: Tue, 16 Aug 2016 10:50:56 +0800 Subject: [PATCH 163/268] fix api doc --- cocos2d/core/components/CCVideoPlayer.js | 2 +- cocos2d/core/components/CCWidget.js | 2 +- cocos2d/core/event-manager/CCEventListener.js | 2 +- cocos2d/core/load-pipeline/CCLoader.js | 2 +- extensions/anysdk/jsb_anysdk.js | 2 +- extensions/spine/SkeletonData.js | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/cocos2d/core/components/CCVideoPlayer.js b/cocos2d/core/components/CCVideoPlayer.js index 332cad9338..837369f585 100644 --- a/cocos2d/core/components/CCVideoPlayer.js +++ b/cocos2d/core/components/CCVideoPlayer.js @@ -151,7 +151,7 @@ var VideoPlayer = cc.Class({ /** * !#en The current time when video start to play. * !#zh 从当前时间点开始播放视频 - * @property {Float} currentTime + * @property {Number} currentTime */ currentTime: { tooltip: 'i18n:COMPONENT.videoplayer.currentTime', diff --git a/cocos2d/core/components/CCWidget.js b/cocos2d/core/components/CCWidget.js index 6063ec7088..7d872e31d7 100644 --- a/cocos2d/core/components/CCWidget.js +++ b/cocos2d/core/components/CCWidget.js @@ -361,7 +361,7 @@ var Widget = cc.Class({ /** * !#en If true, verticalCenter is pixel margin, otherwise is percentage (0 - 1) margin. * !#zh 如果为 true,"verticalCenter" 将会以像素作为偏移值,反之为百分比(0 到 1)。 - * @property isAbsoluteHorizontalCenter + * @property isAbsoluteVerticalCenter * @type {Boolean} * @default true */ diff --git a/cocos2d/core/event-manager/CCEventListener.js b/cocos2d/core/event-manager/CCEventListener.js index 12cf653fe4..13092d1656 100644 --- a/cocos2d/core/event-manager/CCEventListener.js +++ b/cocos2d/core/event-manager/CCEventListener.js @@ -44,7 +44,7 @@ * @param {Number} type * @param {Number} listenerID * @param {Number} callback - * @return {EventListner} + * @return {EventListener} */ cc.EventListener = cc._Class.extend(/** @lends cc.EventListener# */{ _onEvent: null, // Event callback function diff --git a/cocos2d/core/load-pipeline/CCLoader.js b/cocos2d/core/load-pipeline/CCLoader.js index b3a6a7bc39..b8b6089648 100644 --- a/cocos2d/core/load-pipeline/CCLoader.js +++ b/cocos2d/core/load-pipeline/CCLoader.js @@ -457,7 +457,7 @@ JS.mixin(CCLoader.prototype, { /** * Returns an item in pipeline. * @method getItem - * @return {LoadingItem} + * @return {Object} */ getItem: function (url) { var item = this._items.map[url]; diff --git a/extensions/anysdk/jsb_anysdk.js b/extensions/anysdk/jsb_anysdk.js index dbb669b151..b6bbc8e366 100644 --- a/extensions/anysdk/jsb_anysdk.js +++ b/extensions/anysdk/jsb_anysdk.js @@ -459,7 +459,7 @@ anysdk.ProtocolUser = PluginProtocol.extend({ * !#zh * 登录接口 * @method login - * @param {String|Objcet} [...args] optional arguments + * @param {String|Object} [...args] optional arguments */ login: function(){ }, diff --git a/extensions/spine/SkeletonData.js b/extensions/spine/SkeletonData.js index 191de16798..37aba4712d 100644 --- a/extensions/spine/SkeletonData.js +++ b/extensions/spine/SkeletonData.js @@ -128,7 +128,7 @@ var SkeletonData = cc.Class({ // ------------------------------------------------- /** - * @property {Texture2D} textures + * @property {cc.Texture2D} textures */ textures: { default: [], From 52989d64e299b804bccabf5af6679bf9e09fab84 Mon Sep 17 00:00:00 2001 From: Nan Wang Date: Tue, 16 Aug 2016 11:00:41 +0800 Subject: [PATCH 164/268] update engine version --- CCBoot.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CCBoot.js b/CCBoot.js index 3f1f5dbadf..e5af2c5291 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -58,7 +58,7 @@ _p = null; * @name cc.ENGINE_VERSION */ var engineVersion; -engineVersion = '1.2.1-beta.3'; +engineVersion = '1.2.1-beta.4'; window['CocosEngine'] = cc.ENGINE_VERSION = engineVersion; /** From 912bd5651b59df4f38f2e31ddc70f95551b76969 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Tue, 16 Aug 2016 11:08:54 +0800 Subject: [PATCH 165/268] add min, max, step attribute --- cocos2d/core/platform/CCClass.js | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index cfc522cc92..ecf91a9247 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -1061,10 +1061,10 @@ function parseAttributes (attrs, className, propName) { } function parseSimpleAttr (attrName, expectType, attrCreater) { - var val = attrs[attrName]; - if (val) { + if (attrName in attrs) { + var val = attrs[attrName]; if (typeof val === expectType) { - if (typeof attrCreater === 'undefined') { + if ( !attrCreater ) { var attr = {}; attr[attrName] = val; result.push(attr); @@ -1074,7 +1074,7 @@ function parseAttributes (attrs, className, propName) { } } else if (CC_DEV) { - cc.error('The %s of %s.%s must be type %s', attrName, className, propName, expectType); + cc.error(ERR_Type, attrName, className, propName, expectType); } } } @@ -1128,13 +1128,16 @@ function parseAttributes (attrs, className, propName) { result.push({ min: range[0], max: range[1], step: range[2] }); } else if (CC_DEV) { - cc.error('The length of range array must be 2'); + cc.error('The length of range array must be equal or greater than 2'); } } else if (CC_DEV) { - cc.error(ERR_Type, '"range"', className + '.' + propName, 'array'); + cc.error(ERR_Type, 'range', className, propName, 'array'); } } + parseSimpleAttr('min', 'number'); + parseSimpleAttr('max', 'number'); + parseSimpleAttr('step', 'number'); return result; } From 7d2edd261387678770c9249be195b850de1b4ef2 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Mon, 15 Aug 2016 11:55:54 +0800 Subject: [PATCH 166/268] fix scrollview outOfBoundary issue --- cocos2d/core/components/CCScrollView.js | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/cocos2d/core/components/CCScrollView.js b/cocos2d/core/components/CCScrollView.js index 7080b0da58..49791dc45f 100644 --- a/cocos2d/core/components/CCScrollView.js +++ b/cocos2d/core/components/CCScrollView.js @@ -1324,8 +1324,20 @@ var ScrollView = cc.Class({ } }, + _adjustContentOutOfBoundary: function () { + this._outOfBoundaryAmountDirty = true; + if(this._isOutOfBoundary()) { + var outOfBoundary = this._getHowMuchOutOfBoundary(cc.p(0, 0)); + var newPosition = cc.pAdd(this.getContentPosition(), outOfBoundary); + if(this.content) { + this.content.setPosition(newPosition); + } + } + }, + start: function() { this._calculateBoundary(); + cc.director.once(cc.Director.EVENT_AFTER_VISIT, this._adjustContentOutOfBoundary, this); }, onDestroy: function() { From 6874db8130c292bca641a1cb7fdc3e38cf19787a Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Mon, 15 Aug 2016 12:07:36 +0800 Subject: [PATCH 167/268] add doc --- cocos2d/core/components/CCScrollView.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cocos2d/core/components/CCScrollView.js b/cocos2d/core/components/CCScrollView.js index 49791dc45f..762fc7f1db 100644 --- a/cocos2d/core/components/CCScrollView.js +++ b/cocos2d/core/components/CCScrollView.js @@ -1337,6 +1337,8 @@ var ScrollView = cc.Class({ start: function() { this._calculateBoundary(); + //Because widget component will adjust content position and scrollview position is correct after visit + //So this event could make sure the content is on the correct position after loading. cc.director.once(cc.Director.EVENT_AFTER_VISIT, this._adjustContentOutOfBoundary, this); }, From 6e13b1b6043666f1ec53c7f30102f6eacc6f6ed3 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Tue, 16 Aug 2016 14:47:11 +0800 Subject: [PATCH 168/268] fix currentTime, add duration is isPlaying APIs --- cocos2d/core/components/CCVideoPlayer.js | 36 +++++++++++++++++---- cocos2d/core/videoplayer/CCSGVideoPlayer.js | 12 +++++++ 2 files changed, 41 insertions(+), 7 deletions(-) diff --git a/cocos2d/core/components/CCVideoPlayer.js b/cocos2d/core/components/CCVideoPlayer.js index 837369f585..f7d78ff1bc 100644 --- a/cocos2d/core/components/CCVideoPlayer.js +++ b/cocos2d/core/components/CCVideoPlayer.js @@ -147,21 +147,23 @@ var VideoPlayer = cc.Class({ url: cc.RawAsset }, - _time: 0, /** - * !#en The current time when video start to play. - * !#zh 从当前时间点开始播放视频 + * !#en The current playback time of the now playing item in seconds, you could also change the start playback time. + * !#zh 指定视频从什么时间点开始播放,单位是秒,也可以用来获取当前视频播放的时间进度。 * @property {Number} currentTime */ currentTime: { tooltip: 'i18n:COMPONENT.videoplayer.currentTime', type: cc.Float, set: function ( time ) { - this._time = time; - this._sgNode.seekTo(time); + if(this._sgNode) { + this._sgNode.seekTo(time); + } }, get: function () { - return this._time; + if(this._sgNode) { + return this._sgNode.currentTime(); + } } }, @@ -210,7 +212,6 @@ var VideoPlayer = cc.Class({ }, onLoad: function() { - if(CC_JSB) { if (cc.sys.os === cc.sys.OS_OSX || cc.sys.os === cc.sys.OS_WINDOWS) { this.enabled = false; @@ -318,6 +319,27 @@ var VideoPlayer = cc.Class({ } }, + /** + * !#en Gets the duration of the video + * !#zh 获取视频文件的播放总时长 + */ + getDuration: function() { + if(this._sgNode) { + this._sgNode.duration(); + } + }, + + /** + * !#en Determine whether video is playing or not. + * !#zh 判断当前视频是否处于播放状态 + */ + isPlaying: function() { + if(this._sgNode) { + return this._sgNode.isPlaying(); + } + return false; + } + }); cc.VideoPlayer = module.exports = VideoPlayer; diff --git a/cocos2d/core/videoplayer/CCSGVideoPlayer.js b/cocos2d/core/videoplayer/CCSGVideoPlayer.js index 9ec0d6287f..ed81f7bc2e 100644 --- a/cocos2d/core/videoplayer/CCSGVideoPlayer.js +++ b/cocos2d/core/videoplayer/CCSGVideoPlayer.js @@ -73,6 +73,10 @@ _ccsg.VideoPlayer = _ccsg.Node.extend(/** @lends _ccsg.VideoPlayer# */{ return this._renderCmd.isPlaying(); }, + duration: function () { + return this._renderCmd.duration(); + }, + createDomElementIfNeeded: function () { if (!this._renderCmd._video) { this._renderCmd.createDom(); @@ -501,6 +505,7 @@ _ccsg.VideoPlayer.EventType = { }; proto.isPlaying = function () { + var video = this._video; if(_ccsg.VideoPlayer._polyfill.autoplayAfterOperation && this._playing){ setTimeout(function(){ video.play(); @@ -509,4 +514,11 @@ _ccsg.VideoPlayer.EventType = { return this._playing; }; + proto.duration = function () { + var video = this._video; + if(!video) return; + + return video.duration; + }; + })(_ccsg.VideoPlayer._polyfill); From 5e5b143308c6700090f274a2e305a0a891e0bf69 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Tue, 16 Aug 2016 15:24:19 +0800 Subject: [PATCH 169/268] fix edge cases when using outline --- cocos2d/core/label/CCSGLabelCanvasRenderCmd.js | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js b/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js index 370f696a09..c96985fd4a 100644 --- a/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js +++ b/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js @@ -117,10 +117,11 @@ maxWidth -= 2 * this._getMargin(); var wrappedWords = []; //fast return if strArr is empty - if(strArr.length === 0) { + if(strArr.length === 0 || maxWidth < 0) { wrappedWords.push(''); return wrappedWords; } + var text = strArr; var allWidth = ctx.measureText(text).width; while (allWidth > maxWidth && text.length > 1) { @@ -222,6 +223,11 @@ var canvasWidthNoMargin = this._canvasSize.width - 2 * this._getMargin(); var canvasHeightNoMargin = this._canvasSize.height - 2 * this._getMargin(); + if(canvasWidthNoMargin < 0 || canvasHeightNoMargin < 0) { + fontDesc = '1px ' + fontFamily; + this._labelContext.font = fontDesc; + return fontDesc; + } totalHeight = canvasHeightNoMargin + 1; maxLength = canvasWidthNoMargin + 1; var actualFontSize = this._drawFontsize + 1; @@ -251,7 +257,6 @@ textFragment = this._fragmentText(paragraphedStrings[i], canvasWidthNoMargin, this._labelContext); - var isBiggerSize = false; while(j < textFragment.length) { var measureWidth = this._labelContext.measureText(textFragment[j]).width; maxLength = measureWidth; From 5a5eda023dcc2a69583e731d67b89b0f4503c1d7 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Tue, 16 Aug 2016 15:36:16 +0800 Subject: [PATCH 170/268] improve videoPlayer --- cocos2d/core/components/CCVideoPlayer.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cocos2d/core/components/CCVideoPlayer.js b/cocos2d/core/components/CCVideoPlayer.js index f7d78ff1bc..e7044779d3 100644 --- a/cocos2d/core/components/CCVideoPlayer.js +++ b/cocos2d/core/components/CCVideoPlayer.js @@ -164,6 +164,7 @@ var VideoPlayer = cc.Class({ if(this._sgNode) { return this._sgNode.currentTime(); } + return -1; } }, @@ -327,6 +328,7 @@ var VideoPlayer = cc.Class({ if(this._sgNode) { this._sgNode.duration(); } + return -1; }, /** From f6ec41cce48f8fcba398c3086b3f9f2011cba1a0 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Tue, 16 Aug 2016 15:47:46 +0800 Subject: [PATCH 171/268] fix currentTime and duration --- cocos2d/core/components/CCVideoPlayer.js | 2 +- cocos2d/core/videoplayer/CCSGVideoPlayer.js | 13 ++++++++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/components/CCVideoPlayer.js b/cocos2d/core/components/CCVideoPlayer.js index e7044779d3..1de87bf61a 100644 --- a/cocos2d/core/components/CCVideoPlayer.js +++ b/cocos2d/core/components/CCVideoPlayer.js @@ -326,7 +326,7 @@ var VideoPlayer = cc.Class({ */ getDuration: function() { if(this._sgNode) { - this._sgNode.duration(); + return this._sgNode.duration(); } return -1; }, diff --git a/cocos2d/core/videoplayer/CCSGVideoPlayer.js b/cocos2d/core/videoplayer/CCSGVideoPlayer.js index ed81f7bc2e..64dad7323e 100644 --- a/cocos2d/core/videoplayer/CCSGVideoPlayer.js +++ b/cocos2d/core/videoplayer/CCSGVideoPlayer.js @@ -77,6 +77,10 @@ _ccsg.VideoPlayer = _ccsg.Node.extend(/** @lends _ccsg.VideoPlayer# */{ return this._renderCmd.duration(); }, + currentTime: function() { + return this._renderCmd.currentTime(); + }, + createDomElementIfNeeded: function () { if (!this._renderCmd._video) { this._renderCmd.createDom(); @@ -516,9 +520,16 @@ _ccsg.VideoPlayer.EventType = { proto.duration = function () { var video = this._video; - if(!video) return; + if(!video) return -1; return video.duration; }; + proto.currentTime = function () { + var video = this._video; + if(!video) return -1; + + return video.currentTime; + }; + })(_ccsg.VideoPlayer._polyfill); From 2e319a3881bda1ae8cd48b74b2016090cb8922fc Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Tue, 16 Aug 2016 18:03:02 +0800 Subject: [PATCH 172/268] only register event when content is not null --- cocos2d/core/components/CCScrollView.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/components/CCScrollView.js b/cocos2d/core/components/CCScrollView.js index 762fc7f1db..9a209c87d2 100644 --- a/cocos2d/core/components/CCScrollView.js +++ b/cocos2d/core/components/CCScrollView.js @@ -1339,7 +1339,9 @@ var ScrollView = cc.Class({ this._calculateBoundary(); //Because widget component will adjust content position and scrollview position is correct after visit //So this event could make sure the content is on the correct position after loading. - cc.director.once(cc.Director.EVENT_AFTER_VISIT, this._adjustContentOutOfBoundary, this); + if(this.content) { + cc.director.once(cc.Director.EVENT_AFTER_VISIT, this._adjustContentOutOfBoundary, this); + } }, onDestroy: function() { From 722f1a0574137af90d32f052b73a94f06063e2ae Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 18 Aug 2016 16:06:32 +0800 Subject: [PATCH 173/268] Fix Label render command break BMFont batching --- cocos2d/core/label/CCSGLabel.js | 3 +++ cocos2d/core/label/CCSGLabelWebGLRenderCmd.js | 9 ++++++++- cocos2d/core/textures/CCTexture2D.js | 1 - 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/label/CCSGLabel.js b/cocos2d/core/label/CCSGLabel.js index 34c6ca0545..9140092841 100644 --- a/cocos2d/core/label/CCSGLabel.js +++ b/cocos2d/core/label/CCSGLabel.js @@ -359,6 +359,7 @@ _ccsg.Label = _ccsg.Node.extend({ this._fontHandle = fontHandle; this._labelType = _ccsg.Label.Type.SystemFont; this._blendFunc = cc.BlendFunc._alphaPremultiplied(); + this._renderCmd._needDraw = true; this._notifyLabelSkinDirty(); this.emit('load'); return; @@ -367,11 +368,13 @@ _ccsg.Label = _ccsg.Node.extend({ if (extName === ".ttf") { this._labelType = _ccsg.Label.Type.TTF; this._blendFunc = cc.BlendFunc._alphaPremultiplied(); + this._renderCmd._needDraw = true; this._fontHandle = this._loadTTFFont(fontHandle); } else if (extName === ".fnt") { //todo add bmfont here this._labelType = _ccsg.Label.Type.BMFont; this._blendFunc = cc.BlendFunc._alphaNonPremultiplied(); + this._renderCmd._needDraw = false; this._initBMFontWithString(this._string, fontHandle, textureUrl); } this._notifyLabelSkinDirty(); diff --git a/cocos2d/core/label/CCSGLabelWebGLRenderCmd.js b/cocos2d/core/label/CCSGLabelWebGLRenderCmd.js index 541e2f3c11..5247004163 100644 --- a/cocos2d/core/label/CCSGLabelWebGLRenderCmd.js +++ b/cocos2d/core/label/CCSGLabelWebGLRenderCmd.js @@ -69,7 +69,8 @@ proto._updateDisplayOpacity = function (parentOpacity) { proto.transform = function (parentCmd, recursive) { this.originTransform(parentCmd, recursive); - var lx = 0, rx = this._labelCanvas.width, + var node = this._node, + lx = 0, rx = this._labelCanvas.width, by = 0, ty = this._labelCanvas.height, wt = this._worldTransform; @@ -83,6 +84,12 @@ proto.transform = function (parentCmd, recursive) { vert[3].x = rx * wt.a + by * wt.c + wt.tx; // br vert[3].y = rx * wt.b + by * wt.d + wt.ty; + if (!node._string || (node._labelType !== _ccsg.Label.Type.TTF && + node._labelType !== _ccsg.Label.Type.SystemFont)) { + // No culling for bmfont + return; + } + var rect = cc.visibleRect, vl = rect.left.x, vr = rect.right.x, vt = rect.top.y, vb = rect.bottom.y; if (((vert[0].x-vl) & (vert[1].x-vl) & (vert[2].x-vl) & (vert[3].x-vl)) >> 31 || // All outside left diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index 3f6a17b485..abafe8d952 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -96,7 +96,6 @@ var Texture2D = cc.Class(/** @lends cc.Texture2D# */{ this._isGray = false; } else if (cc._renderType === game.RENDER_TYPE_WEBGL) { - this._hasPremultipliedAlpha = false; this._pixelFormat = Texture2D.defaultPixelFormat; this._hasPremultipliedAlpha = false; this._hasMipmaps = false; From 5adb19ca26794e72ba2eac958cca7c4d0dab5c56 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 18 Aug 2016 18:26:01 +0800 Subject: [PATCH 174/268] Update audioEngine --- cocos2d/audio/CCAudio.js | 869 +++++------------- cocos2d/audio/CCAudioEngine.js | 217 +++++ cocos2d/core/CCGame.js | 4 +- cocos2d/core/components/CCAudioSource.js | 68 +- .../core/load-pipeline/audio-downloader.js | 114 +-- modules.json | 2 +- 6 files changed, 510 insertions(+), 764 deletions(-) create mode 100644 cocos2d/audio/CCAudioEngine.js diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index 9eff41ffa2..0601e7f7ae 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -24,42 +24,142 @@ THE SOFTWARE. ****************************************************************************/ -var JS = require('../core/platform/js'); - -/** - * Encapsulate DOM and webAudio - */ -cc.Audio = function (url) { - this.src = url; +var Audio = function () { + this._audioType = Audio.Type.UNKNOWN; this._element = null; - this._AUDIO_TYPE = 'AUDIO'; + + this._eventList = {}; + this._state = Audio.State.ERROR; }; -cc.Audio.touchPlayList = [ - //{ offset: 0, audio: audio } -]; - -cc.Audio.bindTouch = false; -cc.Audio.touchStart = function () { - var list = cc.Audio.touchPlayList; - var item = null; - while (item = list.pop()) { - item.audio.loop = !!item.loop; - item.audio.play(item.offset); - } +Audio.Type = { + DOM: 'AUDIO', + WEBAUDIO: 'WEBAUDIO', + UNKNOWN: 'UNKNOWN' }; -cc.Audio.WebAudio = function (buffer) { - this.buffer = buffer; - this.context = cc.sys.__audioSupport.context; +Audio.State = { + ERROR : -1, + INITIALZING: 0, + PLAYING: 1, + PAUSED: 2 +}; - var volume = this.context['createGain'](); - volume['gain'].value = 1; - volume['connect'](this.context['destination']); - this._volume = volume; +(function (proto) { + proto.on = function (event, callback) { + var list = this._eventList[event]; + if (!list) { + list = this._eventList[event] = []; + } + list.push(callback); + }; + proto.emit = function (event) { + var list = this._eventList[event]; + if (!list) return; + for (var i=0; i Audio duration - return this.context.currentTime - this._startTime > this.buffer.duration; - }, + return this._context.currentTime - this._startTime > this._buffer.duration; + }); - get loop () { return this._loop; }, - set loop (bool) { return this._loop = bool; }, + proto.__defineGetter__('loop', function () { return this._loop; }); + proto.__defineSetter__('loop', function (bool) { + if (this._currentSource) + this._currentSource.loop = bool; - get volume () { return this._volume['gain'].value; }, - set volume (num) { return this._volume['gain'].value = num; }, + return this._loop = bool; + }); - get currentTime () { return this.playedLength; }, - set currentTime (num) { return this.playedLength = num; }, + proto.__defineGetter__('volume', function () { return this._volume['gain'].value; }); + proto.__defineSetter__('volume', function (num) { return this._volume['gain'].value = num; }); - play: function (offset) { - - // If repeat play, you need to stop before an audio - if (this._currentSource && !this.paused) { - this._currentSource.stop(0); - this.playedLength = 0; + proto.__defineGetter__('currentTime', function () { + if (this.paused) { + return this.playedLength; } - - var audio = this.context["createBufferSource"](); - audio.buffer = this.buffer; - audio["connect"](this._volume); - audio.loop = this._loop; - - this._startTime = this.context.currentTime; - offset = offset || this.playedLength; - - var duration = this.buffer.duration; - if (!this._loop) { - if (audio.start) - audio.start(0, offset, duration - offset); - else if (audio["notoGrainOn"]) - audio["noteGrainOn"](0, offset, duration - offset); - else - audio["noteOn"](0, offset, duration - offset); - } else { - if (audio.start) - audio.start(0); - else if (audio["notoGrainOn"]) - audio["noteGrainOn"](0); - else - audio["noteOn"](0); - } - - this._currentSource = audio; - - // If the current audio context time stamp is 0 - // There may be a need to touch events before you can actually start playing audio - if (this.context.currentTime === 0) { - var self = this; - clearTimeout(this._currextTimer); - this._currextTimer = setTimeout(function () { - if (self.context.currentTime === 0) { - cc.Audio.touchPlayList.push({ - offset: offset, - audio: self - }); - } - }, 10); - } - }, - pause: function () { // Record the time the current has been played - this.playedLength = this.context.currentTime - this._startTime; + this.playedLength = this._context.currentTime - this._startTime; // If more than the duration of the audio, Need to take the remainder - this.playedLength %= this.buffer.duration; - var audio = this._currentSource; - this._currentSource = null; - this._startTime = -1; - if (audio) - audio.stop(0); - } -}; - -JS.mixin(cc.Audio.prototype, { - setBuffer: function (buffer) { - this._AUDIO_TYPE = "WEBAUDIO"; - this._element = new cc.Audio.WebAudio(buffer); - }, - - setElement: function (element) { - this._AUDIO_TYPE = "AUDIO"; - this._element = element; - - // Prevent partial browser from playing after the end does not reset the paused tag - element.addEventListener('ended', function () { - if (!element.loop) { - element.paused = true; - } - }); - }, - - play: function (offset, loop) { - if (!this._element) return; - this._element.loop = loop; - this._element.play(); - - if (this._AUDIO_TYPE === 'AUDIO' && this._element.paused) { - this.stop(); - cc.Audio.touchPlayList.push({ loop: loop, offset: offset, audio: this._element }); - } - - 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); - } - }, - - getPlaying: function () { - if (!this._element) return true; - return !this._element.paused; - }, - - stop: function () { - if (!this._element) return; - this._element.pause(); - try{ - this._element.currentTime = 0; - } catch (err) {} - }, - - pause: function () { - if (!this._element) return; - this._element.pause(); - }, - - resume: function () { - if (!this._element) return; - this._element.play(); - }, - - setVolume: function (volume) { - if (!this._element) return; - this._element.volume = volume; - }, - - getVolume: function () { - if (!this._element) return; - return this._element.volume; - }, - - cloneNode: function () { - var audio = new cc.Audio(this.src); - if (this._AUDIO_TYPE === "AUDIO") { - var elem = document.createElement("audio"); - var sources = elem.getElementsByTagName('source'); - for (var i=0; i - * 主要用来播放背景音乐和音效,背景音乐同一时间只能播放一个,而音效则可以同时播放多个。
- * 注意:
- * 在 Android 系统浏览器上,不同浏览器,不同版本的效果不尽相同。
- * 比如说:大多数浏览器都需要用户物理交互才可以开始播放音效,有一些不支持 WebAudio,
- * 有一些不支持多音轨播放。总之如果对音乐依赖比较强,请做尽可能多的测试。 - * @class audioEngine - * @static - */ - cc.audioEngine = { - _currMusic: null, - _musicVolume: 1, - - features: polyfill, - - /** - * !#en Play music. - * !#zh - * 播放指定音乐,并可以设置是否循环播放。
- * 注意:音乐播放接口不支持多音轨,同一时间只能播放一个音乐。 - * @method playMusic - * @param {String} url - The path of the music file without filename extension. - * @param {Boolean} loop - Whether the music loop or not. - * @example - * //example - * cc.audioEngine.playMusic(path, false); - */ - playMusic: function(url, loop){ - var bgMusic = this._currMusic; - if (bgMusic && bgMusic.getPlaying()) { - bgMusic.stop(); - } - var item = cc.loader.getItem(url); - var audio = item && item.audio ? item.audio : null; - if (!audio) { - var self = this; - cc.loader.load(url, function (error) { - if (!error) { - var item = cc.loader.getItem(url); - var audio = item && item.audio ? item.audio : null; - audio.play(0, loop || false); - audio.setVolume(self._musicVolume); - self._currMusic = audio; - } - }); - item = cc.loader.getItem(url); - return item && item.audio ? item.audio : null; - } - audio.play(0, loop); - audio.setVolume(this._musicVolume); - - this._currMusic = audio; - return audio; - }, - - /** - * !#en Stop playing music. - * !#zh 停止当前音乐。 - * @method stopMusic - * @param {Boolean} [releaseData] - If release the music data or not.As default value is false. - * @example - * //example - * cc.audioEngine.stopMusic(); - */ - stopMusic: function(releaseData){ - var audio = this._currMusic; - if (audio) { - audio.stop(); - if (releaseData) - cc.loader.release(audio.src); - } - }, - - /** - * !#en Pause playing music. - * !#zh 暂停正在播放音乐。 - * @method pauseMusic - * @example - * //example - * cc.audioEngine.pauseMusic(); - */ - pauseMusic: function(){ - var audio = this._currMusic; - if (audio) - audio.pause(); - }, - - /** - * !#en Resume playing music. - * !#zh 恢复音乐播放。 - * @method resumeMusic - * @example - * //example - * cc.audioEngine.resumeMusic(); - */ - resumeMusic: function(){ - var audio = this._currMusic; - if (audio) - audio.resume(); - }, - - /** - * !#en Rewind playing music. - * !#zh 从头开始重新播放当前音乐。 - * @method rewindMusic - * @example - * //example - * cc.audioEngine.rewindMusic(); - */ - rewindMusic: function(){ - var audio = this._currMusic; - if (audio) { - audio.stop(); - audio.play(); - } - }, - - /** - * !#en The volume of the music max value is 1.0,the min value is 0.0 . - * !#zh 获取音量(0.0 ~ 1.0)。 - * @method getMusicVolume - * @return {Number} - * @example - * //example - * var volume = cc.audioEngine.getMusicVolume(); - */ - getMusicVolume: function(){ - return this._musicVolume; - }, - - /** - * !#en Set the volume of music. - * !#zh 设置音量(0.0 ~ 1.0)。 - * @method setMusicVolume - * @param {Number} volume Volume must be in 0.0~1.0 . - * @example - * //example - * cc.audioEngine.setMusicVolume(0.5); - */ - setMusicVolume: function(volume){ - volume = volume - 0; - if (isNaN(volume)) volume = 1; - if (volume > 1) volume = 1; - if (volume < 0) volume = 0; - - this._musicVolume = volume; - var audio = this._currMusic; - if (audio) { - audio.setVolume(volume); - } - }, - - /** - * !#en Whether the music is playing. - * !#zh 音乐是否正在播放。 - * @method isMusicPlaying - * @return {Boolean} If is playing return true,or return false. - * @example - * //example - * if (cc.audioEngine.isMusicPlaying()) { - * cc.log("music is playing"); - * } - * else { - * cc.log("music is not playing"); - * } - */ - isMusicPlaying: function(){ - var audio = this._currMusic; - if (audio) { - return audio.getPlaying(); - } else { - return false; - } - }, - - _audioPool: {}, - _maxAudioInstance: 10, - _effectVolume: 1, - /** - * !#en Play sound effect. - * !#zh - * 播放指定音效,并可以设置是否循环播放。
- * 注意:在部分不支持多音轨的浏览器上,这个接口会失效,请使用 playMusic - * @method playEffect - * @param {String} url The path of the sound effect with filename extension. - * @param {Boolean} loop Whether to loop the effect playing, default value is false - * @param {Boolean} volume - * @return {Number|null} the audio id - * @example - * //example - * var soundId = cc.audioEngine.playEffect(path); - */ - playEffect: function(url, loop, volume){ - volume = volume === undefined ? this._effectVolume : volume; - - // 如果只能够播放一个音频,则优先保证背景音乐 - if (SWB && this._currMusic && this._currMusic.getPlaying()) { - cc.log('Browser is only allowed to play one audio'); - return null; - } - - var effectList = this._audioPool[url]; - if (!effectList) { - effectList = this._audioPool[url] = []; - } - - var i; - for(i = 0; i < effectList.length; i++){ - if (!effectList[i].getPlaying()) { - break; - } - } - - if (!SWA && i > this._maxAudioInstance) { - var first = effectList.shift(); - first.stop(); - effectList.push(first); - i = effectList.length - 1; - // cc.log("Error: %s greater than %d", url, this._maxAudioInstance); - } - - var audio; - if (effectList[i]) { - audio = effectList[i]; - audio.setVolume(volume); - audio.play(0, loop || false); - return audio; - } - - var item = cc.loader.getItem(url); - audio = item && item.audio ? item.audio : null; - if (SWA && audio && audio._AUDIO_TYPE != "WEBAUDIO") { - //delete cc.loader.getRes(url); - cc.loader.release(url); - audio = null; - } - - if (!audio) { - // Force using webaudio for effects - cc.Audio.useWebAudio = true; - audio = new cc.Audio(url); - cc.loader.load(url, function (error, url) { - if (error) return; - var item = cc.loader.getItem(url); - var loadAudio = item && item.audio ? item.audio : null; - - if (loadAudio._AUDIO_TYPE === 'WEBAUDIO') - audio.setBuffer(loadAudio._element.buffer); - else - audio.setElement(loadAudio._element); - - audio.setVolume(volume); - audio.play(0, loop || false); - effectList.push(audio); - }); - cc.Audio.useWebAudio = false; - return audio; - } - - audio = audio.cloneNode(); - audio.setVolume(volume); - audio.play(0, loop || false); - effectList.push(audio); - - return audio; - }, - - /** - * !#en Set the volume of sound effects. - * !#zh 设置音效音量(0.0 ~ 1.0)。 - * @method setEffectsVolume - * @param {Number} volume Volume must be in 0.0~1.0 . - * @example - * //example - * cc.audioEngine.setEffectsVolume(0.5); - */ - setEffectsVolume: function(volume){ - volume = 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){ - var audioList = audioPool[p]; - if(Array.isArray(audioList)) - for(var i=0; i list.length) { + audio = new Audio(); + id2audio[id] = audio; + } else { + var oldId = list.shift(); + audio = id2audio[id] = id2audio[oldId]; + delete id2audio[oldId]; + } + audio.instanceId = id; + list.push(id); + + return audio; +}; + +var getAudioFromId = function (id) { + return id2audio[id]; +}; + +var audioEngine = { + + AudioState: Audio.State, + + _maxWebAudioSize: 30720000, // 300kb * 1024 * 100 + _maxAudioInstance: 24, + + play2d: function (filePath, loop, volume/*, profile*/) { + var item = cc.loader.getItem(filePath); + // todo 资源不存在 + var audio = getAudioFromPath(filePath); + audio.mount(item.element || item.buffer); + audio.setLoop(loop || false); + audio.setVolume(volume || 1); + audio.play(); + return audio.instanceId; + }, + setLoop: function (audioID, loop) { + var audio = getAudioFromId(audioID); + if (!audio || !audio.setLoop) + return loop; + audio.setLoop(loop); + return loop; + }, + isLoop: function (audioID) { + var audio = getAudioFromId(audioID); + if (!audio || !audio.isLoop) + return false; + return audio.isLoop(); + }, + setVolume: function (audioID, volume) { + var audio = getAudioFromId(audioID); + if (!audio || !audio.setVolume) + return volume; + audio.setVolume(volume); + return volume; + }, + getVolume: function (audioID) { + var audio = getAudioFromId(audioID); + if (!audio || !audio.getVolume) + return 1; + return audio.getVolume(); + }, + setCurrentTime: function (audioID, sec) { + var audio = getAudioFromId(audioID); + if (!audio || !audio.setCurrentTime) + return sec; + audio.setCurrentTime(sec); + return sec; + }, + getCurrentTime: function (audioID) { + var audio = getAudioFromId(audioID); + if (!audio || !audio.getCurrentTime) + return 0; + return audio.getCurrentTime(); + }, + + getDuration: function (audioID) { + var audio = getAudioFromId(audioID); + if (!audio || !audio.getDuration) + return 0; + return audio.getDuration(); + }, + getState: function (audioID) { + var audio = getAudioFromId(audioID); + if (!audio || !audio.getState) + return 0; + return audio.getState(); + }, + + setFinishCallback: function (audioID, callback) { + }, + + pause: function (audioID) { + var audio = getAudioFromId(audioID); + if (!audio || !audio.pause) + return false; + audio.pause(); + return true; + }, + _pauseIDCache: [], + pauseAll: function () { + for (var id in id2audio) { + var audio = id2audio[id]; + var state = audio.getState(); + if (state === Audio.State.PLAYING) { + this._pauseIDCache.push(id); + audio.pause(); + } + } + }, + resume: function (audioID) { + var audio = getAudioFromId(audioID); + if (!audio || !audio.resume) + return false; + if (audio.getCurrentTime() === 0) { + audio.play(); + } else { + audio.resume(); + } + }, + resumeAll: function () { + while (this._pauseIDCache.length > 0) { + var id = this._pauseIDCache.pop(); + var audio = getAudioFromId(id); + if (audio && audio.resume) + audio.resume(); + } + }, + stop: function (audioID) { + var audio = getAudioFromId(audioID); + if (!audio || !audio.stop) + return false; + audio.stop(); + }, + stopAll: function () { + for (var id in id2audio) { + var audio = id2audio[id]; + if (audio && audio.stop) { + audio.stop(); + } + } + }, + + setMaxAudioInstance: function (num) { + return this._maxAudioInstance = num; + }, + getMaxAudioInstance: function () { + return this._maxAudioInstance; + }, + uncache: function (filePath) { + var list = url2id[filePath]; + if (!list) return; + while (list.length > 0) { + var id = list.pop(); + var audio = id2audio[id]; + if (audio) { + audio.stop(); + delete id2audio[id]; + } + } + }, + uncacheAll: function () { + this.stopAll(); + id2audio = {}; + url2id = {}; + }, + + // getProfile + // preload + + // web 独占接口 + // 设置一个大小,单位为kb,超过这个大小则直接解析成 dom 节点 + // 因为 webAudio 占用内存过多,所以让用户自己手动取舍 + setMaxWebAudioSize: function (kb) { + this._maxWebAudioSize = kb * 1024; + } +}; + +module.exports = audioEngine; \ No newline at end of file diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index e7c7dad0d2..1fb87eb3eb 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -249,7 +249,7 @@ var game = /** @lends cc.game# */{ if (this._paused) return; this._paused = true; // Pause audio engine - cc.audioEngine && cc.audioEngine._pausePlaying(); + cc.audioEngine && cc.audioEngine.pauseAll(); // Pause main loop if (this._intervalId) window.cancelAnimationFrame(this._intervalId); @@ -265,7 +265,7 @@ var game = /** @lends cc.game# */{ if (!this._paused) return; this._paused = false; // Resume audio engine - cc.audioEngine && cc.audioEngine._resumePlaying(); + cc.audioEngine && cc.audioEngine.resumeAll(); // Resume main loop this._runMainLoop(); }, diff --git a/cocos2d/core/components/CCAudioSource.js b/cocos2d/core/components/CCAudioSource.js index adb99c13a7..a7243d829e 100644 --- a/cocos2d/core/components/CCAudioSource.js +++ b/cocos2d/core/components/CCAudioSource.js @@ -30,9 +30,8 @@ * @extends Component */ -// todo jsb 中无法针对单独的音效对象进行设置(如音量大小等) - -var audioEngine = cc.audioEngine; +var audioEngine = require('../../audio/CCAudioEngine'); +cc.audioEngine = audioEngine; var AudioSource = cc.Class({ name: 'cc.AudioSource', @@ -44,7 +43,7 @@ var AudioSource = cc.Class({ }, ctor: function () { - this.audio = null; + this.audioID = 0; }, properties: { @@ -70,7 +69,9 @@ var AudioSource = cc.Class({ */ isPlaying: { get: function () { - return (!cc.sys.isNative && this.audio && this.audio.getPlaying()); + if (!this.audioID) return false; + var state = audioEngine.getState(this.audioID); + return state === audioEngine.AudioState.PLAYING; }, visible: false }, @@ -107,14 +108,9 @@ var AudioSource = cc.Class({ }, set: function (value) { this._volume = value; - if (this.audio) { - if (cc.sys.isNative) { - cc.audioEngine.setEffectsVolume(value); - } - else { - this.audio.setVolume(value); - } - } + if (!this.audioID) return value; + audioEngine.setVolume(value); + return value; }, tooltip: 'i18n:COMPONENT.audio.volume' }, @@ -132,21 +128,9 @@ var AudioSource = cc.Class({ }, set: function (value) { this._mute = value; - if (this.audio) { - if (this._mute) { - if (CC_JSB) { - cc.audioEngine.setEffectsVolume(0); - } else { - this.audio.setVolume(0); - } - } else { - if (CC_JSB) { - cc.audioEngine.setEffectsVolume(this._volume); - } else { - this.audio.setVolume(this._volume); - } - } - } + if (!this.audioID) return value; + audioEngine.setVolume(0); + return value; }, animatable: false, tooltip: 'i18n:COMPONENT.audio.mute', @@ -165,7 +149,9 @@ var AudioSource = cc.Class({ }, set: function (value) { this._loop = value; - if (this.audio) this.audio.loop = this._loop; + if (!this.audioID) return value; + audioEngine.setLoop(value); + return value; }, animatable: false, tooltip: 'i18n:COMPONENT.audio.loop' @@ -207,11 +193,7 @@ var AudioSource = cc.Class({ play: function () { if ( this._clip ) { var volume = this._mute ? 0 : this._volume; - this.audio = audioEngine.playEffect(this._clip, this._loop, volume); - - if (CC_JSB) { - cc.audioEngine.setEffectsVolume(volume); - } + this.audioID = audioEngine.play2d(this._clip, this._loop, volume); } }, @@ -221,7 +203,8 @@ var AudioSource = cc.Class({ * @method stop */ stop: function () { - if ( this.audio ) cc.audioEngine.stopEffect(this.audio); + if (!this.audioID) return false; + audioEngine.stop(this.audioID); }, /** @@ -230,7 +213,8 @@ var AudioSource = cc.Class({ * @method pause */ pause: function () { - if ( this.audio ) cc.audioEngine.pauseEffect(this.audio); + if (!this.audioID) return false; + audioEngine.pause(this.audioID); }, /** @@ -239,7 +223,8 @@ var AudioSource = cc.Class({ * @method resume */ resume: function () { - if ( this.audio ) cc.audioEngine.resumeEffect(this.audio); + if (!this.audioID) return false; + audioEngine.resume(this.audioID); }, /** @@ -248,11 +233,10 @@ var AudioSource = cc.Class({ * @method rewind */ rewind: function(){ - if ( this.audio ) { - this.stop(); - this.play(); - } - }, + if (!this.audioID) return false; + this.stop(); + this.play(); + } }); diff --git a/cocos2d/core/load-pipeline/audio-downloader.js b/cocos2d/core/load-pipeline/audio-downloader.js index 40fdebb9d5..d70c8d50d3 100644 --- a/cocos2d/core/load-pipeline/audio-downloader.js +++ b/cocos2d/core/load-pipeline/audio-downloader.js @@ -26,63 +26,36 @@ var Path = require('../utils/CCPath'); var Sys = require('../platform/CCSys'); var Pipeline = require('./pipeline'); -require('../../audio/CCAudio'); +var audioEngine = require('../../audio/CCAudioEngine'); var __audioSupport = Sys.__audioSupport; var formatSupport = __audioSupport.format; var context = __audioSupport.context; -function loadAudioFromExtList (url, typeList, audio, cb){ - if(typeList.length === 0){ - var ERRSTR = 'can not found the resource of audio! Last match url is : '; - ERRSTR += url.replace(/\.(.*)?$/, '('); - formatSupport.forEach(function(ext){ - ERRSTR += ext + '|'; - }); - ERRSTR = ERRSTR.replace(/\|$/, ')'); - return cb({status: 520, errorMessage: ERRSTR}, null); - } - - if (__audioSupport.WEB_AUDIO && cc.Audio.useWebAudio) { - loadWebAudio(url, typeList, audio, cb); - } else { - loadDomAudio(url, typeList, audio, cb); - } -} - -function loadDomAudio (url, typeList, audio, cb) { - var num = __audioSupport.ONE_SOURCE ? 1 : typeList.length; - - // 加载统一使用dom +function loadDomAudio (item, callback) { var dom = document.createElement('audio'); - for (var i=0; i audioEngine._maxWebAudioSize) { + return loadDomAudio(item, callback); + } + return loadWebAudio(item, callback); + }; + request.onerror = function () { + var ERRSTR = 'can not found the resource of audio! Last match url is : ' + item.url; + return callback({status: 520, errorMessage: ERRSTR}, null); + }; + request.send(); } - module.exports = downloadAudio; \ No newline at end of file diff --git a/modules.json b/modules.json index 24fec2d2d5..a9a8dafb91 100644 --- a/modules.json +++ b/modules.json @@ -144,7 +144,7 @@ { "name": "Audio", "entries": [ - "./cocos2d/audio/CCAudio.js" + "./cocos2d/audio/CCAudioEngine.js" ] }, { From 7345fc9a788f6c07b4d9ce66981a34de2275f6d2 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 19 Aug 2016 10:02:55 +0800 Subject: [PATCH 175/268] Fix event listener mask can't be set if node is not in the hierarchy --- cocos2d/core/CCNode.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index 3eb80ebbe3..828c33bdfe 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -969,6 +969,12 @@ var Node = cc.Class({ // activate cc.director.getActionManager().resumeTarget(this); cc.eventManager.resumeTarget(this); + if (this._touchListener) { + this._touchListener.mask = _searchMaskParent(this); + } + if (this._mouseListener) { + this._mouseListener.mask = _searchMaskParent(this); + } } else { // deactivate From a871df4fc8930ba582d11724c9a1cb576573cd9d Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Fri, 19 Aug 2016 11:54:11 +0800 Subject: [PATCH 176/268] fix outOfBoundary when scrollview size changed --- cocos2d/core/components/CCScrollView.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cocos2d/core/components/CCScrollView.js b/cocos2d/core/components/CCScrollView.js index 9a209c87d2..33b34d1fc6 100644 --- a/cocos2d/core/components/CCScrollView.js +++ b/cocos2d/core/components/CCScrollView.js @@ -813,6 +813,7 @@ var ScrollView = cc.Class({ } this._moveContent(moveDelta); + this._adjustContentOutOfBoundary(); }, _calculateBoundary: function() { @@ -1331,6 +1332,7 @@ var ScrollView = cc.Class({ var newPosition = cc.pAdd(this.getContentPosition(), outOfBoundary); if(this.content) { this.content.setPosition(newPosition); + this._updateScrollBar(0); } } }, From 4edadb381cd73857c8dc19b1fc7e653271e1e76a Mon Sep 17 00:00:00 2001 From: Nan Wang Date: Fri, 19 Aug 2016 15:55:56 +0800 Subject: [PATCH 177/268] update engine version --- CCBoot.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CCBoot.js b/CCBoot.js index e5af2c5291..462bfea9f2 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -58,7 +58,7 @@ _p = null; * @name cc.ENGINE_VERSION */ var engineVersion; -engineVersion = '1.2.1-beta.4'; +engineVersion = '1.2.1-rc.1'; window['CocosEngine'] = cc.ENGINE_VERSION = engineVersion; /** From 8e9016f3625e451b46fb4300e4997d85116bcb24 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 19 Aug 2016 16:06:55 +0800 Subject: [PATCH 178/268] Fix Orientation not supported in Fit height & Fit width mode --- cocos2d/core/platform/CCView.js | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/platform/CCView.js b/cocos2d/core/platform/CCView.js index c5703f7016..053632db0f 100644 --- a/cocos2d/core/platform/CCView.js +++ b/cocos2d/core/platform/CCView.js @@ -154,7 +154,7 @@ var View = cc._Class.extend({ * Constructor of View */ ctor: function () { - var _t = this, d = document, _strategyer = cc.ContainerStrategy, _strategy = cc.ContentStrategy; + var _t = this, _strategyer = cc.ContainerStrategy, _strategy = cc.ContentStrategy; __BrowserGetter.init(this); @@ -1055,7 +1055,15 @@ cc.ContentStrategy = cc._Class.extend(/** @lends cc.ContentStrategy# */{ */ var EqualToFrame = cc.ContainerStrategy.extend({ apply: function (view) { + var frameH = view._frameSize.height, containerStyle = cc.container.style; this._setupContainer(view, view._frameSize.width, view._frameSize.height); + // Setup container's margin and padding + if (view._isRotated) { + containerStyle.marginLeft = frameH + 'px'; + } + else { + containerStyle.margin = '0px'; + } } }); From 42b00ebcb9fc34414c40c81d893ac15088647a84 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 19 Aug 2016 16:25:06 +0800 Subject: [PATCH 179/268] Force update all scene after set design resolution policy --- cocos2d/core/platform/CCView.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/cocos2d/core/platform/CCView.js b/cocos2d/core/platform/CCView.js index 053632db0f..d65dc9b54c 100644 --- a/cocos2d/core/platform/CCView.js +++ b/cocos2d/core/platform/CCView.js @@ -703,6 +703,9 @@ var View = cc._Class.extend({ // 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; From 18632258a0c6e5a8f00238c66e83f959f12b684e Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Fri, 19 Aug 2016 16:55:08 +0800 Subject: [PATCH 180/268] fix possible memory leaks --- cocos2d/core/editbox/CCSGEditBox.js | 4 ++-- cocos2d/core/label/CCSGLabel.js | 19 +++++++++++++++++++ cocos2d/core/videoplayer/CCSGVideoPlayer.js | 4 ++-- cocos2d/core/webview/CCSGWebView.js | 4 ++-- 4 files changed, 25 insertions(+), 6 deletions(-) diff --git a/cocos2d/core/editbox/CCSGEditBox.js b/cocos2d/core/editbox/CCSGEditBox.js index 4e6f82e24d..82647dd0c0 100644 --- a/cocos2d/core/editbox/CCSGEditBox.js +++ b/cocos2d/core/editbox/CCSGEditBox.js @@ -280,9 +280,9 @@ _ccsg.EditBox = _ccsg.Node.extend({ }, cleanup: function () { + this._super(); + this._renderCmd._removeDomInputControl(); - this.stopAllActions(); - this.unscheduleAllCallbacks(); }, _onTouchBegan: function (touch) { diff --git a/cocos2d/core/label/CCSGLabel.js b/cocos2d/core/label/CCSGLabel.js index 9140092841..d7a2c868e8 100644 --- a/cocos2d/core/label/CCSGLabel.js +++ b/cocos2d/core/label/CCSGLabel.js @@ -380,6 +380,23 @@ _ccsg.Label = _ccsg.Node.extend({ this._notifyLabelSkinDirty(); }, + cleanup: function () { + this._super(); + + //remove the created DIV and style due to loading @font-face + if(this.__$fontStyle) { + if(document.body.contains(this.__$fontStyle)) { + document.body.removeChild(this.__$fontStyle); + } + } + + if(this.__$preloadDiv) { + if(document.body.contains(this.__$preloadDiv)) { + document.body.removeChild(this.__$preloadDiv); + } + } + }, + _loadTTFFont: function(fontHandle) { var ttfIndex = fontHandle.lastIndexOf(".ttf"); if (ttfIndex === -1) return fontHandle; @@ -401,6 +418,7 @@ _ccsg.Label = _ccsg.Node.extend({ fontStyle = document.createElement("style"); fontStyle.type = "text/css"; doc.body.appendChild(fontStyle); + this.__$fontStyle = fontStyle; var fontStr = ""; if (isNaN(fontFamilyName - 0)) @@ -421,6 +439,7 @@ _ccsg.Label = _ccsg.Node.extend({ _divStyle.left = "-100px"; _divStyle.top = "-100px"; doc.body.appendChild(preloadDiv); + this.__$preloadDiv = preloadDiv; self.scheduleOnce(function () { self._notifyLabelSkinDirty(); self.emit("load"); diff --git a/cocos2d/core/videoplayer/CCSGVideoPlayer.js b/cocos2d/core/videoplayer/CCSGVideoPlayer.js index 64dad7323e..831672ea52 100644 --- a/cocos2d/core/videoplayer/CCSGVideoPlayer.js +++ b/cocos2d/core/videoplayer/CCSGVideoPlayer.js @@ -139,9 +139,9 @@ _ccsg.VideoPlayer = _ccsg.Node.extend(/** @lends _ccsg.VideoPlayer# */{ }, cleanup: function () { + this._super(); + this._renderCmd.removeDom(); - this.stopAllActions(); - this.unscheduleAllCallbacks(); }, onEnter: function () { diff --git a/cocos2d/core/webview/CCSGWebView.js b/cocos2d/core/webview/CCSGWebView.js index 7973a86a1f..db7f3295f3 100644 --- a/cocos2d/core/webview/CCSGWebView.js +++ b/cocos2d/core/webview/CCSGWebView.js @@ -185,9 +185,9 @@ _ccsg.WebView = _ccsg.Node.extend(/** @lends _ccsg.WebView# */{ * remove node */ cleanup: function(){ + this._super(); + this._renderCmd.removeDom(); - this.stopAllActions(); - this.unscheduleAllCallbacks(); }, setVisible: function ( visible ) { From b1078963506362a7e4d20b78a029fd8cbf5c316d Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Fri, 19 Aug 2016 17:09:51 +0800 Subject: [PATCH 181/268] rename member variables --- cocos2d/core/label/CCSGLabel.js | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/cocos2d/core/label/CCSGLabel.js b/cocos2d/core/label/CCSGLabel.js index d7a2c868e8..8705cc99b0 100644 --- a/cocos2d/core/label/CCSGLabel.js +++ b/cocos2d/core/label/CCSGLabel.js @@ -384,15 +384,15 @@ _ccsg.Label = _ccsg.Node.extend({ this._super(); //remove the created DIV and style due to loading @font-face - if(this.__$fontStyle) { - if(document.body.contains(this.__$fontStyle)) { - document.body.removeChild(this.__$fontStyle); + if(this._fontFaceStyle) { + if(document.body.contains(this._fontFaceStyle)) { + document.body.removeChild(this._fontFaceStyle); } } - if(this.__$preloadDiv) { - if(document.body.contains(this.__$preloadDiv)) { - document.body.removeChild(this.__$preloadDiv); + if(this._preloadDiv) { + if(document.body.contains(this._preloadDiv)) { + document.body.removeChild(this._preloadDiv); } } }, @@ -418,7 +418,7 @@ _ccsg.Label = _ccsg.Node.extend({ fontStyle = document.createElement("style"); fontStyle.type = "text/css"; doc.body.appendChild(fontStyle); - this.__$fontStyle = fontStyle; + this._fontFaceStyle = fontStyle; var fontStr = ""; if (isNaN(fontFamilyName - 0)) @@ -439,7 +439,7 @@ _ccsg.Label = _ccsg.Node.extend({ _divStyle.left = "-100px"; _divStyle.top = "-100px"; doc.body.appendChild(preloadDiv); - this.__$preloadDiv = preloadDiv; + this._preloadDiv = preloadDiv; self.scheduleOnce(function () { self._notifyLabelSkinDirty(); self.emit("load"); From e2fbf3de2c784c91e992317f0caf5f7e916cbe1f Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Tue, 16 Aug 2016 16:36:05 +0800 Subject: [PATCH 182/268] add bbcode parser commit 98767c294a5b5ac1272d320358a65821b8adbbe4 Author: zilongshanren Date: Fri Aug 12 18:41:16 2016 +0800 fix tag commit 4f6bde4e147b69d8c4c91f149140be6e81a41bbd Author: zilongshanren Date: Fri Aug 12 18:11:40 2016 +0800 add bold/italic/underline commit 69a498c44b38f302c448f23e6e544a13e419c2ea Author: zilongshanren Date: Fri Aug 12 17:31:07 2016 +0800 finish nested tag test commit 0a7328a8cf9752612de4f8a4cababf00c8e74427 Author: zilongshanren Date: Fri Aug 12 15:44:08 2016 +0800 finish tag parsing commit d375700850ea52e18710d44d39626f8f22d677ba Author: zilongshanren Date: Fri Aug 12 11:53:16 2016 +0800 refactoring done commit 38b567c3439a8b0858b59645ff81cd458ce235a9 Merge: a30fa24 c6cab77 Author: zilongshanren Date: Fri Aug 12 11:49:44 2016 +0800 Merge branch 'master' into add-rich-text-support commit a30fa24f7127a3cae3945ad994458744766894dc Author: zilongshanren Date: Fri Aug 12 11:48:30 2016 +0800 refactor tag parsing commit f123f52c24b3c994769f8c17de1b3a4099af72cd Merge: ad6e15b f8f9f72 Author: zilongshanren Date: Fri Aug 12 09:56:44 2016 +0800 Merge branch 'master' into add-rich-text-support commit ad6e15b0124c93fa51c551a9d25d71e2d08c85da Author: zilongshanren Date: Fri Aug 12 09:50:42 2016 +0800 parse event tag commit 88cf8a900318408da6f1efba9660efebb2f7469f Author: zilongshanren Date: Wed Aug 10 15:11:03 2016 +0800 add event handler commit a409e294b8b39c0bfc79c1e9872bca7339d06e93 Author: zilongshanren Date: Wed Aug 10 11:30:53 2016 +0800 add size parser commit 15406e1884da24f1d9aade74664f18ce055c91cd Author: zilongshanren Date: Wed Aug 10 10:22:58 2016 +0800 make color parsing works commit 6a5e1966e33ed6bf7aa253c1c4d8df52c5906d4c Author: zilongshanren Date: Tue Aug 9 18:31:20 2016 +0800 support color value commit 5ee73d1fbbaac7b2e2183182dd095ec3ffa76c20 Author: zilongshanren Date: Tue Aug 9 18:21:38 2016 +0800 add basic tag parser commit 05a4de6da69a7101376432e19b4a28c098db22ac Author: zilongshanren Date: Thu Jul 14 14:37:09 2016 +0800 add escape symbol test --- cocos2d/core/index.js | 1 + cocos2d/core/label/CCHtmlTextParser.js | 219 +++++++++++++++++++ test/qunit/run.sh | 0 test/qunit/unit/test-html-text-parser.js | 262 +++++++++++++++++++++++ 4 files changed, 482 insertions(+) create mode 100644 cocos2d/core/label/CCHtmlTextParser.js mode change 100644 => 100755 test/qunit/run.sh create mode 100644 test/qunit/unit/test-html-text-parser.js diff --git a/cocos2d/core/index.js b/cocos2d/core/index.js index 084e855a61..d9eead82ee 100644 --- a/cocos2d/core/index.js +++ b/cocos2d/core/index.js @@ -37,6 +37,7 @@ if (!CC_EDITOR || !Editor.isMainProcess) { require('./components'); require('./graphics'); require('./collider'); + require('./label/CCHtmlTextParser.js'); } require('./base-ui/CCWidgetManager'); diff --git a/cocos2d/core/label/CCHtmlTextParser.js b/cocos2d/core/label/CCHtmlTextParser.js new file mode 100644 index 0000000000..cb7c574303 --- /dev/null +++ b/cocos2d/core/label/CCHtmlTextParser.js @@ -0,0 +1,219 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +/** + * A utils class for parsing HTML texts. The parsed results will be an object array. + */ +cc.HtmlTextParser = function() { + this._parsedObject = {}; + this._specialSymbolArray = []; + this._specialSymbolArray.push([/</g, '<']); + this._specialSymbolArray.push([/>/g, '>']); + this._specialSymbolArray.push([/&/g, '&']); + this._specialSymbolArray.push([/"/g, '"']); + this._specialSymbolArray.push([/'/g, '\'']); +}; + +cc.HtmlTextParser.prototype = { + constructor: cc.HtmlTextParser, + parse: function(htmlString) { + this._resultObjectArray = []; + this._stack = []; + + var startIndex = 0; + var length = htmlString.length; + while (startIndex < length) { + var tagBeginIndex = htmlString.indexOf('<', startIndex); + if (tagBeginIndex < 0) { + this._stack.pop(); + this._processResult(htmlString.substring(startIndex)); + startIndex = length; + } else { + this._processResult(htmlString.substring(startIndex, tagBeginIndex)); + + var tagEndIndex = htmlString.indexOf('>', startIndex); + if (tagEndIndex === -1) { + cc.error('The tag is invalid!'); + tagEndIndex = tagBeginIndex; + } else if (htmlString.charAt(tagBeginIndex + 1) === '\/'){ + this._stack.pop(); + } else { + this._addToStack(htmlString.substring(tagBeginIndex + 1, tagEndIndex)); + } + startIndex = tagEndIndex + 1; + + } + } + + + return this._resultObjectArray; + }, + + _attributeToObject: function (attribute) { + attribute = attribute.trim(); + + var obj = {}; + var header = attribute.match(/^(color|size)(\s)*=/); + var tagName; + var nextSpace; + var eventObj; + if (header) { + tagName = header[0]; + attribute = attribute.substring(tagName.length).trim(); + if(attribute === "") return obj; + + //parse color + nextSpace = attribute.indexOf(' '); + switch(tagName[0]){ + case 'c': + if (nextSpace > -1) { + obj.color = attribute.substring(0, nextSpace).trim(); + } else { + obj.color = attribute; + } + break; + case 's': + obj.size = parseInt(attribute); + break; + } + + //tag has event arguments + if(nextSpace > -1) { + var eventHanlderString = attribute.substring(nextSpace+1).trim(); + eventObj = this._processEventHandler(eventHanlderString); + obj.event = eventObj; + } + } + + header = attribute.match(/^(on|u|b|i)(\s)*/); + if(header && header[0].length > 0) { + tagName = header[0]; + attribute = attribute.substring(tagName.length).trim(); + switch(tagName[0]){ + case 'u': + obj.underline = true; + break; + case 'i': + obj.italic = true; + break; + case 'b': + obj.bold = true; + break; + } + if(attribute === "") { + return obj; + } + eventObj = this._processEventHandler(attribute); + obj.event = eventObj; + } + + return obj; + }, + + _processEventHandler: function (eventString) { + var index = 0; + var obj = {}; + var eventNames = eventString.match(this._getEventRegx()); + var isValidTag = false; + while(eventNames) { + var eventName = eventNames[0]; + var eventValue = ""; + isValidTag = false; + eventString = eventString.substring(eventName.length).trim(); + if(eventString.charAt(0) === "\"") { + index = eventString.indexOf("\"", 1); + if (index > -1) { + eventValue = eventString.substring(1, index).trim(); + isValidTag = true; + } + index++; + } else if(eventString.charAt(0) === "\'") { + index = eventString.indexOf('\'', 1); + if(index > -1) { + eventValue = eventString.substring(1, index).trim(); + isValidTag = true; + } + index++; + } else { + //skip the invalid attribute value + eventValue = eventString.match(/(\S)+/)[0]; + index = eventValue.length; + } + + if(isValidTag) { + eventName = eventName.substring(0, eventName.length-1).trim(); + obj[eventName] = eventValue; + } + + eventString = eventString.substring(index).trim(); + eventNames = eventString.match(this._getEventRegx()); + } + + return obj; + }, + + _addToStack: function(attribute) { + var obj = this._attributeToObject(attribute); + + if (this._stack.length === 0){ + this._stack.push(obj); + } else { + //for nested tags + var previousTagObj = this._stack[this._stack.length - 1]; + for (var key in previousTagObj) { + if (!(obj[key])) { + obj[key] = previousTagObj[key]; + } + } + this._stack.push(obj); + } + }, + + _processResult: function(value) { + if (value === "") { + return; + } + + value = this._escapeSpecialSymbol(value); + if (this._stack.length > 0) { + this._resultObjectArray.push({text: value, style: this._stack[this._stack.length - 1]}); + } else { + this._resultObjectArray.push({text: value}); + } + }, + + _getEventRegx: function () { + return /^(click|hoverin|hoverout)(\s)*=/; + }, + + _escapeSpecialSymbol: function(str) { + for(var i = 0; i < this._specialSymbolArray.length; ++i) { + var key = this._specialSymbolArray[i][0]; + var value = this._specialSymbolArray[i][1]; + + str = str.replace(key, value); + } + return str; + } +}; diff --git a/test/qunit/run.sh b/test/qunit/run.sh old mode 100644 new mode 100755 diff --git a/test/qunit/unit/test-html-text-parser.js b/test/qunit/unit/test-html-text-parser.js new file mode 100644 index 0000000000..f94a556292 --- /dev/null +++ b/test/qunit/unit/test-html-text-parser.js @@ -0,0 +1,262 @@ +/*global test, deepEqual, largeModule, strictEqual */ + +largeModule('HtmlTextParser'); + +var parser = new cc.HtmlTextParser(); + +test('Basic Test', function() { + + var testStr1 = "hello world"; + deepEqual(parser.parse(testStr1), + [{text: "hello world"}], + 'No Html string should be equal to original.'); + + var testInvalidStr2 = "Super weapon"; + + deepEqual(parser.parse(eventTestString2), + [{text: "Super weapon", style: { + color: "#0xff0000", + event: { + click : "event1", + } + }}], "Color with event"); + + var eventTestString3 = "hello world"; + deepEqual(parser.parse(eventTestString3), + [{text: "hello world", + style: { + size: 20, + event: { + click : "event1", + hoverin : "event2" + } + }}], "Size with event"); + + var eventTestString4 = "hello world"; + deepEqual(parser.parse(eventTestString4), + [{text: "hello world", + style: {} + }], "Failed path: Size with event"); + + +}); + +test('Test special symbol escape', function() { + var testLessThan = "hello<world"; + + deepEqual(parser.parse(testLessThan), + [ {text: "helloworld", + style: { + event: { + click: 'event1' + } + }}], + "The > symbol should be correctly escaped."); + + var testAmp = "hello&world"; + deepEqual(parser.parse(testAmp), + [{text: "hello&world", + style: { + color: "#0xff00" + }}], + "The amp symbol should be correctly escaped."); + + var testQuot = "hello"world"; + deepEqual(parser.parse(testQuot), + [{text: "hello\"world", + style: {}}], + "The quot symbol should be correctly escaped."); + + var testApos = "Hi, hello'world"; + deepEqual(parser.parse(testApos), + [{text: "Hi, ", + style: { + color: "#0xffee" + }}, + {text: "hello'world", + style: { + color: "#0xffee", + size: 20 + }}], + "The apos symbol should be correctly escaped."); +}); + + +test('Integrate test', function() { + var eventTestString = "hello world, Ni hao "; + + deepEqual(parser.parse(eventTestString), + [{text: "hello "}, {text: "world", style: {bold: true}}, + {text: ", "}, + {text: " Ni hao ", style : {color: "#0xff0000"}}], "Happy path 1"); + + var moreComplexString = "大小不一,颜色不同可点击"; + deepEqual(parser.parse(moreComplexString), + [{text: "大小", style: {size: 20}}, {text: "不一", style: {size: 10}}, {text:","}, + {text: "颜色", style: {color: "#0xffeeaa"}}, {text: "不同", style: {color: "#0xffaaee"}}, + {text: "可点击", style: {event: {click: 'event1'}}}], "more complex test"); + + +}); + +test('bold/italic/underline test', function () { + var stringWithBold = "hello world"; + + deepEqual(parser.parse(stringWithBold), + [{text: "hello world", style: {bold: true}}], "bold test"); + + var stringWithItalic = "hello world"; + + deepEqual(parser.parse(stringWithItalic), + [{text: "hello world", style: {italic: true}}], "italic test"); + + var stringWithUnderline = "hello world"; + + deepEqual(parser.parse(stringWithUnderline), + [{text: "hello world", style: {underline: true}}], "underline test"); +}); From feca3e5780fa5ad377b614ebbb59ac7fc3488699 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Wed, 17 Aug 2016 14:28:39 +0800 Subject: [PATCH 183/268] add more tests --- test/qunit/unit/test-html-text-parser.js | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/test/qunit/unit/test-html-text-parser.js b/test/qunit/unit/test-html-text-parser.js index f94a556292..29b4defde3 100644 --- a/test/qunit/unit/test-html-text-parser.js +++ b/test/qunit/unit/test-html-text-parser.js @@ -174,6 +174,20 @@ test('Event test', function() { style: {} }], "Failed path: Size with event"); + var invalidEventTestString4 = "hello world"; + deepEqual(parser.parse(invalidEventTestString5), + [{text: "hello world", + style: {size: 20, + event: {}} + }], "Failed path: event name quote not match."); + }); @@ -245,7 +259,7 @@ test('Integrate test', function() { }); test('bold/italic/underline test', function () { - var stringWithBold = "hello world"; + var stringWithBold = "hello world"; deepEqual(parser.parse(stringWithBold), [{text: "hello world", style: {bold: true}}], "bold test"); From 05a97158e144f43ad9be3fa5847357ef2c7b6370 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 22 Aug 2016 11:32:50 +0800 Subject: [PATCH 184/268] Improve RepeatForever doc --- cocos2d/actions/CCActionInterval.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos2d/actions/CCActionInterval.js b/cocos2d/actions/CCActionInterval.js index 74c9232cb8..f6b41a8d19 100644 --- a/cocos2d/actions/CCActionInterval.js +++ b/cocos2d/actions/CCActionInterval.js @@ -705,8 +705,8 @@ cc.RepeatForever = cc.ActionInterval.extend({ }); /** - * !#en Create a acton which repeat forever - * !#zh 永远地重复一个动作,有限次数内重复一个动作请使用 repeat 动作。 + * !#en Create a acton which repeat forever, as it runs forever, it can't be added into cc.sequence and cc.spawn. + * !#zh 永远地重复一个动作,有限次数内重复一个动作请使用 repeat 动作,由于这个动作不会停止,所以不能被添加到 cc.sequence 或 cc.spawn 中。 * @method repeatForever * @param {FiniteTimeAction} action * @return {ActionInterval} From cd6a4ba41b6f384fb2988922da0a630f62008871 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 22 Aug 2016 11:33:39 +0800 Subject: [PATCH 185/268] Only rotate the canvas when orientation changing --- cocos2d/core/platform/CCView.js | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/platform/CCView.js b/cocos2d/core/platform/CCView.js index d65dc9b54c..56e238e52f 100644 --- a/cocos2d/core/platform/CCView.js +++ b/cocos2d/core/platform/CCView.js @@ -127,6 +127,8 @@ var View = cc._Class.extend({ // Custom callback for resize event _resizeCallback: null, + _orientationChanging: false, + _scaleX: 1, _originalScaleX: 1, _scaleY: 1, @@ -210,6 +212,12 @@ var View = cc._Class.extend({ } }, + _orientationChange: function () { + this._orientationChanging = true; + this._resizeEvent(); + this._orientationChanging = false; + }, + /** *

* Sets view's target-densitydpi for android mobile browser. it can be set to:
@@ -249,14 +257,14 @@ var View = cc._Class.extend({ if (!this.__resizeWithBrowserSize) { this.__resizeWithBrowserSize = true; window.addEventListener('resize', this._resizeEvent); - window.addEventListener('orientationchange', this._resizeEvent); + window.addEventListener('orientationchange', this._orientationChange); } } else { //disable if (this.__resizeWithBrowserSize) { this.__resizeWithBrowserSize = false; window.removeEventListener('resize', this._resizeEvent); - window.removeEventListener('orientationchange', this._resizeEvent); + window.removeEventListener('orientationchange', this._orientationChange); } } }, @@ -297,7 +305,7 @@ var View = cc._Class.extend({ var h = __BrowserGetter.availHeight(cc.game.frame); var isLandscape = w >= h; - if (CC_EDITOR || !cc.sys.isMobile || + if (CC_EDITOR || !this._orientationChanging || !cc.sys.isMobile || (isLandscape && this._orientation & cc.macro.ORIENTATION_LANDSCAPE) || (!isLandscape && this._orientation & cc.macro.ORIENTATION_PORTRAIT)) { locFrameSize.width = w; From c7e0e6919cfffa2d660c45fb40a7b2c259e53bba Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 22 Aug 2016 15:06:29 +0800 Subject: [PATCH 186/268] Fix hovered node haven't been reset during scene transition --- cocos2d/core/CCNode.js | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index 828c33bdfe..0813c8a946 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -140,7 +140,7 @@ var _mouseEvents = [ EventType.MOUSE_WHEEL, ]; -var currentHovered = null; +var _currentHovered = null; var _touchStartHandler = function (touch, event) { var pos = touch.getLocation(); @@ -194,12 +194,12 @@ var _mouseMoveHandler = function (event) { event.stopPropagation(); if (!this._previousIn) { // Fix issue when hover node switched, previous hovered node won't get MOUSE_LEAVE notification - if (currentHovered) { + if (_currentHovered) { event.type = EventType.MOUSE_LEAVE; - currentHovered.owner.dispatchEvent(event); - currentHovered._previousIn = false; + _currentHovered.dispatchEvent(event); + _currentHovered._mouseListener._previousIn = false; } - currentHovered = this; + _currentHovered = this.owner; event.type = EventType.MOUSE_ENTER; node.dispatchEvent(event); this._previousIn = true; @@ -211,7 +211,7 @@ var _mouseMoveHandler = function (event) { event.type = EventType.MOUSE_LEAVE; node.dispatchEvent(event); this._previousIn = false; - currentHovered = null; + _currentHovered = null; } }; var _mouseUpHandler = function (event) { @@ -528,8 +528,8 @@ var Node = cc.Class({ this._releaseAllActions(); // Remove Node.currentHovered - if (currentHovered === this) { - currentHovered = null; + if (_currentHovered === this) { + _currentHovered = null; } // Remove all listeners From 572b9a7bea7f523459240231955b8507f9d2acf3 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Mon, 22 Aug 2016 14:15:33 +0800 Subject: [PATCH 187/268] fix scene list --- cocos2d/core/CCGame.js | 2 +- jsb/jsb-game.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index 46c36da7ac..4af10c5b8b 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -634,7 +634,7 @@ var game = { modules && (config[CONFIG_KEY.modules] = modules); // Scene parser - this._sceneInfos = this._sceneInfos.concat(config[CONFIG_KEY.scenes]); + this._sceneInfos = config[CONFIG_KEY.scenes] || []; // Collide Map and Group List this.collisionMatrix = config.collisionMatrix || []; diff --git a/jsb/jsb-game.js b/jsb/jsb-game.js index 78f75bd92e..f2b31eba24 100644 --- a/jsb/jsb-game.js +++ b/jsb/jsb-game.js @@ -250,7 +250,7 @@ cc.js.mixin(cc.game, { this.collisionMatrix = config.collisionMatrix || []; // Scene parser - this._sceneInfos = this._sceneInfos.concat(config[CONFIG_KEY.scenes]); + this._sceneInfos = config[CONFIG_KEY.scenes] || []; cc.director.setDisplayStats(this.config[CONFIG_KEY.showFPS]); cc.director.setAnimationInterval(1.0/this.config[CONFIG_KEY.frameRate]); From 7e5bea497a4bcdc0b29baf03c5a90188561918d9 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 22 Aug 2016 16:51:18 +0800 Subject: [PATCH 188/268] setFinishCallback (audio) --- cocos2d/audio/CCAudio.js | 77 +++++++++++++++++++----- cocos2d/audio/CCAudioEngine.js | 50 ++++++++++++++- cocos2d/core/components/CCAudioSource.js | 8 +-- 3 files changed, 114 insertions(+), 21 deletions(-) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index 0601e7f7ae..7a560f1692 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -24,6 +24,11 @@ THE SOFTWARE. ****************************************************************************/ +var touchBinded = false; +var touchPlayList = [ + //{ offset: 0, audio: audio } +]; + var Audio = function () { this._audioType = Audio.Type.UNKNOWN; this._element = null; @@ -63,44 +68,74 @@ Audio.State = { }; proto.off = function (event, callback) { var list = this._eventList[event]; - if (!list) return; + if (!list) return false; + if (!callback) { + this._eventList[event] = []; + return true; + } + for (var i=0; i 0) { + this._pauseIDCache.push(waitQueue.pop()); + } }, resume: function (audioID) { var audio = getAudioFromId(audioID); @@ -169,6 +212,8 @@ var audioEngine = { if (!audio || !audio.stop) return false; audio.stop(); + removeWaitQueue(audioID); + return true; }, stopAll: function () { for (var id in id2audio) { @@ -177,6 +222,7 @@ var audioEngine = { audio.stop(); } } + waitQueue = []; }, setMaxAudioInstance: function (num) { diff --git a/cocos2d/core/components/CCAudioSource.js b/cocos2d/core/components/CCAudioSource.js index a7243d829e..12a7a473aa 100644 --- a/cocos2d/core/components/CCAudioSource.js +++ b/cocos2d/core/components/CCAudioSource.js @@ -203,7 +203,7 @@ var AudioSource = cc.Class({ * @method stop */ stop: function () { - if (!this.audioID) return false; + if (this.audioID === undefined) return false; audioEngine.stop(this.audioID); }, @@ -213,7 +213,7 @@ var AudioSource = cc.Class({ * @method pause */ pause: function () { - if (!this.audioID) return false; + if (this.audioID === undefined) return false; audioEngine.pause(this.audioID); }, @@ -223,7 +223,7 @@ var AudioSource = cc.Class({ * @method resume */ resume: function () { - if (!this.audioID) return false; + if (this.audioID === undefined) return false; audioEngine.resume(this.audioID); }, @@ -233,7 +233,7 @@ var AudioSource = cc.Class({ * @method rewind */ rewind: function(){ - if (!this.audioID) return false; + if (this.audioID === undefined) return false; this.stop(); this.play(); } From c295826dac172c678d85d7da04d42ac2c54ae0de Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 22 Aug 2016 17:15:28 +0800 Subject: [PATCH 189/268] add cc.audioEngine.play --- cocos2d/audio/CCAudioEngine.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/cocos2d/audio/CCAudioEngine.js b/cocos2d/audio/CCAudioEngine.js index 6c4b02287d..854cc535bb 100644 --- a/cocos2d/audio/CCAudioEngine.js +++ b/cocos2d/audio/CCAudioEngine.js @@ -74,9 +74,13 @@ var audioEngine = { AudioState: Audio.State, - _maxWebAudioSize: 30720000, // 300kb * 1024 + _maxWebAudioSize: 307200, // 300kb * 1024 _maxAudioInstance: 24, + play: function () { + this.play2d.apply(this, arguments); + }, + play2d: function (filePath, loop, volume/*, profile*/) { var item = cc.loader.getItem(filePath); From 7a3b562804cc26222cba2ae9befb736f718e551f Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 22 Aug 2016 17:28:09 +0800 Subject: [PATCH 190/268] remove test code --- cocos2d/audio/CCAudio.js | 1 - 1 file changed, 1 deletion(-) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index 7a560f1692..7bff802160 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -102,7 +102,6 @@ Audio.State = { }; proto.play = function () { - window.audio = this; if (!this._element) return; this._element.play(); this.emit('play'); From 112c91861df77769ffb9617a0db5cf9f95d5b1f4 Mon Sep 17 00:00:00 2001 From: Nan Wang Date: Mon, 22 Aug 2016 18:31:46 +0800 Subject: [PATCH 191/268] merged enableAntiAlias to v1.2 --- cocos2d/core/platform/CCView.js | 52 ++++++++++++++++++++++++++++ cocos2d/core/textures/CCTexture2D.js | 10 ++++++ 2 files changed, 62 insertions(+) diff --git a/cocos2d/core/platform/CCView.js b/cocos2d/core/platform/CCView.js index d65dc9b54c..4b4129047f 100644 --- a/cocos2d/core/platform/CCView.js +++ b/cocos2d/core/platform/CCView.js @@ -149,6 +149,7 @@ var View = cc._Class.extend({ __resizeWithBrowserSize: false, _isAdjustViewPort: true, _targetDensityDPI: null, + _antiAliasEnabled: false, /** * Constructor of View @@ -181,6 +182,7 @@ var View = cc._Class.extend({ _t._rpFixedWidth = new cc.ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.FIXED_WIDTH); _t._targetDensityDPI = cc.macro.DENSITYDPI_HIGH; + _t.enableAntiAlias(true); }, // Resize helper functions @@ -415,6 +417,56 @@ var View = cc._Class.extend({ return this._retinaEnabled; }, + /** + * !#en Whether to Enable on anti-alias + * !#zh 是否开启抗锯齿 + * @method enableAntiAlias + * @param {Boolean} enabled - Enable or not anti-alias + */ + enableAntiAlias: function (enabled) { + if (this._antiAliasEnabled === enabled) { + return; + } + this._antiAliasEnabled = enabled; + if(cc._renderType === cc.game.RENDER_TYPE_WEBGL) { + var map = cc.loader._items.map; + for (var key in map) { + var item = map[key]; + var tex = item && item.content instanceof cc.Texture2D ? item.content : null; + if (tex) { + if (enabled) { + tex.setAntiAliasTexParameters(); + } + else { + tex.setAliasTexParameters(); + } + } + } + } + else if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) { + var ctx = cc._canvas.getContext('2d'); + ctx.imageSmoothingEnabled = enabled; + ctx.mozImageSmoothingEnabled = enabled; + // refresh canvas + var dirtyRegion = cc.rendererCanvas._dirtyRegion; + if (dirtyRegion) { + var oldRegion = new cc.Region(); + oldRegion.setTo(0, 0, cc.visibleRect.width, cc.visibleRect.height); + dirtyRegion.addRegion(oldRegion); + } + } + }, + + /** + * !#en Returns whether the current enable on anti-alias + * !#zh 返回当前是否抗锯齿 + * @method isAntiAliasEnabled + * @param {Boolean} + */ + isAntiAliasEnabled: function () { + return this._antiAliasEnabled; + }, + /** * If enabled, the application will try automatically to enter full screen mode on mobile devices
* You can pass true as parameter to enable it and disable it by passing false.
diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index abafe8d952..4d48899d12 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -232,6 +232,16 @@ var Texture2D = cc.Class(/** @lends cc.Texture2D# */{ self._pixelHeight = self._contentSize.height = locElement.height; self._textureLoaded = true; + // anti-alias + if(cc._renderType === cc.game.RENDER_TYPE_WEBGL) { + if (cc.view._antiAliasEnabled) { + self.setAntiAliasTexParameters(); + } + else { + self.setAliasTexParameters(); + } + } + //dispatch load event to listener. self.emit("load"); }, From 362616d6dc45449361378cc89659e92acffa057f Mon Sep 17 00:00:00 2001 From: Nan Wang Date: Mon, 22 Aug 2016 18:48:10 +0800 Subject: [PATCH 192/268] revert pause and resume event in CCGame.js --- cocos2d/core/CCGame.js | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index 46c36da7ac..ac4e1d5bb4 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -258,11 +258,6 @@ var game = { cc.audioEngine.stopAllEffects(); cc.audioEngine.pauseMusic(); } - // Pause event - var scene = cc.director.getScene() || cc.director.getRunningScene(); - if (scene) { - cc.eventManager.pauseTarget(scene, true); - } // Pause main loop if (this._intervalId) window.cancelAnimationFrame(this._intervalId); @@ -282,11 +277,6 @@ var game = { if (cc.audioEngine && _isMusicPlaying) { cc.audioEngine.resumeMusic(); } - // Resume event - var scene = cc.director.getScene() || cc.director.getRunningScene(); - if (scene) { - cc.eventManager.resumeTarget(scene, true); - } // Resume main loop this._runMainLoop(); }, From 0ffcf53a7f312fb664f25c09fe77902a25134717 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 22 Aug 2016 18:21:30 +0800 Subject: [PATCH 193/268] Delay pause inactive target when adding touch/mouse listener to Node --- cocos2d/core/CCNode.js | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index 0813c8a946..136c8794a2 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -1103,6 +1103,7 @@ var Node = cc.Class({ * node.on(cc.Node.EventType.TOUCH_CANCEL, callback, this.node); */ on: function (type, callback, target, useCapture) { + var newAdded = false; if (_touchEvents.indexOf(type) !== -1) { if (!this._touchListener) { this._touchListener = cc.EventListener.create({ @@ -1118,6 +1119,7 @@ var Node = cc.Class({ this._touchListener.retain(); } cc.eventManager.addListener(this._touchListener, this); + newAdded = true; } } else if (_mouseEvents.indexOf(type) !== -1) { @@ -1136,8 +1138,17 @@ var Node = cc.Class({ this._mouseListener.retain(); } cc.eventManager.addListener(this._mouseListener, this); + newAdded = true; } } + if (newAdded && !this._activeInHierarchy) { + cc.director.getScheduler().schedule(function() { + if (this._activeInHierarchy) { + cc.eventManager.pauseTarget(this); + } + }, this, 0, 0, 0, false); + } + this._EventTargetOn(type, callback, target, useCapture); }, From 859ba5c75e94a95e77308ab4807145db5a716b6c Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Tue, 23 Aug 2016 10:12:14 +0800 Subject: [PATCH 194/268] disable dirty region in IE to prevent some bugs --- cocos2d/core/CCGame.js | 1 + cocos2d/core/renderer/RendererCanvas.js | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index 46c36da7ac..c95fdd145c 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -707,6 +707,7 @@ var game = { } else { cc._renderType = game.RENDER_TYPE_CANVAS; cc.renderer = cc.rendererCanvas; + cc.renderer.init(); this._renderContext = cc._renderContext = new cc.CanvasContextWrapper(localCanvas.getContext("2d")); cc._drawingUtil = cc.DrawingPrimitiveCanvas ? new cc.DrawingPrimitiveCanvas(this._renderContext) : null; } diff --git a/cocos2d/core/renderer/RendererCanvas.js b/cocos2d/core/renderer/RendererCanvas.js index 15c6467d30..d1b610e743 100644 --- a/cocos2d/core/renderer/RendererCanvas.js +++ b/cocos2d/core/renderer/RendererCanvas.js @@ -44,6 +44,11 @@ cc.rendererCanvas = { //max dirty Region count, default is 10 _dirtyRegionCountThreshold: 10, + init: function() { + if(cc.sys.browserType === cc.sys.BROWSER_TYPE_IE) { + this.enableDirtyRegion(false); + } + }, getRenderCmd: function (renderableObject) { //TODO Add renderCmd pool here From 0537b46da951193bd0b6ff9dd219ab4c24a1f0e3 Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Tue, 23 Aug 2016 10:22:23 +0800 Subject: [PATCH 195/268] disable dirty region UC --- cocos2d/core/renderer/RendererCanvas.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/renderer/RendererCanvas.js b/cocos2d/core/renderer/RendererCanvas.js index d1b610e743..dc0665fcb8 100644 --- a/cocos2d/core/renderer/RendererCanvas.js +++ b/cocos2d/core/renderer/RendererCanvas.js @@ -45,7 +45,7 @@ cc.rendererCanvas = { //max dirty Region count, default is 10 _dirtyRegionCountThreshold: 10, init: function() { - if(cc.sys.browserType === cc.sys.BROWSER_TYPE_IE) { + if(cc.sys.browserType === cc.sys.BROWSER_TYPE_IE || cc.sys.browserType === cc.sys.BROWSER_TYPE_UC) { this.enableDirtyRegion(false); } }, From ebe5dccdac739fd4ce4735b0c0516dad32851576 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Tue, 23 Aug 2016 11:08:05 +0800 Subject: [PATCH 196/268] fix _previousIn error for fireball/issues/3919 --- cocos2d/core/CCNode.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index 0813c8a946..b62c241f9d 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -1205,6 +1205,10 @@ var Node = cc.Class({ } } + if (_currentHovered === this) { + _currentHovered = null; + } + cc.eventManager.removeListener(this._mouseListener); this._mouseListener = null; } From 2de63d951a03d7482de1d3d27e73b4e21e60b6ed Mon Sep 17 00:00:00 2001 From: Nan Wang Date: Tue, 23 Aug 2016 17:06:14 +0800 Subject: [PATCH 197/268] update videoplayer api typo --- cocos2d/core/components/CCVideoPlayer.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/components/CCVideoPlayer.js b/cocos2d/core/components/CCVideoPlayer.js index 1de87bf61a..f16a085f7f 100644 --- a/cocos2d/core/components/CCVideoPlayer.js +++ b/cocos2d/core/components/CCVideoPlayer.js @@ -131,7 +131,7 @@ var VideoPlayer = cc.Class({ /** * !#en The local video full path. * !#zh 本地视频的 URL - * @property {String} video + * @property {String} clip */ clip: { tooltip: 'i18n:COMPONENT.videoplayer.video', From f4da3e3b2899d6c5dacc28ebf4138cb0f88ba427 Mon Sep 17 00:00:00 2001 From: Nan Wang Date: Tue, 23 Aug 2016 17:17:38 +0800 Subject: [PATCH 198/268] update engine version --- CCBoot.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CCBoot.js b/CCBoot.js index 462bfea9f2..ac3ab270c3 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -58,7 +58,7 @@ _p = null; * @name cc.ENGINE_VERSION */ var engineVersion; -engineVersion = '1.2.1-rc.1'; +engineVersion = '1.2.2-beta.1'; window['CocosEngine'] = cc.ENGINE_VERSION = engineVersion; /** From 47c31b2346693170a831c0ef363062aa1fc2c5cc Mon Sep 17 00:00:00 2001 From: Nan Wang Date: Wed, 24 Aug 2016 11:36:15 +0800 Subject: [PATCH 199/268] fix ccview api comment --- cocos2d/core/platform/CCView.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/platform/CCView.js b/cocos2d/core/platform/CCView.js index f3ca968c76..86df5e28b0 100644 --- a/cocos2d/core/platform/CCView.js +++ b/cocos2d/core/platform/CCView.js @@ -469,7 +469,7 @@ var View = cc._Class.extend({ * !#en Returns whether the current enable on anti-alias * !#zh 返回当前是否抗锯齿 * @method isAntiAliasEnabled - * @param {Boolean} + * @param {Boolean} enabled - Pass false to make pixel art sharp. */ isAntiAliasEnabled: function () { return this._antiAliasEnabled; From 91ef43405c69a699d31141009d39334a7e6be9db Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Wed, 24 Aug 2016 11:42:44 +0800 Subject: [PATCH 200/268] fix anti-alias error --- cocos2d/core/textures/CCTexture2D.js | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index 4d48899d12..d129e8f82d 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -232,16 +232,6 @@ var Texture2D = cc.Class(/** @lends cc.Texture2D# */{ self._pixelHeight = self._contentSize.height = locElement.height; self._textureLoaded = true; - // anti-alias - if(cc._renderType === cc.game.RENDER_TYPE_WEBGL) { - if (cc.view._antiAliasEnabled) { - self.setAntiAliasTexParameters(); - } - else { - self.setAliasTexParameters(); - } - } - //dispatch load event to listener. self.emit("load"); }, @@ -873,6 +863,13 @@ game.once(game.EVENT_RENDERER_INITED, function () { self._hasMipmaps = false; self._textureLoaded = true; + if (cc.view._antiAliasEnabled) { + self.setAntiAliasTexParameters(); + } + else { + self.setAliasTexParameters(); + } + //dispatch load event to listener. self.emit("load"); }, From a96507d040533df6b683257e59720a9fc3a7d1bf Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 25 Aug 2016 14:23:56 +0800 Subject: [PATCH 201/268] Fix event handler not activated if register before active --- cocos2d/core/CCNode.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index 8b13349535..3a928d006d 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -1143,7 +1143,7 @@ var Node = cc.Class({ } if (newAdded && !this._activeInHierarchy) { cc.director.getScheduler().schedule(function() { - if (this._activeInHierarchy) { + if (!this._activeInHierarchy) { cc.eventManager.pauseTarget(this); } }, this, 0, 0, 0, false); From 57e17c73b9ee52dbade133f67bd0773e46050f63 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Thu, 18 Aug 2016 14:32:34 +0800 Subject: [PATCH 202/268] add RichText component A minimal working prototype try and fix fix richtext color make richtext properties tweakable temp refine add measure text fix fragment text finish non \n case make non maxWidth working adjust calling order fix wired bugs get first word still one bug remained fix wrap error refactoring update lineOffsetX refactoring refactoring fix a return issue don't display vertical alignment improve performance refactoring almost done refactoring refactoring improve setColor use shared htmlTextParser fix contentSize change issue add click event handler add hoverin and hoverout event handler fix a issue remove mousein and mouseover done --- cocos2d/core/components/CCLabel.js | 3 +- cocos2d/core/components/CCRichText.js | 605 +++++++++++++++++++++++ cocos2d/core/components/index.js | 1 + cocos2d/core/index.js | 2 +- cocos2d/core/label/CCHtmlTextParser.js | 14 +- cocos2d/core/label/CCSGLabel.js | 4 +- test/qunit/unit/test-html-text-parser.js | 10 +- 7 files changed, 624 insertions(+), 15 deletions(-) create mode 100644 cocos2d/core/components/CCRichText.js diff --git a/cocos2d/core/components/CCLabel.js b/cocos2d/core/components/CCLabel.js index bb31dbb0ce..abafc3fe0f 100644 --- a/cocos2d/core/components/CCLabel.js +++ b/cocos2d/core/components/CCLabel.js @@ -114,7 +114,6 @@ var Overflow = _ccsg.Label.Overflow; * !#zh 系统字体 * @property {Number} SystemFont */ -var LabelType = _ccsg.Label.Type; // Returns a function, that, as long as it continues to be invoked, will not @@ -134,7 +133,7 @@ function debounce(func, wait, immediate) { timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; -}; +} /** diff --git a/cocos2d/core/components/CCRichText.js b/cocos2d/core/components/CCRichText.js new file mode 100644 index 0000000000..b74df92102 --- /dev/null +++ b/cocos2d/core/components/CCRichText.js @@ -0,0 +1,605 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Chukong Aipu reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ +var HorizontalAlign = cc.TextAlignment; +var VerticalAlign = cc.VerticalTextAlignment; + +var label_wrapinspection = true; +var label_wordRex = /([a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]+|\S)/; +var label_symbolRex = /^[!,.:;}\]%\?>、‘“》?。,!]/; +var label_lastWordRex = /([a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]+|\S)$/; +var label_lastEnglish = /[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]+$/; +var label_firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; + +// Returns a function, that, as long as it continues to be invoked, will not +// be triggered. The function will be called after it stops being called for +// N milliseconds. If `immediate` is passed, trigger the function on the +// leading edge, instead of the trailing. +function debounce(func, wait, immediate) { + var timeout; + return function() { + var context = this, args = arguments; + var later = function() { + timeout = null; + if (!immediate) func.apply(context, args); + }; + var callNow = immediate && !timeout; + clearTimeout(timeout); + timeout = setTimeout(later, wait); + if (callNow) func.apply(context, args); + }; +} + +/** + * !#en The RichText Component. + * !#zh 富文本组件 + * @class RichText + * @extends Component + */ +var RichText = cc.Class({ + name: 'cc.RichText', + extends: cc._RendererUnderSG, + + ctor: function() { + this._textArray = null; + + this._resetState(); + }, + + editor: CC_EDITOR && { + menu: 'i18n:MAIN_MENU.component.renderers/RichText', + }, + + + properties: { + _useOriginalSize: true, + /** + * !#en Content string of RichText. + * !#zh 富文本显示的文本内容。 + * @property {String} string + */ + string: { + default: 'Label', + multiline: true, + tooltip: 'i18n:COMPONENT.label.string', + notify: function () { + this._updateRichTextStatus(); + } + }, + + /** + * !#en Horizontal Alignment of label. + * !#zh 文本内容的水平对齐方式。 + * @property {RichText.HorizontalAlign} horizontalAlign + */ + horizontalAlign: { + default: HorizontalAlign.LEFT, + type: HorizontalAlign, + tooltip: 'i18n:COMPONENT.label.horizontal_align', + animatable: false, + notify: function () { + this._updateRichTextStatus(); + } + }, + + /** + * !#en Font size of label. + * !#zh 文本字体大小。 + * @property {Number} fontSize + */ + fontSize: { + default: 40, + tooltip: 'i18n:COMPONENT.label.font_size', + notify: function () { + this._updateRichTextStatus(); + } + }, + + /** + * !#en The maximize width of the RichText + * !#zh 富文本的最大宽度 + * @property {Number} maxWidth + */ + maxWidth: { + default: 0, + notify: function () { + this._updateRichTextStatus(); + } + }, + + /** + * !#en Line Height of label. + * !#zh 文本行高。 + * @property {Number} lineHeight + */ + lineHeight: { + default: 40, + tooltip: 'i18n:COMPONENT.label.line_height', + notify: function () { + this._updateRichTextStatus(); + } + } + }, + + _updateRichTextStatus: function () { + if(this._sgNode) { + if(CC_EDITOR) { + this._debouncedUpdateRichText(); + } else { + this._updateRichText(); + } + } + }, + + statics: { + HorizontalAlign: HorizontalAlign, + VerticalAlign: VerticalAlign + }, + + _createSgNode: function () { + return null; + }, + + __preload: function () { + this._super(); + if(CC_EDITOR) { + this._debouncedUpdateRichText = debounce(this._updateRichText, 200); + } else { + this._registerEvents(); + } + + }, + + _updateLabelSegmentColor: function() { + this._labelSegments.forEach(function(item) { + this._applyTextAttribute(item); + }.bind(this)); + }, + + _initSgNode: function () { + + var sgNode = this._sgNode = new _ccsg.Node(); + sgNode.setCascadeOpacityEnabled(true); + + if (this.enabledInHierarchy && !sgNode.isVisible()) { + sgNode.setVisible(true); + } + + if ( !this.enabledInHierarchy ) { + sgNode.setVisible(false); + } + + var self = this; + sgNode.setColor = function () { + self._updateLabelSegmentColor(); + }; + + sgNode._setContentSize = sgNode.setContentSize; + sgNode.setContentSize = function () {}; + + this._updateRichText(); + + if(CC_JSB) { + sgNode.retain(); + } + }, + + _computeAlignmentOffset: function() { + this._linesOffsetX = []; + switch (this.horizontalAlign) { + case cc.TextAlignment.LEFT: + for (var i = 0; i < this._lineCount; ++i) { + this._linesOffsetX.push(0); + } + break; + case cc.TextAlignment.CENTER: + this._linesWidth.forEach(function(lineWidth) { + this._linesOffsetX.push((this._labelWidth - lineWidth) / 2); + }.bind(this)); + break; + case cc.TextAlignment.RIGHT: + this._linesWidth.forEach(function(lineWidth) { + this._linesOffsetX.push(this._labelWidth - lineWidth); + }.bind(this)); + break; + default: + break; + } + }, + + _measureText: function (string, styleIndex) { + var label = new _ccsg.Label(string); + label._styleIndex = styleIndex; + this._applyTextAttribute(label); + var labelSize = label.getContentSize(); + return labelSize.width; + }, + + + _onTouchEnded: function (event) { + if(!this.enabledInHierarchy) return; + + var components = this.node.getComponents(cc.Component); + + for (var i = 0; i < this._labelSegments.length; ++i ) { + var labelSegment = this._labelSegments[i]; + var clickHandler = labelSegment._clickHandler; + if (clickHandler && this._containsTouchLocation(labelSegment, event.touch.getLocation())) { + components.forEach(function(component) { + if(component.enabledInHierarchy && component[clickHandler]) { + component[clickHandler](event); + } + }); + } + } + }, + + _containsTouchLocation:function (label, point) { + var myRect = label.getBoundingBoxToWorld(); + + return cc.rectContainsPoint(myRect, point); + }, + + _registerEvents: function () { + this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); + }, + + _fragmentText: function (stringToken, allWidth, styleIndex) { + //check the first character + var wrappedWords = []; + //fast return if strArr is empty + if(stringToken.length === 0 || this.maxWidth < 0) { + wrappedWords.push(''); + return wrappedWords; + } + + var text = stringToken; + while (allWidth > this.maxWidth && text.length > 1) { + + var fuzzyLen = text.length * ( this.maxWidth / allWidth ) | 0; + var tmpText = text.substr(fuzzyLen); + var width = allWidth - this._measureText(tmpText, styleIndex); + var sLine = tmpText; + var pushNum = 0; + + var checkWhile = 0; + var checkCount = 10; + + //Exceeded the size + while (width > this.maxWidth && checkWhile++ < checkCount) { + fuzzyLen *= this.maxWidth / width; + fuzzyLen = fuzzyLen | 0; + tmpText = text.substr(fuzzyLen); + width = allWidth - this._measureText(tmpText, styleIndex); + } + + checkWhile = 0; + + //Find the truncation point + while (width < this.maxWidth && checkWhile++ < checkCount) { + if (tmpText) { + var exec = label_wordRex.exec(tmpText); + pushNum = exec ? exec[0].length : 1; + sLine = tmpText; + } + + fuzzyLen = fuzzyLen + pushNum; + tmpText = text.substr(fuzzyLen); + width = allWidth - this._measureText(tmpText, styleIndex); + } + + fuzzyLen -= pushNum; + if (fuzzyLen === 0) { + fuzzyLen = 1; + sLine = sLine.substr(1); + } + + var sText = text.substr(0, fuzzyLen), result; + + //symbol in the first + if (label_wrapinspection) { + if (label_symbolRex.test(sLine || tmpText)) { + result = label_lastWordRex.exec(sText); + fuzzyLen -= result ? result[0].length : 0; + if (fuzzyLen === 0) fuzzyLen = 1; + + sLine = text.substr(fuzzyLen); + sText = text.substr(0, fuzzyLen); + } + } + + //To judge whether a English words are truncated + if (label_firsrEnglish.test(sLine)) { + result = label_lastEnglish.exec(sText); + if (result && sText !== result[0]) { + fuzzyLen -= result[0].length; + sLine = text.substr(fuzzyLen); + sText = text.substr(0, fuzzyLen); + } + } + if (sText.trim().length > 0) { + wrappedWords.push(sText); + } + text = sLine || tmpText; + allWidth = this._measureText(text, styleIndex); + } + if (text.length > 0) { + wrappedWords.push(text); + } + + return wrappedWords; + }, + + _resetState: function () { + var sgNode = this._sgNode; + if(sgNode) { + sgNode.removeAllChildren(); + } + + this._labelSegments = []; + this._linesWidth = []; + this._lineOffsetX = 0; + this._lineCount = 1; + this._labelWidth = 0; + this._labelHeight = 0; + }, + + _addLabelSegment: function(stringToken, styleIndex) { + var labelSegment = new _ccsg.Label(stringToken); + labelSegment._styleIndex = styleIndex; + labelSegment._lineCount = this._lineCount; + + this._applyTextAttribute(labelSegment); + + labelSegment.setAnchorPoint(cc.p(0, 0)); + this._sgNode.addChild(labelSegment); + this._labelSegments.push(labelSegment); + + return labelSegment; + }, + + _updateRichTextWithMaxWidth: function (labelString, labelWidth, styleIndex) { + var fragmentWidth = labelWidth; + var labelSegment; + + if (this._lineOffsetX > 0 && fragmentWidth + this._lineOffsetX > this.maxWidth) { + //concat previous line + var checkStartIndex = 0; + while (this._lineOffsetX < this.maxWidth) { + var checkEndIndex = this._getFirstWordLen(labelString, checkStartIndex, labelString.length); + var checkString = labelString.substr(checkStartIndex, checkEndIndex); + var checkStringWidth = this._measureText(checkString, styleIndex); + + if(this._lineOffsetX + checkStringWidth < this.maxWidth) { + this._lineOffsetX += checkStringWidth; + checkStartIndex += checkEndIndex; + } else { + + if(checkStartIndex > 0) { + var remainingString = labelString.substr(0, checkStartIndex); + + this._addLabelSegment(remainingString, styleIndex); + + labelString = labelString.substr(checkStartIndex, labelString.length); + fragmentWidth = this._measureText(labelString, styleIndex); + } + this._updateLineInfo(); + break; + } + } + } + if(fragmentWidth > this.maxWidth) { + var fragments = this._fragmentText(labelString, fragmentWidth, styleIndex); + for(var k = 0; k < fragments.length; ++k) { + var splitString = fragments[k]; + + labelSegment = this._addLabelSegment(splitString, styleIndex); + + var labelSize = labelSegment.getContentSize(); + + this._lineOffsetX += labelSize.width; + + if(fragments.length > 1 && k < fragments.length - 1) { + this._updateLineInfo(); + } + } + } else { + this._lineOffsetX += fragmentWidth; + + this._addLabelSegment(labelString, styleIndex); + } + + }, + + _isLastComponentCR: function(stringToken) { + return stringToken.length -1 === stringToken.lastIndexOf("\n"); + }, + + _updateLineInfo: function () { + this._linesWidth.push(this._lineOffsetX); + this._lineOffsetX = 0; + this._lineCount++; + }, + + _updateRichText: function () { + this._textArray = cc.htmlTextParser.parse(this.string); + var sgNode = this._sgNode; + this._resetState(); + + var lastEmptyLine = false; + var label; + var labelSize; + + for (var i = 0; i < this._textArray.length; ++i) { + var text = this._textArray[i].text; + var multilineTexts = text.split("\n"); + + for (var j = 0; j < multilineTexts.length; ++j) { + var labelString = multilineTexts[j]; + if(labelString === "") { + //for continues \n + if(this._isLastComponentCR(text) && j == multilineTexts.length - 1) { + continue; + } + this._updateLineInfo(); + lastEmptyLine = true; + continue; + } + lastEmptyLine = false; + + if(this.maxWidth > 0) { + var labelWidth = this._measureText(labelString, i); + this._updateRichTextWithMaxWidth(labelString, labelWidth, i); + + if(multilineTexts.length > 1 && j < multilineTexts.length - 1) { + this._updateLineInfo(); + } + } else { + label = this._addLabelSegment(labelString, i); + labelSize = label.getContentSize(); + + this._lineOffsetX += labelSize.width; + if(this._lineOffsetX > this._labelWidth) { + this._labelWidth = this._lineOffsetX; + } + + if(multilineTexts.length > 1 && j < multilineTexts.length - 1) { + this._updateLineInfo(); + } + } + } + } + if(!lastEmptyLine) { + this._linesWidth.push(this._lineOffsetX); + } + + if(this.maxWidth > 0) { + this._labelWidth = this.maxWidth; + } + this._labelHeight =this._lineCount * this.lineHeight; + + sgNode._setContentSize(cc.size(this._labelWidth, this._labelHeight)); + + this._updateRichTextPosition(); + }, + + _isCJK_unicode: function(ch) { + var __CHINESE_REG = /^[\u4E00-\u9FFF\u3400-\u4DFF]+$/; + var __JAPANESE_REG = /[\u3000-\u303F]|[\u3040-\u309F]|[\u30A0-\u30FF]|[\uFF00-\uFFEF]|[\u4E00-\u9FAF]|[\u2605-\u2606]|[\u2190-\u2195]|\u203B/g; + var __KOREAN_REG = /^[\u1100-\u11FF]|[\u3130-\u318F]|[\uA960-\uA97F]|[\uAC00-\uD7AF]|[\uD7B0-\uD7FF]+$/; + return __CHINESE_REG.test(ch) || __JAPANESE_REG.test(ch) || __KOREAN_REG.test(ch); + }, + + //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); + }, + + _getFirstWordLen: function(text, startIndex, textLen) { + var character = text.charAt(startIndex); + if (this._isCJK_unicode(character) || this._isspace_unicode(character)) { + return 1; + } + + var len = 1; + for (var index = startIndex + 1; index < textLen; ++index) { + character = text.charAt(index); + if (this._isspace_unicode(character) || this._isCJK_unicode(character)) { + break; + } + len++; + } + + return len; + }, + + _updateRichTextPosition: function () { + this._computeAlignmentOffset(); + + var nextTokenX = 0; + var nextLineIndex = 1; + var totalLineCount = this._lineCount; + for(var i = 0; i < this._labelSegments.length; ++i) { + var label = this._labelSegments[i]; + var lineCount = label._lineCount; + if (lineCount > nextLineIndex) { + nextTokenX = 0; + nextLineIndex = lineCount; + } + var lineOffsetX = this._linesOffsetX[lineCount - 1]; + label.setPositionX(nextTokenX + lineOffsetX); + + var labelSize = label.getContentSize(); + + var positionY = (totalLineCount - lineCount) * this.lineHeight; + + label.setPositionY(positionY); + + if (lineCount === nextLineIndex) { + nextTokenX += labelSize.width; + } + + } + }, + + _applyTextAttribute: function (label) { + var index = label._styleIndex; + label.setLineHeight(this.lineHeight); + label.setVerticalAlign(VerticalAlign.CENTER); + + var textStyle = null; + if(this._textArray[index]) { + textStyle = this._textArray[index].style; + } + if(textStyle && textStyle.color) { + label.setColor(cc.hexToColor(textStyle.color)); + } else { + label.setColor(this.node.color); + } + + if(textStyle && textStyle.size) { + label.setFontSize(textStyle.size); + } else { + label.setFontSize(this.fontSize); + } + + if(textStyle && textStyle.event) { + if(textStyle.event.click) { + label._clickHandler = textStyle.event.click; + } + + if(textStyle.event.hoverin) { + label._hoverinHandler = textStyle.event.hoverin; + } + + if(textStyle.event.hoverout) { + label._hoveroutHandler = textStyle.event.hoverout; + } + } + } + + }); + + cc.RichText = module.exports = RichText; diff --git a/cocos2d/core/components/index.js b/cocos2d/core/components/index.js index cf89692912..49d5614db4 100644 --- a/cocos2d/core/components/index.js +++ b/cocos2d/core/components/index.js @@ -47,4 +47,5 @@ module.exports = [ require('./CCWebView'), require('./CCSpriteDistortion'), require('./CCLabelOutline'), + require('./CCRichText'), ]; diff --git a/cocos2d/core/index.js b/cocos2d/core/index.js index d9eead82ee..fdf6acf4c7 100644 --- a/cocos2d/core/index.js +++ b/cocos2d/core/index.js @@ -34,10 +34,10 @@ if (!CC_EDITOR || !Editor.isMainProcess) { require('./CCNode'); require('./CCScene'); + require('./label/CCHtmlTextParser.js'); require('./components'); require('./graphics'); require('./collider'); - require('./label/CCHtmlTextParser.js'); } require('./base-ui/CCWidgetManager'); diff --git a/cocos2d/core/label/CCHtmlTextParser.js b/cocos2d/core/label/CCHtmlTextParser.js index cb7c574303..92f57fc040 100644 --- a/cocos2d/core/label/CCHtmlTextParser.js +++ b/cocos2d/core/label/CCHtmlTextParser.js @@ -54,7 +54,7 @@ cc.HtmlTextParser.prototype = { var tagEndIndex = htmlString.indexOf('>', startIndex); if (tagEndIndex === -1) { - cc.error('The tag is invalid!'); + // cc.error('The HTML tag is invalid!'); tagEndIndex = tagBeginIndex; } else if (htmlString.charAt(tagBeginIndex + 1) === '\/'){ this._stack.pop(); @@ -157,7 +157,12 @@ cc.HtmlTextParser.prototype = { index++; } else { //skip the invalid attribute value - eventValue = eventString.match(/(\S)+/)[0]; + var match = eventString.match(/(\S)+/); + if(match) { + eventValue = match[0]; + } else { + eventValue = ""; + } index = eventValue.length; } @@ -204,7 +209,7 @@ cc.HtmlTextParser.prototype = { }, _getEventRegx: function () { - return /^(click|hoverin|hoverout)(\s)*=/; + return /^(click)(\s)*=/; }, _escapeSpecialSymbol: function(str) { @@ -217,3 +222,6 @@ cc.HtmlTextParser.prototype = { return str; } }; + + +cc.htmlTextParser = new cc.HtmlTextParser(); diff --git a/cocos2d/core/label/CCSGLabel.js b/cocos2d/core/label/CCSGLabel.js index 9140092841..12942e0326 100644 --- a/cocos2d/core/label/CCSGLabel.js +++ b/cocos2d/core/label/CCSGLabel.js @@ -1120,7 +1120,7 @@ cc.BMFontHelper = { } }, - _computeHorizontalKerningForText: function(text) { + _computeHorizontalKerningForText: function() { var stringLen = this.getStringLength(); var locKerningDict = this._config.kerningDict; @@ -1155,7 +1155,7 @@ cc.BMFontHelper = { var locIsLoaded = texture.isLoaded(); self._textureLoaded = locIsLoaded; if (!locIsLoaded) { - texture.once("load", function(event) { + texture.once("load", function() { var self = this; if (!self._spriteBatchNode) { diff --git a/test/qunit/unit/test-html-text-parser.js b/test/qunit/unit/test-html-text-parser.js index 29b4defde3..353d9a41f9 100644 --- a/test/qunit/unit/test-html-text-parser.js +++ b/test/qunit/unit/test-html-text-parser.js @@ -115,9 +115,7 @@ test('Event test', function() { deepEqual(parser.parse(eventTestString), [{text: "hello world", style: { event: { - click : "event1", - hoverin : "event2", - hoverout : "event3" + click : "event1" }}}], "Happy path 1"); var eventTestStringFail1 = "hello world"; @@ -143,7 +141,6 @@ test('Event test', function() { [{text: "hello world", style: { size: 20, event: { - hoverin : "event2", }}}], "Fail path 3"); @@ -164,7 +161,6 @@ test('Event test', function() { size: 20, event: { click : "event1", - hoverin : "event2" } }}], "Size with event"); @@ -259,10 +255,10 @@ test('Integrate test', function() { }); test('bold/italic/underline test', function () { - var stringWithBold = "hello world"; + var stringWithBold = "hello \n world"; deepEqual(parser.parse(stringWithBold), - [{text: "hello world", style: {bold: true}}], "bold test"); + [{text: "hello \n world", style: {bold: true}}], "bold test"); var stringWithItalic = "hello world"; From 9f83695250f447d0f957cc96a55868af0a3f53fb Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Thu, 25 Aug 2016 16:47:00 +0800 Subject: [PATCH 203/268] improve performance --- cocos2d/core/components/CCRichText.js | 61 +++++++++++++++++++++++---- 1 file changed, 53 insertions(+), 8 deletions(-) diff --git a/cocos2d/core/components/CCRichText.js b/cocos2d/core/components/CCRichText.js index b74df92102..323ea33b4e 100644 --- a/cocos2d/core/components/CCRichText.js +++ b/cocos2d/core/components/CCRichText.js @@ -89,7 +89,7 @@ var RichText = cc.Class({ }, /** - * !#en Horizontal Alignment of label. + * !#en Horizontal Alignment of each line in RichText. * !#zh 文本内容的水平对齐方式。 * @property {RichText.HorizontalAlign} horizontalAlign */ @@ -104,8 +104,8 @@ var RichText = cc.Class({ }, /** - * !#en Font size of label. - * !#zh 文本字体大小。 + * !#en Font size of RichText. + * !#zh 富文本字体大小。 * @property {Number} fontSize */ fontSize: { @@ -129,8 +129,8 @@ var RichText = cc.Class({ }, /** - * !#en Line Height of label. - * !#zh 文本行高。 + * !#en Line Height of RichText. + * !#zh 富文本行高。 * @property {Number} lineHeight */ lineHeight: { @@ -171,7 +171,7 @@ var RichText = cc.Class({ }, - _updateLabelSegmentColor: function() { + _updateLabelSegmentTextAttributes: function() { this._labelSegments.forEach(function(item) { this._applyTextAttribute(item); }.bind(this)); @@ -192,7 +192,7 @@ var RichText = cc.Class({ var self = this; sgNode.setColor = function () { - self._updateLabelSegmentColor(); + self._updateLabelSegmentTextAttributes(); }; sgNode._setContentSize = sgNode.setContentSize; @@ -442,8 +442,53 @@ var RichText = cc.Class({ this._lineCount++; }, + _needsUpdateTextLayout: function (newTextArray) { + if(!this._textArray || !newTextArray) { + return true; + } + + if(this._textArray.length !== newTextArray.length) { + return true; + } + + for(var i = 0; i < this._textArray.length; ++i) { + var oldItem = this._textArray[i]; + var newItem = newTextArray[i]; + if(oldItem.text != newItem.text) { + return true; + } else { + if (oldItem.style) { + if (newItem.style) { + //TODO: add more when adding bold/italic/underline + if(oldItem.style.size != newItem.style.size) { + return true; + } + } else { + if(oldItem.style.size) { + return true; + } + } + } else { + if (newItem.style) { + if(newItem.style.size) { + return true; + } + } + } + } + } + return false; + }, + _updateRichText: function () { - this._textArray = cc.htmlTextParser.parse(this.string); + var newTextArray = cc.htmlTextParser.parse(this.string); + if(!this._needsUpdateTextLayout(newTextArray)) { + this._textArray = newTextArray; + this._updateLabelSegmentTextAttributes(); + return; + } + + this._textArray = newTextArray; var sgNode = this._sgNode; this._resetState(); From e2de6a3f2ad415d60d491f718c77a5dbb7ae9a31 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Thu, 25 Aug 2016 17:40:00 +0800 Subject: [PATCH 204/268] fix layout issue --- cocos2d/core/components/CCRichText.js | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/components/CCRichText.js b/cocos2d/core/components/CCRichText.js index 323ea33b4e..295bd6bda3 100644 --- a/cocos2d/core/components/CCRichText.js +++ b/cocos2d/core/components/CCRichText.js @@ -99,6 +99,7 @@ var RichText = cc.Class({ tooltip: 'i18n:COMPONENT.label.horizontal_align', animatable: false, notify: function () { + this._layoutDirty = true; this._updateRichTextStatus(); } }, @@ -112,6 +113,7 @@ var RichText = cc.Class({ default: 40, tooltip: 'i18n:COMPONENT.label.font_size', notify: function () { + this._layoutDirty = true; this._updateRichTextStatus(); } }, @@ -124,6 +126,7 @@ var RichText = cc.Class({ maxWidth: { default: 0, notify: function () { + this._layoutDirty = true; this._updateRichTextStatus(); } }, @@ -137,6 +140,7 @@ var RichText = cc.Class({ default: 40, tooltip: 'i18n:COMPONENT.label.line_height', notify: function () { + this._layoutDirty = true; this._updateRichTextStatus(); } } @@ -363,6 +367,7 @@ var RichText = cc.Class({ this._lineCount = 1; this._labelWidth = 0; this._labelHeight = 0; + this._layoutDirty = true; }, _addLabelSegment: function(stringToken, styleIndex) { @@ -443,7 +448,7 @@ var RichText = cc.Class({ }, _needsUpdateTextLayout: function (newTextArray) { - if(!this._textArray || !newTextArray) { + if(this._layoutDirty || !this._textArray || !newTextArray) { return true; } @@ -547,6 +552,7 @@ var RichText = cc.Class({ sgNode._setContentSize(cc.size(this._labelWidth, this._labelHeight)); this._updateRichTextPosition(); + this._layoutDirty = false; }, _isCJK_unicode: function(ch) { From 69231a85430ca46346f135e85b1a713e71574c9b Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Thu, 25 Aug 2016 17:51:13 +0800 Subject: [PATCH 205/268] improve api doc --- cocos2d/core/load-pipeline/CCLoader.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/load-pipeline/CCLoader.js b/cocos2d/core/load-pipeline/CCLoader.js index 9168bf4210..38feb9da4a 100644 --- a/cocos2d/core/load-pipeline/CCLoader.js +++ b/cocos2d/core/load-pipeline/CCLoader.js @@ -288,7 +288,7 @@ JS.mixin(CCLoader.prototype, { * cc.log('Result should be a prefab: ' + (prefab instanceof cc.Prefab)); * }); * - * // load the sprite frame (project/assets/resources/imgs/cocos.png/cocos) from resources folder + * // load the sprite frame of (project/assets/resources/imgs/cocos.png) from resources folder * cc.loader.loadRes('imgs/cocos', cc.SpriteFrame, function (err, spriteFrame) { * if (err) { * cc.error(err.message || err); @@ -353,7 +353,7 @@ JS.mixin(CCLoader.prototype, { * * @example * - * // load the texture (resources/imgs/cocos.png) and sprite frame (resources/imgs/cocos.png/cocos) + * // load the texture (resources/imgs/cocos.png) and the corresponding sprite frame * cc.loader.loadResAll('imgs/cocos', function (err, assets) { * if (err) { * cc.error(err); From 71aa9aaea187367e2f93c9965148073162e99d97 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Thu, 25 Aug 2016 18:28:18 +0800 Subject: [PATCH 206/268] fix jsb effect --- cocos2d/core/components/CCRichText.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/cocos2d/core/components/CCRichText.js b/cocos2d/core/components/CCRichText.js index 295bd6bda3..c5da2965ab 100644 --- a/cocos2d/core/components/CCRichText.js +++ b/cocos2d/core/components/CCRichText.js @@ -381,6 +381,12 @@ var RichText = cc.Class({ this._sgNode.addChild(labelSegment); this._labelSegments.push(labelSegment); + if(CC_JSB) { + labelSegment.setOverflow(1); + var size = labelSegment.getContentSize(); + labelSegment.setContentSize(size.width, this.lineHeight); + } + return labelSegment; }, From 2f4da7092e2ffbbbce93c35af96c9162d6339c66 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Fri, 26 Aug 2016 10:07:08 +0800 Subject: [PATCH 207/268] add RichText to modules.json --- modules.json | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/modules.json b/modules.json index 24fec2d2d5..e3b84c5db5 100644 --- a/modules.json +++ b/modules.json @@ -108,6 +108,12 @@ "./cocos2d/core/components/CCVideoPlayer.js" ] }, + { + "name": "RichText", + "entries": [ + "./cocos2d/core/components/CCRichText.js" + ] + }, { "name": "AudioSource", "entries": [ @@ -153,4 +159,4 @@ "./cocos2d/core/graphics/index.js" ] } -] \ No newline at end of file +] From 5c95065551642ff0f39f5085d3b0ede406d2d180 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Fri, 26 Aug 2016 11:50:56 +0800 Subject: [PATCH 208/268] update i18n and fix some minor issues --- cocos2d/core/components/CCRichText.js | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/cocos2d/core/components/CCRichText.js b/cocos2d/core/components/CCRichText.js index c5da2965ab..ce92bff21f 100644 --- a/cocos2d/core/components/CCRichText.js +++ b/cocos2d/core/components/CCRichText.js @@ -69,6 +69,7 @@ var RichText = cc.Class({ editor: CC_EDITOR && { menu: 'i18n:MAIN_MENU.component.renderers/RichText', + help: 'i18n:COMPONENT.help_url.richtext', }, @@ -80,9 +81,9 @@ var RichText = cc.Class({ * @property {String} string */ string: { - default: 'Label', + default: 'RichText', multiline: true, - tooltip: 'i18n:COMPONENT.label.string', + tooltip: 'i18n:COMPONENT.richtext.string', notify: function () { this._updateRichTextStatus(); } @@ -96,7 +97,7 @@ var RichText = cc.Class({ horizontalAlign: { default: HorizontalAlign.LEFT, type: HorizontalAlign, - tooltip: 'i18n:COMPONENT.label.horizontal_align', + tooltip: 'i18n:COMPONENT.richtext.horizontal_align', animatable: false, notify: function () { this._layoutDirty = true; @@ -111,7 +112,7 @@ var RichText = cc.Class({ */ fontSize: { default: 40, - tooltip: 'i18n:COMPONENT.label.font_size', + tooltip: 'i18n:COMPONENT.richtext.font_size', notify: function () { this._layoutDirty = true; this._updateRichTextStatus(); @@ -125,6 +126,7 @@ var RichText = cc.Class({ */ maxWidth: { default: 0, + tooltip: 'i18n:COMPONENT.richtext.max_width', notify: function () { this._layoutDirty = true; this._updateRichTextStatus(); @@ -138,7 +140,7 @@ var RichText = cc.Class({ */ lineHeight: { default: 40, - tooltip: 'i18n:COMPONENT.label.line_height', + tooltip: 'i18n:COMPONENT.richtext.line_height', notify: function () { this._layoutDirty = true; this._updateRichTextStatus(); @@ -183,17 +185,12 @@ var RichText = cc.Class({ _initSgNode: function () { + this._resetState(); + var sgNode = this._sgNode = new _ccsg.Node(); + sgNode.setVisible(false); sgNode.setCascadeOpacityEnabled(true); - if (this.enabledInHierarchy && !sgNode.isVisible()) { - sgNode.setVisible(true); - } - - if ( !this.enabledInHierarchy ) { - sgNode.setVisible(false); - } - var self = this; sgNode.setColor = function () { self._updateLabelSegmentTextAttributes(); From ad3cf8076ddad9c52fbda672c2839b33870ad60f Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Fri, 26 Aug 2016 14:48:28 +0800 Subject: [PATCH 209/268] add built-in color value support --- cocos2d/core/components/CCRichText.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/components/CCRichText.js b/cocos2d/core/components/CCRichText.js index ce92bff21f..887c12149d 100644 --- a/cocos2d/core/components/CCRichText.js +++ b/cocos2d/core/components/CCRichText.js @@ -628,7 +628,12 @@ var RichText = cc.Class({ textStyle = this._textArray[index].style; } if(textStyle && textStyle.color) { - label.setColor(cc.hexToColor(textStyle.color)); + var colorValue = textStyle.color.toUpperCase(); + if(cc.Color[colorValue]) { + label.setColor(cc.Color[colorValue]); + } else { + label.setColor(cc.hexToColor(textStyle.color)); + } } else { label.setColor(this.node.color); } From df2675bd2c72bab7f1eb6c2f29b8aa21b5698ebc Mon Sep 17 00:00:00 2001 From: zhangbin Date: Fri, 26 Aug 2016 17:21:16 +0800 Subject: [PATCH 210/268] Solve the error when delete TiledMap node & undo the delete action. --- cocos2d/tilemap/CCTiledMap.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/cocos2d/tilemap/CCTiledMap.js b/cocos2d/tilemap/CCTiledMap.js index a262be266b..55c54d4d63 100644 --- a/cocos2d/tilemap/CCTiledMap.js +++ b/cocos2d/tilemap/CCTiledMap.js @@ -751,6 +751,9 @@ var TiledMap = cc.Class({ var ret = sgNode.initWithXML(file.tmxXmlStr, resPath); if (ret) { + // Asset is changed, the layers are recreated. + // The layers of pre asset should be cleaned. + self._detachedLayers.length = 0; self._onMapLoaded(); } } else { From 4a89edb410cb2dc4ee5aad308f89acf4fa7674d4 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Fri, 26 Aug 2016 17:38:38 +0800 Subject: [PATCH 211/268] refactoring --- cocos2d/core/components/CCRichText.js | 47 +++++++------------------- cocos2d/core/label/CCHtmlTextParser.js | 9 ++--- 2 files changed, 15 insertions(+), 41 deletions(-) diff --git a/cocos2d/core/components/CCRichText.js b/cocos2d/core/components/CCRichText.js index 887c12149d..99ea3f94df 100644 --- a/cocos2d/core/components/CCRichText.js +++ b/cocos2d/core/components/CCRichText.js @@ -65,6 +65,12 @@ var RichText = cc.Class({ this._textArray = null; this._resetState(); + + if(CC_EDITOR) { + this._updateRichTextStatus = debounce(this._updateRichText, 200); + } else { + this._updateRichTextStatus = this._updateRichText; + } }, editor: CC_EDITOR && { @@ -74,7 +80,6 @@ var RichText = cc.Class({ properties: { - _useOriginalSize: true, /** * !#en Content string of RichText. * !#zh 富文本显示的文本内容。 @@ -148,33 +153,21 @@ var RichText = cc.Class({ } }, - _updateRichTextStatus: function () { - if(this._sgNode) { - if(CC_EDITOR) { - this._debouncedUpdateRichText(); - } else { - this._updateRichText(); - } - } - }, - statics: { HorizontalAlign: HorizontalAlign, VerticalAlign: VerticalAlign }, - _createSgNode: function () { - return null; - }, - __preload: function () { this._super(); - if(CC_EDITOR) { - this._debouncedUpdateRichText = debounce(this._updateRichText, 200); - } else { + + if (!CC_EDITOR) { this._registerEvents(); } + }, + _createSgNode: function () { + return new _ccsg.Node(); }, _updateLabelSegmentTextAttributes: function() { @@ -184,11 +177,7 @@ var RichText = cc.Class({ }, _initSgNode: function () { - - this._resetState(); - - var sgNode = this._sgNode = new _ccsg.Node(); - sgNode.setVisible(false); + var sgNode = this._sgNode; sgNode.setCascadeOpacityEnabled(true); var self = this; @@ -200,10 +189,6 @@ var RichText = cc.Class({ sgNode.setContentSize = function () {}; this._updateRichText(); - - if(CC_JSB) { - sgNode.retain(); - } }, _computeAlignmentOffset: function() { @@ -648,14 +633,6 @@ var RichText = cc.Class({ if(textStyle.event.click) { label._clickHandler = textStyle.event.click; } - - if(textStyle.event.hoverin) { - label._hoverinHandler = textStyle.event.hoverin; - } - - if(textStyle.event.hoverout) { - label._hoveroutHandler = textStyle.event.hoverout; - } } } diff --git a/cocos2d/core/label/CCHtmlTextParser.js b/cocos2d/core/label/CCHtmlTextParser.js index 92f57fc040..633714f92d 100644 --- a/cocos2d/core/label/CCHtmlTextParser.js +++ b/cocos2d/core/label/CCHtmlTextParser.js @@ -22,6 +22,7 @@ THE SOFTWARE. ****************************************************************************/ +var eventRegx = /^(click)(\s)*=/; /** * A utils class for parsing HTML texts. The parsed results will be an object array. */ @@ -134,7 +135,7 @@ cc.HtmlTextParser.prototype = { _processEventHandler: function (eventString) { var index = 0; var obj = {}; - var eventNames = eventString.match(this._getEventRegx()); + var eventNames = eventString.match(eventRegx); var isValidTag = false; while(eventNames) { var eventName = eventNames[0]; @@ -172,7 +173,7 @@ cc.HtmlTextParser.prototype = { } eventString = eventString.substring(index).trim(); - eventNames = eventString.match(this._getEventRegx()); + eventNames = eventString.match(eventRegx); } return obj; @@ -208,10 +209,6 @@ cc.HtmlTextParser.prototype = { } }, - _getEventRegx: function () { - return /^(click)(\s)*=/; - }, - _escapeSpecialSymbol: function(str) { for(var i = 0; i < this._specialSymbolArray.length; ++i) { var key = this._specialSymbolArray[i][0]; From 5c2adc05390e6cc6076d4a994d7e777bfd8e8f0a Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Fri, 26 Aug 2016 17:52:42 +0800 Subject: [PATCH 212/268] refine lineOffsetX calculation --- cocos2d/core/components/CCRichText.js | 39 ++++++++++----------------- 1 file changed, 14 insertions(+), 25 deletions(-) diff --git a/cocos2d/core/components/CCRichText.js b/cocos2d/core/components/CCRichText.js index 99ea3f94df..9191ac9a55 100644 --- a/cocos2d/core/components/CCRichText.js +++ b/cocos2d/core/components/CCRichText.js @@ -191,29 +191,6 @@ var RichText = cc.Class({ this._updateRichText(); }, - _computeAlignmentOffset: function() { - this._linesOffsetX = []; - switch (this.horizontalAlign) { - case cc.TextAlignment.LEFT: - for (var i = 0; i < this._lineCount; ++i) { - this._linesOffsetX.push(0); - } - break; - case cc.TextAlignment.CENTER: - this._linesWidth.forEach(function(lineWidth) { - this._linesOffsetX.push((this._labelWidth - lineWidth) / 2); - }.bind(this)); - break; - case cc.TextAlignment.RIGHT: - this._linesWidth.forEach(function(lineWidth) { - this._linesOffsetX.push(this._labelWidth - lineWidth); - }.bind(this)); - break; - default: - break; - } - }, - _measureText: function (string, styleIndex) { var label = new _ccsg.Label(string); label._styleIndex = styleIndex; @@ -575,7 +552,6 @@ var RichText = cc.Class({ }, _updateRichTextPosition: function () { - this._computeAlignmentOffset(); var nextTokenX = 0; var nextLineIndex = 1; @@ -587,7 +563,20 @@ var RichText = cc.Class({ nextTokenX = 0; nextLineIndex = lineCount; } - var lineOffsetX = this._linesOffsetX[lineCount - 1]; + var lineOffsetX = 0; + switch (this.horizontalAlign) { + case cc.TextAlignment.LEFT: + lineOffsetX = 0; + break; + case cc.TextAlignment.CENTER: + lineOffsetX = (this._labelWidth - this._linesWidth[lineCount - 1]) / 2; + break; + case cc.TextAlignment.RIGHT: + lineOffsetX = this._labelWidth - this._linesWidth[lineCount - 1]; + break; + default: + break; + } label.setPositionX(nextTokenX + lineOffsetX); var labelSize = label.getContentSize(); From a15c2cf750824face5412473fbc6c75a28aeb437 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Mon, 29 Aug 2016 16:47:23 +0800 Subject: [PATCH 213/268] add bold and italic support --- cocos2d/core/components/CCLabel.js | 27 +++++++++++++++++ cocos2d/core/label/CCSGLabel.js | 19 ++++++++++++ .../core/label/CCSGLabelCanvasRenderCmd.js | 29 ++++++++++++++----- 3 files changed, 68 insertions(+), 7 deletions(-) diff --git a/cocos2d/core/components/CCLabel.js b/cocos2d/core/components/CCLabel.js index abafc3fe0f..7b911b3315 100644 --- a/cocos2d/core/components/CCLabel.js +++ b/cocos2d/core/components/CCLabel.js @@ -408,6 +408,33 @@ var Label = cc.Class({ tooltip: 'i18n:COMPONENT.label.system_font', }, + bold: { + default: false, + notify: function () { + if(this._sgNode) { + this._sgNode.enableBold(this.bold); + } + } + }, + + italic: { + default: false, + notify: function () { + if(this._sgNode) { + this._sgNode.enableItalics(this.italic); + } + } + }, + + underline: { + default: false, + notify: function () { + if(this._sgNode) { + this._sgNode.enableUnderline(this.underline); + } + } + }, + _bmFontOriginalSize: { displayName: 'BMFont Original Size', default: -1, diff --git a/cocos2d/core/label/CCSGLabel.js b/cocos2d/core/label/CCSGLabel.js index 12942e0326..eca1841c44 100644 --- a/cocos2d/core/label/CCSGLabel.js +++ b/cocos2d/core/label/CCSGLabel.js @@ -131,6 +131,10 @@ _ccsg.Label = _ccsg.Node.extend({ _className: "Label", //used for left and right margin _margin : 0, + //bold,italic, underline + _isBold: false, + _isItalic: false, + _isUnderline: false, //fontHandle it is a system font name, ttf file path or bmfont file path. ctor: function(string, fontHandle, textureUrl) { @@ -234,6 +238,21 @@ _ccsg.Label = _ccsg.Node.extend({ this._notifyLabelSkinDirty(); }, + enableItalics: function (enabled) { + this._isItalic = enabled; + this._notifyLabelSkinDirty(); + }, + + enableBold: function (enabled) { + this._isBold = enabled; + this._notifyLabelSkinDirty(); + }, + + enableUnderline: function (enabled) { + this._isUnderline = enabled; + this._notifyLabelSkinDirty(); + }, + isWrapTextEnabled: function() { return this._isWrapText; }, diff --git a/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js b/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js index c96985fd4a..22e3ca91a1 100644 --- a/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js +++ b/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js @@ -1,3 +1,5 @@ +/*global dirtyFlags */ + /**************************************************************************** Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2011-2012 cocos2d-x.org @@ -201,14 +203,28 @@ return wrappedWords; }; + proto._constructFontDesc = function () { + var node = this._node; + var fontDesc = node._fontSize.toString() + 'px '; + var fontFamily = node._fontHandle.length === 0 ? 'serif' : node._fontHandle; + fontDesc = fontDesc + fontFamily; + if(node._isBold) { + fontDesc = "bold " + fontDesc; + } + + if(node._isItalic) { + fontDesc = "italic " + fontDesc; + } + + return fontDesc; + }; + proto._calculateLabelFont = function() { var node = this._node; var paragraphedStrings = node._string.split('\n'); - var fontDesc = this._drawFontsize.toString() + 'px '; - var fontFamily = node._fontHandle.length === 0 ? 'serif' : node._fontHandle; - fontDesc = fontDesc + fontFamily; + var fontDesc = this._constructFontDesc(); this._labelContext.font = fontDesc; var paragraphLength = this._calculateParagraphLength(paragraphedStrings, this._labelContext); @@ -224,7 +240,7 @@ var canvasWidthNoMargin = this._canvasSize.width - 2 * this._getMargin(); var canvasHeightNoMargin = this._canvasSize.height - 2 * this._getMargin(); if(canvasWidthNoMargin < 0 || canvasHeightNoMargin < 0) { - fontDesc = '1px ' + fontFamily; + fontDesc = this._constructFontDesc(); this._labelContext.font = fontDesc; return fontDesc; } @@ -247,8 +263,7 @@ break; } node._fontSize = actualFontSize; - fontDesc = actualFontSize.toString() + 'px ' + fontFamily; - this._labelContext.font = fontDesc; + this._labelContext.font = this._constructFontDesc(); this._splitedStrings = []; totalHeight = 0; @@ -288,7 +303,7 @@ var scaleY = this._canvasSize.height / totalHeight; node._fontSize = (this._drawFontsize * Math.min(1, scaleX, scaleY)) | 0; - fontDesc = node._fontSize.toString() + 'px ' + fontFamily; + fontDesc = this._constructFontDesc(); } } From 02e10f089925a2d5d6548400ca17749792f68d3a Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Mon, 29 Aug 2016 18:57:56 +0800 Subject: [PATCH 214/268] fix asset-watcher --- cocos2d/core/components/CCComponent.js | 7 ++++--- cocos2d/core/components/CCSprite.js | 13 ++++++++++--- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/cocos2d/core/components/CCComponent.js b/cocos2d/core/components/CCComponent.js index 0c0d70444c..f278c7ca24 100644 --- a/cocos2d/core/components/CCComponent.js +++ b/cocos2d/core/components/CCComponent.js @@ -236,9 +236,10 @@ var Component = cc.Class({ name: 'cc.Component', extends: cc.Object, - ctor: (CC_EDITOR && window._Scene && _Scene.AssetsWatcher) ? function () { - _Scene.AssetsWatcher.initComponent(this); - + ctor: CC_EDITOR ? function () { + if (window._Scene && _Scene.AssetsWatcher) { + _Scene.AssetsWatcher.initComponent(this); + } // Support for Scheduler this.__instanceId = cc.ClassManager.getNewInstanceId(); } : function () { diff --git a/cocos2d/core/components/CCSprite.js b/cocos2d/core/components/CCSprite.js index 055b2fffbe..0dd40826b0 100644 --- a/cocos2d/core/components/CCSprite.js +++ b/cocos2d/core/components/CCSprite.js @@ -163,10 +163,17 @@ var Sprite = cc.Class({ return this._spriteFrame; }, set: function (value, force) { - if (this._spriteFrame === value) { - return; - } var lastSprite = this._spriteFrame; + if (CC_EDITOR) { + if (!force && ((lastSprite && lastSprite._uuid) === (value && value._uuid))) { + return; + } + } + else { + if (lastSprite === value) { + return; + } + } this._spriteFrame = value; this._applySpriteFrame(lastSprite); if (CC_EDITOR) { From 66fa31d3e1fde55fc2b467c263e4630181e8adbc Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Tue, 30 Aug 2016 11:06:32 +0800 Subject: [PATCH 215/268] add bold/italic/underline support --- cocos2d/core/components/CCLabel.js | 27 -------------- .../core/label/CCSGLabelCanvasRenderCmd.js | 37 +++++++++++++++++-- jsb/jsb-label.js | 27 ++++++++++++++ 3 files changed, 61 insertions(+), 30 deletions(-) diff --git a/cocos2d/core/components/CCLabel.js b/cocos2d/core/components/CCLabel.js index 7b911b3315..abafc3fe0f 100644 --- a/cocos2d/core/components/CCLabel.js +++ b/cocos2d/core/components/CCLabel.js @@ -408,33 +408,6 @@ var Label = cc.Class({ tooltip: 'i18n:COMPONENT.label.system_font', }, - bold: { - default: false, - notify: function () { - if(this._sgNode) { - this._sgNode.enableBold(this.bold); - } - } - }, - - italic: { - default: false, - notify: function () { - if(this._sgNode) { - this._sgNode.enableItalics(this.italic); - } - } - }, - - underline: { - default: false, - notify: function () { - if(this._sgNode) { - this._sgNode.enableUnderline(this.underline); - } - } - }, - _bmFontOriginalSize: { displayName: 'BMFont Original Size', default: -1, diff --git a/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js b/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js index 22e3ca91a1..7599f8ced2 100644 --- a/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js +++ b/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js @@ -460,9 +460,28 @@ }; - // proto._updateColor = function() { - // this._rebuildLabelSkin(); - // }; + + proto._calculateUnderlineStartPosition = function () { + var node = this._node; + var lineHeight = this._getLineHeight(); + var lineCount = this._splitedStrings.length; + var labelX; + var firstLinelabelY; + + labelX = 0 + this._getMargin(); + + if (cc.VerticalTextAlignment.TOP === node._vAlign) { + firstLinelabelY = node._fontSize; + } + else if (cc.VerticalTextAlignment.CENTER === node._vAlign) { + firstLinelabelY = this._canvasSize.height / 2 - lineHeight * (lineCount - 1) / 2 + node._fontSize / 2; + } + else { + firstLinelabelY = this._canvasSize.height - lineHeight * (lineCount - 1); + } + + return cc.p(labelX, firstLinelabelY); + }; proto._updateTexture = function() { this._labelContext.clearRect(0, 0, this._labelCanvas.width, this._labelCanvas.height); @@ -475,6 +494,7 @@ this._labelContext.lineJoin = 'round'; var color = this._displayedColor; this._labelContext.fillStyle = 'rgb(' + color.r + ',' + color.g + ',' + color.b + ')'; + var underlineStartPosition; //do real rendering for (var i = 0; i < this._splitedStrings.length; ++i) { @@ -488,6 +508,17 @@ startPosition.x, startPosition.y + i * lineHeight); } this._labelContext.fillText(this._splitedStrings[i], startPosition.x, startPosition.y + i * lineHeight); + if(this._node._isUnderline) { + underlineStartPosition = this._calculateUnderlineStartPosition(); + this._labelContext.save(); + this._labelContext.beginPath(); + this._labelContext.lineWidth = this._node._fontSize / 8; + this._labelContext.strokeStyle = 'rgb(' + color.r + ',' + color.g + ',' + color.b + ')'; + this._labelContext.moveTo(underlineStartPosition.x, underlineStartPosition.y + i * lineHeight - 2); + this._labelContext.lineTo(underlineStartPosition.x + this._labelCanvas.width, underlineStartPosition.y + i * lineHeight - 2); + this._labelContext.stroke(); + this._labelContext.restore(); + } } this._texture._textureLoaded = false; diff --git a/jsb/jsb-label.js b/jsb/jsb-label.js index f8ef6d264b..2532465ae6 100644 --- a/jsb/jsb-label.js +++ b/jsb/jsb-label.js @@ -58,6 +58,33 @@ jsbLabel.prototype.getOverflow = function() { return this._overFlow; }; +jsbLabel.prototype._enableBold = jsbLabel.prototype.enableBold; +jsbLabel.prototype.enableBold = function(enabled) { + if(enabled) { + this._enableBold(); + } else { + this.disableEffect(5); + } +}; + +jsbLabel.prototype._enableItalics = jsbLabel.prototype.enableItalics; +jsbLabel.prototype.enableItalics = function(enabled) { + if(enabled) { + this._enableItalics(); + } else { + this.disableEffect(4); + } +}; + +jsbLabel.prototype._enableUnderline = jsbLabel.prototype.enableUnderline; +jsbLabel.prototype.enableUnderline = function(enabled) { + if(enabled) { + this._enableUnderline(); + } else { + this.disableEffect(6); + } +}; + jsbLabel.prototype.setFontSize = function (size) { this._fontSize = size; if (this._labelType === _ccsg.Label.Type.SystemFont) { From eb454e5ce0a9c7592f72bd8df9f7339abd08a899 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Tue, 30 Aug 2016 11:25:24 +0800 Subject: [PATCH 216/268] add richtext bold/italics/underline --- cocos2d/core/components/CCRichText.js | 12 ++++++++++++ cocos2d/core/label/CCSGLabelCanvasRenderCmd.js | 4 ++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/components/CCRichText.js b/cocos2d/core/components/CCRichText.js index 9191ac9a55..f390fcf451 100644 --- a/cocos2d/core/components/CCRichText.js +++ b/cocos2d/core/components/CCRichText.js @@ -612,6 +612,18 @@ var RichText = cc.Class({ label.setColor(this.node.color); } + if(textStyle && textStyle.bold) { + label.enableBold(true); + } + + if(textStyle && textStyle.italic) { + label.enableItalics(true); + } + + if(textStyle && textStyle.underline) { + label.enableUnderline(true); + } + if(textStyle && textStyle.size) { label.setFontSize(textStyle.size); } else { diff --git a/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js b/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js index 7599f8ced2..d48508ad01 100644 --- a/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js +++ b/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js @@ -514,8 +514,8 @@ this._labelContext.beginPath(); this._labelContext.lineWidth = this._node._fontSize / 8; this._labelContext.strokeStyle = 'rgb(' + color.r + ',' + color.g + ',' + color.b + ')'; - this._labelContext.moveTo(underlineStartPosition.x, underlineStartPosition.y + i * lineHeight - 2); - this._labelContext.lineTo(underlineStartPosition.x + this._labelCanvas.width, underlineStartPosition.y + i * lineHeight - 2); + this._labelContext.moveTo(underlineStartPosition.x, underlineStartPosition.y + i * lineHeight - 1); + this._labelContext.lineTo(underlineStartPosition.x + this._labelCanvas.width, underlineStartPosition.y + i * lineHeight - 1); this._labelContext.stroke(); this._labelContext.restore(); } From 3f87d5b5fa1e2bb85bcd70f9072429c70feb98fe Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Tue, 30 Aug 2016 11:58:15 +0800 Subject: [PATCH 217/268] fix italic bold underline of richtext --- cocos2d/core/components/CCRichText.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/components/CCRichText.js b/cocos2d/core/components/CCRichText.js index f390fcf451..cd9cc0bcfa 100644 --- a/cocos2d/core/components/CCRichText.js +++ b/cocos2d/core/components/CCRichText.js @@ -429,7 +429,6 @@ var RichText = cc.Class({ } else { if (oldItem.style) { if (newItem.style) { - //TODO: add more when adding bold/italic/underline if(oldItem.style.size != newItem.style.size) { return true; } @@ -596,6 +595,9 @@ var RichText = cc.Class({ var index = label._styleIndex; label.setLineHeight(this.lineHeight); label.setVerticalAlign(VerticalAlign.CENTER); + label.enableBold(false); + label.enableItalics(false); + label.enableUnderline(false); var textStyle = null; if(this._textArray[index]) { From 771b92d26a03631da9d58f6912f2dce4e32a1e57 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Tue, 30 Aug 2016 13:34:27 +0800 Subject: [PATCH 218/268] minor fix of Button docs --- cocos2d/core/components/CCButton.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/components/CCButton.js b/cocos2d/core/components/CCButton.js index b1be6c7133..421ae56ff5 100644 --- a/cocos2d/core/components/CCButton.js +++ b/cocos2d/core/components/CCButton.js @@ -299,10 +299,10 @@ var Button = cc.Class({ * If Transition type is Button.Transition.SPRITE, Button will change target Sprite's sprite * !#zh * 需要过渡的目标。 - * 当前按钮状态改变有: + * 当前按钮状态改变规则: * -如果 Transition type 选择 Button.Transition.NONE,按钮不做任何过渡。 * -如果 Transition type 选择 Button.Transition.COLOR,按钮会对目标颜色进行颜色之间的过渡。 - * -如果 Transition type 选择 Button.Transition.NONE,按钮会对目标 Sprite 进行 Sprite 之间的过渡。 + * -如果 Transition type 选择 Button.Transition.Sprite,按钮会对目标 Sprite 进行 Sprite 之间的过渡。 * @property {Node} target */ target: { From c8565e217ea7c3fc104c8b81e37fc5abd125d161 Mon Sep 17 00:00:00 2001 From: 2youyouo2 <501251991@qq.com> Date: Tue, 30 Aug 2016 14:46:58 +0800 Subject: [PATCH 219/268] fixed typo --- cocos2d/core/graphics/graphics-webgl-cmd.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/graphics/graphics-webgl-cmd.js b/cocos2d/core/graphics/graphics-webgl-cmd.js index 18c79e62f8..63baed8035 100644 --- a/cocos2d/core/graphics/graphics-webgl-cmd.js +++ b/cocos2d/core/graphics/graphics-webgl-cmd.js @@ -30,7 +30,7 @@ var LineJoin = require('./types').LineJoin; var Earcut = require('./earcut'); -var Helper = require('./Helper'); +var Helper = require('./helper'); var Vec2 = cc.Vec2; var Js = cc.js; From e467bf1f58f1d11cd3405d91651f97332a4ca068 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Wed, 31 Aug 2016 09:29:46 +0800 Subject: [PATCH 220/268] add getAllTextures for CCTextureCache for fireball/issues/2836 --- cocos2d/core/platform/CCView.js | 5 ++--- cocos2d/core/textures/CCTextureCache.js | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/platform/CCView.js b/cocos2d/core/platform/CCView.js index 86df5e28b0..646b8a3d49 100644 --- a/cocos2d/core/platform/CCView.js +++ b/cocos2d/core/platform/CCView.js @@ -151,7 +151,7 @@ var View = cc._Class.extend({ __resizeWithBrowserSize: false, _isAdjustViewPort: true, _targetDensityDPI: null, - _antiAliasEnabled: false, + _antiAliasEnabled: true, /** * Constructor of View @@ -184,7 +184,6 @@ var View = cc._Class.extend({ _t._rpFixedWidth = new cc.ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.FIXED_WIDTH); _t._targetDensityDPI = cc.macro.DENSITYDPI_HIGH; - _t.enableAntiAlias(true); }, // Resize helper functions @@ -469,7 +468,7 @@ var View = cc._Class.extend({ * !#en Returns whether the current enable on anti-alias * !#zh 返回当前是否抗锯齿 * @method isAntiAliasEnabled - * @param {Boolean} enabled - Pass false to make pixel art sharp. + * @return {Boolean} */ isAntiAliasEnabled: function () { return this._antiAliasEnabled; diff --git a/cocos2d/core/textures/CCTextureCache.js b/cocos2d/core/textures/CCTextureCache.js index 54bd675522..ac6650163b 100644 --- a/cocos2d/core/textures/CCTextureCache.js +++ b/cocos2d/core/textures/CCTextureCache.js @@ -125,6 +125,21 @@ var textureCache = /** @lends cc.textureCache# */{ return this._textureColorsCache[key]; }, + /** + * #en get all textures + * #zh 获取所有贴图 + * @method getAllTextures + * @return {Texture2D[]} + */ + getAllTextures: function () { + var texs = []; + for (var key in this._textures) { + var item = this._textures[key]; + texs.push(item); + } + return texs; + }, + /** *

Purges the dictionary of loaded textures.
* Call this method if you receive the "Memory Warning"
From 8bc2220233f4b8138c2209c70adeae2cc29cf815 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Wed, 10 Aug 2016 15:51:53 +0800 Subject: [PATCH 221/268] fix editbox maxLength on PC --- cocos2d/core/editbox/CCSGEditBox.js | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/cocos2d/core/editbox/CCSGEditBox.js b/cocos2d/core/editbox/CCSGEditBox.js index 82647dd0c0..3d779c8a65 100644 --- a/cocos2d/core/editbox/CCSGEditBox.js +++ b/cocos2d/core/editbox/CCSGEditBox.js @@ -581,10 +581,18 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; 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) { - editBox._text = this.value; - thisPointer._updateEditBoxContentStyle(); - editBox._delegate.editBoxTextChanged(editBox, editBox._text); + if (editBox._text.toLowerCase() !== this.value.toLowerCase()) { + editBox._text = this.value; + thisPointer._updateEditBoxContentStyle(); + editBox._delegate.editBoxTextChanged(editBox, editBox._text); + } } }); tmpEdTxt.addEventListener('keypress', function (e) { @@ -597,6 +605,7 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; this.style.fontSize = editBox._placeholderFontSize + 'px'; this.style.color = cc.colorToHex(editBox._placeholderColor); } + editBox._text = this.value; thisPointer._updateEditBoxContentStyle(); thisPointer.hidden(); @@ -670,11 +679,17 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; tmpEdTxt.style.className = "cocosEditBox"; 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) { - editBox._text = this.value; - thisPointer._updateEditBoxContentStyle(); - editBox._delegate.editBoxTextChanged(editBox, editBox._text); + if(editBox._text.toLowerCase() !== this.value.toLowerCase()) { + editBox._text = this.value; + thisPointer._updateEditBoxContentStyle(); + editBox._delegate.editBoxTextChanged(editBox, editBox._text); + } } }); From ca69aaf1fed1c646fc2ad9f6818fb76cd595e3d9 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Wed, 31 Aug 2016 16:12:30 +0800 Subject: [PATCH 222/268] add touch up event to scrollview --- cocos2d/core/components/CCScrollView.js | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/components/CCScrollView.js b/cocos2d/core/components/CCScrollView.js index 33b34d1fc6..5f27b68f40 100644 --- a/cocos2d/core/components/CCScrollView.js +++ b/cocos2d/core/components/CCScrollView.js @@ -103,7 +103,13 @@ var EventType = cc.Enum({ * !#zh 滚动视图滚动滚动结束的时候发出的事件 * @property {Number} AUTOSCROLL_ENDED */ - AUTOSCROLL_ENDED : 9 + AUTOSCROLL_ENDED : 9, + /** + * !#en The event emmitted when user release the touch + * !#zh 当用户松手的时候会发出一个事件 + * @property {Number} TOUCH_UP + */ + TOUCH_UP : 10 }); /** @@ -885,6 +891,7 @@ var ScrollView = cc.Class({ if (this.content) { this._handleReleaseLogic(touch); } + this._dispatchEvent(EventType.TOUCH_UP); if (this._touchMoved) { event.stopPropagation(); } From e43fe1d47f27155a9d34380ab0add01e5804bbd4 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Wed, 31 Aug 2016 16:27:13 +0800 Subject: [PATCH 223/268] fix scrollview enable event handling --- cocos2d/core/components/CCScrollView.js | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/cocos2d/core/components/CCScrollView.js b/cocos2d/core/components/CCScrollView.js index 33b34d1fc6..0bc2a0c41c 100644 --- a/cocos2d/core/components/CCScrollView.js +++ b/cocos2d/core/components/CCScrollView.js @@ -698,6 +698,8 @@ var ScrollView = cc.Class({ }, _onMouseWheel: function(event) { + if (!this.enabledInHierarchy) return; + var deltaMove = cc.p(0, 0); var wheelPrecision = 1.0 / 40; if(CC_JSB) { @@ -847,6 +849,8 @@ var ScrollView = cc.Class({ // touch event handler _onTouchBegan: function(event) { + if (!this.enabledInHierarchy) return; + var touch = event.touch; if (this.content) { this._handlePressLogic(touch); @@ -855,6 +859,8 @@ var ScrollView = cc.Class({ }, _onTouchMoved: function(event) { + if (!this.enabledInHierarchy) return; + var touch = event.touch; if (this.content) { this._handleMoveLogic(touch); @@ -881,6 +887,8 @@ var ScrollView = cc.Class({ }, _onTouchEnded: function(event) { + if (!this.enabledInHierarchy) return; + var touch = event.touch; if (this.content) { this._handleReleaseLogic(touch); @@ -890,6 +898,8 @@ var ScrollView = cc.Class({ } }, _onTouchCancelled: function(event) { + if (!this.enabledInHierarchy) return; + // Filte touch cancel event send from self if (!event.simulate) { var touch = event.touch; From f893152aa21af12a87ac20e04a02afeac8862347 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Wed, 31 Aug 2016 17:58:16 +0800 Subject: [PATCH 224/268] fix shrink bug --- cocos2d/core/label/CCSGLabelCanvasRenderCmd.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js b/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js index d48508ad01..045359499c 100644 --- a/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js +++ b/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js @@ -263,7 +263,8 @@ break; } node._fontSize = actualFontSize; - this._labelContext.font = this._constructFontDesc(); + fontDesc = this._constructFontDesc(); + this._labelContext.font = fontDesc; this._splitedStrings = []; totalHeight = 0; From 61e699eaa28d9e665ff67717236c1c6b34e97fb8 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 2 Aug 2016 17:58:20 +0800 Subject: [PATCH 225/268] Improve Action management in JSB --- cocos2d/core/CCNode.js | 2 +- jsb/jsb-action.js | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index 3a928d006d..d15f781ba9 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -524,7 +524,7 @@ var Node = cc.Class({ } // Actions - this.stopAllActions(); + cc.director.getActionManager().removeAllActionsFromTarget(this); this._releaseAllActions(); // Remove Node.currentHovered diff --git a/jsb/jsb-action.js b/jsb/jsb-action.js index f48501f545..a0dd2ecafd 100644 --- a/jsb/jsb-action.js +++ b/jsb/jsb-action.js @@ -343,9 +343,7 @@ function syncColorUpdate (dt) { // Sub classes must be registered before their super class. // Otherwise, JSB there will be internal Error: "too much recursion". var actionUpdate = { - 'MoveTo': syncPositionUpdate, 'MoveBy': syncPositionUpdate, - 'JumpTo': syncPositionUpdate, 'JumpBy': syncPositionUpdate, 'Place': syncPositionUpdate, 'CardinalSplineTo': syncPositionUpdate, From a5a0e308a71cf90cbae9967dda69101dcffe1256 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 11 Aug 2016 15:25:57 +0800 Subject: [PATCH 226/268] Upgrade API with v3.13 --- .../base-nodes/BaseNodesPropertyDefine.js | 2 +- cocos2d/core/base-nodes/CCSGNode.js | 29 ++++++------------- cocos2d/core/components/CCRendererInSG.js | 2 +- cocos2d/core/components/CCRendererUnderSG.js | 2 +- cocos2d/core/sprites/CCSGSprite.js | 8 ++--- cocos2d/core/utils/base-node.js | 10 +++---- cocos2d/deprecated.js | 5 ++-- jsb/jsb-etc.js | 1 - 8 files changed, 24 insertions(+), 35 deletions(-) diff --git a/cocos2d/core/base-nodes/BaseNodesPropertyDefine.js b/cocos2d/core/base-nodes/BaseNodesPropertyDefine.js index ef525bdaa7..f788df4b5b 100644 --- a/cocos2d/core/base-nodes/BaseNodesPropertyDefine.js +++ b/cocos2d/core/base-nodes/BaseNodesPropertyDefine.js @@ -48,7 +48,7 @@ cc._tmp.PrototypeCCNode = function () { cc.defineGetterSetter(_p, "parent", _p.getParent, _p.setParent); cc.defineGetterSetter(_p, "visible", _p.isVisible, _p.setVisible); cc.defineGetterSetter(_p, "running", _p.isRunning); - cc.defineGetterSetter(_p, "ignoreAnchor", _p.isIgnoreAnchorPointForPosition, _p.ignoreAnchorPointForPosition); + cc.defineGetterSetter(_p, "ignoreAnchor", _p.isIgnoreAnchorPointForPosition, _p.setIgnoreAnchorPointForPosition); cc.defineGetterSetter(_p, "actionManager", _p.getActionManager, _p.setActionManager); cc.defineGetterSetter(_p, "scheduler", _p.getScheduler, _p.setScheduler); //cc.defineGetterSetter(_p, "boundingBox", _p.getBoundingBox); diff --git a/cocos2d/core/base-nodes/CCSGNode.js b/cocos2d/core/base-nodes/CCSGNode.js index d910e429a5..ad34d5dada 100644 --- a/cocos2d/core/base-nodes/CCSGNode.js +++ b/cocos2d/core/base-nodes/CCSGNode.js @@ -161,7 +161,7 @@ _ccsg.Node = cc.Class({ this._running = false; this._reorderChildDirty = false; this._shaderProgram = null; - this.arrivalOrder = 0; + this._arrivalOrder = 0; this._additionalTransformDirty = false; this._isTransitionFinished = false; @@ -892,7 +892,7 @@ _ccsg.Node = cc.Class({ * @function * @param {Boolean} newValue true if anchor point will be ignored when you position this node */ - ignoreAnchorPointForPosition: function (newValue) { + setIgnoreAnchorPointForPosition: function (newValue) { if (newValue !== this._ignoreAnchorPointForPosition) { this._ignoreAnchorPointForPosition = newValue; this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.transformDirty); @@ -958,28 +958,18 @@ _ccsg.Node = cc.Class({ return this._name; }, - /** - * Returns the arrival order, indicates which children should be added previously. - * @function - * @return {Number} The arrival order. - */ - getOrderOfArrival: function () { - return this.arrivalOrder; - }, - /** *

- * Sets the arrival order when this node has a same ZOrder with other children.
+ * Update the arrival order.
*
* A node which called addChild subsequently will take a larger arrival order,
* If two children have the same Z order, the child with larger arrival order will be drawn later. *

* @function - * @warning This method is used internally for zOrder sorting, don't change this manually - * @param {Number} Var The arrival order. + * @warning This method is used internally for zOrder sorting, don't call this method manually */ - setOrderOfArrival: function (Var) { - this.arrivalOrder = Var; + updateOrderOfArrival: function () { + this._arrivalOrder = ++cc.s_globalOrderOfArrival; }, /** @@ -1154,7 +1144,7 @@ _ccsg.Node = cc.Class({ child.setName(name); child.setParent(this); - child.setOrderOfArrival(cc.s_globalOrderOfArrival++); + child.updateOrderOfArrival(); if( this._running ){ child.onEnter(); @@ -1319,8 +1309,7 @@ _ccsg.Node = cc.Class({ reorderChild: function (child, zOrder) { cc.assert(child, cc._LogInfos.Node.reorderChild); cc.renderer.childrenOrderDirty = this._reorderChildDirty = true; - child.arrivalOrder = cc.s_globalOrderOfArrival; - cc.s_globalOrderOfArrival++; + child.updateOrderOfArrival(); child._setLocalZOrder(zOrder); this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.orderDirty); }, @@ -1347,7 +1336,7 @@ _ccsg.Node = cc.Class({ 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){ + }else if(tmp._localZOrder === _children[j]._localZOrder && tmp._arrivalOrder < _children[j]._arrivalOrder){ _children[j+1] = _children[j]; }else{ break; diff --git a/cocos2d/core/components/CCRendererInSG.js b/cocos2d/core/components/CCRendererInSG.js index 57476afe85..d2b212914f 100644 --- a/cocos2d/core/components/CCRendererInSG.js +++ b/cocos2d/core/components/CCRendererInSG.js @@ -123,8 +123,8 @@ var RendererInSG = cc.Class({ if (parentNode) { parentNode.removeChild(replaced); parentNode.addChild(sgNode); - sgNode.arrivalOrder = replaced.arrivalOrder; if ( !CC_JSB ) { + sgNode._arrivalOrder = replaced._arrivalOrder; cc.renderer.childrenOrderDirty = parentNode._reorderChildDirty = true; } } diff --git a/cocos2d/core/components/CCRendererUnderSG.js b/cocos2d/core/components/CCRendererUnderSG.js index fbbee4c901..54e71fdc4f 100644 --- a/cocos2d/core/components/CCRendererUnderSG.js +++ b/cocos2d/core/components/CCRendererUnderSG.js @@ -93,7 +93,7 @@ var RendererUnderSG = cc.Class({ } sgNode.setAnchorPoint(node._anchorPoint); - sgNode.ignoreAnchorPointForPosition(node.__ignoreAnchor); + sgNode.setIgnoreAnchorPointForPosition(node.__ignoreAnchor); sgNode.setOpacityModifyRGB(node._opacityModifyRGB); diff --git a/cocos2d/core/sprites/CCSGSprite.js b/cocos2d/core/sprites/CCSGSprite.js index f7d6488693..c0bde3d40a 100644 --- a/cocos2d/core/sprites/CCSGSprite.js +++ b/cocos2d/core/sprites/CCSGSprite.js @@ -400,12 +400,12 @@ _ccsg.Sprite = _ccsg.Node.extend({ * @param {Boolean} relative * @override */ - ignoreAnchorPointForPosition:function (relative) { + setIgnoreAnchorPointForPosition:function (relative) { if(this._batchNode){ - cc.log(cc._LogInfos.Sprite.ignoreAnchorPointForPosition); + cc.log(cc._LogInfos.Sprite.setIgnoreAnchorPointForPosition); return; } - _ccsg.Node.prototype.ignoreAnchorPointForPosition.call(this, relative); + _ccsg.Node.prototype.setIgnoreAnchorPointForPosition.call(this, relative); }, /** @@ -975,7 +975,7 @@ Object.defineProperty(spritePro, 'visible', { Object.defineProperty(spritePro, 'ignoreAnchor', { get: _ccsg.Node.prototype.isIgnoreAnchorPointForPosition, - set: spritePro.ignoreAnchorPointForPosition + set: spritePro.setIgnoreAnchorPointForPosition }); Object.defineProperty(spritePro, 'opacityModifyRGB', { diff --git a/cocos2d/core/utils/base-node.js b/cocos2d/core/utils/base-node.js index 2e727fd3b3..35cbc414bf 100644 --- a/cocos2d/core/utils/base-node.js +++ b/cocos2d/core/utils/base-node.js @@ -1886,7 +1886,7 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ sibling.setLocalZOrder(zOrder); } else { - sibling.arrivalOrder = i; + sibling._arrivalOrder = i; cc.eventManager._setDirtyForNode(siblings[i]); } } @@ -1943,7 +1943,7 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ if (child._localZOrder < _children[j]._localZOrder) { _children[j+1] = _children[j]; } else if (child._localZOrder === _children[j]._localZOrder && - child._sgNode.arrivalOrder < _children[j]._sgNode.arrivalOrder) { + child._sgNode._arrivalOrder < _children[j]._sgNode._arrivalOrder) { _children[j+1] = _children[j]; } else { break; @@ -1972,11 +1972,11 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ sgNode.setScale(self._scaleX, self._scaleY); sgNode.setSkewX(self._skewX); sgNode.setSkewY(self._skewY); - sgNode.ignoreAnchorPointForPosition(self.__ignoreAnchor); + sgNode.setIgnoreAnchorPointForPosition(self.__ignoreAnchor); - var arrivalOrder = sgNode.arrivalOrder; + var arrivalOrder = sgNode._arrivalOrder; sgNode.setLocalZOrder(self._localZOrder); - sgNode.arrivalOrder = arrivalOrder; // revert arrivalOrder changed in setLocalZOrder + sgNode._arrivalOrder = arrivalOrder; // revert arrivalOrder changed in setLocalZOrder sgNode.setGlobalZOrder(self._globalZOrder); diff --git a/cocos2d/deprecated.js b/cocos2d/deprecated.js index c36d786f4f..e2cc099b37 100644 --- a/cocos2d/deprecated.js +++ b/cocos2d/deprecated.js @@ -398,6 +398,8 @@ if (CC_DEV && typeof eruda === 'undefined') { 'transform', 'getCamera', 'grid', + 'getOrderOfArrival', + 'setOrderOfArrival', 'getGrid', 'setGrid', 'getShaderProgram', @@ -428,8 +430,6 @@ if (CC_DEV && typeof eruda === 'undefined') { _detachChild: 'removeChild', getZOrder: 'getLocalZOrder', setZOrder: 'setLocalZOrder', - getOrderOfArrival: 'getSiblingIndex', - setOrderOfArrival: 'setSiblingIndex', boundingBox: 'getBoundingBox', removeFromParentAndCleanup: 'removeFromParent', removeAllChildrenWithCleanup: 'removeAllChildren', @@ -573,6 +573,7 @@ if (CC_DEV && typeof eruda === 'undefined') { 'setCameraMask', 'getCameraMask' ], '_ccsg.Node'); + js.obsolete(_ccsg.Node.prototype, '_ccsg.Node.ignoreAnchorPointForPosition', 'setIgnoreAnchorPointForPosition'); js.obsoletes(cc.Scale9Sprite.prototype, 'cc.Scale9Sprite', { setPreferredSize: 'setContentSize', diff --git a/jsb/jsb-etc.js b/jsb/jsb-etc.js index 853258faa5..047694e187 100644 --- a/jsb/jsb-etc.js +++ b/jsb/jsb-etc.js @@ -89,7 +89,6 @@ cc.Scheduler.prototype.unschedule = function (callback, target) { // Node var nodeProto = cc.Node.prototype; -cc.defineGetterSetter(nodeProto, "arrivalOrder", nodeProto.getOrderOfArrival, nodeProto.setOrderOfArrival); cc.defineGetterSetter(nodeProto, "_parent", nodeProto.getParent, nodeProto.setParent); // TextureCache addImage From 922c7420ae68fd3613eb09e182f2ca65d5dfa93a Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 1 Sep 2016 10:44:05 +0800 Subject: [PATCH 227/268] Fix initDebugSettings in jsb --- jsb/index.js | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/jsb/index.js b/jsb/index.js index a840eab77a..091abb149e 100644 --- a/jsb/index.js +++ b/jsb/index.js @@ -58,9 +58,7 @@ if (_engineNumberVersion) { cc.initEngine = function (config, cb) { require('script/jsb.js'); cc._renderType = cc.game.RENDER_TYPE_OPENGL; - if (config) { - cc._initDebugSetting(config[cc.game.CONFIG_KEY.debugMode]); - } + cc._initDebugSetting(config ? config[cc.game.CONFIG_KEY.debugMode] : 0); cc._engineLoaded = true; cc.log(cc.ENGINE_VERSION); if (cb) cb(); From 22fe4ca38c1511423d4349424f65d29bdf2d1d89 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 1 Sep 2016 10:44:49 +0800 Subject: [PATCH 228/268] Improve cc.game.end doc --- cocos2d/core/CCGame.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index b79280f93a..30b1efdd2c 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -305,7 +305,9 @@ var game = { }, /** - * End game, it will close the game window + * !#en End game, it will close the game window + * !#zh 退出游戏 + * @method end */ end: function () { close(); From 97da14b4c881b8a1b2da95919b5d25133201ce72 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 1 Sep 2016 21:05:34 +0800 Subject: [PATCH 229/268] review code --- cocos2d/audio/CCAudioEngine.js | 113 ++++++++++++++++++++++- cocos2d/core/CCGame.js | 14 +-- cocos2d/core/components/CCAudioSource.js | 13 ++- 3 files changed, 125 insertions(+), 15 deletions(-) diff --git a/cocos2d/audio/CCAudioEngine.js b/cocos2d/audio/CCAudioEngine.js index 854cc535bb..2ecdad315a 100644 --- a/cocos2d/audio/CCAudioEngine.js +++ b/cocos2d/audio/CCAudioEngine.js @@ -78,7 +78,7 @@ var audioEngine = { _maxAudioInstance: 24, play: function () { - this.play2d.apply(this, arguments); + return this.play2d.apply(this, arguments); }, play2d: function (filePath, loop, volume/*, profile*/) { @@ -254,13 +254,124 @@ var audioEngine = { }, // getProfile + getProfile: function () {}, // preload + preload: function () {}, // web 独占接口 // 设置一个大小,单位为kb,超过这个大小则直接解析成 dom 节点 // 因为 webAudio 占用内存过多,所以让用户自己手动取舍 setMaxWebAudioSize: function (kb) { this._maxWebAudioSize = kb * 1024; + }, + + // deprecated + _musicId: -1, + _backgroundVolume: 1, + _effectsVolume: 1, + willPlayMusic: function () { return false; }, + playMusic: function (url, loop) { + cc.log('audioEngine.playMusic is deprecated, please call audioEngine.play'); + this._musicId = this.play(url, loop, this._backgroundVolume); + return this._musicId; + }, + stopMusic: function () { + cc.log('audioEngine.stopMusic is deprecated, please call audioEngine.stop'); + this.stop(this._musicId); + return this._musicId; + }, + pauseMusic: function () { + cc.log('audioEngine.pauseMusic is deprecated, please call audioEngine.pause'); + this.pause(this._musicId); + return this._musicId; + }, + resumeMusic: function () { + cc.log('audioEngine.resumeMusic is deprecated, please call audioEngine.resume'); + this.resume(this._musicId); + return this._musicId; + }, + rewindMusic: function () { + cc.log('audioEngine.rewindMusic is deprecated, please call audioEngine.setCurrentTime'); + this.setCurrentTime(this._musicId, 0); + return this._musicId; + }, + getMusicVolume: function () { + cc.log('audioEngine.getMusicVolume is deprecated, please call audioEngine.getVolume'); + return this._backgroundVolume; + }, + setMusicVolume: function (volume) { + cc.log('audioEngine.setMusicVolume is deprecated, please call audioEngine.setVolume'); + this._backgroundVolume = volume; + this.setVolume(this._musicId, volume); + return this._backgroundVolume; + }, + isMusicPlaying: function () { + cc.log('audioEngine.isMusicPlaying is deprecated, please call audioEngine.getState'); + return this.getState(this._musicId) === Audio.State.PLAYING; + }, + playEffect: function (url, loop, volume) { + cc.log('audioEngine.playEffect is deprecated, please call audioEngine.play'); + return this.play(url, loop, volume === undefined ? this._effectsVolume : volume); + }, + setEffectsVolume: function (volume) { + cc.log('audioEngine.setEffectsVolume is deprecated, please call audioEngine.setVolume'); + this._effectsVolume = volume; + for (var id in id2audio) { + if (id === this._musicId) continue; + this.setVolume(id, volume); + } + }, + getEffectsVolume: function () { + cc.log('audioEngine.getEffectsVolume is deprecated, please call audioEngine.getVolume'); + return this._effectsVolume; + }, + pauseEffect: function (id) { + cc.log('audioEngine.pauseEffect is deprecated, please call audioEngine.pause'); + return this.pause(id); + }, + pauseAllEffects: function () { + cc.log('audioEngine.pauseAllEffects is deprecated, please call audioEngine.pause'); + for (var id in id2audio) { + if (id === this._musicId) continue; + var audio = id2audio[id]; + var state = audio.getState(); + if (state === Audio.State.PLAYING) { + this._pauseIDCache.push(id); + audio.pause(); + } + } + while (waitQueue.length > 0) { + this._pauseIDCache.push(waitQueue.pop()); + } + }, + resumeEffect: function (id) { + cc.log('audioEngine.resumeEffect is deprecated, please call audioEngine.resume'); + this.resume(id); + }, + resumeAllEffects: function () { + cc.log('audioEngine.resumeAllEffects is deprecated, please call audioEngine.resumeAll'); + while (this._pauseIDCache.length > 0) { + var id = this._pauseIDCache.pop(); + var audio = getAudioFromId(id); + if (audio && audio.resume) + audio.resume(); + } + }, + stopEffect: function (id) { + cc.log('audioEngine.stopEffect is deprecated, please call audioEngine.stop'); + return this.stop(id); + }, + stopAllEffects: function (id) { + cc.log('audioEngine.stopEffect is deprecated, please call audioEngine.stop'); + return this.stop(id); + }, + unloadEffect: function () { + cc.log('audioEngine.stopEffect is deprecated, please call audioEngine.stop'); + return this.stop(id); + }, + end: function () { + cc.log('audioEngine.end is deprecated, please call audioEngine.stopAll'); + return this.stopAll(); } }; diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index b79280f93a..d2eb55cefa 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -29,7 +29,7 @@ if (!(CC_EDITOR && Editor.isMainProcess)) { View = require('./platform/CCView'); } -var _isMusicPlaying = false; +var audioEngine = cc.audioEngine = require('../../audio/CCAudioEngine'); /** * !#en An object to boot the game. @@ -253,11 +253,7 @@ var game = { if (this._paused) return; this._paused = true; // Pause audio engine - if (cc.audioEngine) { - _isMusicPlaying = cc.audioEngine.isMusicPlaying(); - cc.audioEngine.stopAllEffects(); - cc.audioEngine.pauseMusic(); - } + audioEngine && audioEngine.pauseAll(); // Pause main loop if (this._intervalId) window.cancelAnimationFrame(this._intervalId); @@ -274,9 +270,7 @@ var game = { if (!this._paused) return; this._paused = false; // Resume audio engine - if (cc.audioEngine && _isMusicPlaying) { - cc.audioEngine.resumeMusic(); - } + audioEngine && audioEngine.resumeAll(); // Resume main loop this._runMainLoop(); }, @@ -299,7 +293,7 @@ var game = { restart: function () { cc.director.popToSceneStackLevel(0); // Clean up audio - cc.audioEngine && cc.audioEngine.end(); + audioEngine && audioEngine.end(); game.onStart(); }, diff --git a/cocos2d/core/components/CCAudioSource.js b/cocos2d/core/components/CCAudioSource.js index 12a7a473aa..3305d6d100 100644 --- a/cocos2d/core/components/CCAudioSource.js +++ b/cocos2d/core/components/CCAudioSource.js @@ -30,8 +30,13 @@ * @extends Component */ -var audioEngine = require('../../audio/CCAudioEngine'); -cc.audioEngine = audioEngine; +var audioEngine; + +if (cc.sys.isNative) { + audioEngine = jsb.AudioEngine; +} else { + audioEngine = require('../../audio/CCAudioEngine'); +} var AudioSource = cc.Class({ name: 'cc.AudioSource', @@ -183,6 +188,7 @@ var AudioSource = cc.Class({ onDestroy: function () { this.stop(); + audioEngine.uncache(this._clip); }, /** @@ -234,8 +240,7 @@ var AudioSource = cc.Class({ */ rewind: function(){ if (this.audioID === undefined) return false; - this.stop(); - this.play(); + audioEngine.setCurrentTime(this.audioID, 0); } }); From 54d0467fb5d8d5dc2b61bb1e1919c8632413c6b5 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Thu, 1 Sep 2016 22:35:35 +0800 Subject: [PATCH 230/268] add newline richtext element --- cocos2d/core/label/CCHtmlTextParser.js | 9 +++++++ test/qunit/unit/test-html-text-parser.js | 34 ++++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/cocos2d/core/label/CCHtmlTextParser.js b/cocos2d/core/label/CCHtmlTextParser.js index 633714f92d..ef882a1826 100644 --- a/cocos2d/core/label/CCHtmlTextParser.js +++ b/cocos2d/core/label/CCHtmlTextParser.js @@ -106,6 +106,14 @@ cc.HtmlTextParser.prototype = { obj.event = eventObj; } } + header = attribute.match(/^(br(\s)*\/)/); + if(header && header[0].length > 0) { + tagName = header[0].trim(); + attribute = attribute.substring(tagName.length).trim(); + if(tagName.substring(0,2) === "br" && tagName[tagName.length-1] === "/") { + this._resultObjectArray.push({text: "", style: {newline: true}}); + } + } header = attribute.match(/^(on|u|b|i)(\s)*/); if(header && header[0].length > 0) { @@ -129,6 +137,7 @@ cc.HtmlTextParser.prototype = { obj.event = eventObj; } + return obj; }, diff --git a/test/qunit/unit/test-html-text-parser.js b/test/qunit/unit/test-html-text-parser.js index 353d9a41f9..93410d5e98 100644 --- a/test/qunit/unit/test-html-text-parser.js +++ b/test/qunit/unit/test-html-text-parser.js @@ -270,3 +270,37 @@ test('bold/italic/underline test', function () { deepEqual(parser.parse(stringWithUnderline), [{text: "hello world", style: {underline: true}}], "underline test"); }); + +test('test br tag', function () { + var newlineTest = "
"; + + deepEqual(parser.parse(newlineTest), + [{text: "", style: {newline: true}},], "newline element test"); + + var newlineTest2 = "hello a< br /> world"; + + deepEqual(parser.parse(newlineTest2), + [{text: "hello "}, + {text: "a", style: {bold: true}}, + {text: "", style: {newline: true}}, + {text: " world"} + ], "newline element test"); + + var newlineTest3 = "< br />"; + + deepEqual(parser.parse(newlineTest3), + [{text: "", style: {newline: true}},], "newline element test"); + + var newlineTest4 = "

"; + + deepEqual(parser.parse(newlineTest4), + [], "newline element test"); + + var newlineTest5 = "hello a
world"; + + deepEqual(parser.parse(newlineTest5), + [{text: "hello "}, + {text: "a", style: {bold: true}}, + {text: " world"} + ], "newline element test"); +}); From f7eacf9e135192b7e463c85bd8fbd4250a17ff4e Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 2 Sep 2016 09:37:50 +0800 Subject: [PATCH 231/268] Fixed a bug about audioEngine path --- cocos2d/core/CCGame.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index d2eb55cefa..e9cc7fe659 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -29,7 +29,7 @@ if (!(CC_EDITOR && Editor.isMainProcess)) { View = require('./platform/CCView'); } -var audioEngine = cc.audioEngine = require('../../audio/CCAudioEngine'); +var audioEngine = cc.audioEngine = require('../audio/CCAudioEngine'); /** * !#en An object to boot the game. From c74095b4412906db59fcea1a840735bbed7d4a9c Mon Sep 17 00:00:00 2001 From: Nan Wang Date: Fri, 2 Sep 2016 10:23:25 +0800 Subject: [PATCH 232/268] update engine version --- CCBoot.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CCBoot.js b/CCBoot.js index ac3ab270c3..606c9d4276 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -58,7 +58,7 @@ _p = null; * @name cc.ENGINE_VERSION */ var engineVersion; -engineVersion = '1.2.2-beta.1'; +engineVersion = '1.2.2-beta.2'; window['CocosEngine'] = cc.ENGINE_VERSION = engineVersion; /** From 8f072ece929ef1301d0a81b1d89ed03922a97e2a Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Fri, 2 Sep 2016 11:10:22 +0800 Subject: [PATCH 233/268] add more br element test --- test/qunit/unit/test-html-text-parser.js | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/test/qunit/unit/test-html-text-parser.js b/test/qunit/unit/test-html-text-parser.js index 93410d5e98..64105f30bf 100644 --- a/test/qunit/unit/test-html-text-parser.js +++ b/test/qunit/unit/test-html-text-parser.js @@ -303,4 +303,24 @@ test('test br tag', function () { {text: "a", style: {bold: true}}, {text: " world"} ], "newline element test"); + + var newlineTest6 = "hello a

world"; + + deepEqual(parser.parse(newlineTest6), + [{text: "hello "}, + {text: "a", style: {bold: true}}, + {text: "", style: {newline: true}}, + {text: "", style: {newline: true}}, + {text: " world"} + ], "newline element test"); + + var newlineTest7 = "hello a

world"; + + deepEqual(parser.parse(newlineTest7), + [{text: "hello "}, + {text: "a", style: {bold: true}}, + {text: "", style: {newline: true}}, + {text: "", style: {newline: true}}, + {text: " world"} + ], "newline element test"); }); From 11982eee3364682f41943fe813ca36e03facf346 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Fri, 2 Sep 2016 11:21:48 +0800 Subject: [PATCH 234/268] don't execute adjust content logic in editor --- cocos2d/core/components/CCScrollView.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/components/CCScrollView.js b/cocos2d/core/components/CCScrollView.js index 972f1a223a..90e35cd21e 100644 --- a/cocos2d/core/components/CCScrollView.js +++ b/cocos2d/core/components/CCScrollView.js @@ -129,7 +129,7 @@ var ScrollView = cc.Class({ editor: CC_EDITOR && { menu: 'i18n:MAIN_MENU.component.ui/ScrollView', help: 'i18n:COMPONENT.help_url.scrollview', - executeInEditMode: true, + executeInEditMode: false, }, ctor: function() { From 6286c73b600832aae355f268508a28b1662ba608 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Fri, 2 Sep 2016 11:39:22 +0800 Subject: [PATCH 235/268] fix show and hide ToggleVisibility error for fireball/issues/4128 --- jsb/jsb-action.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/jsb/jsb-action.js b/jsb/jsb-action.js index f48501f545..f0fc376d2d 100644 --- a/jsb/jsb-action.js +++ b/jsb/jsb-action.js @@ -125,7 +125,7 @@ cc.Follow.prototype.update = function(dt) { cc.Show.prototype.update = function (dt) { var target = this.getTarget(); - var _renderComps = target._owner.getComponentsInChildren(); + var _renderComps = target._owner.getComponentsInChildren(cc._SGComponent); for (var i = 0; i < _renderComps.length; ++i) { var render = _renderComps[i]; render.enabled = true; @@ -134,7 +134,7 @@ cc.Show.prototype.update = function (dt) { cc.Hide.prototype.update = function (dt) { var target = this.getTarget(); - var _renderComps = target._owner.getComponentsInChildren(); + var _renderComps = target._owner.getComponentsInChildren(cc._SGComponent); for (var i = 0; i < _renderComps.length; ++i) { var render = _renderComps[i]; render.enabled = false; @@ -143,7 +143,7 @@ cc.Hide.prototype.update = function (dt) { cc.ToggleVisibility.prototype.update = function (dt) { var target = this.getTarget(); - var _renderComps = target._owner.getComponentsInChildren(); + var _renderComps = target._owner.getComponentsInChildren(cc._SGComponent); for (var i = 0; i < _renderComps.length; ++i) { var render = _renderComps[i]; render.enabled = true; From 4fb5194d98c2053d91251f04f957bf738f81e031 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Fri, 2 Sep 2016 11:43:08 +0800 Subject: [PATCH 236/268] remove redundant variable for _antiAliasEnabled --- cocos2d/core/platform/CCView.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/cocos2d/core/platform/CCView.js b/cocos2d/core/platform/CCView.js index 168d9b05f0..c49b540ffe 100644 --- a/cocos2d/core/platform/CCView.js +++ b/cocos2d/core/platform/CCView.js @@ -153,8 +153,6 @@ var View = cc._Class.extend({ _targetDensityDPI: null, _antiAliasEnabled: true, - _antiAliasEnabled: false, - /** * Constructor of View */ From 911f6389ecce20bde545244be20cb23c843255b5 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Fri, 2 Sep 2016 11:21:48 +0800 Subject: [PATCH 237/268] don't execute adjust content logic in editor --- cocos2d/core/components/CCScrollView.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/components/CCScrollView.js b/cocos2d/core/components/CCScrollView.js index 33b34d1fc6..9657d6155d 100644 --- a/cocos2d/core/components/CCScrollView.js +++ b/cocos2d/core/components/CCScrollView.js @@ -123,7 +123,7 @@ var ScrollView = cc.Class({ editor: CC_EDITOR && { menu: 'i18n:MAIN_MENU.component.ui/ScrollView', help: 'i18n:COMPONENT.help_url.scrollview', - executeInEditMode: true, + executeInEditMode: false, }, ctor: function() { From 9173a9c0a6d50a04b909e0044a208bf87e25bdbe Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Fri, 2 Sep 2016 14:01:32 +0800 Subject: [PATCH 238/268] fix newline rich text element --- cocos2d/core/label/CCHtmlTextParser.js | 4 ++++ test/qunit/unit/test-html-text-parser.js | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/label/CCHtmlTextParser.js b/cocos2d/core/label/CCHtmlTextParser.js index ef882a1826..a9483fc083 100644 --- a/cocos2d/core/label/CCHtmlTextParser.js +++ b/cocos2d/core/label/CCHtmlTextParser.js @@ -111,6 +111,7 @@ cc.HtmlTextParser.prototype = { tagName = header[0].trim(); attribute = attribute.substring(tagName.length).trim(); if(tagName.substring(0,2) === "br" && tagName[tagName.length-1] === "/") { + obj.isNewLine = true; this._resultObjectArray.push({text: "", style: {newline: true}}); } } @@ -194,6 +195,9 @@ cc.HtmlTextParser.prototype = { if (this._stack.length === 0){ this._stack.push(obj); } else { + if(obj.isNewLine) { + return; + } //for nested tags var previousTagObj = this._stack[this._stack.length - 1]; for (var key in previousTagObj) { diff --git a/test/qunit/unit/test-html-text-parser.js b/test/qunit/unit/test-html-text-parser.js index 64105f30bf..e4c40c6e0b 100644 --- a/test/qunit/unit/test-html-text-parser.js +++ b/test/qunit/unit/test-html-text-parser.js @@ -321,6 +321,6 @@ test('test br tag', function () { {text: "a", style: {bold: true}}, {text: "", style: {newline: true}}, {text: "", style: {newline: true}}, - {text: " world"} + {text: "world"} ], "newline element test"); }); From a41f4505c0454c3a2ec05b80ed6bfcb06d43a558 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Fri, 2 Sep 2016 14:25:08 +0800 Subject: [PATCH 239/268] fix richtext instantiate issue --- cocos2d/core/components/CCRichText.js | 20 ++++++++++---------- test/qunit/unit/test-html-text-parser.js | 4 ++-- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/cocos2d/core/components/CCRichText.js b/cocos2d/core/components/CCRichText.js index cd9cc0bcfa..8fb002c7d3 100644 --- a/cocos2d/core/components/CCRichText.js +++ b/cocos2d/core/components/CCRichText.js @@ -167,17 +167,8 @@ var RichText = cc.Class({ }, _createSgNode: function () { - return new _ccsg.Node(); - }, + var sgNode = new _ccsg.Node(); - _updateLabelSegmentTextAttributes: function() { - this._labelSegments.forEach(function(item) { - this._applyTextAttribute(item); - }.bind(this)); - }, - - _initSgNode: function () { - var sgNode = this._sgNode; sgNode.setCascadeOpacityEnabled(true); var self = this; @@ -187,7 +178,16 @@ var RichText = cc.Class({ sgNode._setContentSize = sgNode.setContentSize; sgNode.setContentSize = function () {}; + return sgNode; + }, + _updateLabelSegmentTextAttributes: function() { + this._labelSegments.forEach(function(item) { + this._applyTextAttribute(item); + }.bind(this)); + }, + + _initSgNode: function () { this._updateRichText(); }, diff --git a/test/qunit/unit/test-html-text-parser.js b/test/qunit/unit/test-html-text-parser.js index e4c40c6e0b..6fea81779f 100644 --- a/test/qunit/unit/test-html-text-parser.js +++ b/test/qunit/unit/test-html-text-parser.js @@ -67,7 +67,7 @@ test('Color test', function(){ [{text: "hello world", style: {}}], "tag name is invalid"); - var colorTestStr6 = "hello world"; + var colorTestStr6 = "hello world"; deepEqual(parser.parse(colorTestStr6), [{text: "hello world"}], "The close tag is missing."); @@ -76,7 +76,7 @@ test('Color test', function(){ }); test('Size test', function() { - var sizeTestStr1 = "hello world"; + var sizeTestStr1 = "hello world"; deepEqual(parser.parse(sizeTestStr1), [{text: "hello world", style: {size: 20}}], "Happy path 1."); From acf49462bf9ef2c32c76cb9148f5218e5f94aea3 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Fri, 2 Sep 2016 14:58:33 +0800 Subject: [PATCH 240/268] add richtext element
support --- cocos2d/core/components/CCRichText.js | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/components/CCRichText.js b/cocos2d/core/components/CCRichText.js index 8fb002c7d3..443f1baa1d 100644 --- a/cocos2d/core/components/CCRichText.js +++ b/cocos2d/core/components/CCRichText.js @@ -466,7 +466,15 @@ var RichText = cc.Class({ var labelSize; for (var i = 0; i < this._textArray.length; ++i) { - var text = this._textArray[i].text; + var richTextElement = this._textArray[i]; + var text = richTextElement.text; + //handle
tag + if(text === "") { + if(richTextElement.style && richTextElement.style.newline) { + this._updateLineInfo(); + continue; + } + } var multilineTexts = text.split("\n"); for (var j = 0; j < multilineTexts.length; ++j) { From 7a745fa740e1cf0f76a47d9c48534dc39e970a88 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Fri, 2 Sep 2016 15:24:07 +0800 Subject: [PATCH 241/268] refactoring code --- cocos2d/core/label/CCHtmlTextParser.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/cocos2d/core/label/CCHtmlTextParser.js b/cocos2d/core/label/CCHtmlTextParser.js index a9483fc083..f2dc69fe4a 100644 --- a/cocos2d/core/label/CCHtmlTextParser.js +++ b/cocos2d/core/label/CCHtmlTextParser.js @@ -109,8 +109,7 @@ cc.HtmlTextParser.prototype = { header = attribute.match(/^(br(\s)*\/)/); if(header && header[0].length > 0) { tagName = header[0].trim(); - attribute = attribute.substring(tagName.length).trim(); - if(tagName.substring(0,2) === "br" && tagName[tagName.length-1] === "/") { + if(tagName.startsWith("br") && tagName[tagName.length-1] === "/") { obj.isNewLine = true; this._resultObjectArray.push({text: "", style: {newline: true}}); } From c5bf08e526ca7e2c1680d993340b23c4b7b1b6d0 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 2 Sep 2016 18:34:36 +0800 Subject: [PATCH 242/268] Improve webgl support detection and orientation adaptation --- cocos2d/core/platform/CCSys.js | 9 ++++++++- cocos2d/core/platform/CCView.js | 4 ++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/platform/CCSys.js b/cocos2d/core/platform/CCSys.js index 0c4463e89f..611b70eab7 100644 --- a/cocos2d/core/platform/CCSys.js +++ b/cocos2d/core/platform/CCSys.js @@ -705,10 +705,17 @@ else { var tmpCanvas = document.createElement("CANVAS"); try{ var context = cc.create3DContext(tmpCanvas, {'stencil': true}); - if(context) { + 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 (!window.indexedDB) { + _supportWebGL = false; + } + } + if (_supportWebGL && sys.os === sys.OS_ANDROID) { var browserVer = parseFloat(sys.browserVersion); switch (sys.browserType) { diff --git a/cocos2d/core/platform/CCView.js b/cocos2d/core/platform/CCView.js index 168d9b05f0..8fa2a54a82 100644 --- a/cocos2d/core/platform/CCView.js +++ b/cocos2d/core/platform/CCView.js @@ -127,7 +127,7 @@ var View = cc._Class.extend({ // Custom callback for resize event _resizeCallback: null, - _orientationChanging: false, + _orientationChanging: true, _scaleX: 1, _originalScaleX: 1, @@ -219,7 +219,6 @@ var View = cc._Class.extend({ _orientationChange: function () { this._orientationChanging = true; this._resizeEvent(); - this._orientationChanging = false; }, /** @@ -327,6 +326,7 @@ var View = cc._Class.extend({ cc.container.style.transformOrigin = '0px 0px 0px'; this._isRotated = true; } + this._orientationChanging = false; }, // hack From 7c53c47b5fa68c3d6aa6d09e368ebde4e3e95c23 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Mon, 22 Aug 2016 16:07:19 +0800 Subject: [PATCH 243/268] working on synced prefab --- cocos2d/core/CCNode.js | 42 ++- cocos2d/core/CCScene.js | 13 +- cocos2d/core/assets/CCPrefab.js | 4 + cocos2d/core/platform/index.js | 1 - cocos2d/core/platform/instantiate.js | 42 ++- cocos2d/core/utils/base-node.js | 23 -- .../prefab-info.js => utils/prefab-helper.js} | 61 ++++- package.json | 2 +- test/qunit/unit/test-prefab-sync.js | 259 ++++++++++++++++++ test/qunit/unit/test-prefab.js | 28 +- ...erialization.js => test-serialize-node.js} | 0 11 files changed, 422 insertions(+), 53 deletions(-) rename cocos2d/core/{platform/prefab-info.js => utils/prefab-helper.js} (51%) create mode 100644 test/qunit/unit/test-prefab-sync.js rename test/qunit/unit/{test-node-serialization.js => test-serialize-node.js} (100%) diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index 3a928d006d..cd892d31ec 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -25,6 +25,7 @@ 'use strict'; var EventTarget = require('./event/event-target'); +var PrefabHelper = require('./utils/prefab-helper'); var JS = cc.js; var Flags = cc.Object.Flags; @@ -899,6 +900,33 @@ var Node = cc.Class({ } }, + /* + * The initializer for Node which will be called before all components onLoad + */ + _onBatchCreated: function () { + var prefabInfo = this._prefab; + if (prefabInfo && prefabInfo.sync && !prefabInfo._synced) { + PrefabHelper.syncWithPrefab(this); + } + + this._updateDummySgNode(); + + if (this._parent) { + this._parent._sgNode.addChild(this._sgNode); + } + + if ( !this._activeInHierarchy ) { + // deactivate ActionManager and EventManager by default + cc.director.getActionManager().pauseTarget(this); + cc.eventManager.pauseTarget(this); + } + + var children = this._children; + for (var i = 0, len = children.length; i < len; i++) { + children[i]._onBatchCreated(); + } + }, + _activeRecursively: function (newActive) { var cancelActivation = false; if (this._objFlags & Activating) { @@ -1063,10 +1091,20 @@ var Node = cc.Class({ var clone = cc.instantiate._clone(this, this); clone._parent = null; - // init - if (CC_EDITOR && cc.engine._isPlaying) { + var thisPrefabInfo = this._prefab; + var syncing = thisPrefabInfo && this === thisPrefabInfo.root && thisPrefabInfo.sync; + if (syncing) { + // copy non-serialized property + clone._prefab._synced = thisPrefabInfo._synced; + //if (thisPrefabInfo._synced) { + // return clone; + //} + } + else if (CC_EDITOR && cc.engine._isPlaying) { this._name += ' (Clone)'; } + + // init clone._onBatchCreated(); return clone; diff --git a/cocos2d/core/CCScene.js b/cocos2d/core/CCScene.js index 9f5d73efc2..c8d293103f 100644 --- a/cocos2d/core/CCScene.js +++ b/cocos2d/core/CCScene.js @@ -87,7 +87,18 @@ cc.Scene = cc.Class({ _load: function () { if ( ! this._inited) { - this._onBatchCreated(); + + this._updateDummySgNode(); + + // deactivate ActionManager and EventManager by default + cc.director.getActionManager().pauseTarget(this); + cc.eventManager.pauseTarget(this); + + var children = this._children; + for (var i = 0, len = children.length; i < len; i++) { + children[i]._onBatchCreated(); + } + this._inited = true; } }, diff --git a/cocos2d/core/assets/CCPrefab.js b/cocos2d/core/assets/CCPrefab.js index 70fc9890b0..5a59bd7195 100644 --- a/cocos2d/core/assets/CCPrefab.js +++ b/cocos2d/core/assets/CCPrefab.js @@ -55,10 +55,14 @@ var Prefab = cc.Class({ }, _instantiate: function () { + // prefab asset is always synced + this.data._prefab._synced = true; + // instantiate var node = cc.instantiate(this.data); if (CC_EDITOR || CC_TEST) { + // This operation is not necessary, but some old prefab asset may not contain complete data. _Scene.PrefabUtils.linkPrefab(this, node); } diff --git a/cocos2d/core/platform/index.js b/cocos2d/core/platform/index.js index 727edca891..c4c74cd209 100644 --- a/cocos2d/core/platform/index.js +++ b/cocos2d/core/platform/index.js @@ -30,7 +30,6 @@ require('./callbacks-invoker'); require('./url'); require('./deserialize'); require('./instantiate'); -require('./prefab-info'); require('./requiring-frame'); require('./CCSys'); require('./CCMacro'); diff --git a/cocos2d/core/platform/instantiate.js b/cocos2d/core/platform/instantiate.js index 34218a6012..90cda88410 100644 --- a/cocos2d/core/platform/instantiate.js +++ b/cocos2d/core/platform/instantiate.js @@ -46,15 +46,21 @@ var _isDomNode = require('./utils').isDomNode; */ function instantiate (original) { if (typeof original !== 'object' || Array.isArray(original)) { - cc.error('The thing you want to instantiate must be an object'); + if (CC_DEV) { + cc.error('The thing you want to instantiate must be an object'); + } return null; } if (!original) { - cc.error('The thing you want to instantiate is nil'); + if (CC_DEV) { + cc.error('The thing you want to instantiate is nil'); + } return null; } if (original instanceof CCObject && !original.isValid) { - cc.error('The thing you want to instantiate is destroyed'); + if (CC_DEV) { + cc.error('The thing you want to instantiate is destroyed'); + } return null; } @@ -69,7 +75,9 @@ function instantiate (original) { } else if (original instanceof cc.Asset) { // 不允许用通用方案实例化资源 - cc.error('The instantiate method for given asset do not implemented'); + if (CC_DEV) { + cc.error('The instantiate method for given asset do not implemented'); + } return null; } } @@ -108,7 +116,16 @@ function doInstantiate (obj, parent) { return null; } - var clone = enumerateObject(obj, parent); + var clone; + if (obj._iN$t) { + clone = obj._iN$t; + } + else { + // User can specify an existing object by assigning the "_iN$t" property + var klass = obj.constructor; + clone = new klass(); + } + enumerateObject(obj, clone, parent); for (var i = 0, len = objsToClearTmpVar.length; i < len; ++i) { objsToClearTmpVar[i]._iN$t = null; @@ -118,14 +135,10 @@ function doInstantiate (obj, parent) { return clone; } -///** -// * @param {Object} obj - The object to instantiate, typeof must be 'object' and should not be an array. -// * @return {Object} - the instantiated instance -// */ -var enumerateObject = function (obj, parent) { +// @param {Object} obj - The object to instantiate, typeof must be 'object' and should not be an array. +function enumerateObject (obj, clone, parent) { var value, type, key; var klass = obj.constructor; - var clone = new klass(); obj._iN$t = clone; objsToClearTmpVar.push(obj); if (cc.Class._isCCClass(klass)) { @@ -175,8 +188,7 @@ var enumerateObject = function (obj, parent) { if (obj instanceof CCObject) { clone._objFlags &= PersistentMask; } - return clone; -}; +} ///** // * @return {Object} - the original non-nil object, typeof must be 'object' @@ -248,7 +260,9 @@ function instantiateObj (obj, parent, ownerObj, ownerKey) { // unknown type return obj; } - return enumerateObject(obj, parent); + clone = new ctor(); + enumerateObject(obj, clone, parent); + return clone; } } diff --git a/cocos2d/core/utils/base-node.js b/cocos2d/core/utils/base-node.js index 2e727fd3b3..16e1eaba49 100644 --- a/cocos2d/core/utils/base-node.js +++ b/cocos2d/core/utils/base-node.js @@ -2004,29 +2004,6 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ } }, - /* - * The deserializer for sgNode which will be called before components onLoad - * @param {Boolean} [skipChildrenInEditor=false] - */ - _onBatchCreated: function () { - this._updateDummySgNode(); - - if (this._parent) { - this._parent._sgNode.addChild(this._sgNode); - } - - if ( !this._activeInHierarchy ) { - // deactivate ActionManager and EventManager by default - cc.director.getActionManager().pauseTarget(this); - cc.eventManager.pauseTarget(this); - } - - var children = this._children; - for (var i = 0, len = children.length; i < len; i++) { - children[i]._onBatchCreated(); - } - }, - onRestore: CC_EDITOR && function () { this._updateDummySgNode(); diff --git a/cocos2d/core/platform/prefab-info.js b/cocos2d/core/utils/prefab-helper.js similarity index 51% rename from cocos2d/core/platform/prefab-info.js rename to cocos2d/core/utils/prefab-helper.js index c238dc65a7..89efaad05c 100644 --- a/cocos2d/core/platform/prefab-info.js +++ b/cocos2d/core/utils/prefab-helper.js @@ -24,7 +24,7 @@ ****************************************************************************/ // 保存编辑器下用到的 prefab 相关信息 -var PrefabInfo = cc.Class({ +cc._PrefabInfo = cc.Class({ name: 'cc.PrefabInfo', properties: { //// the serialized version @@ -42,9 +42,62 @@ var PrefabInfo = cc.Class({ // 用来标识别该节点在 prefab 资源中的位置,因此这个 ID 只需要保证在 Assets 里不重复就行 fileId: '', - //// Indicates whether this node should always synchronize with the prefab asset. - //sync: false, + // Indicates whether this node should always synchronize with the prefab asset, only available in the root node + sync: false, + + // Indicates whether this node is synchronized, only available in the root node + _synced: { + default: false, + serializable: false + }, } }); -cc._PrefabInfo = module.exports = PrefabInfo; +// prefab helper function +module.exports = { + // update node to make it sync with prefab + syncWithPrefab: function (node) { + + // save preserved props to avoid overwritten by prefabRoot + var _objFlags = node._objFlags; + var _parent = node._parent; + var _id = node._id; + var _prefab = node._prefab; + var _name = node._name; + var _active = node._active; + var _position = node._position; + var _rotationX = node._rotationX; + var _rotationY = node._rotationY; + var _localZOrder = node._localZOrder; + var _globalZOrder = node._globalZOrder; + + // non-reentrant + _prefab._synced = true; + + var prefabRoot = _prefab.asset.data; + + // prefab asset is always synced + prefabRoot._prefab._synced = true; + + // use node as the instantiated prefabRoot to make references to prefabRoot in prefab redirect to node + prefabRoot._iN$t = node; + + // instantiate prefab and apply to node + cc.game._isCloning = true; + cc.instantiate._clone(prefabRoot, prefabRoot); + cc.game._isCloning = false; + + // restore preserved props + node._objFlags = _objFlags; + node._parent = _parent; + node._id = _id; + node._prefab = _prefab; + node._name = _name; + node._active = _active; + node._position = _position; + node._rotationX = _rotationX; + node._rotationY = _rotationY; + node._localZOrder = _localZOrder; + node._globalZOrder = _globalZOrder; + } +}; diff --git a/package.json b/package.json index 09e8334775..ec066c7036 100644 --- a/package.json +++ b/package.json @@ -20,7 +20,7 @@ "gulp": "3.9.0", "gulp-cached": "1.1.0", "gulp-concat": "2.6.0", - "gulp-fb": "0.5.0", + "gulp-fb": "0.5.1", "gulp-header": "1.2.2", "gulp-jshint": "1.11.2", "gulp-mirror": "0.4.0", diff --git a/test/qunit/unit/test-prefab-sync.js b/test/qunit/unit/test-prefab-sync.js new file mode 100644 index 0000000000..c1b2eeeb96 --- /dev/null +++ b/test/qunit/unit/test-prefab-sync.js @@ -0,0 +1,259 @@ +(function () { + + if (!TestEditorExtends) { + return; + } + + var MyComponent = cc.Class({ + name: '8537489053431', + extends: CallbackTester, + editor: { + executeInEditMode: true + } + }); + + var UUID = '19941122'; + var DEBUG_SERIALIZED_PREFAB = 0 && !isPhantomJS; + + var parent = new cc.Node('parent'); + parent.addComponent(MyComponent); + parent.scale = cc.v2(123, 432); + parent.x = 1020; + parent.active = false; + + var child = new cc.Node('child'); + child.addComponent(MyComponent); + child.scale = cc.v2(3, 2); + child.parent = parent; + child.y = 1029; + child.active = false; + + var prefabAsset; + var prefabJson; + var parentJson; + var reloadedParent; + + (function beforeAll () { + + // CREATE PREFAB ASSET + + _Scene.PrefabUtils.createPrefabFrom(parent); + //var asset = new cc.Prefab(); + //asset.data = parent; + parent._prefab.asset._uuid = UUID; + //_Scene.PrefabUtils.setPrefabAsset(parent, Editor.serialize.asAsset()); + _Scene.PrefabUtils.setPrefabSync(parent, true); + + // apply sync property + prefabAsset = _Scene.PrefabUtils.createAppliedPrefab(parent); + + // 重新生成已经加载好的 prefab,去除类型,去除 runtime node + prefabJson = Editor.serialize(prefabAsset, { stringify: false }); + prefabAsset = cc.deserialize(prefabJson); + prefabAsset._uuid = UUID; + + // SAVE SCENE ASSET + + parentJson = Editor.serialize(parent, { stringify: false }); + if (DEBUG_SERIALIZED_PREFAB) { + console.log(JSON.stringify(parentJson, null, 4)); + } + reloadedParent = cc.deserialize(parentJson); + reloadedParent._prefab.asset = prefabAsset; + //reloadedParent.children[0]._prefab.asset = prefabAsset; + })(); + + test('prefab info', function () { + strictEqual(parent._prefab.sync, true, "sync property should be saved to root prefab info"); + }); + + test('prefab asset should not discard content if sync enabled', function () { + var nodeToSave = prefabAsset.data; + ok(nodeToSave.children.length > 0, 'children should be saved'); + var childToSave = nodeToSave.children[0]; + strictEqual(nodeToSave.scaleX, parent.scaleX, 'root scale should be saved'); + strictEqual(childToSave.scaleY, child.scaleY, 'child scale should be saved'); + ok(nodeToSave.getComponent(cc.Component), 'root component should be saved'); + ok(childToSave.getComponent(cc.Component), 'child component should be saved'); + strictEqual(childToSave.name, child.name, 'child name should be saved'); + strictEqual(nodeToSave.active, false, 'root active should be saved'); + strictEqual(childToSave.active, false, 'child active should be saved'); + }); + + test('sync config saved in prefab asset', function () { + var nodeToSave = prefabAsset.data; + strictEqual(nodeToSave._prefab.sync, false, 'sync config should not saved'); + }); + + test('saved scene node if sync enabled', function () { + strictEqual(reloadedParent.scaleX, 1, 'all scale should not saved'); + strictEqual(reloadedParent.getComponent(cc.Component), null, 'all component should not saved'); + strictEqual(reloadedParent.x, parent.x, 'root position should be saved'); + strictEqual(reloadedParent.name, parent.name, 'root name should be saved'); + strictEqual(reloadedParent.active, false, 'root active should be saved'); + ok(reloadedParent.children.length === 0, 'children should not saved'); + + var prefabInfo = reloadedParent._prefab; + ok(prefabInfo, 'prefab info should be saved'); + ok(prefabInfo.asset, 'asset should be saved'); + strictEqual(prefabInfo.sync, true, 'sync should be saved'); + strictEqual(prefabInfo.fileId, parent.uuid, 'fileId should be saved'); + + //ok(reloadedParent.children.length > 0, 'children should be saved'); + //var reloadedChild = reloadedParent.children[0]; + //strictEqual(reloadedChild.y, 0, 'child position should not saved'); + //notEqual(reloadedChild.name, child.name, 'child name should not saved'); + //strictEqual(reloadedChild.active, true, 'child active should not saved'); + }); + + test('prefab info in exported scene if syncable', function () { + var reloadedParent = cc.deserialize(Editor.serialize(parent, { stringify: false, exporting: true })); + ok(reloadedParent._prefab, 'prefab info should be saved'); + strictEqual(reloadedParent._prefab.sync, true, 'sync should be saved'); + strictEqual(reloadedParent._prefab.fileId, parent.uuid, 'fileId should be saved'); + }); + + function testInstantiatedNode (newNode) { + var prefabInfo = newNode._prefab; + ok(prefabInfo, "new node should preserve the prefab info"); + ok(newNode.children.length > 0, 'instantiated node should have children'); + ok(newNode.getComponent(cc.Component), 'instantiated node should have component'); + return newNode; + } + test('instantiated prefab asset', function () { + var newNode = cc.instantiate(prefabAsset); + testInstantiatedNode(newNode); + }); + test('instantiating synced scene node', function () { + var newNode = cc.instantiate(parent); + testInstantiatedNode(newNode); + ok(newNode._prefab.sync === true, "sync should be instantiated"); + ok(newNode._prefab._synced === true, "instantiated node should be _synced"); + }); + + test('load and sync scene', function () { + // prepare dummy scene + var scene = new cc.Scene(); + scene._inited = false; + scene.children.push(reloadedParent); + reloadedParent._parent = scene; + + // invoke sync + cc.director.runSceneImmediate(scene); + + // test prefabInfo + var prefabInfo = reloadedParent._prefab; + ok(prefabInfo, "new node should preserve the prefab info"); + ok(prefabInfo.sync === true, "sync should be instantiated"); + ok(prefabInfo._synced === true, "instantiated node should be _synced"); + strictEqual(prefabInfo.fileId, parent.uuid, 'fileId should be kept'); + + // test parent + strictEqual(reloadedParent.scaleX, parent.scaleX, 'all scale should be synced'); + var comp = reloadedParent.getComponent(cc.Component); + ok(comp, 'all component should be synced'); + strictEqual(comp.node, reloadedParent, 'component reference should redirect to scene node'); + strictEqual(reloadedParent.x, parent.x, 'root position should be kept'); + strictEqual(reloadedParent.name, parent.name, 'root name should be kept'); + strictEqual(reloadedParent.active, false, 'root active should be kept'); + strictEqual(reloadedParent.children.length, 1, 'children should be synced'); + + // test parent sgNode + strictEqual(reloadedParent._sgNode.parent === scene._sgNode, true, 'parent of parent _sgNode should be synced'); + + // test child + var syncedChild = reloadedParent.children[0]; + strictEqual(syncedChild.active, child.active, 'child active should be synced'); + strictEqual(syncedChild.getComponent(cc.Component) != null, true, 'child component should be synced'); + strictEqual(syncedChild.y, child.y, 'child position should be synced'); + strictEqual(syncedChild.scaleY, child.scaleY, 'child scale should be synced'); + strictEqual(syncedChild.parent, reloadedParent, 'prefab reference should redirect to scene node'); + + // test child sgNode + strictEqual(syncedChild._sgNode.parent === reloadedParent._sgNode, true, 'parent of child _sgNode should be synced'); + }); + + // + //test('re-instantiate an instantiated node', function () { + // var first = cc.instantiate(prefab); + // var second = cc.instantiate(first); + // var secondInfo = second._prefab; + // + // ok(second, "new node should be created"); + // ok(secondInfo, "new node should preserve the prefab info"); + // ok(secondInfo !== first._prefab, "prefab info should not the same"); + // ok(secondInfo.asset === prefab, "should reference to origin prefab asset in prefab info"); + // ok(secondInfo.root === second, "check root"); + // ok(secondInfo.fileId === first._prefab.fileId, "check fileId"); + // + // notEqual(first.uuid, second.uuid, 'The id of instances should be different'); + //}); + // + //test('apply node', function () { + // var newNode = cc.instantiate(prefab); + // var newPrefab = _Scene.PrefabUtils.createAppliedPrefab(newNode); + // strictEqual(newPrefab.data._prefab.fileId, prefab.data._prefab.fileId, "fileId should not changed during apply"); + //}); + // + //asyncTest('revert prefab', function () { + // // stub + // cc.loader.insertPipe({ + // id : 'Prefab_Provider', + // async : false, + // handle : function (item) { + // var url = item.id; + // if (url === UUID) { + // item.states['Downloader'] = cc.Pipeline.ItemState.COMPLETE; + // return JSON.stringify(prefabJson); + // } + // else { + // return; + // } + // } + // }, 0); + // + // var testNode = cc.instantiate(prefab); + // var testChild = testNode.children[0]; + // + // testNode.scale = 0; + // testNode.removeComponent(TestScript); + // testNode.children[1].parent = null; + // testChild.scale = cc.Vec2.ZERO; + // testChild.addComponent(TestScript); + // + // var newNode = new cc.Node(); + // newNode.parent = testChild; + // + // var newNode2 = new cc.Node(); + // newNode2.parent = testNode; + // newNode2.setSiblingIndex(0); + // + // _Scene.PrefabUtils.revertPrefab(testNode, function () { + // ok(testNode.getScaleX() === 123 && testNode.getScaleY() === 432, 'Revert property of the parent node'); + // ok(testNode.getComponent(TestScript).constructor === TestScript, 'Restore removed component'); + // var c = testNode.children[0]; + // ok(c.getScaleX() === 22 && c.getScaleY() === 11, 'Revert child node'); + // ok(testChild.getComponent(TestScript) == null, 'Remove added component'); + // + // ok(testNode.getComponent(TestScript).target === testChild, 'Should redirect reference to scene node'); + // + // strictEqual(testChild.children.length, 0, 'Should remove new node'); + // + // strictEqual(testNode.childrenCount, 2, 'Should create removed node'); + // var created = testNode.children[1]; + // ok(created._sgNode, 'Checking created node'); + // + // var comp = created.getComponent(MyComponent); + // comp.resetExpect(CallbackTester.OnLoad, 'call onLoad while attaching to node'); + // comp.pushExpect(CallbackTester.OnEnable, 'then call onEnable if node active'); + // + // cc.director.getScene().addChild(testNode); + // + // comp.stopTest(); + // + // strictEqual(newNode2.isValid, false, 'should remove new node which is not the last sibling'); + // + // start(); + // }); + //}); +})(); diff --git a/test/qunit/unit/test-prefab.js b/test/qunit/unit/test-prefab.js index b3bb4874ee..a9be37aeef 100644 --- a/test/qunit/unit/test-prefab.js +++ b/test/qunit/unit/test-prefab.js @@ -38,7 +38,7 @@ }); var UUID = '19851210'; - var OUTPUT_PREFAB = 0; + var DEBUG_SERIALIZED_PREFAB = 0 && !isPhantomJS; var parent = new cc.Node('parent'); var child = new cc.Node('child'); @@ -60,25 +60,29 @@ (function savePrefab () { prefab = _Scene.PrefabUtils.createPrefabFrom(parent); - _Scene.PrefabUtils.savePrefabUuid(parent, UUID); + prefab._uuid = UUID; + //_Scene.PrefabUtils.setPrefabAsset(parent, prefab); - // 已经加载好的 prefab,去除类型,去除 runtime node + // 重新生成已经加载好的 prefab,去除类型,去除 runtime node prefabJson = Editor.serialize(prefab); - if (OUTPUT_PREFAB) { + if (DEBUG_SERIALIZED_PREFAB) { console.log(prefabJson); } prefab = cc.deserialize(prefabJson); prefab._uuid = UUID; })(); - test('create prefab', function () { + test('prefab info', function () { var prefabInfo = parent._prefab; ok(prefab !== null, "prefab asset should be created"); ok(prefabInfo !== null, "wrapper should preserve the prefab info"); ok(prefabInfo.asset instanceof cc.Asset, "the prefab asset should be preserved"); + strictEqual(prefabInfo.root, parent,"the parent prefab's root should be itself"); strictEqual(prefabInfo.asset._uuid, UUID, "the prefab asset should be preserved"); + }); + test('saved prefab node', function () { var nodeToSave = prefab.data; ok(nodeToSave instanceof cc.Node, 'Checking prefab data'); ok(!nodeToSave._id, 'The id in prefab data should be cleared'); @@ -100,6 +104,11 @@ strictEqual(child2._prefab, null, 'Prefab info should be cleared if detached from parent'); }); + test('asset reference in prefab info', function () { + var node = prefab.data; + strictEqual(node._prefab.asset, prefab, "should reference to the main asset directly"); + }); + test('instantiate prefab', function () { var newNode = cc.instantiate(prefab); var newNode2 = cc.instantiate(prefab); @@ -163,9 +172,12 @@ var testNode = cc.instantiate(prefab); var testChild = testNode.children[0]; + testNode.x += 1; testNode.scale = 0; testNode.removeComponent(TestScript); testNode.children[1].parent = null; + + testChild.x += 1; testChild.scale = cc.Vec2.ZERO; testChild.addComponent(TestScript); @@ -177,10 +189,12 @@ newNode2.setSiblingIndex(0); _Scene.PrefabUtils.revertPrefab(testNode, function () { + ok(testNode.x != prefab.data.x, 'Should not revert root position'); ok(testNode.getScaleX() === 123 && testNode.getScaleY() === 432, 'Revert property of the parent node'); ok(testNode.getComponent(TestScript).constructor === TestScript, 'Restore removed component'); - var c = testNode.children[0]; - ok(c.getScaleX() === 22 && c.getScaleY() === 11, 'Revert child node'); + + ok(testChild.x === prefab.data.children[0].x, 'Revert child position'); + ok(testChild.getScaleX() === 22 && testChild.getScaleY() === 11, 'Revert child node'); ok(testChild.getComponent(TestScript) == null, 'Remove added component'); ok(testNode.getComponent(TestScript).target === testChild, 'Should redirect reference to scene node'); diff --git a/test/qunit/unit/test-node-serialization.js b/test/qunit/unit/test-serialize-node.js similarity index 100% rename from test/qunit/unit/test-node-serialization.js rename to test/qunit/unit/test-serialize-node.js From 8a244d64b2daae5f9d8644a13786952b71d2e69a Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Wed, 24 Aug 2016 20:47:19 +0800 Subject: [PATCH 244/268] minor tweaks --- cocos2d/core/CCNode.js | 7 +- .../core/load-pipeline/auto-release-utils.js | 2 +- cocos2d/core/platform/instantiate.js | 2 +- cocos2d/core/platform/utils.js | 17 ++-- cocos2d/deprecated.js | 1 - test/qunit/unit/test-prefab-sync.js | 89 ------------------- 6 files changed, 17 insertions(+), 101 deletions(-) diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index cd892d31ec..a98cf4d96f 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -792,13 +792,14 @@ var Node = cc.Class({ return; } } - if (ctor._requireComponent) { + var ReqComp = ctor._requireComponent; + if (ReqComp && !this.getComponent(ReqComp)) { if (index === this._components.length) { // If comp should be last component, increase the index because required component added ++index; } - var depend = this.addComponent(ctor._requireComponent); - if (!depend) { + var depended = this.addComponent(ReqComp); + if (!depended) { // depend conflicts return null; } diff --git a/cocos2d/core/load-pipeline/auto-release-utils.js b/cocos2d/core/load-pipeline/auto-release-utils.js index 3a8164aad3..5e6eb4f685 100644 --- a/cocos2d/core/load-pipeline/auto-release-utils.js +++ b/cocos2d/core/load-pipeline/auto-release-utils.js @@ -20,7 +20,7 @@ function release (loader, key, nextSceneAssets) { var item = loader.getItem(key); if (item) { var removed = loader.removeItem(key); - console.log('auto release: ' + key); + //console.log('auto release: ' + key); // TODO: Audio var asset = item.content; if (asset instanceof cc.Texture2D) { diff --git a/cocos2d/core/platform/instantiate.js b/cocos2d/core/platform/instantiate.js index 90cda88410..9feb76de04 100644 --- a/cocos2d/core/platform/instantiate.js +++ b/cocos2d/core/platform/instantiate.js @@ -111,7 +111,7 @@ function doInstantiate (obj, parent) { cc.error('Can not instantiate array'); return null; } - if (_isDomNode && _isDomNode(obj)) { + if (!CC_JSB && _isDomNode && _isDomNode(obj)) { cc.error('Can not instantiate DOM element'); return null; } diff --git a/cocos2d/core/platform/utils.js b/cocos2d/core/platform/utils.js index a1ff8bda00..b38154bf89 100644 --- a/cocos2d/core/platform/utils.js +++ b/cocos2d/core/platform/utils.js @@ -24,12 +24,17 @@ ****************************************************************************/ module.exports = { - isDomNode: typeof window === 'object' && function (obj) { - return ( - typeof Node === "object" ? obj instanceof Node : - obj && typeof obj === "object" && typeof obj.nodeType === "number" && typeof obj.nodeName === "string" - ); - }, + isDomNode: typeof window === 'object' && (typeof Node === 'function' ? + function (obj) { + return obj instanceof Node; + } : + function (obj) { + return obj && + typeof obj === 'object' && + typeof obj.nodeType === 'number' && + typeof obj.nodeName === 'string'; + } + ), callInNextTick: CC_EDITOR ? function (callback, p1, p2) { diff --git a/cocos2d/deprecated.js b/cocos2d/deprecated.js index c36d786f4f..1bfb323bae 100644 --- a/cocos2d/deprecated.js +++ b/cocos2d/deprecated.js @@ -378,7 +378,6 @@ if (CC_DEV && typeof eruda === 'undefined') { 'onEnterTransitionDidFinish', 'onExitTransitionDidStart', 'onExit', - 'getNumberOfRunningActions', 'scheduleUpdate', 'scheduleUpdateWithPriority', 'unscheduleUpdate', diff --git a/test/qunit/unit/test-prefab-sync.js b/test/qunit/unit/test-prefab-sync.js index c1b2eeeb96..ae2d8722fe 100644 --- a/test/qunit/unit/test-prefab-sync.js +++ b/test/qunit/unit/test-prefab-sync.js @@ -98,12 +98,6 @@ ok(prefabInfo.asset, 'asset should be saved'); strictEqual(prefabInfo.sync, true, 'sync should be saved'); strictEqual(prefabInfo.fileId, parent.uuid, 'fileId should be saved'); - - //ok(reloadedParent.children.length > 0, 'children should be saved'); - //var reloadedChild = reloadedParent.children[0]; - //strictEqual(reloadedChild.y, 0, 'child position should not saved'); - //notEqual(reloadedChild.name, child.name, 'child name should not saved'); - //strictEqual(reloadedChild.active, true, 'child active should not saved'); }); test('prefab info in exported scene if syncable', function () { @@ -173,87 +167,4 @@ strictEqual(syncedChild._sgNode.parent === reloadedParent._sgNode, true, 'parent of child _sgNode should be synced'); }); - // - //test('re-instantiate an instantiated node', function () { - // var first = cc.instantiate(prefab); - // var second = cc.instantiate(first); - // var secondInfo = second._prefab; - // - // ok(second, "new node should be created"); - // ok(secondInfo, "new node should preserve the prefab info"); - // ok(secondInfo !== first._prefab, "prefab info should not the same"); - // ok(secondInfo.asset === prefab, "should reference to origin prefab asset in prefab info"); - // ok(secondInfo.root === second, "check root"); - // ok(secondInfo.fileId === first._prefab.fileId, "check fileId"); - // - // notEqual(first.uuid, second.uuid, 'The id of instances should be different'); - //}); - // - //test('apply node', function () { - // var newNode = cc.instantiate(prefab); - // var newPrefab = _Scene.PrefabUtils.createAppliedPrefab(newNode); - // strictEqual(newPrefab.data._prefab.fileId, prefab.data._prefab.fileId, "fileId should not changed during apply"); - //}); - // - //asyncTest('revert prefab', function () { - // // stub - // cc.loader.insertPipe({ - // id : 'Prefab_Provider', - // async : false, - // handle : function (item) { - // var url = item.id; - // if (url === UUID) { - // item.states['Downloader'] = cc.Pipeline.ItemState.COMPLETE; - // return JSON.stringify(prefabJson); - // } - // else { - // return; - // } - // } - // }, 0); - // - // var testNode = cc.instantiate(prefab); - // var testChild = testNode.children[0]; - // - // testNode.scale = 0; - // testNode.removeComponent(TestScript); - // testNode.children[1].parent = null; - // testChild.scale = cc.Vec2.ZERO; - // testChild.addComponent(TestScript); - // - // var newNode = new cc.Node(); - // newNode.parent = testChild; - // - // var newNode2 = new cc.Node(); - // newNode2.parent = testNode; - // newNode2.setSiblingIndex(0); - // - // _Scene.PrefabUtils.revertPrefab(testNode, function () { - // ok(testNode.getScaleX() === 123 && testNode.getScaleY() === 432, 'Revert property of the parent node'); - // ok(testNode.getComponent(TestScript).constructor === TestScript, 'Restore removed component'); - // var c = testNode.children[0]; - // ok(c.getScaleX() === 22 && c.getScaleY() === 11, 'Revert child node'); - // ok(testChild.getComponent(TestScript) == null, 'Remove added component'); - // - // ok(testNode.getComponent(TestScript).target === testChild, 'Should redirect reference to scene node'); - // - // strictEqual(testChild.children.length, 0, 'Should remove new node'); - // - // strictEqual(testNode.childrenCount, 2, 'Should create removed node'); - // var created = testNode.children[1]; - // ok(created._sgNode, 'Checking created node'); - // - // var comp = created.getComponent(MyComponent); - // comp.resetExpect(CallbackTester.OnLoad, 'call onLoad while attaching to node'); - // comp.pushExpect(CallbackTester.OnEnable, 'then call onEnable if node active'); - // - // cc.director.getScene().addChild(testNode); - // - // comp.stopTest(); - // - // strictEqual(newNode2.isValid, false, 'should remove new node which is not the last sibling'); - // - // start(); - // }); - //}); })(); From dccf301be3e77081e33d4bb6c7448bfca38875e8 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Mon, 5 Sep 2016 10:55:18 +0800 Subject: [PATCH 245/268] fix targetedAction error for fireball/issues/4129 --- jsb/jsb-action.js | 36 ++++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/jsb/jsb-action.js b/jsb/jsb-action.js index f0fc376d2d..39e2945b6c 100644 --- a/jsb/jsb-action.js +++ b/jsb/jsb-action.js @@ -112,6 +112,16 @@ for (var i = 0; i < actionArr.length; ++i) { } } +cc.targetedAction = function (target, action) { + return new cc.TargetedAction(target, action); +}; + +cc.TargetedAction.prototype._ctor = function(target, action) { + var node = target._sgNode || target; + node._owner = target; + action && this.initWithTarget(node, action); +}; + cc.follow = function (followedNode, rect) { return new cc.Follow(followedNode._sgNode, rect); }; @@ -123,31 +133,25 @@ cc.Follow.prototype.update = function(dt) { } }; -cc.Show.prototype.update = function (dt) { - var target = this.getTarget(); - var _renderComps = target._owner.getComponentsInChildren(cc._SGComponent); +function setRendererVisibility (sgNode, toggleVisible, visible) { + if (!sgNode) { return; } + var _renderComps = sgNode._owner.getComponentsInChildren(cc._SGComponent); for (var i = 0; i < _renderComps.length; ++i) { var render = _renderComps[i]; - render.enabled = true; + render.enabled = toggleVisible ? !render.enabled : visible; } +} + +cc.Show.prototype.update = function (dt) { + setRendererVisibility(this.getTarget(), false, true); }; cc.Hide.prototype.update = function (dt) { - var target = this.getTarget(); - var _renderComps = target._owner.getComponentsInChildren(cc._SGComponent); - for (var i = 0; i < _renderComps.length; ++i) { - var render = _renderComps[i]; - render.enabled = false; - } + setRendererVisibility(this.getTarget(), false, false); }; cc.ToggleVisibility.prototype.update = function (dt) { - var target = this.getTarget(); - var _renderComps = target._owner.getComponentsInChildren(cc._SGComponent); - for (var i = 0; i < _renderComps.length; ++i) { - var render = _renderComps[i]; - render.enabled = true; - } + setRendererVisibility(this.getTarget(), true); }; // Special call func From fda6c98d8aba73a5cfea3682bb8fb872b5a701f5 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Mon, 5 Sep 2016 11:31:06 +0800 Subject: [PATCH 246/268] fix tintTo and tintBy in the Simulator displays an error for fireball/issues/4137 --- cocos2d/core/utils/base-node.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/cocos2d/core/utils/base-node.js b/cocos2d/core/utils/base-node.js index 2e727fd3b3..12c4f26394 100644 --- a/cocos2d/core/utils/base-node.js +++ b/cocos2d/core/utils/base-node.js @@ -1980,6 +1980,10 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ sgNode.setGlobalZOrder(self._globalZOrder); + if (CC_JSB) { + // fix tintTo and tintBy action for jsb displays err for fireball/issues/4137 + sgNode.setColor(this._color); + } sgNode.setOpacity(self._opacity); sgNode.setOpacityModifyRGB(self._opacityModifyRGB); sgNode.setCascadeOpacityEnabled(self._cascadeOpacityEnabled); From 7ceba7b5122e100bbafeec9be610297f34be9068 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 2 Sep 2016 18:34:36 +0800 Subject: [PATCH 247/268] Improve webgl support detection and orientation adaptation --- cocos2d/core/platform/CCSys.js | 9 ++++++++- cocos2d/core/platform/CCView.js | 4 ++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/platform/CCSys.js b/cocos2d/core/platform/CCSys.js index 0c4463e89f..611b70eab7 100644 --- a/cocos2d/core/platform/CCSys.js +++ b/cocos2d/core/platform/CCSys.js @@ -705,10 +705,17 @@ else { var tmpCanvas = document.createElement("CANVAS"); try{ var context = cc.create3DContext(tmpCanvas, {'stencil': true}); - if(context) { + 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 (!window.indexedDB) { + _supportWebGL = false; + } + } + if (_supportWebGL && sys.os === sys.OS_ANDROID) { var browserVer = parseFloat(sys.browserVersion); switch (sys.browserType) { diff --git a/cocos2d/core/platform/CCView.js b/cocos2d/core/platform/CCView.js index c49b540ffe..042cece1e0 100644 --- a/cocos2d/core/platform/CCView.js +++ b/cocos2d/core/platform/CCView.js @@ -127,7 +127,7 @@ var View = cc._Class.extend({ // Custom callback for resize event _resizeCallback: null, - _orientationChanging: false, + _orientationChanging: true, _scaleX: 1, _originalScaleX: 1, @@ -217,7 +217,6 @@ var View = cc._Class.extend({ _orientationChange: function () { this._orientationChanging = true; this._resizeEvent(); - this._orientationChanging = false; }, /** @@ -325,6 +324,7 @@ var View = cc._Class.extend({ cc.container.style.transformOrigin = '0px 0px 0px'; this._isRotated = true; } + this._orientationChanging = false; }, // hack From 54e07aa6ac227e797c4032b48fe8183aecae6e9c Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 5 Sep 2016 17:50:40 +0800 Subject: [PATCH 248/268] Fix cc.log issue in JSB --- CCBoot.js | 10 ++++------ cocos2d/core/CCGame.js | 2 ++ cocos2d/core/utils/base-node.js | 4 ++-- jsb/index.js | 6 +++--- jsb/jsb-game.js | 5 +++-- 5 files changed, 14 insertions(+), 13 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index aca973689b..ad944f8cbf 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -152,20 +152,18 @@ function _getJsListOfModule(moduleMap, moduleName, dir) { return jsList; } -function _afterEngineLoaded(config) { - cc._initDebugSetting(config[cc.game.CONFIG_KEY.debugMode]); +function _afterEngineLoaded() { cc._engineLoaded = true; - cc.log(cc.ENGINE_VERSION); + console.log(cc.ENGINE_VERSION); if (_engineLoadedCallback) _engineLoadedCallback(); } function _load(config) { - var self = this; var CONFIG_KEY = cc.game.CONFIG_KEY, engineDir = config[CONFIG_KEY.engineDir], loader = cc.loader; if (cc._Class) { // Single file loaded - _afterEngineLoaded(config); + _afterEngineLoaded(); } else { // Load cocos modules var ccModulesPath = cc.path.join(engineDir, "moduleConfig.json"); @@ -182,7 +180,7 @@ function _load(config) { } loader.load(jsList, function (err) { if (err) throw new Error(JSON.stringify(err)); - _afterEngineLoaded(config); + _afterEngineLoaded(); }); }); } diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index 30b1efdd2c..bc756d4792 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -631,6 +631,8 @@ var game = { // Collide Map and Group List this.collisionMatrix = config.collisionMatrix || []; this.groupList = config.groupList || []; + + cc._initDebugSetting(config[CONFIG_KEY.debugMode]); this.config = config; }, diff --git a/cocos2d/core/utils/base-node.js b/cocos2d/core/utils/base-node.js index 7b5a6a53d2..60731f904a 100644 --- a/cocos2d/core/utils/base-node.js +++ b/cocos2d/core/utils/base-node.js @@ -688,8 +688,8 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ }, /** - * !#en Indicate whether node's opacity value affect its child nodes, default value is false. - * !#zh 节点的不透明度值是否影响其子节点,默认值为 false。 + * !#en Indicate whether node's opacity value affect its child nodes, default value is true. + * !#zh 节点的不透明度值是否影响其子节点,默认值为 true。 * @property cascadeOpacity * @type {Boolean} * @example diff --git a/jsb/index.js b/jsb/index.js index 091abb149e..3b0ae026de 100644 --- a/jsb/index.js +++ b/jsb/index.js @@ -54,19 +54,19 @@ if (_engineNumberVersion) { } } +var originLog = console.log; + // cc.initEngine cc.initEngine = function (config, cb) { require('script/jsb.js'); cc._renderType = cc.game.RENDER_TYPE_OPENGL; - cc._initDebugSetting(config ? config[cc.game.CONFIG_KEY.debugMode] : 0); cc._engineLoaded = true; - cc.log(cc.ENGINE_VERSION); + originLog(cc.ENGINE_VERSION); if (cb) cb(); }; // overwrite original console.log try { - var originLog = console.log; console.log = function () { originLog.call(console, cc.js.formatStr.apply(null, arguments)); }; diff --git a/jsb/jsb-game.js b/jsb/jsb-game.js index f2b31eba24..a725dcc931 100644 --- a/jsb/jsb-game.js +++ b/jsb/jsb-game.js @@ -252,8 +252,9 @@ cc.js.mixin(cc.game, { // Scene parser this._sceneInfos = config[CONFIG_KEY.scenes] || []; - cc.director.setDisplayStats(this.config[CONFIG_KEY.showFPS]); - cc.director.setAnimationInterval(1.0/this.config[CONFIG_KEY.frameRate]); + cc.director.setDisplayStats(config[CONFIG_KEY.showFPS]); + cc.director.setAnimationInterval(1.0/config[CONFIG_KEY.frameRate]); + cc._initDebugSetting(config[CONFIG_KEY.debugMode]); this.config = config; } From bd1d89ae98c4c843b3997d3aa12144b6cc14b955 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 5 Sep 2016 18:46:56 +0800 Subject: [PATCH 249/268] review code --- cocos2d/audio/CCAudio.js | 30 +- cocos2d/audio/CCAudioEngine.js | 421 +++++++++++------- cocos2d/core/CCGame.js | 11 +- cocos2d/core/components/CCAudioSource.js | 58 +-- .../core/load-pipeline/audio-downloader.js | 4 +- cocos2d/deprecated.js | 122 +++++ jsb/index.js | 1 + jsb/jsb-audio.js | 88 ++++ jsb/jsb-etc.js | 4 + 9 files changed, 536 insertions(+), 203 deletions(-) create mode 100644 jsb/jsb-audio.js diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index 7bff802160..2893a35fcb 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -29,12 +29,14 @@ var touchPlayList = [ //{ offset: 0, audio: audio } ]; -var Audio = function () { +var Audio = function (src) { + this._src = src; this._audioType = Audio.Type.UNKNOWN; this._element = null; this._eventList = {}; this._state = Audio.State.ERROR; + this._loaded = false; }; Audio.Type = { @@ -52,6 +54,25 @@ Audio.State = { (function (proto) { + proto.startLoad = function () { + var src = this._src, + audio = this; + var item = cc.loader.getItem(src); + + // If the resource does not exist + if (!item) { + return cc.loader.load(src, function (error) { + if (!error) { + var item = cc.loader.getItem(src); + audio.mount(item.element || item.buffer); + audio.emit('load'); + } + }); + } + audio.mount(item.element || item.buffer); + audio.emit('load'); + }; + proto.on = function (event, callback) { var list = this._eventList[event]; if (!list) { @@ -99,6 +120,7 @@ Audio.State = { }; } this._state = Audio.State.INITIALZING; + this._loaded = true; }; proto.play = function () { @@ -141,7 +163,9 @@ Audio.State = { proto.stop = function () { if (!this._element) return; this._element.pause(); - this._element.currentTime = 0; + try { + this._element.currentTime = 0; + } catch (error) {} this.emit('pause'); this._state = Audio.State.PAUSED; }; @@ -186,7 +210,7 @@ Audio.State = { })(Audio.prototype); -// 将 webAudio 封装出 dom 的接口,方便统一调用 +// Encapsulated WebAudio interface var webAudioElement = function (buffer) { this._context = cc.sys.__audioSupport.context; this._buffer = buffer; diff --git a/cocos2d/audio/CCAudioEngine.js b/cocos2d/audio/CCAudioEngine.js index 2ecdad315a..c48a5b3912 100644 --- a/cocos2d/audio/CCAudioEngine.js +++ b/cocos2d/audio/CCAudioEngine.js @@ -38,7 +38,7 @@ var getAudioFromPath = function (path) { } var audio; if (audioEngine._maxAudioInstance > list.length) { - audio = new Audio(); + audio = new Audio(path); id2audio[id] = audio; } else { var oldId = list.shift(); @@ -55,21 +55,6 @@ var getAudioFromId = function (id) { return id2audio[id]; }; -// Wait for playing queue -var waitQueue = []; -var addWaitQueue = function (id) { - var index = waitQueue.indexOf(id); - if (index !== -1) return false; - waitQueue.push(id); - return true; -}; -var removeWaitQueue = function (id) { - var index = waitQueue.indexOf(id); - if (index === -1) return false; - waitQueue.splice(index, 1); - return true; -}; - var audioEngine = { AudioState: Audio.State, @@ -77,38 +62,43 @@ var audioEngine = { _maxWebAudioSize: 307200, // 300kb * 1024 _maxAudioInstance: 24, - play: function () { - return this.play2d.apply(this, arguments); - }, - - play2d: function (filePath, loop, volume/*, profile*/) { - var item = cc.loader.getItem(filePath); + _id2audio: id2audio, + /** + * !#en Play audio. + * !#zh 播放音频 + * @method play + * @param {String} filePath - The path of the audio file without filename extension. + * @param {Boolean} loop - Whether the music loop or not. + * @param {Number} volume - Volume size. + * @return {Number} audioId + * @example + * //example + * cc.audioEngine.(path, false, 0.5); + */ + play: function (filePath, loop, volume/*, profile*/) { var audio = getAudioFromPath(filePath); + var callback = function () { + audio.setLoop(loop || false); + audio.setVolume(volume || 1); + audio.play(); + }; + audio.on('load', callback); + audio.startLoad(); - // If the resource does not exist - if (!item) { - addWaitQueue(audio.instanceId); - cc.loader.load(filePath, function (error) { - if (!error) { - var item = cc.loader.getItem(filePath); - audio.mount(item.element || item.buffer); - audio.setLoop(loop || false); - audio.setVolume(volume || 1); - if (removeWaitQueue(audio.instanceId)) { - audio.play(); - } - } - }); - return audio.instanceId; - } - - audio.mount(item.element || item.buffer); - audio.setLoop(loop || false); - audio.setVolume(volume || 1); - audio.play(); return audio.instanceId; }, + + /** + * !#en Set audio loop. + * !#zh 设置音频是否循环。 + * @method setLoop + * @param {Number} audioID - audio id. + * @param {Boolean} loop - Whether cycle. + * @example + * //example + * cc.audioEngine.setLoop(id, true); + */ setLoop: function (audioID, loop) { var audio = getAudioFromId(audioID); if (!audio || !audio.setLoop) @@ -116,32 +106,87 @@ var audioEngine = { audio.setLoop(loop); return loop; }, + + /** + * !#en Get audio cycle state. + * !#zh 获取音频的循环状态。 + * @method isLoop + * @param {Number} audioID - audio id. + * @return {Boolean} Whether cycle. + * @example + * //example + * cc.audioEngine.isLoop(id); + */ isLoop: function (audioID) { var audio = getAudioFromId(audioID); if (!audio || !audio.isLoop) return false; return audio.isLoop(); }, + + /** + * !#en Set the volume of audio. + * !#zh 设置音量(0.0 ~ 1.0)。 + * @method setVolume + * @param {Number} audioID audio id. + * @param {Number} volume Volume must be in 0.0~1.0 . + * @example + * //example + * cc.audioEngine.setVolume(0.5); + */ setVolume: function (audioID, volume) { var audio = getAudioFromId(audioID); if (!audio || !audio.setVolume) - return volume; + return; audio.setVolume(volume); - return volume; }, + + /** + * !#en The volume of the music max value is 1.0,the min value is 0.0 . + * !#zh 获取音量(0.0 ~ 1.0)。 + * @method getVolume + * @param {Number} audioID audio id. + * @return {Boolean} + * @example + * //example + * var volume = cc.audioEngine.getVolume(id); + */ getVolume: function (audioID) { var audio = getAudioFromId(audioID); if (!audio || !audio.getVolume) return 1; return audio.getVolume(); }, + + /** + * !#en Set current time + * !#zh 设置当前的音频时间。 + * @method setCurrentTime + * @param {Number} audioID audio id. + * @param {Number} sec current time. + * @return {Boolean} + * @example + * //example + * cc.audioEngine.setCurrentTime(id, 2); + */ setCurrentTime: function (audioID, sec) { var audio = getAudioFromId(audioID); if (!audio || !audio.setCurrentTime) - return sec; + return false; audio.setCurrentTime(sec); - return sec; + return true; }, + + /** + * !#en Get current time + * !#zh 获取当前的音频播放时间。 + * @method getCurrentTime + * @param {Number} audioID audio id. + * @return {Number} audio current time. + * @example + * //example + * var time = cc.audioEngine.getCurrentTime(id); + */ getCurrentTime: function (audioID) { var audio = getAudioFromId(audioID); if (!audio || !audio.getCurrentTime) @@ -149,12 +194,33 @@ var audioEngine = { return audio.getCurrentTime(); }, + /** + * !#en Get audio duration + * !#zh 获取音频总时长。 + * @method getDuration + * @param {Number} audioID audio id. + * @return {Number} audio duration. + * @example + * //example + * var time = cc.audioEngine.getDuration(id); + */ getDuration: function (audioID) { var audio = getAudioFromId(audioID); if (!audio || !audio.getDuration) return 0; return audio.getDuration(); }, + + /** + * !#en Get audio state + * !#zh 获取音频状态。 + * @method getState + * @param {Number} audioID audio id. + * @return {cc.audioEngine.AudioState} audio duration. + * @example + * //example + * var state = cc.audioEngine.getState(id); + */ getState: function (audioID) { var audio = getAudioFromId(audioID); if (!audio || !audio.getState) @@ -162,6 +228,17 @@ var audioEngine = { return audio.getState(); }, + /** + * !#en Get audio state + * !#zh 获取音频状态。 + * @method getState + * @param {Number} audioID audio id. + * @param {Function} callback loaded callback. + * @return {Boolean} Whether set successfully. + * @example + * //example + * cc.audioEngine.setFinishCallback(id, function () {}); + */ setFinishCallback: function (audioID, callback) { var audio = getAudioFromId(audioID); if (!audio) @@ -169,17 +246,34 @@ var audioEngine = { audio.off('ended'); audio.on('ended', callback); + return true; }, + /** + * !#en Pause playing audio. + * !#zh 暂停正在播放音频。 + * @method pause + * @example + * //example + * cc.audioEngine.pause(id); + */ pause: function (audioID) { var audio = getAudioFromId(audioID); if (!audio || !audio.pause) return false; audio.pause(); - removeWaitQueue(audioID); return true; }, _pauseIDCache: [], + + /** + * !#en Pause all playing audio + * !#zh 暂停现在正在播放的所有音频。 + * @method pauseAll + * @example + * //example + * cc.audioEngine.pauseAll(); + */ pauseAll: function () { for (var id in id2audio) { var audio = id2audio[id]; @@ -189,10 +283,16 @@ var audioEngine = { audio.pause(); } } - while (waitQueue.length > 0) { - this._pauseIDCache.push(waitQueue.pop()); - } }, + + /** + * !#en Resume playing audio. + * !#zh 恢复播放指定的音频。 + * @method resume + * @param {Number} audioID - The return value of function play. + * //example + * cc.audioEngine.resume(audioID); + */ resume: function (audioID) { var audio = getAudioFromId(audioID); if (!audio || !audio.resume) @@ -203,6 +303,15 @@ var audioEngine = { audio.resume(); } }, + + /** + * !#en Resume all playing audio. + * !#zh 恢复播放所有之前暂停的所有音频。 + * @method resumeAll + * @example + * //example + * cc.audioEngine.resumeAll(); + */ resumeAll: function () { while (this._pauseIDCache.length > 0) { var id = this._pauseIDCache.pop(); @@ -211,14 +320,32 @@ var audioEngine = { audio.resume(); } }, + + /** + * !#en Stop playing audio. + * !#zh 停止播放指定音频。 + * @method stop + * @param {Number} audioID - The return value of function play. + * @example + * //example + * cc.audioEngine.stop(audioID); + */ stop: function (audioID) { var audio = getAudioFromId(audioID); if (!audio || !audio.stop) return false; audio.stop(); - removeWaitQueue(audioID); return true; }, + + /** + * !#en Stop all playing audio. + * !#zh 停止正在播放的所有音频。 + * @method stopAll + * @example + * //example + * cc.audioEngine.stopAll(); + */ stopAll: function () { for (var id in id2audio) { var audio = id2audio[id]; @@ -226,15 +353,41 @@ var audioEngine = { audio.stop(); } } - waitQueue = []; }, + /** + * !#en Set up an audio can generate a few examples. + * !#zh 设置一个音频可以设置几个实例 + * @method setMaxAudioInstance + * @example + * //example + * cc.audioEngine.setMaxAudioInstance(20); + */ setMaxAudioInstance: function (num) { return this._maxAudioInstance = num; }, + + /** + * !#en Getting audio can produce several examples. + * !#zh 获取一个音频可以设置几个实例 + * @method getMaxAudioInstance + * @example + * //example + * cc.audioEngine.getMaxAudioInstance(); + */ getMaxAudioInstance: function () { return this._maxAudioInstance; }, + + /** + * !#en Unload the preloaded audio from internal buffer. + * !#zh 卸载预加载的音频。 + * @method uncache + * @param {String} filePath + * @example + * //example + * cc.audioEngine.uncache(filePath); + */ uncache: function (filePath) { var list = url2id[filePath]; if (!list) return; @@ -247,132 +400,60 @@ var audioEngine = { } } }, + + /** + * !#en Unload all audio from internal buffer. + * !#zh 卸载所有音频。 + * @method uncacheAll + * @example + * //example + * cc.audioEngine.uncacheAll(); + */ uncacheAll: function () { this.stopAll(); id2audio = {}; url2id = {}; }, - // getProfile - getProfile: function () {}, - // preload - preload: function () {}, + /** + * !#en Gets an audio profile by name. + * + * @param profileName A name of audio profile. + * @return The audio profile. + */ + getProfile: function (profileName) {}, - // web 独占接口 - // 设置一个大小,单位为kb,超过这个大小则直接解析成 dom 节点 - // 因为 webAudio 占用内存过多,所以让用户自己手动取舍 + /** + * !#en Preload audio file. + * !#zh 预加载一个音频 + * @param filePath The file path of an audio. + * @param callback The callback of an audio. + * @method preload + * @example + * //example + * cc.audioEngine.preload(path); + */ + preload: function (filePath, callback) { + cc.loader.load(filePath, function (error) { + if (!error) { + callback(); + } + }); + }, + + /** + * !#en Set a size, the unit is KB,Over this size is directly resolved into DOM nodes + * !#zh 设置一个以kb为单位的尺寸,大于这个尺寸的音频在加载的时候会强制使用 dom 方式加载 + * @param kb The file path of an audio. + * @method setMaxWebAudioSize + * @example + * //example + * cc.audioEngine.setMaxWebAudioSize(300); + */ + // Because webAudio takes up too much memory,So allow users to manually choose setMaxWebAudioSize: function (kb) { this._maxWebAudioSize = kb * 1024; - }, - - // deprecated - _musicId: -1, - _backgroundVolume: 1, - _effectsVolume: 1, - willPlayMusic: function () { return false; }, - playMusic: function (url, loop) { - cc.log('audioEngine.playMusic is deprecated, please call audioEngine.play'); - this._musicId = this.play(url, loop, this._backgroundVolume); - return this._musicId; - }, - stopMusic: function () { - cc.log('audioEngine.stopMusic is deprecated, please call audioEngine.stop'); - this.stop(this._musicId); - return this._musicId; - }, - pauseMusic: function () { - cc.log('audioEngine.pauseMusic is deprecated, please call audioEngine.pause'); - this.pause(this._musicId); - return this._musicId; - }, - resumeMusic: function () { - cc.log('audioEngine.resumeMusic is deprecated, please call audioEngine.resume'); - this.resume(this._musicId); - return this._musicId; - }, - rewindMusic: function () { - cc.log('audioEngine.rewindMusic is deprecated, please call audioEngine.setCurrentTime'); - this.setCurrentTime(this._musicId, 0); - return this._musicId; - }, - getMusicVolume: function () { - cc.log('audioEngine.getMusicVolume is deprecated, please call audioEngine.getVolume'); - return this._backgroundVolume; - }, - setMusicVolume: function (volume) { - cc.log('audioEngine.setMusicVolume is deprecated, please call audioEngine.setVolume'); - this._backgroundVolume = volume; - this.setVolume(this._musicId, volume); - return this._backgroundVolume; - }, - isMusicPlaying: function () { - cc.log('audioEngine.isMusicPlaying is deprecated, please call audioEngine.getState'); - return this.getState(this._musicId) === Audio.State.PLAYING; - }, - playEffect: function (url, loop, volume) { - cc.log('audioEngine.playEffect is deprecated, please call audioEngine.play'); - return this.play(url, loop, volume === undefined ? this._effectsVolume : volume); - }, - setEffectsVolume: function (volume) { - cc.log('audioEngine.setEffectsVolume is deprecated, please call audioEngine.setVolume'); - this._effectsVolume = volume; - for (var id in id2audio) { - if (id === this._musicId) continue; - this.setVolume(id, volume); - } - }, - getEffectsVolume: function () { - cc.log('audioEngine.getEffectsVolume is deprecated, please call audioEngine.getVolume'); - return this._effectsVolume; - }, - pauseEffect: function (id) { - cc.log('audioEngine.pauseEffect is deprecated, please call audioEngine.pause'); - return this.pause(id); - }, - pauseAllEffects: function () { - cc.log('audioEngine.pauseAllEffects is deprecated, please call audioEngine.pause'); - for (var id in id2audio) { - if (id === this._musicId) continue; - var audio = id2audio[id]; - var state = audio.getState(); - if (state === Audio.State.PLAYING) { - this._pauseIDCache.push(id); - audio.pause(); - } - } - while (waitQueue.length > 0) { - this._pauseIDCache.push(waitQueue.pop()); - } - }, - resumeEffect: function (id) { - cc.log('audioEngine.resumeEffect is deprecated, please call audioEngine.resume'); - this.resume(id); - }, - resumeAllEffects: function () { - cc.log('audioEngine.resumeAllEffects is deprecated, please call audioEngine.resumeAll'); - while (this._pauseIDCache.length > 0) { - var id = this._pauseIDCache.pop(); - var audio = getAudioFromId(id); - if (audio && audio.resume) - audio.resume(); - } - }, - stopEffect: function (id) { - cc.log('audioEngine.stopEffect is deprecated, please call audioEngine.stop'); - return this.stop(id); - }, - stopAllEffects: function (id) { - cc.log('audioEngine.stopEffect is deprecated, please call audioEngine.stop'); - return this.stop(id); - }, - unloadEffect: function () { - cc.log('audioEngine.stopEffect is deprecated, please call audioEngine.stop'); - return this.stop(id); - }, - end: function () { - cc.log('audioEngine.end is deprecated, please call audioEngine.stopAll'); - return this.stopAll(); } }; -module.exports = audioEngine; \ No newline at end of file +module.exports = cc.audioEngine = audioEngine; \ No newline at end of file diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index e9cc7fe659..3c5348c6ec 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -30,6 +30,7 @@ if (!(CC_EDITOR && Editor.isMainProcess)) { } var audioEngine = cc.audioEngine = require('../audio/CCAudioEngine'); +var isMusicPlaying = false; /** * !#en An object to boot the game. @@ -253,7 +254,10 @@ var game = { if (this._paused) return; this._paused = true; // Pause audio engine - audioEngine && audioEngine.pauseAll(); + if (audioEngine) { + isMusicPlaying = true; + audioEngine.pauseAll(); + } // Pause main loop if (this._intervalId) window.cancelAnimationFrame(this._intervalId); @@ -270,7 +274,10 @@ var game = { if (!this._paused) return; this._paused = false; // Resume audio engine - audioEngine && audioEngine.resumeAll(); + if (audioEngine && isMusicPlaying) { + isMusicPlaying = false; + audioEngine.resumeAll(); + } // Resume main loop this._runMainLoop(); }, diff --git a/cocos2d/core/components/CCAudioSource.js b/cocos2d/core/components/CCAudioSource.js index 3305d6d100..d2a9397eb6 100644 --- a/cocos2d/core/components/CCAudioSource.js +++ b/cocos2d/core/components/CCAudioSource.js @@ -30,13 +30,6 @@ * @extends Component */ -var audioEngine; - -if (cc.sys.isNative) { - audioEngine = jsb.AudioEngine; -} else { - audioEngine = require('../../audio/CCAudioEngine'); -} var AudioSource = cc.Class({ name: 'cc.AudioSource', @@ -48,7 +41,7 @@ var AudioSource = cc.Class({ }, ctor: function () { - this.audioID = 0; + this.audio = new cc.Audio(this._clip); }, properties: { @@ -74,9 +67,9 @@ var AudioSource = cc.Class({ */ isPlaying: { get: function () { - if (!this.audioID) return false; - var state = audioEngine.getState(this.audioID); - return state === audioEngine.AudioState.PLAYING; + if (!this.audio) return false; + var state = this.audio.getState(); + return state === cc.Audio.State.PLAYING; }, visible: false }, @@ -94,6 +87,10 @@ var AudioSource = cc.Class({ }, set: function (value) { this._clip = value; + this.audio.src = this._clip; + if (this.audio.startLoad) { + this.audio.startLoad(); + } }, url: cc.AudioClip, tooltip: 'i18n:COMPONENT.audio.clip', @@ -113,8 +110,9 @@ var AudioSource = cc.Class({ }, set: function (value) { this._volume = value; - if (!this.audioID) return value; - audioEngine.setVolume(value); + if (this.audio && !this._mute) { + this.audio.setVolume(value); + } return value; }, tooltip: 'i18n:COMPONENT.audio.volume' @@ -133,8 +131,9 @@ var AudioSource = cc.Class({ }, set: function (value) { this._mute = value; - if (!this.audioID) return value; - audioEngine.setVolume(0); + if (this.audio) { + this.audio.setVolume(value ? 0 : this._volume); + } return value; }, animatable: false, @@ -154,8 +153,9 @@ var AudioSource = cc.Class({ }, set: function (value) { this._loop = value; - if (!this.audioID) return value; - audioEngine.setLoop(value); + if (this.audio) { + this.audio.setLoop(value); + } return value; }, animatable: false, @@ -199,7 +199,9 @@ var AudioSource = cc.Class({ play: function () { if ( this._clip ) { var volume = this._mute ? 0 : this._volume; - this.audioID = audioEngine.play2d(this._clip, this._loop, volume); + this.audio.setLoop(this._loop); + this.audio.setVolume(volume); + this.audio.play(); } }, @@ -209,8 +211,9 @@ var AudioSource = cc.Class({ * @method stop */ stop: function () { - if (this.audioID === undefined) return false; - audioEngine.stop(this.audioID); + if (this.audio) { + this.audio.stop(); + } }, /** @@ -219,8 +222,9 @@ var AudioSource = cc.Class({ * @method pause */ pause: function () { - if (this.audioID === undefined) return false; - audioEngine.pause(this.audioID); + if (this.audio) { + this.audio.pause(); + } }, /** @@ -229,8 +233,9 @@ var AudioSource = cc.Class({ * @method resume */ resume: function () { - if (this.audioID === undefined) return false; - audioEngine.resume(this.audioID); + if (this.audio) { + this.audio.resume(); + } }, /** @@ -239,8 +244,9 @@ var AudioSource = cc.Class({ * @method rewind */ rewind: function(){ - if (this.audioID === undefined) return false; - audioEngine.setCurrentTime(this.audioID, 0); + if (this.audio) { + this.audio.setCurrentTime(0); + } } }); diff --git a/cocos2d/core/load-pipeline/audio-downloader.js b/cocos2d/core/load-pipeline/audio-downloader.js index d70c8d50d3..b46b5b65f8 100644 --- a/cocos2d/core/load-pipeline/audio-downloader.js +++ b/cocos2d/core/load-pipeline/audio-downloader.js @@ -97,11 +97,11 @@ function downloadAudio (item, callback) { item.content = item.url; if (!__audioSupport.WEB_AUDIO) { - // 不支持 webAudio 就直接使用 dom 方式加载 + // If WebAudio is not supported, load using DOM mode return loadDomAudio(item, callback); } - // 获取一次头文件 + // Get a header // check audio size var request = Pipeline.getXMLHttpRequest(); request.open("HEAD", item.url, true); diff --git a/cocos2d/deprecated.js b/cocos2d/deprecated.js index c36d786f4f..f8350b8866 100644 --- a/cocos2d/deprecated.js +++ b/cocos2d/deprecated.js @@ -655,4 +655,126 @@ if (CC_DEV && typeof eruda === 'undefined') { } }, }); + + (function (audioEngine) { + if (typeof audioEngine === 'undefined') return; + markAsRemoved(audioEngine, ['willPlayMusic']); + var musicId = -1; + var musicVolume = 1; + var effectsVolume = 1; + var pauseIDCache = []; + js.get(audioEngine, 'playMusic', function (url, loop) { + cc.warn(INFO, 'audioEngine.playMusic', 'audioEngine.play'); + musicId = this.play(url, loop, musicVolume); + return musicId; + }); + js.get(audioEngine, 'stopMusic', function () { + cc.warn(INFO, 'audioEngine.stopMusic', 'audioEngine.stop'); + this.stop(musicId); + return musicId; + }); + js.get(audioEngine, 'pauseMusic', function () { + cc.warn(INFO, 'audioEngine.pauseMusic', 'audioEngine.pause'); + this.pause(musicId); + return musicId; + }); + js.get(audioEngine, 'resumeMusic', function () { + cc.warn(INFO, 'audioEngine.resumeMusic', 'audioEngine.resume'); + this.resume(musicId); + return musicId; + }); + js.get(audioEngine, 'rewindMusic', function () { + cc.warn(INFO, 'audioEngine.rewindMusic', 'audioEngine.setCurrentTime'); + this.setCurrentTime(musicId, 0); + return musicId; + }); + js.get(audioEngine, 'getMusicVolume', function () { + cc.warn(INFO, 'audioEngine.getMusicVolume', 'audioEngine.getVolume'); + return musicVolume; + }); + js.get(audioEngine, 'setMusicVolume', function (volume) { + cc.warn(INFO, 'audioEngine.setMusicVolume', 'audioEngine.setVolume'); + musicVolume = volume; + this.setVolume(musicId, musicVolume); + return musicVolume; + }); + js.get(audioEngine, 'isMusicPlaying', function () { + cc.warn(INFO, 'audioEngine.isMusicPlaying', 'audioEngine.getState'); + return this.getState(musicId) === this.AudioState.PLAYING; + }); + js.get(audioEngine, 'playEffect', function (url, loop, volume) { + cc.warn(INFO, 'audioEngine.playEffect', 'audioEngine.play'); + return this.play(url, loop, volume === undefined ? effectsVolume : volume); + }); + js.get(audioEngine, 'setEffectsVolume', function (volume) { + cc.warn(INFO, 'audioEngine.setEffectsVolume', 'audioEngine.setVolume'); + effectsVolume = volume; + var id2audio = this._id2audio; + for (var id in id2audio) { + if (id === musicId) continue; + this.setVolume(id, volume); + } + }); + js.get(audioEngine, 'getEffectsVolume', function () { + cc.warn(INFO, 'audioEngine.getEffectsVolume', 'audioEngine.getVolume'); + return effectsVolume; + }); + js.get(audioEngine, 'pauseEffect', function (id) { + cc.warn(INFO, 'audioEngine.pauseEffect', 'audioEngine.pause'); + return this.pause(id); + }); + js.get(audioEngine, 'pauseAllEffects', function () { + cc.warn(INFO, 'audioEngine.pauseAllEffects', 'audioEngine.pauseAll'); + var id2audio = this._id2audio; + for (var id in id2audio) { + if (id === musicId) continue; + var audio = id2audio[id]; + var state = audio.getState(); + if (state === this.AudioState.PLAYING) { + pauseIDCache.push(id); + audio.pause(); + } + } + }); + js.get(audioEngine, 'resumeEffect', function (id) { + cc.warn(INFO, 'audioEngine.resumeEffect', 'audioEngine.resume'); + this.resume(id); + }); + js.get(audioEngine, 'resumeAllEffects', function () { + cc.warn(INFO, 'audioEngine.resumeEffect', 'audioEngine.resume'); + var id2audio = this._id2audio; + while (pauseIDCache.length > 0) { + var id = pauseIDCache.pop(); + var audio = id2audio[id]; + if (audio && audio.resume) + audio.resume(); + } + }); + js.get(audioEngine, 'stopEffect', function (id) { + cc.warn(INFO, 'audioEngine.stopEffect', 'audioEngine.stop'); + return this.stop(id); + }); + js.get(audioEngine, 'stopAllEffects', function () { + cc.warn(INFO, 'audioEngine.stopAllEffects', 'audioEngine.stopAll'); + var id2audio = this._id2audio; + for (var id in id2audio) { + if (id === musicId) continue; + var audio = id2audio[id]; + var state = audio.getState(); + if (state === this.AudioState.PLAYING) { + audio.stop(); + } + } + }); + js.get(audioEngine, 'unloadEffect', function (id) { + cc.warn(INFO, 'audioEngine.unloadEffect', 'audioEngine.stop'); + return this.stop(id); + }); + js.get(audioEngine, 'end', function () { + cc.warn(INFO, 'audioEngine.end', 'audioEngine.stopAll'); + return this.stopAll(); + }); + + })(cc.audioEngine); + } diff --git a/jsb/index.js b/jsb/index.js index a840eab77a..a3b2093b45 100644 --- a/jsb/index.js +++ b/jsb/index.js @@ -105,6 +105,7 @@ require('./jsb-enums'); require('./jsb-event'); require('./jsb-action'); require('./jsb-etc'); +require('./jsb-audio'); if (cc.runtime) { require('./versions/jsb-polyfill-runtime'); diff --git a/jsb/jsb-audio.js b/jsb/jsb-audio.js new file mode 100644 index 0000000000..b1fdd81c47 --- /dev/null +++ b/jsb/jsb-audio.js @@ -0,0 +1,88 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Chukong Aipu reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +cc.Audio = function (src) { + this.src = src; + this.volume = 1; + this.loop = false; + + this.id = -1; +}; + +(function (prototype, audioEngine) { + + prototype.State = audioEngine.AudioState; + + prototype.play = function () { + this.id = audioEngine.play2d(this.src, this.loop, this.volume); + }; + + prototype.pause = function () { + audioEngine.pause(this.id); + }; + + prototype.resume = function () { + audioEngine.resume(this.id); + }; + + prototype.stop = function () { + audioEngine.stop(this.id); + }; + + prototype.setLoop = function (loop) { + this.loop = loop; + audioEngine.setLoop(this.id, loop) + }; + + prototype.getLoop = function () { + return audioEngine.getLoop(this.id) + }; + + prototype.setVolume = function (volume) { + this.volume = volume; + return audioEngine.setVolume(this.id, volume) + }; + + prototype.getVolume = function () { + return audioEngine.getVolume(this.id) + }; + + prototype.setCurrentTime = function (time) { + audioEngine.setCurrentTime(this.id, time); + }; + + prototype.getCurrentTime = function () { + return audioEngine.getCurrentTime(this.id) + }; + + prototype.getDuration = function () { + return audioEngine.getDuration(this.id) + }; + + prototype.getState = function () { + return audioEngine.getState(this.id) + }; + +})(cc.Audio.prototype, jsb.AudioEngine); \ No newline at end of file diff --git a/jsb/jsb-etc.js b/jsb/jsb-etc.js index 853258faa5..cc98d65f13 100644 --- a/jsb/jsb-etc.js +++ b/jsb/jsb-etc.js @@ -235,3 +235,7 @@ cc.formatStr = cc.js.formatStr; if (cc.Image && cc.Image.setPNGPremultipliedAlphaEnabled) { cc.Image.setPNGPremultipliedAlphaEnabled(false); } + +if (cc.audioEngine) { + cc.audioEngine.setMaxWebAudioSize = function () {}; +} \ No newline at end of file From 4a38d84fbf0a752c7aa5152acb78ee6c4e522027 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 6 Sep 2016 09:28:42 +0800 Subject: [PATCH 250/268] create cc.Audio --- 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 2893a35fcb..94543c5cc0 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -350,4 +350,4 @@ var webAudioElement = function (buffer) { })(webAudioElement.prototype); -module.exports = Audio; \ No newline at end of file +module.exports = cc.Audio = Audio; \ No newline at end of file From d15b82f476e2f6444d99ec7cb78084340b29f354 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Tue, 6 Sep 2016 10:41:03 +0800 Subject: [PATCH 251/268] fix label shrink effect --- cocos2d/core/label/CCSGLabelCanvasRenderCmd.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js b/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js index 045359499c..22c49effd0 100644 --- a/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js +++ b/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js @@ -224,6 +224,7 @@ var node = this._node; var paragraphedStrings = node._string.split('\n'); + node._fontSize = node._drawFontsize; var fontDesc = this._constructFontDesc(); this._labelContext.font = fontDesc; @@ -305,6 +306,7 @@ node._fontSize = (this._drawFontsize * Math.min(1, scaleX, scaleY)) | 0; fontDesc = this._constructFontDesc(); + this._labelContext.font = fontDesc; } } From 30f1edfcfc0c2965950c14afb0b985987f3a2e69 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Tue, 6 Sep 2016 11:00:35 +0800 Subject: [PATCH 252/268] minor fix --- cocos2d/core/CCNode.js | 5 +---- cocos2d/core/assets/CCPrefab.js | 6 ++++-- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index a98cf4d96f..ec525115cc 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -395,10 +395,7 @@ var Node = cc.Class({ * @type {PrefabInfo} * @private */ - _prefab: { - default: null, - editorOnly: true - }, + _prefab: null, /** * If true, the node is an persist node which won't be destroyed during scene transition. diff --git a/cocos2d/core/assets/CCPrefab.js b/cocos2d/core/assets/CCPrefab.js index 5a59bd7195..a7a515fc39 100644 --- a/cocos2d/core/assets/CCPrefab.js +++ b/cocos2d/core/assets/CCPrefab.js @@ -55,8 +55,10 @@ var Prefab = cc.Class({ }, _instantiate: function () { - // prefab asset is always synced - this.data._prefab._synced = true; + //if (this.data._prefab) { + // prefab asset is always synced + this.data._prefab._synced = true; + //} // instantiate var node = cc.instantiate(this.data); From 58f1d4ac9b4cc578fca259c3dd88d95c32951db6 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Tue, 6 Sep 2016 11:19:55 +0800 Subject: [PATCH 253/268] fix wrap edge cases --- cocos2d/core/components/CCRichText.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/components/CCRichText.js b/cocos2d/core/components/CCRichText.js index 443f1baa1d..60e9337173 100644 --- a/cocos2d/core/components/CCRichText.js +++ b/cocos2d/core/components/CCRichText.js @@ -356,12 +356,12 @@ var RichText = cc.Class({ if (this._lineOffsetX > 0 && fragmentWidth + this._lineOffsetX > this.maxWidth) { //concat previous line var checkStartIndex = 0; - while (this._lineOffsetX < this.maxWidth) { + while (this._lineOffsetX <= this.maxWidth) { var checkEndIndex = this._getFirstWordLen(labelString, checkStartIndex, labelString.length); var checkString = labelString.substr(checkStartIndex, checkEndIndex); var checkStringWidth = this._measureText(checkString, styleIndex); - if(this._lineOffsetX + checkStringWidth < this.maxWidth) { + if(this._lineOffsetX + checkStringWidth <= this.maxWidth) { this._lineOffsetX += checkStringWidth; checkStartIndex += checkEndIndex; } else { From 232e6a53c5555a39ce974a19bafdc720dc822b91 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Tue, 6 Sep 2016 11:45:32 +0800 Subject: [PATCH 254/268] fix Scrollview mouse wheel scroll direction --- cocos2d/core/components/CCScrollView.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/components/CCScrollView.js b/cocos2d/core/components/CCScrollView.js index 90e35cd21e..0a535109cf 100644 --- a/cocos2d/core/components/CCScrollView.js +++ b/cocos2d/core/components/CCScrollView.js @@ -707,9 +707,9 @@ var ScrollView = cc.Class({ if (!this.enabledInHierarchy) return; var deltaMove = cc.p(0, 0); - var wheelPrecision = 1.0 / 40; + var wheelPrecision = -0.1; if(CC_JSB) { - wheelPrecision = 7; + wheelPrecision = -7; } if(this.vertical) { deltaMove = cc.p(0, event.getScrollY() * wheelPrecision); From 4734c20e22e02b5d369c21aa12cd5dc585a3268c Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Tue, 6 Sep 2016 18:02:00 +0800 Subject: [PATCH 255/268] refine ttf file loading --- cocos2d/core/label/CCSGLabel.js | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/cocos2d/core/label/CCSGLabel.js b/cocos2d/core/label/CCSGLabel.js index 8705cc99b0..0ab2ecaf3f 100644 --- a/cocos2d/core/label/CCSGLabel.js +++ b/cocos2d/core/label/CCSGLabel.js @@ -440,10 +440,14 @@ _ccsg.Label = _ccsg.Node.extend({ _divStyle.top = "-100px"; doc.body.appendChild(preloadDiv); this._preloadDiv = preloadDiv; - self.scheduleOnce(function () { - self._notifyLabelSkinDirty(); - self.emit("load"); - }, 2); + fontStyle.onload = function() { + + self.scheduleOnce(function() { + self._notifyLabelSkinDirty(); + self.emit("load"); + },0.1); + }; + } return fontFamilyName; From c6d536899775aa0f4b679334bb5d3ecdb7db1937 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Tue, 6 Sep 2016 18:03:08 +0800 Subject: [PATCH 256/268] add api href for spine official runtime --- extensions/spine/SGSkeleton.js | 17 ++++++--- extensions/spine/Skeleton.js | 64 ++++++++++++++++++++------------ extensions/spine/SkeletonData.js | 6 ++- extensions/spine/index.js | 10 +++++ 4 files changed, 66 insertions(+), 31 deletions(-) diff --git a/extensions/spine/SGSkeleton.js b/extensions/spine/SGSkeleton.js index 386d7b4614..43fd396091 100644 --- a/extensions/spine/SGSkeleton.js +++ b/extensions/spine/SGSkeleton.js @@ -208,7 +208,8 @@ sp._SGSkeleton = _ccsg.Node.extend({ }, /** - * Finds a bone by name. This does a string comparison for every bone. + * Finds a bone by name. This does a string comparison for every bone.
+ * Returns a {{#crossLinkModule "spine"}}spine{{/crossLinkModule}}.Bone object. * @param {String} boneName * @returns {spine.Bone} */ @@ -217,7 +218,9 @@ sp._SGSkeleton = _ccsg.Node.extend({ }, /** - * Finds a slot by name. This does a string comparison for every slot. + * Finds a slot by name. This does a string comparison for every slot.
+ * Returns a {{#crossLinkModule "spine"}}spine{{/crossLinkModule}}.Slot object. + * * @param {String} slotName * @returns {spine.Slot} */ @@ -226,7 +229,9 @@ sp._SGSkeleton = _ccsg.Node.extend({ }, /** - * 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. + * 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.
+ * Returns a {{#crossLinkModule "spine"}}spine{{/crossLinkModule}}.Skin object. + * * @param {string} skinName * @returns {spine.Skin} */ @@ -235,10 +240,12 @@ sp._SGSkeleton = _ccsg.Node.extend({ }, /** - * Returns the attachment for the slot and attachment name. The skeleton looks first in its skin, then in the skeleton data’s default skin. + * Returns the attachment for the slot and attachment name. The skeleton looks first in its skin, then in the skeleton data’s default skin.
+ * Returns a {{#crossLinkModule "spine"}}spine{{/crossLinkModule}}.Attachment object. + * * @param {String} slotName * @param {String} attachmentName - * @returns {spine.RegionAttachment|spine.BoundingBoxAttachment} + * @returns {spine.Attachment} */ getAttachment: function (slotName, attachmentName) { return this._skeleton.getAttachmentBySlotName(slotName, attachmentName); diff --git a/extensions/spine/Skeleton.js b/extensions/spine/Skeleton.js index 67dea2fa9a..c2197280fd 100644 --- a/extensions/spine/Skeleton.js +++ b/extensions/spine/Skeleton.js @@ -504,10 +504,13 @@ sp.Skeleton = cc.Class({ /** * !#en * Finds a bone by name. - * This does a string comparison for every bone. + * This does a string comparison for every bone.
+ * Returns a {{#crossLinkModule "spine"}}spine{{/crossLinkModule}}.Bone object. * !#zh * 通过名称查找 bone。 - * 这里对每个 bone 的名称进行了对比。 + * 这里对每个 bone 的名称进行了对比。
+ * 返回一个 {{#crossLinkModule "spine"}}spine{{/crossLinkModule}}.Bone 对象。 + * * @method findBone * @param {String} boneName * @return {spine.Bone} @@ -521,11 +524,12 @@ sp.Skeleton = cc.Class({ /** * !#en - * Finds a slot by name. - * This does a string comparison for every slot. + * Finds a slot by name. This does a string comparison for every slot.
+ * Returns a {{#crossLinkModule "spine"}}spine{{/crossLinkModule}}.Slot object. * !#zh - * 通过名称查找 slot。 - * 这里对每个 slot 的名称进行了比较。 + * 通过名称查找 slot。这里对每个 slot 的名称进行了比较。
+ * 返回一个 {{#crossLinkModule "spine"}}spine{{/crossLinkModule}}.Slot 对象。 + * * @method findSlot * @param {String} slotName * @return {spine.Slot} @@ -540,12 +544,14 @@ sp.Skeleton = cc.Class({ /** * !#en * 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. + * This does a string comparison for every skin.
+ * Note that setting the skin does not change which attachments are visible.
+ * Returns a {{#crossLinkModule "spine"}}spine{{/crossLinkModule}}.Skin object. * !#zh - * 按名称查找皮肤,激活该皮肤。 - * 这里对每个皮肤的名称进行了比较。 - * 注意:设置皮肤不会改变 attachment 的可见性。。 + * 按名称查找皮肤,激活该皮肤。这里对每个皮肤的名称进行了比较。
+ * 注意:设置皮肤不会改变 attachment 的可见性。
+ * 返回一个 {{#crossLinkModule "spine"}}spine{{/crossLinkModule}}.Skin 对象。 + * * @method setSkin * @param {String} skinName * @return {spine.Skin} @@ -560,14 +566,16 @@ sp.Skeleton = cc.Class({ /** * !#en * Returns the attachment for the slot and attachment name. - * The skeleton looks first in its skin, then in the skeleton data’s default skin. + * The skeleton looks first in its skin, then in the skeleton data’s default skin.
+ * Returns a {{#crossLinkModule "spine"}}spine{{/crossLinkModule}}.Attachment object. * !#zh - * 通过 slot 和 attachment 的名称获取 attachment。 - * Skeleton 优先查找它的皮肤,然后才是 Skeleton Data 中默认的皮肤。 + * 通过 slot 和 attachment 的名称获取 attachment。Skeleton 优先查找它的皮肤,然后才是 Skeleton Data 中默认的皮肤。
+ * 返回一个 {{#crossLinkModule "spine"}}spine{{/crossLinkModule}}.Attachment 对象。 + * * @method getAttachment * @param {String} slotName * @param {String} attachmentName - * @return {spine.RegionAttachment|sp.spine.BoundingBoxAttachment} + * @return {spine.Attachment} */ getAttachment: function (slotName, attachmentName) { if (this._sgNode) { @@ -609,7 +617,7 @@ sp.Skeleton = cc.Class({ ///** // * Return the renderer of attachment. // * @method getTextureAtlas - // * @param {spine.RegionAttachment|sp.spine.BoundingBoxAttachment} regionAttachment + // * @param {spine.RegionAttachment|spine.BoundingBoxAttachment} regionAttachment // * @return {_ccsg.Node} // */ //getTextureAtlas: function (regionAttachment) { @@ -621,8 +629,10 @@ sp.Skeleton = cc.Class({ // ANIMATION /** - * !#en Sets animation state data. - * !#zh 设置动画状态数据。 + * !#en Sets animation state data.
+ * The parameter type is {{#crossLinkModule "spine"}}spine{{/crossLinkModule}}.AnimationStateData. + * !#zh 设置动画状态数据。
+ * 参数是 {{#crossLinkModule "spine"}}spine{{/crossLinkModule}}.AnimationStateData。 * @method setAnimationStateData * @param {spine.AnimationStateData} stateData */ @@ -662,8 +672,10 @@ sp.Skeleton = cc.Class({ }, /** - * !#en Set the current animation. Any queued animations are cleared. - * !#zh 设置当前动画。队列中的任何的动画将被清除。 + * !#en Set the current animation. Any queued animations are cleared.
+ * Returns a {{#crossLinkModule "spine"}}spine{{/crossLinkModule}}.TrackEntry object. + * !#zh 设置当前动画。队列中的任何的动画将被清除。
+ * 返回一个 {{#crossLinkModule "spine"}}spine{{/crossLinkModule}}.TrackEntry 对象。 * @method setAnimation * @param {Number} trackIndex * @param {String} name @@ -689,8 +701,10 @@ sp.Skeleton = cc.Class({ }, /** - * !#en Adds an animation to be played delay seconds after the current or last queued animation. - * !#zh 添加一个动画到动画队列尾部,还可以延迟指定的秒数。 + * !#en Adds an animation to be played delay seconds after the current or last queued animation.
+ * Returns a {{#crossLinkModule "spine"}}spine{{/crossLinkModule}}.TrackEntry object. + * !#zh 添加一个动画到动画队列尾部,还可以延迟指定的秒数。
+ * 返回一个 {{#crossLinkModule "spine"}}spine{{/crossLinkModule}}.TrackEntry 对象。 * @method addAnimation * @param {Number} trackIndex * @param {String} name @@ -706,8 +720,10 @@ sp.Skeleton = cc.Class({ }, /** - * !#en Returns track entry by trackIndex. - * !#zh 通过 track 索引获取 TrackEntry。 + * !#en Returns track entry by trackIndex.
+ * Returns a {{#crossLinkModule "spine"}}spine{{/crossLinkModule}}.TrackEntry object. + * !#zh 通过 track 索引获取 TrackEntry。
+ * 返回一个 {{#crossLinkModule "spine"}}spine{{/crossLinkModule}}.TrackEntry 对象。 * @method getCurrent * @param trackIndex * @return {spine.TrackEntry} diff --git a/extensions/spine/SkeletonData.js b/extensions/spine/SkeletonData.js index 37aba4712d..373fceae74 100644 --- a/extensions/spine/SkeletonData.js +++ b/extensions/spine/SkeletonData.js @@ -187,8 +187,10 @@ var SkeletonData = cc.Class({ }, /** - * !#en Get the included SkeletonData used in spine runtime. - * !#zh 获取 Spine Runtime 使用的 SkeletonData。 + * !#en Get the included SkeletonData used in spine runtime.
+ * Returns a {{#crossLinkModule "spine"}}spine{{/crossLinkModule}}.SkeletonData object. + * !#zh 获取 Spine Runtime 使用的 SkeletonData。
+ * 返回一个 {{#crossLinkModule "spine"}}spine{{/crossLinkModule}}.SkeletonData 对象。 * @method getRuntimeData * @param {Boolean} [quiet=false] * @return {spine.SkeletonData} diff --git a/extensions/spine/index.js b/extensions/spine/index.js index 24e2f04352..67d7db7569 100644 --- a/extensions/spine/index.js +++ b/extensions/spine/index.js @@ -124,3 +124,13 @@ if (!CC_EDITOR || !Editor.isMainProcess) { else { require('./SkeletonData'); } + +/** + * !#en + * `spine` is the namespace for official Spine Runtime, which officially implemented and maintained by Spine.
+ * Please refer to the official documentation for its detailed usage: [http://en.esotericsoftware.com/spine-using-runtimes](http://en.esotericsoftware.com/spine-using-runtimes) + * !#zh + * spine 模块是 Spine 官方运行库的 API 入口,由 Spine 官方统一实现和维护,具体用法请参考:[http://zh.esotericsoftware.com/spine-using-runtimes](http://zh.esotericsoftware.com/spine-using-runtimes) + * @module spine + * @main spine + */ From 2bc87645f2834e75668c5775cde872e829ba5267 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 6 Sep 2016 18:22:54 +0800 Subject: [PATCH 257/268] review code and support jsb --- cocos2d/audio/CCAudio.js | 20 +- cocos2d/audio/CCAudioEngine.js | 9 +- cocos2d/core/CCGame.js | 5 +- cocos2d/core/components/CCAudioSource.js | 23 ++- cocos2d/deprecated.js | 236 ++++++++++++++--------- extends.js | 4 + index.js | 3 - jsb/jsb-audio.js | 84 ++++++-- 8 files changed, 252 insertions(+), 132 deletions(-) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index 94543c5cc0..e412424273 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -30,7 +30,7 @@ var touchPlayList = [ ]; var Audio = function (src) { - this._src = src; + this.src = src; this._audioType = Audio.Type.UNKNOWN; this._element = null; @@ -42,6 +42,7 @@ var Audio = function (src) { Audio.Type = { DOM: 'AUDIO', WEBAUDIO: 'WEBAUDIO', + NATIVE: 'NATIVE', UNKNOWN: 'UNKNOWN' }; @@ -54,8 +55,8 @@ Audio.State = { (function (proto) { - proto.startLoad = function () { - var src = this._src, + proto.preload = function () { + var src = this.src, audio = this; var item = cc.loader.getItem(src); @@ -80,6 +81,13 @@ Audio.State = { } list.push(callback); }; + proto.once = function (event, callback) { + var onceCallback = function (elem) { + callback.call(this, elem); + this.off(event, onceCallback); + }; + this.on(event, onceCallback); + }; proto.emit = function (event) { var list = this._eventList[event]; if (!list) return; @@ -113,7 +121,7 @@ Audio.State = { this.emit('ended', this); }, this); } else { - this._element = new webAudioElement(elem); + this._element = new WebAudioElement(elem); this._audioType = Audio.Type.WEBAUDIO; elem.onended = function () { this.emit('ended', this); @@ -211,7 +219,7 @@ Audio.State = { })(Audio.prototype); // Encapsulated WebAudio interface -var webAudioElement = function (buffer) { +var WebAudioElement = function (buffer) { this._context = cc.sys.__audioSupport.context; this._buffer = buffer; this._volume = this._context['createGain'](); @@ -348,6 +356,6 @@ var webAudioElement = function (buffer) { return num; }); -})(webAudioElement.prototype); +})(WebAudioElement.prototype); module.exports = cc.Audio = Audio; \ No newline at end of file diff --git a/cocos2d/audio/CCAudioEngine.js b/cocos2d/audio/CCAudioEngine.js index c48a5b3912..9705ce576c 100644 --- a/cocos2d/audio/CCAudioEngine.js +++ b/cocos2d/audio/CCAudioEngine.js @@ -84,7 +84,7 @@ var audioEngine = { audio.play(); }; audio.on('load', callback); - audio.startLoad(); + audio.preload(); return audio.instanceId; }, @@ -102,9 +102,8 @@ var audioEngine = { setLoop: function (audioID, loop) { var audio = getAudioFromId(audioID); if (!audio || !audio.setLoop) - return loop; + return; audio.setLoop(loop); - return loop; }, /** @@ -234,7 +233,6 @@ var audioEngine = { * @method getState * @param {Number} audioID audio id. * @param {Function} callback loaded callback. - * @return {Boolean} Whether set successfully. * @example * //example * cc.audioEngine.setFinishCallback(id, function () {}); @@ -242,11 +240,10 @@ var audioEngine = { setFinishCallback: function (audioID, callback) { var audio = getAudioFromId(audioID); if (!audio) - return false; + return; audio.off('ended'); audio.on('ended', callback); - return true; }, /** diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index 9fbe2e50a4..7dd7151a96 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -30,7 +30,6 @@ if (!(CC_EDITOR && Editor.isMainProcess)) { } var audioEngine = cc.audioEngine = require('../audio/CCAudioEngine'); -var isMusicPlaying = false; /** * !#en An object to boot the game. @@ -255,7 +254,6 @@ var game = { this._paused = true; // Pause audio engine if (audioEngine) { - isMusicPlaying = true; audioEngine.pauseAll(); } // Pause main loop @@ -274,8 +272,7 @@ var game = { if (!this._paused) return; this._paused = false; // Resume audio engine - if (audioEngine && isMusicPlaying) { - isMusicPlaying = false; + if (audioEngine) { audioEngine.resumeAll(); } // Resume main loop diff --git a/cocos2d/core/components/CCAudioSource.js b/cocos2d/core/components/CCAudioSource.js index d2a9397eb6..d134f7f2d2 100644 --- a/cocos2d/core/components/CCAudioSource.js +++ b/cocos2d/core/components/CCAudioSource.js @@ -41,7 +41,7 @@ var AudioSource = cc.Class({ }, ctor: function () { - this.audio = new cc.Audio(this._clip); + this.audio = new cc.Audio(); }, properties: { @@ -88,8 +88,8 @@ var AudioSource = cc.Class({ set: function (value) { this._clip = value; this.audio.src = this._clip; - if (this.audio.startLoad) { - this.audio.startLoad(); + if (this.audio.preload) { + this.audio.preload(); } }, url: cc.AudioClip, @@ -197,12 +197,17 @@ var AudioSource = cc.Class({ * @method play */ play: function () { - if ( this._clip ) { - var volume = this._mute ? 0 : this._volume; - this.audio.setLoop(this._loop); - this.audio.setVolume(volume); - this.audio.play(); - } + if ( !this._clip ) return; + + var volume = this._mute ? 0 : this._volume; + var audio = this.audio; + audio.src = this._clip; + audio.setLoop(this._loop); + audio.setVolume(volume); + audio.once('load', function () { + audio.play(); + }); + audio.preload(); }, /** diff --git a/cocos2d/deprecated.js b/cocos2d/deprecated.js index 88db96570d..1b08d8831b 100644 --- a/cocos2d/deprecated.js +++ b/cocos2d/deprecated.js @@ -279,7 +279,9 @@ if (CC_DEV && typeof eruda === 'undefined') { } // deprecateEnum(cc.ProgressTimer, 'cc.ProgressTimer.TYPE', 'cc.ProgressTimer.Type'); deprecateEnum(cc.game, 'cc.game.DEBUG_MODE', 'cc.DebugMode'); - deprecateEnum(cc, 'cc', 'cc.Texture2D.WrapMode', false); + if (!CC_JSB) { + deprecateEnum(cc, 'cc', 'cc.Texture2D.WrapMode', false); + } if (_ccsg.EditBox) { deprecateEnum(cc, 'cc.KEYBOARD_RETURNTYPE', '_ccsg.EditBox.KeyboardReturnType'); deprecateEnum(cc, 'cc.EDITBOX_INPUT_MODE', '_ccsg.EditBox.InputMode'); @@ -439,7 +441,7 @@ if (CC_DEV && typeof eruda === 'undefined') { removeAllComponents: 'removeComponent', getNodeToParentAffineTransform: 'getNodeToParentTransform', }); - + // RENDERERS function shouldNotUseNodeProp (component) { @@ -549,29 +551,32 @@ if (CC_DEV && typeof eruda === 'undefined') { Mode: 'EmitterMode' }); - // _ccsg.Node - markAsRemoved(_ccsg.Node, [ - '_normalizedPositionDirty', - '_normalizedPosition', - '_usingNormalizedPosition', - 'grid', - 'userData', - 'userObject', - 'getNormalizedPosition', - 'setNormalizedPosition', - 'getCamera', - 'getUserData', - 'setUserData', - 'getUserObject', - 'setUserObject', - 'getComponent', - 'addComponent', - 'removeComponent', - 'removeAllComponents', - 'enumerateChildren', - 'setCameraMask', - 'getCameraMask' - ], '_ccsg.Node'); + if (!CC_JSB) { + // _ccsg.Node + markAsRemoved(_ccsg.Node, [ + '_normalizedPositionDirty', + '_normalizedPosition', + '_usingNormalizedPosition', + 'grid', + 'userData', + 'userObject', + 'getNormalizedPosition', + 'setNormalizedPosition', + 'getCamera', + 'getUserData', + 'setUserData', + 'getUserObject', + 'setUserObject', + 'getComponent', + 'addComponent', + 'removeComponent', + 'removeAllComponents', + 'enumerateChildren', + 'setCameraMask', + 'getCameraMask' + ], '_ccsg.Node'); + } + js.obsolete(_ccsg.Node.prototype, '_ccsg.Node.ignoreAnchorPointForPosition', 'setIgnoreAnchorPointForPosition'); js.obsoletes(cc.Scale9Sprite.prototype, 'cc.Scale9Sprite', { @@ -658,123 +663,174 @@ if (CC_DEV && typeof eruda === 'undefined') { (function (audioEngine) { if (typeof audioEngine === 'undefined') return; - markAsRemoved(audioEngine, ['willPlayMusic']); + + (function (prop) { + function error () { + cc.error('Sorry, %s.%s is removed.', 'cc.audioEngine', prop); + } + js.getset(audioEngine, prop, error, error); + })('willPlayMusic'); + var musicId = -1; var musicVolume = 1; var effectsVolume = 1; var pauseIDCache = []; - js.get(audioEngine, 'playMusic', function (url, loop) { + js.get(audioEngine, 'playMusic', function () { cc.warn(INFO, 'audioEngine.playMusic', 'audioEngine.play'); - musicId = this.play(url, loop, musicVolume); - return musicId; + return function (url, loop) { + musicId = audioEngine.play(url, loop, musicVolume); + return musicId; + } }); js.get(audioEngine, 'stopMusic', function () { cc.warn(INFO, 'audioEngine.stopMusic', 'audioEngine.stop'); - this.stop(musicId); - return musicId; + return function () { + audioEngine.stop(musicId); + return musicId; + } }); js.get(audioEngine, 'pauseMusic', function () { cc.warn(INFO, 'audioEngine.pauseMusic', 'audioEngine.pause'); - this.pause(musicId); - return musicId; + return function () { + audioEngine.pause(musicId); + return musicId; + } }); js.get(audioEngine, 'resumeMusic', function () { cc.warn(INFO, 'audioEngine.resumeMusic', 'audioEngine.resume'); - this.resume(musicId); - return musicId; + return function () { + audioEngine.resume(musicId); + return musicId; + } }); js.get(audioEngine, 'rewindMusic', function () { cc.warn(INFO, 'audioEngine.rewindMusic', 'audioEngine.setCurrentTime'); - this.setCurrentTime(musicId, 0); - return musicId; + return function () { + audioEngine.setCurrentTime(musicId, 0); + return musicId; + } }); js.get(audioEngine, 'getMusicVolume', function () { cc.warn(INFO, 'audioEngine.getMusicVolume', 'audioEngine.getVolume'); - return musicVolume; + return function () { + return musicVolume; + } }); - js.get(audioEngine, 'setMusicVolume', function (volume) { + js.get(audioEngine, 'setMusicVolume', function () { cc.warn(INFO, 'audioEngine.setMusicVolume', 'audioEngine.setVolume'); - musicVolume = volume; - this.setVolume(musicId, musicVolume); - return musicVolume; + return function (volume) { + musicVolume = volume; + audioEngine.setVolume(musicId, musicVolume); + return musicVolume; + } }); js.get(audioEngine, 'isMusicPlaying', function () { cc.warn(INFO, 'audioEngine.isMusicPlaying', 'audioEngine.getState'); - return this.getState(musicId) === this.AudioState.PLAYING; + return function () { + return audioEngine.getState(musicId) === audioEngine.AudioState.PLAYING; + } }); - js.get(audioEngine, 'playEffect', function (url, loop, volume) { + js.get(audioEngine, 'playEffect', function () { cc.warn(INFO, 'audioEngine.playEffect', 'audioEngine.play'); - return this.play(url, loop, volume === undefined ? effectsVolume : volume); + + return function (url, loop, volume) { + return audioEngine.play(url, loop, volume === undefined ? effectsVolume : volume); + } }); js.get(audioEngine, 'setEffectsVolume', function (volume) { cc.warn(INFO, 'audioEngine.setEffectsVolume', 'audioEngine.setVolume'); - effectsVolume = volume; - var id2audio = this._id2audio; - for (var id in id2audio) { - if (id === musicId) continue; - this.setVolume(id, volume); + return function (volume) { + effectsVolume = volume; + var id2audio = audioEngine._id2audio; + for (var id in id2audio) { + if (id === musicId) continue; + audioEngine.setVolume(id, volume); + } } }); js.get(audioEngine, 'getEffectsVolume', function () { cc.warn(INFO, 'audioEngine.getEffectsVolume', 'audioEngine.getVolume'); - return effectsVolume; + return function () { + return effectsVolume; + } }); - js.get(audioEngine, 'pauseEffect', function (id) { + js.get(audioEngine, 'pauseEffect', function () { cc.warn(INFO, 'audioEngine.pauseEffect', 'audioEngine.pause'); - return this.pause(id); + + return function (id) { + return audioEngine.pause(id); + } }); js.get(audioEngine, 'pauseAllEffects', function () { cc.warn(INFO, 'audioEngine.pauseAllEffects', 'audioEngine.pauseAll'); - var id2audio = this._id2audio; - for (var id in id2audio) { - if (id === musicId) continue; - var audio = id2audio[id]; - var state = audio.getState(); - if (state === this.AudioState.PLAYING) { - pauseIDCache.push(id); - audio.pause(); + + return function () { + var id2audio = audioEngine._id2audio; + for (var id in id2audio) { + if (id === musicId) continue; + var audio = id2audio[id]; + var state = audio.getState(); + if (state === audioEngine.AudioState.PLAYING) { + pauseIDCache.push(id); + audio.pause(); + } } } }); - js.get(audioEngine, 'resumeEffect', function (id) { + js.get(audioEngine, 'resumeEffect', function () { cc.warn(INFO, 'audioEngine.resumeEffect', 'audioEngine.resume'); - this.resume(id); + return function (id) { + audioEngine.resume(id); + } }); js.get(audioEngine, 'resumeAllEffects', function () { cc.warn(INFO, 'audioEngine.resumeEffect', 'audioEngine.resume'); - var id2audio = this._id2audio; - while (pauseIDCache.length > 0) { - var id = pauseIDCache.pop(); - var audio = id2audio[id]; - if (audio && audio.resume) - audio.resume(); - } - }); - js.get(audioEngine, 'stopEffect', function (id) { - cc.warn(INFO, 'audioEngine.stopEffect', 'audioEngine.stop'); - return this.stop(id); - }); - js.get(audioEngine, 'stopAllEffects', function () { - cc.warn(INFO, 'audioEngine.stopAllEffects', 'audioEngine.stopAll'); - var id2audio = this._id2audio; - for (var id in id2audio) { - if (id === musicId) continue; - var audio = id2audio[id]; - var state = audio.getState(); - if (state === this.AudioState.PLAYING) { - audio.stop(); + return function () { + var id2audio = audioEngine._id2audio; + while (pauseIDCache.length > 0) { + var id = pauseIDCache.pop(); + var audio = id2audio[id]; + if (audio && audio.resume) + audio.resume(); } } }); - js.get(audioEngine, 'unloadEffect', function (id) { + js.get(audioEngine, 'stopEffect', function () { + cc.warn(INFO, 'audioEngine.stopEffect', 'audioEngine.stop'); + return function (id) { + return audioEngine.stop(id); + } + }); + js.get(audioEngine, 'stopAllEffects', function () { + cc.warn(INFO, 'audioEngine.stopAllEffects', 'audioEngine.stopAll'); + return function () { + var id2audio = audioEngine._id2audio; + for (var id in id2audio) { + if (id === musicId) continue; + var audio = id2audio[id]; + var state = audio.getState(); + if (state === audioEngine.AudioState.PLAYING) { + audio.stop(); + } + } + } + }); + js.get(audioEngine, 'unloadEffect', function () { cc.warn(INFO, 'audioEngine.unloadEffect', 'audioEngine.stop'); - return this.stop(id); - }); - js.get(audioEngine, 'end', function () { - cc.warn(INFO, 'audioEngine.end', 'audioEngine.stopAll'); - return this.stopAll(); + return function (id) { + return audioEngine.stop(id); + } }); + if (!CC_JSB) { + js.get(audioEngine, 'end', function () { + cc.warn(INFO, 'audioEngine.end', 'audioEngine.stopAll'); + return function () { + return audioEngine.stopAll(); + } + }); + } + })(cc.audioEngine); } diff --git a/extends.js b/extends.js index 72c662f0a8..67792ca8ee 100644 --- a/extends.js +++ b/extends.js @@ -56,3 +56,7 @@ if (!(CC_EDITOR && Editor.isMainProcess)) { require('./extensions/ccpool/CCNodePool.js'); require('./extensions/ccpool/CCPool.js'); } + +if (!CC_EDITOR || !Editor.isMainProcess) { + require('./cocos2d/deprecated'); +} \ No newline at end of file diff --git a/index.js b/index.js index 82e68c17f4..131ca7f84c 100644 --- a/index.js +++ b/index.js @@ -75,8 +75,5 @@ if (CC_EDITOR) { if (isMainProcess) { Editor.versions['cocos2d'] = require('./package.json').version; } -else { - require('./cocos2d/deprecated'); -} module.exports = cc; diff --git a/jsb/jsb-audio.js b/jsb/jsb-audio.js index b1fdd81c47..e79c41cb26 100644 --- a/jsb/jsb-audio.js +++ b/jsb/jsb-audio.js @@ -29,60 +29,116 @@ cc.Audio = function (src) { this.loop = false; this.id = -1; + this._eventList = {}; + + this.type = cc.Audio.Type.NATIVE; }; -(function (prototype, audioEngine) { +cc.Audio.Type = { + DOM: 'AUDIO', + WEBAUDIO: 'WEBAUDIO', + NATIVE: 'NATIVE', + UNKNOWN: 'UNKNOWN' +}; - prototype.State = audioEngine.AudioState; +(function (proto, audioEngine) { - prototype.play = function () { + // Using the new audioEngine + cc.audioEngine = audioEngine; + audioEngine.play = audioEngine.play2d; + + proto.State = audioEngine.AudioState; + + proto.play = function () { this.id = audioEngine.play2d(this.src, this.loop, this.volume); }; - prototype.pause = function () { + proto.pause = function () { audioEngine.pause(this.id); }; - prototype.resume = function () { + proto.resume = function () { audioEngine.resume(this.id); }; - prototype.stop = function () { + proto.stop = function () { audioEngine.stop(this.id); }; - prototype.setLoop = function (loop) { + proto.setLoop = function (loop) { this.loop = loop; audioEngine.setLoop(this.id, loop) }; - prototype.getLoop = function () { + proto.getLoop = function () { return audioEngine.getLoop(this.id) }; - prototype.setVolume = function (volume) { + proto.setVolume = function (volume) { this.volume = volume; return audioEngine.setVolume(this.id, volume) }; - prototype.getVolume = function () { + proto.getVolume = function () { return audioEngine.getVolume(this.id) }; - prototype.setCurrentTime = function (time) { + proto.setCurrentTime = function (time) { audioEngine.setCurrentTime(this.id, time); }; - prototype.getCurrentTime = function () { + proto.getCurrentTime = function () { return audioEngine.getCurrentTime(this.id) }; - prototype.getDuration = function () { + proto.getDuration = function () { return audioEngine.getDuration(this.id) }; - prototype.getState = function () { + proto.getState = function () { return audioEngine.getState(this.id) }; + proto.preload = function () { + this.emit('load'); + }; + + proto.on = function (event, callback) { + var list = this._eventList[event]; + if (!list) { + list = this._eventList[event] = []; + } + list.push(callback); + }; + proto.once = function (event, callback) { + var onceCallback = function (elem) { + callback.call(this, elem); + this.off(event, onceCallback); + }; + this.on(event, onceCallback); + }; + proto.emit = function (event) { + var list = this._eventList[event]; + if (!list) return; + for (var i=0; i Date: Mon, 5 Sep 2016 17:50:40 +0800 Subject: [PATCH 258/268] Fix cc.log issue --- CCBoot.js | 10 ++++------ cocos2d/core/CCGame.js | 2 ++ cocos2d/core/utils/base-node.js | 4 ++-- jsb/index.js | 8 +++----- jsb/jsb-game.js | 5 +++-- 5 files changed, 14 insertions(+), 15 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index 606c9d4276..6470fdf0a3 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -152,20 +152,18 @@ function _getJsListOfModule(moduleMap, moduleName, dir) { return jsList; } -function _afterEngineLoaded(config) { - cc._initDebugSetting(config[cc.game.CONFIG_KEY.debugMode]); +function _afterEngineLoaded() { cc._engineLoaded = true; - cc.log(cc.ENGINE_VERSION); + console.log(cc.ENGINE_VERSION); if (_engineLoadedCallback) _engineLoadedCallback(); } function _load(config) { - var self = this; var CONFIG_KEY = cc.game.CONFIG_KEY, engineDir = config[CONFIG_KEY.engineDir], loader = cc.loader; if (cc._Class) { // Single file loaded - _afterEngineLoaded(config); + _afterEngineLoaded(); } else { // Load cocos modules var ccModulesPath = cc.path.join(engineDir, "moduleConfig.json"); @@ -182,7 +180,7 @@ function _load(config) { } loader.load(jsList, function (err) { if (err) throw new Error(JSON.stringify(err)); - _afterEngineLoaded(config); + _afterEngineLoaded(); }); }); } diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index b79280f93a..af3d6ae010 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -629,6 +629,8 @@ var game = { // Collide Map and Group List this.collisionMatrix = config.collisionMatrix || []; this.groupList = config.groupList || []; + + cc._initDebugSetting(config[CONFIG_KEY.debugMode]); this.config = config; }, diff --git a/cocos2d/core/utils/base-node.js b/cocos2d/core/utils/base-node.js index aa1299f7b6..2497505744 100644 --- a/cocos2d/core/utils/base-node.js +++ b/cocos2d/core/utils/base-node.js @@ -688,8 +688,8 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ }, /** - * !#en Indicate whether node's opacity value affect its child nodes, default value is false. - * !#zh 节点的不透明度值是否影响其子节点,默认值为 false。 + * !#en Indicate whether node's opacity value affect its child nodes, default value is true. + * !#zh 节点的不透明度值是否影响其子节点,默认值为 true。 * @property cascadeOpacity * @type {Boolean} * @example diff --git a/jsb/index.js b/jsb/index.js index a840eab77a..3b0ae026de 100644 --- a/jsb/index.js +++ b/jsb/index.js @@ -54,21 +54,19 @@ if (_engineNumberVersion) { } } +var originLog = console.log; + // cc.initEngine cc.initEngine = function (config, cb) { require('script/jsb.js'); cc._renderType = cc.game.RENDER_TYPE_OPENGL; - if (config) { - cc._initDebugSetting(config[cc.game.CONFIG_KEY.debugMode]); - } cc._engineLoaded = true; - cc.log(cc.ENGINE_VERSION); + originLog(cc.ENGINE_VERSION); if (cb) cb(); }; // overwrite original console.log try { - var originLog = console.log; console.log = function () { originLog.call(console, cc.js.formatStr.apply(null, arguments)); }; diff --git a/jsb/jsb-game.js b/jsb/jsb-game.js index f2b31eba24..a725dcc931 100644 --- a/jsb/jsb-game.js +++ b/jsb/jsb-game.js @@ -252,8 +252,9 @@ cc.js.mixin(cc.game, { // Scene parser this._sceneInfos = config[CONFIG_KEY.scenes] || []; - cc.director.setDisplayStats(this.config[CONFIG_KEY.showFPS]); - cc.director.setAnimationInterval(1.0/this.config[CONFIG_KEY.frameRate]); + cc.director.setDisplayStats(config[CONFIG_KEY.showFPS]); + cc.director.setAnimationInterval(1.0/config[CONFIG_KEY.frameRate]); + cc._initDebugSetting(config[CONFIG_KEY.debugMode]); this.config = config; } From dd628378562a8fedf590a39b1ae5feb33031a8b4 Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Wed, 7 Sep 2016 10:13:49 +0800 Subject: [PATCH 259/268] small adjusts --- cocos2d/core/label/CCSGLabel.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/label/CCSGLabel.js b/cocos2d/core/label/CCSGLabel.js index 0ab2ecaf3f..85b488904b 100644 --- a/cocos2d/core/label/CCSGLabel.js +++ b/cocos2d/core/label/CCSGLabel.js @@ -441,7 +441,7 @@ _ccsg.Label = _ccsg.Node.extend({ doc.body.appendChild(preloadDiv); this._preloadDiv = preloadDiv; fontStyle.onload = function() { - + fontStyle.onload = null; self.scheduleOnce(function() { self._notifyLabelSkinDirty(); self.emit("load"); From d33cb280ae046a154d9779a332a30b586504ff82 Mon Sep 17 00:00:00 2001 From: zhangbin Date: Wed, 7 Sep 2016 15:15:56 +0800 Subject: [PATCH 260/268] Solve the error in the TiledMap parser. --- cocos2d/tilemap/CCTMXXMLParser.js | 23 +++++++++-------------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/cocos2d/tilemap/CCTMXXMLParser.js b/cocos2d/tilemap/CCTMXXMLParser.js index 482e931394..de265a9685 100644 --- a/cocos2d/tilemap/CCTMXXMLParser.js +++ b/cocos2d/tilemap/CCTMXXMLParser.js @@ -222,7 +222,6 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ // tile properties _tileProperties:null, _resources:"", - _currentFirstGID:0, // hex map values _staggerAxis: null, @@ -245,8 +244,6 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ this.properties = []; this._tileProperties = {}; - this._currentFirstGID = 0; - if (resourcePath !== undefined) { this.initWithXML(tmxFile,resourcePath); } else if(tmxFile !== undefined){ @@ -529,9 +526,10 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ /** Initalises parsing of an XML file, either a tmx (Map) file or tsx (Tileset) file * @param {String} tmxFile * @param {boolean} [isXmlString=false] + * @param {Number} tilesetFirstGid * @return {Element} */ - parseXMLFile:function (tmxFile, isXmlString) { + parseXMLFile:function (tmxFile, isXmlString, tilesetFirstGid) { isXmlString = isXmlString || false; var xmlStr = isXmlString ? tmxFile : cc.loader.getRes(tmxFile); if(!xmlStr) throw new Error("Please load the resource first : " + tmxFile); @@ -612,19 +610,17 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ // If this is an external tileset then start parsing that var tsxName = selTileset.getAttribute('source'); if (tsxName) { - //this._currentFirstGID = parseInt(selTileset.getAttribute('firstgid')); + var currentFirstGID = parseInt(selTileset.getAttribute('firstgid')); var tsxPath = isXmlString ? cc.path.join(this._resources, tsxName) : cc.path.changeBasename(tmxFile, tsxName); - this.parseXMLFile(tsxPath); + this.parseXMLFile(tsxPath, false, currentFirstGID); } else { var tileset = new cc.TMXTilesetInfo(); tileset.name = selTileset.getAttribute('name') || ""; - //TODO need fix - //if(this._currentFirstGID === 0){ - tileset.firstGid = parseInt(selTileset.getAttribute('firstgid')) || 0; - //}else{ - // tileset.firstGid = this._currentFirstGID; - // this._currentFirstGID = 0; - //} + if (tilesetFirstGid) { + tileset.firstGid = tilesetFirstGid; + } else { + tileset.firstGid = parseInt(selTileset.getAttribute('firstgid')) || 0; + } tileset.spacing = parseInt(selTileset.getAttribute('spacing')) || 0; tileset.margin = parseInt(selTileset.getAttribute('margin')) || 0; @@ -928,7 +924,6 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ this.storingCharacters = false; this.layerAttrs = cc.TMXLayerInfo.ATTRIB_NONE; this.parentElement = cc.TiledMap.NONE; - this._currentFirstGID = 0; } }); From 6e0f299d2ba2976ac3f56cf24e74057f6a510d4d Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Wed, 7 Sep 2016 14:13:09 +0800 Subject: [PATCH 261/268] support premultipliedAlpha on spine --- extensions/spine/Skeleton.js | 25 +++++++++++++++++++++++++ jsb/jsb-spine.js | 5 +++++ 2 files changed, 30 insertions(+) diff --git a/extensions/spine/Skeleton.js b/extensions/spine/Skeleton.js index c2197280fd..384b68f013 100644 --- a/extensions/spine/Skeleton.js +++ b/extensions/spine/Skeleton.js @@ -286,6 +286,28 @@ sp.Skeleton = cc.Class({ tooltip: 'i18n:COMPONENT.skeleton.loop' }, + /** + * !#en Indicates whether to enable premultiplied alpha. + * You should disable this option when image's transparent area appears to have opaque pixels, + * or enable this option when image's half transparent area appears to be darken. + * !#zh 是否启用贴图预乘。 + * 当图片的透明区域出现色块时需要关闭该选项,当图片的半透明区域颜色变黑时需要启用该选项。 + * @property {Boolean} premultipliedAlpha + * @default true + */ + _premultipliedAlpha: true, + premultipliedAlpha: { + get: function () { + return this._premultipliedAlpha; + }, + set: function (value) { + this._premultipliedAlpha = value; + if (this._sgNode) { + this._sgNode.setPremultipliedAlpha(value); + } + }, + tooltip: 'i18n:COMPONENT.skeleton.premultipliedAlpha' + }, /** * !#en The time scale of this skeleton. @@ -417,6 +439,9 @@ sp.Skeleton = cc.Class({ cc._throw(e); } } + + sgNode.setPremultipliedAlpha(this._premultipliedAlpha); + this.animation = this.defaultAnimation; if (CC_EDITOR) { sgNode.setDebugSlotsEnabled(this.debugSlots); diff --git a/jsb/jsb-spine.js b/jsb/jsb-spine.js index 53c6259d2b..096ef41d90 100644 --- a/jsb/jsb-spine.js +++ b/jsb/jsb-spine.js @@ -1,2 +1,7 @@ sp._SGSkeleton = sp.Skeleton; sp._SGSkeletonAnimation = sp.SkeletonAnimation; + +sp._SGSkeleton.prototype.setPremultipliedAlpha = sp._SGSkeleton.prototype.setOpacityModifyRGB; + +// 不能执行任何操作以免覆盖 premultiplied 属性 +sp._SGSkeleton.prototype.setOpacityModifyRGB = function () {}; From d735f05096013732a4e5f5fe14dfa880ec6844a4 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Wed, 7 Sep 2016 17:40:14 +0800 Subject: [PATCH 262/268] add scale transition --- cocos2d/core/components/CCButton.js | 91 +++++++++++++++++++++-------- 1 file changed, 68 insertions(+), 23 deletions(-) diff --git a/cocos2d/core/components/CCButton.js b/cocos2d/core/components/CCButton.js index 421ae56ff5..164e80c8fc 100644 --- a/cocos2d/core/components/CCButton.js +++ b/cocos2d/core/components/CCButton.js @@ -47,7 +47,13 @@ var Transition = cc.Enum({ * !#zh 精灵过渡 * @property {Number} SPRITE */ - SPRITE: 2 + SPRITE: 2, + /** + * !#en The scale type + * !#zh 缩放过渡 + * @property {Number} SCALE + */ + SCALE: 3 }); /** @@ -108,6 +114,9 @@ var Button = cc.Class({ this._toColor = null; this._time = 0; this._transitionFinished = true; + this._fromScale = 1.0; + this._toScale = 1.0; + this._originalScale = 1.0; this._sprite = null; @@ -225,8 +234,8 @@ var Button = cc.Class({ }, /** - * !#en Color transition duration - * !#zh 颜色过渡时所需时间 + * !#en Color and Scale transition duration + * !#zh 颜色过渡和绽放过渡时所需时间 * @property {Number} duration */ duration: { @@ -235,6 +244,11 @@ var Button = cc.Class({ tooltip: 'i18n:COMPONENT.button.duration', }, + zoomScale: { + default: 0.1, + tooltip: 'i18n:COMPONENT.button.zoomScale' + }, + // sprite transition /** * !#en Normal state sprite @@ -369,7 +383,8 @@ var Button = cc.Class({ update: function (dt) { var target = this.target; - if (!this.transition === Transition.COLOR || !target || this._transitionFinished) return; + if (!this.transition === Transition.COLOR || !this.transition === Transition.SCALE + || !target || this._transitionFinished) return; this.time += dt; var ratio = this.time / this.duration; @@ -378,7 +393,12 @@ var Button = cc.Class({ this._transitionFinished = true; } - target.color = this._fromColor.lerp(this._toColor, ratio); + if(this.transition === Transition.COLOR) { + target.color = this._fromColor.lerp(this._toColor, ratio); + } else if (this.transition === Transition.SCALE) { + target.scale = cc.lerp(this._fromScale, this._toScale, ratio); + } + }, _registerEvent: function () { @@ -406,6 +426,7 @@ var Button = cc.Class({ if (!this.interactable || !this.enabledInHierarchy) return; this._pressed = true; + this._zoomUp(); this._updateState(); event.stopPropagation(); }, @@ -436,14 +457,29 @@ var Button = cc.Class({ cc.Component.EventHandler.emitEvents(this.clickEvents, event); } this._pressed = false; + this._zoomBack(); this._updateState(); event.stopPropagation(); }, + _zoomUp: function () { + if(!this.target) return; + + this._originalScale = this.target.scale; + this._fromScale = this._originalScale; + this._toScale = this._originalScale + this.zoomScale; + }, + + _zoomBack: function () { + this._fromScale = this._originalScale + this.zoomScale; + this._toScale = this._originalScale; + }, + _onTouchCancel: function () { if (!this.interactable || !this.enabledInHierarchy) return; this._pressed = false; + this._zoomBack(); this._updateState(); }, @@ -452,36 +488,45 @@ var Button = cc.Class({ if (!this._hovered) { this._hovered = true; - this._updateState(); + if(this.transition !== Transition.SCALE) { + this._updateState(); + } } }, _onMouseMoveOut: function(){ if (this._hovered) { this._hovered = false; - this._updateState(); + if(this.transition !== Transition.SCALE) { + this._updateState(); + } } }, // state handler _updateState: function () { - var state; - if (!this.interactable) { - state = 'disabled'; - } - else if (this._pressed) { - state = 'pressed'; - } - else if (this._hovered) { - state = 'hover'; - } - else { - state = 'normal'; - } - var color = this[state + 'Color']; - var sprite = this[state + 'Sprite']; + if (this.transition === Transition.SCALE) { + this.time = 0; + this._transitionFinished = false; + } else { + var state; + if (!this.interactable) { + state = 'disabled'; + } + else if (this._pressed) { + state = 'pressed'; + } + else if (this._hovered) { + state = 'hover'; + } + else { + state = 'normal'; + } + var color = this[state + 'Color']; + var sprite = this[state + 'Sprite']; - this._applyTransition(color, sprite); + this._applyTransition(color, sprite); + } }, onDisable: function() { From 1cfde666a77d46a0d45850a05785c5f39e97a7be Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Wed, 7 Sep 2016 18:15:29 +0800 Subject: [PATCH 263/268] fix transition touch move --- cocos2d/core/components/CCButton.js | 53 ++++++++++++++++++----------- 1 file changed, 34 insertions(+), 19 deletions(-) diff --git a/cocos2d/core/components/CCButton.js b/cocos2d/core/components/CCButton.js index 164e80c8fc..0700d29977 100644 --- a/cocos2d/core/components/CCButton.js +++ b/cocos2d/core/components/CCButton.js @@ -116,7 +116,6 @@ var Button = cc.Class({ this._transitionFinished = true; this._fromScale = 1.0; this._toScale = 1.0; - this._originalScale = 1.0; this._sprite = null; @@ -244,6 +243,9 @@ var Button = cc.Class({ tooltip: 'i18n:COMPONENT.button.duration', }, + /** + * !#en + */ zoomScale: { default: 0.1, tooltip: 'i18n:COMPONENT.button.zoomScale' @@ -387,8 +389,12 @@ var Button = cc.Class({ || !target || this._transitionFinished) return; this.time += dt; - var ratio = this.time / this.duration; - if (ratio > 1) { + var ratio = 1.0; + if(this.duration > 0) { + ratio = this.time / this.duration; + } + + if (ratio >= 1) { ratio = 1; this._transitionFinished = true; } @@ -437,16 +443,24 @@ var Button = cc.Class({ // so we have to do hit test when touch moving var touch = event.touch; var hit = this.node._hitTest(touch.getLocation()); - var state; - if (hit) { - state = 'pressed'; - } else { - state = 'normal'; - } - var color = this[state + 'Color']; - var sprite = this[state + 'Sprite']; - this._applyTransition(color, sprite); + if(this.transition === Transition.SCALE && this.target) { + if(hit) { + this.target.scale = 1.0 + this.zoomScale; + } else { + this.target.scale = 1.0; + } + } else { + var state; + if (hit) { + state = 'pressed'; + } else { + state = 'normal'; + } + var color = this[state + 'Color']; + var sprite = this[state + 'Sprite']; + this._applyTransition(color, sprite); + } event.stopPropagation(); }, @@ -465,22 +479,23 @@ var Button = cc.Class({ _zoomUp: function () { if(!this.target) return; - this._originalScale = this.target.scale; - this._fromScale = this._originalScale; - this._toScale = this._originalScale + this.zoomScale; + this._fromScale = 1.0; + this._toScale = 1.0 + this.zoomScale; }, _zoomBack: function () { - this._fromScale = this._originalScale + this.zoomScale; - this._toScale = this._originalScale; + this._fromScale = 1.0 + this.zoomScale; + this._toScale = 1.0; }, _onTouchCancel: function () { if (!this.interactable || !this.enabledInHierarchy) return; this._pressed = false; - this._zoomBack(); - this._updateState(); + + if(this.transition !== Transition.SCALE) { + this._updateState(); + } }, _onMouseMoveIn: function () { From 9ac823877022eb85c720db40961310d871b92adc Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Thu, 8 Sep 2016 14:21:59 +0800 Subject: [PATCH 264/268] refactoring zoom feature --- cocos2d/core/components/CCButton.js | 69 ++++++++++++++--------------- 1 file changed, 33 insertions(+), 36 deletions(-) diff --git a/cocos2d/core/components/CCButton.js b/cocos2d/core/components/CCButton.js index 0700d29977..17245ba0ed 100644 --- a/cocos2d/core/components/CCButton.js +++ b/cocos2d/core/components/CCButton.js @@ -432,8 +432,11 @@ var Button = cc.Class({ if (!this.interactable || !this.enabledInHierarchy) return; this._pressed = true; - this._zoomUp(); - this._updateState(); + if(this.transition === Transition.SCALE) { + this._zoomUp(); + } else { + this._updateState(); + } event.stopPropagation(); }, @@ -471,21 +474,26 @@ var Button = cc.Class({ cc.Component.EventHandler.emitEvents(this.clickEvents, event); } this._pressed = false; - this._zoomBack(); - this._updateState(); + if(this.transition === Transition.SCALE) { + this._zoomBack(); + } else { + this._updateState(); + } event.stopPropagation(); }, _zoomUp: function () { - if(!this.target) return; - this._fromScale = 1.0; this._toScale = 1.0 + this.zoomScale; + this.time = 0; + this._transitionFinished = false; }, _zoomBack: function () { this._fromScale = 1.0 + this.zoomScale; this._toScale = 1.0; + this.time = 0; + this._transitionFinished = false; }, _onTouchCancel: function () { @@ -493,9 +501,7 @@ var Button = cc.Class({ this._pressed = false; - if(this.transition !== Transition.SCALE) { - this._updateState(); - } + this._updateState(); }, _onMouseMoveIn: function () { @@ -503,45 +509,36 @@ var Button = cc.Class({ if (!this._hovered) { this._hovered = true; - if(this.transition !== Transition.SCALE) { - this._updateState(); - } + this._updateState(); } }, _onMouseMoveOut: function(){ if (this._hovered) { this._hovered = false; - if(this.transition !== Transition.SCALE) { - this._updateState(); - } + this._updateState(); } }, // state handler _updateState: function () { - if (this.transition === Transition.SCALE) { - this.time = 0; - this._transitionFinished = false; - } else { - var state; - if (!this.interactable) { - state = 'disabled'; - } - else if (this._pressed) { - state = 'pressed'; - } - else if (this._hovered) { - state = 'hover'; - } - else { - state = 'normal'; - } - var color = this[state + 'Color']; - var sprite = this[state + 'Sprite']; - - this._applyTransition(color, sprite); + var state; + if (!this.interactable) { + state = 'disabled'; } + else if (this._pressed) { + state = 'pressed'; + } + else if (this._hovered) { + state = 'hover'; + } + else { + state = 'normal'; + } + var color = this[state + 'Color']; + var sprite = this[state + 'Sprite']; + + this._applyTransition(color, sprite); }, onDisable: function() { From 05591ad27e43819e66f54b33e1eb02627003d0c2 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Thu, 8 Sep 2016 15:07:55 +0800 Subject: [PATCH 265/268] all button custom scale --- cocos2d/core/components/CCButton.js | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/cocos2d/core/components/CCButton.js b/cocos2d/core/components/CCButton.js index 17245ba0ed..091b5d1b32 100644 --- a/cocos2d/core/components/CCButton.js +++ b/cocos2d/core/components/CCButton.js @@ -116,6 +116,7 @@ var Button = cc.Class({ this._transitionFinished = true; this._fromScale = 1.0; this._toScale = 1.0; + this._originalScale = 1.0; this._sprite = null; @@ -244,11 +245,14 @@ var Button = cc.Class({ }, /** - * !#en + * !#en When user press the button, the button will zoom to a scale. + * The final scale of the button equals (button original scale + zoomScale), zoomScale could be negative value. + * !#zh 当用户点击按钮后,按钮会缩放到一个值,这个值等于 Button原始 scale + zoomScale, zoomScale 可以为负数 + * @property {Number} zoomScale */ zoomScale: { default: 0.1, - tooltip: 'i18n:COMPONENT.button.zoomScale' + tooltip: 'i18n:COMPONENT.button.zoom_scale' }, // sprite transition @@ -421,6 +425,7 @@ var Button = cc.Class({ var target = this.target; if (target) { this._sprite = target.getComponent(cc.Sprite); + this._originalScale = target.scale; } else { this._sprite = null; @@ -449,9 +454,9 @@ var Button = cc.Class({ if(this.transition === Transition.SCALE && this.target) { if(hit) { - this.target.scale = 1.0 + this.zoomScale; + this.target.scale = this._originalScale + this.zoomScale; } else { - this.target.scale = 1.0; + this.target.scale = this._originalScale; } } else { var state; @@ -483,15 +488,15 @@ var Button = cc.Class({ }, _zoomUp: function () { - this._fromScale = 1.0; - this._toScale = 1.0 + this.zoomScale; + this._fromScale = this._originalScale; + this._toScale = this._originalScale + this.zoomScale; this.time = 0; this._transitionFinished = false; }, _zoomBack: function () { - this._fromScale = 1.0 + this.zoomScale; - this._toScale = 1.0; + this._fromScale = this._originalScale + this.zoomScale; + this._toScale = this._originalScale; this.time = 0; this._transitionFinished = false; }, From e93b8c22a4ae5027838cccff76809b8308f7806f Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Thu, 8 Sep 2016 18:02:25 +0800 Subject: [PATCH 266/268] finish resize node to target node --- cocos2d/core/components/CCButton.js | 41 ++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/components/CCButton.js b/cocos2d/core/components/CCButton.js index 091b5d1b32..dd76121984 100644 --- a/cocos2d/core/components/CCButton.js +++ b/cocos2d/core/components/CCButton.js @@ -168,6 +168,25 @@ var Button = cc.Class({ animatable: false }, + _resizeToTarget: { + serializable: false, + visible: false, + animatable: false, + set: function (value) { + if(value) { + this._resizeNodeToTargetNode(); + } + } + }, + + enableAutoGrayEffect: { + default: true, + tooltip: 'i18n:COMPONENT.button.auto_gray_effect', + notify: function () { + this._updateDisabledState(); + } + }, + /** * !#en Transition type * !#zh 按钮状态改变时过渡方式。 @@ -382,7 +401,7 @@ var Button = cc.Class({ } }, - start: function () { + onLoad: function () { this._applyTarget(); this._updateState(); }, @@ -544,6 +563,7 @@ var Button = cc.Class({ var sprite = this[state + 'Sprite']; this._applyTransition(color, sprite); + this._updateDisabledState(); }, onDisable: function() { @@ -584,6 +604,25 @@ var Button = cc.Class({ } }, + _resizeNodeToTargetNode: CC_EDITOR && function () { + if(this.target) { + this.node.setContentSize(this.target.getContentSize()); + } + }, + + _updateDisabledState: function () { + if(this._sprite) { + this._sprite._sgNode.setState(0); + } + if(this.enableAutoGrayEffect) { + if(! (this.transition === Transition.SPRITE && this.disabledSprite)) { + if(this._sprite && !this.interactable) { + this._sprite._sgNode.setState(1); + } + } + } + } + }); cc.Button = module.exports = Button; From d15afcf418e0a13eb48c243444c97719aa9926d2 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Fri, 9 Sep 2016 11:37:07 +0800 Subject: [PATCH 267/268] improve button scale transition --- cocos2d/core/components/CCButton.js | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/cocos2d/core/components/CCButton.js b/cocos2d/core/components/CCButton.js index dd76121984..0889d34fa3 100644 --- a/cocos2d/core/components/CCButton.js +++ b/cocos2d/core/components/CCButton.js @@ -169,8 +169,6 @@ var Button = cc.Class({ }, _resizeToTarget: { - serializable: false, - visible: false, animatable: false, set: function (value) { if(value) { @@ -179,6 +177,11 @@ var Button = cc.Class({ } }, + /** + * !#en When this flag is true, Button target sprite will turn gray when interactable is false. + * !#zh 如果这个标记为 true,当 button 的 interactable 属性为 false 的时候,会使用内置 shader 让 button 的 target 节点的 sprite 组件变灰 + * @property {Boolean} enableAutoGrayEffect + */ enableAutoGrayEffect: { default: true, tooltip: 'i18n:COMPONENT.button.auto_gray_effect', @@ -254,7 +257,7 @@ var Button = cc.Class({ /** * !#en Color and Scale transition duration - * !#zh 颜色过渡和绽放过渡时所需时间 + * !#zh 颜色过渡和缩放过渡时所需时间 * @property {Number} duration */ duration: { @@ -265,8 +268,8 @@ var Button = cc.Class({ /** * !#en When user press the button, the button will zoom to a scale. - * The final scale of the button equals (button original scale + zoomScale), zoomScale could be negative value. - * !#zh 当用户点击按钮后,按钮会缩放到一个值,这个值等于 Button原始 scale + zoomScale, zoomScale 可以为负数 + * The final scale of the button equals (button original scale * zoomScale) + * !#zh 当用户点击按钮后,按钮会缩放到一个值,这个值等于 Button 原始 scale * zoomScale * @property {Number} zoomScale */ zoomScale: { @@ -473,7 +476,7 @@ var Button = cc.Class({ if(this.transition === Transition.SCALE && this.target) { if(hit) { - this.target.scale = this._originalScale + this.zoomScale; + this.target.scale = this._originalScale * this.zoomScale; } else { this.target.scale = this._originalScale; } @@ -508,13 +511,13 @@ var Button = cc.Class({ _zoomUp: function () { this._fromScale = this._originalScale; - this._toScale = this._originalScale + this.zoomScale; + this._toScale = this._originalScale * this.zoomScale; this.time = 0; this._transitionFinished = false; }, _zoomBack: function () { - this._fromScale = this._originalScale + this.zoomScale; + this._fromScale = this._originalScale * this.zoomScale; this._toScale = this._originalScale; this.time = 0; this._transitionFinished = false; From 8fe1d04111441ecb11016a37d1ad7be82df4c329 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Fri, 9 Sep 2016 11:41:21 +0800 Subject: [PATCH 268/268] improve button equality test logic --- cocos2d/core/components/CCButton.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/components/CCButton.js b/cocos2d/core/components/CCButton.js index 0889d34fa3..5743baf6d5 100644 --- a/cocos2d/core/components/CCButton.js +++ b/cocos2d/core/components/CCButton.js @@ -411,7 +411,7 @@ var Button = cc.Class({ update: function (dt) { var target = this.target; - if (!this.transition === Transition.COLOR || !this.transition === Transition.SCALE + if (this.transition !== Transition.COLOR || this.transition !== Transition.SCALE || !target || this._transitionFinished) return; this.time += dt;