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/CCBoot.js b/CCBoot.js index c23be52534..ad944f8cbf 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.3.0-beta.2'; window['CocosEngine'] = cc.ENGINE_VERSION = engineVersion; /** @@ -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'); @@ -154,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"); @@ -184,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/CCDebugger.js b/CCDebugger.js index 3a54773167..73f672db61 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 */ @@ -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; @@ -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/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 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/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/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} 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 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-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/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/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index 9eff41ffa2..e412424273 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -24,42 +24,208 @@ THE SOFTWARE. ****************************************************************************/ -var JS = require('../core/platform/js'); - -/** - * Encapsulate DOM and webAudio - */ -cc.Audio = function (url) { - this.src = url; - this._element = null; - this._AUDIO_TYPE = 'AUDIO'; -}; - -cc.Audio.touchPlayList = [ +var touchBinded = false; +var 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); - } +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; }; -cc.Audio.WebAudio = function (buffer) { - this.buffer = buffer; - this.context = cc.sys.__audioSupport.context; +Audio.Type = { + DOM: 'AUDIO', + WEBAUDIO: 'WEBAUDIO', + NATIVE: 'NATIVE', + UNKNOWN: 'UNKNOWN' +}; - var volume = this.context['createGain'](); - volume['gain'].value = 1; - volume['connect'](this.context['destination']); - this._volume = volume; +Audio.State = { + ERROR : -1, + INITIALZING: 0, + PLAYING: 1, + PAUSED: 2 +}; +(function (proto) { + + proto.preload = 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) { + 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 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(path); + 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: 307200, // 300kb * 1024 + _maxAudioInstance: 24, + + _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.preload(); + + 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) + return; + audio.setLoop(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; + audio.setVolume(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 false; + audio.setCurrentTime(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) + return 0; + 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) + return 0; + return audio.getState(); + }, + + /** + * !#en Get audio state + * !#zh 获取音频状态。 + * @method getState + * @param {Number} audioID audio id. + * @param {Function} callback loaded callback. + * @example + * //example + * cc.audioEngine.setFinishCallback(id, function () {}); + */ + setFinishCallback: function (audioID, callback) { + var audio = getAudioFromId(audioID); + if (!audio) + return; + + audio.off('ended'); + audio.on('ended', callback); + }, + + /** + * !#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(); + 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]; + var state = audio.getState(); + if (state === Audio.State.PLAYING) { + this._pauseIDCache.push(id); + audio.pause(); + } + } + }, + + /** + * !#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) + return false; + if (audio.getCurrentTime() === 0) { + audio.play(); + } else { + 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(); + var audio = getAudioFromId(id); + if (audio && audio.resume) + 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(); + 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]; + if (audio && audio.stop) { + audio.stop(); + } + } + }, + + /** + * !#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; + while (list.length > 0) { + var id = list.pop(); + var audio = id2audio[id]; + if (audio) { + audio.stop(); + delete id2audio[id]; + } + } + }, + + /** + * !#en Unload all audio from internal buffer. + * !#zh 卸载所有音频。 + * @method uncacheAll + * @example + * //example + * cc.audioEngine.uncacheAll(); + */ + uncacheAll: function () { + this.stopAll(); + id2audio = {}; + url2id = {}; + }, + + /** + * !#en Gets an audio profile by name. + * + * @param profileName A name of audio profile. + * @return The audio profile. + */ + getProfile: function (profileName) {}, + + /** + * !#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; + } +}; + +module.exports = cc.audioEngine = audioEngine; \ No newline at end of file diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js index 55e45ddc3f..bc9b1039c0 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; @@ -268,7 +269,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()) { @@ -296,16 +297,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, @@ -399,8 +390,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 () { @@ -546,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 @@ -558,8 +552,13 @@ cc.Director = Class.extend(/** @lends 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(); } @@ -828,8 +827,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 () { @@ -1389,7 +1388,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 +1429,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(); } diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index 15b7f5d507..197c58d99a 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -29,17 +29,19 @@ if (!(CC_EDITOR && Editor.isMainProcess)) { View = require('./platform/CCView'); } +var audioEngine = cc.audioEngine = require('../audio/CCAudioEngine'); + /** * !#en An object to boot the game. * !#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. - * @constant + * @property EVENT_HIDE * @type {String} * @example * cc.game.on(cc.game.EVENT_HIDE, function () { @@ -52,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. - * @constant + * @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 - * @constant + * @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 - * @constant + * @property EVENT_RENDERER_INITED * @type {String} */ EVENT_RENDERER_INITED: "renderer_inited", @@ -80,7 +82,7 @@ var game = /** @lends cc.game# */{ /** * Key of config - * @constant + * @property CONFIG_KEY * @type {Object} */ CONFIG_KEY: { @@ -241,15 +243,19 @@ 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 (audioEngine) { + audioEngine.pauseAll(); + } // Pause main loop if (this._intervalId) window.cancelAnimationFrame(this._intervalId); @@ -257,15 +263,18 @@ 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 (audioEngine) { + audioEngine.resumeAll(); + } // Resume main loop this._runMainLoop(); }, @@ -288,13 +297,15 @@ var game = /** @lends cc.game# */{ restart: function () { cc.director.popToSceneStackLevel(0); // Clean up audio - cc.audioEngine && cc.audioEngine.end(); + audioEngine && audioEngine.end(); game.onStart(); }, /** - * End game, it will close the game window + * !#en End game, it will close the game window + * !#zh 退出游戏 + * @method end */ end: function () { close(); @@ -613,11 +624,13 @@ var game = /** @lends cc.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 || []; this.groupList = config.groupList || []; + + cc._initDebugSetting(config[CONFIG_KEY.debugMode]); this.config = config; }, @@ -686,6 +699,7 @@ var game = /** @lends cc.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/CCNode.js b/cocos2d/core/CCNode.js index c5910124e6..30669bcaa1 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; @@ -140,7 +141,7 @@ var _mouseEvents = [ EventType.MOUSE_WHEEL, ]; -var currentHovered = null; +var _currentHovered = null; var _touchStartHandler = function (touch, event) { var pos = touch.getLocation(); @@ -194,12 +195,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 +212,7 @@ var _mouseMoveHandler = function (event) { event.type = EventType.MOUSE_LEAVE; node.dispatchEvent(event); this._previousIn = false; - currentHovered = null; + _currentHovered = null; } }; var _mouseUpHandler = function (event) { @@ -394,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. @@ -524,16 +522,25 @@ var Node = cc.Class({ } // Actions - this.stopAllActions(); + cc.director.getActionManager().removeAllActionsFromTarget(this); this._releaseAllActions(); + // Remove Node.currentHovered + if (_currentHovered === this) { + _currentHovered = null; + } + // 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 +573,7 @@ var Node = cc.Class({ } else if (CC_JSB) { this._sgNode.release(); + this._sgNode._entity = null; this._sgNode = null; } }, @@ -633,8 +641,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[]} @@ -645,6 +653,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; @@ -780,13 +789,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; } @@ -888,6 +898,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) { @@ -958,6 +995,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 @@ -1046,10 +1089,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; @@ -1086,6 +1139,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({ @@ -1101,6 +1155,7 @@ var Node = cc.Class({ this._touchListener.retain(); } cc.eventManager.addListener(this._touchListener, this); + newAdded = true; } } else if (_mouseEvents.indexOf(type) !== -1) { @@ -1119,8 +1174,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); }, @@ -1188,6 +1252,10 @@ var Node = cc.Class({ } } + if (_currentHovered === this) { + _currentHovered = null; + } + cc.eventManager.removeListener(this._mouseListener); this._mouseListener = null; } @@ -1211,7 +1279,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 { @@ -1258,17 +1326,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/cocos2d/core/CCScene.js b/cocos2d/core/CCScene.js index d717379369..c8d293103f 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(); @@ -59,6 +61,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 () { @@ -82,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; } }, @@ -112,40 +128,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/assets/CCPrefab.js b/cocos2d/core/assets/CCPrefab.js index 70fc9890b0..a7a515fc39 100644 --- a/cocos2d/core/assets/CCPrefab.js +++ b/cocos2d/core/assets/CCPrefab.js @@ -55,10 +55,16 @@ var Prefab = cc.Class({ }, _instantiate: function () { + //if (this.data._prefab) { + // 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/assets/CCSceneAsset.js b/cocos2d/core/assets/CCSceneAsset.js index d27b61a3c3..bb6109c6f7 100644 --- a/cocos2d/core/assets/CCSceneAsset.js +++ b/cocos2d/core/assets/CCSceneAsset.js @@ -35,14 +35,27 @@ 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 + asyncLoadAssets: undefined, + + //// backup prefab assets in editor + //// {string} assetUuid: {cc.Node} rootInPrefab + //_prefabDatas: { + // default: null, + // editorOnly: true + //} }, }); 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/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/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/base-nodes/CCSGNode.js b/cocos2d/core/base-nodes/CCSGNode.js index f3697ee4a4..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; @@ -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); }, /** @@ -891,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); @@ -957,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; }, /** @@ -1153,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(); @@ -1318,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); }, @@ -1346,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/base-nodes/CCSGNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCSGNodeCanvasRenderCmd.js index 9ec836d821..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) { @@ -448,16 +448,22 @@ _ccsg.Node.RenderCmd.prototype = { var locFlag = this._dirtyFlag; var colorDirty = locFlag & dirtyFlags.colorDirty, opacityDirty = locFlag & dirtyFlags.opacityDirty; - if(colorDirty) + + if (locFlag & dirtyFlags.contentDirty) { + this._notifyRegionStatus && this._notifyRegionStatus(_ccsg.Node.CanvasRenderCmd.RegionStatus.Dirty); + this._dirtyFlag &= ~dirtyFlags.contentDirty; + } + + 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; @@ -481,7 +487,7 @@ _ccsg.Node.RenderCmd.prototype = { //update the opacity this._syncDisplayOpacity(); - if(colorDirty) + if (colorDirty || opacityDirty) this._updateColor(); if (transformDirty) diff --git a/cocos2d/core/base-ui/CCWidgetManager.js b/cocos2d/core/base-ui/CCWidgetManager.js index 5ea2b125b7..ffe8b68f8f 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 localHorizontalCenter = widget._isAbsHorizontalCenter ? widget._horizontalCenter : widget._horizontalCenter * parentWidth; + var parentCenter = (0.5 - parentAnchor.x) * parentWidth; + x = parentCenter + (anchorX - 0.5) * width + localHorizontalCenter; } 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 localVerticalCenter = widget._isAbsVerticalCenter ? widget._verticalCenter : widget._verticalCenter * parentHeight; + var parentMiddle = (0.5 - parentAnchor.y) * parentHeight; + y = parentMiddle + (anchorY - 0.5) * height + localVerticalCenter; } else if (widget.isAlignBottom) { y = localBottom + anchorY * height; @@ -156,7 +158,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 +174,34 @@ function visitNode (node) { } } +if (CC_EDITOR) { + var animationState = { + previewing: false, + time: 0, + animatedSinceLastFrame: false, + }; +} + function refreshScene () { + // check animation editor + if (CC_EDITOR && window._Scene && _Scene.AnimUtils) { + 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 +209,15 @@ 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 + if (CC_EDITOR && window._Scene && _Scene.AnimUtils && _Scene.AnimUtils.curAnimState) { + var editingNode = _Scene.AnimUtils.curRootNode; for (i = len - 1; i >= 0; i--) { node = nodes[i]; var widget = node._widget; - if (widget.isAlignOnce) { + if (widget.isAlignOnce && animationState.animatedSinceLastFrame && node.isChildOf(editingNode)) { // widget contains in _nodesWithWidget should aligned at least once widget.enabled = false; } @@ -206,6 +236,10 @@ function refreshScene () { widgetManager.isAligning = false; } + // check animation editor + if (CC_EDITOR) { + animationState.animatedSinceLastFrame = false; + } } var adjustWidgetToAllowMovingInEditor = CC_EDITOR && function (event) { @@ -237,14 +271,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); } }; @@ -280,14 +310,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/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); } diff --git a/cocos2d/core/components/CCAnimation.js b/cocos2d/core/components/CCAnimation.js index 86e66b3a6b..fbb01027ff 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: { @@ -146,19 +166,16 @@ var Animation = cc.Class({ } }, - __preload: function () { - if (CC_EDITOR) return; + onEnable: function () { + if (!CC_EDITOR && this.playOnLoad && this._defaultClip) { + this.playOnLoad = false; - this._init(); - - if (this.playOnLoad && this._defaultClip) { var state = this.getAnimationState(this._defaultClip.name); this._animator.playState(state); } - }, - - onEnable: function () { - this.resume(); + else { + this.resume(); + } }, onDisable: function () { @@ -471,6 +488,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 +629,4 @@ var Animation = cc.Class({ } }); - cc.Animation = module.exports = Animation; diff --git a/cocos2d/core/components/CCAudioSource.js b/cocos2d/core/components/CCAudioSource.js index adb99c13a7..d134f7f2d2 100644 --- a/cocos2d/core/components/CCAudioSource.js +++ b/cocos2d/core/components/CCAudioSource.js @@ -30,9 +30,6 @@ * @extends Component */ -// todo jsb 中无法针对单独的音效对象进行设置(如音量大小等) - -var audioEngine = cc.audioEngine; var AudioSource = cc.Class({ name: 'cc.AudioSource', @@ -44,7 +41,7 @@ var AudioSource = cc.Class({ }, ctor: function () { - this.audio = null; + this.audio = new cc.Audio(); }, properties: { @@ -70,7 +67,9 @@ var AudioSource = cc.Class({ */ isPlaying: { get: function () { - return (!cc.sys.isNative && this.audio && this.audio.getPlaying()); + if (!this.audio) return false; + var state = this.audio.getState(); + return state === cc.Audio.State.PLAYING; }, visible: false }, @@ -88,6 +87,10 @@ var AudioSource = cc.Class({ }, set: function (value) { this._clip = value; + this.audio.src = this._clip; + if (this.audio.preload) { + this.audio.preload(); + } }, url: cc.AudioClip, tooltip: 'i18n:COMPONENT.audio.clip', @@ -107,14 +110,10 @@ 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.audio && !this._mute) { + this.audio.setVolume(value); } + return value; }, tooltip: 'i18n:COMPONENT.audio.volume' }, @@ -133,20 +132,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); - } - } + this.audio.setVolume(value ? 0 : this._volume); } + return value; }, animatable: false, tooltip: 'i18n:COMPONENT.audio.mute', @@ -165,7 +153,10 @@ var AudioSource = cc.Class({ }, set: function (value) { this._loop = value; - if (this.audio) this.audio.loop = this._loop; + if (this.audio) { + this.audio.setLoop(value); + } + return value; }, animatable: false, tooltip: 'i18n:COMPONENT.audio.loop' @@ -197,6 +188,7 @@ var AudioSource = cc.Class({ onDestroy: function () { this.stop(); + audioEngine.uncache(this._clip); }, /** @@ -205,14 +197,17 @@ var AudioSource = cc.Class({ * @method play */ play: function () { - if ( this._clip ) { - var volume = this._mute ? 0 : this._volume; - this.audio = audioEngine.playEffect(this._clip, this._loop, volume); + if ( !this._clip ) return; - if (CC_JSB) { - cc.audioEngine.setEffectsVolume(volume); - } - } + 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(); }, /** @@ -221,7 +216,9 @@ var AudioSource = cc.Class({ * @method stop */ stop: function () { - if ( this.audio ) cc.audioEngine.stopEffect(this.audio); + if (this.audio) { + this.audio.stop(); + } }, /** @@ -230,7 +227,9 @@ var AudioSource = cc.Class({ * @method pause */ pause: function () { - if ( this.audio ) cc.audioEngine.pauseEffect(this.audio); + if (this.audio) { + this.audio.pause(); + } }, /** @@ -239,7 +238,9 @@ var AudioSource = cc.Class({ * @method resume */ resume: function () { - if ( this.audio ) cc.audioEngine.resumeEffect(this.audio); + if (this.audio) { + this.audio.resume(); + } }, /** @@ -248,11 +249,10 @@ var AudioSource = cc.Class({ * @method rewind */ rewind: function(){ - if ( this.audio ) { - this.stop(); - this.play(); + if (this.audio) { + this.audio.setCurrentTime(0); } - }, + } }); diff --git a/cocos2d/core/components/CCButton.js b/cocos2d/core/components/CCButton.js index b6e8a7996d..5743baf6d5 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 }); /** @@ -103,6 +109,15 @@ var Button = cc.Class({ ctor: function () { this._resetState(); + + this._fromColor = null; + this._toColor = null; + this._time = 0; + this._transitionFinished = true; + this._fromScale = 1.0; + this._toScale = 1.0; + this._originalScale = 1.0; + this._sprite = null; if(CC_EDITOR) { @@ -114,10 +129,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 && { @@ -157,6 +168,28 @@ var Button = cc.Class({ animatable: false }, + _resizeToTarget: { + animatable: false, + set: function (value) { + if(value) { + this._resizeNodeToTargetNode(); + } + } + }, + + /** + * !#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', + notify: function () { + this._updateDisabledState(); + } + }, + /** * !#en Transition type * !#zh 按钮状态改变时过渡方式。 @@ -216,15 +249,15 @@ 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(); } }, /** - * !#en Color transition duration - * !#zh 颜色过渡时所需时间 + * !#en Color and Scale transition duration + * !#zh 颜色过渡和缩放过渡时所需时间 * @property {Number} duration */ duration: { @@ -233,6 +266,17 @@ var Button = cc.Class({ tooltip: 'i18n:COMPONENT.button.duration', }, + /** + * !#en When user press the button, the button will zoom to a scale. + * The final scale of the button equals (button original scale * zoomScale) + * !#zh 当用户点击按钮后,按钮会缩放到一个值,这个值等于 Button 原始 scale * zoomScale + * @property {Number} zoomScale + */ + zoomScale: { + default: 0.1, + tooltip: 'i18n:COMPONENT.button.zoom_scale' + }, + // sprite transition /** * !#en Normal state sprite @@ -297,10 +341,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: { @@ -360,23 +404,33 @@ var Button = cc.Class({ } }, - start: function () { + onLoad: function () { this._applyTarget(); this._updateState(); }, 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; - if (ratio > 1) { + var ratio = 1.0; + if(this.duration > 0) { + ratio = this.time / this.duration; + } + + if (ratio >= 1) { ratio = 1; 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 () { @@ -393,6 +447,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; @@ -404,7 +459,11 @@ var Button = cc.Class({ if (!this.interactable || !this.enabledInHierarchy) return; this._pressed = true; - this._updateState(); + if(this.transition === Transition.SCALE) { + this._zoomUp(); + } else { + this._updateState(); + } event.stopPropagation(); }, @@ -414,16 +473,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 = this._originalScale * this.zoomScale; + } else { + this.target.scale = this._originalScale; + } + } 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(); }, @@ -434,19 +501,38 @@ var Button = cc.Class({ cc.Component.EventHandler.emitEvents(this.clickEvents, event); } this._pressed = false; - this._updateState(); + if(this.transition === Transition.SCALE) { + this._zoomBack(); + } else { + this._updateState(); + } event.stopPropagation(); }, + _zoomUp: function () { + this._fromScale = this._originalScale; + this._toScale = this._originalScale * this.zoomScale; + this.time = 0; + this._transitionFinished = false; + }, + + _zoomBack: function () { + this._fromScale = this._originalScale * this.zoomScale; + this._toScale = this._originalScale; + this.time = 0; + this._transitionFinished = false; + }, + _onTouchCancel: function () { if (!this.interactable || !this.enabledInHierarchy) return; this._pressed = false; + this._updateState(); }, _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; @@ -480,6 +566,7 @@ var Button = cc.Class({ var sprite = this[state + 'Sprite']; this._applyTransition(color, sprite); + this._updateDisabledState(); }, onDisable: function() { @@ -520,6 +607,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; diff --git a/cocos2d/core/components/CCComponent.js b/cocos2d/core/components/CCComponent.js index 11af567b87..f278c7ca24 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; @@ -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; } } @@ -216,8 +217,6 @@ function _callPreloadOnComponent (component) { } } -var idGenerater = new IdGenerater('Comp'); - /** * !#en * Base class for everything attached to Node(Entity).
@@ -237,11 +236,13 @@ var Component = cc.Class({ name: 'cc.Component', extends: cc.Object, - ctor: function () { - if (CC_EDITOR && !CC_TEST && window._Scene) { + ctor: CC_EDITOR ? function () { + if (window._Scene && _Scene.AssetsWatcher) { _Scene.AssetsWatcher.initComponent(this); } - + // Support for Scheduler + this.__instanceId = cc.ClassManager.getNewInstanceId(); + } : function () { // Support for Scheduler this.__instanceId = cc.ClassManager.getNewInstanceId(); }, @@ -374,7 +375,7 @@ var Component = cc.Class({ */ enabledInHierarchy: { get: function () { - return this._objFlags & IsOnEnableCalled; + return (this._objFlags & IsOnEnableCalled) > 0; }, visible: false }, @@ -550,8 +551,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 or any of its children using depth first search. + * !#zh 递归查找自身或所有子节点中指定类型的组件 * * @method getComponentsInChildren * @param {Function|String} typeOrClassName diff --git a/cocos2d/core/components/CCComponentEventHandler.js b/cocos2d/core/components/CCComponentEventHandler.js index cbaf23cbe7..312c968d82 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/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/CCMask.js b/cocos2d/core/components/CCMask.js index 4b93e78e17..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', @@ -120,6 +122,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(); @@ -133,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; @@ -174,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/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/components/CCRendererInSG.js b/cocos2d/core/components/CCRendererInSG.js index 0629445317..d2b212914f 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 () { /** @@ -83,6 +84,7 @@ var RendererInSG = cc.Class({ var releasedByNode = this.node._sgNode; if (this._plainNode !== releasedByNode) { this._plainNode.release(); + this._plainNode = null; } } }, @@ -94,6 +96,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'); @@ -120,15 +123,16 @@ 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; } } + // replaced.release(); // apply node's property - node._sgNode = sgNode; + node._sgNode._entity = node; node._updateSgNode(); }, }); diff --git a/cocos2d/core/components/CCRendererUnderSG.js b/cocos2d/core/components/CCRendererUnderSG.js index 12c424d248..54e71fdc4f 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 () { /** @@ -92,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/components/CCRichText.js b/cocos2d/core/components/CCRichText.js new file mode 100644 index 0000000000..60e9337173 --- /dev/null +++ b/cocos2d/core/components/CCRichText.js @@ -0,0 +1,652 @@ +/**************************************************************************** + 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(); + + if(CC_EDITOR) { + this._updateRichTextStatus = debounce(this._updateRichText, 200); + } else { + this._updateRichTextStatus = this._updateRichText; + } + }, + + editor: CC_EDITOR && { + menu: 'i18n:MAIN_MENU.component.renderers/RichText', + help: 'i18n:COMPONENT.help_url.richtext', + }, + + + properties: { + /** + * !#en Content string of RichText. + * !#zh 富文本显示的文本内容。 + * @property {String} string + */ + string: { + default: 'RichText', + multiline: true, + tooltip: 'i18n:COMPONENT.richtext.string', + notify: function () { + this._updateRichTextStatus(); + } + }, + + /** + * !#en Horizontal Alignment of each line in RichText. + * !#zh 文本内容的水平对齐方式。 + * @property {RichText.HorizontalAlign} horizontalAlign + */ + horizontalAlign: { + default: HorizontalAlign.LEFT, + type: HorizontalAlign, + tooltip: 'i18n:COMPONENT.richtext.horizontal_align', + animatable: false, + notify: function () { + this._layoutDirty = true; + this._updateRichTextStatus(); + } + }, + + /** + * !#en Font size of RichText. + * !#zh 富文本字体大小。 + * @property {Number} fontSize + */ + fontSize: { + default: 40, + tooltip: 'i18n:COMPONENT.richtext.font_size', + notify: function () { + this._layoutDirty = true; + this._updateRichTextStatus(); + } + }, + + /** + * !#en The maximize width of the RichText + * !#zh 富文本的最大宽度 + * @property {Number} maxWidth + */ + maxWidth: { + default: 0, + tooltip: 'i18n:COMPONENT.richtext.max_width', + notify: function () { + this._layoutDirty = true; + this._updateRichTextStatus(); + } + }, + + /** + * !#en Line Height of RichText. + * !#zh 富文本行高。 + * @property {Number} lineHeight + */ + lineHeight: { + default: 40, + tooltip: 'i18n:COMPONENT.richtext.line_height', + notify: function () { + this._layoutDirty = true; + this._updateRichTextStatus(); + } + } + }, + + statics: { + HorizontalAlign: HorizontalAlign, + VerticalAlign: VerticalAlign + }, + + __preload: function () { + this._super(); + + if (!CC_EDITOR) { + this._registerEvents(); + } + }, + + _createSgNode: function () { + var sgNode = new _ccsg.Node(); + + sgNode.setCascadeOpacityEnabled(true); + + var self = this; + sgNode.setColor = function () { + self._updateLabelSegmentTextAttributes(); + }; + + 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(); + }, + + _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; + this._layoutDirty = true; + }, + + _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); + + if(CC_JSB) { + labelSegment.setOverflow(1); + var size = labelSegment.getContentSize(); + labelSegment.setContentSize(size.width, this.lineHeight); + } + + 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++; + }, + + _needsUpdateTextLayout: function (newTextArray) { + if(this._layoutDirty || !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) { + 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 () { + 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(); + + var lastEmptyLine = false; + var label; + var labelSize; + + for (var i = 0; i < this._textArray.length; ++i) { + 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) { + 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(); + this._layoutDirty = false; + }, + + _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 () { + + 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 = 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(); + + 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); + label.enableBold(false); + label.enableItalics(false); + label.enableUnderline(false); + + var textStyle = null; + if(this._textArray[index]) { + textStyle = this._textArray[index].style; + } + if(textStyle && 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); + } + + 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 { + label.setFontSize(this.fontSize); + } + + if(textStyle && textStyle.event) { + if(textStyle.event.click) { + label._clickHandler = textStyle.event.click; + } + } + } + + }); + + cc.RichText = module.exports = RichText; 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/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 660e27173a..0a535109cf 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 }); /** @@ -123,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() { @@ -160,7 +166,7 @@ var ScrollView = cc.Class({ * @property {Node} content */ content: { - default: null, + default: undefined, type: cc.Node, tooltip: 'i18n:COMPONENT.scrollview.content', }, @@ -240,7 +246,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 +264,7 @@ var ScrollView = cc.Class({ * @property {Scrollbar} verticalScrollBar */ verticalScrollBar: { - default: null, + default: undefined, type: cc.Scrollbar, tooltip: 'i18n:COMPONENT.scrollview.vertical_bar', notify: function() { @@ -278,6 +284,18 @@ var ScrollView = cc.Class({ scrollEvents: { default: [], type: cc.Component.EventHandler + }, + + /** + * !#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 也不会受影响。 + * @property {Boolean} cancelInnerEvents + */ + cancelInnerEvents: { + default: true, + animatable: false, } }, @@ -686,10 +704,12 @@ var ScrollView = cc.Class({ }, _onMouseWheel: function(event) { + 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); @@ -762,6 +782,48 @@ 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); + this._adjustContentOutOfBoundary(); + }, + _calculateBoundary: function() { if (this.content) { //refresh content size @@ -779,44 +841,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); } }, @@ -828,6 +855,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); @@ -836,36 +865,54 @@ var ScrollView = cc.Class({ }, _onTouchMoved: function(event) { + if (!this.enabledInHierarchy) return; + var touch = event.touch; if (this.content) { this._handleMoveLogic(touch); } - var deltaMove = touch.getDelta(); + // 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) { - this._touchMoved = true; - var buttonComponent = event.target.getComponent(cc.Button); - if (buttonComponent) { - buttonComponent._onTouchCancel(); + 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(); } - // TODO: detect move distance, if distance greater than a seuil, then stop propagation. - event.stopPropagation(); }, _onTouchEnded: function(event) { + if (!this.enabledInHierarchy) return; + var touch = event.touch; if (this.content) { this._handleReleaseLogic(touch); } + this._dispatchEvent(EventType.TOUCH_UP); if (this._touchMoved) { event.stopPropagation(); } }, _onTouchCancelled: function(event) { - var touch = event.touch; - if(this.content){ - this._handleReleaseLogic(touch); + if (!this.enabledInHierarchy) return; + + // Filte touch cancel event send from self + if (!event.simulate) { + var touch = event.touch; + if(this.content){ + this._handleReleaseLogic(touch); + } } }, @@ -1093,7 +1140,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(); @@ -1107,10 +1153,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); }, @@ -1159,7 +1218,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) { @@ -1282,8 +1342,25 @@ 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); + this._updateScrollBar(0); + } + } + }, + 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. + if(this.content) { + cc.director.once(cc.Director.EVENT_AFTER_VISIT, this._adjustContentOutOfBoundary, this); + } }, onDestroy: function() { @@ -1303,11 +1380,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); diff --git a/cocos2d/core/components/CCSprite.js b/cocos2d/core/components/CCSprite.js index 3dcfef3575..0dd40826b0 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', @@ -161,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) { @@ -379,15 +388,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; }, @@ -492,11 +492,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()) { @@ -505,11 +500,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) { @@ -632,6 +622,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/components/CCVideoPlayer.js b/cocos2d/core/components/CCVideoPlayer.js index 178f30b419..f16a085f7f 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; @@ -106,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', @@ -122,21 +147,24 @@ var VideoPlayer = cc.Class({ url: cc.RawAsset }, - _time: 0, /** - * !#en The current time when video start to play. - * !#zh 从当前时间点开始播放视频 - * @property {Float} currentTime + * !#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(); + } + return -1; } }, @@ -185,7 +213,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; @@ -293,6 +320,28 @@ var VideoPlayer = cc.Class({ } }, + /** + * !#en Gets the duration of the video + * !#zh 获取视频文件的播放总时长 + */ + getDuration: function() { + if(this._sgNode) { + return this._sgNode.duration(); + } + return -1; + }, + + /** + * !#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/components/CCWebView.js b/cocos2d/core/components/CCWebView.js new file mode 100644 index 0000000000..aa639de9a1 --- /dev/null +++ b/cocos2d/core/components/CCWebView.js @@ -0,0 +1,155 @@ +/*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 WebView event type + * !#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 组件,用于在游戏中显示网页 + * @class WebView + * @extends _RendererUnderSG + */ +var WebView = cc.Class({ + name: 'cc.WebView', + extends: cc._RendererUnderSG, + + editor: CC_EDITOR && { + menu: 'i18n:MAIN_MENU.component.ui/WebView' + }, + + properties: { + _useOriginalSize: true, + + _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, + tooltip: 'i18n:COMPONENT.webview.url', + get: function () { + return this._url; + }, + set: function (url) { + this._url = url; + var sgNode = this._sgNode; + if (sgNode) { + sgNode.loadURL(url); + } + } + }, + + /** + * !#en The webview's event callback , it will be triggered when certain webview event occurs. + * !#zh WebView 的回调事件,当网页加载过程中,加载完成后或者加载出错时都会回调此函数 + * @property {cc.Component.EventHandler[]} webviewLoadedEvents + */ + webviewEvents: { + default: [], + type: cc.Component.EventHandler, + }, + }, + + statics: { + EventType: EventType, + }, + + onLoad: CC_JSB && function() { + 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); + + if (CC_EDITOR && this._useOriginalSize) { + this.node.setContentSize(sgNode.getContentSize()); + this._useOriginalSize = false; + } else { + sgNode.setContentSize(this.node.getContentSize()); + } + }, + + _onWebViewLoaded: function () { + cc.Component.EventHandler.emitEvents(this.webviewEvents, this, EventType.LOADED); + }, + + _onWebViewLoading: function () { + cc.Component.EventHandler.emitEvents(this.webviewEvents, this, EventType.LOADING); + return true; + }, + + _onWebViewLoadError: function () { + cc.Component.EventHandler.emitEvents(this.webviewEvents, this, EventType.ERROR); + } + +}); + +cc.WebView = module.exports = WebView; diff --git a/cocos2d/core/components/CCWidget.js b/cocos2d/core/components/CCWidget.js index 4c4c739bcf..37ddc18014 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 */ @@ -301,8 +303,80 @@ var Widget = cc.Class({ tooltip: 'i18n:COMPONENT.widget.right', }, + /** + * !#en + * Horizontal aligns the midpoint offset value, + * the value can be negative, Only available in 'isAlignHorizontalCenter' open. + * !#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 + * Vertical aligns the midpoint offset value, + * the value can be negative, Only available in 'isAlignVerticalCenter' open. + * !#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 If true, horizontalCenter is pixel margin, otherwise is percentage (0 - 1) margin. + * !#zh 如果为 true,"horizontalCenter" 将会以像素作为偏移值,反之为百分比(0 到 1)。 + * @property isAbsoluteHorizontalCenter + * @type {Boolean} + * @default true + */ + isAbsoluteHorizontalCenter: { + get: function () { + return this._isAbsHorizontalCenter; + }, + set: function (value) { + this._isAbsHorizontalCenter = value; + }, + animatable: false + }, + + /** + * !#en If true, verticalCenter is pixel margin, otherwise is percentage (0 - 1) margin. + * !#zh 如果为 true,"verticalCenter" 将会以像素作为偏移值,反之为百分比(0 到 1)。 + * @property isAbsoluteVerticalCenter + * @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 +485,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, diff --git a/cocos2d/core/components/index.js b/cocos2d/core/components/index.js index 84ae107c59..49d5614db4 100644 --- a/cocos2d/core/components/index.js +++ b/cocos2d/core/components/index.js @@ -44,6 +44,8 @@ module.exports = [ require('./CCLayout'), require('./CCEditBox'), require('./CCVideoPlayer'), + require('./CCWebView'), require('./CCSpriteDistortion'), require('./CCLabelOutline'), + require('./CCRichText'), ]; diff --git a/cocos2d/core/components/missing-script.js b/cocos2d/core/components/missing-script.js index 82bafac5bf..6b0ebad064 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,19 +97,25 @@ 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) { - return MissingScript; + cc.deserialize.reportMissingClass(id); + if (data.node && (CC_EDITOR && Editor.UuidUtils.isUuid(id))) { + return MissingScript; + } + else { + return MissingClass; + } } return null; } }, 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/editbox/CCSGEditBox.js b/cocos2d/core/editbox/CCSGEditBox.js index f8d275f832..3d779c8a65 100644 --- a/cocos2d/core/editbox/CCSGEditBox.js +++ b/cocos2d/core/editbox/CCSGEditBox.js @@ -26,6 +26,31 @@ THE SOFTWARE. ****************************************************************************/ +// https://segmentfault.com/q/1010000002914610 +var SCROLLY = 40; +var TIMER_NAME = 400; +var LEFT_PADDING = 2; + +function scrollWindowUp(editBox) { + if (cc.sys.os === cc.sys.OS_IOS && cc.sys.osMainVersion === 9) { + var worldPos = editBox.convertToWorldSpace(cc.p(0,0)); + var windowHeight = cc.visibleRect.height; + var windowWidth = cc.visibleRect.width; + var factor = 0.5; + if(windowWidth > windowHeight) { + factor = 0.7; + } + setTimeout(function() { + if(window.scrollY < SCROLLY && worldPos.y < windowHeight * factor) { + var scrollOffset = windowHeight * factor - worldPos.y - window.scrollY; + if (scrollOffset < 35) scrollOffset = 35; + if (scrollOffset > 320) scrollOffset = 320; + window.scrollTo(0, scrollOffset); + } + }, TIMER_NAME); + } +} + var capitalize = function(string) { return string.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); }); }; @@ -223,7 +248,7 @@ _ccsg.EditBox = _ccsg.Node.extend({ this._placeholderColor = cc.Color.GRAY; this.initWithSizeAndBackgroundSprite(size, normal9SpriteBg); - this._renderCmd.createNativeControl(); + this._renderCmd._createLabels(); }, _createRenderCmd: function () { @@ -255,9 +280,9 @@ _ccsg.EditBox = _ccsg.Node.extend({ }, cleanup: function () { + this._super(); + this._renderCmd._removeDomInputControl(); - this.stopAllActions(); - this.unscheduleAllCallbacks(); }, _onTouchBegan: function (touch) { @@ -492,7 +517,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); @@ -519,12 +544,22 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; var editBox = this._edTxt; if (node.visible) { editBox.style.visibility = 'visible'; + cc.game.container.appendChild(editBox); } else { editBox.style.visibility = 'hidden'; + var hasChild = false; + if('contains' in cc.game.container) { + hasChild = cc.game.container.contains(editBox); + }else { + hasChild = cc.game.container.compareDocumentPosition(editBox) % 16; + } + if(hasChild) + cc.game.container.removeChild(editBox); } }; proto._createDomInput = function () { + this._removeDomInputControl(); var thisPointer = this; var tmpEdTxt = this._edTxt = document.createElement('input'); tmpEdTxt.type = 'text'; @@ -541,15 +576,23 @@ _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 () { 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) { @@ -562,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(); @@ -571,10 +615,20 @@ _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); + if(cc.view.isAutoFullScreenEnabled()) { + thisPointer.__fullscreen = true; + cc.view.enableAutoFullScreen(false); + cc.screen.exitFullScreen(); + } else { + thisPointer.__fullscreen = false; + } + + scrollWindowUp(editBox); if (editBox._delegate && editBox._delegate.editBoxEditingDidBegan) { editBox._delegate.editBoxEditingDidBegan(editBox); @@ -584,7 +638,10 @@ _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); } @@ -599,6 +656,7 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; }; proto._createDomTextArea = function () { + this._removeDomInputControl(); var thisPointer = this; var tmpEdTxt = this._edTxt = document.createElement('textarea'); tmpEdTxt.type = 'text'; @@ -617,15 +675,21 @@ _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 () { + 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); + } } }); @@ -634,6 +698,15 @@ _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); if (editBox._delegate && editBox._delegate.editBoxEditingDidBegan) { editBox._delegate.editBoxEditingDidBegan(editBox); @@ -655,6 +728,10 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; var editBox = thisPointer._editBox; editBox._text = this.value; thisPointer._updateEditBoxContentStyle(); + window.scrollY = 0; + if(thisPointer.__fullscreen) { + cc.view.enableAutoFullScreen(true); + } if (editBox._delegate && editBox._delegate.editBoxEditingDidEnded) { editBox._delegate.editBoxEditingDidEnded(editBox); @@ -688,21 +765,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); } @@ -929,24 +1007,23 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; proto.createNativeControl = function() { this._createDomTextArea(); this._addDomInputControl(); - this._createLabels(); }; 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; }; @@ -955,7 +1032,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/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/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/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/event/event-target.js b/cocos2d/core/event/event-target.js index 7e825896e6..265040f88d 100644 --- a/cocos2d/core/event/event-target.js +++ b/cocos2d/core/event/event-target.js @@ -56,7 +56,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 +89,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. @@ -337,7 +329,16 @@ JS.mixin(EventTarget.prototype, { var event = new cc.Event.EventCustom(message); event.detail = detail; - _doSendEvent(this, event); + + // Event.AT_TARGET + event.eventPhase = 2; + event.target = event.currentTarget = this; + if (caplisteners) { + this._capturingListeners.invoke(event); + } + if (bublisteners && !event._propagationImmediateStopped) { + this._bubblingListeners.invoke(event); + } }, /* diff --git a/cocos2d/core/event/event.js b/cocos2d/core/event/event.js index 47e887084b..73c30d686f 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. diff --git a/cocos2d/core/graphics/graphics-canvas-cmd.js b/cocos2d/core/graphics/graphics-canvas-cmd.js index d55d57bb7b..04ba3e56aa 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); @@ -47,12 +38,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; @@ -63,7 +61,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(); @@ -87,12 +86,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]); }, @@ -150,69 +149,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) { @@ -224,28 +170,12 @@ 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) { this.cmds.push(['fillRect', arguments]); + this.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); }, close: function () { @@ -254,14 +184,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/graphics/graphics-webgl-cmd.js b/cocos2d/core/graphics/graphics-webgl-cmd.js index a8f7f4bf0b..63baed8035 100644 --- a/cocos2d/core/graphics/graphics-webgl-cmd.js +++ b/cocos2d/core/graphics/graphics-webgl-cmd.js @@ -30,18 +30,18 @@ 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; +var PI = Math.PI; var min = Math.min; var max = Math.max; var ceil = Math.ceil; @@ -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/graphics.js b/cocos2d/core/graphics/graphics.js index d9af550be5..e7b5968899 100644 --- a/cocos2d/core/graphics/graphics.js +++ b/cocos2d/core/graphics/graphics.js @@ -26,6 +26,7 @@ var LineCap = require('./types').LineCap; var LineJoin = require('./types').LineJoin; + /** * @class Graphics * @extends _RendererUnderSG @@ -157,6 +158,15 @@ var Graphics = cc.Class({ }, _createSgNode: function () { + 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(); }, @@ -168,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)); }, /** diff --git a/cocos2d/core/graphics/helper.js b/cocos2d/core/graphics/helper.js new file mode 100644 index 0000000000..e21bfd6879 --- /dev/null +++ b/cocos2d/core/graphics/helper.js @@ -0,0 +1,99 @@ + +var PI = Math.PI; +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, +}; 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'); diff --git a/cocos2d/core/index.js b/cocos2d/core/index.js index 084e855a61..fdf6acf4c7 100644 --- a/cocos2d/core/index.js +++ b/cocos2d/core/index.js @@ -34,6 +34,7 @@ if (!CC_EDITOR || !Editor.isMainProcess) { require('./CCNode'); require('./CCScene'); + require('./label/CCHtmlTextParser.js'); require('./components'); require('./graphics'); require('./collider'); diff --git a/cocos2d/core/label/CCHtmlTextParser.js b/cocos2d/core/label/CCHtmlTextParser.js new file mode 100644 index 0000000000..f2dc69fe4a --- /dev/null +++ b/cocos2d/core/label/CCHtmlTextParser.js @@ -0,0 +1,236 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +var eventRegx = /^(click)(\s)*=/; +/** + * 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 HTML 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(/^(br(\s)*\/)/); + if(header && header[0].length > 0) { + tagName = header[0].trim(); + if(tagName.startsWith("br") && tagName[tagName.length-1] === "/") { + obj.isNewLine = true; + this._resultObjectArray.push({text: "", style: {newline: true}}); + } + } + + 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(eventRegx); + 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 + var match = eventString.match(/(\S)+/); + if(match) { + eventValue = match[0]; + } else { + eventValue = ""; + } + index = eventValue.length; + } + + if(isValidTag) { + eventName = eventName.substring(0, eventName.length-1).trim(); + obj[eventName] = eventValue; + } + + eventString = eventString.substring(index).trim(); + eventNames = eventString.match(eventRegx); + } + + return obj; + }, + + _addToStack: function(attribute) { + var obj = this._attributeToObject(attribute); + + 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) { + 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}); + } + }, + + _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; + } +}; + + +cc.htmlTextParser = new cc.HtmlTextParser(); diff --git a/cocos2d/core/label/CCSGLabel.js b/cocos2d/core/label/CCSGLabel.js index eb2704d396..c57be4f0ef 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; }, @@ -358,6 +377,8 @@ _ccsg.Label = _ccsg.Node.extend({ if (!extName) { this._fontHandle = fontHandle; this._labelType = _ccsg.Label.Type.SystemFont; + this._blendFunc = cc.BlendFunc._alphaPremultiplied(); + this._renderCmd._needDraw = true; this._notifyLabelSkinDirty(); this.emit('load'); return; @@ -365,15 +386,36 @@ _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(); }, + cleanup: function () { + this._super(); + + //remove the created DIV and style due to loading @font-face + 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); + } + } + }, + _loadTTFFont: function(fontHandle) { var ttfIndex = fontHandle.lastIndexOf(".ttf"); if (ttfIndex === -1) return fontHandle; @@ -395,6 +437,7 @@ _ccsg.Label = _ccsg.Node.extend({ fontStyle = document.createElement("style"); fontStyle.type = "text/css"; doc.body.appendChild(fontStyle); + this._fontFaceStyle = fontStyle; var fontStr = ""; if (isNaN(fontFamilyName - 0)) @@ -415,10 +458,15 @@ _ccsg.Label = _ccsg.Node.extend({ _divStyle.left = "-100px"; _divStyle.top = "-100px"; doc.body.appendChild(preloadDiv); - self.scheduleOnce(function () { - self._notifyLabelSkinDirty(); - self.emit("load"); - }, 2); + this._preloadDiv = preloadDiv; + fontStyle.onload = function() { + fontStyle.onload = null; + self.scheduleOnce(function() { + self._notifyLabelSkinDirty(); + self.emit("load"); + },0.1); + }; + } return fontFamilyName; @@ -484,7 +532,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() { @@ -1114,7 +1162,7 @@ cc.BMFontHelper = { } }, - _computeHorizontalKerningForText: function(text) { + _computeHorizontalKerningForText: function() { var stringLen = this.getStringLength(); var locKerningDict = this._config.kerningDict; @@ -1149,7 +1197,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/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js b/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js index af49a464e5..22c49effd0 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 @@ -39,6 +41,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(); @@ -112,10 +119,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) { @@ -195,14 +203,29 @@ 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; + node._fontSize = node._drawFontsize; + var fontDesc = this._constructFontDesc(); this._labelContext.font = fontDesc; var paragraphLength = this._calculateParagraphLength(paragraphedStrings, this._labelContext); @@ -217,6 +240,11 @@ var canvasWidthNoMargin = this._canvasSize.width - 2 * this._getMargin(); var canvasHeightNoMargin = this._canvasSize.height - 2 * this._getMargin(); + if(canvasWidthNoMargin < 0 || canvasHeightNoMargin < 0) { + fontDesc = this._constructFontDesc(); + this._labelContext.font = fontDesc; + return fontDesc; + } totalHeight = canvasHeightNoMargin + 1; maxLength = canvasWidthNoMargin + 1; var actualFontSize = this._drawFontsize + 1; @@ -236,7 +264,7 @@ break; } node._fontSize = actualFontSize; - fontDesc = actualFontSize.toString() + 'px ' + fontFamily; + fontDesc = this._constructFontDesc(); this._labelContext.font = fontDesc; this._splitedStrings = []; @@ -246,7 +274,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; @@ -278,7 +305,8 @@ 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(); + this._labelContext.font = fontDesc; } } @@ -435,9 +463,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); @@ -450,6 +497,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) { @@ -463,10 +511,21 @@ 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 - 1); + this._labelContext.lineTo(underlineStartPosition.x + this._labelCanvas.width, underlineStartPosition.y + i * lineHeight - 1); + this._labelContext.stroke(); + this._labelContext.restore(); + } } 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 bf26a7144a..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 @@ -104,17 +111,11 @@ proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset) { return 0; // Fill in vertex data with quad information (4 vertices for sprite) + // Use 255 because color has been set when baking label + // premultiplied alpha is used for labelTTF and system font 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); + this._color[0] = ((opacity<<24) | (opacity<<16) | (opacity<<8) | opacity); + var z = node._vertexZ; var vertices = this._vertices; diff --git a/cocos2d/core/load-pipeline/CCLoader.js b/cocos2d/core/load-pipeline/CCLoader.js index 6f21df201c..38feb9da4a 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); }, /** @@ -281,7 +288,7 @@ JS.mixin(cc.loader, { * 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); @@ -295,7 +302,8 @@ JS.mixin(cc.loader, { completeCallback = type; type = null; } - var uuid = this._getResUuid(url, type); + var self = this; + var uuid = self._getResUuid(url, type); if (uuid) { this.load( { @@ -303,7 +311,15 @@ JS.mixin(cc.loader, { 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.setAutoReleaseRecursively(asset, false); + } + if (completeCallback) { + completeCallback(err, asset); + } + } ); } else { @@ -315,7 +331,9 @@ JS.mixin(cc.loader, { else { info = 'Resources url "' + url + '" does not exist.'; } - completeCallback(new Error(info), null); + if (completeCallback) { + completeCallback(new Error(info), null); + } }); } }, @@ -335,7 +353,7 @@ JS.mixin(cc.loader, { * * @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); @@ -360,6 +378,7 @@ JS.mixin(cc.loader, { completeCallback = type; type = null; } + var self = this; var uuids = resources.getUuidArray(url, type); var remain = uuids.length; if (remain > 0) { @@ -371,18 +390,25 @@ JS.mixin(cc.loader, { } 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.setAutoReleaseRecursively(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', @@ -394,7 +420,9 @@ JS.mixin(cc.loader, { } else { callInNextTick(function () { - completeCallback(null, []); + if (completeCallback) { + completeCallback(null, []); + } }); } }, @@ -429,7 +457,7 @@ JS.mixin(cc.loader, { /** * Returns an item in pipeline. * @method getItem - * @return {LoadingItem} + * @return {Object} */ getItem: function (url) { var item = this._items.map[url]; @@ -489,9 +517,131 @@ JS.mixin(cc.loader, { */ releaseAll: function () { this.clear(); - } + }, + + // AUTO RELEASE + + _baseRemoveItem: Pipeline.prototype.removeItem, + + // override + removeItem: function (key) { + var removed = this._baseRemoveItem(key); + delete this._autoReleaseSetting[key]; + return removed; + }, + + /** + * !#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 {Asset|String} assetOrUrl - asset object or the raw asset's url + * @param {Boolean} autoRelease - indicates whether should release automatically + */ + setAutoRelease: 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.'); + } + }, + + /** + * !#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 {Asset|String} assetOrUrl - asset object or the raw asset's url + * @param {Boolean} autoRelease - indicates whether should release automatically + */ + setAutoReleaseRecursively: function (assetOrUrl, autoRelease) { + 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.'); + } + }, + + /** + * !#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 {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/audio-downloader.js b/cocos2d/core/load-pipeline/audio-downloader.js index 40fdebb9d5..b46b5b65f8 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/cocos2d/core/load-pipeline/auto-release-utils.js b/cocos2d/core/load-pipeline/auto-release-utils.js new file mode 100644 index 0000000000..5e6eb4f685 --- /dev/null +++ b/cocos2d/core/load-pipeline/auto-release-utils.js @@ -0,0 +1,93 @@ + +function parseDepends (key, parsed) { + 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] ) { + parsed[depend] = true; + parseDepends(depend, parsed); + } + } + } + } +} + +function release (loader, key, nextSceneAssets) { + if (!nextSceneAssets || nextSceneAssets.indexOf(key) === -1) { + var item = loader.getItem(key); + if (item) { + 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 (CC_JSB && asset instanceof cc.SpriteFrame && removed) { + // for the "Temporary solution" in deserialize.js + asset.release(); + } + } + } +} + +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 (!CC_JSB && 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) { + release(loader, key, nextSceneAssets); + } + } + } + + // 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) { + release(loader, key, nextSceneAssets); + } + } + }, + + // get dependencies not including self + getDependsRecursively: function (key) { + var depends = {}; + parseDepends(key, depends); + return Object.keys(depends); + } +}; 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); 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/cocos2d/core/load-pipeline/uuid-loader.js b/cocos2d/core/load-pipeline/uuid-loader.js index a074f4e931..ebc3db3669 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, @@ -159,9 +164,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; @@ -210,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/CCAssetLibrary.js b/cocos2d/core/platform/CCAssetLibrary.js index 6601c11166..ccab1468ff 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.getDependsRecursively(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.getDependsRecursively(randomUuid); + } + if (CC_EDITOR || isScene(asset)) { + Loader.removeItem(randomUuid); + } } asset._uuid = ''; if (callback) { diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index 8111c78d98..4eda3efe1f 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; } @@ -416,7 +426,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 +435,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 { @@ -448,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; } } @@ -520,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 = []; @@ -604,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; }; } @@ -679,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 */ @@ -752,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. @@ -762,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}} @@ -776,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(); @@ -896,6 +848,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); @@ -1042,10 +1003,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); @@ -1055,7 +1016,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); } } } @@ -1068,6 +1029,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) { @@ -1105,16 +1067,19 @@ 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'); + 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; } @@ -1131,5 +1096,5 @@ module.exports = { }; if (CC_EDITOR) { - module.exports.getDefault = getDefault; + module.exports.getDefault = getDefault; } 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/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/CCSys.js b/cocos2d/core/platform/CCSys.js index 73c3eaff0d..611b70eab7 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 */ @@ -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; } @@ -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 b667c6f7ca..042cece1e0 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: true, + _scaleX: 1, _originalScaleX: 1, _scaleY: 1, @@ -149,12 +151,13 @@ var View = cc._Class.extend({ __resizeWithBrowserSize: false, _isAdjustViewPort: true, _targetDensityDPI: null, + _antiAliasEnabled: true, /** * 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); @@ -171,7 +174,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 @@ -182,6 +184,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 @@ -211,6 +214,11 @@ var View = cc._Class.extend({ } }, + _orientationChange: function () { + this._orientationChanging = true; + this._resizeEvent(); + }, + /** *

* Sets view's target-densitydpi for android mobile browser. it can be set to:
@@ -250,14 +258,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); } } }, @@ -298,7 +306,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; @@ -316,6 +324,7 @@ var View = cc._Class.extend({ cc.container.style.transformOrigin = '0px 0px 0px'; this._isRotated = true; } + this._orientationChanging = false; }, // hack @@ -416,6 +425,55 @@ 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 + * @return {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.
@@ -704,6 +762,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; @@ -875,32 +936,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; } } }); @@ -1058,7 +1117,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'; + } } }); 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 }; diff --git a/cocos2d/core/platform/deserialize.js b/cocos2d/core/platform/deserialize.js index 76b5d66d11..d94ef033ff 100644 --- a/cocos2d/core/platform/deserialize.js +++ b/cocos2d/core/platform/deserialize.js @@ -27,9 +27,6 @@ var JS = require('./js'); var CCObject = require('./CCObject'); var Attr = require('./attribute'); -var EDITOR = CC_DEV; -var ENABLE_TARGET = EDITOR; - // HELPERS /** @@ -67,22 +64,18 @@ var Details = function () { */ this.rawProp = ''; - if (EDITOR) { + 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; } }; /** @@ -95,17 +88,15 @@ Details.prototype.reset = function () { this.rawProp = ''; //this.rawObjList.length = 0; //this.rawPropList.length = 0; - - if (EDITOR) { - this.visitorInEditor = null; - this.visitObjList.length = 0; - this.visitPropList.length = 0; - } }; -if (EDITOR) { - Details.prototype.visitLater = function (obj, propName) { - this.visitObjList.push(obj); - this.visitPropList.push(propName); +if (CC_DEV) { + 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); + } }; } /** @@ -122,28 +113,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 @@ -159,13 +128,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 = []; @@ -181,7 +148,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); @@ -209,14 +176,9 @@ var _Deserializer = (function () { // dereference _dereference(this); - - // call visitor after all properties initialized - if (EDITOR) { - this._callVisitorInEditor(); - } } - var _dereference = function (self) { + function _dereference (self) { // 这里不采用遍历反序列化结果的方式,因为反序列化的结果如果引用到复杂的外部库,很容易堆栈溢出。 var deserializedList = self.deserializedList; var idPropList = self._idPropList; @@ -227,18 +189,9 @@ var _Deserializer = (function () { var id = idList[i]; idObjList[i][propName] = deserializedList[id]; } - }; - - if (EDITOR) { - _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') { @@ -258,14 +211,14 @@ var _Deserializer = (function () { this.result.uuidPropList.push(propName); } else { - if (ENABLE_TARGET) { + if (CC_DEV) { obj[propName] = _deserializeObject(this, jsonObj, target && target[propName]); } else { obj[propName] = _deserializeObject(this, jsonObj); } - if (this.result.visitorInEditor && EDITOR) { - this.result.visitLater(obj, propName); + if (CC_DEV && this.result.visit) { + this.result.visit(obj, propName); } } } @@ -279,8 +232,8 @@ var _Deserializer = (function () { this._idObjList.push(obj); this._idPropList.push(propName); } - if (this.result.visitorInEditor && EDITOR) { - this.result.visitLater(obj, propName); + if (CC_DEV && this.result.visit) { + this.result.visit(obj, propName); } } }; @@ -292,14 +245,14 @@ var _Deserializer = (function () { if (typeof prop !== 'object') { if (propName !== '__type__'/* && k != '__id__'*/) { instance[propName] = prop; - if (self.result.visitorInEditor && EDITOR) { - self.result.visitLater(instance, propName); + if (CC_DEV && self.result.visit) { + self.result.visit(instance, propName); } } } else { if (prop) { - if (ENABLE_TARGET) { + if (CC_DEV) { self._deserializeObjField(instance, prop, propName, self._target && instance); } else { @@ -328,7 +281,7 @@ var _Deserializer = (function () { } else { if (prop) { - if (ENABLE_TARGET) { + if (CC_DEV) { self._deserializeObjField(instance, prop, propName, self._target && instance); } else { @@ -344,22 +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 (!EDITOR && 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 not editor + 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]; @@ -371,7 +327,7 @@ var _Deserializer = (function () { } else { if (prop) { - if (ENABLE_TARGET) { + if (CC_DEV) { self._deserializeObjField(obj, prop, propName, target && obj); } else { @@ -404,8 +360,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__) { @@ -413,18 +369,16 @@ var _Deserializer = (function () { // Type Object (including CCClass) var type = serialized.__type__; - klass = self._classFinder(type); + klass = self._classFinder(type, serialized); 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) { + cc.deserialize.reportMissingClass(type); } - cc.warn('Can not find class "%s"', type); 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', @@ -456,14 +410,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; } @@ -474,7 +428,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 { @@ -483,21 +437,18 @@ var _Deserializer = (function () { } else { obj[i] = prop; - - if (self.result.visitorInEditor && EDITOR) { - self.result.visitLater(obj, '' + i); + if (CC_DEV && self.result.visit) { + self.result.visit(obj, '' + i); } } } } return obj; - }; + } return _Deserializer; })(); -// FACADE - /** * @module cc */ @@ -516,11 +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 = ENABLE_TARGET && (options && options.target); - var customEnv = (options && options.customEnv); + 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(); @@ -536,7 +489,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) { @@ -552,3 +505,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); + } +}; 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..9feb76de04 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; } } @@ -103,12 +111,21 @@ 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; } - 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/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/core/renderer/RendererCanvas.js b/cocos2d/core/renderer/RendererCanvas.js index af6676b101..dc0665fcb8 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 || cc.sys.browserType === cc.sys.BROWSER_TYPE_UC) { + this.enableDirtyRegion(false); + } + }, getRenderCmd: function (renderableObject) { //TODO Add renderCmd pool here @@ -390,14 +395,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){ 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/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/sprites/CCScale9Sprite.js b/cocos2d/core/sprites/CCScale9Sprite.js index 52e1a20362..cb29379ebf 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._pixelWidth; + var atlasHeight = spriteFrame._texture._pixelHeight; 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 (sprite._uvsDirty) { + this._calculateUVs(sprite, spriteFrame, insetLeft, insetRight, insetTop, insetBottom); + } }, _calculateUVs: function (sprite, spriteFrame, insetLeft, insetRight, insetTop, insetBottom) { var uvs = sprite._uvs; var rect = spriteFrame._rect; - var atlasWidth = spriteFrame._texture.getPixelWidth(); - var atlasHeight = spriteFrame._texture.getPixelHeight(); + var atlasWidth = spriteFrame._texture._pixelWidth; + var atlasHeight = spriteFrame._texture._pixelHeight; //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,20 +287,20 @@ 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; - 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++) { @@ -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._pixelWidth; + var atlasHeight = spriteFrame._texture._pixelHeight; var textureRect = spriteFrame._rect; //uv computation should take spritesheet into account. @@ -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; } }; @@ -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._pixelWidth; + var atlasHeight = spriteFrame._texture._pixelHeight; var textureRect = spriteFrame._rect; //uv computation should take spritesheet into account. var ul, vb, ur, vt; @@ -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; @@ -532,14 +510,12 @@ var fillQuadGeneratorBar = { // tr : 6, 7 var progressStart, progressEnd; switch (fillType) { - case cc.Scale9Sprite.FillType.HORIZONTAL: - progressStart = vertices[0] + (vertices[2] - vertices[0]) * fillStart; - progressEnd = vertices[0] + (vertices[2] - vertices[0]) * fillEnd; + case FillType.HORIZONTAL: + 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]; @@ -550,14 +526,12 @@ var fillQuadGeneratorBar = { uvs[6] = quadUV[4] + (quadUV[6] - quadUV[4]) * fillEnd; uvs[7] = quadUV[7]; break; - case cc.Scale9Sprite.FillType.VERTICAL: - progressStart = vertices[1] + (vertices[5] - vertices[1]) * fillStart; - progressEnd = vertices[1] + (vertices[5] - vertices[1]) * fillEnd; + case FillType.VERTICAL: + 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; @@ -603,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; @@ -681,12 +676,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; @@ -697,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; @@ -715,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; @@ -728,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; } @@ -751,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; @@ -763,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); @@ -879,23 +884,15 @@ 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) { - var atlasWidth = spriteFrame._texture.getPixelWidth(); - var atlasHeight = spriteFrame._texture.getPixelHeight(); + var atlasWidth = spriteFrame._texture._pixelWidth; + var atlasHeight = spriteFrame._texture._pixelHeight; var textureRect = spriteFrame._rect; //uv computation should take spritesheet into account. @@ -946,6 +943,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ _uvs: null, _vertCount: 0, _quadsDirty: true, + _uvsDirty: true, _isTriangle: false, _isTrimmedContentSize: true, //fill type @@ -1045,6 +1043,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 () { @@ -1076,6 +1075,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 +1106,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 +1121,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 +1140,8 @@ 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); }, /** * get the rendering type, could be simple or slice @@ -1153,6 +1157,8 @@ cc.Scale9Sprite = _ccsg.Node.extend({ setInsetLeft: function (insetLeft) { this._insetLeft = insetLeft; this._quadsDirty = true; + this._uvsDirty = true; + this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); }, /** * get the left border of 9 slice sprite, the result is specified before trimmed. @@ -1168,6 +1174,8 @@ cc.Scale9Sprite = _ccsg.Node.extend({ setInsetTop: function (insetTop) { this._insetTop = insetTop; this._quadsDirty = true; + this._uvsDirty = true; + this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); }, /** @@ -1185,6 +1193,8 @@ cc.Scale9Sprite = _ccsg.Node.extend({ setInsetRight: function (insetRight) { this._insetRight = insetRight; this._quadsDirty = true; + this._uvsDirty = true; + this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); }, /** @@ -1202,6 +1212,8 @@ cc.Scale9Sprite = _ccsg.Node.extend({ setInsetBottom: function (insetBottom) { this._insetBottom = insetBottom; this._quadsDirty = true; + this._uvsDirty = true; + this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); }, /** * get the bottom border of 9 slice sprite, the result is specified before trimmed. @@ -1215,8 +1227,9 @@ 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); } }, @@ -1226,8 +1239,9 @@ 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); } }, @@ -1259,8 +1273,9 @@ 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); } }, @@ -1272,8 +1287,9 @@ 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); } }, @@ -1287,24 +1303,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; @@ -1312,20 +1328,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; @@ -1333,12 +1348,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; } @@ -1358,6 +1374,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ } this._quadsDirty = false; + this._uvsDirty = false; }, _createRenderCmd: function () { if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) @@ -1382,7 +1399,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 */ @@ -1401,7 +1418,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/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/sprites/CCScale9SpriteWebGLRenderCmd.js b/cocos2d/core/sprites/CCScale9SpriteWebGLRenderCmd.js index d34298c50c..0c7ed638bd 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; @@ -84,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(); @@ -106,7 +92,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,16 +101,16 @@ 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 ); + cc.renderer._breakBatch(); } // Color & z @@ -144,20 +130,30 @@ 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) { 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); 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 +163,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 +186,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 +201,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 +215,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; }; diff --git a/cocos2d/core/sprites/CCSpriteFrame.js b/cocos2d/core/sprites/CCSpriteFrame.js index 50d886fbbd..8065abc8ba 100644 --- a/cocos2d/core/sprites/CCSpriteFrame.js +++ b/cocos2d/core/sprites/CCSpriteFrame.js @@ -292,20 +292,23 @@ 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()); var tempTexture = new cc.Texture2D(); tempTexture.initWithElement(tempElement); tempTexture.handleLoadedTexture(); - // _refreshTexture will be recalled in setTexture - self.setTexture(tempTexture); - return; + self._texture = tempTexture; + self._rotated = false; + 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)); diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index 859c5d646a..c60399c190 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 = ""; @@ -94,10 +96,7 @@ 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._pixelsWide = 0; - this._pixelsHigh = 0; this._hasPremultipliedAlpha = false; this._hasMipmaps = false; @@ -111,7 +110,7 @@ var Texture2D = cc.Class(/** @lends cc.Texture2D# */{ * @return {Number} */ getPixelWidth: function () { - return this._contentSize.width; + return this._pixelWidth; }, /** @@ -120,7 +119,7 @@ var Texture2D = cc.Class(/** @lends cc.Texture2D# */{ * @return {Number} */ getPixelHeight: function () { - return this._contentSize.height; + return this._pixelHeight; }, /** @@ -162,8 +161,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,10 +228,20 @@ 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; + // 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"); }, @@ -716,13 +725,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 +786,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,14 +865,21 @@ 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; self._hasMipmaps = false; self._textureLoaded = true; + if (cc.view._antiAliasEnabled) { + self.setAntiAliasTexParameters(); + } + else { + self.setAliasTexParameters(); + } + //dispatch load event to listener. self.emit("load"); }, @@ -882,7 +891,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 +926,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); diff --git a/cocos2d/core/textures/CCTextureCache.js b/cocos2d/core/textures/CCTextureCache.js index 657c66a408..ac6650163b 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} @@ -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"
diff --git a/cocos2d/core/utils/base-node.js b/cocos2d/core/utils/base-node.js index 43e078f206..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 @@ -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 @@ -1609,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} @@ -1885,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]); } } @@ -1942,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; @@ -1971,14 +1972,18 @@ 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); + 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); @@ -2003,29 +2008,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(); @@ -2055,6 +2037,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); 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 '/' diff --git a/cocos2d/core/utils/prefab-helper.js b/cocos2d/core/utils/prefab-helper.js new file mode 100644 index 0000000000..89efaad05c --- /dev/null +++ b/cocos2d/core/utils/prefab-helper.js @@ -0,0 +1,103 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +// 保存编辑器下用到的 prefab 相关信息 +cc._PrefabInfo = cc.Class({ + name: 'cc.PrefabInfo', + properties: { + //// the serialized version + //VER: { + // default: 1 + //}, + + // the most top node of this prefab in the scene + root: null, + + // 所属的 prefab 资源对象 (cc.Prefab) + // (这个属性在场景中是会保存的,但是不会保存在 prefab 里面,因为创建 prefab 时还不知道自己的 uuid 是多少。) + asset: null, + + // 用来标识别该节点在 prefab 资源中的位置,因此这个 ID 只需要保证在 Assets 里不重复就行 + fileId: '', + + // 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 + }, + } +}); + +// 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/cocos2d/core/utils/scene-graph-helper.js b/cocos2d/core/utils/scene-graph-helper.js index 5b6d2ffcb7..1b0fc22a10 100644 --- a/cocos2d/core/utils/scene-graph-helper.js +++ b/cocos2d/core/utils/scene-graph-helper.js @@ -34,6 +34,9 @@ var SceneGraphUtils = { parent.removeChild(node); } node.release(); + if (this._sgNode._entity) { + this._sgNode._entity = null; + } } }, }; 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; diff --git a/cocos2d/core/videoplayer/CCSGVideoPlayer.js b/cocos2d/core/videoplayer/CCSGVideoPlayer.js index 4dc4b8bfe2..831672ea52 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(){ @@ -74,6 +73,14 @@ _ccsg.VideoPlayer = _ccsg.Node.extend(/** @lends _ccsg.VideoPlayer# */{ return this._renderCmd.isPlaying(); }, + duration: function () { + return this._renderCmd.duration(); + }, + + currentTime: function() { + return this._renderCmd.currentTime(); + }, + createDomElementIfNeeded: function () { if (!this._renderCmd._video) { this._renderCmd.createDom(); @@ -132,9 +139,9 @@ _ccsg.VideoPlayer = _ccsg.Node.extend(/** @lends _ccsg.VideoPlayer# */{ }, cleanup: function () { + this._super(); + this._renderCmd.removeDom(); - this.stopAllActions(); - this.unscheduleAllCallbacks(); }, onEnter: function () { @@ -183,15 +190,11 @@ 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: "play", - PAUSED: "pause", - STOPPED: "stop", - COMPLETED: "complete" + PLAYING: 0, + PAUSED: 1, + STOPPED: 2, + COMPLETED: 3 }; (function (video) { @@ -275,7 +278,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); @@ -388,9 +391,20 @@ _ccsg.VideoPlayer.EventType = { var video = this._video; if (node.visible) { video.style.visibility = 'visible'; + cc.game.container.appendChild(video); } else { video.style.visibility = 'hidden'; video.pause(); + if(video){ + var hasChild = false; + if('contains' in cc.game.container) { + hasChild = cc.game.container.contains(video); + }else { + hasChild = cc.game.container.compareDocumentPosition(video) % 16; + } + if(hasChild) + cc.game.container.removeChild(video); + } } }; @@ -402,20 +416,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 = ""; @@ -495,6 +509,7 @@ _ccsg.VideoPlayer.EventType = { }; proto.isPlaying = function () { + var video = this._video; if(_ccsg.VideoPlayer._polyfill.autoplayAfterOperation && this._playing){ setTimeout(function(){ video.play(); @@ -503,4 +518,18 @@ _ccsg.VideoPlayer.EventType = { return this._playing; }; + proto.duration = function () { + var video = this._video; + if(!video) return -1; + + return video.duration; + }; + + proto.currentTime = function () { + var video = this._video; + if(!video) return -1; + + return video.currentTime; + }; + })(_ccsg.VideoPlayer._polyfill); diff --git a/cocos2d/core/webview/CCSGWebView.js b/cocos2d/core/webview/CCSGWebView.js new file mode 100644 index 0000000000..db7f3295f3 --- /dev/null +++ b/cocos2d/core/webview/CCSGWebView.js @@ -0,0 +1,407 @@ +/**************************************************************************** + 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.WebView# */{ + + ctor: function () { + _ccsg.Node.prototype.ctor.call(this); + this.setContentSize(cc.size(300, 200)); + this._EventList = {}; + }, + + createDomElementIfNeeded: function () { + if (!this._renderCmd._div) { + this._renderCmd.createNativeControl(); + } + }, + + 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} width + * @param {Number} height + */ + setContentSize: function(width, height){ + if (width.width !== undefined && width.height !== undefined) { + height = width.height; + width = width.width; + } + _ccsg.Node.prototype.setContentSize.call(this, width, height); + this._renderCmd.updateSize(width, height); + }, + + /** + * remove node + */ + cleanup: function(){ + this._super(); + + this._renderCmd.removeDom(); + }, + + setVisible: function ( visible ) { + _ccsg.Node.prototype.setVisible.call(this, visible); + this._renderCmd.updateVisibility(); + } +}); + +_ccsg.WebView.EventType = { + LOADING: 0, + LOADED: 1, + ERROR: 2, + JS_EVALUATED: 3 +}; + +(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._parent = null; + this._div = null; + this._iframe = null; + this._listener = null; + }; + + var proto = _ccsg.WebView.RenderCmd.prototype = Object.create(RenderCmd.prototype); + proto.constructor = _ccsg.WebView.RenderCmd; + + proto.transform = function (parentCmd, recursive) { + this.originTransform(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.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){ + 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(){ + 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; + + scaleX /= dpr; + scaleY /= dpr; + + var container = cc.game.container; + var a = t.a * scaleX, b = t.b, c = t.c, d = t.d * scaleY; + + var offsetX = container && container.style.paddingLeft && parseInt(container.style.paddingLeft); + var offsetY = container && container.style.paddingBottom && parseInt(container.style.paddingBottom); + var tx = t.tx * scaleX + offsetX, ty = t.ty * scaleY + offsetY; + + 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; + self.updateVisibility(); + iframe.removeEventListener("load", cb); + }; + iframe.addEventListener("load", cb); + }; + + proto.updateSize = function(w, h){ + var div = this._div; + if(div){ + div.style["width"] = w+"px"; + div.style["height"] = h+"px"; + } + }; + + 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.game.container.appendChild(this._div); + }; + + proto.createNativeControl = function () { + this.createDom(); + this.initStyle(); + this.initEvent(); + }; + + proto.removeDom = function(){ + var div = this._div; + if(div){ + var hasChild = false; + if('contains' in cc.game.container) { + hasChild = cc.game.container.contains(div); + }else { + hasChild = cc.game.container.compareDocumentPosition(div) % 16; + } + if(hasChild) + cc.game.container.removeChild(div); + } + 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'; + cc.game.container.appendChild(div); + } else { + div.style.visibility = 'hidden'; + if(div){ + var hasChild = false; + if('contains' in cc.game.container) { + hasChild = cc.game.container.contains(div); + }else { + hasChild = cc.game.container.compareDocumentPosition(div) % 16; + } + if(hasChild) + cc.game.container.removeChild(div); + } + } + }; + +})(_ccsg.WebView._polyfill); diff --git a/cocos2d/deprecated.js b/cocos2d/deprecated.js index 9cc425071f..1b08d8831b 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; @@ -210,6 +211,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 @@ -273,7 +279,9 @@ if (CC_DEV) { } // 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'); @@ -372,7 +380,6 @@ if (CC_DEV) { 'onEnterTransitionDidFinish', 'onExitTransitionDidStart', 'onExit', - 'getNumberOfRunningActions', 'scheduleUpdate', 'scheduleUpdateWithPriority', 'unscheduleUpdate', @@ -392,6 +399,8 @@ if (CC_DEV) { 'transform', 'getCamera', 'grid', + 'getOrderOfArrival', + 'setOrderOfArrival', 'getGrid', 'setGrid', 'getShaderProgram', @@ -422,8 +431,6 @@ if (CC_DEV) { _detachChild: 'removeChild', getZOrder: 'getLocalZOrder', setZOrder: 'setLocalZOrder', - getOrderOfArrival: 'getSiblingIndex', - setOrderOfArrival: 'setSiblingIndex', boundingBox: 'getBoundingBox', removeFromParentAndCleanup: 'removeFromParent', removeAllChildrenWithCleanup: 'removeAllChildren', @@ -434,7 +441,7 @@ if (CC_DEV) { removeAllComponents: 'removeComponent', getNodeToParentAffineTransform: 'getNodeToParentTransform', }); - + // RENDERERS function shouldNotUseNodeProp (component) { @@ -544,29 +551,33 @@ if (CC_DEV) { 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', { setPreferredSize: 'setContentSize', @@ -612,4 +623,214 @@ 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; + }; + } + }, + }); + + (function (audioEngine) { + if (typeof audioEngine === 'undefined') return; + + (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 () { + cc.warn(INFO, 'audioEngine.playMusic', 'audioEngine.play'); + return function (url, loop) { + musicId = audioEngine.play(url, loop, musicVolume); + return musicId; + } + }); + js.get(audioEngine, 'stopMusic', function () { + cc.warn(INFO, 'audioEngine.stopMusic', 'audioEngine.stop'); + return function () { + audioEngine.stop(musicId); + return musicId; + } + }); + js.get(audioEngine, 'pauseMusic', function () { + cc.warn(INFO, 'audioEngine.pauseMusic', 'audioEngine.pause'); + return function () { + audioEngine.pause(musicId); + return musicId; + } + }); + js.get(audioEngine, 'resumeMusic', function () { + cc.warn(INFO, 'audioEngine.resumeMusic', 'audioEngine.resume'); + return function () { + audioEngine.resume(musicId); + return musicId; + } + }); + js.get(audioEngine, 'rewindMusic', function () { + cc.warn(INFO, 'audioEngine.rewindMusic', 'audioEngine.setCurrentTime'); + return function () { + audioEngine.setCurrentTime(musicId, 0); + return musicId; + } + }); + js.get(audioEngine, 'getMusicVolume', function () { + cc.warn(INFO, 'audioEngine.getMusicVolume', 'audioEngine.getVolume'); + return function () { + return musicVolume; + } + }); + js.get(audioEngine, 'setMusicVolume', function () { + cc.warn(INFO, 'audioEngine.setMusicVolume', 'audioEngine.setVolume'); + return function (volume) { + musicVolume = volume; + audioEngine.setVolume(musicId, musicVolume); + return musicVolume; + } + }); + js.get(audioEngine, 'isMusicPlaying', function () { + cc.warn(INFO, 'audioEngine.isMusicPlaying', 'audioEngine.getState'); + return function () { + return audioEngine.getState(musicId) === audioEngine.AudioState.PLAYING; + } + }); + js.get(audioEngine, 'playEffect', function () { + cc.warn(INFO, 'audioEngine.playEffect', 'audioEngine.play'); + + 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'); + 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 function () { + return effectsVolume; + } + }); + js.get(audioEngine, 'pauseEffect', function () { + cc.warn(INFO, 'audioEngine.pauseEffect', 'audioEngine.pause'); + + return function (id) { + return audioEngine.pause(id); + } + }); + js.get(audioEngine, 'pauseAllEffects', function () { + cc.warn(INFO, 'audioEngine.pauseAllEffects', 'audioEngine.pauseAll'); + + 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 () { + cc.warn(INFO, 'audioEngine.resumeEffect', 'audioEngine.resume'); + return function (id) { + audioEngine.resume(id); + } + }); + js.get(audioEngine, 'resumeAllEffects', function () { + cc.warn(INFO, 'audioEngine.resumeEffect', 'audioEngine.resume'); + 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, '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 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/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) { diff --git a/cocos2d/tilemap/CCSGTMXLayer.js b/cocos2d/tilemap/CCSGTMXLayer.js index 940b8aa0f7..da8dacb4a9 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,8 +163,12 @@ _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.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; @@ -321,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; }, @@ -329,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; }, @@ -434,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) { @@ -477,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]; diff --git a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js index fad0e201b3..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); @@ -167,14 +169,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) { diff --git a/cocos2d/tilemap/CCTMXXMLParser.js b/cocos2d/tilemap/CCTMXXMLParser.js index 1ab54869f8..94bb8ebb90 100644 --- a/cocos2d/tilemap/CCTMXXMLParser.js +++ b/cocos2d/tilemap/CCTMXXMLParser.js @@ -275,7 +275,6 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ // tile properties _tileProperties:null, _resources:"", - _currentFirstGID:0, // hex map values _staggerAxis: null, @@ -299,8 +298,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){ @@ -589,9 +586,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); @@ -672,19 +670,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; @@ -1044,7 +1040,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; } }); diff --git a/cocos2d/tilemap/CCTiledLayer.js b/cocos2d/tilemap/CCTiledLayer.js index 358048ab4f..91bea306c4 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 获得层大小。 diff --git a/cocos2d/tilemap/CCTiledMap.js b/cocos2d/tilemap/CCTiledMap.js index e090315b7f..5e55296329 100644 --- a/cocos2d/tilemap/CCTiledMap.js +++ b/cocos2d/tilemap/CCTiledMap.js @@ -814,6 +814,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 { diff --git a/extends.js b/extends.js index acea5b0d64..7c32d5e406 100644 --- a/extends.js +++ b/extends.js @@ -57,3 +57,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/extensions/anysdk/jsb_anysdk.js b/extensions/anysdk/jsb_anysdk.js new file mode 100644 index 0000000000..b6bbc8e366 --- /dev/null +++ b/extensions/anysdk/jsb_anysdk.js @@ -0,0 +1,2784 @@ +/**************************************************************************** + 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 {anysdk.AgentManager} agentManager + */ +anysdk.agentManager = anysdk.AgentManager.getInstance(); + +/** + * !#en + * agent manager of plugin + * !#zh + * 插件管理类 + * @class AgentManager + * @constructor + */ +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 getIAPPlugins + * @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 + * @static + */ + end: function(){ + }, + + /** + * !#en + * get instance + * !#zh + * 获取单例 + * @method getInstance + * @return {anysdk.AgentManager} + * @static + */ + 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; + }, + + /** + * !#en + * void methods for reflections with parameter + * !#zh + * 反射调用带参数的void方法 + * @method callFuncWithParam + * @param {String} funName + * @param {Object|anysdk.PluginParam} [...args] optional arguments + * @expose + */ + callFuncWithParam: function(funName){ + }, + + /** + * !#en + * String methods for reflections with parameter + * !#zh + * 反射调用带参数的 String 方法 + * @method callStringFuncWithParam + * @param {String} funName + * @param {Object|anysdk.PluginParam} [...args] optional arguments + * @return {String} + * @expose + */ + callStringFuncWithParam: function(funName){ + return String; + }, + + /** + * !#en + * int methods for reflections with parameter + * !#zh + * 反射调用带参数的 Int 方法 + * @method callIntFuncWithParam + * @param {String} funName + * @param {Object|anysdk.PluginParam} [...args] optional arguments + * @return {Number} Type:int + * @expose + */ + callIntFuncWithParam: function(funName){ + return int; + }, + + /** + * !#en + * boolean methods for reflections with parameter + * !#zh + * 反射调用带参数的 boolean 方法 + * @method callBoolFuncWithParam + * @param {String} funName + * @param {Object|anysdk.PluginParam} [...args] optional arguments + * @return {boolean} + * @expose + */ + callBoolFuncWithParam: function(funName){ + return boolean; + }, + + /** + * !#en + * float methods for reflections with parameter + * !#zh + * 反射调用带参数的 float 方法 + * @method callFloatFuncWithParam + * @param {String} funName + * @param {Object|anysdk.PluginParam} [...args] optional arguments + * @return {Number} Type:float + * @expose + */ + callFloatFuncWithParam: function(funName){ + return float; + }, +}; + +/** + * !#en + * user protocol + * !#zh + * 用户系统协议接口 + * @class ProtocolUser + * @extends PluginProtocol + */ +anysdk.ProtocolUser = PluginProtocol.extend({ + + /** + * !#en + * login interface + * !#zh + * 登录接口 + * @method login + * @param {String|Object} [...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 {Object} data + */ + submitLoginGameRole: function(data){ + }, + /** + * !#en + * get user information + * Before to invoke, you need to verdict whether this properties existed + * !#zh + * 获取用户信息,调用前需要判断属性是否存在 + * @method getUserInfo + * @param {Object} info + */ + getUserInfo:function(info){ + }, + + /** + * !#en + * set login type + * Before to invoke, you need to verdict whether this properties existed + * !#zh + * 设置登录类型,调用前需要判断属性是否存在 + * @method getAvailableLoginType + * @param {Object} 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(){ + }, + +}); + + +/** + * !#en + * IAP protocol + * !#zh + * 支付系统协议接口 + * @class ProtocolIAP + * @extends PluginProtocol + */ +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; + }, + +}); + +/** + * !#en + * analytics protocol + * !#zh + * 统计系统协议接口 + * @class ProtocolAnalytics + * @extends PluginProtocol + */ +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){ + }, + + + +}); + +/** + * !#en + * share protocol + * !#zh + * 分享系统协议接口 + * @class ProtocolShare + * @extends PluginProtocol + */ +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; + }, +}); + + +/** + * !#en + * ads protocol + * !#zh + * 广告系统协议接口 + * @class ProtocolAds + * @extends PluginProtocol + */ +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; + }, + +}); + +/** + * !#en + * social protocol + * !#zh + * 社交系统协议接口 + * @class ProtocolSocial + * @extends PluginProtocol + */ +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(){ + }, +}); + +/** + * !#en + * push protocol + * !#zh + * 推送系统协议接口 + * @class ProtocolPush + * @extends PluginProtocol + */ +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; + }, + +}); + +/** + * !#en + * crash protocol + * !#zh + * 崩溃分析系统协议接口 + * @class ProtocolCrash + * @extends PluginProtocol + */ +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) + { + }, + +}); + +/** + * !#en + * REC protocol + * !#zh + * 录屏系统协议接口 + * @class ProtocolREC + * @extends PluginProtocol + */ +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){ + }, + +}); + + + +/** + * !#en + * ad tracking protocol + * !#zh + * 广告追踪系统协议接口 + * @class ProtocolAdTracking + * @extends PluginProtocol + */ +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){ + }, + +}); + +/** + * !#en + * custom protocol + * !#zh + * 自定义系统协议接口 + * @class ProtocolCustom + * @extends PluginProtocol + */ +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 + * 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 用户系统回调 + * @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 +}; + + + + + + + + + + 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: {}, 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/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; diff --git a/extensions/spine/Skeleton.js b/extensions/spine/Skeleton.js index 67dea2fa9a..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); @@ -504,10 +529,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 +549,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 +569,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 +591,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 +642,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 +654,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 +697,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 +726,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 +745,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 191de16798..373fceae74 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: [], @@ -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 + */ 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'); })); } diff --git a/gulp/tasks/modular.js b/gulp/tasks/modular.js index c8240efeb8..f7f511b1bf 100644 --- a/gulp/tasks/modular.js +++ b/gulp/tasks/modular.js @@ -112,6 +112,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', 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 diff --git a/gulpfile.js b/gulpfile.js index b3be965f30..7da5a86c95 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/cocos2d-js.js', './bin/cocos2d-js-min.js', './bin/.cache'], done); +}); ///////////// @@ -140,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); }); 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/index.js b/jsb/index.js index 18f61b6f61..26f7833650 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)); }; @@ -98,12 +96,14 @@ 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'); 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-action.js b/jsb/jsb-action.js index f2f0659f6f..6880d17034 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,6 +133,27 @@ cc.Follow.prototype.update = function(dt) { } }; +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 = toggleVisible ? !render.enabled : visible; + } +} + +cc.Show.prototype.update = function (dt) { + setRendererVisibility(this.getTarget(), false, true); +}; + +cc.Hide.prototype.update = function (dt) { + setRendererVisibility(this.getTarget(), false, false); +}; + +cc.ToggleVisibility.prototype.update = function (dt) { + setRendererVisibility(this.getTarget(), true); +}; + // Special call func cc.callFunc = function (selector, selectorTarget, data) { var callback = function (sender, data) { @@ -178,6 +209,7 @@ cc.Node.prototype.runAction = function (action) { action.release(); action._retained = false; } + return action; }; function getSGTarget (target) { @@ -315,24 +347,22 @@ 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, 'RotateTo': syncRotationUpdate, 'RotateBy': syncRotationUpdate, 'ScaleTo': syncScaleUpdate, - 'ScaleBy': syncScaleUpdate, 'RemoveSelf': syncRemoveSelfUpdate, 'SkewTo': syncSkewUpdate, - 'SkewBy': syncSkewUpdate, 'Blink': syncOpacityUpdate, 'FadeIn': syncOpacityUpdate, 'FadeOut': syncOpacityUpdate, 'FadeTo': syncOpacityUpdate, 'TintTo': syncColorUpdate, - 'TintBy': syncColorUpdate + 'TintBy': syncColorUpdate, + 'BezierBy': syncPositionUpdate }; for (var key in actionUpdate) { diff --git a/jsb/jsb-audio.js b/jsb/jsb-audio.js new file mode 100644 index 0000000000..e79c41cb26 --- /dev/null +++ b/jsb/jsb-audio.js @@ -0,0 +1,144 @@ +/**************************************************************************** + 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; + this._eventList = {}; + + this.type = cc.Audio.Type.NATIVE; +}; + +cc.Audio.Type = { + DOM: 'AUDIO', + WEBAUDIO: 'WEBAUDIO', + NATIVE: 'NATIVE', + UNKNOWN: 'UNKNOWN' +}; + +(function (proto, audioEngine) { + + // 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); + }; + + proto.pause = function () { + audioEngine.pause(this.id); + }; + + proto.resume = function () { + audioEngine.resume(this.id); + }; + + proto.stop = function () { + audioEngine.stop(this.id); + }; + + proto.setLoop = function (loop) { + this.loop = loop; + audioEngine.setLoop(this.id, loop) + }; + + proto.getLoop = function () { + return audioEngine.getLoop(this.id) + }; + + proto.setVolume = function (volume) { + this.volume = volume; + return audioEngine.setVolume(this.id, volume) + }; + + proto.getVolume = function () { + return audioEngine.getVolume(this.id) + }; + + proto.setCurrentTime = function (time) { + audioEngine.setCurrentTime(this.id, time); + }; + + proto.getCurrentTime = function () { + return audioEngine.getCurrentTime(this.id) + }; + + proto.getDuration = function () { + return audioEngine.getDuration(this.id) + }; + + 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 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'); 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 () {}; +} 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-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']]); +}); + 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..6fea81779f --- /dev/null +++ b/test/qunit/unit/test-html-text-parser.js @@ -0,0 +1,326 @@ +/*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", + } + }}], "Size with event"); + + var eventTestString4 = "hello world"; + deepEqual(parser.parse(eventTestString4), + [{text: "hello world", + 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."); + + +}); + +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 \n world"; + + deepEqual(parser.parse(stringWithBold), + [{text: "hello \n 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"); +}); + +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"); + + 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"); +}); 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); }); diff --git a/test/qunit/unit/test-prefab-sync.js b/test/qunit/unit/test-prefab-sync.js new file mode 100644 index 0000000000..ae2d8722fe --- /dev/null +++ b/test/qunit/unit/test-prefab-sync.js @@ -0,0 +1,170 @@ +(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'); + }); + + 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'); + }); + +})(); 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 diff --git a/test/qunit/unit/test-spriteRenderer.js b/test/qunit/unit/test-spriteRenderer.js index 6e5c743108..7a3bd1596f 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.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(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.01, 'texCoords-bl-x test success'); + deepClose(uvs[1], 70 / 100, 0.01, '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.01, 'texCoords-tr-x test success'); + deepClose(uvs[7], 10 / 100, 0.01, '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.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(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.01, 'texCoords-bl-x test success'); + deepClose(uvs[1], 70 / 100, 0.01, '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.01, 'texCoords-tr-x test success'); + deepClose(uvs[7], 10 / 100, 0.01, '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.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'); + 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.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(); @@ -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[8], 40, 'x1 test success'); + strictEqual(vertices[16], 80, 'x2 test success'); + strictEqual(vertices[18], 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[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(); @@ -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.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'); - 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.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(); - 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.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'); - 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], 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(); @@ -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.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'); - 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.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(); - 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.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'); - 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.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(); @@ -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.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(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.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();