From 750b1406c8a070452c2d16b751afff29e46df54d Mon Sep 17 00:00:00 2001 From: Dany Ellement Date: Mon, 16 Feb 2015 14:52:55 -0500 Subject: [PATCH 0001/1039] Added GradientStops Feature to LayerGradient (Canvas Mode) --- cocos2d/core/layers/CCLayer.js | 64 +++++++++++++++++-- cocos2d/core/layers/CCLayerCanvasRenderCmd.js | 29 ++++++++- 2 files changed, 84 insertions(+), 9 deletions(-) diff --git a/cocos2d/core/layers/CCLayer.js b/cocos2d/core/layers/CCLayer.js index 297217e3b6..a072e282a3 100644 --- a/cocos2d/core/layers/CCLayer.js +++ b/cocos2d/core/layers/CCLayer.js @@ -322,21 +322,38 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{ _alongVector: null, _compressedInterpolation: false, _className: "LayerGradient", + _colorStops: [], /** * Constructor of cc.LayerGradient * @param {cc.Color} start * @param {cc.Color} end * @param {cc.Point} [v=cc.p(0, -1)] - */ - ctor: function (start, end, v) { + * @param {Array|Null} stops + * + * @example Using ColorStops argument: + * //startColor & endColor are for default and backward compatibility + * var layerGradient = new cc.LayerGradient(cc.color.RED, new cc.Color(255,0,0,0), cc.p(0, -1), + * [{p:0, color: cc.color.RED}, + * {p:.5, color: new cc.Color(0,0,0,0)}, + * {p:1, color: cc.color.RED}]); + * //where p = A value between 0.0 and 1.0 that represents the position between start and end in a gradient + * + */ + ctor: function (start, end, v, stops) { var _t = this; cc.LayerColor.prototype.ctor.call(_t); _t._endColor = cc.color(0, 0, 0, 255); _t._alongVector = cc.p(0, -1); _t._startOpacity = 255; _t._endOpacity = 255; - cc.LayerGradient.prototype.init.call(_t, start, end, v); + + if(stops && stops instanceof Array) + _t._colorStops = stops; + else + _t._colorStops = [{p:0, color: start}, {p:1, color: end}]; + + cc.LayerGradient.prototype.init.call(_t, start, end, v, stops); }, /** @@ -344,9 +361,10 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{ * @param {cc.Color} start starting color * @param {cc.Color} end * @param {cc.Point|Null} v + * @param {Array|Null} stops * @return {Boolean} */ - init: function (start, end, v) { + init: function (start, end, v, stops) { start = start || cc.color(0, 0, 0, 255); end = end || cc.color(0, 0, 0, 255); v = v || cc.p(0, -1); @@ -498,6 +516,36 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.gradientDirty); }, + /** + * Return an array of Object representing a colorStop for the gradient, if no stops was specified + * start & endColor will be provided as default values + * @example + * [{p: 0, color: cc.color.RED},{p: 1, color: cc.color.RED},...] + * @returns {Array} + */ + getColorStops: function(){ + return this._colorStops; + }, + /** + * Set the colorStops to create the gradient using multiple point & color + * + * @param colorStops + * + * @example + * //startColor & endColor are for default and backward compatibility + * var layerGradient = new cc.LayerGradient(cc.color.RED, new cc.Color(255,0,0,0), cc.p(0, -1)); + * layerGradient.setColorStops([{p:0, color: cc.color.RED}, + * {p:.5, color: new cc.Color(0,0,0,0)}, + * {p:1, color: cc.color.RED}]); + * //where p = A value between 0.0 and 1.0 that represents the position between start and end in a gradient + * + */ + setColorStops: function(colorStops){ + + this._colorStops = colorStops; + this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty|cc.Node._dirtyFlags.opacityDirty|cc.Node._dirtyFlags.gradientDirty); + }, + _createRenderCmd: function(){ if (cc._renderType === cc._RENDER_TYPE_CANVAS) return new cc.LayerGradient.CanvasRenderCmd(this); @@ -513,10 +561,11 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{ * @param {cc.Color} start starting color * @param {cc.Color} end ending color * @param {cc.Point|Null} v + * @param {Array|NULL} stops * @return {cc.LayerGradient} */ -cc.LayerGradient.create = function (start, end, v) { - return new cc.LayerGradient(start, end, v); +cc.LayerGradient.create = function (start, end, v, stops) { + return new cc.LayerGradient(start, end, v, stops); }; //LayerGradient - Getter Setter (function(){ @@ -537,6 +586,9 @@ cc.LayerGradient.create = function (start, end, v) { /** @expose */ proto.vector; cc.defineGetterSetter(proto, "vector", proto.getVector, proto.setVector); + /** @expose */ + proto.colorStops; + cc.defineGetterSetter(proto, "colorStops", proto.getColorStops, proto.setColorStops); })(); /** diff --git a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js index a7f3c6a24b..cf8ce7abfd 100644 --- a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js +++ b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js @@ -369,9 +369,18 @@ var locWidth = node._contentSize.width, locHeight = node._contentSize.height; wrapper.setCompositeOperation(this._blendFuncStr); wrapper.setGlobalAlpha(opacity); - var gradient = context.createLinearGradient(this._startPoint.x, this._startPoint.y, this._endPoint.x, this._endPoint.y); - gradient.addColorStop(0, this._startStopStr); - gradient.addColorStop(1, this._endStopStr); + var gradient = context.createLinearGradient(this._startPoint.x*scaleX, this._startPoint.y*scaleY, this._endPoint.x*scaleX, this._endPoint.y*scaleY); + + if(node._colorStops){ //Should always fall here now + for(var i=0; i < node._colorStops.length; i++) { + var stop = node._colorStops[i]; + gradient.addColorStop(stop.p, this._colorStopsStr[i]); + } + }else{ + gradient.addColorStop(0, this._startStopStr); + gradient.addColorStop(1, this._endStopStr); + } + wrapper.setFillStyle(gradient); wrapper.setTransform(this._worldTransform, scaleX, scaleY); @@ -430,5 +439,19 @@ + Math.round(locStartColor.b) + "," + startOpacity.toFixed(4) + ")"; this._endStopStr = "rgba(" + Math.round(locEndColor.r) + "," + Math.round(locEndColor.g) + "," + Math.round(locEndColor.b) + "," + endOpacity.toFixed(4) + ")"; + + if( node._colorStops){ + this._startOpacity = 0; + this._endOpacity = 0; + + this._colorStopsStr = []; + for(var i =0; i < node._colorStops.length; i++){ + var stopColor = node._colorStops[i].color; + var stopOpacity = stopColor.a/255; + this._colorStopsStr.push("rgba(" + Math.round(stopColor.r) + "," + Math.round(stopColor.g) + "," + + Math.round(stopColor.b) + "," + stopOpacity.toFixed(4) + ")"); + } + } + }; })(); \ No newline at end of file From 521235099fff435c7e7749f38ce1ef1f024fb4e2 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Thu, 26 Feb 2015 09:58:50 +0800 Subject: [PATCH 0002/1039] Fixed #2416: fixed a bug of cc.Sprite in setTextureRect --- cocos2d/core/labelttf/CCLabelTTF.js | 6 +++--- cocos2d/core/sprites/CCSprite.js | 10 +++++----- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/cocos2d/core/labelttf/CCLabelTTF.js b/cocos2d/core/labelttf/CCLabelTTF.js index 95b2e776fe..106e92bc19 100644 --- a/cocos2d/core/labelttf/CCLabelTTF.js +++ b/cocos2d/core/labelttf/CCLabelTTF.js @@ -642,7 +642,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ this._dimensions.width = width; this._dimensions.height = height; this._updateString(); - // Force udpate + // Force update this._setUpdateTextureDirty(); } }, @@ -654,7 +654,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ if (width != this._dimensions.width) { this._dimensions.width = width; this._updateString(); - // Force udpate + // Force update this._setUpdateTextureDirty(); } }, @@ -666,7 +666,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ if (height != this._dimensions.height) { this._dimensions.height = height; this._updateString(); - // Force udpate + // Force update this._setUpdateTextureDirty(); } }, diff --git a/cocos2d/core/sprites/CCSprite.js b/cocos2d/core/sprites/CCSprite.js index 876b5def45..7bcd41db64 100644 --- a/cocos2d/core/sprites/CCSprite.js +++ b/cocos2d/core/sprites/CCSprite.js @@ -759,14 +759,14 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ _t.setVertexRect(rect); _t._renderCmd._setTextureCoords(rect, needConvert); - var relativeOffset = _t._unflippedOffsetPositionFromCenter; + var relativeOffsetX = _t._unflippedOffsetPositionFromCenter.x, relativeOffsetY = _t._unflippedOffsetPositionFromCenter.y; if (_t._flippedX) - relativeOffset.x = -relativeOffset.x; + relativeOffsetX = -relativeOffsetX; if (_t._flippedY) - relativeOffset.y = -relativeOffset.y; + relativeOffsetY = -relativeOffsetY; var locRect = _t._rect; - _t._offsetPosition.x = relativeOffset.x + (_t._contentSize.width - locRect.width) / 2; - _t._offsetPosition.y = relativeOffset.y + (_t._contentSize.height - locRect.height) / 2; + _t._offsetPosition.x = relativeOffsetX + (_t._contentSize.width - locRect.width) / 2; + _t._offsetPosition.y = relativeOffsetY + (_t._contentSize.height - locRect.height) / 2; // rendering using batch node if (_t._batchNode) { From 9cdb4c03cf444f33105d384159692f48db502a4f Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 27 Feb 2015 11:20:24 +0800 Subject: [PATCH 0003/1039] update scheduler cocos2d/cocos2d-js#1316 --- cocos2d/core/CCDirector.js | 2 +- cocos2d/core/CCScheduler.js | 785 ++++++++++++------ cocos2d/core/base-nodes/CCNode.js | 75 +- .../armature/utils/CCDataReaderHelper.js | 2 +- 4 files changed, 617 insertions(+), 247 deletions(-) diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js index c4111ffdc3..ab18b55675 100644 --- a/cocos2d/core/CCDirector.js +++ b/cocos2d/core/CCDirector.js @@ -154,7 +154,7 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ this._scheduler = new cc.Scheduler(); //action manager this._actionManager = cc.ActionManager ? new cc.ActionManager() : null; - this._scheduler.scheduleUpdateForTarget(this._actionManager, cc.Scheduler.PRIORITY_SYSTEM, false); + this._scheduler.scheduleUpdate(this._actionManager, cc.Scheduler.PRIORITY_SYSTEM, false); this._eventAfterDraw = new cc.EventCustom(cc.Director.EVENT_AFTER_DRAW); this._eventAfterDraw.setUserData(this); diff --git a/cocos2d/core/CCScheduler.js b/cocos2d/core/CCScheduler.js index df1f7354cc..6bc4a72b0b 100644 --- a/cocos2d/core/CCScheduler.js +++ b/cocos2d/core/CCScheduler.js @@ -39,14 +39,16 @@ cc.PRIORITY_NON_SYSTEM = cc.PRIORITY_SYSTEM + 1; * @name cc.ListEntry * @param {cc.ListEntry} prev * @param {cc.ListEntry} next + * @param {function} callback * @param {cc.Class} target not retained (retained by hashUpdateEntry) * @param {Number} priority * @param {Boolean} paused * @param {Boolean} markedForDeletion selector will no longer be called and entry will be removed at end of the next tick */ -cc.ListEntry = function (prev, next, target, priority, paused, markedForDeletion) { +cc.ListEntry = function (prev, next, callback, target, priority, paused, markedForDeletion) { this.prev = prev; this.next = next; + this.callback = callback; this.target = target; this.priority = priority; this.paused = paused; @@ -60,12 +62,14 @@ cc.ListEntry = function (prev, next, target, priority, paused, markedForDeletion * @param {cc.ListEntry} list Which list does it belong to ? * @param {cc.ListEntry} entry entry in the list * @param {cc.Class} target hash key (retained) + * @param {function} callback * @param {Array} hh */ -cc.HashUpdateEntry = function (list, entry, target, hh) { +cc.HashUpdateEntry = function (list, entry, target, callback, hh) { this.list = list; this.entry = entry; this.target = target; + this.callback = callback; this.hh = hh; }; @@ -81,7 +85,7 @@ cc.HashUpdateEntry = function (list, entry, target, hh) { * @param {Boolean} paused * @param {Array} hh */ -cc.HashTimerEntry = function (timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused, hh) { +cc.HashTimerEntry = cc.hashSelectorEntry = function (timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused, hh) { var _t = this; _t.timers = timers; _t.target = target; @@ -98,17 +102,18 @@ cc.HashTimerEntry = function (timers, target, timerIndex, currentTimer, currentT * @extends cc.Class */ cc.Timer = cc.Class.extend(/** @lends cc.Timer# */{ - _interval:0.0, - _callback:null,//is called _callback before - - _target:null,//target of _callback + _scheduler: null, _elapsed:0.0, - _runForever:false, _useDelay:false, _timesExecuted:0, _repeat:0, //0 = once, 1 is 2 x executed _delay:0, + _interval:0.0, + + //_callback:null,//is called _callback before + //_target:null,//target of _callback + /** * @return {Number} returns interval of timer @@ -119,10 +124,30 @@ cc.Timer = cc.Class.extend(/** @lends cc.Timer# */{ */ setInterval : function(interval){this._interval = interval;}, + setupTimerWithInterval: function(seconds, repeat, delay){ + //todo checking here + this._elapsed = -1; + this._interval = seconds; + this._delay = delay; + this._useDelay = this._delay > 0 ? true : false; + this._repeat = repeat; + this._runForever = this._repeat == cc.REPEAT_FOREVER ? true : false; + }, + + //todo checking here + trigger: function(){ + return 0; + }, + + //todo checking here + cancel: function(){ + return 0; + }, + /** * @return {String|function} returns callback */ - getCallback : function(){return this._callback}, + //getCallback : function(){return this._callback}, /** @@ -135,23 +160,14 @@ cc.Timer = cc.Class.extend(/** @lends cc.Timer# */{ * @param {Number} [delay=0] delay */ ctor:function (target, callback, interval, repeat, delay) { - var self = this; - self._target = target; - self._callback = callback; - self._elapsed = -1; - self._interval = interval || 0; - self._delay = delay || 0; - self._useDelay = self._delay > 0; - self._repeat = (repeat == null) ? cc.REPEAT_FOREVER : repeat; - self._runForever = (self._repeat == cc.REPEAT_FOREVER); - }, - - _doCallback:function(){ - var self = this; - if (cc.isString(self._callback)) - self._target[self._callback](self._elapsed); - else // if (typeof(this._callback) == "function") { - self._callback.call(self._target, self._elapsed); + this._scheduler = null; + this._elapsed = -1; + this._runForever = false; + this._useDelay = false; + this._timesExecuted = 0; + this._repeat = 0; + this._delay = 0; + this._interval = 0; }, /** @@ -159,47 +175,119 @@ cc.Timer = cc.Class.extend(/** @lends cc.Timer# */{ * @param {Number} dt delta time */ update:function (dt) { - var self = this; - if (self._elapsed == -1) { - self._elapsed = 0; - self._timesExecuted = 0; + if (this._elapsed == -1) { + this._elapsed = 0; + this._timesExecuted = 0; } else { - var locTarget = self._target, locCallback = self._callback; - self._elapsed += dt;//standard timer usage - if (self._runForever && !self._useDelay) { - if (self._elapsed >= self._interval) { - if (locTarget && locCallback) - self._doCallback(); - self._elapsed = 0; + this._elapsed += dt; + if (this._runForever && !this._useDelay) {//standard timer usage + if (this._elapsed >= this._interval) { + this.trigger(); + this._elapsed = 0; } - } else { - //advanced usage - if (self._useDelay) { - if (self._elapsed >= self._delay) { - if (locTarget && locCallback) - self._doCallback(); - - self._elapsed = self._elapsed - self._delay; - self._timesExecuted += 1; - self._useDelay = false; + } else {//advanced usage + if (this._useDelay) { + if (this._elapsed >= this._delay) { + this.trigger(); + + this._elapsed -= this._delay; + this._timesExecuted += 1; + this._useDelay = false; } } else { - if (self._elapsed >= self._interval) { - if (locTarget && locCallback) - self._doCallback(); + if (this._elapsed >= this._interval) { + this.trigger(); - self._elapsed = 0; - self._timesExecuted += 1; + this._elapsed = 0; + this._timesExecuted += 1; } } - if (self._timesExecuted > self._repeat) - cc.director.getScheduler().unscheduleCallbackForTarget(locTarget, locCallback); + if (!this._runForever && this._timesExecuted > this._repeat) + this.cancel(); } } } }); +cc.TimerTargetSelector = cc.Timer.extend({ + + _target: null, + _selector: null, + + ctor: function(){ + this._target = null; + this._selector = null; + }, + + initWithSelector: function(scheduler, selector, target, seconds, repeat, delay){ + this._scheduler = scheduler; + this._target = target; + this._selector = selector; + this.setupTimerWithInterval(seconds, repeat, delay); + return true; + }, + + getSelector: function(){ + return this._selector; + }, + + trigger: function(){ + //override + if (this._target && this._selector){ + this._target.call(this._selector, this._elapsed); + } + }, + + cancel: function(){ + //override + this._scheduler.unschedule(this._selector, this._target); + } + +}); + +cc.TimerTargetCallback = cc.Timer.extend({ + + _target: null, + _callback: null, + _key: null, + + ctor: function(){ + this._target = null; + this._callback = null; + }, + + initWithCallback: function(scheduler, callback, target, key, seconds, repeat, delay){ + //todo checking here + this._scheduler = scheduler; + this._target = target; + this._callback = callback; + this._key = key; + this.setupTimerWithInterval(seconds, repeat, delay); + return true; + }, + + getCallback: function(){ + return this._callback; + }, + + getKey: function(){ + return this._key; + }, + + trigger: function(){ + //override + if(this._callback) + this._callback.call(this._target, this._elapsed); + }, + + cancel: function(){ + //override + this._scheduler.unschedule(this._key, this._target); + } + +}); + /** *

* Scheduler is responsible of triggering the scheduled callbacks.
@@ -221,38 +309,79 @@ cc.Timer = cc.Class.extend(/** @lends cc.Timer# */{ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ _timeScale:1.0, - _updates : null, //_updates[0] list of priority < 0, _updates[1] list of priority == 0, _updates[2] list of priority > 0, + //_updates : null, //_updates[0] list of priority < 0, _updates[1] list of priority == 0, _updates[2] list of priority > 0, + _updatesNegList: null, + _updates0List: null, + _updatesPosList: null, _hashForUpdates:null, // hash used to fetch quickly the list entries for pause,delete,etc - _arrayForUpdates:null, _hashForTimers:null, //Used for "selectors with interval" - _arrayForTimes:null, - _currentTarget:null, _currentTargetSalvaged:false, _updateHashLocked:false, //If true unschedule will not remove anything from a hash. Elements will only be marked for deletion. + //_arrayForTimes:null, + //_arrayForUpdates:null, + ctor:function () { var self = this; self._timeScale = 1.0; - self._updates = [[], [], []]; + //self._updates = [[], [], []]; + this._updatesNegList = []; + this._updates0List = []; + this._updatesPosList = []; self._hashForUpdates = {}; - self._arrayForUpdates = []; - self._hashForTimers = {}; - self._arrayForTimers = []; - self._currentTarget = null; self._currentTargetSalvaged = false; self._updateHashLocked = false; + + //self._arrayForUpdates = []; + //self._arrayForTimers = []; + }, //-----------------------private method---------------------- + + _schedulePerFrame: function(callback, target, priority, paused){ + //todo + var hashElement = this._hashForUpdates[target.__instanceId]; + if (hashElement){ + // check if priority has changed + if (hashElement.list.priority != priority){ + if (this._updateHashLocked){ + cc.log("warning: you CANNOT change update priority in scheduled function"); + hashElement.entry.markedForDeletion = false; + hashElement.entry.paused = paused; + return; + }else{ + // will be added again outside if (hashElement). + this.unscheduleUpdate(target); + } + }else{ + hashElement.entry.markedForDeletion = false; + hashElement.entry.paused = paused; + return; + } + } + + // most of the updates are going to be 0, that's way there + // is an special list for updates with priority 0 + if (priority == 0){ + this._appendIn(this._updates0List, callback, target, paused); + }else if (priority < 0){ + this._priorityIn(this._updatesNegList, callback, target, priority, paused); + }else{ + // priority > 0 + this._priorityIn(this._updatesPosList, callback, target, priority, paused); + } + }, + _removeHashElement:function (element) { delete this._hashForTimers[element.target.__instanceId]; - cc.arrayRemoveObject(this._arrayForTimers, element); + //cc.arrayRemoveObject(this._arrayForTimers, element); element.Timer = null; element.target = null; element = null; @@ -265,7 +394,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ cc.arrayRemoveObject(element.list, element.entry); delete self._hashForUpdates[element.target.__instanceId]; - cc.arrayRemoveObject(self._arrayForUpdates, element); + cc.arrayRemoveObject(self._hashForUpdates, element); element.entry = null; //hash entry @@ -273,8 +402,9 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ } }, - _priorityIn:function (ppList, target, priority, paused) { - var self = this, listElement = new cc.ListEntry(null, null, target, priority, paused, false); + _priorityIn:function (ppList, callback, target, priority, paused) { + var self = this, + listElement = new cc.ListEntry(null, null, callback, target, priority, paused, false); // empey list ? if (!ppList) { @@ -293,19 +423,17 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ //update hash entry for quick access var hashElement = new cc.HashUpdateEntry(ppList, listElement, target, null); - self._arrayForUpdates.push(hashElement); self._hashForUpdates[target.__instanceId] = hashElement; return ppList; }, - _appendIn:function (ppList, target, paused) { - var self = this, listElement = new cc.ListEntry(null, null, target, 0, paused, false); + _appendIn:function (ppList, callback, target, paused) { + var self = this, listElement = new cc.ListEntry(null, null, callback, target, 0, paused, false); ppList.push(listElement); //update hash entry for quicker access - var hashElement = new cc.HashUpdateEntry(ppList, listElement, target, null); - self._arrayForUpdates.push(hashElement); + var hashElement = new cc.HashUpdateEntry(ppList, listElement, target, null, null); self._hashForUpdates[target.__instanceId] = hashElement; }, @@ -337,33 +465,40 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ * @param {Number} dt delta time */ update:function (dt) { - var self = this; - var locUpdates = self._updates, locArrayForTimers = self._arrayForTimers; - var tmpEntry, elt, i, li; - self._updateHashLocked = true; - - if (this._timeScale != 1.0) { + this._updateHashLocked = true; + if(this._timeScale != 1) dt *= this._timeScale; + + var i, list, len, entry; + + for(i=0,list=this._updatesNegList, len = list.length; i= 0; i++){ - var update = self._updates[i]; - for(var j = 0, lj = update.length; j < lj; j++){ - tmpEntry = update[j]; - if ((!tmpEntry.paused) && (!tmpEntry.markedForDeletion)) tmpEntry.target.update(dt); - } + for(i=0, list=this._updates0List, len=list.length; i * delay is the amount of time the action will wait before it'll start
*

+ * @deprecated since v3.4 please use .schedule * @param {cc.Class} target * @param {function} callback_fn * @param {Number} interval @@ -411,109 +566,111 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ * //register a schedule to scheduler * cc.director.getScheduler().scheduleCallbackForTarget(this, function, interval, repeat, delay, !this._isRunning ); */ - scheduleCallbackForTarget:function (target, callback_fn, interval, repeat, delay, paused) { + scheduleCallbackForTarget: function(target, callback_fn, interval, repeat, delay, paused){ + cc.log("scheduleCallbackForTarget is deprecated. Please use schedule."); + this.schedule(callback_fn, target, interval, repeat, delay, paused, target.__instanceId + ""); + }, - cc.assert(callback_fn, cc._LogInfos.Scheduler_scheduleCallbackForTarget_2); + schedule: function(callback, target, interval, repeat, delay, paused, key){ + var isSelector = false; + if(typeof callback != "function"){ + var selector = callback; + isSelector = true; + } - cc.assert(target, cc._LogInfos.Scheduler_scheduleCallbackForTarget_3); + if(isSelector === false){ + //callback, target, interval, repeat, delay, paused, key + //callback, target, interval, paused, key + if(arguments.length === 5){ + key = delay; + paused = repeat; + delay = 0; + repeat = cc.REPEAT_FOREVER; + } + }else{ + //selector, target, interval, repeat, delay, paused + //selector, target, interval, paused + if(arguments.length == 4){ + paused = repeat; + repeat = cc.REPEAT_FOREVER; + delay = 0; + } + } - // default arguments - interval = interval || 0; - repeat = (repeat == null) ? cc.REPEAT_FOREVER : repeat; - delay = delay || 0; - paused = paused || false; + cc.assert(target, cc._LogInfos.Scheduler_scheduleCallbackForTarget_3); + if(isSelector === false) + cc.assert(key, "key should not be empty!"); - var self = this, timer; - var element = self._hashForTimers[target.__instanceId]; + var element = this._hashForTimers[target.__instanceId]; - if (!element) { + if(!element){ // Is this the 1st element ? Then set the pause level to all the callback_fns of this target element = new cc.HashTimerEntry(null, target, 0, null, null, paused, null); - self._arrayForTimers.push(element); - self._hashForTimers[target.__instanceId] = element; + //this._arrayForTimers.push(element); + this._hashForTimers[target.__instanceId] = element; + }else{ + cc.assert(element.paused == paused, ""); } + var timer; if (element.timers == null) { element.timers = []; - } else { + } else if(isSelector === false) { for (var i = 0; i < element.timers.length; i++) { timer = element.timers[i]; - if (callback_fn == timer._callback) { + if (callback == timer._callback) { cc.log(cc._LogInfos.Scheduler_scheduleCallbackForTarget, timer.getInterval().toFixed(4), interval.toFixed(4)); timer._interval = interval; return; } } + }else{ + for (var i = 0; i < element.timers.length; ++i){ + timer =element.timers[i]; + if (timer && selector == timer.getSelector()){ + cc.log("CCScheduler#scheduleSelector. Selector already scheduled. Updating interval from: %.4f to %.4f", timer.getInterval(), interval); + timer.setInterval(interval); + return; + } + } + //ccArrayEnsureExtraCapacity(element->timers, 1); } - timer = new cc.Timer(target, callback_fn, interval, repeat, delay); - element.timers.push(timer); - }, - - /** - *

- * Schedules the 'update' callback_fn for a given target with a given priority.
- * The 'update' callback_fn will be called every frame.
- * The lower the priority, the earlier it is called. - *

- * @param {cc.Class} target - * @param {Number} priority - * @param {Boolean} paused - * @example - * //register this object to scheduler - * cc.director.getScheduler().scheduleUpdateForTarget(this, priority, !this._isRunning ); - */ - scheduleUpdateForTarget:function (target, priority, paused) { - if(target === null) - return; - var self = this, locUpdates = self._updates; - var hashElement = self._hashForUpdates[target.__instanceId]; - - if (hashElement) { - // TODO: check if priority has changed! - hashElement.entry.markedForDeletion = false; - return; + if(isSelector === false){ + timer = new cc.TimerTargetCallback(); + timer.initWithCallback(this, callback, target, key, interval, repeat, delay); + element.timers.push(timer); + }else{ + timer = new cc.TimerTargetSelector(); + timer.initWithSelector(this, selector, target, interval, repeat, delay); + element.timers.push(timer); } + }, - // most of the updates are going to be 0, that's way there - // is an special list for updates with priority 0 - if (priority == 0) { - self._appendIn(locUpdates[1], target, paused); - } else if (priority < 0) { - locUpdates[0] = self._priorityIn(locUpdates[0], target, priority, paused); - } else { - // priority > 0 - locUpdates[2] = self._priorityIn(locUpdates[2], target, priority, paused); - } + scheduleUpdate: function(target, priority, paused){ + this._schedulePerFrame(function(dt){ + target.update(dt); + }, target, priority, paused); }, - /** - *

- * Unschedule a callback function for a given target.
- * If you want to unschedule the "update", use unscheudleUpdateForTarget. - *

- * @param {cc.Class} target - * @param {function} callback_fn - * @example - * //unschedule a callback of target - * cc.director.getScheduler().unscheduleCallbackForTarget(function, this); - */ - unscheduleCallbackForTarget:function (target, callback_fn) { + unschedule: function(key, target){ + //key, target + //selector, target + // explicity handle nil arguments when removing an object - if ((target == null) || (callback_fn == null)) { + if (!target || !key) return; - } var self = this, element = self._hashForTimers[target.__instanceId]; if (element) { var timers = element.timers; for(var i = 0, li = timers.length; i < li; i++){ var timer = timers[i]; - if (callback_fn == timer._callback) { + if (key == timer.getKey()) { if ((timer == element.currentTimer) && (!element.currentTimerSalvaged)) { element.currentTimerSalvaged = true; } - timers.splice(i, 1) + timers.splice(i, 1); //update timerIndex in case we are in tick;, looping over the actions if (element.timerIndex >= i) { element.timerIndex--; @@ -532,89 +689,122 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ } }, - /** - * Unschedules the update callback function for a given target - * @param {cc.Class} target - * @example - * //unschedules the "update" method. - * cc.director.getScheduler().unscheduleUpdateForTarget(this); - */ - unscheduleUpdateForTarget:function (target) { - if (target == null) { + unscheduleUpdate: function(target){ + if (target == null) return; - } - var self = this, element = self._hashForUpdates[target.__instanceId]; - if (element != null) { - if (self._updateHashLocked) { + var element = this._hashForUpdates[target.__instanceId]; + + if (element){ + if (this._updateHashLocked){ element.entry.markedForDeletion = true; - } else { - self._removeUpdateFromHash(element.entry); + }else{ + this._removeUpdateFromHash(element.entry); } } }, - /** - * Unschedules all function callbacks for a given target. This also includes the "update" callback function. - * @param {cc.Class} target - */ - unscheduleAllCallbacksForTarget:function (target) { - //explicit NULL handling - if (target == null) { + unscheduleAllForTarget: function(target){ + // explicit nullptr handling + if (target == null){ return; } - var self = this, element = self._hashForTimers[target.__instanceId]; - if (element) { - var timers = element.timers; - if ((!element.currentTimerSalvaged) && (timers.indexOf(element.currentTimer) >= 0)) { + // Custom Selectors + var element = this._hashForTimers[target.__instanceId]; + + if (element){ + if (element.timers.indexOf(element.currentTimer) > -1 + && (! element.currentTimerSalvaged)){ element.currentTimerSalvaged = true; } - timers.length = 0; + // ccArrayRemoveAllObjects(element.timers); + element.timers.length = 0; - if (self._currentTarget == element) { - self._currentTargetSalvaged = true; - } else { - self._removeHashElement(element); + if (this._currentTarget == element){ + this._currentTargetSalvaged = true; + }else{ + this._removeHashElement(element); } } - // update callback - self.unscheduleUpdateForTarget(target); + + // update selector + this.unscheduleUpdate(target); }, - /** - *

- * Unschedules all function callbacks from all targets.
- * You should NEVER call this method, unless you know what you are doing. - *

- */ - unscheduleAllCallbacks:function () { - this.unscheduleAllCallbacksWithMinPriority(cc.Scheduler.PRIORITY_SYSTEM); + unscheduleAll: function(){ + this.unscheduleAllWithMinPriority(cc.Scheduler.PRIORITY_SYSTEM); }, - /** - *

- * Unschedules all function callbacks from all targets with a minimum priority.
- * You should only call this with kCCPriorityNonSystemMin or higher. - *

- * @param {Number} minPriority - */ - unscheduleAllCallbacksWithMinPriority:function (minPriority) { + unscheduleAllWithMinPriority: function(minPriority){ // Custom Selectors - var self = this, locArrayForTimers = self._arrayForTimers, locUpdates = self._updates; - for(var i = 0, li = locArrayForTimers.length; i < li; i++){ - // element may be removed in unscheduleAllCallbacksForTarget - self.unscheduleAllCallbacksForTarget(locArrayForTimers[i].target); + var element; + for(var p in this._hashForTimers){ + element = this._hashForTimers[p]; + this.unscheduleAllForTarget(element.target); } - for(var i = 2; i >= 0; i--){ - if((i == 1 && minPriority > 0) || (i == 0 && minPriority >= 0)) continue; - var updates = locUpdates[i]; - for(var j = 0, lj = updates.length; j < lj; j++){ - self.unscheduleUpdateForTarget(updates[j].target); + + // Updates selectors + var entry, i; + if(minPriority < 0){ + for(i=0; i= minPriority){ + this.unscheduleUpdate(entry.target); + } + } + } + } + + if(minPriority <= 0){ + for(i=0; i= minPriority) + { + this.unscheduleUpdate(entry.target); + } } } }, + isScheduled: function(key, target){ + //key, target + //selector, target + cc.assert(key, "Argument key must not be empty"); + cc.assert(target, "Argument target must be non-nullptr"); + + var element = this._hashForUpdates[target.__instanceId]; + + if (!element){ + return false; + } + + if (element.timers == null){ + return false; + }else{ + //todo checking here timers.length + var timers = element.timers; + for (var i = 0; i < timers.length; ++i){ + var timer = timers[i]; + + if (key == timer.getKey()){ + return true; + } + } + return false; + } + }, + /** *

* Pause all selectors from all targets.
@@ -733,7 +923,138 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ if (element) { return element.paused; } + var elementUpdate = this._hashForUpdates[target.__instanceId]; + if (elementUpdate) { + return elementUpdate.entry.paused; + } return false; + }, + + /** + *

+ * Schedules the 'update' callback_fn for a given target with a given priority.
+ * The 'update' callback_fn will be called every frame.
+ * The lower the priority, the earlier it is called. + *

+ * @deprecated since v3.4 please use .scheduleUpdate + * @param {cc.Class} target + * @param {Number} priority + * @param {Boolean} paused + * @example + * //register this object to scheduler + * cc.director.getScheduler().scheduleUpdateForTarget(this, priority, !this._isRunning ); + */ + scheduleUpdateForTarget: function(target, priority, paused){ + cc.log("scheduleUpdateForTarget is deprecated. Please use scheduleUpdate."); + this.scheduleUpdate(target, priority, paused); + }, + + /** + *

+ * Unschedule a callback function for a given target.
+ * If you want to unschedule the "update", use unscheudleUpdateForTarget. + *

+ * @deprecated since v3.4 please use .unschedule + * @param {cc.Class} target + * @param {function} callback callback[Function] or key[String] + * @example + * //unschedule a callback of target + * cc.director.getScheduler().unscheduleCallbackForTarget(function, this); + */ + unscheduleCallbackForTarget:function (target, callback) { + cc.log("unscheduleCallbackForTarget is deprecated. Please use unschedule."); + //this.unschedule(callback, target); + // explicity handle nil arguments when removing an object + if ((target == null) || (callback == null)) { + return; + } + + var self = this, element = self._hashForTimers[target.__instanceId]; + if (element) { + var timers = element.timers; + for(var i = 0, li = timers.length; i < li; i++){ + var timer = timers[i]; + if (callback == timer._callback) { + if ((timer == element.currentTimer) && (!element.currentTimerSalvaged)) { + element.currentTimerSalvaged = true; + } + timers.splice(i, 1); + //update timerIndex in case we are in tick;, looping over the actions + if (element.timerIndex >= i) { + element.timerIndex--; + } + + if (timers.length == 0) { + if (self._currentTarget == element) { + self._currentTargetSalvaged = true; + } else { + self._removeHashElement(element); + } + } + return; + } + } + } + }, + + /** + * Unschedules the update callback function for a given target + * @param {cc.Class} target + * @deprecated since v3.4 please use .unschedule + * @example + * //unschedules the "update" method. + * cc.director.getScheduler().unscheduleUpdateForTarget(this); + */ + unscheduleUpdateForTarget:function (target) { + cc.log("unscheduleUpdateForTarget is deprecated. Please use unschedule."); + //this.unschedule(callback, target); + if (target == null) { + return; + } + + var self = this, element = self._hashForUpdates[target.__instanceId]; + if (element != null) { + if (self._updateHashLocked) { + element.entry.markedForDeletion = true; + } else { + self._removeUpdateFromHash(element.entry); + } + } + }, + + /** + * Unschedules all function callbacks for a given target. This also includes the "update" callback function. + * @deprecated since v3.4 please use .unscheduleAll + * @param {cc.Class} target + */ + unscheduleAllCallbacksForTarget: function(target){ + cc.log("unscheduleAllCallbacksForTarget is deprecated. Please use unscheduleAll."); + this.unscheduleAll(); + }, + + /** + *

+ * Unschedules all function callbacks from all targets.
+ * You should NEVER call this method, unless you know what you are doing. + *

+ * @deprecated since v3.4 please use .unscheduleAllWithMinPriority + */ + unscheduleAllCallbacks: function(){ + cc.log("unscheduleAllCallbacks is deprecated. Please use unscheduleAllWithMinPriority."); + this.unscheduleAllWithMinPriority(cc.Scheduler.PRIORITY_SYSTEM); + }, + + /** + *

+ * Unschedules all function callbacks from all targets with a minimum priority.
+ * You should only call this with kCCPriorityNonSystemMin or higher. + *

+ * @deprecated since v3.4 please use .unscheduleAllWithMinPriority + * @param {Number} minPriority + */ + unscheduleAllCallbacksWithMinPriority:function (minPriority) { + cc.log("unscheduleAllCallbacksWithMinPriority is deprecated. Please use unscheduleAllWithMinPriority."); + this.unscheduleAllWithMinPriority(minPriority); } }); /** diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index a82ded43a2..f91b0097f1 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -1652,7 +1652,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @param {Number} priority */ scheduleUpdateWithPriority: function (priority) { - this.scheduler.scheduleUpdateForTarget(this, priority, !this._running); + this.scheduler.scheduleUpdate(this, priority, !this._running); }, /** @@ -1661,39 +1661,86 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @see cc.Node#scheduleUpdate */ unscheduleUpdate: function () { - this.scheduler.unscheduleUpdateForTarget(this); + this.scheduler.unschedule(this.__instanceId, this); }, /** *

Schedules a custom selector.
* If the selector is already scheduled, then the interval parameter will be updated without scheduling it again.

* @function - * @param {function} callback_fn A function wrapped as a selector + * @param {function} callback A function wrapped as a selector * @param {Number} interval Tick interval in seconds. 0 means tick every frame. If interval = 0, it's recommended to use scheduleUpdate() instead. * @param {Number} repeat The selector will be executed (repeat + 1) times, you can use kCCRepeatForever for tick infinitely. * @param {Number} delay The amount of time that the first tick will wait before execution. - */ - schedule: function (callback_fn, interval, repeat, delay) { - interval = interval || 0; + * @param {String} key The only string identifying the callback + */ + schedule: function (callback, interval, repeat, delay, key) { + var len = arguments.length; + if(typeof callback === "function"){ + //callback, interval, repeat, delay, key + if(len == 1){ + //callback + interval = 0; + repeat = cc.REPEAT_FOREVER; + delay = 0; + key = this.__instanceId; + }else if(len == 2){ + if(typeof interval === "number"){ + //callback, interval + repeat = cc.REPEAT_FOREVER; + delay = 0; + key = this.__instanceId; + }else{ + //callback, key + key = interval; + interval = 0; + repeat = cc.REPEAT_FOREVER; + delay = 0; + } + }else if(len === 3){ + //callback, interval, key + key = repeat; + repeat = cc.REPEAT_FOREVER; + delay = 0; + }else if(len === 4){ + key = this.__instanceId; + } + }else{ + //selector + //selector, interval + //selector, interval, repeat, delay + if(len == 1){ + interval = 0; + repeat = cc.REPEAT_FOREVER; + delay = 0; + }else if(len == 2){ + repeat = cc.REPEAT_FOREVER; + delay = 0; + } + } - cc.assert(callback_fn, cc._LogInfos.Node_schedule); + cc.assert(callback, cc._LogInfos.Node_schedule); cc.assert(interval >= 0, cc._LogInfos.Node_schedule_2); + interval = interval || 0; repeat = (repeat == null) ? cc.REPEAT_FOREVER : repeat; delay = delay || 0; - this.scheduler.scheduleCallbackForTarget(this, callback_fn, interval, repeat, delay, !this._running); + this.scheduler.schedule(callback, this, interval, repeat, delay, !this._running, key); }, /** * Schedules a callback function that runs only once, with a delay of 0 or larger * @function * @see cc.Node#schedule - * @param {function} callback_fn A function wrapped as a selector + * @param {function} callback A function wrapped as a selector * @param {Number} delay The amount of time that the first tick will wait before execution. + * @param {String} key The only string identifying the callback */ - scheduleOnce: function (callback_fn, delay) { - this.schedule(callback_fn, 0.0, 0, delay); + scheduleOnce: function (callback, delay, key) { + //selector, delay + //callback, delay, key + this.schedule(callback, 0, 0, delay, key); }, /** @@ -1703,10 +1750,12 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @param {function} callback_fn A function wrapped as a selector */ unschedule: function (callback_fn) { + //key + //selector if (!callback_fn) return; - this.scheduler.unscheduleCallbackForTarget(this, callback_fn); + this.scheduler.unschedule(this.__instanceId, callback_fn); }, /** @@ -1715,7 +1764,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @function */ unscheduleAllCallbacks: function () { - this.scheduler.unscheduleAllCallbacksForTarget(this); + this.scheduler.unscheduleAllForTarget(this); }, /** diff --git a/extensions/cocostudio/armature/utils/CCDataReaderHelper.js b/extensions/cocostudio/armature/utils/CCDataReaderHelper.js index 1068296453..bffb430d5d 100644 --- a/extensions/cocostudio/armature/utils/CCDataReaderHelper.js +++ b/extensions/cocostudio/armature/utils/CCDataReaderHelper.js @@ -233,7 +233,7 @@ ccs.dataReaderHelper = /** @lends ccs.dataReaderHelper# */{ self._asyncRefCount--; self._asyncCallBack(selector,target, (self._asyncRefTotalCount - self._asyncRefCount) / self._asyncRefTotalCount); }; - cc.director.getScheduler().scheduleCallbackForTarget(this, fun, 0.1, false); + cc.director.getScheduler().schedule(fun, this, 0.1, false, 0, false, "armatrueDataHelper"); }, /** From 801f992c8c9f440be7a1257d79a8c5680a744df6 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Fri, 27 Feb 2015 13:39:07 +0800 Subject: [PATCH 0004/1039] Issue #2699: fix the bug of sprite about premultiplied. --- CCBoot.js | 3 ++- cocos2d/core/platform/CCTypesWebGL.js | 2 +- cocos2d/core/textures/TexturesWebGL.js | 1 + template/project.json | 4 ++-- template/src/myApp.js | 11 +++++++++++ template/src/resource.js | 1 + 6 files changed, 18 insertions(+), 4 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index 11dcd5661b..6d52bd02e6 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -1854,7 +1854,8 @@ cc._setup = function (el, width, height) { 'stencil': true, 'preserveDrawingBuffer': true, 'antialias': !cc.sys.isMobile, - 'alpha': false}); + 'alpha': false + }); if (cc._renderContext) { win.gl = cc._renderContext; // global variable declared in CCMacro.js cc._drawingUtil = new cc.DrawingPrimitiveWebGL(cc._renderContext); diff --git a/cocos2d/core/platform/CCTypesWebGL.js b/cocos2d/core/platform/CCTypesWebGL.js index e9e0151da6..643b973aa1 100644 --- a/cocos2d/core/platform/CCTypesWebGL.js +++ b/cocos2d/core/platform/CCTypesWebGL.js @@ -561,7 +561,7 @@ cc._tmp.WebGLColor = function () { //redefine cc.V2F_C4B_T2F /** * @class cc.V2F_C4B_T2F - * @param {new cc.Vertex2F} vertices + * @param {cc.Vertex2F} vertices * @param {cc.color} colors * @param {cc.Tex2F} texCoords * @param {Array} arrayBuffer diff --git a/cocos2d/core/textures/TexturesWebGL.js b/cocos2d/core/textures/TexturesWebGL.js index d26cbe5a57..a62de74fff 100644 --- a/cocos2d/core/textures/TexturesWebGL.js +++ b/cocos2d/core/textures/TexturesWebGL.js @@ -462,6 +462,7 @@ cc._tmp.WebGLTexture2D = function () { cc.glBindTexture2D(self); gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4); + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); // Specify OpenGL texture image gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, self._htmlElementObj); diff --git a/template/project.json b/template/project.json index 6c2c93bd3d..d1a00e8fdd 100644 --- a/template/project.json +++ b/template/project.json @@ -1,7 +1,7 @@ { "debugMode" : 1, - "noCache": true, - "showFPS" : true, + "noCache": false, + "showFPS" : false, "frameRate" : 60, "id" : "gameCanvas", "renderMode" : 0, diff --git a/template/src/myApp.js b/template/src/myApp.js index f91b7c40af..b4258ed20a 100644 --- a/template/src/myApp.js +++ b/template/src/myApp.js @@ -44,6 +44,17 @@ var MyLayer = cc.Layer.extend({ this.sprite.setPosition(size.width / 2, size.height / 2); this.sprite.setScale(size.height / this.sprite.getContentSize().height); this.addChild(this.sprite, 0); + + var root = new cc.Node(); + var body = new cc.Sprite("cut_the_hope1.png", cc.rect(827, 775, 143, 134)); + var leg = new cc.Sprite("cut_the_hope1.png", cc.rect(934, 248, 46, 51)); + //leg.setBlendFunc(cc.BlendFunc.ALPHA_PREMULTIPLIED); + + root.addChild(body); + root.addChild(leg); + this.addChild(root); + root.setScale(3); + root.setPosition(size.width/2, size.height/2); } }); diff --git a/template/src/resource.js b/template/src/resource.js index 94284083d1..a70fc7f61b 100644 --- a/template/src/resource.js +++ b/template/src/resource.js @@ -5,6 +5,7 @@ var s_CloseSelected = "CloseSelected.png"; var g_resources = [ //image s_HelloWorld, + "cut_the_hope1.png", s_CloseNormal, s_CloseSelected From cb1fbaf46f6b02b61ec6e885136229ba434478f6 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 27 Feb 2015 14:07:20 +0800 Subject: [PATCH 0005/1039] update scheduler cocos2d/cocos2d-js#1316 --- cocos2d/core/base-nodes/CCNode.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index f91b0097f1..b9ea1c7502 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -1155,7 +1155,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ */ setScheduler: function (scheduler) { if (this._scheduler != scheduler) { - this.unscheduleAllCallbacks(); + this.unscheduleAllWithMinPriority(); this._scheduler = scheduler; } }, @@ -1755,7 +1755,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ if (!callback_fn) return; - this.scheduler.unschedule(this.__instanceId, callback_fn); + this.scheduler.unschedule(this.__instanceId, this, callback_fn); }, /** From 5987cbf8652656331260b1ca43aa89a742d64a42 Mon Sep 17 00:00:00 2001 From: IShm Date: Sat, 28 Feb 2015 01:00:42 +0200 Subject: [PATCH 0006/1039] use fullscreenElement for determining on/off fullscreen mode instead of fullscreenEnabled --- cocos2d/core/platform/CCScreen.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/platform/CCScreen.js b/cocos2d/core/platform/CCScreen.js index 130ebfbafb..c33566b5d4 100644 --- a/cocos2d/core/platform/CCScreen.js +++ b/cocos2d/core/platform/CCScreen.js @@ -92,7 +92,7 @@ cc.screen = /** @lends cc.screen# */{ } } - this._supportsFullScreen = (this._fn.requestFullscreen != undefined); + this._supportsFullScreen = (this._fn.requestFullscreen != undefined); this._touchEvent = ('ontouchstart' in window) ? 'touchstart' : 'mousedown'; }, @@ -101,7 +101,7 @@ cc.screen = /** @lends cc.screen# */{ * @returns {Boolean} */ fullScreen: function() { - return this._supportsFullScreen && document[ this._fn.fullscreenEnabled ]; + return this._supportsFullScreen && document[this._fn.fullscreenElement]; }, /** From 3eeeae290e4c8e93f9bc582035c7913cb4867cf7 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Sat, 28 Feb 2015 10:00:39 +0800 Subject: [PATCH 0007/1039] Issue #2693: implements Gradient color stops --- cocos2d/core/layers/CCLayer.js | 59 ++++++++++++++----- cocos2d/core/layers/CCLayerCanvasRenderCmd.js | 2 +- template/project.json | 4 +- template/src/myApp.js | 10 ++++ 4 files changed, 56 insertions(+), 19 deletions(-) diff --git a/cocos2d/core/layers/CCLayer.js b/cocos2d/core/layers/CCLayer.js index a072e282a3..a6b2cf7f4e 100644 --- a/cocos2d/core/layers/CCLayer.js +++ b/cocos2d/core/layers/CCLayer.js @@ -341,19 +341,20 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{ * */ ctor: function (start, end, v, stops) { - var _t = this; - cc.LayerColor.prototype.ctor.call(_t); - _t._endColor = cc.color(0, 0, 0, 255); - _t._alongVector = cc.p(0, -1); - _t._startOpacity = 255; - _t._endOpacity = 255; - - if(stops && stops instanceof Array) - _t._colorStops = stops; - else - _t._colorStops = [{p:0, color: start}, {p:1, color: end}]; + cc.LayerColor.prototype.ctor.call(this); + this._endColor = cc.color(0, 0, 0, 255); + this._alongVector = cc.p(0, -1); + this._startOpacity = 255; + this._endOpacity = 255; + + if(stops && stops instanceof Array){ + this._colorStops = stops; + stops.splice(0, 0, {p:0, color: start}); + stops.push({p:1, color: end}); + } else + this._colorStops = [{p:0, color: start}, {p:1, color: end}]; - cc.LayerGradient.prototype.init.call(_t, start, end, v, stops); + cc.LayerGradient.prototype.init.call(this, start, end, v, stops); }, /** @@ -411,7 +412,7 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{ * @return {cc.Color} */ getStartColor: function () { - return this._realColor; + return cc.color(this._realColor); }, /** @@ -424,6 +425,14 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{ */ setStartColor: function (color) { this.color = color; + //update the color stops + var stops = this._colorStops; + if(stops && stops.length > 0){ + var selColor = stops[0].color; + selColor.r = color.r; + selColor.g = color.g; + selColor.b = color.b; + } }, /** @@ -435,7 +444,18 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{ * //set the ending gradient to red */ setEndColor: function (color) { - this._endColor = color; + var locColor = this._endColor; + locColor.r = color.r; + locColor.g = color.g; + locColor.b = color.b; + //update the color stops + var stops = this._colorStops; + if(stops && stops.length > 0){ + var selColor = stops[stops.length -1].color; + selColor.r = color.r; + selColor.g = color.g; + selColor.b = color.b; + } this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty); }, @@ -444,7 +464,7 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{ * @return {cc.Color} */ getEndColor: function () { - return this._endColor; + return cc.color(this._endColor); }, /** @@ -453,6 +473,10 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{ */ setStartOpacity: function (o) { this._startOpacity = o; + //update the color stops + var stops = this._colorStops; + if(stops && stops.length > 0) + stops[0].color.a = o; this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.opacityDirty); }, @@ -470,6 +494,9 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{ */ setEndOpacity: function (o) { this._endOpacity = o; + var stops = this._colorStops; + if(stops && stops.length > 0) + stops[stops.length -1].color.a = o; this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.opacityDirty); }, @@ -541,8 +568,8 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{ * */ setColorStops: function(colorStops){ - this._colorStops = colorStops; + //todo need update the start color and end color this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty|cc.Node._dirtyFlags.opacityDirty|cc.Node._dirtyFlags.gradientDirty); }, diff --git a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js index afbe414842..e01fc07def 100644 --- a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js +++ b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js @@ -426,7 +426,7 @@ this._colorStopsStr = []; for(var i =0; i < node._colorStops.length; i++){ var stopColor = node._colorStops[i].color; - var stopOpacity = stopColor.a/255; + var stopOpacity = stopColor.a == null ? 1 : stopColor.a / 255; this._colorStopsStr.push("rgba(" + Math.round(stopColor.r) + "," + Math.round(stopColor.g) + "," + Math.round(stopColor.b) + "," + stopOpacity.toFixed(4) + ")"); } diff --git a/template/project.json b/template/project.json index 6c2c93bd3d..fbca33527f 100644 --- a/template/project.json +++ b/template/project.json @@ -1,10 +1,10 @@ { "debugMode" : 1, - "noCache": true, + "noCache": false, "showFPS" : true, "frameRate" : 60, "id" : "gameCanvas", - "renderMode" : 0, + "renderMode" : 1, "engineDir":"../", "modules" : ["cocos2d"], diff --git a/template/src/myApp.js b/template/src/myApp.js index f91b7c40af..627c735ac3 100644 --- a/template/src/myApp.js +++ b/template/src/myApp.js @@ -44,6 +44,16 @@ var MyLayer = cc.Layer.extend({ this.sprite.setPosition(size.width / 2, size.height / 2); this.sprite.setScale(size.height / this.sprite.getContentSize().height); this.addChild(this.sprite, 0); + + var layerGradient = new cc.LayerGradient(cc.color.RED, cc.color.GREEN, cc.p(1,1), + [//{p:0, color: cc.color.RED}, + {p:0.25, color: new cc.Color(0,255,255,128)}, + {p:0.50, color: new cc.Color(255,255,0,128)}, + {p:0.75, color: new cc.Color(255,0,0,128)} + //{p:1, color: cc.color.GREEN} + ]); + this.addChild(layerGradient, 100); + window.gradient = layerGradient; } }); From 523e67c85c5c8480442aeae5800e6491b6316d3a Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Sat, 28 Feb 2015 10:08:32 +0800 Subject: [PATCH 0008/1039] Fixed #2701: added getSpriteFrame to cc.Sprite --- cocos2d/core/sprites/CCSprite.js | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/cocos2d/core/sprites/CCSprite.js b/cocos2d/core/sprites/CCSprite.js index 7bcd41db64..7c891aeb7d 100644 --- a/cocos2d/core/sprites/CCSprite.js +++ b/cocos2d/core/sprites/CCSprite.js @@ -875,14 +875,23 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ /** * Returns the current displayed frame. + * @deprecated since 3.4, please use getSpriteFrame instead * @return {cc.SpriteFrame} */ displayFrame: function () { + return this.getSpriteFrame(); + }, + + /** + * Returns the current displayed frame. + * @return {cc.SpriteFrame} + */ + getSpriteFrame: function () { return new cc.SpriteFrame(this._texture, - cc.rectPointsToPixels(this._rect), - this._rectRotated, - cc.pointPointsToPixels(this._unflippedOffsetPositionFromCenter), - cc.sizePointsToPixels(this._contentSize)); + cc.rectPointsToPixels(this._rect), + this._rectRotated, + cc.pointPointsToPixels(this._unflippedOffsetPositionFromCenter), + cc.sizePointsToPixels(this._contentSize)); }, /** From 84f7513a7608a35596300042744d12dfa58a7bb1 Mon Sep 17 00:00:00 2001 From: IShm Date: Sat, 28 Feb 2015 04:31:15 +0200 Subject: [PATCH 0009/1039] code formatting --- cocos2d/core/platform/CCScreen.js | 155 +++++++++++++++--------------- 1 file changed, 79 insertions(+), 76 deletions(-) diff --git a/cocos2d/core/platform/CCScreen.js b/cocos2d/core/platform/CCScreen.js index c33566b5d4..97452e6e36 100644 --- a/cocos2d/core/platform/CCScreen.js +++ b/cocos2d/core/platform/CCScreen.js @@ -2,19 +2,19 @@ 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 @@ -32,116 +32,119 @@ */ cc.screen = /** @lends cc.screen# */{ _supportsFullScreen: false, - // the pre fullscreenchange function + // the pre fullscreenchange function _preOnFullScreenChange: null, _touchEvent: "", - _fn: null, - // Function mapping for cross browser support - _fnMap: [ - [ - 'requestFullscreen', - 'exitFullscreen', - 'fullscreenchange', - 'fullscreenEnabled', - 'fullscreenElement' - ], - [ - 'requestFullScreen', - 'exitFullScreen', - 'fullScreenchange', - 'fullScreenEnabled', - 'fullScreenElement' - ], - [ - 'webkitRequestFullScreen', - 'webkitCancelFullScreen', - 'webkitfullscreenchange', - 'webkitIsFullScreen', - 'webkitCurrentFullScreenElement' - ], - [ - 'mozRequestFullScreen', - 'mozCancelFullScreen', - 'mozfullscreenchange', - 'mozFullScreen', - 'mozFullScreenElement' - ], - [ - 'msRequestFullscreen', - 'msExitFullscreen', - 'MSFullscreenChange', - 'msFullscreenEnabled', - 'msFullscreenElement' - ] - ], - + _fn: null, + // Function mapping for cross browser support + _fnMap: [ + [ + 'requestFullscreen', + 'exitFullscreen', + 'fullscreenchange', + 'fullscreenEnabled', + 'fullscreenElement' + ], + [ + 'requestFullScreen', + 'exitFullScreen', + 'fullScreenchange', + 'fullScreenEnabled', + 'fullScreenElement' + ], + [ + 'webkitRequestFullScreen', + 'webkitCancelFullScreen', + 'webkitfullscreenchange', + 'webkitIsFullScreen', + 'webkitCurrentFullScreenElement' + ], + [ + 'mozRequestFullScreen', + 'mozCancelFullScreen', + 'mozfullscreenchange', + 'mozFullScreen', + 'mozFullScreenElement' + ], + [ + 'msRequestFullscreen', + 'msExitFullscreen', + 'MSFullscreenChange', + 'msFullscreenEnabled', + 'msFullscreenElement' + ] + ], + /** * initialize * @function */ init: function () { - this._fn = {}; - var i, val, map = this._fnMap, valL; - for (i = 0, l = map.length; i < l; i++ ) { - val = map[ i ]; - if ( val && val[1] in document ) { - for ( i = 0, valL = val.length; i < valL; i++ ) { - this._fn[ map[0][ i ] ] = val[ i ]; - } - break; - } - } + this._fn = {}; + var i, val, map = this._fnMap, valL; + for (i = 0, l = map.length; i < l; i++) { + val = map[i]; + if (val && val[1] in document) { + for (i = 0, valL = val.length; i < valL; i++) { + this._fn[map[0][i]] = val[i]; + } + break; + } + } - this._supportsFullScreen = (this._fn.requestFullscreen != undefined); + this._supportsFullScreen = (typeof this._fn.requestFullscreen !== 'undefined'); this._touchEvent = ('ontouchstart' in window) ? 'touchstart' : 'mousedown'; }, - + /** * return true if it's full now. * @returns {Boolean} */ - fullScreen: function() { - return this._supportsFullScreen && document[this._fn.fullscreenElement]; + fullScreen: function () { + return this._supportsFullScreen && document[this._fn.fullscreenElement]; }, - + /** * change the screen to full mode. * @param {Element} element * @param {Function} onFullScreenChange */ requestFullScreen: function (element, onFullScreenChange) { - if (!this._supportsFullScreen) return; + if (!this._supportsFullScreen) { + return; + } - element = element || document.documentElement; - element[ this._fn.requestFullscreen ](); + element = element || document.documentElement; + element[this._fn.requestFullscreen](); - if (onFullScreenChange) { - var eventName = this._fn.fullscreenchange; - if (this._preOnFullScreenChange) - document.removeEventListener(eventName, this._preOnFullScreenChange); - this._preOnFullScreenChange = onFullScreenChange; + if (onFullScreenChange) { + var eventName = this._fn.fullscreenchange; + if (this._preOnFullScreenChange) { + document.removeEventListener(eventName, this._preOnFullScreenChange); + } + this._preOnFullScreenChange = onFullScreenChange; cc._addEventListener(document, eventName, onFullScreenChange, false); - } + } - return element[ this._fn.requestFullscreen ](); + return element[this._fn.requestFullscreen](); }, - + /** * exit the full mode. * @return {Boolean} */ exitFullScreen: function () { - return this._supportsFullScreen ? document[ this._fn.exitFullscreen ]() : true; + return this._supportsFullScreen ? document[this._fn.exitFullscreen]() : true; }, - + /** * Automatically request full screen with a touch/click event * @param {Element} element * @param {Function} onFullScreenChange */ autoFullScreen: function (element, onFullScreenChange) { - element = element || document.body; - var touchTarget = cc._canvas || element; + element = element || document.body; + var touchTarget = cc._canvas || element; var theScreen = this; // Function bind will be too complicated here because we need the callback function's reference to remove the listener function callback() { From f813a7f0712bc4ad228071585c9935068cf61caa Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Sat, 28 Feb 2015 10:40:50 +0800 Subject: [PATCH 0010/1039] Update scheduler; --- cocos2d/core/CCActionManager.js | 2 +- cocos2d/core/CCDirector.js | 2 +- cocos2d/core/CCScheduler.js | 121 ++++++------------ cocos2d/core/base-nodes/CCNode.js | 2 + cocos2d/core/platform/CCInputExtension.js | 4 +- extensions/ccpool/CCPool.js | 2 +- .../cocostudio/action/CCActionObject.js | 4 +- extensions/editbox/CCdomNode.js | 2 +- 8 files changed, 50 insertions(+), 89 deletions(-) diff --git a/cocos2d/core/CCActionManager.js b/cocos2d/core/CCActionManager.js index 18c2e3900d..ba8c2b499a 100644 --- a/cocos2d/core/CCActionManager.js +++ b/cocos2d/core/CCActionManager.js @@ -287,7 +287,7 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{ * because it uses this, so it can not be static */ purgeSharedManager:function () { - cc.director.getScheduler().unscheduleUpdateForTarget(this); + cc.director.getScheduler().scheduleUpdate(this); }, //protected diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js index ab18b55675..b9cfbc1437 100644 --- a/cocos2d/core/CCDirector.js +++ b/cocos2d/core/CCDirector.js @@ -386,7 +386,7 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ */ purgeDirector: function () { //cleanup scheduler - this.getScheduler().unscheduleAllCallbacks(); + this.getScheduler().unscheduleAll(); // Disable event dispatching if (cc.eventManager) diff --git a/cocos2d/core/CCScheduler.js b/cocos2d/core/CCScheduler.js index 6bc4a72b0b..7820616047 100644 --- a/cocos2d/core/CCScheduler.js +++ b/cocos2d/core/CCScheduler.js @@ -125,21 +125,18 @@ cc.Timer = cc.Class.extend(/** @lends cc.Timer# */{ setInterval : function(interval){this._interval = interval;}, setupTimerWithInterval: function(seconds, repeat, delay){ - //todo checking here this._elapsed = -1; this._interval = seconds; this._delay = delay; - this._useDelay = this._delay > 0 ? true : false; + this._useDelay = (this._delay > 0); this._repeat = repeat; - this._runForever = this._repeat == cc.REPEAT_FOREVER ? true : false; + this._runForever = (this._repeat == cc.REPEAT_FOREVER); }, - //todo checking here trigger: function(){ return 0; }, - //todo checking here cancel: function(){ return 0; }, @@ -153,13 +150,8 @@ cc.Timer = cc.Class.extend(/** @lends cc.Timer# */{ /** * cc.Timer's Constructor * Constructor of cc.Timer - * @param {cc.Class} target target - * @param {String|function} callback Selector - * @param {Number} [interval=0] second - * @param {Number} [repeat=cc.REPEAT_FOREVER] repeat times - * @param {Number} [delay=0] delay */ - ctor:function (target, callback, interval, repeat, delay) { + ctor:function () { this._scheduler = null; this._elapsed = -1; this._runForever = false; @@ -314,32 +306,30 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ _updates0List: null, _updatesPosList: null, + _hashForTimers:null, //Used for "selectors with interval" + //_arrayForTimes:null, //Speed up indexing _hashForUpdates:null, // hash used to fetch quickly the list entries for pause,delete,etc + //_arrayForUpdates:null, //Speed up indexing - _hashForTimers:null, //Used for "selectors with interval" _currentTarget:null, _currentTargetSalvaged:false, _updateHashLocked:false, //If true unschedule will not remove anything from a hash. Elements will only be marked for deletion. - //_arrayForTimes:null, - //_arrayForUpdates:null, ctor:function () { - var self = this; - self._timeScale = 1.0; - //self._updates = [[], [], []]; + this._timeScale = 1.0; this._updatesNegList = []; this._updates0List = []; this._updatesPosList = []; - self._hashForUpdates = {}; - self._hashForTimers = {}; - self._currentTarget = null; - self._currentTargetSalvaged = false; - self._updateHashLocked = false; + this._hashForUpdates = {}; + this._hashForTimers = {}; + this._currentTarget = null; + this._currentTargetSalvaged = false; + this._updateHashLocked = false; - //self._arrayForUpdates = []; - //self._arrayForTimers = []; + //this._arrayForUpdates = []; + //this._arrayForTimers = []; }, @@ -422,8 +412,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ } //update hash entry for quick access - var hashElement = new cc.HashUpdateEntry(ppList, listElement, target, null); - self._hashForUpdates[target.__instanceId] = hashElement; + self._hashForUpdates[target.__instanceId] = new cc.HashUpdateEntry(ppList, listElement, target, null); return ppList; }, @@ -433,8 +422,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ ppList.push(listElement); //update hash entry for quicker access - var hashElement = new cc.HashUpdateEntry(ppList, listElement, target, null, null); - self._hashForUpdates[target.__instanceId] = hashElement; + self._hashForUpdates[target.__instanceId] = new cc.HashUpdateEntry(ppList, listElement, target, null, null); }, //-----------------------public method------------------------- @@ -612,11 +600,11 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ cc.assert(element.paused == paused, ""); } - var timer; + var timer, i; if (element.timers == null) { element.timers = []; } else if(isSelector === false) { - for (var i = 0; i < element.timers.length; i++) { + for (i = 0; i < element.timers.length; i++) { timer = element.timers[i]; if (callback == timer._callback) { cc.log(cc._LogInfos.Scheduler_scheduleCallbackForTarget, timer.getInterval().toFixed(4), interval.toFixed(4)); @@ -625,7 +613,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ } } }else{ - for (var i = 0; i < element.timers.length; ++i){ + for (i = 0; i < element.timers.length; ++i){ timer =element.timers[i]; if (timer && selector == timer.getSelector()){ cc.log("CCScheduler#scheduleSelector. Selector already scheduled. Updating interval from: %.4f to %.4f", timer.getInterval(), interval); @@ -653,9 +641,22 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ }, target, priority, paused); }, + _getUnscheduleMark: function(key, timer){ + //key, callback, selector + switch (typeof key){ + case "number": + case "string": + return key == timer.getKey(); + case "function": + return key == timer._callback; + default: + return key == timer.getSelector(); + } + }, unschedule: function(key, target){ //key, target //selector, target + //callback, target - This is in order to increase compatibility // explicity handle nil arguments when removing an object if (!target || !key) @@ -666,7 +667,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ var timers = element.timers; for(var i = 0, li = timers.length; i < li; i++){ var timer = timers[i]; - if (key == timer.getKey()) { + if (this._getUnscheduleMark(key, timer)) { if ((timer == element.currentTimer) && (!element.currentTimerSalvaged)) { element.currentTimerSalvaged = true; } @@ -824,15 +825,16 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ var idsWithSelectors = []; var self = this, element, locArrayForTimers = self._arrayForTimers, locUpdates = self._updates; + var i, li; // Custom Selectors - for(var i = 0, li = locArrayForTimers.length; i < li; i++){ + for(i = 0, li = locArrayForTimers.length; i < li; i++){ element = locArrayForTimers[i]; if (element) { element.paused = true; idsWithSelectors.push(element.target); } } - for(var i = 0, li = locUpdates.length; i < li; i++){ + for(i = 0, li = locUpdates.length; i < li; i++){ var updates = locUpdates[i]; for(var j = 0, lj = updates.length; j < lj; j++){ element = updates[j]; @@ -963,38 +965,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ */ unscheduleCallbackForTarget:function (target, callback) { cc.log("unscheduleCallbackForTarget is deprecated. Please use unschedule."); - //this.unschedule(callback, target); - // explicity handle nil arguments when removing an object - if ((target == null) || (callback == null)) { - return; - } - - var self = this, element = self._hashForTimers[target.__instanceId]; - if (element) { - var timers = element.timers; - for(var i = 0, li = timers.length; i < li; i++){ - var timer = timers[i]; - if (callback == timer._callback) { - if ((timer == element.currentTimer) && (!element.currentTimerSalvaged)) { - element.currentTimerSalvaged = true; - } - timers.splice(i, 1); - //update timerIndex in case we are in tick;, looping over the actions - if (element.timerIndex >= i) { - element.timerIndex--; - } - - if (timers.length == 0) { - if (self._currentTarget == element) { - self._currentTargetSalvaged = true; - } else { - self._removeHashElement(element); - } - } - return; - } - } - } + this.unschedule(callback, target); }, /** @@ -1007,19 +978,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ */ unscheduleUpdateForTarget:function (target) { cc.log("unscheduleUpdateForTarget is deprecated. Please use unschedule."); - //this.unschedule(callback, target); - if (target == null) { - return; - } - - var self = this, element = self._hashForUpdates[target.__instanceId]; - if (element != null) { - if (self._updateHashLocked) { - element.entry.markedForDeletion = true; - } else { - self._removeUpdateFromHash(element.entry); - } - } + this.unscheduleUpdate(target); }, /** @@ -1029,7 +988,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ */ unscheduleAllCallbacksForTarget: function(target){ cc.log("unscheduleAllCallbacksForTarget is deprecated. Please use unscheduleAll."); - this.unscheduleAll(); + this.unschedule(target.__instanceId + "", target); }, /** @@ -1040,7 +999,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ * @deprecated since v3.4 please use .unscheduleAllWithMinPriority */ unscheduleAllCallbacks: function(){ - cc.log("unscheduleAllCallbacks is deprecated. Please use unscheduleAllWithMinPriority."); + cc.log("unscheduleAllCallbacks is deprecated. Please use unscheduleAll."); this.unscheduleAllWithMinPriority(cc.Scheduler.PRIORITY_SYSTEM); }, diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index b9ea1c7502..0e869aad9c 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -1740,6 +1740,8 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ scheduleOnce: function (callback, delay, key) { //selector, delay //callback, delay, key + if(key == undefined) + key = this.__instanceId; this.schedule(callback, 0, 0, delay, key); }, diff --git a/cocos2d/core/platform/CCInputExtension.js b/cocos2d/core/platform/CCInputExtension.js index 1d6c49bbcd..3c13edfcd0 100644 --- a/cocos2d/core/platform/CCInputExtension.js +++ b/cocos2d/core/platform/CCInputExtension.js @@ -39,10 +39,10 @@ _p.setAccelerometerEnabled = function(isEnable){ var scheduler = cc.director.getScheduler(); if(_t._accelEnabled){ _t._accelCurTime = 0; - scheduler.scheduleUpdateForTarget(_t); + scheduler.scheduleUpdate(_t); } else { _t._accelCurTime = 0; - scheduler.unscheduleUpdateForTarget(_t); + scheduler.scheduleUpdate(_t); } }; diff --git a/extensions/ccpool/CCPool.js b/extensions/ccpool/CCPool.js index 4121439db4..8c930642c3 100644 --- a/extensions/ccpool/CCPool.js +++ b/extensions/ccpool/CCPool.js @@ -52,7 +52,7 @@ cc.pool = /** @lends cc.pool# */{ _autoRelease: function (obj) { var running = obj._running === undefined ? false : !obj._running; - cc.director.getScheduler().scheduleCallbackForTarget(obj, this._releaseCB, 0, 0, 0, running) + cc.director.getScheduler().schedule(this._releaseCB, obj, 0, 0, 0, running) }, /** diff --git a/extensions/cocostudio/action/CCActionObject.js b/extensions/cocostudio/action/CCActionObject.js index 15e0c200d4..7c0ca0c9eb 100644 --- a/extensions/cocostudio/action/CCActionObject.js +++ b/extensions/cocostudio/action/CCActionObject.js @@ -200,7 +200,7 @@ ccs.ActionObject = ccs.Class.extend(/** @lends ccs.ActionObject# */{ locActionNodeList[i].playAction(fun); } if (this._loop) - this._scheduler.scheduleCallbackForTarget(this, this.simulationActionUpdate, 0, cc.REPEAT_FOREVER, 0, false); + this._scheduler.schedule(this.simulationActionUpdate, this, 0, cc.REPEAT_FOREVER, 0, false, this.__instanceId + ""); if(fun !== undefined) this._callback = fun; }, @@ -220,7 +220,7 @@ ccs.ActionObject = ccs.Class.extend(/** @lends ccs.ActionObject# */{ var locActionNodeList = this._actionNodeList; for (var i = 0; i < locActionNodeList.length; i++) locActionNodeList[i].stopAction(); - this._scheduler.unscheduleCallbackForTarget(this, this.simulationActionUpdate); + this._scheduler.unschedule(this.simulationActionUpdate, this); this._pause = false; this._playing = false; }, diff --git a/extensions/editbox/CCdomNode.js b/extensions/editbox/CCdomNode.js index fb62932ed3..a9b6a09c45 100644 --- a/extensions/editbox/CCdomNode.js +++ b/extensions/editbox/CCdomNode.js @@ -391,7 +391,7 @@ cc.DOM.methods = /** @lends cc.DOM# */{ cleanup:function () { // actions this.stopAllActions(); - this.unscheduleAllCallbacks(); + this.unscheduleAll(); // timers this._arrayMakeObjectsPerformSelector(this._children, cc.Node._stateCallbackType.cleanup); From d3ad9484a4ee3ec2f4b1ab68073957ce54389848 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Sat, 28 Feb 2015 13:39:53 +0800 Subject: [PATCH 0011/1039] Speed up indexing --- cocos2d/core/CCScheduler.js | 73 +++++++++++++++++++++---------------- 1 file changed, 42 insertions(+), 31 deletions(-) diff --git a/cocos2d/core/CCScheduler.js b/cocos2d/core/CCScheduler.js index 7820616047..c7a20bc6ff 100644 --- a/cocos2d/core/CCScheduler.js +++ b/cocos2d/core/CCScheduler.js @@ -111,10 +111,6 @@ cc.Timer = cc.Class.extend(/** @lends cc.Timer# */{ _delay:0, _interval:0.0, - //_callback:null,//is called _callback before - //_target:null,//target of _callback - - /** * @return {Number} returns interval of timer */ @@ -141,12 +137,6 @@ cc.Timer = cc.Class.extend(/** @lends cc.Timer# */{ return 0; }, - /** - * @return {String|function} returns callback - */ - //getCallback : function(){return this._callback}, - - /** * cc.Timer's Constructor * Constructor of cc.Timer @@ -250,7 +240,6 @@ cc.TimerTargetCallback = cc.Timer.extend({ }, initWithCallback: function(scheduler, callback, target, key, seconds, repeat, delay){ - //todo checking here this._scheduler = scheduler; this._target = target; this._callback = callback; @@ -307,7 +296,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ _updatesPosList: null, _hashForTimers:null, //Used for "selectors with interval" - //_arrayForTimes:null, //Speed up indexing + _arrayForTimers:null, //Speed up indexing _hashForUpdates:null, // hash used to fetch quickly the list entries for pause,delete,etc //_arrayForUpdates:null, //Speed up indexing @@ -328,15 +317,14 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ this._currentTargetSalvaged = false; this._updateHashLocked = false; + this._arrayForTimers = []; //this._arrayForUpdates = []; - //this._arrayForTimers = []; }, //-----------------------private method---------------------- _schedulePerFrame: function(callback, target, priority, paused){ - //todo var hashElement = this._hashForUpdates[target.__instanceId]; if (hashElement){ // check if priority has changed @@ -371,7 +359,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ _removeHashElement:function (element) { delete this._hashForTimers[element.target.__instanceId]; - //cc.arrayRemoveObject(this._arrayForTimers, element); + cc.arrayRemoveObject(this._arrayForTimers, element); element.Timer = null; element.target = null; element = null; @@ -384,7 +372,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ cc.arrayRemoveObject(element.list, element.entry); delete self._hashForUpdates[element.target.__instanceId]; - cc.arrayRemoveObject(self._hashForUpdates, element); + //cc.arrayRemoveObject(self._hashForUpdates, element); element.entry = null; //hash entry @@ -478,9 +466,9 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ } // Iterate over all the custom selectors - var elt; - for (var p in this._hashForTimers){ - elt = this._hashForTimers[p]; + var elt, arr = this._arrayForTimers; + for(i=0; i= minPriority){ + element.paused = true; + idsWithSelectors.push(element.target); + } + } + } + } + + if(minPriority <= 0){ + for(i=0; i= minPriority){ + element.paused = true; + idsWithSelectors.push(element.target); + } + } + } + return idsWithSelectors; }, From 2a964f93a35160971ffbf2be83b4b8757bd79595 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Sat, 28 Feb 2015 14:58:09 +0800 Subject: [PATCH 0012/1039] Maybe the black screen of 8.1.2 after adaptation --- cocos2d/core/platform/CCEGLView.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/platform/CCEGLView.js b/cocos2d/core/platform/CCEGLView.js index 78184ce5c5..fd5cfe2aa3 100644 --- a/cocos2d/core/platform/CCEGLView.js +++ b/cocos2d/core/platform/CCEGLView.js @@ -54,10 +54,13 @@ cc.__BrowserGetter = { meta: { "width": "device-width", "user-scalable": "no" - } + }, + adaptationType: cc.sys.browserType }; +if(window.navigator.userAgent.indexOf("OS 8_1_2") > -1) + cc.__BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_MIUI; -switch(cc.sys.browserType){ +switch(cc.__BrowserGetter.adaptationType){ case cc.sys.BROWSER_TYPE_SAFARI: cc.__BrowserGetter.meta["minimal-ui"] = "true"; cc.__BrowserGetter.availWidth = function(frame){ From 8e8357a4e0440f4f08c643031b4259c7cf5975c3 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Sat, 28 Feb 2015 15:41:32 +0800 Subject: [PATCH 0013/1039] Added note --- cocos2d/core/platform/CCEGLView.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/platform/CCEGLView.js b/cocos2d/core/platform/CCEGLView.js index fd5cfe2aa3..271033a5af 100644 --- a/cocos2d/core/platform/CCEGLView.js +++ b/cocos2d/core/platform/CCEGLView.js @@ -57,7 +57,8 @@ cc.__BrowserGetter = { }, adaptationType: cc.sys.browserType }; -if(window.navigator.userAgent.indexOf("OS 8_1_2") > -1) + +if(window.navigator.userAgent.indexOf("OS 8_1_2") > -1) //this mistake like MIUI, so use of MIUI treatment method cc.__BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_MIUI; switch(cc.__BrowserGetter.adaptationType){ From 376ff5e6c00dbb50c66bc11f6c2811a630064a87 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Sat, 28 Feb 2015 16:06:41 +0800 Subject: [PATCH 0014/1039] Fixed - Call error --- cocos2d/core/CCActionManager.js | 2 +- cocos2d/core/base-nodes/CCNode.js | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/CCActionManager.js b/cocos2d/core/CCActionManager.js index ba8c2b499a..aeade2fe6e 100644 --- a/cocos2d/core/CCActionManager.js +++ b/cocos2d/core/CCActionManager.js @@ -287,7 +287,7 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{ * because it uses this, so it can not be static */ purgeSharedManager:function () { - cc.director.getScheduler().scheduleUpdate(this); + cc.director.getScheduler().unscheduleUpdate(this); }, //protected diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index 0e869aad9c..b83d29e7ec 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -1155,7 +1155,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ */ setScheduler: function (scheduler) { if (this._scheduler != scheduler) { - this.unscheduleAllWithMinPriority(); + this.unscheduleAll(); this._scheduler = scheduler; } }, @@ -1661,7 +1661,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @see cc.Node#scheduleUpdate */ unscheduleUpdate: function () { - this.scheduler.unschedule(this.__instanceId, this); + this.scheduler.unscheduleUpdate(this); }, /** From 8338e63936fee91073cd0df82e98c8eab91322fe Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 2 Mar 2015 11:25:54 +0800 Subject: [PATCH 0015/1039] Issue #1498: bug on cc.isObject --- CCBoot.js | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index 11dcd5661b..98e933bc8f 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -141,7 +141,8 @@ cc.isString = function(obj) { * @returns {boolean} */ cc.isArray = function(obj) { - return Object.prototype.toString.call(obj) == '[object Array]'; + return Array.isArray(obj) || + (typeof obj === 'object' && objectToString(obj) === '[object Array]'); }; /** @@ -150,7 +151,7 @@ cc.isArray = function(obj) { * @returns {boolean} */ cc.isUndefined = function(obj) { - return typeof obj == 'undefined'; + return typeof obj === 'undefined'; }; /** @@ -159,9 +160,7 @@ cc.isUndefined = function(obj) { * @returns {boolean} */ cc.isObject = function(obj) { - var type = typeof obj; - - return type == 'function' || (obj && type == 'object'); + return typeof obj === "object" && Object.prototype.toString.call(obj) === '[object Object]'; }; /** From d7d507f91db15e7907c2c54b7246222f2ce0e43b Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 2 Mar 2015 11:31:05 +0800 Subject: [PATCH 0016/1039] Issue #1498: bug on cc.isObject --- CCBoot.js | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index 11dcd5661b..98e933bc8f 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -141,7 +141,8 @@ cc.isString = function(obj) { * @returns {boolean} */ cc.isArray = function(obj) { - return Object.prototype.toString.call(obj) == '[object Array]'; + return Array.isArray(obj) || + (typeof obj === 'object' && objectToString(obj) === '[object Array]'); }; /** @@ -150,7 +151,7 @@ cc.isArray = function(obj) { * @returns {boolean} */ cc.isUndefined = function(obj) { - return typeof obj == 'undefined'; + return typeof obj === 'undefined'; }; /** @@ -159,9 +160,7 @@ cc.isUndefined = function(obj) { * @returns {boolean} */ cc.isObject = function(obj) { - var type = typeof obj; - - return type == 'function' || (obj && type == 'object'); + return typeof obj === "object" && Object.prototype.toString.call(obj) === '[object Object]'; }; /** From 653452095feb6efb4a2091a16a9f58acabe0afda Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 2 Mar 2015 11:39:11 +0800 Subject: [PATCH 0017/1039] Issue #1498: bug on cc.isObject --- CCBoot.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CCBoot.js b/CCBoot.js index 98e933bc8f..aca8a3b6f2 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -142,7 +142,7 @@ cc.isString = function(obj) { */ cc.isArray = function(obj) { return Array.isArray(obj) || - (typeof obj === 'object' && objectToString(obj) === '[object Array]'); + (typeof obj === 'object' && Object.prototype.toString.call(obj) === '[object Array]'); }; /** From 2b6809fb7f5eaec961d0949f2e1099a781a3e4ed Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 2 Mar 2015 13:39:39 +0800 Subject: [PATCH 0018/1039] cc.TMXObjectGroup.prototype.objectNamed in JSB --- cocos2d/tilemap/CCTMXObjectGroup.js | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/cocos2d/tilemap/CCTMXObjectGroup.js b/cocos2d/tilemap/CCTMXObjectGroup.js index ddeb400080..7cd3267c21 100644 --- a/cocos2d/tilemap/CCTMXObjectGroup.js +++ b/cocos2d/tilemap/CCTMXObjectGroup.js @@ -116,6 +116,16 @@ cc.TMXObjectGroup = cc.Class.extend(/** @lends cc.TMXObjectGroup# */{ * @return {object|Null} */ objectNamed:function (objectName) { + this.getObject(objectName); + }, + + /** + *

Return the dictionary for the specific object name.
+ * It will return the 1st object found on the array for the given name.

+ * @param {String} objectName + * @return {object|Null} + */ + getObject: function(objectName){ if (this._objects && this._objects.length > 0) { var locObjects = this._objects; for (var i = 0, len = locObjects.length; i < len; i++) { From 868ee3d9462e06db4f9308a70d60fd4ae8bd9f4d Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 2 Mar 2015 14:36:13 +0800 Subject: [PATCH 0019/1039] cc.TMXObjectGroup.prototype.objectNamed in JSB --- cocos2d/tilemap/CCTMXObjectGroup.js | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos2d/tilemap/CCTMXObjectGroup.js b/cocos2d/tilemap/CCTMXObjectGroup.js index 7cd3267c21..7bfcafbe32 100644 --- a/cocos2d/tilemap/CCTMXObjectGroup.js +++ b/cocos2d/tilemap/CCTMXObjectGroup.js @@ -112,6 +112,7 @@ cc.TMXObjectGroup = cc.Class.extend(/** @lends cc.TMXObjectGroup# */{ /** *

Return the dictionary for the specific object name.
* It will return the 1st object found on the array for the given name.

+ * @deprecated since v3.4 please use .getObject * @param {String} objectName * @return {object|Null} */ From 161afd07449280573947dc6bf3224247ebe8a9d0 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 2 Mar 2015 15:46:06 +0800 Subject: [PATCH 0020/1039] Maybe the black screen of 8.1.3 after adaptation --- cocos2d/core/platform/CCEGLView.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/platform/CCEGLView.js b/cocos2d/core/platform/CCEGLView.js index 271033a5af..e5be3e63b5 100644 --- a/cocos2d/core/platform/CCEGLView.js +++ b/cocos2d/core/platform/CCEGLView.js @@ -58,7 +58,7 @@ cc.__BrowserGetter = { adaptationType: cc.sys.browserType }; -if(window.navigator.userAgent.indexOf("OS 8_1_2") > -1) //this mistake like MIUI, so use of MIUI treatment method +if(window.navigator.userAgent.indexOf("OS 8_1_") > -1) //this mistake like MIUI, so use of MIUI treatment method cc.__BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_MIUI; switch(cc.__BrowserGetter.adaptationType){ From 936651b64728b8f5ba3d381aeca93a6d9c9be767 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 3 Mar 2015 14:01:06 +0800 Subject: [PATCH 0021/1039] audioEngine not playing in Firefox, using minified/compiled lib --- cocos2d/audio/CCAudio.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index 4c4b565d32..de28710216 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -32,6 +32,7 @@ * auto : Supports auto-play audio - if Don‘t support it, On a touch detecting background music canvas, and then replay * replay : The first music will fail, must be replay after touchstart * emptied : Whether to use the emptied event to replace load callback + * delay : delay created the context object - only webAudio * * May be modifications for a few browser version */ @@ -48,7 +49,7 @@ // ANDROID // supportTable[sys.BROWSER_TYPE_ANDROID] = {multichannel: false, webAudio: false, auto: false}; supportTable[sys.BROWSER_TYPE_CHROME] = {multichannel: true , webAudio: true , auto: false}; - supportTable[sys.BROWSER_TYPE_FIREFOX] = {multichannel: true , webAudio: true , auto: true }; + supportTable[sys.BROWSER_TYPE_FIREFOX] = {multichannel: true , webAudio: true , auto: true , delay: true}; supportTable[sys.BROWSER_TYPE_UC] = {multichannel: true , webAudio: false, auto: false}; supportTable[sys.BROWSER_TYPE_QQ] = {multichannel: false, webAudio: false, auto: true }; supportTable[sys.BROWSER_TYPE_OUPENG] = {multichannel: false, webAudio: false, auto: false, replay: true , emptied: true }; @@ -476,6 +477,8 @@ cc.Audio = cc.Class.extend({ try{ if(SWA){ var context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)(); + if(polyfill.delay) + setTimeout(function(){ context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)(); }, 0); } }catch(error){ SWA = false; From 30764bc4b89d270aef9dca0cc52c8d401a579466 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Tue, 3 Mar 2015 17:40:24 +0800 Subject: [PATCH 0022/1039] Fixed #2693: Add color stops to cc.LayerGradient on WebGL and fixed a bug of cc.LayerGradientRenderCmd --- cocos2d/core/layers/CCLayerCanvasRenderCmd.js | 16 +- cocos2d/core/layers/CCLayerWebGLRenderCmd.js | 143 +++++++++++++----- cocos2d/core/support/CCPointExtension.js | 2 +- template/project.json | 2 +- template/src/myApp.js | 10 -- 5 files changed, 115 insertions(+), 58 deletions(-) diff --git a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js index e01fc07def..cfa224148d 100644 --- a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js +++ b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js @@ -404,13 +404,18 @@ proto._updateColor = function(){ var node = this._node; var contentSize = node._contentSize; - var locAlongVector = node._alongVector, tWidth = contentSize.width * 0.5, tHeight = contentSize.height * 0.5; + var tWidth = contentSize.width * 0.5, tHeight = contentSize.height * 0.5; this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.gradientDirty ^ this._dirtyFlag; - this._startPoint.x = tWidth * (-locAlongVector.x) + tWidth; - this._startPoint.y = tHeight * locAlongVector.y - tHeight; - this._endPoint.x = tWidth * locAlongVector.x + tWidth; - this._endPoint.y = tHeight * (-locAlongVector.y) - tHeight; + //fix the bug of gradient layer + var angle = cc.pAngleSigned(cc.p(0, -1), node._alongVector); + var p1 = cc.pRotateByAngle(cc.p(0, -1), cc.p(0,0), angle); + var factor = Math.min(Math.abs(1 / p1.x), Math.abs(1/ p1.y)); + + this._startPoint.x = tWidth * (-p1.x * factor) + tWidth; + this._startPoint.y = tHeight * (p1.y * factor) - tHeight; + this._endPoint.x = tWidth * (p1.x * factor) + tWidth; + this._endPoint.y = tHeight * (-p1.y * factor) - tHeight; var locStartColor = this._displayedColor, locEndColor = node._endColor; var startOpacity = node._startOpacity/255, endOpacity = node._endOpacity/255; @@ -431,6 +436,5 @@ + Math.round(stopColor.b) + "," + stopOpacity.toFixed(4) + ")"); } } - }; })(); \ No newline at end of file diff --git a/cocos2d/core/layers/CCLayerWebGLRenderCmd.js b/cocos2d/core/layers/CCLayerWebGLRenderCmd.js index 85e90b33dd..812c6d9394 100644 --- a/cocos2d/core/layers/CCLayerWebGLRenderCmd.js +++ b/cocos2d/core/layers/CCLayerWebGLRenderCmd.js @@ -75,7 +75,7 @@ var proto = cc.LayerColor.WebGLRenderCmd.prototype = Object.create(cc.Layer.WebGLRenderCmd.prototype); proto.constructor = cc.LayerColor.WebGLRenderCmd; - cc.LayerColor.WebGLRenderCmd.prototype.rendering = function (ctx) { + proto.rendering = function (ctx) { var context = ctx || cc._renderContext; var node = this._node; @@ -93,7 +93,7 @@ context.bindBuffer(context.ARRAY_BUFFER, this._colorsUint8Buffer); context.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, context.UNSIGNED_BYTE, true, 0, 0); - context.drawArrays(context.TRIANGLE_STRIP, 0, 4); + context.drawArrays(context.TRIANGLE_STRIP, 0, this._squareVertices.length); }; proto._updateSquareVertices = function(size, height){ @@ -160,6 +160,8 @@ cc.LayerGradient.WebGLRenderCmd = function(renderable){ cc.LayerColor.WebGLRenderCmd.call(this, renderable); this._needDraw = true; + this._clipRect = new cc.Rect(); + this._clippingRectDirty = false; }; var proto = cc.LayerGradient.WebGLRenderCmd.prototype = Object.create(cc.LayerColor.WebGLRenderCmd.prototype); cc.inject(cc.LayerGradient.RenderCmd, proto); @@ -201,48 +203,109 @@ proto._updateColor = function(){ this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.gradientDirty ^ this._dirtyFlag; - var _t = this, node = this._node; - var locAlongVector = node._alongVector; - var h = cc.pLength(locAlongVector); - if (h === 0) + var node = this._node, stops = node._colorStops; + if(!stops || stops.length < 2) return; - var c = Math.sqrt(2.0), u = cc.p(locAlongVector.x / h, locAlongVector.y / h); + this._clippingRectDirty = true; + var stopsLen = stops.length, verticesLen = stopsLen * 2, i, contentSize = node._contentSize; + this._squareVerticesAB = new ArrayBuffer(verticesLen * 8); + this._squareColorsAB = new ArrayBuffer(verticesLen * 4); + var locVertices = this._squareVertices, locColors = this._squareColors; + locVertices.length = 0; + locColors.length = 0; - // Compressed Interpolation mode - if (node._compressedInterpolation) { - var h2 = 1 / ( Math.abs(u.x) + Math.abs(u.y) ); - u = cc.pMult(u, h2 * c); + var locSquareVerticesAB = this._squareVerticesAB, locSquareColorsAB = this._squareColorsAB; + var locVertex2FLen = cc.Vertex2F.BYTES_PER_ELEMENT, locColorLen = cc.Color.BYTES_PER_ELEMENT; + for(i = 0; i < verticesLen; i++){ + locVertices.push(new cc.Vertex2F(0, 0, locSquareVerticesAB, locVertex2FLen * i)); + locColors.push(cc.color(0, 0, 0, 255, locSquareColorsAB, locColorLen * i)) + } + + //init vertex + var angle = Math.PI + cc.pAngleSigned(cc.p(0, -1), node._alongVector), locAnchor = cc.p(contentSize.width/2, contentSize.height /2); + var degrees = Math.round(cc.radiansToDegrees(angle)); + var transMat = cc.affineTransformMake(1, 0, 0, 1, locAnchor.x, locAnchor.y); + transMat = cc.affineTransformRotate(transMat, angle); + var a, b; + if(degrees < 90) { + a = cc.p(-locAnchor.x, locAnchor.y); + b = cc.p(locAnchor.x, locAnchor.y); + } else if(degrees < 180) { + a = cc.p(locAnchor.x, locAnchor.y); + b = cc.p(locAnchor.x, -locAnchor.y); + } else if(degrees < 270) { + a = cc.p(locAnchor.x, -locAnchor.y); + b = cc.p(-locAnchor.x, -locAnchor.y); + } else { + a = cc.p(-locAnchor.x, -locAnchor.y); + b = cc.p(-locAnchor.x, locAnchor.y); + } + + var sin = Math.sin(angle), cos = Math.cos(angle); + var tx = Math.abs((a.x * cos - a.y * sin)/locAnchor.x), ty = Math.abs((b.x * sin + b.y * cos)/locAnchor.y); + transMat = cc.affineTransformScale(transMat, tx, ty); + for (i = 0; i < stopsLen; i++) { + var stop = stops[i], y = stop.p * contentSize.height ; + var p0 = cc._pointApplyAffineTransform(- locAnchor.x , y - locAnchor.y, transMat); + locVertices[i * 2].x = p0.x; + locVertices[i * 2].y = p0.y; + var p1 = cc._pointApplyAffineTransform(contentSize.width - locAnchor.x, y - locAnchor.y, transMat); + locVertices[i * 2 + 1].x = p1.x; + locVertices[i * 2 + 1].y = p1.y; + } + + //init color + var opacityf = this._displayedOpacity / 255.0; //, displayColor = this._displayedColor; + for(i = 0; i < stopsLen; i++){ + var stopColor = stops[i].color, locSquareColor0 = locColors[i * 2], locSquareColor1 = locColors[i * 2 + 1]; + locSquareColor0.r = stopColor.r; + locSquareColor0.g = stopColor.g; + locSquareColor0.b = stopColor.b; + locSquareColor0.a = stopColor.a * opacityf; + + locSquareColor1.r = stopColor.r; + locSquareColor1.g = stopColor.g; + locSquareColor1.b = stopColor.b; + locSquareColor1.a = stopColor.a * opacityf; } + this._bindLayerVerticesBufferData(); + this._bindLayerColorsBufferData(); + }; + + proto.rendering = function (ctx) { + var context = ctx || cc._renderContext, node = this._node; + + //it is too expensive to use stencil to clip, so it use Scissor, + //but it has a bug when layer rotated and layer's content size less than canvas's size. + var clippingRect = this._getClippingRect(); + context.enable(context.SCISSOR_TEST); + cc.view.setScissorInPoints(clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height); + + //draw gradient layer + this._shaderProgram.use(); + this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix); + cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POSITION | cc.VERTEX_ATTRIB_FLAG_COLOR); + cc.glBlendFunc(node._blendFunc.src, node._blendFunc.dst); + // + // Attributes + // + context.bindBuffer(context.ARRAY_BUFFER, this._verticesFloat32Buffer); + context.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, context.FLOAT, false, 0, 0); + context.bindBuffer(context.ARRAY_BUFFER, this._colorsUint8Buffer); + context.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, context.UNSIGNED_BYTE, true, 0, 0); + context.drawArrays(context.TRIANGLE_STRIP, 0, this._squareVertices.length); - var opacityf = _t._displayedOpacity / 255.0; - var locDisplayedColor = _t._displayedColor, locEndColor = node._endColor; - var S = { r: locDisplayedColor.r, g: locDisplayedColor.g, b: locDisplayedColor.b, a: node._startOpacity * opacityf}; - var E = {r: locEndColor.r, g: locEndColor.g, b: locEndColor.b, a: node._endOpacity * opacityf}; - - // (-1, -1) - var locSquareColors = _t._squareColors; - var locSquareColor0 = locSquareColors[0], locSquareColor1 = locSquareColors[1], locSquareColor2 = locSquareColors[2], locSquareColor3 = locSquareColors[3]; - locSquareColor0.r = ((E.r + (S.r - E.r) * ((c + u.x + u.y) / (2.0 * c)))); - locSquareColor0.g = ((E.g + (S.g - E.g) * ((c + u.x + u.y) / (2.0 * c)))); - locSquareColor0.b = ((E.b + (S.b - E.b) * ((c + u.x + u.y) / (2.0 * c)))); - locSquareColor0.a = ((E.a + (S.a - E.a) * ((c + u.x + u.y) / (2.0 * c)))); - // (1, -1) - locSquareColor1.r = ((E.r + (S.r - E.r) * ((c - u.x + u.y) / (2.0 * c)))); - locSquareColor1.g = ((E.g + (S.g - E.g) * ((c - u.x + u.y) / (2.0 * c)))); - locSquareColor1.b = ((E.b + (S.b - E.b) * ((c - u.x + u.y) / (2.0 * c)))); - locSquareColor1.a = ((E.a + (S.a - E.a) * ((c - u.x + u.y) / (2.0 * c)))); - // (-1, 1) - locSquareColor2.r = ((E.r + (S.r - E.r) * ((c + u.x - u.y) / (2.0 * c)))); - locSquareColor2.g = ((E.g + (S.g - E.g) * ((c + u.x - u.y) / (2.0 * c)))); - locSquareColor2.b = ((E.b + (S.b - E.b) * ((c + u.x - u.y) / (2.0 * c)))); - locSquareColor2.a = ((E.a + (S.a - E.a) * ((c + u.x - u.y) / (2.0 * c)))); - // (1, 1) - locSquareColor3.r = ((E.r + (S.r - E.r) * ((c - u.x - u.y) / (2.0 * c)))); - locSquareColor3.g = ((E.g + (S.g - E.g) * ((c - u.x - u.y) / (2.0 * c)))); - locSquareColor3.b = ((E.b + (S.b - E.b) * ((c - u.x - u.y) / (2.0 * c)))); - locSquareColor3.a = ((E.a + (S.a - E.a) * ((c - u.x - u.y) / (2.0 * c)))); - - _t._bindLayerColorsBufferData(); + context.disable(context.SCISSOR_TEST); + }; + + proto._getClippingRect = function(){ + if(this._clippingRectDirty){ + var node = this._node; + var rect = cc.rect(0, 0, node._contentSize.width, node._contentSize.height); + var trans = node.getNodeToWorldTransform(); + this._clipRect = cc._rectApplyAffineTransformIn(rect, trans); + } + return this._clipRect; }; })(); \ No newline at end of file diff --git a/cocos2d/core/support/CCPointExtension.js b/cocos2d/core/support/CCPointExtension.js index db74da1001..cf74e24b79 100644 --- a/cocos2d/core/support/CCPointExtension.js +++ b/cocos2d/core/support/CCPointExtension.js @@ -507,7 +507,7 @@ cc.pAddIn = function(v1, v2) { /** * normalizes the point (inplace) - * @param {cc.Point{ v + * @param {cc.Point} v */ cc.pNormalizeIn = function(v) { cc.pMultIn(v, 1.0 / Math.sqrt(v.x * v.x + v.y * v.y)); diff --git a/template/project.json b/template/project.json index fbca33527f..a4a9435aab 100644 --- a/template/project.json +++ b/template/project.json @@ -4,7 +4,7 @@ "showFPS" : true, "frameRate" : 60, "id" : "gameCanvas", - "renderMode" : 1, + "renderMode" : 0, "engineDir":"../", "modules" : ["cocos2d"], diff --git a/template/src/myApp.js b/template/src/myApp.js index 627c735ac3..f91b7c40af 100644 --- a/template/src/myApp.js +++ b/template/src/myApp.js @@ -44,16 +44,6 @@ var MyLayer = cc.Layer.extend({ this.sprite.setPosition(size.width / 2, size.height / 2); this.sprite.setScale(size.height / this.sprite.getContentSize().height); this.addChild(this.sprite, 0); - - var layerGradient = new cc.LayerGradient(cc.color.RED, cc.color.GREEN, cc.p(1,1), - [//{p:0, color: cc.color.RED}, - {p:0.25, color: new cc.Color(0,255,255,128)}, - {p:0.50, color: new cc.Color(255,255,0,128)}, - {p:0.75, color: new cc.Color(255,0,0,128)} - //{p:1, color: cc.color.GREEN} - ]); - this.addChild(layerGradient, 100); - window.gradient = layerGradient; } }); From 169f117d3a18f121402a2ed2295aca56b3a4510b Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 3 Mar 2015 17:52:30 +0800 Subject: [PATCH 0023/1039] update scheduler cocos2d/cocos2d-js#1316 --- cocos2d/core/CCScheduler.js | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/cocos2d/core/CCScheduler.js b/cocos2d/core/CCScheduler.js index c7a20bc6ff..510b21735b 100644 --- a/cocos2d/core/CCScheduler.js +++ b/cocos2d/core/CCScheduler.js @@ -543,7 +543,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ * cc.director.getScheduler().scheduleCallbackForTarget(this, function, interval, repeat, delay, !this._isRunning ); */ scheduleCallbackForTarget: function(target, callback_fn, interval, repeat, delay, paused){ - cc.log("scheduleCallbackForTarget is deprecated. Please use schedule."); + //cc.log("scheduleCallbackForTarget is deprecated. Please use schedule."); this.schedule(callback_fn, target, interval, repeat, delay, paused, target.__instanceId + ""); }, @@ -958,7 +958,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ * cc.director.getScheduler().scheduleUpdateForTarget(this, priority, !this._isRunning ); */ scheduleUpdateForTarget: function(target, priority, paused){ - cc.log("scheduleUpdateForTarget is deprecated. Please use scheduleUpdate."); + //cc.log("scheduleUpdateForTarget is deprecated. Please use scheduleUpdate."); this.scheduleUpdate(target, priority, paused); }, @@ -975,7 +975,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ * cc.director.getScheduler().unscheduleCallbackForTarget(function, this); */ unscheduleCallbackForTarget:function (target, callback) { - cc.log("unscheduleCallbackForTarget is deprecated. Please use unschedule."); + //cc.log("unscheduleCallbackForTarget is deprecated. Please use unschedule."); this.unschedule(callback, target); }, @@ -988,7 +988,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ * cc.director.getScheduler().unscheduleUpdateForTarget(this); */ unscheduleUpdateForTarget:function (target) { - cc.log("unscheduleUpdateForTarget is deprecated. Please use unschedule."); + //cc.log("unscheduleUpdateForTarget is deprecated. Please use unschedule."); this.unscheduleUpdate(target); }, @@ -998,7 +998,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ * @param {cc.Class} target */ unscheduleAllCallbacksForTarget: function(target){ - cc.log("unscheduleAllCallbacksForTarget is deprecated. Please use unscheduleAll."); + //cc.log("unscheduleAllCallbacksForTarget is deprecated. Please use unscheduleAll."); this.unschedule(target.__instanceId + "", target); }, @@ -1010,7 +1010,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ * @deprecated since v3.4 please use .unscheduleAllWithMinPriority */ unscheduleAllCallbacks: function(){ - cc.log("unscheduleAllCallbacks is deprecated. Please use unscheduleAll."); + //cc.log("unscheduleAllCallbacks is deprecated. Please use unscheduleAll."); this.unscheduleAllWithMinPriority(cc.Scheduler.PRIORITY_SYSTEM); }, @@ -1023,7 +1023,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ * @param {Number} minPriority */ unscheduleAllCallbacksWithMinPriority:function (minPriority) { - cc.log("unscheduleAllCallbacksWithMinPriority is deprecated. Please use unscheduleAllWithMinPriority."); + //cc.log("unscheduleAllCallbacksWithMinPriority is deprecated. Please use unscheduleAllWithMinPriority."); this.unscheduleAllWithMinPriority(minPriority); } }); From d129bf4791ac020eebcc538e54d2d3dabc237b6f Mon Sep 17 00:00:00 2001 From: Igor Shmulyan Date: Tue, 3 Mar 2015 15:06:34 +0200 Subject: [PATCH 0024/1039] removed requestFullscreen before adding of listener --- cocos2d/core/platform/CCScreen.js | 1 - 1 file changed, 1 deletion(-) diff --git a/cocos2d/core/platform/CCScreen.js b/cocos2d/core/platform/CCScreen.js index 97452e6e36..f1730fe015 100644 --- a/cocos2d/core/platform/CCScreen.js +++ b/cocos2d/core/platform/CCScreen.js @@ -115,7 +115,6 @@ cc.screen = /** @lends cc.screen# */{ } element = element || document.documentElement; - element[this._fn.requestFullscreen](); if (onFullScreenChange) { var eventName = this._fn.fullscreenchange; From 2f8c9023864ba35f9cbd4c249fdf01df9742e023 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Wed, 4 Mar 2015 14:55:23 +0800 Subject: [PATCH 0025/1039] Fixed #2699: add the parameter 'premultiplied' to cc.Texture --- cocos2d/core/textures/TexturesWebGL.js | 11 ++++++++--- template/src/myApp.js | 11 ----------- 2 files changed, 8 insertions(+), 14 deletions(-) diff --git a/cocos2d/core/textures/TexturesWebGL.js b/cocos2d/core/textures/TexturesWebGL.js index a62de74fff..7f838f0609 100644 --- a/cocos2d/core/textures/TexturesWebGL.js +++ b/cocos2d/core/textures/TexturesWebGL.js @@ -442,8 +442,10 @@ cc._tmp.WebGLTexture2D = function () { /** * handler of texture loaded event + * @param {Boolean} [premultipled=false] */ - handleLoadedTexture: function () { + handleLoadedTexture: function (premultipled) { + premultipled = (premultipled === undefined)?false: premultipled; var self = this; // Not sure about this ! Some texture need to be updated even after loaded if (!cc._rendererInitialized) @@ -462,7 +464,8 @@ cc._tmp.WebGLTexture2D = function () { cc.glBindTexture2D(self); gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); + if(premultipled) + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1); // Specify OpenGL texture image gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, self._htmlElementObj); @@ -474,6 +477,8 @@ cc._tmp.WebGLTexture2D = function () { self.shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURE); cc.glBindTexture2D(null); + if(premultipled) + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0); var pixelsWide = self._htmlElementObj.width; var pixelsHigh = self._htmlElementObj.height; @@ -484,7 +489,7 @@ cc._tmp.WebGLTexture2D = function () { self.maxS = 1; self.maxT = 1; - self._hasPremultipliedAlpha = false; + self._hasPremultipliedAlpha = premultipled; self._hasMipmaps = false; //dispatch load event to listener. diff --git a/template/src/myApp.js b/template/src/myApp.js index b4258ed20a..f91b7c40af 100644 --- a/template/src/myApp.js +++ b/template/src/myApp.js @@ -44,17 +44,6 @@ var MyLayer = cc.Layer.extend({ this.sprite.setPosition(size.width / 2, size.height / 2); this.sprite.setScale(size.height / this.sprite.getContentSize().height); this.addChild(this.sprite, 0); - - var root = new cc.Node(); - var body = new cc.Sprite("cut_the_hope1.png", cc.rect(827, 775, 143, 134)); - var leg = new cc.Sprite("cut_the_hope1.png", cc.rect(934, 248, 46, 51)); - //leg.setBlendFunc(cc.BlendFunc.ALPHA_PREMULTIPLIED); - - root.addChild(body); - root.addChild(leg); - this.addChild(root); - root.setScale(3); - root.setPosition(size.width/2, size.height/2); } }); From 32ec57da1a90b53a7a82d47c3298890ea85c2e88 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Wed, 4 Mar 2015 15:01:39 +0800 Subject: [PATCH 0026/1039] Removed the test codes. --- template/src/resource.js | 1 - 1 file changed, 1 deletion(-) diff --git a/template/src/resource.js b/template/src/resource.js index a70fc7f61b..94284083d1 100644 --- a/template/src/resource.js +++ b/template/src/resource.js @@ -5,7 +5,6 @@ var s_CloseSelected = "CloseSelected.png"; var g_resources = [ //image s_HelloWorld, - "cut_the_hope1.png", s_CloseNormal, s_CloseSelected From 5b5d0c9b77fa9c3e511c2790a1cf0b7616d05f1e Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Thu, 5 Mar 2015 14:02:22 +0800 Subject: [PATCH 0027/1039] Fixed a bug of cc.DrawNode that its lineWidth is always to default value when set linewidth to zero. --- cocos2d/shape-nodes/CCDrawNode.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/cocos2d/shape-nodes/CCDrawNode.js b/cocos2d/shape-nodes/CCDrawNode.js index 18b8456fd2..9564b6bdc9 100644 --- a/cocos2d/shape-nodes/CCDrawNode.js +++ b/cocos2d/shape-nodes/CCDrawNode.js @@ -181,7 +181,7 @@ cc.DrawNodeCanvas = cc.Node.extend(/** @lends cc.DrawNode# */{ * @param {cc.Color} lineColor */ drawRect: function (origin, destination, fillColor, lineWidth, lineColor) { - lineWidth = lineWidth || this._lineWidth; + lineWidth = (lineWidth == null) ? this._lineWidth : lineWidth; lineColor = lineColor || this.getDrawColor(); if(lineColor.a == null) lineColor.a = 255; @@ -436,7 +436,7 @@ cc.DrawNodeCanvas = cc.Node.extend(/** @lends cc.DrawNode# */{ * @param {cc.Color} color */ drawPoly_: function (verts, fillColor, lineWidth, color) { - lineWidth = lineWidth || this._lineWidth; + lineWidth = (lineWidth == null ) ? this._lineWidth : lineWidth; color = color || this.getDrawColor(); if (color.a == null) color.a = 255; @@ -554,7 +554,7 @@ cc.DrawNodeWebGL = cc.Node.extend({ }, drawRect: function (origin, destination, fillColor, lineWidth, lineColor) { - lineWidth = lineWidth || this._lineWidth; + lineWidth = (lineWidth == null) ? this._lineWidth : lineWidth; lineColor = lineColor || this.getDrawColor(); if (lineColor.a == null) lineColor.a = 255; @@ -789,7 +789,7 @@ cc.DrawNodeWebGL = cc.Node.extend({ fillColor.a = 255; if (borderColor.a == null) borderColor.a = 255; - borderWidth = borderWidth || this._lineWidth; + borderWidth = (borderWidth == null)? this._lineWidth : borderWidth; borderWidth *= 0.5; var c4bFillColor = {r: 0 | fillColor.r, g: 0 | fillColor.g, b: 0 | fillColor.b, a: 0 | fillColor.a}; var c4bBorderColor = {r: 0 | borderColor.r, g: 0 | borderColor.g, b: 0 | borderColor.b, a: 0 | borderColor.a}; @@ -852,7 +852,7 @@ cc.DrawNodeWebGL = cc.Node.extend({ }, _drawSegments: function(verts, borderWidth, borderColor, closePoly){ - borderWidth = borderWidth || this._lineWidth; + borderWidth = (borderWidth == null) ? this._lineWidth : borderWidth; borderColor = borderColor || this._drawColor; if(borderColor.a == null) borderColor.a = 255; From 1d091c2801877a949dd1b2842937a45c8ca3cf17 Mon Sep 17 00:00:00 2001 From: SijieWang Date: Thu, 5 Mar 2015 15:42:57 +0800 Subject: [PATCH 0028/1039] Revert "Remove _loadTxtSync, Because chrome(40) deprecated this API" --- CCBoot.js | 58 +++++++++++++++++++++++++++++-------------------------- 1 file changed, 31 insertions(+), 27 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index 5e76480f82..5359522ea4 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -689,6 +689,26 @@ cc.loader = /** @lends cc.loader# */{ }); } }, + _loadTxtSync: function (url) { + if (!cc._isNodeJs) { + var xhr = this.getXMLHttpRequest(); + xhr.open("GET", url, false); + if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) { + // IE-specific logic here + xhr.setRequestHeader("Accept-Charset", "utf-8"); + } else { + if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=utf-8"); + } + xhr.send(null); + if (!xhr.readyState == 4 || xhr.status != 200) { + return null; + } + return xhr.responseText; + } else { + var fs = require("fs"); + return fs.readFileSync(url).toString(); + } + }, loadCsb: function(url, cb){ var xhr = new XMLHttpRequest(); @@ -1944,7 +1964,6 @@ cc.game = /** @lends cc.game# */{ DEBUG_MODE_INFO_FOR_WEB_PAGE: 4, DEBUG_MODE_WARN_FOR_WEB_PAGE: 5, DEBUG_MODE_ERROR_FOR_WEB_PAGE: 6, - _ready: false, EVENT_HIDE: "game_on_hide", EVENT_SHOW: "game_on_show", @@ -2082,12 +2101,6 @@ cc.game = /** @lends cc.game# */{ * Run game. */ run: function (id) { - if(this._ready === false){ - this._ready = id === undefined ? true : id; - return; - }else if(typeof this._ready !== "boolean"){ - id = this._ready; - } var self = this; var _run = function () { if (id) { @@ -2130,13 +2143,7 @@ cc.game = /** @lends cc.game# */{ cfg[CONFIG_KEY.frameRate] = cfg[CONFIG_KEY.frameRate] || 60; if(cfg[CONFIG_KEY.renderMode] == null) cfg[CONFIG_KEY.renderMode] = 1; - //init debug move to CCDebugger - cc._initSys(cfg, CONFIG_KEY); - self.config = cfg; - if(cc.game._ready !== false){ - self._ready = true; - cc.game.run(); - } + return cfg; }; if (document["ccConfig"]) { self.config = _init(document["ccConfig"]); @@ -2147,7 +2154,7 @@ cc.game = /** @lends cc.game# */{ var _t = cocos_script[i].getAttribute('cocos'); if(_t == '' || _t){break;} } - var _src, _resPath; + var _src, txt, _resPath; if(i < cocos_script.length){ _src = cocos_script[i].src; if(_src){ @@ -2155,23 +2162,20 @@ cc.game = /** @lends cc.game# */{ cc.loader.resPath = _resPath; _src = cc.path.join(_resPath, 'project.json'); } - cc.loader.loadTxt(_src, function(err, txt){ - if(err) - return cc.error(err); - _init(JSON.parse(txt) || {}); - }); - }else{ - cc.loader.loadTxt("project.json", function(err, txt){ - if(err) - return cc.error(err); - _init(JSON.parse(txt) || {}); - }); + txt = cc.loader._loadTxtSync(_src); + } + if(!txt){ + txt = cc.loader._loadTxtSync("project.json"); } + var data = JSON.parse(txt); + self.config = _init(data || {}); } catch (e) { cc.log("Failed to read or parse project.json"); - _init({}); + self.config = _init({}); } } + //init debug move to CCDebugger + cc._initSys(self.config, CONFIG_KEY); }, //cache for js and module that has added into jsList to be loaded. From c88599e642744796b963a3d32640093308a91bff Mon Sep 17 00:00:00 2001 From: Igor Shmulyan Date: Fri, 6 Mar 2015 11:37:15 +0200 Subject: [PATCH 0029/1039] fixed bug in hack for performance. --- cocos2d/particle/CCParticleSystemCanvasRenderCmd.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js b/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js index 8420e8e1e2..ed58e9821b 100644 --- a/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js +++ b/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js @@ -206,7 +206,7 @@ proto._initWithTotalParticles = function(totalParticles){}; proto._updateDeltaColor = function(selParticle, dt){ - if (!this._dontTint) { + if (!this._node._dontTint) { selParticle.color.r += selParticle.deltaColor.r * dt; selParticle.color.g += selParticle.deltaColor.g * dt; selParticle.color.b += selParticle.deltaColor.b * dt; From 24373c424456b6dcb380994c066a3107f5a453b0 Mon Sep 17 00:00:00 2001 From: Thomas Jablonski Date: Sat, 7 Mar 2015 13:29:40 +0100 Subject: [PATCH 0030/1039] audioEngine not playing in Firefox, using minified/compiled lib Load the right supportTable to support BROWSER_TYPE_FIREFOX settings --- cocos2d/audio/CCAudio.js | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index de28710216..6ce489238c 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -134,11 +134,16 @@ else cc.__audioSupport = supportTable[sys.BROWSER_TYPE_SAFARI]; }else{ - //Desktop support all - if(cc.sys.browserType != cc.sys.BROWSER_TYPE_IE) - cc.__audioSupport = supportTable["common"]; - else - cc.__audioSupport = supportTable[sys.BROWSER_TYPE_IE]; + switch(sys.browserType){ + case sys.BROWSER_TYPE_IE: + cc.__audioSupport = supportTable[sys.BROWSER_TYPE_IE]; + break; + case sys.BROWSER_TYPE_FIREFOX: + cc.__audioSupport = supportTable[sys.BROWSER_TYPE_FIREFOX]; + break; + default: + cc.__audioSupport = supportTable["common"]; + } } if(DEBUG){ From ef6b796829933b65785f8c412dfdd96d529f2320 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 9 Mar 2015 09:49:18 +0800 Subject: [PATCH 0031/1039] Add an initial loading icon --- template/index.html | 1 + template/main.js | 3 +++ template/src/loading.js | 1 + 3 files changed, 5 insertions(+) create mode 100644 template/src/loading.js diff --git a/template/index.html b/template/index.html index a5e02d13d4..776f7d11d7 100644 --- a/template/index.html +++ b/template/index.html @@ -23,6 +23,7 @@ + \ No newline at end of file diff --git a/template/main.js b/template/main.js index 8d14ccf6a2..dcbd88808c 100644 --- a/template/main.js +++ b/template/main.js @@ -1,4 +1,7 @@ cc.game.onStart = function(){ + if(!cc.sys.isNative) //If referenced loading.js, please remove it + document.body.removeChild(document.getElementById("cocosLoading")); + var designSize = cc.size(480, 800); var screenSize = cc.view.getFrameSize(); diff --git a/template/src/loading.js b/template/src/loading.js new file mode 100644 index 0000000000..d17a700344 --- /dev/null +++ b/template/src/loading.js @@ -0,0 +1 @@ +(function(){var createStyle=function(){return".cocosLoading{position:absolute;margin:-30px -60px;padding:0;top:50%;left:50%}"+".cocosLoading ul{margin:0;padding:0;}"+".cocosLoading span{color:#FFF;text-align:center;display:block;}"+".cocosLoading li{list-style:none;float:left;border-radius:15px;width:15px;height:15px;background:#FFF;margin:5px 0 0 10px}"+".cocosLoading li .ball,.cocosLoading li .unball{background-color:#2187e7;background-image:-moz-linear-gradient(90deg,#2187e7 25%,#a0eaff);background-image:-webkit-linear-gradient(90deg,#2187e7 25%,#a0eaff);width:15px;height:15px;border-radius:50px}"+".cocosLoading li .ball{transform:scale(0);-moz-transform:scale(0);-webkit-transform:scale(0);animation:showDot 1s linear forwards;-moz-animation:showDot 1s linear forwards;-webkit-animation:showDot 1s linear forwards}"+".cocosLoading li .unball{transform:scale(1);-moz-transform:scale(1);-webkit-transform:scale(1);animation:hideDot 1s linear forwards;-moz-animation:hideDot 1s linear forwards;-webkit-animation:hideDot 1s linear forwards}"+"@keyframes showDot{0%{transform:scale(0,0)}100%{transform:scale(1,1)}}"+"@-moz-keyframes showDot{0%{-moz-transform:scale(0,0)}100%{-moz-transform:scale(1,1)}}"+"@-webkit-keyframes showDot{0%{-webkit-transform:scale(0,0)}100%{-webkit-transform:scale(1,1)}}"+"@keyframes hideDot{0%{transform:scale(1,1)}100%{transform:scale(0,0)}}"+"@-moz-keyframes hideDot{0%{-moz-transform:scale(1,1)}100%{-moz-transform:scale(0,0)}}"+"@-webkit-keyframes hideDot{0%{-webkit-transform:scale(1,1)}100%{-webkit-transform:scale(0,0)}}"};var createDom=function(id,num){id=id||"cocosLoading";num=num||5;var i,item;var div=document.createElement("div");div.className="cocosLoading";div.id=id;var bar=document.createElement("ul");var list=[];for(i=0;i=list.length){direction=!direction;index=0;time=1000}else{time=300}animation()},time)};animation()};(function(){var bgColor=document.body.style.background;document.body.style.background="#000";var style=document.createElement("style");style.type="text/css";style.innerHTML=createStyle();document.head.appendChild(style);var list=createDom();startAnimation(list,function(){var div=document.getElementById("cocosLoading");if(!div){document.body.style.background=bgColor}return !!div})})()})(); \ No newline at end of file From dcd76c6225eda3e1463a5e9a7bdcc66c6eb1ab91 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 9 Mar 2015 09:58:33 +0800 Subject: [PATCH 0032/1039] update build.xml --- tools/build.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/build.xml b/tools/build.xml index aa09aa2fa3..c1d0858cb8 100644 --- a/tools/build.xml +++ b/tools/build.xml @@ -5,7 +5,7 @@ classpath="./compiler/compiler.jar"/> + debug="false" output="./../lib/cocos2d-js-v3.3-min.js"> @@ -298,7 +298,7 @@ + debug="false" output="./../lib/cocos2d-js-v3.3-core-min.js"> From e15c3eaff03b09c6268c32c2eea7e926e7b0dc78 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 9 Mar 2015 10:13:06 +0800 Subject: [PATCH 0033/1039] =?UTF-8?q?IPhone=E2=80=98s=20WebView=20does=20n?= =?UTF-8?q?ot=20default=20=20use=20the=20webgl?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CCBoot.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CCBoot.js b/CCBoot.js index 5359522ea4..7543fbc756 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -1560,6 +1560,8 @@ cc._initSys = function (config, CONFIG_KEY) { browserType = sys.BROWSER_TYPE_ANDROID; else if (browserType == "trident") browserType = sys.BROWSER_TYPE_IE; else if (browserType == "360 aphone") browserType = sys.BROWSER_TYPE_360; + }else if(ua.indexOf("iphone") && ua.indexOf("mobile")){ + browserType = "safari"; } /** * Indicate the running browser type From dfa1b8be502675e3f578b1f79b81dcad0526f8a4 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Mon, 9 Mar 2015 11:59:28 +0800 Subject: [PATCH 0034/1039] Issue #2698: refactor vec2, vec3 and aabb --- cocos2d/core/CCCamera.js | 20 +- cocos2d/core/CCDirectorWebGL.js | 20 +- cocos2d/kazmath/aabb.js | 52 +++-- cocos2d/kazmath/gl/matrix.js | 4 +- cocos2d/kazmath/mat3.js | 4 +- cocos2d/kazmath/mat4.js | 68 ++++--- cocos2d/kazmath/plane.js | 47 ++--- cocos2d/kazmath/quaternion.js | 99 ++++------ cocos2d/kazmath/ray2.js | 221 ++++++++++----------- cocos2d/kazmath/utility.js | 46 ++--- cocos2d/kazmath/vec2.js | 162 ++++++++-------- cocos2d/kazmath/vec3.js | 330 ++++++++++++++++---------------- cocos2d/kazmath/vec4.js | 12 +- 13 files changed, 494 insertions(+), 591 deletions(-) diff --git a/cocos2d/core/CCCamera.js b/cocos2d/core/CCCamera.js index 79fe599b66..d9189391e8 100644 --- a/cocos2d/core/CCCamera.js +++ b/cocos2d/core/CCCamera.js @@ -113,14 +113,10 @@ cc.Camera = cc.Class.extend({ */ locate:function () { if (this._dirty) { - var eye = new cc.kmVec3(), center = new cc.kmVec3(), up = new cc.kmVec3(); - - cc.kmVec3Fill( eye, this._eyeX, this._eyeY , this._eyeZ ); - cc.kmVec3Fill( center, this._centerX, this._centerY, this._centerZ); - - cc.kmVec3Fill( up, this._upX, this._upY, this._upZ); + var eye = new cc.math.Vec3(this._eyeX, this._eyeY , this._eyeZ), + center = new cc.math.Vec3(this._centerX, this._centerY, this._centerZ), + up = new cc.math.Vec3(this._upX, this._upY, this._upZ); cc.kmMat4LookAt( this._lookupMatrix, eye, center, up); - this._dirty = false; } cc.kmGLMultMatrix( this._lookupMatrix); @@ -128,14 +124,10 @@ cc.Camera = cc.Class.extend({ _locateForRenderer: function(matrix){ if (this._dirty) { - var eye = new cc.kmVec3(), center = new cc.kmVec3(), up = new cc.kmVec3(); - - cc.kmVec3Fill( eye, this._eyeX, this._eyeY , this._eyeZ ); - cc.kmVec3Fill( center, this._centerX, this._centerY, this._centerZ); - - cc.kmVec3Fill( up, this._upX, this._upY, this._upZ); + var eye = new cc.math.Vec3(this._eyeX, this._eyeY , this._eyeZ), + center = new cc.math.Vec3(this._centerX, this._centerY, this._centerZ), + up = new cc.math.Vec3(this._upX, this._upY, this._upZ); cc.kmMat4LookAt( this._lookupMatrix, eye, center, up); - this._dirty = false; } cc.kmMat4Multiply(matrix, matrix, this._lookupMatrix); diff --git a/cocos2d/core/CCDirectorWebGL.js b/cocos2d/core/CCDirectorWebGL.js index d5468d4fe0..092dda5b7d 100644 --- a/cocos2d/core/CCDirectorWebGL.js +++ b/cocos2d/core/CCDirectorWebGL.js @@ -82,9 +82,9 @@ if (cc._renderType === cc._RENDER_TYPE_WEBGL) { cc.kmGLMatrixMode(cc.KM_GL_MODELVIEW); cc.kmGLLoadIdentity(); - var eye = cc.kmVec3Fill(null, -ox + size.width / 2, -oy + size.height / 2, zeye); - var center = cc.kmVec3Fill(null, -ox + size.width / 2, -oy + size.height / 2, 0.0); - var up = cc.kmVec3Fill(null, 0.0, 1.0, 0.0); + var eye = new cc.math.Vec3(-ox + size.width / 2, -oy + size.height / 2, zeye); + var center = new cc.math.Vec3( -ox + size.width / 2, -oy + size.height / 2, 0.0); + var up = new cc.math.Vec3( 0.0, 1.0, 0.0); cc.kmMat4LookAt(matrixLookup, eye, center, up); cc.kmGLMultMatrix(matrixLookup); break; @@ -246,13 +246,9 @@ if (cc._renderType === cc._RENDER_TYPE_WEBGL) { // Calculate z=0 using -> transform*[0, 0, 0, 1]/w var zClip = transform.mat[14] / transform.mat[15]; - var glSize = this._openGLView.getDesignResolutionSize(); - var clipCoord = new cc.kmVec3(2.0 * uiPoint.x / glSize.width - 1.0, 1.0 - 2.0 * uiPoint.y / glSize.height, zClip); - - var glCoord = new cc.kmVec3(); - cc.kmVec3TransformCoord(glCoord, clipCoord, transformInv); - + var glCoord = new cc.math.Vec3(2.0 * uiPoint.x / glSize.width - 1.0, 1.0 - 2.0 * uiPoint.y / glSize.height, zClip); + glCoord.transformCoord(transformInv); return cc.p(glCoord.x, glCoord.y); }; @@ -260,16 +256,14 @@ if (cc._renderType === cc._RENDER_TYPE_WEBGL) { var transform = new cc.kmMat4(); cc.GLToClipTransform(transform); - var clipCoord = new cc.kmVec3(); + var clipCoord = new cc.math.Vec3(glPoint.x, glPoint.y, 0.0); // Need to calculate the zero depth from the transform. - var glCoord = new cc.kmVec3(glPoint.x, glPoint.y, 0.0); - cc.kmVec3TransformCoord(clipCoord, glCoord, transform); + clipCoord.transformCoord(transform); var glSize = this._openGLView.getDesignResolutionSize(); return cc.p(glSize.width * (clipCoord.x * 0.5 + 0.5), glSize.height * (-clipCoord.y * 0.5 + 0.5)); }; - _p.getVisibleSize = function () { //if (this._openGLView) { return this._openGLView.getVisibleSize(); diff --git a/cocos2d/kazmath/aabb.js b/cocos2d/kazmath/aabb.js index 8fafef6f67..a6d207ad8b 100644 --- a/cocos2d/kazmath/aabb.js +++ b/cocos2d/kazmath/aabb.js @@ -27,42 +27,52 @@ */ /** - * A struture that represents an axis-aligned - * bounding box. + * A structure that represents an axis-aligned bounding box. + * cc.kmAABB => cc.math.AABB */ -cc.kmAABB = function (min, max) { +cc.math.AABB = function (min, max) { /** The max corner of the box */ - this.min = min || new cc.kmVec3(); + this.min = min || new cc.math.Vec3(); /** The min corner of the box */ - this.max = max || new cc.kmVec3(); + this.max = max || new cc.math.Vec3(); }; /** - * Returns KM_TRUE if point is in the specified AABB, returns - * KM_FALSE otherwise. + * Returns true if point is in the specified AABB, returns false otherwise. + * @param {cc.kmVec3} point + * @returns {boolean} */ -cc.kmAABBContainsPoint = function (pPoint, pBox) { - if (pPoint.x >= pBox.min.x && pPoint.x <= pBox.max.x && +cc.math.AABB.prototype.containsPoint = function (point) { + return (point.x >= this.min.x && point.x <= this.max.x && + point.y >= this.min.y && point.y <= this.max.y && + point.z >= this.min.z && point.z <= this.max.z); +}; + +/** + * Returns true if point is in the specified AABB, returns + * false otherwise. + */ +cc.math.AABB.containsPoint = function (pPoint, pBox) { + return (pPoint.x >= pBox.min.x && pPoint.x <= pBox.max.x && pPoint.y >= pBox.min.y && pPoint.y <= pBox.max.y && - pPoint.z >= pBox.min.z && pPoint.z <= pBox.max.z) { - return cc.KM_TRUE; - } - return cc.KM_FALSE; + pPoint.z >= pBox.min.z && pPoint.z <= pBox.max.z); }; /** - * Assigns pIn to pOut, returns pOut. + * Assigns aabb to current AABB object + * @param {cc.math.AABB} aabb */ -cc.kmAABBAssign = function (pOut, pIn) { - cc.kmVec3Assign(pOut.min, pIn.min); - cc.kmVec3Assign(pOut.max, pIn.max); - return pOut; +cc.math.AABB.prototype.assign = function(aabb){ + this.min.assign(aabb.min); + this.max.assign(aabb.max); }; /** - * Scales pIn by s, stores the resulting AABB in pOut. Returns pOut + * Assigns pIn to pOut, returns pOut. */ -cc.kmAABBScale = function (pOut, pIn, s) { - cc.log("cc.kmAABBScale hasn't been supported."); +cc.math.AABB.assign = function (pOut, pIn) { //cc.kmAABBAssign + pOut.min.assign(pIn.min); + pOut.max.assign(pIn.max); + return pOut; }; diff --git a/cocos2d/kazmath/gl/matrix.js b/cocos2d/kazmath/gl/matrix.js index ed579f8c0f..97b0134faf 100644 --- a/cocos2d/kazmath/gl/matrix.js +++ b/cocos2d/kazmath/gl/matrix.js @@ -133,11 +133,11 @@ cc.kmGLTranslatef = function (x, y, z) { }; cc.kmGLRotatef = function (angle, x, y, z) { - var axis = new cc.kmVec3(x, y, z); + var axis = new cc.math.Vec3(x, y, z); var rotation = new cc.kmMat4(); //Create a rotation matrix using the axis and the angle - cc.kmMat4RotationAxisAngle(rotation, axis, cc.kmDegreesToRadians(angle)); + cc.kmMat4RotationAxisAngle(rotation, axis, cc.degreesToRadians(angle)); //Multiply the rotation matrix by the current matrix cc.kmMat4Multiply(cc.current_stack.top, cc.current_stack.top, rotation); diff --git a/cocos2d/kazmath/mat3.js b/cocos2d/kazmath/mat3.js index fea8559630..565df74a6f 100644 --- a/cocos2d/kazmath/mat3.js +++ b/cocos2d/kazmath/mat3.js @@ -179,8 +179,8 @@ cc.kmMat3AreEqual = function (pMat1, pMat2) { return true; for (var i = 0; i < 9; ++i) { - if (!(pMat1.mat[i] + cc.kmEpsilon > pMat2.mat[i] && - pMat1.mat[i] - cc.kmEpsilon < pMat2.mat[i])) { + if (!(pMat1.mat[i] + cc.math.EPSILON > pMat2.mat[i] && + pMat1.mat[i] - cc.math.EPSILON < pMat2.mat[i])) { return false; } } diff --git a/cocos2d/kazmath/mat4.js b/cocos2d/kazmath/mat4.js index 9c62be7284..fd1a428ea5 100644 --- a/cocos2d/kazmath/mat4.js +++ b/cocos2d/kazmath/mat4.js @@ -122,7 +122,7 @@ cc.kmMat4._gaussj = function (a, b) { indxr[i] = irow; indxc[i] = icol; if (cc.kmMat4._get(a, icol, icol) == 0.0) - return cc.KM_FALSE; + return false; pivinv = 1.0 / cc.kmMat4._get(a, icol, icol); cc.kmMat4._set(a, icol, icol, 1.0); @@ -153,7 +153,7 @@ cc.kmMat4._gaussj = function (a, b) { cc.kmMat4._swap(a, k, indxr[l], k, indxc[l]); } } - return cc.KM_TRUE; + return true; }; cc.kmMat4._identity = @@ -174,7 +174,7 @@ cc.kmMat4Inverse = function (pOut, pM) { cc.kmMat4Assign(inv, pM); cc.kmMat4Identity(tmp); - if (cc.kmMat4._gaussj(inv, tmp) == cc.KM_FALSE) + if (cc.kmMat4._gaussj(inv, tmp) == false) return null; cc.kmMat4Assign(pOut, inv); @@ -338,8 +338,8 @@ cc.kmMat4AreEqual = function (pMat1, pMat2) { } for (var i = 0; i < 16; i++) { - if (!(pMat1.mat[i] + cc.kmEpsilon > pMat2.mat[i] && - pMat1.mat[i] - cc.kmEpsilon < pMat2.mat[i])) { + if (!(pMat1.mat[i] + cc.math.EPSILON > pMat2.mat[i] && + pMat1.mat[i] - cc.math.EPSILON < pMat2.mat[i])) { return false; } } @@ -573,35 +573,32 @@ cc.kmMat4Translation = function (pOut, x, y, z) { * wish to extract the vector from. pOut is a pointer to the * kmVec3 structure that should hold the resulting vector */ -cc.kmMat4GetUpVec3 = function (pOut, pIn) { - pOut.x = pIn.mat[4]; - pOut.y = pIn.mat[5]; - pOut.z = pIn.mat[6]; - cc.kmVec3Normalize(pOut, pOut); - return pOut; +cc.kmMat4GetUpVec3 = function (vec3, mat4) { + vec3.x = mat4.mat[4]; + vec3.y = mat4.mat[5]; + vec3.z = mat4.mat[6]; + return vec3.normalize(); }; /** Extract the right vector from a 4x4 matrix. The result is * stored in pOut. Returns pOut. */ -cc.kmMat4GetRightVec3 = function (pOut, pIn) { - pOut.x = pIn.mat[0]; - pOut.y = pIn.mat[1]; - pOut.z = pIn.mat[2]; - cc.kmVec3Normalize(pOut, pOut); - return pOut; +cc.kmMat4GetRightVec3 = function (vec3, mat4) { + vec3.x = mat4.mat[0]; + vec3.y = mat4.mat[1]; + vec3.z = mat4.mat[2]; + return vec3.normalize(); }; /** * Extract the forward vector from a 4x4 matrix. The result is * stored in pOut. Returns pOut. */ -cc.kmMat4GetForwardVec3 = function (pOut, pIn) { - pOut.x = pIn.mat[8]; - pOut.y = pIn.mat[9]; - pOut.z = pIn.mat[10]; - cc.kmVec3Normalize(pOut, pOut); - return pOut; +cc.kmMat4GetForwardVec3 = function (vec3, mat4) { + vec3.x = mat4.mat[8]; + vec3.y = mat4.mat[9]; + vec3.z = mat4.mat[10]; + return vec3.normalize(); }; /** @@ -609,7 +606,7 @@ cc.kmMat4GetForwardVec3 = function (pOut, pIn) { * same way as gluPerspective */ cc.kmMat4PerspectiveProjection = function (pOut, fovY, aspect, zNear, zFar) { - var r = cc.kmDegreesToRadians(fovY / 2); + var r = cc.degreesToRadians(fovY / 2); var deltaZ = zFar - zNear; var s = Math.sin(r); @@ -647,20 +644,21 @@ cc.kmMat4OrthographicProjection = function (pOut, left, right, bottom, top, near * the resulting matrix is stored in pOut. pOut is returned. */ cc.kmMat4LookAt = function (pOut, pEye, pCenter, pUp) { - var f = new cc.kmVec3(), up = new cc.kmVec3(), s = new cc.kmVec3(), u = new cc.kmVec3(); + var f = new cc.math.Vec3(pCenter), up = new cc.math.Vec3(pUp); var translate = new cc.kmMat4(); - cc.kmVec3Subtract(f, pCenter, pEye); - cc.kmVec3Normalize(f, f); + f.subtract(pEye); + f.normalize(); - cc.kmVec3Assign(up, pUp); - cc.kmVec3Normalize(up, up); + up.normalize(); - cc.kmVec3Cross(s, f, up); - cc.kmVec3Normalize(s, s); + var s = new cc.math.Vec3(f); + s.cross(up); + s.normalize(); - cc.kmVec3Cross(u, s, f); - cc.kmVec3Normalize(s, s); + var u = new cc.math.Vec3(s); + u.cross(f); + s.normalize(); cc.kmMat4Identity(pOut); @@ -690,8 +688,8 @@ cc.kmMat4RotationAxisAngle = function (pOut, axis, radians) { var rcos = Math.cos(radians); var rsin = Math.sin(radians); - var normalizedAxis = new cc.kmVec3(); - cc.kmVec3Normalize(normalizedAxis, axis); + var normalizedAxis = new cc.math.Vec3(axis); + normalizedAxis.normalize(); pOut.mat[0] = rcos + normalizedAxis.x * normalizedAxis.x * (1 - rcos); pOut.mat[1] = normalizedAxis.z * rsin + normalizedAxis.y * normalizedAxis.x * (1 - rcos); diff --git a/cocos2d/kazmath/plane.js b/cocos2d/kazmath/plane.js index 02acd8399b..a3b9a0d5bd 100644 --- a/cocos2d/kazmath/plane.js +++ b/cocos2d/kazmath/plane.js @@ -84,7 +84,7 @@ cc.kmPlaneFromPointNormal = function(pOut, pPoint, pNormal){ pOut.a = pNormal.x; pOut.b = pNormal.y; pOut.c = pNormal.z; - pOut.d = -cc.kmVec3Dot(pNormal, pPoint); + pOut.d = - pNormal.dot(pPoint); return pOut; }; @@ -103,58 +103,33 @@ cc.kmPlaneFromPoints = function(pOut, p1, p2, p3){ Outd = −n⋅A */ - var n = new cc.kmVec3(), v1 = new cc.kmVec3(), v2 = new cc.kmVec3(); - cc.kmVec3Subtract(v1, p2, p1); //Create the vectors for the 2 sides of the triangle - cc.kmVec3Subtract(v2, p3, p1); - cc.kmVec3Cross(n, v1, v2); //Use the cross product to get the normal - - cc.kmVec3Normalize(n, n); //Normalize it and assign to pOut.m_N + var v1 = new cc.math.Vec3(p2), v2 = new cc.math.Vec3(p3); + v1.subtract(p1); //Create the vectors for the 2 sides of the triangle + v2.subtract(p1); + var n = new cc.math.Vec3(v1); + n.cross(v2); // Use the cross product to get the normal + n.normalize(); //Normalize it and assign to pOut.m_N pOut.a = n.x; pOut.b = n.y; pOut.c = n.z; - pOut.d = cc.kmVec3Dot(cc.kmVec3Scale(n, n, -1.0), p1); - + pOut.d = n.scale(-1.0).dot(p1); return pOut; }; -cc.kmPlaneIntersectLine = function(pOut, pP, pV1, pV2){ - throw "cc.kmPlaneIntersectLine() hasn't been implemented."; - /* - n = (Planea, Planeb, Planec) - d = V − U - Out = U − d⋅(Pd + n⋅U)⁄(d⋅n) [iff d⋅n ≠ 0] - */ - //var d = new cc.kmVec3(); - - //cc.kmVec3Subtract(d, pV2, pV1); //Get the direction vector - - //TODO: Continue here! - /*if (fabs(kmVec3Dot(&pP.m_N, &d)) > kmEpsilon) - { - //If we get here then the plane and line are parallel (i.e. no intersection) - pOut = nullptr; //Set to nullptr - - return pOut; - } */ - - //return null; -}; - cc.kmPlaneNormalize = function(pOut, pP){ - var n = new cc.kmVec3(); + var n = new cc.math.Vec3(); n.x = pP.a; n.y = pP.b; n.z = pP.c; - var l = 1.0 / cc.kmVec3Length(n); //Get 1/length - cc.kmVec3Normalize(n, n); //Normalize the vector and assign to pOut + var l = 1.0 / n.length(); //Get 1/length + n.normalize(); //Normalize the vector and assign to pOut pOut.a = n.x; pOut.b = n.y; pOut.c = n.z; - pOut.d = pP.d * l; //Scale the D value and assign to pOut return pOut; diff --git a/cocos2d/kazmath/quaternion.js b/cocos2d/kazmath/quaternion.js index 1a863f372b..6c7b20ca2b 100644 --- a/cocos2d/kazmath/quaternion.js +++ b/cocos2d/kazmath/quaternion.js @@ -82,7 +82,7 @@ cc.kmQuaternionInverse = function (pOut, pIn) { var l = cc.kmQuaternionLength(pIn); var tmp = new cc.kmQuaternion(); - if (Math.abs(l) > cc.kmEpsilon) { + if (Math.abs(l) > cc.math.EPSILON) { pOut.x = 0.0; pOut.y = 0.0; pOut.z = 0.0; @@ -139,7 +139,7 @@ cc.kmQuaternionMultiply = function (pOut, q1, q2) { ///< Normalizes a quaternion cc.kmQuaternionNormalize = function (pOut, pIn) { var length = cc.kmQuaternionLength(pIn); - if(Math.abs(length) <= cc.kmEpsilon) + if(Math.abs(length) <= cc.math.EPSILON) throw "cc.kmQuaternionNormalize(): pIn is an invalid value"; cc.kmQuaternionScale(pOut, pIn, 1.0 / length); @@ -217,7 +217,7 @@ cc.kmQuaternionRotationMatrix = function (pOut, pIn) { diagonal = pMatrix[0] + pMatrix[5] + pMatrix[10] + 1; - if (diagonal > cc.kmEpsilon) { + if (diagonal > cc.math.EPSILON) { // Calculate the scale of the diagonal scale = Math.sqrt(diagonal) * 2; @@ -275,9 +275,9 @@ cc.kmQuaternionRotationYawPitchRoll = function (pOut, yaw, pitch, roll) { var ex, ey, ez; // temp half euler angles var cr, cp, cy, sr, sp, sy, cpcy, spsy; // temp vars in roll,pitch yaw - ex = cc.kmDegreesToRadians(pitch) / 2.0; // convert to rads and half them - ey = cc.kmDegreesToRadians(yaw) / 2.0; - ez = cc.kmDegreesToRadians(roll) / 2.0; + ex = cc.degreesToRadians(pitch) / 2.0; // convert to rads and half them + ey = cc.degreesToRadians(yaw) / 2.0; + ez = cc.degreesToRadians(roll) / 2.0; cr = Math.cos(ex); cp = Math.cos(ey); @@ -330,7 +330,7 @@ cc.kmQuaternionSlerp = function (pOut, q1, q2, t) { var ct = cc.kmQuaternionDot(q1, q2); var theta = Math.acos(ct); - var st = Math.sqrt(1.0 - cc.kmSQR(ct)); + var st = Math.sqrt(1.0 - cc.math.square(ct)); var stt = Math.sin(t * theta) / st; var somt = Math.sin((1.0 - t) * theta) / st; @@ -349,10 +349,10 @@ cc.kmQuaternionToAxisAngle = function (pIn, pAxis, pAngle) { var scale; // temp vars tempAngle = Math.acos(pIn.w); - scale = Math.sqrt(cc.kmSQR(pIn.x) + cc.kmSQR(pIn.y) + cc.kmSQR(pIn.z)); + scale = Math.sqrt(cc.math.square(pIn.x) + cc.math.square(pIn.y) + cc.math.square(pIn.z)); - if (((scale > -cc.kmEpsilon) && scale < cc.kmEpsilon) - || (scale < 2 * cc.kmPI + cc.kmEpsilon && scale > 2 * cc.kmPI - cc.kmEpsilon)) { // angle is 0 or 360 so just simply set axis to 0,0,1 with angle 0 + if (((scale > -cc.math.EPSILON) && scale < cc.math.EPSILON) + || (scale < 2 * Math.PI + cc.math.EPSILON && scale > 2 * Math.PI - cc.math.EPSILON)) { // angle is 0 or 360 so just simply set axis to 0,0,1 with angle 0 pAngle = 0.0; pAxis.x = 0.0; @@ -364,7 +364,7 @@ cc.kmQuaternionToAxisAngle = function (pIn, pAxis, pAngle) { pAxis.x = pIn.x / scale; pAxis.y = pIn.y / scale; pAxis.z = pIn.z / scale; - cc.kmVec3Normalize(pAxis, pAxis); + pAxis.normalize(); } }; @@ -407,16 +407,10 @@ cc.kmQuaternionAdd = function (pOut, pQ1, pQ2) { ANY axis of rotation is valid. */ cc.kmQuaternionRotationBetweenVec3 = function (pOut, vec1, vec2, fallback) { - var v1 = new cc.kmVec3(), v2 = new cc.kmVec3(); - var a; - - cc.kmVec3Assign(v1, vec1); - cc.kmVec3Assign(v2, vec2); - - cc.kmVec3Normalize(v1, v1); - cc.kmVec3Normalize(v2, v2); - - a = cc.kmVec3Dot(v1, v2); + var v1 = new cc.math.Vec3(vec1), v2 = new cc.math.Vec3(vec2); + v1.normalize(); + v2.normalize(); + var a = v1.dot(v2); if (a >= 1.0) { cc.kmQuaternionIdentity(pOut); @@ -424,40 +418,28 @@ cc.kmQuaternionRotationBetweenVec3 = function (pOut, vec1, vec2, fallback) { } if (a < (1e-6 - 1.0)) { - if (Math.abs(cc.kmVec3LengthSq(fallback)) < cc.kmEpsilon) { - cc.kmQuaternionRotationAxis(pOut, fallback, cc.kmPI); + if (Math.abs(fallback.lengthSq()) < cc.math.EPSILON) { + cc.kmQuaternionRotationAxis(pOut, fallback, Math.PI); } else { - var axis = new cc.kmVec3(); - var X = new cc.kmVec3(); - X.x = 1.0; - X.y = 0.0; - X.z = 0.0; - - cc.kmVec3Cross(axis, X, vec1); + var X = new cc.math.Vec3(1.0, 0.0, 0.0); + var axis = new cc.math.Vec3(X); + axis.cross(vec1); //If axis is zero - if (Math.abs(cc.kmVec3LengthSq(axis)) < cc.kmEpsilon) { - var Y = new cc.kmVec3(); - Y.x = 0.0; - Y.y = 1.0; - Y.z = 0.0; - - cc.kmVec3Cross(axis, Y, vec1); + if (Math.abs(axis.lengthSq()) < cc.math.EPSILON) { + axis.fill(0.0, 1.0, 0.0); + axis.cross(vec1); } - - cc.kmVec3Normalize(axis, axis); - cc.kmQuaternionRotationAxis(pOut, axis, cc.kmPI); + axis.normalize(); + cc.kmQuaternionRotationAxis(pOut, axis, Math.PI); } } else { - var s = Math.sqrt((1 + a) * 2); - var invs = 1 / s; - - var c = new cc.kmVec3(); - cc.kmVec3Cross(c, v1, v2); + var s = Math.sqrt((1 + a) * 2), invs = 1 / s; + v1.cross(v2); - pOut.x = c.x * invs; - pOut.y = c.y * invs; - pOut.z = c.z * invs; + pOut.x = v1.x * invs; + pOut.y = v1.y * invs; + pOut.z = v1.z * invs; pOut.w = s * 0.5; cc.kmQuaternionNormalize(pOut, pOut); @@ -466,21 +448,16 @@ cc.kmQuaternionRotationBetweenVec3 = function (pOut, vec1, vec2, fallback) { }; cc.kmQuaternionMultiplyVec3 = function (pOut, q, v) { - var uv = new cc.kmVec3(), uuv = new cc.kmVec3(), qvec = new cc.kmVec3(); - - qvec.x = q.x; - qvec.y = q.y; - qvec.z = q.z; - - cc.kmVec3Cross(uv, qvec, v); - cc.kmVec3Cross(uuv, qvec, uv); - - cc.kmVec3Scale(uv, uv, (2.0 * q.w)); - cc.kmVec3Scale(uuv, uuv, 2.0); + var uv = new cc.math.Vec3(q), uuv = new cc.math.Vec3(q); + uv.cross(v); + uuv.cross(uv); - cc.kmVec3Add(pOut, v, uv); - cc.kmVec3Add(pOut, pOut, uuv); + uv.scale((2.0 * q.w)); + uuv.scale(2.0); + pOut.fill(v); + pOut.add(uv); + pOut.add(uuv); return pOut; }; diff --git a/cocos2d/kazmath/ray2.js b/cocos2d/kazmath/ray2.js index e9edbcd13d..5a29794e88 100644 --- a/cocos2d/kazmath/ray2.js +++ b/cocos2d/kazmath/ray2.js @@ -26,138 +26,115 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -cc.kmRay2 = function(start, dir){ - this.start = start || new cc.kmVec2(); - this.start = start || new cc.kmVec2(); -}; - -cc.kmRay2Fill = function(ray, px, py,vx,vy){ - ray.start.x = px; - ray.start.y = py; - ray.dir.x = vx; - ray.dir.y = vy; -}; - -cc.kmRay2IntersectLineSegment = function(ray, p1, p2, intersection){ - var x1 = ray.start.x; - var y1 = ray.start.y; - var x2 = ray.start.x + ray.dir.x; - var y2 = ray.start.y + ray.dir.y; - var x3 = p1.x; - var y3 = p1.y; - var x4 = p2.x; - var y4 = p2.y; - - var denom = (y4 -y3) * (x2 - x1) - (x4 - x3) * (y2 - y1); - var ua, x, y; - //If denom is zero, the lines are parallel - if(denom > -cc.kmEpsilon && denom < cc.kmEpsilon) { - return cc.KM_FALSE; - } +(function(cc){ + cc.math.Ray2 = function (start, dir) { // = cc.kmRay2 + this.start = start || new cc.math.Vec2(); + this.dir = dir || new cc.math.Vec2(); + }; + + cc.math.Ray2.prototype.fill = function (px, py, vx, vy) { // = cc.kmRay2Fill + this.start.x = px; + this.start.y = py; + this.dir.x = vx; + this.dir.y = vy; + }; + + cc.math.Ray2.prototype.intersectLineSegment = function (p1, p2, intersection) { // = cc.kmRay2IntersectLineSegment + var x1 = this.start.x, y1 = this.start.y; + var x2 = this.start.x + this.dir.x, y2 = this.start.y + this.dir.y; + var x3 = p1.x, y3 = p1.y; + var x4 = p2.x, y4 = p2.y; + + var denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1); + var ua, x, y; + //If denom is zero, the lines are parallel + if (denom > -cc.math.EPSILON && denom < cc.math.EPSILON) + return false; + + ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / denom; + //var ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / denom; + + x = x1 + ua * (x2 - x1); + y = y1 + ua * (y2 - y1); + + if (x < Math.min(p1.x, p2.x) - cc.math.EPSILON || + x > Math.max(p1.x, p2.x) + cc.math.EPSILON || + y < Math.min(p1.y, p2.y) - cc.math.EPSILON || + y > Math.max(p1.y, p2.y) + cc.math.EPSILON) { + //Outside of line + //printf("Outside of line, %f %f (%f %f)(%f, %f)\n", x, y, p1.x, p1.y, p2.x, p2.y); + return false; + } - ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / denom; -// var ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / denom; + if (x < Math.min(x1, x2) - cc.math.EPSILON || + x > Math.max(x1, x2) + cc.math.EPSILON || + y < Math.min(y1, y2) - cc.math.EPSILON || + y > Math.max(y1, y2) + cc.math.EPSILON) { + //printf("Outside of ray, %f %f (%f %f)(%f, %f)\n", x, y, x1, y1, x2, y2); + return false; + } - x = x1 + ua * (x2 - x1); - y = y1 + ua * (y2 - y1); + intersection.x = x; + intersection.y = y; + return true; + }; - if(x < cc.kmMin(p1.x, p2.x) - cc.kmEpsilon || - x > cc.kmMax(p1.x, p2.x) + cc.kmEpsilon || - y < cc.kmMin(p1.y, p2.y) - cc.kmEpsilon || - y > cc.kmMax(p1.y, p2.y) + cc.kmEpsilon) { - //Outside of line - //printf("Outside of line, %f %f (%f %f)(%f, %f)\n", x, y, p1.x, p1.y, p2.x, p2.y); - return cc.KM_FALSE; - } + function calculate_line_normal(p1, p2, normalOut){ + var tmp = new cc.math.Vec2(p2); + tmp.subtract(p1); - if(x < cc.kmMin(x1, x2) - cc.kmEpsilon || - x > cc.kmMax(x1, x2) + cc.kmEpsilon || - y < cc.kmMin(y1, y2) - cc.kmEpsilon || - y > cc.kmMax(y1, y2) + cc.kmEpsilon) { - //printf("Outside of ray, %f %f (%f %f)(%f, %f)\n", x, y, x1, y1, x2, y2); - return cc.KM_FALSE; + normalOut.x = -tmp.y; + normalOut.y = tmp.x; + normalOut.normalize(); + //TODO: should check that the normal is pointing out of the triangle } - intersection.x = x; - intersection.y = y; - - return cc.KM_TRUE; -}; - -cc.calculate_line_normal = function(p1, p2, normal_out){ - var tmp = new cc.kmVec2(); - cc.kmVec2Subtract(tmp, p2, p1); //Get direction vector - - normal_out.x = -tmp.y; - normal_out.y = tmp.x; - cc.kmVec2Normalize(normal_out, normal_out); - - //TODO: should check that the normal is pointing out of the triangle -}; - -cc.kmRay2IntersectTriangle = function(ray, p1, p2, p3, intersection, normal_out){ - var intersect = new cc.kmVec2(); - var final_intersect = new cc.kmVec2(); - var normal = new cc.kmVec2(); - var distance = 10000.0; - var intersected = cc.KM_FALSE; - - var tmp,this_distance; - - if(cc.kmRay2IntersectLineSegment(ray, p1, p2, intersect)) { - tmp = new cc.kmVec2(); - - intersected = cc.KM_TRUE; - this_distance = cc.kmVec2Length(cc.kmVec2Subtract(tmp, intersect, ray.start)); - if(this_distance < distance) { - final_intersect.x = intersect.x; - final_intersect.y = intersect.y; - distance = this_distance; - - cc.calculate_line_normal(p1, p2, normal); + cc.math.Ray2.prototype.intersectTriangle = function(p1, p2, p3, intersection, normal_out){ + var intersect = new cc.math.Vec2(), final_intersect = new cc.math.Vec2(); + var normal = new cc.math.Vec2(), distance = 10000.0, intersected = false; + var this_distance; + + if(this.intersectLineSegment(p1, p2, intersect)) { + intersected = true; + this_distance = intersect.subtract(this.start).length(); + if(this_distance < distance) { + final_intersect.x = intersect.x; + final_intersect.y = intersect.y; + distance = this_distance; + calculate_line_normal(p1, p2, normal); + } } - } - - if(cc.kmRay2IntersectLineSegment(ray, p2, p3, intersect)) { - tmp = new cc.kmVec2(); - intersected = cc.KM_TRUE; - this_distance = cc.kmVec2Length(cc.kmVec2Subtract(tmp, intersect, ray.start)); - if(this_distance < distance) { - final_intersect.x = intersect.x; - final_intersect.y = intersect.y; - distance = this_distance; - - cc.calculate_line_normal(p2, p3, normal); + if(this.intersectLineSegment(p2, p3, intersect)) { + intersected = true; + this_distance = intersect.subtract(this.start).length(); + if(this_distance < distance) { + final_intersect.x = intersect.x; + final_intersect.y = intersect.y; + distance = this_distance; + calculate_line_normal(p2, p3, normal); + } } - } - - if(cc.kmRay2IntersectLineSegment(ray, p3, p1, intersect)) { - tmp = new cc.kmVec2(); - intersected = cc.KM_TRUE; - this_distance = cc.kmVec2Length(cc.kmVec2Subtract(tmp, intersect, ray.start)); - if(this_distance < distance) { - final_intersect.x = intersect.x; - final_intersect.y = intersect.y; - distance = this_distance; - - cc.calculate_line_normal(p3, p1, normal); + if(this.intersectLineSegment(p3, p1, intersect)) { + intersected = true; + this_distance = intersect.subtract(this.start).length(); + if(this_distance < distance) { + final_intersect.x = intersect.x; + final_intersect.y = intersect.y; + distance = this_distance; + calculate_line_normal(p3, p1, normal); + } } - } - if(intersected) { - intersection.x = final_intersect.x; - intersection.y = final_intersect.y; - if(normal_out) { - normal_out.x = normal.x; - normal_out.y = normal.y; + if(intersected) { + intersection.x = final_intersect.x; + intersection.y = final_intersect.y; + if(normal_out) { + normal_out.x = normal.x; + normal_out.y = normal.y; + } } - } - - return intersected; -}; - -cc.kmRay2IntersectCircle = function(ray, centre, radius, intersection) { - cc.log("cc.kmRay2IntersectCircle() has not been implemented."); -}; \ No newline at end of file + return intersected; + }; +})(cc); diff --git a/cocos2d/kazmath/utility.js b/cocos2d/kazmath/utility.js index 4f1d8153c7..9cd3fb4c71 100644 --- a/cocos2d/kazmath/utility.js +++ b/cocos2d/kazmath/utility.js @@ -26,51 +26,29 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + /** - * @ignore + *

The main namespace of Cocos2d-html5's math library,
+ * all math core classes, functions, properties and constants are defined in this namespace

+ * @namespace + * @name cc.math */ -cc.kmScalar = Number; - -cc.kmBool = Number; - -cc.kmEnum = Number; - -cc.KM_FALSE = 0; +cc.math = cc.math || {}; -cc.KM_TRUE = 1; +//cc.kmPIOver180 = 0.017453; please use cc.RAD -cc.kmPI = 3.141592; +//cc.kmPIUnder180 = 57.295779; please use cc.DEG -cc.kmPIOver180 = 0.017453; - -cc.kmPIUnder180 = 57.295779; - -cc.kmEpsilon = 1.0 / 64.0; +cc.math.EPSILON = 1.0 / 64.0; //cc.kmEpsilon /** * Returns the square of s (e.g. s*s) * @param {Number} s */ -cc.kmSQR = function(s){ +cc.math.square = function(s){ return s*s; }; -cc.kmDegreesToRadians = function(degrees){ - return degrees * cc.kmPIOver180; -}; - -cc.kmRadiansToDegrees = function(radians){ - return radians * cc.kmPIUnder180; -}; - -cc.kmMin = function(lhs,rhs){ - return (lhs < rhs)? lhs : rhs; -}; - -cc.kmMax = function(lhs,rhs){ - return (lhs > rhs)? lhs : rhs; -}; - -cc.kmAlmostEqual = function(lhs,rhs){ - return (lhs + cc.kmEpsilon > rhs && lhs - cc.kmEpsilon < rhs); +cc.math.almostEqual = function(lhs,rhs){ + return (lhs + cc.math.EPSILON > rhs && lhs - cc.math.EPSILON < rhs); }; diff --git a/cocos2d/kazmath/vec2.js b/cocos2d/kazmath/vec2.js index 888b234bf1..a682bc4853 100644 --- a/cocos2d/kazmath/vec2.js +++ b/cocos2d/kazmath/vec2.js @@ -26,82 +26,88 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -cc.kmVec2 = function (x, y) { - this.x = x || 0; - this.y = y || 0; -}; +(function(cc){ + cc.math.Vec2 = function (x, y) { + if(y === undefined){ + this.x = x.x; + this.y = x.y; + }else{ + this.x = x || 0; + this.y = y || 0; + } + }; + + var proto = cc.math.Vec2.prototype; + proto.fill = function(x, y){ // = cc.kmVec2Fill + this.x = x; + this.y = y; + }; + + proto.length = function(){ // = cc.kmVec2Length + return Math.sqrt(cc.math.square(this.x) + cc.math.square(this.y)); + }; + + proto.lengthSq = function(){ // = cc.kmVec2LengthSq + return cc.math.square(this.x) + cc.math.square(this.y); + }; + + proto.normalize = function(){ // = cc.kmVec2Normalize + var l = 1.0 / this.length(); + this.x *= l; + this.y *= l; + return this; + }; + + cc.math.Vec2.add = function (pOut, pV1, pV2) { // = cc.kmVec2Add + pOut.x = pV1.x + pV2.x; + pOut.y = pV1.y + pV2.y; + return pOut + }; + + proto.add = function(vec){ // = cc.kmVec2Add + this.x += vec.x; + this.y += vec.y; + return this; + }; + + proto.dot = function (vec) { //cc.kmVec2Dot + return this.x * vec.x + this.y * vec.y; + }; + + cc.math.Vec2.subtract = function (pOut, pV1, pV2) { // = cc.kmVec2Subtract + pOut.x = pV1.x - pV2.x; + pOut.y = pV1.y - pV2.y; + return pOut; + }; + + proto.subtract = function(vec){ // = cc.kmVec2Subtract + this.x -= vec.x; + this.y -= vec.y; + return this; + }; + + proto.transform = function (mat3) { // = cc.kmVec2Transform + var x = this.x, y = this.y; + this.x = x * mat3.mat[0] + y * mat3.mat[3] + mat3.mat[6]; + this.y = x * mat3.mat[1] + y * mat3.mat[4] + mat3.mat[7]; + return this; + }; + + cc.math.Vec2.scale = function (pOut, pIn, s) { // = cc.kmVec2Scale + pOut.x = pIn.x * s; + pOut.y = pIn.y * s; + return pOut; + }; + + proto.scale = function(s) { // = cc.kmVec2Scale + this.x *= s; + this.y *= s; + return this; + }; + + proto.equals = function (vec) { // = cc.kmVec2AreEqual + return (this.x < vec.x + cc.math.EPSILON && this.x > vec.x - cc.math.EPSILON) && + (this.y < vec.y + cc.math.EPSILON && this.y > vec.y - cc.math.EPSILON); + }; +})(cc); -cc.kmVec2Fill = function (pOut, x, y) { - pOut.x = x; - pOut.y = y; - return pOut; -}; - -cc.kmVec2Length = function (pIn) { - return Math.sqrt(cc.kmSQR(pIn.x) + cc.kmSQR(pIn.y)); -}; - -cc.kmVec2LengthSq = function (pIn) { - return cc.kmSQR(pIn.x) + cc.kmSQR(pIn.y); -}; - -cc.kmVec2Normalize = function (pOut, pIn) { - var l = 1.0 / cc.kmVec2Length(pIn); - - var v = new cc.kmVec2(); - v.x = pIn.x * l; - v.y = pIn.y * l; - - pOut.x = v.x; - pOut.y = v.y; - - return pOut; -}; - -cc.kmVec2Add = function (pOut, pV1, pV2) { - pOut.x = pV1.x + pV2.x; - pOut.y = pV1.y + pV2.y; - - return pOut -}; - -cc.kmVec2Dot = function (pV1, pV2) { - return pV1.x * pV2.x + pV1.y * pV2.y; -}; - -cc.kmVec2Subtract = function (pOut, pV1, pV2) { - pOut.x = pV1.x - pV2.x; - pOut.y = pV1.y - pV2.y; - - return pOut; -}; - -cc.kmVec2Transform = function (pOut, pV, pM) { - var v= new cc.kmVec2(); - - v.x = pV.x * pM.mat[0] + pV.y * pM.mat[3] + pM.mat[6]; - v.y = pV.x * pM.mat[1] + pV.y * pM.mat[4] + pM.mat[7]; - - pOut.x = v.x; - pOut.y = v.y; - - return pOut; -}; - -cc.kmVec2TransformCoord = function (pOut, pV, pM) { - return null; -}; - -cc.kmVec2Scale = function (pOut, pIn, s) { - pOut.x = pIn.x * s; - pOut.y = pIn.y * s; - - return pOut; -}; - -cc.kmVec2AreEqual = function (p1, p2) { - return ( - (p1.x < p2.x + cc.kmEpsilon && p1.x > p2.x - cc.kmEpsilon) && - (p1.y < p2.y + cc.kmEpsilon && p1.y > p2.y - cc.kmEpsilon) - ); -}; diff --git a/cocos2d/kazmath/vec3.js b/cocos2d/kazmath/vec3.js index 07dc0fb4ea..77fd12f3da 100644 --- a/cocos2d/kazmath/vec3.js +++ b/cocos2d/kazmath/vec3.js @@ -26,173 +26,169 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -cc.kmVec3 = function (x, y, z) { - this.x = x || 0; - this.y = y || 0; - this.z = z || 0; -}; - -cc.kmVec3Fill = function(pOut, x, y , z){ - if(!pOut) - return new cc.kmVec3(x, y , z); - pOut.x = x; - pOut.y = y; - pOut.z = z; - return pOut; -}; - -cc.kmVec3Length = function(pIn){ - return Math.sqrt(cc.kmSQR(pIn.x) + cc.kmSQR(pIn.y) + cc.kmSQR(pIn.z)); -}; - -cc.kmVec3LengthSq = function(pIn){ - return cc.kmSQR(pIn.x) + cc.kmSQR(pIn.y) + cc.kmSQR(pIn.z) -} ; - -cc.kmVec3Normalize = function(pOut,pIn){ - var l = 1.0 / cc.kmVec3Length(pIn); - - pOut.x = pIn.x * l; - pOut.y = pIn.y * l; - pOut.z = pIn.z * l; - return pOut; -}; - -cc.kmVec3Cross = function(pOut, pV1,pV2){ - pOut.x = (pV1.y * pV2.z) - (pV1.z * pV2.y); - pOut.y = (pV1.z * pV2.x) - (pV1.x * pV2.z); - pOut.z = (pV1.x * pV2.y) - (pV1.y * pV2.x); - return pOut; -}; - -cc.kmVec3Dot = function(pV1, pV2){ - return ( pV1.x * pV2.x - + pV1.y * pV2.y - + pV1.z * pV2.z ); -} ; - -cc.kmVec3Add = function(pOut, pV1, pV2){ - pOut.x = pV1.x + pV2.x; - pOut.y = pV1.y + pV2.y; - pOut.z = pV1.z + pV2.z; - return pOut; -}; - -cc.kmVec3Subtract = function(pOut, pV1, pV2){ - pOut.x = pV1.x - pV2.x; - pOut.y = pV1.y - pV2.y; - pOut.z = pV1.z - pV2.z; - return pOut; -}; - -cc.kmVec3Transform = function(pOut, pV, pM){ - /* - a = (Vx, Vy, Vz, 1) - b = (a×M)T - Out = (bx, by, bz) - */ - pOut.x = pV.x * pM.mat[0] + pV.y * pM.mat[4] + pV.z * pM.mat[8] + pM.mat[12]; - pOut.y = pV.x * pM.mat[1] + pV.y * pM.mat[5] + pV.z * pM.mat[9] + pM.mat[13]; - pOut.z = pV.x * pM.mat[2] + pV.y * pM.mat[6] + pV.z * pM.mat[10] + pM.mat[14]; - return pOut; -}; - -cc.kmVec3TransformNormal = function(pOut, pV, pM){ - /* - a = (Vx, Vy, Vz, 0) - b = (a×M)T - Out = (bx, by, bz) - */ - //Omits the translation, only scaling + rotating - pOut.x = pV.x * pM.mat[0] + pV.y * pM.mat[4] + pV.z * pM.mat[8]; - pOut.y = pV.x * pM.mat[1] + pV.y * pM.mat[5] + pV.z * pM.mat[9]; - pOut.z = pV.x * pM.mat[2] + pV.y * pM.mat[6] + pV.z * pM.mat[10]; - return pOut; -}; - -cc.kmVec3TransformCoord = function(pOut,pV,pM){ - /* - a = (Vx, Vy, Vz, 1) - b = (a×M)T - Out = 1⁄bw(bx, by, bz) - */ - var v = new cc.kmVec4(); - var inV = new cc.kmVec4(); - cc.kmVec4Fill(inV, pV.x, pV.y, pV.z, 1.0); - - cc.kmVec4Transform(v, inV,pM); - - pOut.x = v.x / v.w; - pOut.y = v.y / v.w; - pOut.z = v.z / v.w; - - return pOut; -}; - -cc.kmVec3Scale = function(pOut, pIn, s){ - pOut.x = pIn.x * s; - pOut.y = pIn.y * s; - pOut.z = pIn.z * s; - - return pOut; -}; - -cc.kmVec3AreEqual = function(p1, p2){ - if ((p1.x < (p2.x + cc.kmEpsilon) && p1.x > (p2.x - cc.kmEpsilon)) && - (p1.y < (p2.y + cc.kmEpsilon) && p1.y > (p2.y - cc.kmEpsilon)) && - (p1.z < (p2.z + cc.kmEpsilon) && p1.z > (p2.z - cc.kmEpsilon))) { - return 1; - } - - return 0; -}; - -cc.kmVec3InverseTransform = function(pOut, pVect,pM){ - var v1 = new cc.kmVec3(pVect.x - pM.mat[12], pVect.y - pM.mat[13],pVect.z - pM.mat[14]); - - pOut.x = v1.x * pM.mat[0] + v1.y * pM.mat[1] + v1.z * pM.mat[2]; - pOut.y = v1.x * pM.mat[4] + v1.y * pM.mat[5] + v1.z * pM.mat[6]; - pOut.z = v1.x * pM.mat[8] + v1.y * pM.mat[9] + v1.z * pM.mat[10]; - - return pOut; -}; - -cc.kmVec3InverseTransformNormal = function(pOut, pVect, pM){ - pOut.x = pVect.x * pM.mat[0] + pVect.y * pM.mat[1] + pVect.z * pM.mat[2]; - pOut.y = pVect.x * pM.mat[4] + pVect.y * pM.mat[5] + pVect.z * pM.mat[6]; - pOut.z = pVect.x * pM.mat[8] + pVect.y * pM.mat[9] + pVect.z * pM.mat[10]; - - return pOut; -}; - -cc.kmVec3Assign = function(pOut,pIn){ - if (pOut == pIn) - return pOut; - - pOut.x = pIn.x; - pOut.y = pIn.y; - pOut.z = pIn.z; - return pOut; -}; - -cc.kmVec3Zero = function(pOut){ - pOut.x = 0.0; - pOut.y = 0.0; - pOut.z = 0.0; - - return pOut; -}; - -cc.kmVec3ToTypeArray = function(vecValue){ - if(!vecValue) - return null; - - var tyArr = new Float32Array(3); - tyArr[0] = vecValue.x; - tyArr[1] = vecValue.y; - tyArr[2] = vecValue.z; - return tyArr; -}; +(function(cc) { + cc.kmVec3 = cc.math.Vec3 = function (x, y, z) { + if(y === undefined){ + this.x = x.x; + this.y = x.y; + this.z = x.z; + } else { + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; + } + }; + + var proto = cc.math.Vec3.prototype; + + proto.fill = function (x, y, z) { // =cc.kmVec3Fill + if (y === undefined) { + this.x = x.x; + this.y = x.y; + this.z = x.z; + } else { + this.x = x; + this.y = y; + this.z = z; + } + return this; + }; + + proto.length = function () { //=cc.kmVec3Length + return Math.sqrt(cc.math.square(this.x) + cc.math.square(this.y) + cc.math.square(this.z)); + }; + + proto.lengthSq = function () { //=cc.kmVec3LengthSq + return cc.math.square(this.x) + cc.math.square(this.y) + cc.math.square(this.z) + }; + + proto.normalize = function () { //= cc.kmVec3Normalize + var l = 1.0 / this.length(); + this.x *= l; + this.y *= l; + this.z *= l; + return this; + }; + + proto.cross = function (vec3) { //= cc.kmVec3Cross + var x = this.x, y = this.y, z = this.z; + this.x = (y * vec3.z) - (z * vec3.y); + this.y = (z * vec3.x) - (x * vec3.z); + this.z = (x * vec3.y) - (y * vec3.x); + return this; + }; + + proto.dot = function (vec) { //= cc.kmVec3Dot + return ( this.x * vec.x + this.y * vec.y + this.z * vec.z ); + }; + + proto.add = function(vec){ //= cc.kmVec3Add + this.x += vec.x; + this.y += vec.y; + this.z += vec.z; + return this; + }; + + proto.subtract = function (vec) { // = cc.kmVec3Subtract + this.x -= vec.x; + this.y -= vec.y; + this.z -= vec.z; + return this; + }; + + proto.transform = function (mat4) { // = cc.kmVec3Transform + var x = this.x, y = this.y, z = this.z, mat = mat4.mat; + this.x = x * mat[0] + y * mat[4] + z * mat[8] + mat[12]; + this.y = x * mat[1] + y * mat[5] + z * mat[9] + mat[13]; + this.z = x * mat[2] + y * mat[6] + z * mat[10] + mat[14]; + return this; + }; + + proto.transformNormal = function(mat4){ + /* + a = (Vx, Vy, Vz, 0) + b = (a×M)T + Out = (bx, by, bz) + */ + //Omits the translation, only scaling + rotating + var x = this.x, y = this.y, z = this.z, mat = mat4.mat; + this.x = x * mat[0] + y * mat[4] + z * mat[8]; + this.y = x * mat[1] + y * mat[5] + z * mat[9]; + this.z = x * mat[2] + y * mat[6] + z * mat[10]; + return this; + }; + + proto.transformCoord = function(mat4){ // = cc.kmVec3TransformCoord + /* + a = (Vx, Vy, Vz, 1) + b = (a×M)T + Out = 1⁄bw(bx, by, bz) + */ + var v = new cc.kmVec4(); + var inV = new cc.kmVec4(); + cc.kmVec4Fill(inV, this.x, this.y, this.z, 1.0); + cc.kmVec4Transform(v, inV, mat4); + this.x = v.x / v.w; + this.y = v.y / v.w; + this.z = v.z / v.w; + return this; + }; + + proto.scale = function(scale){ // = cc.kmVec3Scale + this.x *= scale; + this.y *= scale; + this.z *= scale; + return this; + }; + + proto.equals = function(vec){ // = cc.kmVec3AreEqual + var EPSILON = cc.math.EPSILON; + return (this.x < (vec.x + EPSILON) && this.x > (vec.x - EPSILON)) && + (this.y < (vec.y + EPSILON) && this.y > (vec.y - EPSILON)) && + (this.z < (vec.z + EPSILON) && this.z > (vec.z - EPSILON)); + }; + + proto.inverseTransform = function(mat4){ //= cc.kmVec3InverseTransform + var mat = mat4.mat; + var v1 = new cc.math.Vec3(this.x - mat[12], this.y - mat[13], this.z - mat[14]); + this.x = v1.x * mat[0] + v1.y * mat[1] + v1.z * mat[2]; + this.y = v1.x * mat[4] + v1.y * mat[5] + v1.z * mat[6]; + this.z = v1.x * mat[8] + v1.y * mat[9] + v1.z * mat[10]; + return this; + }; + + proto.inverseTransformNormal = function(mat4){ // = cc.kmVec3InverseTransformNormal + var x = this.x, y = this.y, z = this.z, mat = mat4.mat; + this.x = x * mat[0] + y * mat[1] + z * mat[2]; + this.y = x * mat[4] + y * mat[5] + z * mat[6]; + this.z = x * mat[8] + y * mat[9] + z * mat[10]; + return this; + }; + + proto.assign = function(vec){ + if(!vec) + return this; + this.x = vec.x; + this.y = vec.y; + this.z = vec.z; + return this; + }; + + cc.math.Vec3.zero = function(vec){ // = cc.kmVec3Zero + vec.x = vec.y = vec.z = 0.0; + return vec; + }; + + cc.mat.Vec3.toTypeArray = function(vec){ //cc.kmVec3ToTypeArray + if(!vec) + return null; + var tyArr = new Float32Array(3); + tyArr[0] = vec.x; + tyArr[1] = vec.y; + tyArr[2] = vec.z; + return tyArr; + }; +})(cc); diff --git a/cocos2d/kazmath/vec4.js b/cocos2d/kazmath/vec4.js index 9712743fff..20c8c78118 100644 --- a/cocos2d/kazmath/vec4.js +++ b/cocos2d/kazmath/vec4.js @@ -59,11 +59,11 @@ cc.kmVec4Dot = function( vec1, vec2){ }; cc.kmVec4Length = function(inVec){ - return Math.sqrt(cc.kmSQR(inVec.x) + cc.kmSQR(inVec.y) + cc.kmSQR(inVec.z) + cc.kmSQR(inVec.w)); + return Math.sqrt(cc.math.square(inVec.x) + cc.math.square(inVec.y) + cc.math.square(inVec.z) + cc.math.square(inVec.w)); }; cc.kmVec4LengthSq = function(inVec){ - return cc.kmSQR(inVec.x) + cc.kmSQR(inVec.y) + cc.kmSQR(inVec.z) + cc.kmSQR(inVec.w); + return cc.math.square(inVec.x) + cc.math.square(inVec.y) + cc.math.square(inVec.z) + cc.math.square(inVec.w); }; cc.kmVec4Lerp = function(outVec, pV1, pV2, t){ @@ -123,10 +123,10 @@ cc.kmVec4TransformArray = function(outVec,outStride,vecObj,stride,mat4Obj,count) cc.kmVec4AreEqual = function(vec1,vec2){ return ( - (vec1.x < vec2.x + cc.kmEpsilon && vec1.x > vec2.x - cc.kmEpsilon) && - (vec1.y < vec2.y + cc.kmEpsilon && vec1.y > vec2.y - cc.kmEpsilon) && - (vec1.z < vec2.z + cc.kmEpsilon && vec1.z > vec2.z - cc.kmEpsilon) && - (vec1.w < vec2.w + cc.kmEpsilon && vec1.w > vec2.w - cc.kmEpsilon) + (vec1.x < vec2.x + cc.math.EPSILON && vec1.x > vec2.x - cc.math.EPSILON) && + (vec1.y < vec2.y + cc.math.EPSILON && vec1.y > vec2.y - cc.math.EPSILON) && + (vec1.z < vec2.z + cc.math.EPSILON && vec1.z > vec2.z - cc.math.EPSILON) && + (vec1.w < vec2.w + cc.math.EPSILON && vec1.w > vec2.w - cc.math.EPSILON) ); }; From 6d56bfb25462ba8ea6ebb6936a79bdeecd5b4fc2 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Mon, 9 Mar 2015 13:45:30 +0800 Subject: [PATCH 0035/1039] Fixed : Added addImageAsync to cc.textureCache. --- cocos2d/core/textures/CCTextureCache.js | 1 + cocos2d/core/textures/TexturesWebGL.js | 4 +++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/textures/CCTextureCache.js b/cocos2d/core/textures/CCTextureCache.js index a32929ffbf..ad24eea7d9 100644 --- a/cocos2d/core/textures/CCTextureCache.js +++ b/cocos2d/core/textures/CCTextureCache.js @@ -362,6 +362,7 @@ if (cc._renderType === cc._RENDER_TYPE_CANVAS) { return tex; }; + _p.addImageAsync = _p.addImage; _p = null; } else { diff --git a/cocos2d/core/textures/TexturesWebGL.js b/cocos2d/core/textures/TexturesWebGL.js index 7f838f0609..b1667ed971 100644 --- a/cocos2d/core/textures/TexturesWebGL.js +++ b/cocos2d/core/textures/TexturesWebGL.js @@ -901,5 +901,7 @@ cc._tmp.WebGLTextureCache = function () { return tex; }; - _p = null; + + _p.addImageAsync = _p.addImage; + _p = null; }; From 2be3a494916b21cc57316b96585daa22b3c67253 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Tue, 10 Mar 2015 14:00:26 +0800 Subject: [PATCH 0036/1039] Issue #2698: refactor the math library and remove the unuse function from cc namespace. --- cocos2d/kazmath/gl/matrix.js | 1 - cocos2d/kazmath/mat3.js | 603 +++++++++++++------------ cocos2d/kazmath/mat4.js | 21 +- cocos2d/kazmath/plane.js | 228 +++++----- cocos2d/kazmath/quaternion.js | 823 +++++++++++++++++----------------- cocos2d/kazmath/vec3.js | 20 +- cocos2d/kazmath/vec4.js | 258 +++++------ 7 files changed, 964 insertions(+), 990 deletions(-) diff --git a/cocos2d/kazmath/gl/matrix.js b/cocos2d/kazmath/gl/matrix.js index 97b0134faf..0431721b7c 100644 --- a/cocos2d/kazmath/gl/matrix.js +++ b/cocos2d/kazmath/gl/matrix.js @@ -151,7 +151,6 @@ cc.kmGLScalef = function (x, y, z) { cc.kmGLGetMatrix = function (mode, pOut) { //cc.lazyInitialize(); - switch (mode) { case cc.KM_GL_MODELVIEW: cc.kmMat4Assign(pOut, cc.modelview_matrix_stack.top); diff --git a/cocos2d/kazmath/mat3.js b/cocos2d/kazmath/mat3.js index 565df74a6f..87c11a4871 100644 --- a/cocos2d/kazmath/mat3.js +++ b/cocos2d/kazmath/mat3.js @@ -27,301 +27,320 @@ */ var Float32Array = Float32Array || Array; - -cc.kmMat3 = function () { - this.mat = new Float32Array([0, 0, 0, - 0, 0, 0, - 0, 0, 0]); -}; - -cc.kmMat3Fill = function (pOut, pMat) { - for (var i = 0; i < 9; i++) { - pOut.mat[i] = pMat; - } - return pOut; -}; - -cc.kmMat3Adjugate = function (pOut, pIn) { - pOut.mat[0] = pIn.mat[4] * pIn.mat[8] - pIn.mat[5] * pIn.mat[7]; - pOut.mat[1] = pIn.mat[2] * pIn.mat[7] - pIn.mat[1] * pIn.mat[8]; - pOut.mat[2] = pIn.mat[1] * pIn.mat[5] - pIn.mat[2] * pIn.mat[4]; - pOut.mat[3] = pIn.mat[5] * pIn.mat[6] - pIn.mat[3] * pIn.mat[8]; - pOut.mat[4] = pIn.mat[0] * pIn.mat[8] - pIn.mat[2] * pIn.mat[6]; - pOut.mat[5] = pIn.mat[2] * pIn.mat[3] - pIn.mat[0] * pIn.mat[5]; - pOut.mat[6] = pIn.mat[3] * pIn.mat[7] - pIn.mat[4] * pIn.mat[6]; - - // XXX: pIn.mat[9] is invalid! -// pOut.mat[7] = pIn.mat[1] * pIn.mat[6] - pIn.mat[9] * pIn.mat[7]; - pOut.mat[8] = pIn.mat[0] * pIn.mat[4] - pIn.mat[1] * pIn.mat[3]; - - return pOut; -}; - -cc.kmMat3Identity = function (pOut) { - pOut.mat[1] = pOut.mat[2] = pOut.mat[3] = - pOut.mat[5] = pOut.mat[6] = pOut.mat[7] = 0; - pOut.mat[0] = pOut.mat[4] = pOut.mat[8] = 1.0; - return pOut; -}; - -cc.kmMat3Inverse = function (pOut, pDeterminate, pM) { - var detInv; - var adjugate = new cc.kmMat3(); - - if (pDeterminate === 0.0) - return null; - - detInv = 1.0 / pDeterminate; - - cc.kmMat3Adjugate(adjugate, pM); - cc.kmMat3ScalarMultiply(pOut, adjugate, detInv); - - return pOut; -}; - -cc.kmMat3._identity = - new Float32Array([1.0, 0.0, 0.0, - 0.0, 1.0, 0.0, - 0.0, 0.0, 1.0]); - -cc.kmMat3IsIdentity = function (pIn) { - for (var i = 0; i < 9; i++) { - if (cc.kmMat3._identity[i] !== pIn.mat[i]) - return false; - } - return true; -}; - -cc.kmMat3Transpose = function (pOut, pIn) { - var z, x; - for (z = 0; z < 3; ++z) { - for (x = 0; x < 3; ++x) - pOut.mat[(z * 3) + x] = pIn.mat[(x * 3) + z]; - } - - return pOut; -}; - -cc.kmMat3Determinant = function (pIn) { - var output; - /* - calculating the determinant following the rule of sarus, - | 0 3 6 | 0 3 | - m = | 1 4 7 | 1 4 | - | 2 5 8 | 2 5 | - now sum up the products of the diagonals going to the right (i.e. 0,4,8) - and substract the products of the other diagonals (i.e. 2,4,6) - */ - - output = pIn.mat[0] * pIn.mat[4] * pIn.mat[8] + pIn.mat[1] * pIn.mat[5] * pIn.mat[6] + pIn.mat[2] * pIn.mat[3] * pIn.mat[7]; - output -= pIn.mat[2] * pIn.mat[4] * pIn.mat[6] + pIn.mat[0] * pIn.mat[5] * pIn.mat[7] + pIn.mat[1] * pIn.mat[3] * pIn.mat[8]; - - return output; -}; - -cc.kmMat3Multiply = function (pOut, pM1, pM2) { - var m1 = pM1.mat, m2 = pM2.mat; - - pOut.mat[0] = m1[0] * m2[0] + m1[3] * m2[1] + m1[6] * m2[2]; - pOut.mat[1] = m1[1] * m2[0] + m1[4] * m2[1] + m1[7] * m2[2]; - pOut.mat[2] = m1[2] * m2[0] + m1[5] * m2[1] + m1[8] * m2[2]; - - pOut.mat[3] = m1[0] * m2[3] + m1[3] * m2[4] + m1[6] * m2[5]; - pOut.mat[4] = m1[1] * m2[3] + m1[4] * m2[4] + m1[7] * m2[5]; - pOut.mat[5] = m1[2] * m2[3] + m1[5] * m2[4] + m1[8] * m2[5]; - - pOut.mat[6] = m1[0] * m2[6] + m1[3] * m2[7] + m1[6] * m2[8]; - pOut.mat[7] = m1[1] * m2[6] + m1[4] * m2[7] + m1[7] * m2[8]; - pOut.mat[8] = m1[2] * m2[6] + m1[5] * m2[7] + m1[8] * m2[8]; - - return pOut; -}; - -cc.kmMat3ScalarMultiply = function (pOut, pM, pFactor) { - for (var i = 0; i < 9; i++) { - pOut.mat[i] = pM.mat[i] * pFactor; - } - return pOut; -}; - -cc.kmMat3RotationAxisAngle = function (pOut, axis, radians) { - var rcos = Math.cos(radians); - var rsin = Math.sin(radians); - - pOut.mat[0] = rcos + axis.x * axis.x * (1 - rcos); - pOut.mat[1] = axis.z * rsin + axis.y * axis.x * (1 - rcos); - pOut.mat[2] = -axis.y * rsin + axis.z * axis.x * (1 - rcos); - - pOut.mat[3] = -axis.z * rsin + axis.x * axis.y * (1 - rcos); - pOut.mat[4] = rcos + axis.y * axis.y * (1 - rcos); - pOut.mat[5] = axis.x * rsin + axis.z * axis.y * (1 - rcos); - - pOut.mat[6] = axis.y * rsin + axis.x * axis.z * (1 - rcos); - pOut.mat[7] = -axis.x * rsin + axis.y * axis.z * (1 - rcos); - pOut.mat[8] = rcos + axis.z * axis.z * (1 - rcos); - - return pOut; -}; - -cc.kmMat3Assign = function (pOut, pIn) { - if(pOut == pIn) { - cc.log("cc.kmMat3Assign(): pOut equals pIn"); - return pOut; - } - - for (var i = 0; i < 9; i++) - pOut.mat[i] = pIn.mat[i]; - return pOut; -}; - -cc.kmMat3AreEqual = function (pMat1, pMat2) { - if (pMat1 == pMat2) - return true; - - for (var i = 0; i < 9; ++i) { - if (!(pMat1.mat[i] + cc.math.EPSILON > pMat2.mat[i] && - pMat1.mat[i] - cc.math.EPSILON < pMat2.mat[i])) { - return false; +(function(cc){ + cc.math.Matrix3 = function(mat3) { + if (mat3) { + var mat = mat3; + this.mat = new Float32Array([mat[0], mat[1], mat[2], + mat[3], mat[4], mat[5], + mat[60], mat[7], mat[8]]); + } else { + this.mat = new Float32Array([0, 0, 0, + 0, 0, 0, + 0, 0, 0]); + } + }; + cc.kmMat3 = cc.math.Matrix3; + var proto = cc.math.Matrix3.prototype; + + proto.fill = function(mat3) { //cc.kmMat3Fill + var mat = this.mat, matIn = mat3.mat; + mat[0] = matIn[0]; + mat[1] = matIn[1]; + mat[2] = matIn[2]; + mat[3] = matIn[3]; + mat[4] = matIn[4]; + mat[5] = matIn[5]; + mat[6] = matIn[6]; + mat[7] = matIn[7]; + mat[8] = matIn[8]; + return this; + }; + + proto.adjugate = function(){ //= cc.kmMat3Adjugate + var mat = this.mat; + var m0 = mat[0], m1 = mat[1], m2 = mat[2], m3 = mat[3], m4 = mat[4], + m5 = mat[5], m6 = mat[6], m7 = mat[7], m8 = mat[8]; + mat[0] = m4 * m8 - m5 * m7; + mat[1] = m2 * m7 - m1 * m8; + mat[2] = m1 * m5 - m2 * m4; + mat[3] = m5 * m6 - m3 * m8; + mat[4] = m0 * m8 - m2 * m6; + mat[5] = m2 * m3 - m0 * m5; + mat[6] = m3 * m7 - m4 * m6; + + // XXX: pIn.mat[9] is invalid! + //mat[7] = m1 * m6 - pIn.mat[9] * m7; + mat[8] = m0 * m4 - m1 * m3; + return this; + }; + + proto.identity = function() { //cc.kmMat3Identity + var mat = this.mat; + mat[1] = mat[2] = mat[3] = + mat[5] = mat[6] = mat[7] = 0; + mat[0] = mat[4] = mat[8] = 1.0; + return this; + }; + + var tmpMatrix = new cc.math.Matrix3(); // internal matrix + + proto.inverse = function(determinate){ //cc.kmMat3Inverse + if (determinate === 0.0) + return this; + tmpMatrix.assign(this); + var detInv = 1.0 / determinate; + this.adjugate(); + this.multiplyScalar(detInv); + return this; + }; + + proto.isIdentity = function(){ //= cc.kmMat3IsIdentity + var mat = this.mat; + return (mat[0] === 1 && mat[1] === 0 && mat[2] === 0 + && mat[3] === 0 && mat[4] === 1 && mat[5] === 0 + && mat[6] === 0 && mat[7] === 0 && mat[8] === 1); + }; + + proto.transpose = function(){ // cc.kmMat3Transpose + var mat = this.mat; + var m1 = mat[1], m2 = mat[2], m3 = mat[3], m5 = mat[5], + m6 = mat[6], m7 = mat[7]; + // m0 = mat[0],m8 = mat[8], m4 = mat[4]; + //mat[0] = m0; + //mat[8] = m8; + //mat[4] = m4 + mat[1] = m3; + mat[2] = m6; + mat[3] = m1; + mat[5] = m7; + mat[6] = m2; + mat[7] = m5; + return this; + }; + + proto.determinant = function(){ + var mat = this.mat; + /* + calculating the determinant following the rule of sarus, + | 0 3 6 | 0 3 | + m = | 1 4 7 | 1 4 | + | 2 5 8 | 2 5 | + now sum up the products of the diagonals going to the right (i.e. 0,4,8) + and substract the products of the other diagonals (i.e. 2,4,6) + */ + var output = mat[0] * mat[4] * mat[8] + mat[1] * mat[5] * mat[6] + mat[2] * mat[3] * mat[7]; + output -= mat[2] * mat[4] * mat[6] + mat[0] * mat[5] * mat[7] + mat[1] * mat[3] * mat[8]; + return output; + }; + + proto.multiply = function(mat3){ + var m1 = this.mat, m2 = mat3.mat; + var a0 = m1[0], a1 = m1[1], a2 = m1[2], a3 = m1[3], a4 = m1[4], a5 = m1[5], + a6 = m1[6], a7 = m1[7], a8 = m1[8]; + var b0 = m2[0], b1 = m2[1], b2 = m2[2], b3 = m2[3], b4 = m2[4], b5 = m2[5], + b6 = m2[6], b7 = m2[7], b8 = m2[8]; + + m1[0] = a0 * b0 + a3 * b1 + a6 * b2; + m1[1] = a1 * b0 + a4 * b1 + a7 * b2; + m1[2] = a2 * b0 + a5 * b1 + a8 * b2; + + m1[3] = a2 * b0 + a5 * b1 + a8 * b2; + m1[4] = a1 * b3 + a4 * b4 + a7 * b5; + m1[5] = a2 * b3 + a5 * b4 + a8 * b5; + + m1[6] = a0 * b6 + a3 * b7 + a6 * b8; + m1[7] = a1 * b6 + a4 * b7 + a7 * b8; + m1[8] = a2 * b6 + a5 * b7 + a8 * b8; + return this; + }; + + proto.multiplyScalar = function(factor) { + var mat = this.mat; + mat[0] *= factor; + mat[1] *= factor; + mat[2] *= factor; + mat[3] *= factor; + mat[4] *= factor; + mat[5] *= factor; + mat[6] *= factor; + mat[7] *= factor; + mat[8] *= factor; + return this; + }; + + cc.math.Matrix3.rotationAxisAngle = function(axis, radians) { //cc.kmMat3RotationAxisAngle + var rcos = Math.cos(radians), rsin = Math.sin(radians); + var retMat = new cc.math.Matrix3(); + var mat = retMat.mat; + + mat[0] = rcos + axis.x * axis.x * (1 - rcos); + mat[1] = axis.z * rsin + axis.y * axis.x * (1 - rcos); + mat[2] = -axis.y * rsin + axis.z * axis.x * (1 - rcos); + + mat[3] = -axis.z * rsin + axis.x * axis.y * (1 - rcos); + mat[4] = rcos + axis.y * axis.y * (1 - rcos); + mat[5] = axis.x * rsin + axis.z * axis.y * (1 - rcos); + + mat[6] = axis.y * rsin + axis.x * axis.z * (1 - rcos); + mat[7] = -axis.x * rsin + axis.y * axis.z * (1 - rcos); + mat[8] = rcos + axis.z * axis.z * (1 - rcos); + + return retMat; + }; + + proto.assign = function(matIn){ // cc.kmMat3Assign + if(this === matIn) { + cc.log("cc.math.Matrix3.assign(): current matrix equals matIn"); + return this; } + var mat = this.mat, m2 = matIn.mat; + mat[0] = m2[0]; + mat[1] = m2[1]; + mat[2] = m2[2]; + mat[3] = m2[3]; + mat[4] = m2[4]; + mat[5] = m2[5]; + mat[6] = m2[6]; + mat[7] = m2[7]; + mat[8] = m2[8]; + return this; + }; + + proto.equals = function(mat3) { + if (this === mat3) + return true; + var EPSILON = cc.math.EPSILON,m1 = this.mat, m2 = mat3.mat; + for (var i = 0; i < 9; ++i) { + if (!(m1[i] + EPSILON > m2[i] && m1[i] - EPSILON < m2[i])) + return false; + } + return true; + }; + + cc.math.Matrix3.createByRotationX = function(radians) { + var retMat = new cc.math.Matrix3(), mat = retMat.mat; + mat[0] = 1.0; + mat[1] = 0.0; + mat[2] = 0.0; + + mat[3] = 0.0; + mat[4] = Math.cos(radians); + mat[5] = Math.sin(radians); + + mat[6] = 0.0; + mat[7] = -Math.sin(radians); + mat[8] = Math.cos(radians); + return retMat; + }; + + cc.math.Matrix3.createByRotationY = function(radians) { + /* + | cos(A) 0 sin(A) | + M = | 0 1 0 | + | -sin(A) 0 cos(A) | + */ + var retMat = new cc.math.Matrix3(), mat = retMat.mat; + mat[0] = Math.cos(radians); + mat[1] = 0.0; + mat[2] = -Math.sin(radians); + + mat[3] = 0.0; + mat[4] = 1.0; + mat[5] = 0.0; + + mat[6] = Math.sin(radians); + mat[7] = 0.0; + mat[8] = Math.cos(radians); + return retMat; + }; + + cc.math.Matrix3.createByRotationZ = function(radians) { + /* + | cos(A) -sin(A) 0 | + M = | sin(A) cos(A) 0 | + | 0 0 1 | + */ + var retMat = new cc.math.Matrix3(), mat = retMat.mat; + mat[0] = Math.cos(radians); + mat[1] = -Math.sin(radians); + mat[2] = 0.0; + + mat[3] = Math.sin(radians); + mat[4] = Math.cos(radians); + mat[5] = 0.0; + + mat[6] = 0.0; + mat[7] = 0.0; + mat[8] = 1.0; + return retMat; + }; + + cc.math.Matrix3.createByRotation = function(radians) { + /* + | cos(A) -sin(A) 0 | + M = | sin(A) cos(A) 0 | + | 0 0 1 | + */ + var retMat = new cc.math.Matrix3(), mat = retMat.mat; + mat[0] = Math.cos(radians); + mat[1] = Math.sin(radians); + mat[2] = 0.0; + + mat[3] = -Math.sin(radians); + mat[4] = Math.cos(radians); + mat[5] = 0.0; + + mat[6] = 0.0; + mat[7] = 0.0; + mat[8] = 1.0; + return retMat; + }; + + cc.math.Matrix3.createByScale = function(x, y) { + var ret = new cc.math.Matrix3(); + ret.identity(); + ret.mat[0] = x; + ret.mat[4] = y; + return ret; + }; + + cc.math.Matrix3.createByTranslation = function(x, y){ + var ret = new cc.math.Matrix3(); + ret.identity(); + ret.mat[6] = x; + ret.mat[7] = y; + return ret; + }; + + cc.math.Matrix3.createByQuaternion = function(quaternion) { //cc.kmMat3RotationQuaternion + if(!quaternion) + return null; + + var ret = new cc.math.Matrix3(), mat = ret.mat; + // First row + mat[0] = 1.0 - 2.0 * (quaternion.y * quaternion.y + quaternion.z * quaternion.z); + mat[1] = 2.0 * (quaternion.x * quaternion.y - quaternion.w * quaternion.z); + mat[2] = 2.0 * (quaternion.x * quaternion.z + quaternion.w * quaternion.y); + + // Second row + mat[3] = 2.0 * (quaternion.x * quaternion.y + quaternion.w * quaternion.z); + mat[4] = 1.0 - 2.0 * (quaternion.x * quaternion.x + quaternion.z * quaternion.z); + mat[5] = 2.0 * (quaternion.y * quaternion.z - quaternion.w * quaternion.x); + + // Third row + mat[6] = 2.0 * (quaternion.x * quaternion.z - quaternion.w * quaternion.y); + mat[7] = 2.0 * (quaternion.y * quaternion.z + quaternion.w * quaternion.x); + mat[8] = 1.0 - 2.0 * (quaternion.x * quaternion.x + quaternion.y * quaternion.y); + return ret; + }; + + proto.rotationToAxisAngle = function() { //cc.kmMat3RotationToAxisAngle + return cc.math.Quaternion.rotationMatrix(this).toAxisAndAngle(); } +})(cc); + - return true; -}; - -cc.kmMat3RotationX = function (pOut, radians) { - /* - | 1 0 0 | - M = | 0 cos(A) -sin(A) | - | 0 sin(A) cos(A) | - - */ - - pOut.mat[0] = 1.0; - pOut.mat[1] = 0.0; - pOut.mat[2] = 0.0; - - pOut.mat[3] = 0.0; - pOut.mat[4] = Math.cos(radians); - pOut.mat[5] = Math.sin(radians); - - pOut.mat[6] = 0.0; - pOut.mat[7] = -Math.sin(radians); - pOut.mat[8] = Math.cos(radians); - - return pOut; -}; - -cc.kmMat3RotationY = function (pOut, radians) { - /* - | cos(A) 0 sin(A) | - M = | 0 1 0 | - | -sin(A) 0 cos(A) | - */ - - pOut.mat[0] = Math.cos(radians); - pOut.mat[1] = 0.0; - pOut.mat[2] = -Math.sin(radians); - - pOut.mat[3] = 0.0; - pOut.mat[4] = 1.0; - pOut.mat[5] = 0.0; - - pOut.mat[6] = Math.sin(radians); - pOut.mat[7] = 0.0; - pOut.mat[8] = Math.cos(radians); - - return pOut; -}; - -cc.kmMat3RotationZ = function (pOut, radians) { - /* - | cos(A) -sin(A) 0 | - M = | sin(A) cos(A) 0 | - | 0 0 1 | - */ - pOut.mat[0] = Math.cos(radians); - pOut.mat[1] = -Math.sin(radians); - pOut.mat[2] = 0.0; - - pOut.mat[3] = Math.sin(radians); - pOut.mat[4] = Math.cos(radians); - pOut.mat[5] = 0.0; - - pOut.mat[6] = 0.0; - pOut.mat[7] = 0.0; - pOut.mat[8] = 1.0; - - return pOut; -}; - -cc.kmMat3Rotation = function (pOut, radians) { - /* - | cos(A) -sin(A) 0 | - M = | sin(A) cos(A) 0 | - | 0 0 1 | - */ - pOut.mat[0] = Math.cos(radians); - pOut.mat[1] = Math.sin(radians); - pOut.mat[2] = 0.0; - - pOut.mat[3] = -Math.sin(radians); - pOut.mat[4] = Math.cos(radians); - pOut.mat[5] = 0.0; - - pOut.mat[6] = 0.0; - pOut.mat[7] = 0.0; - pOut.mat[8] = 1.0; - return pOut; -}; - -cc.kmMat3Scaling = function (pOut, x, y) { -// memset(pOut.mat, 0, sizeof(float) * 9); - cc.kmMat3Identity(pOut); - pOut.mat[0] = x; - pOut.mat[4] = y; - - return pOut; -}; - -cc.kmMat3Translation = function (pOut, x, y) { -// memset(pOut.mat, 0, sizeof(float) * 9); - cc.kmMat3Identity(pOut); - pOut.mat[6] = x; - pOut.mat[7] = y; -// pOut.mat[8] = 1.0; - - return pOut; -}; - -cc.kmMat3RotationQuaternion = function (pOut, pIn) { - if (!pIn || !pOut) - return null; - - // First row - pOut.mat[0] = 1.0 - 2.0 * (pIn.y * pIn.y + pIn.z * pIn.z); - pOut.mat[1] = 2.0 * (pIn.x * pIn.y - pIn.w * pIn.z); - pOut.mat[2] = 2.0 * (pIn.x * pIn.z + pIn.w * pIn.y); - - // Second row - pOut.mat[3] = 2.0 * (pIn.x * pIn.y + pIn.w * pIn.z); - pOut.mat[4] = 1.0 - 2.0 * (pIn.x * pIn.x + pIn.z * pIn.z); - pOut.mat[5] = 2.0 * (pIn.y * pIn.z - pIn.w * pIn.x); - - // Third row - pOut.mat[6] = 2.0 * (pIn.x * pIn.z - pIn.w * pIn.y); - pOut.mat[7] = 2.0 * (pIn.y * pIn.z + pIn.w * pIn.x); - pOut.mat[8] = 1.0 - 2.0 * (pIn.x * pIn.x + pIn.y * pIn.y); - - return pOut; -}; - -cc.kmMat3RotationToAxisAngle = function (pAxis, radians, pIn) { - /*Surely not this easy?*/ - var temp; - cc.kmQuaternionRotationMatrix(temp, pIn); - cc.kmQuaternionToAxisAngle(temp, pAxis, radians); - return pAxis; -}; diff --git a/cocos2d/kazmath/mat4.js b/cocos2d/kazmath/mat4.js index fd1a428ea5..f142132742 100644 --- a/cocos2d/kazmath/mat4.js +++ b/cocos2d/kazmath/mat4.js @@ -730,43 +730,42 @@ cc.kmMat4ExtractRotation = function (pOut, pIn) { pOut.mat[6] = pIn.mat[8]; pOut.mat[7] = pIn.mat[9]; pOut.mat[8] = pIn.mat[10]; - return pOut; }; cc.kmMat4ExtractPlane = function (pOut, pIn, plane) { switch (plane) { - case cc.KM_PLANE_RIGHT: + case cc.math.Plane.RIGHT: pOut.a = pIn.mat[3] - pIn.mat[0]; pOut.b = pIn.mat[7] - pIn.mat[4]; pOut.c = pIn.mat[11] - pIn.mat[8]; pOut.d = pIn.mat[15] - pIn.mat[12]; break; - case cc.KM_PLANE_LEFT: + case cc.math.Plane.LEFT: pOut.a = pIn.mat[3] + pIn.mat[0]; pOut.b = pIn.mat[7] + pIn.mat[4]; pOut.c = pIn.mat[11] + pIn.mat[8]; pOut.d = pIn.mat[15] + pIn.mat[12]; break; - case cc.KM_PLANE_BOTTOM: + case cc.math.Plane.BOTTOM: pOut.a = pIn.mat[3] + pIn.mat[1]; pOut.b = pIn.mat[7] + pIn.mat[5]; pOut.c = pIn.mat[11] + pIn.mat[9]; pOut.d = pIn.mat[15] + pIn.mat[13]; break; - case cc.KM_PLANE_TOP: + case cc.math.Plane.TOP: pOut.a = pIn.mat[3] - pIn.mat[1]; pOut.b = pIn.mat[7] - pIn.mat[5]; pOut.c = pIn.mat[11] - pIn.mat[9]; pOut.d = pIn.mat[15] - pIn.mat[13]; break; - case cc.KM_PLANE_FAR: + case cc.math.Plane.FAR: pOut.a = pIn.mat[3] - pIn.mat[2]; pOut.b = pIn.mat[7] - pIn.mat[6]; pOut.c = pIn.mat[11] - pIn.mat[10]; pOut.d = pIn.mat[15] - pIn.mat[14]; break; - case cc.KM_PLANE_NEAR: + case cc.math.Plane.NEAR: pOut.a = pIn.mat[3] + pIn.mat[2]; pOut.b = pIn.mat[7] + pIn.mat[6]; pOut.c = pIn.mat[11] + pIn.mat[10]; @@ -794,12 +793,10 @@ cc.kmMat4ExtractPlane = function (pOut, pIn, plane) { */ cc.kmMat4RotationToAxisAngle = function (pAxis, radians, pIn) { /*Surely not this easy?*/ - var temp = new cc.kmQuaternion(); - var rotation = new cc.kmMat3(); + var rotation = new cc.math.Matrix3(); cc.kmMat4ExtractRotation(rotation, pIn); - cc.kmQuaternionRotationMatrix(temp, rotation); - cc.kmQuaternionToAxisAngle(temp, pAxis, radians); - return pAxis; + var temp = cc.math.Quaternion.rotationMatrix(rotation); + return temp.toAxisAndAngle(); }; diff --git a/cocos2d/kazmath/plane.js b/cocos2d/kazmath/plane.js index a3b9a0d5bd..94ab4e9b71 100644 --- a/cocos2d/kazmath/plane.js +++ b/cocos2d/kazmath/plane.js @@ -29,131 +29,109 @@ /** * @ignore */ -cc.KM_PLANE_LEFT = 0; +(function(cc){ + cc.math.Plane = function (a, b, c, d) { + if (a && b === undefined) { + this.a = a.a; + this.b = a.b; + this.c = a.c; + this.d = a.d; + } else { + this.a = a || 0; + this.b = b || 0; + this.c = c || 0; + this.d = d || 0; + } + }; + cc.kmPlane = cc.math.Plane; + var proto = cc.math.Plane.prototype; + + cc.math.Plane.LEFT = 0; + + cc.math.Plane.RIGHT = 1; + + cc.math.Plane.BOTTOM = 2; + + cc.math.Plane.TOP = 3; + + cc.math.Plane.NEAR = 4; + + cc.math.Plane.FAR = 5; + + cc.math.Plane.POINT_INFRONT_OF_PLANE = 0; + + cc.math.Plane.POINT_BEHIND_PLANE = 1; + + cc.math.Plane.POINT_ON_PLANE = 2; + + proto.dot = function(vec4){ //cc.kmPlaneDot + return (this.a * vec4.x + this.b * vec4.y + this.c * vec4.z + this.d * vec4.w); + }; + + proto.dotCoord = function(vec3) { //=cc.kmPlaneDotCoord + return (this.a * vec3.x + this.b * vec3.y + this.c * vec3.z + this.d); + }; + + proto.dotNormal = function(vec3) { //=cc.kmPlaneDotNormal + return (this.a * vec3.x + this.b * vec3.y + this.c * vec3.z); + }; + + cc.math.Plane.fromPointNormal = function(vec3, normal) { //cc.kmPlaneFromPointNormal + /* + Planea = Nx + Planeb = Ny + Planec = Nz + Planed = −N⋅P + */ + return new cc.math.Plane(normal.x, normal.y, normal.z, -normal.dot(vec3)); + }; + + cc.math.Plane.fromPoints = function(vec1, vec2, vec3) { //cc.kmPlaneFromPoints + /* + v = (B − A) × (C − A) + n = 1⁄|v| v + Outa = nx + Outb = ny + Outc = nz + Outd = −n⋅A + */ + var v1 = new cc.math.Vec3(vec2), v2 = new cc.math.Vec3(vec3), plane = new cc.math.Plane(); + v1.subtract(vec1); //Create the vectors for the 2 sides of the triangle + v2.subtract(vec1); + v1.cross(v2); // Use the cross product to get the normal + v1.normalize(); //Normalize it and assign to pOut.m_N + + plane.a = v1.x; + plane.b = v1.y; + plane.c = v1.z; + plane.d = v1.scale(-1.0).dot(vec1); + return plane; + }; + + proto.normalize = function(){ //cc.kmPlaneNormalize + var n = new cc.math.Vec3(this.a, this.b, this.c), l = 1.0 / n.length(); //Get 1/length + n.normalize(); //Normalize the vector and assign to pOut + this.a = n.x; + this.b = n.y; + this.c = n.z; + this.d = this.d * l; //Scale the D value and assign to pOut + return this; + }; + + proto.classifyPoint = function(vec3) { + // This function will determine if a point is on, in front of, or behind + // the plane. First we store the dot product of the plane and the point. + var distance = this.a * vec3.x + this.b * vec3.y + this.c * vec3.z + this.d; + + // Simply put if the dot product is greater than 0 then it is infront of it. + // If it is less than 0 then it is behind it. And if it is 0 then it is on it. + if(distance > 0.001) + return cc.math.Plane.POINT_INFRONT_OF_PLANE; + if(distance < -0.001) + return cc.math.Plane.POINT_BEHIND_PLANE; + return cc.math.Plane.POINT_ON_PLANE; + }; +})(cc); -cc.KM_PLANE_RIGHT = 1; - -cc.KM_PLANE_BOTTOM = 2; - -cc.KM_PLANE_TOP = 3; - -cc.KM_PLANE_NEAR = 4; - -cc.KM_PLANE_FAR = 5; - -cc.kmPlane = function (a, b, c, d) { - this.a = a || 0; - this.b = b || 0; - this.c = c || 0; - this.d = d || 0; -}; - -cc.POINT_INFRONT_OF_PLANE = 0; - -cc.POINT_BEHIND_PLANE = 1; - -cc.POINT_ON_PLANE = 2; - -cc.kmPlaneDot = function(pP, pV){ - //a*x + b*y + c*z + d*w - return (pP.a * pV.x + - pP.b * pV.y + - pP.c * pV.z + - pP.d * pV.w); -}; - -cc.kmPlaneDotCoord = function(pP, pV){ - return (pP.a * pV.x + - pP.b * pV.y + - pP.c * pV.z + pP.d); -}; - -cc.kmPlaneDotNormal = function(pP, pV){ - return (pP.a * pV.x + - pP.b * pV.y + - pP.c * pV.z); -}; - -cc.kmPlaneFromPointNormal = function(pOut, pPoint, pNormal){ - /* - Planea = Nx - Planeb = Ny - Planec = Nz - Planed = −N⋅P - */ - pOut.a = pNormal.x; - pOut.b = pNormal.y; - pOut.c = pNormal.z; - pOut.d = - pNormal.dot(pPoint); - - return pOut; -}; - -/** - * Creates a plane from 3 points. The result is stored in pOut. - * pOut is returned. - */ -cc.kmPlaneFromPoints = function(pOut, p1, p2, p3){ - /* - v = (B − A) × (C − A) - n = 1⁄|v| v - Outa = nx - Outb = ny - Outc = nz - Outd = −n⋅A - */ - - var v1 = new cc.math.Vec3(p2), v2 = new cc.math.Vec3(p3); - v1.subtract(p1); //Create the vectors for the 2 sides of the triangle - v2.subtract(p1); - var n = new cc.math.Vec3(v1); - n.cross(v2); // Use the cross product to get the normal - n.normalize(); //Normalize it and assign to pOut.m_N - - pOut.a = n.x; - pOut.b = n.y; - pOut.c = n.z; - pOut.d = n.scale(-1.0).dot(p1); - return pOut; -}; - -cc.kmPlaneNormalize = function(pOut, pP){ - var n = new cc.math.Vec3(); - - n.x = pP.a; - n.y = pP.b; - n.z = pP.c; - - var l = 1.0 / n.length(); //Get 1/length - n.normalize(); //Normalize the vector and assign to pOut - - pOut.a = n.x; - pOut.b = n.y; - pOut.c = n.z; - pOut.d = pP.d * l; //Scale the D value and assign to pOut - - return pOut; -}; - -cc.kmPlaneScale = function(pOut, pP, s){ - cc.log("cc.kmPlaneScale() has not been implemented."); -}; - -/** - * Returns POINT_INFRONT_OF_PLANE if pP is infront of pIn. Returns - * POINT_BEHIND_PLANE if it is behind. Returns POINT_ON_PLANE otherwise - */ -cc.kmPlaneClassifyPoint = function(pIn, pP){ - // This function will determine if a point is on, in front of, or behind - // the plane. First we store the dot product of the plane and the point. - var distance = pIn.a * pP.x + pIn.b * pP.y + pIn.c * pP.z + pIn.d; - - // Simply put if the dot product is greater than 0 then it is infront of it. - // If it is less than 0 then it is behind it. And if it is 0 then it is on it. - if(distance > 0.001) return cc.POINT_INFRONT_OF_PLANE; - if(distance < -0.001) return cc.POINT_BEHIND_PLANE; - - return cc.POINT_ON_PLANE; -}; diff --git a/cocos2d/kazmath/quaternion.js b/cocos2d/kazmath/quaternion.js index 6c7b20ca2b..3b24830871 100644 --- a/cocos2d/kazmath/quaternion.js +++ b/cocos2d/kazmath/quaternion.js @@ -26,440 +26,425 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/** - * The Quaternion class - * @param {Number} x - * @param {Number} y - * @param {Number} z - * @param {Number} w - * @constructor - */ -cc.kmQuaternion = function (x, y, z, w) { - this.x = x || 0; - this.y = y || 0; - this.z = z || 0; - this.w = w || 0; -}; - -///< Returns pOut, sets pOut to the conjugate of pIn -cc.kmQuaternionConjugate = function (pOut, pIn) { - pOut.x = -pIn.x; - pOut.y = -pIn.y; - pOut.z = -pIn.z; - pOut.w = pIn.w; - - return pOut; -}; - -///< Returns the dot product of the 2 quaternions -cc.kmQuaternionDot = function (q1, q2) { - // A dot B = B dot A = AtBt + AxBx + AyBy + AzBz - return (q1.w * q2.w + - q1.x * q2.x + - q1.y * q2.y + - q1.z * q2.z); -}; - -///< Returns the exponential of the quaternion -cc.kmQuaternionExp = function (pOut, pIn) { - //TODO not implement - //cc.assert(0); - return pOut; -}; - -///< Makes the passed quaternion an identity quaternion -cc.kmQuaternionIdentity = function (pOut) { - pOut.x = 0.0; - pOut.y = 0.0; - pOut.z = 0.0; - pOut.w = 1.0; - - return pOut; -}; - -///< Returns the inverse of the passed Quaternion -cc.kmQuaternionInverse = function (pOut, pIn) { - var l = cc.kmQuaternionLength(pIn); - var tmp = new cc.kmQuaternion(); - - if (Math.abs(l) > cc.math.EPSILON) { - pOut.x = 0.0; - pOut.y = 0.0; - pOut.z = 0.0; - pOut.w = 0.0; - return pOut; - } - - ///Get the conjugute and divide by the length - cc.kmQuaternionScale(pOut, - cc.kmQuaternionConjugate(tmp, pIn), 1.0 / l); - - return pOut; -}; - -///< Returns true if the quaternion is an identity quaternion -cc.kmQuaternionIsIdentity = function (pIn) { - return (pIn.x == 0.0 && pIn.y == 0.0 && pIn.z == 0.0 && - pIn.w == 1.0); -}; - -///< Returns the length of the quaternion -cc.kmQuaternionLength = function (pIn) { - return Math.sqrt(cc.kmQuaternionLengthSq(pIn)); -}; - -///< Returns the length of the quaternion squared (prevents a sqrt) -cc.kmQuaternionLengthSq = function (pIn) { - return pIn.x * pIn.x + pIn.y * pIn.y + - pIn.z * pIn.z + pIn.w * pIn.w; -}; - -///< Returns the natural logarithm -cc.kmQuaternionLn = function (pOut, pIn) { - /* - A unit quaternion, is defined by: - Q == (cos(theta), sin(theta) * v) where |v| = 1 - The natural logarithm of Q is, ln(Q) = (0, theta * v) +(function(cc) { + /** + * The Quaternion class + * @param {Number|cc.math.Quaternion} [x=0] + * @param {Number} [y=0] + * @param {Number} [z=0] + * @param {Number} [w=0] + * @constructor */ - //assert(0); - //TODO not implement - return pOut; -}; - -///< Multiplies 2 quaternions together -cc.kmQuaternionMultiply = function (pOut, q1, q2) { - pOut.w = q1.w * q2.w - q1.x * q2.x - q1.y * q2.y - q1.z * q2.z; - pOut.x = q1.w * q2.x + q1.x * q2.w + q1.y * q2.z - q1.z * q2.y; - pOut.y = q1.w * q2.y + q1.y * q2.w + q1.z * q2.x - q1.x * q2.z; - pOut.z = q1.w * q2.z + q1.z * q2.w + q1.x * q2.y - q1.y * q2.x; - - return pOut; -}; - -///< Normalizes a quaternion -cc.kmQuaternionNormalize = function (pOut, pIn) { - var length = cc.kmQuaternionLength(pIn); - if(Math.abs(length) <= cc.math.EPSILON) - throw "cc.kmQuaternionNormalize(): pIn is an invalid value"; - cc.kmQuaternionScale(pOut, pIn, 1.0 / length); - - return pOut; -}; - -///< Rotates a quaternion around an axis -cc.kmQuaternionRotationAxis = function (pOut, pV, angle) { - var rad = angle * 0.5; - var scale = Math.sin(rad); - - pOut.w = Math.cos(rad); - pOut.x = pV.x * scale; - pOut.y = pV.y * scale; - pOut.z = pV.z * scale; - - return pOut; -}; - -///< Creates a quaternion from a rotation matrix -cc.kmQuaternionRotationMatrix = function (pOut, pIn) { - /* - Note: The OpenGL matrices are transposed from the description below - taken from the Matrix and Quaternion FAQ - - if ( mat[0] > mat[5] && mat[0] > mat[10] ) { // Column 0: - S = sqrt( 1.0 + mat[0] - mat[5] - mat[10] ) * 2; - X = 0.25 * S; - Y = (mat[4] + mat[1] ) / S; - Z = (mat[2] + mat[8] ) / S; - W = (mat[9] - mat[6] ) / S; - } else if ( mat[5] > mat[10] ) { // Column 1: - S = sqrt( 1.0 + mat[5] - mat[0] - mat[10] ) * 2; - X = (mat[4] + mat[1] ) / S; - Y = 0.25 * S; - Z = (mat[9] + mat[6] ) / S; - W = (mat[2] - mat[8] ) / S; - } else { // Column 2: - S = sqrt( 1.0 + mat[10] - mat[0] - mat[5] ) * 2; - X = (mat[2] + mat[8] ) / S; - Y = (mat[9] + mat[6] ) / S; - Z = 0.25 * S; - W = (mat[4] - mat[1] ) / S; - } - */ - var x, y, z, w; - var m4x4 = []; - var scale = 0.0; - var diagonal = 0.0; - - if (!pIn) { - return null; - } - - /* 0 3 6 - 1 4 7 - 2 5 8 - - 0 1 2 3 - 4 5 6 7 - 8 9 10 11 - 12 13 14 15*/ - - m4x4[0] = pIn.mat[0]; - m4x4[1] = pIn.mat[3]; - m4x4[2] = pIn.mat[6]; - m4x4[4] = pIn.mat[1]; - m4x4[5] = pIn.mat[4]; - m4x4[6] = pIn.mat[7]; - m4x4[8] = pIn.mat[2]; - m4x4[9] = pIn.mat[5]; - m4x4[10] = pIn.mat[8]; - m4x4[15] = 1; - var pMatrix = m4x4[0]; - - diagonal = pMatrix[0] + pMatrix[5] + pMatrix[10] + 1; - - if (diagonal > cc.math.EPSILON) { - // Calculate the scale of the diagonal - scale = Math.sqrt(diagonal) * 2; - - // Calculate the x, y, x and w of the quaternion through the respective equation - x = ( pMatrix[9] - pMatrix[6] ) / scale; - y = ( pMatrix[2] - pMatrix[8] ) / scale; - z = ( pMatrix[4] - pMatrix[1] ) / scale; - w = 0.25 * scale; - } else { - // If the first element of the diagonal is the greatest value - if (pMatrix[0] > pMatrix[5] && pMatrix[0] > pMatrix[10]) { - // Find the scale according to the first element, and double that value - scale = Math.sqrt(1.0 + pMatrix[0] - pMatrix[5] - pMatrix[10]) * 2.0; - - // Calculate the x, y, x and w of the quaternion through the respective equation - x = 0.25 * scale; - y = (pMatrix[4] + pMatrix[1] ) / scale; - z = (pMatrix[2] + pMatrix[8] ) / scale; - w = (pMatrix[9] - pMatrix[6] ) / scale; - } - // Else if the second element of the diagonal is the greatest value - else if (pMatrix[5] > pMatrix[10]) { - // Find the scale according to the second element, and double that value - scale = Math.sqrt(1.0 + pMatrix[5] - pMatrix[0] - pMatrix[10]) * 2.0; - - // Calculate the x, y, x and w of the quaternion through the respective equation - x = (pMatrix[4] + pMatrix[1] ) / scale; - y = 0.25 * scale; - z = (pMatrix[9] + pMatrix[6] ) / scale; - w = (pMatrix[2] - pMatrix[8] ) / scale; + cc.math.Quaternion = function (x, y, z, w) { + if (x && y === undefined) { + this.x = x.x; + this.y = x.y; + this.z = x.z; + this.w = x.w; } else { - // Else the third element of the diagonal is the greatest value - - // Find the scale according to the third element, and double that value - scale = Math.sqrt(1.0 + pMatrix[10] - pMatrix[0] - pMatrix[5]) * 2.0; - - // Calculate the x, y, x and w of the quaternion through the respective equation - x = (pMatrix[2] + pMatrix[8] ) / scale; - y = (pMatrix[9] + pMatrix[6] ) / scale; - z = 0.25 * scale; - w = (pMatrix[4] - pMatrix[1] ) / scale; + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; + this.w = w || 0; } - } - - pOut.x = x; - pOut.y = y; - pOut.z = z; - pOut.w = w; - - return pOut; -}; + }; + cc.kmQuaternion = cc.math.Quaternion; + var proto = cc.math.Quaternion.prototype; -///< Create a quaternion from yaw, pitch and roll -cc.kmQuaternionRotationYawPitchRoll = function (pOut, yaw, pitch, roll) { - var ex, ey, ez; // temp half euler angles - var cr, cp, cy, sr, sp, sy, cpcy, spsy; // temp vars in roll,pitch yaw - - ex = cc.degreesToRadians(pitch) / 2.0; // convert to rads and half them - ey = cc.degreesToRadians(yaw) / 2.0; - ez = cc.degreesToRadians(roll) / 2.0; - - cr = Math.cos(ex); - cp = Math.cos(ey); - cy = Math.cos(ez); - - sr = Math.sin(ex); - sp = Math.sin(ey); - sy = Math.sin(ez); - - cpcy = cp * cy; - spsy = sp * sy; + /** + * Sets the conjugate of quaternion to self + * @param {cc.math.Quaternion} quaternion + */ + proto.conjugate = function (quaternion) { //= cc.kmQuaternionConjugate + this.x = -quaternion.x; + this.y = -quaternion.y; + this.z = -quaternion.z; + this.w = quaternion.w; + return this; + }; + + /** + * Returns the dot product of the current quaternion and parameter quaternion + * @param quaternion + * @returns {number} + */ + proto.dot = function(quaternion) { // = cc.kmQuaternionDot + // A dot B = B dot A = AtBt + AxBx + AyBy + AzBz + return (this.w * quaternion.w + this.x * quaternion.x + this.y * quaternion.y + this.z * quaternion.z); + }; + + /** + * Returns the exponential of the quaternion, this function doesn't implemented. + * @returns {cc.math.Quaternion} + */ + proto.exponential = function(){ //=cc.kmQuaternionExp + return this; + }; - pOut.w = cr * cpcy + sr * spsy; - - pOut.x = sr * cpcy - cr * spsy; - pOut.y = cr * sp * cy + sr * cp * sy; - pOut.z = cr * cp * sy - sr * sp * cy; + /** + * Makes the current quaternion an identity quaternion + */ + proto.identity = function(){ //=cc.kmQuaternionIdentity + this.x = 0.0; + this.y = 0.0; + this.z = 0.0; + this.w = 1.0; + return this; + }; + + /** + * Inverses the value of current Quaternion + */ + proto.inverse = function(){ //=cc.kmQuaternionInverse + var len = this.length(); + if (Math.abs(len) > cc.math.EPSILON) { + this.x = 0.0; + this.y = 0.0; + this.z = 0.0; + this.w = 0.0; + return this; + } - cc.kmQuaternionNormalize(pOut, pOut); + ///Get the conjugute and divide by the length + this.conjugate(this).scale(1.0 / len); + return this; + }; - return pOut; -}; + /** + * Returns true if the quaternion is an identity quaternion + * @returns {boolean} + */ + proto.isIdentity = function(){ //=cc.kmQuaternionIsIdentity + return (this.x == 0.0 && this.y == 0.0 && this.z == 0.0 && this.w == 1.0); + }; -///< Interpolate between 2 quaternions -cc.kmQuaternionSlerp = function (pOut, q1, q2, t) { - /*float CosTheta = Q0.DotProd(Q1); - float Theta = acosf(CosTheta); - float SinTheta = sqrtf(1.0f-CosTheta*CosTheta); - - float Sin_T_Theta = sinf(T*Theta)/SinTheta; - float Sin_OneMinusT_Theta = sinf((1.0f-T)*Theta)/SinTheta; - - Quaternion Result = Q0*Sin_OneMinusT_Theta; - Result += (Q1*Sin_T_Theta); - - return Result;*/ - - if (q1.x == q2.x && - q1.y == q2.y && - q1.z == q2.z && - q1.w == q2.w) { - - pOut.x = q1.x; - pOut.y = q1.y; - pOut.z = q1.z; - pOut.w = q1.w; - - return pOut; - } - - var ct = cc.kmQuaternionDot(q1, q2); - var theta = Math.acos(ct); - var st = Math.sqrt(1.0 - cc.math.square(ct)); - - var stt = Math.sin(t * theta) / st; - var somt = Math.sin((1.0 - t) * theta) / st; - - var temp = new cc.kmQuaternion(), temp2 = new cc.kmQuaternion(); - cc.kmQuaternionScale(temp, q1, somt); - cc.kmQuaternionScale(temp2, q2, stt); - cc.kmQuaternionAdd(pOut, temp, temp2); - - return pOut; -}; - -///< Get the axis and angle of rotation from a quaternion -cc.kmQuaternionToAxisAngle = function (pIn, pAxis, pAngle) { - var tempAngle; // temp angle - var scale; // temp vars - - tempAngle = Math.acos(pIn.w); - scale = Math.sqrt(cc.math.square(pIn.x) + cc.math.square(pIn.y) + cc.math.square(pIn.z)); - - if (((scale > -cc.math.EPSILON) && scale < cc.math.EPSILON) - || (scale < 2 * Math.PI + cc.math.EPSILON && scale > 2 * Math.PI - cc.math.EPSILON)) { // angle is 0 or 360 so just simply set axis to 0,0,1 with angle 0 - pAngle = 0.0; - - pAxis.x = 0.0; - pAxis.y = 0.0; - pAxis.z = 1.0; - } else { - pAngle = tempAngle * 2.0; // angle in radians - - pAxis.x = pIn.x / scale; - pAxis.y = pIn.y / scale; - pAxis.z = pIn.z / scale; - pAxis.normalize(); - } -}; - -///< Scale a quaternion -cc.kmQuaternionScale = function (pOut, pIn, s) { - pOut.x = pIn.x * s; - pOut.y = pIn.y * s; - pOut.z = pIn.z * s; - pOut.w = pIn.w * s; + /** + * Returns the length of the quaternion + * @returns {number} + */ + proto.length = function() { //=cc.kmQuaternionLength + return Math.sqrt(this.lengthSq()); + }; - return pOut; -}; - -cc.kmQuaternionAssign = function (pOut, pIn) { - pOut.x = pIn.x; - pOut.y = pIn.y; - pOut.z = pIn.z; - pOut.w = pIn.w; - - return pOut; -}; + /** + * Returns the length of the quaternion squared (prevents a sqrt) + * @returns {number} + */ + proto.lengthSq = function() { //=cc.kmQuaternionLengthSq + return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; + }; + + /** + * Uses current quaternion multiplies other quaternion. + * @param {cc.math.Quaternion} quaternion + * @returns {cc.math.Quaternion} + */ + proto.multiply = function(quaternion) { //cc.kmQuaternionMultiply + var x = this.x, y = this.y, z = this.z, w = this.w; + this.w = w * quaternion.w - x * quaternion.x - y * quaternion.y - z * quaternion.z; + this.x = w * quaternion.x + x * quaternion.w + y * quaternion.z - z * quaternion.y; + this.y = w * quaternion.y + y * quaternion.w + z * quaternion.x - x * quaternion.z; + this.z = w * quaternion.z + z * quaternion.w + x * quaternion.y - y * quaternion.x; + return this; + }; + + /** + * Normalizes a quaternion + * @returns {cc.math.Quaternion} + */ + proto.normalize = function(){ //=cc.kmQuaternionNormalize + var length = this.length(); + if (Math.abs(length) <= cc.math.EPSILON) + throw "current quaternion is an invalid value"; + this.scale(1.0 / length); + return this; + }; + + /** + * Rotates a quaternion around an axis and an angle + * @param {cc.math.Vec3} axis + * @param {Number} angle + */ + proto.rotationAxis = function(axis, angle){ //cc.kmQuaternionRotationAxis + var rad = angle * 0.5, scale = Math.sin(rad); + this.w = Math.cos(rad); + this.x = axis.x * scale; + this.y = axis.y * scale; + this.z = axis.z * scale; + return this; + }; + + /** + * Creates a quaternion from a rotation matrix + * @param mat3 + * @returns {*} + */ + cc.math.Quaternion.rotationMatrix = function (mat3) { //cc.kmQuaternionRotationMatrix + if (!mat3) + return null; + + var x, y, z, w; + var m4x4 = [], mat = mat3.mat, scale = 0.0; + + /* 0 3 6 + 1 4 7 + 2 5 8 + + 0 1 2 3 + 4 5 6 7 + 8 9 10 11 + 12 13 14 15*/ + m4x4[0] = mat[0]; + m4x4[1] = mat[3]; + m4x4[2] = mat[6]; + m4x4[4] = mat[1]; + m4x4[5] = mat[4]; + m4x4[6] = mat[7]; + m4x4[8] = mat[2]; + m4x4[9] = mat[5]; + m4x4[10] = mat[8]; + m4x4[15] = 1; + var pMatrix = m4x4[0]; + + var diagonal = pMatrix[0] + pMatrix[5] + pMatrix[10] + 1; + if (diagonal > cc.math.EPSILON) { + // Calculate the scale of the diagonal + scale = Math.sqrt(diagonal) * 2; -cc.kmQuaternionAdd = function (pOut, pQ1, pQ2) { - pOut.x = pQ1.x + pQ2.x; - pOut.y = pQ1.y + pQ2.y; - pOut.z = pQ1.z + pQ2.z; - pOut.w = pQ1.w + pQ2.w; - - return pOut; -}; - -/** Adapted from the OGRE engine! - - Gets the shortest arc quaternion to rotate this vector to the destination - vector. - @remarks - If you call this with a dest vector that is close to the inverse - of this vector, we will rotate 180 degrees around the 'fallbackAxis' - (if specified, or a generated axis if not) since in this case - ANY axis of rotation is valid. - */ -cc.kmQuaternionRotationBetweenVec3 = function (pOut, vec1, vec2, fallback) { - var v1 = new cc.math.Vec3(vec1), v2 = new cc.math.Vec3(vec2); - v1.normalize(); - v2.normalize(); - var a = v1.dot(v2); - - if (a >= 1.0) { - cc.kmQuaternionIdentity(pOut); - return pOut; - } - - if (a < (1e-6 - 1.0)) { - if (Math.abs(fallback.lengthSq()) < cc.math.EPSILON) { - cc.kmQuaternionRotationAxis(pOut, fallback, Math.PI); + // Calculate the x, y, x and w of the quaternion through the respective equation + x = ( pMatrix[9] - pMatrix[6] ) / scale; + y = ( pMatrix[2] - pMatrix[8] ) / scale; + z = ( pMatrix[4] - pMatrix[1] ) / scale; + w = 0.25 * scale; + } else { + // If the first element of the diagonal is the greatest value + if (pMatrix[0] > pMatrix[5] && pMatrix[0] > pMatrix[10]) { + // Find the scale according to the first element, and double that value + scale = Math.sqrt(1.0 + pMatrix[0] - pMatrix[5] - pMatrix[10]) * 2.0; + + // Calculate the x, y, x and w of the quaternion through the respective equation + x = 0.25 * scale; + y = (pMatrix[4] + pMatrix[1] ) / scale; + z = (pMatrix[2] + pMatrix[8] ) / scale; + w = (pMatrix[9] - pMatrix[6] ) / scale; + } + // Else if the second element of the diagonal is the greatest value + else if (pMatrix[5] > pMatrix[10]) { + // Find the scale according to the second element, and double that value + scale = Math.sqrt(1.0 + pMatrix[5] - pMatrix[0] - pMatrix[10]) * 2.0; + + // Calculate the x, y, x and w of the quaternion through the respective equation + x = (pMatrix[4] + pMatrix[1] ) / scale; + y = 0.25 * scale; + z = (pMatrix[9] + pMatrix[6] ) / scale; + w = (pMatrix[2] - pMatrix[8] ) / scale; + } else { + // Else the third element of the diagonal is the greatest value + + // Find the scale according to the third element, and double that value + scale = Math.sqrt(1.0 + pMatrix[10] - pMatrix[0] - pMatrix[5]) * 2.0; + + // Calculate the x, y, x and w of the quaternion through the respective equation + x = (pMatrix[2] + pMatrix[8] ) / scale; + y = (pMatrix[9] + pMatrix[6] ) / scale; + z = 0.25 * scale; + w = (pMatrix[4] - pMatrix[1] ) / scale; + } + } + return new cc.math.Quaternion(x, y, z, w); + }; + + /** + * Create a quaternion from yaw, pitch and roll + * @param yaw + * @param pitch + * @param roll + * @returns {cc.math.Quaternion} + */ + cc.math.Quaternion.rotationYawPitchRoll = function (yaw, pitch, roll) { //cc.kmQuaternionRotationYawPitchRoll + var ex, ey, ez; // temp half euler angles + var cr, cp, cy, sr, sp, sy, cpcy, spsy; // temp vars in roll,pitch yaw + + ex = cc.degreesToRadians(pitch) / 2.0; // convert to rads and half them + ey = cc.degreesToRadians(yaw) / 2.0; + ez = cc.degreesToRadians(roll) / 2.0; + + cr = Math.cos(ex); + cp = Math.cos(ey); + cy = Math.cos(ez); + + sr = Math.sin(ex); + sp = Math.sin(ey); + sy = Math.sin(ez); + + cpcy = cp * cy; + spsy = sp * sy; + + var ret = new cc.math.Quaternion(); + ret.w = cr * cpcy + sr * spsy; + ret.x = sr * cpcy - cr * spsy; + ret.y = cr * sp * cy + sr * cp * sy; + ret.z = cr * cp * sy - sr * sp * cy; + ret.normalize(); + return ret; + }; + + /** + * Interpolate with other quaternions + * @param {cc.math.Quaternion} quaternion + * @param {Number} t + * @returns {cc.math.Quaternion} + */ + proto.slerp = function(quaternion, t) { //=cc.kmQuaternionSlerp + if (this.x === quaternion.x && this.y === quaternion.y && this.z === quaternion.z && this.w === quaternion.w) { + return this; + } + var ct = this.dot(quaternion), theta = Math.acos(ct), st = Math.sqrt(1.0 - cc.math.square(ct)); + var stt = Math.sin(t * theta) / st, somt = Math.sin((1.0 - t) * theta) / st; + var temp2 = new cc.math.Quaternion(quaternion); + this.scale(somt); + temp2.scale(stt); + this.add(temp2); + return this; + }; + + /** + * Get the axis and angle of rotation from a quaternion + * @returns {{axis: cc.math.Vec3, angle: number}} + */ + proto.toAxisAndAngle = function(){ //=cc.kmQuaternionToAxisAngle + var tempAngle; // temp angle + var scale; // temp vars + var retAngle, retAxis = new cc.math.Vec3(); + + tempAngle = Math.acos(this.w); + scale = Math.sqrt(cc.math.square(this.x) + cc.math.square(this.y) + cc.math.square(this.z)); + + if (((scale > -cc.math.EPSILON) && scale < cc.math.EPSILON) + || (scale < 2 * Math.PI + cc.math.EPSILON && scale > 2 * Math.PI - cc.math.EPSILON)) { // angle is 0 or 360 so just simply set axis to 0,0,1 with angle 0 + retAngle = 0.0; + retAxis.x = 0.0; + retAxis.y = 0.0; + retAxis.z = 1.0; } else { - var X = new cc.math.Vec3(1.0, 0.0, 0.0); - var axis = new cc.math.Vec3(X); - axis.cross(vec1); + retAngle = tempAngle * 2.0; // angle in radians + retAxis.x = this.x / scale; + retAxis.y = this.y / scale; + retAxis.z = this.z / scale; + retAxis.normalize(); + } + return {axis: retAxis, angle: retAngle}; + }; - //If axis is zero - if (Math.abs(axis.lengthSq()) < cc.math.EPSILON) { - axis.fill(0.0, 1.0, 0.0); + /** + * Scale a quaternion + * @param {Number} scale + */ + proto.scale = function(scale) { //cc.kmQuaternionScale + this.x *= scale; + this.y *= scale; + this.z *= scale; + this.w *= scale; + return this; + }; + + /** + * Assign current quaternion value from a quaternion. + * @param {cc.math.Quaternion} quaternion + * @returns {cc.math.Quaternion} current quaternion + */ + proto.assign = function(quaternion){ //=cc.kmQuaternionAssign + this.x = quaternion.x; + this.y = quaternion.y; + this.z = quaternion.z; + this.w = quaternion.w; + return this; + }; + + /** + * Adds other quaternion + * @param {cc.math.Quaternion} quaternion + * @returns {cc.math.Quaternion} + */ + proto.add = function(quaternion) { //cc.kmQuaternionAdd + this.x += quaternion.x; + this.y += quaternion.y; + this.z += quaternion.z; + this.w += quaternion.w; + return this; + }; + + /** + *

+ * Adapted from the OGRE engine!
+ * Gets the shortest arc quaternion to rotate this vector to the destination vector.
+ * @remarks
+ * If you call this with a destination vector that is close to the inverse
+ * of this vector, we will rotate 180 degrees around the 'fallbackAxis'
+ * (if specified, or a generated axis if not) since in this case ANY axis of rotation is valid. + *

+ * @param {cc.math.Vec3} vec1 + * @param {cc.math.Vec3} vec2 + * @param {cc.math.Vec3} fallback + * @returns {cc.math.Quaternion} + */ + cc.math.Quaternion.rotationBetweenVec3 = function(vec1, vec2, fallback) { //cc.kmQuaternionRotationBetweenVec3 + var v1 = new cc.math.Vec3(vec1), v2 = new cc.math.Vec3(vec2); + v1.normalize(); + v2.normalize(); + var a = v1.dot(v2), quaternion = new cc.math.Quaternion(); + + if (a >= 1.0) { + quaternion.identity(); + return quaternion; + } + + if (a < (1e-6 - 1.0)) { + if (Math.abs(fallback.lengthSq()) < cc.math.EPSILON) { + quaternion.rotationAxis(fallback, Math.PI); + } else { + var axis = new cc.math.Vec3(1.0, 0.0, 0.0); axis.cross(vec1); + + //If axis is zero + if (Math.abs(axis.lengthSq()) < cc.math.EPSILON) { + axis.fill(0.0, 1.0, 0.0); + axis.cross(vec1); + } + axis.normalize(); + quaternion.rotationAxis(axis, Math.PI); } - axis.normalize(); - cc.kmQuaternionRotationAxis(pOut, axis, Math.PI); + } else { + var s = Math.sqrt((1 + a) * 2), invs = 1 / s; + v1.cross(v2); + quaternion.x = v1.x * invs; + quaternion.y = v1.y * invs; + quaternion.z = v1.z * invs; + quaternion.w = s * 0.5; + quaternion.normalize(); } - } else { - var s = Math.sqrt((1 + a) * 2), invs = 1 / s; - v1.cross(v2); - - pOut.x = v1.x * invs; - pOut.y = v1.y * invs; - pOut.z = v1.z * invs; - pOut.w = s * 0.5; - - cc.kmQuaternionNormalize(pOut, pOut); - } - return pOut; -}; - -cc.kmQuaternionMultiplyVec3 = function (pOut, q, v) { - var uv = new cc.math.Vec3(q), uuv = new cc.math.Vec3(q); - uv.cross(v); - uuv.cross(uv); - - uv.scale((2.0 * q.w)); - uuv.scale(2.0); - - pOut.fill(v); - pOut.add(uv); - pOut.add(uuv); - return pOut; -}; + return quaternion; + }; + + /** + * Current quaternion multiplies a vec3 + * @param {cc.math.Vec3} vec + * @returns {cc.math.Vec3} + */ + proto.multiplyVec3 = function(vec){ //=cc.kmQuaternionMultiplyVec3 + var x = this.x, y = this.y, z = this.z, retVec = new cc.math.Vec3(vec); + var uv = new cc.math.Vec3(x, y, z), uuv = new cc.math.Vec3(x, y, z); + uv.cross(vec); + uuv.cross(uv); + uv.scale((2.0 * q.w)); + uuv.scale(2.0); + + retVec.add(uv); + retVec.add(uuv); + return retVec; + }; +})(cc); + diff --git a/cocos2d/kazmath/vec3.js b/cocos2d/kazmath/vec3.js index 77fd12f3da..18200dfa8b 100644 --- a/cocos2d/kazmath/vec3.js +++ b/cocos2d/kazmath/vec3.js @@ -28,7 +28,7 @@ (function(cc) { cc.kmVec3 = cc.math.Vec3 = function (x, y, z) { - if(y === undefined){ + if(x && y === undefined){ this.x = x.x; this.y = x.y; this.z = x.z; @@ -42,7 +42,7 @@ var proto = cc.math.Vec3.prototype; proto.fill = function (x, y, z) { // =cc.kmVec3Fill - if (y === undefined) { + if (x && y === undefined) { this.x = x.x; this.y = x.y; this.z = x.z; @@ -124,10 +124,8 @@ b = (a×M)T Out = 1⁄bw(bx, by, bz) */ - var v = new cc.kmVec4(); - var inV = new cc.kmVec4(); - cc.kmVec4Fill(inV, this.x, this.y, this.z, 1.0); - cc.kmVec4Transform(v, inV, mat4); + var v = new cc.math.Vec4(this.x, this.y, this.z, 1.0); + v.transform(mat4); this.x = v.x / v.w; this.y = v.y / v.w; this.z = v.z / v.w; @@ -179,13 +177,11 @@ return vec; }; - cc.mat.Vec3.toTypeArray = function(vec){ //cc.kmVec3ToTypeArray - if(!vec) - return null; + proto.toTypeArray = function(){ //cc.kmVec3ToTypeArray var tyArr = new Float32Array(3); - tyArr[0] = vec.x; - tyArr[1] = vec.y; - tyArr[2] = vec.z; + tyArr[0] = this.x; + tyArr[1] = this.y; + tyArr[2] = this.z; return tyArr; }; })(cc); diff --git a/cocos2d/kazmath/vec4.js b/cocos2d/kazmath/vec4.js index 20c8c78118..bb4e2ac807 100644 --- a/cocos2d/kazmath/vec4.js +++ b/cocos2d/kazmath/vec4.js @@ -26,133 +26,133 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -cc.kmVec4 = function (x, y, z, w) { - this.x = x || 0; - this.y = y || 0; - this.z = z || 0; - this.w = w || 0; -}; - - -cc.kmVec4Fill = function(outVec, x, y ,z, w){ - outVec.x = x; - outVec.y = y; - outVec.z = z; - outVec.w = w; - return outVec; -}; - -cc.kmVec4Add = function(outVec, pV1, pV2){ - outVec.x = pV1.x + pV2.x; - outVec.y = pV1.y + pV2.y; - outVec.z = pV1.z + pV2.z; - outVec.w = pV1.w + pV2.w; - - return outVec; -}; - -cc.kmVec4Dot = function( vec1, vec2){ - return ( vec1.x * vec2.x - + vec1.y * vec2.y - + vec1.z * vec2.z - + vec1.w * vec2.w ); -}; - -cc.kmVec4Length = function(inVec){ - return Math.sqrt(cc.math.square(inVec.x) + cc.math.square(inVec.y) + cc.math.square(inVec.z) + cc.math.square(inVec.w)); -}; - -cc.kmVec4LengthSq = function(inVec){ - return cc.math.square(inVec.x) + cc.math.square(inVec.y) + cc.math.square(inVec.z) + cc.math.square(inVec.w); -}; - -cc.kmVec4Lerp = function(outVec, pV1, pV2, t){ - return outVec; -}; - -cc.kmVec4Normalize = function(outVec, inVec){ - var l = 1.0 / cc.kmVec4Length(inVec); - - outVec.x *= l; - outVec.y *= l; - outVec.z *= l; - outVec.w *= l; - - return outVec; -}; - -cc.kmVec4Scale = function(outVec, inVec, scale){ - cc.kmVec4Normalize(outVec, inVec); - - outVec.x *= scale; - outVec.y *= scale; - outVec.z *= scale; - outVec.w *= scale; - return outVec; -}; - -cc.kmVec4Subtract = function(outVec,vec1, vec2){ - outVec.x = vec1.x - vec2.x; - outVec.y = vec1.y - vec2.y; - outVec.z = vec1.z - vec2.z; - outVec.w = vec1.w - vec2.w; - - return outVec; -}; - -cc.kmVec4Transform = function(outVec, vec,mat4Obj){ - outVec.x = vec.x * mat4Obj.mat[0] + vec.y * mat4Obj.mat[4] + vec.z * mat4Obj.mat[8] + vec.w * mat4Obj.mat[12]; - outVec.y = vec.x * mat4Obj.mat[1] + vec.y * mat4Obj.mat[5] + vec.z * mat4Obj.mat[9] + vec.w * mat4Obj.mat[13]; - outVec.z = vec.x * mat4Obj.mat[2] + vec.y * mat4Obj.mat[6] + vec.z * mat4Obj.mat[10] + vec.w * mat4Obj.mat[14]; - outVec.w = vec.x * mat4Obj.mat[3] + vec.y * mat4Obj.mat[7] + vec.z * mat4Obj.mat[11] + vec.w * mat4Obj.mat[15]; - return outVec; -}; - -cc.kmVec4TransformArray = function(outVec,outStride,vecObj,stride,mat4Obj,count){ - var i = 0; - //Go through all of the vectors - while (i < count) { - var currIn = vecObj + (i * stride); //Get a pointer to the current input - var out = outVec + (i * outStride); //and the current output - cc.kmVec4Transform(out, currIn, mat4Obj); //Perform transform on it - ++i; - } - - return outVec; -}; - -cc.kmVec4AreEqual = function(vec1,vec2){ - return ( - (vec1.x < vec2.x + cc.math.EPSILON && vec1.x > vec2.x - cc.math.EPSILON) && - (vec1.y < vec2.y + cc.math.EPSILON && vec1.y > vec2.y - cc.math.EPSILON) && - (vec1.z < vec2.z + cc.math.EPSILON && vec1.z > vec2.z - cc.math.EPSILON) && - (vec1.w < vec2.w + cc.math.EPSILON && vec1.w > vec2.w - cc.math.EPSILON) - ); -}; - -cc.kmVec4Assign = function(destVec, srcVec){ - if(destVec == srcVec){ - cc.log("destVec and srcVec are same object"); - return destVec; - } - - destVec.x = srcVec.x; - destVec.y = srcVec.y; - destVec.z = srcVec.z; - destVec.w = srcVec.w; - - return destVec; -}; - -cc.kmVec4ToTypeArray = function(vecValue){ - if(!vecValue) - return null; - - var tyArr = new Float32Array(4); - tyArr[0] = vecValue.x; - tyArr[1] = vecValue.y; - tyArr[2] = vecValue.z; - tyArr[3] = vecValue.w; - return tyArr; -}; +(function(cc) { + cc.math.Vec4 = function (x, y, z, w) { + if (x && y === undefined) { + this.x = x.x; + this.y = x.y; + this.z = x.z; + this.w = x.w; + } else { + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; + this.w = w || 0; + } + }; + cc.kmVec4 = cc.math.Vec4; + var proto = cc.math.Vec4.prototype; + + proto.fill = function (x, y, z, w) { //=cc.kmVec4Fill + if (x && y === undefined) { + this.x = x.x; + this.y = x.y; + this.z = x.z; + this.w = x.w; + } else { + this.x = x; + this.y = y; + this.z = z; + this.w = w; + } + }; + + proto.add = function(vec) { //cc.kmVec4Add + if(!vec) + return this; + this.x += vec.x; + this.y += vec.y; + this.z += vec.z; + this.w += vec.w; + return this; + }; + + proto.dot = function(vec){ //cc.kmVec4Dot + return ( this.x * vec.x + this.y * vec.y + this.z * vec.z + this.w * vec.w ); + }; + + proto.length = function(){ //=cc.kmVec4Length + return Math.sqrt(cc.math.square(this.x) + cc.math.square(this.y) + cc.math.square(this.z) + cc.math.square(this.w)); + }; + + proto.lengthSq = function(){ //=cc.kmVec4LengthSq + return cc.math.square(this.x) + cc.math.square(this.y) + cc.math.square(this.z) + cc.math.square(this.w); + }; + + proto.lerp = function(vec, t){ //= cc.kmVec4Lerp + //not implemented + return this; + }; + + proto.normalize = function() { // cc.kmVec4Normalize + var l = 1.0 / this.length(); + this.x *= l; + this.y *= l; + this.z *= l; + this.w *= l; + return this; + }; + + proto.scale = function(scale){ //= cc.kmVec4Scale + /// Scales a vector to the required length. This performs a Normalize before multiplying by S. + this.normalize(); + this.x *= scale; + this.y *= scale; + this.z *= scale; + this.w *= scale; + return this; + }; + + proto.subtract = function(vec) { + this.x -= vec.x; + this.y -= vec.y; + this.z -= vec.z; + this.w -= vec.w; + }; + + proto.transform = function(mat4) { + var x = this.x, y = this.y, z = this.z, w = this.w, mat = mat4.mat; + this.x = x * mat[0] + y * mat[4] + z * mat[8] + w * mat[12]; + this.y = x * mat[1] + y * mat[5] + z * mat[9] + w * mat[13]; + this.z = x * mat[2] + y * mat[6] + z * mat[10] + w * mat[14]; + this.w = x * mat[3] + y * mat[7] + z * mat[11] + w * mat[15]; + return this; + }; + + cc.math.Vec4.transformArray = function(vecArray, mat4){ + var retArray = []; + for (var i = 0; i < vecArray.length; i++) { + var selVec = new cc.math.Vec4(vecArray[i]); + selVec.transform(mat4); + retArray.push(selVec); + } + return retArray; + }; + + proto.equals = function(vec){ //=cc.kmVec4AreEqual + var EPSILON = cc.math.EPSILON; + return (this.x < vec.x + EPSILON && this.x > vec.x - EPSILON) && + (this.y < vec.y + EPSILON && this.y > vec.y - EPSILON) && + (this.z < vec.z + EPSILON && this.z > vec.z - EPSILON) && + (this.w < vec.w + EPSILON && this.w > vec.w - EPSILON); + }; + + proto.assign = function(vec) { //= cc.kmVec4Assign + this.x = vec.x; + this.y = vec.y; + this.z = vec.z; + this.w = vec.w; + return this; + }; + + proto.toTypeArray = function(){ //cc.kmVec4ToTypeArray + var tyArr = new Float32Array(4); + tyArr[0] = this.x; + tyArr[1] = this.y; + tyArr[2] = this.z; + tyArr[3] = this.w; + return tyArr; + }; +})(cc); + From 876527a98590a0c60440d2ebaf0ca1cef47713cc Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 10 Mar 2015 17:00:48 +0800 Subject: [PATCH 0037/1039] Fixed parser is not exists. --- extensions/cocostudio/loader/parsers/timelineParser-2.x.js | 1 + 1 file changed, 1 insertion(+) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 7b719077a0..e3a9f47f3f 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -1250,6 +1250,7 @@ var register = [ {name: "SingleNodeObjectData", handle: parser.initSingleNode}, + {name: "NodeObjectData", handle: parser.initSingleNode}, {name: "LayerObjectData", handle: parser.initSingleNode}, {name: "SpriteObjectData", handle: parser.initSprite}, {name: "ParticleObjectData", handle: parser.initParticle}, From d38b562b0b6ec289d43f5c9b7de15d53d53bad5d Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Tue, 10 Mar 2015 18:08:18 +0800 Subject: [PATCH 0038/1039] Use cc.defineGetterSetter to replace Object.defineProperties for performance on firefox --- cocos2d/core/platform/CCTypesWebGL.js | 561 +++++++++--------- .../CCRenderTextureCanvasRenderCmd.js | 2 +- 2 files changed, 281 insertions(+), 282 deletions(-) diff --git a/cocos2d/core/platform/CCTypesWebGL.js b/cocos2d/core/platform/CCTypesWebGL.js index 643b973aa1..dbcd2ad478 100644 --- a/cocos2d/core/platform/CCTypesWebGL.js +++ b/cocos2d/core/platform/CCTypesWebGL.js @@ -84,9 +84,7 @@ cc._tmp.WebGLColor = function () { * @type {number} */ cc.Color.BYTES_PER_ELEMENT = 4; - var _p = cc.Color.prototype; - _p._getR = function () { return this._rU8[0]; }; @@ -124,7 +122,6 @@ cc._tmp.WebGLColor = function () { _p.a; cc.defineGetterSetter(_p, "a", _p._getA, _p._setA); - //redefine cc.Vertex2F /** * @class cc.Vertex2F @@ -148,26 +145,26 @@ cc._tmp.WebGLColor = function () { * @type {number} */ cc.Vertex2F.BYTES_PER_ELEMENT = 8; - Object.defineProperties(cc.Vertex2F.prototype, { - x: { - get: function () { - return this._xF32[0]; - }, - set: function (xValue) { - this._xF32[0] = xValue; - }, - enumerable: true - }, - y: { - get: function () { - return this._yF32[0]; - }, - set: function (yValue) { - this._yF32[0] = yValue; - }, - enumerable: true - } - }); + + _p = cc.Vertex2F.prototype; + _p._getX = function () { + return this._xF32[0]; + }; + _p._setX = function (xValue) { + this._xF32[0] = xValue; + }; + _p._getY = function () { + return this._yF32[0]; + }; + _p._setY = function (yValue) { + this._yF32[0] = yValue; + }; + /** @expose */ + _p.x; + cc.defineGetterSetter(_p, "x", _p._getX, _p._setX); + /** @expose */ + _p.y; + cc.defineGetterSetter(_p, "y", _p._getY, _p._setY); // redefine cc.Vertex3F /** @@ -196,35 +193,35 @@ cc._tmp.WebGLColor = function () { * @type {number} */ cc.Vertex3F.BYTES_PER_ELEMENT = 12; - Object.defineProperties(cc.Vertex3F.prototype, { - x: { - get: function () { - return this._xF32[0]; - }, - set: function (xValue) { - this._xF32[0] = xValue; - }, - enumerable: true - }, - y: { - get: function () { - return this._yF32[0]; - }, - set: function (yValue) { - this._yF32[0] = yValue; - }, - enumerable: true - }, - z: { - get: function () { - return this._zF32[0]; - }, - set: function (zValue) { - this._zF32[0] = zValue; - }, - enumerable: true - } - }); + + _p = cc.Vertex3F.prototype; + _p._getX = function () { + return this._xF32[0]; + }; + _p._setX = function (xValue) { + this._xF32[0] = xValue; + }; + _p._getY = function () { + return this._yF32[0]; + }; + _p._setY = function (yValue) { + this._yF32[0] = yValue; + }; + _p._getZ = function () { + return this._zF32[0]; + }; + _p._setZ = function (zValue) { + this._zF32[0] = zValue; + }; + /** @expose */ + _p.x; + cc.defineGetterSetter(_p, "x", _p._getX, _p._setX); + /** @expose */ + _p.y; + cc.defineGetterSetter(_p, "y", _p._getY, _p._setY); + /** @expose */ + _p.z; + cc.defineGetterSetter(_p, "z", _p._getZ, _p._setZ); // redefine cc.Tex2F /** @@ -249,26 +246,26 @@ cc._tmp.WebGLColor = function () { * @type {number} */ cc.Tex2F.BYTES_PER_ELEMENT = 8; - Object.defineProperties(cc.Tex2F.prototype, { - u: { - get: function () { - return this._uF32[0]; - }, - set: function (xValue) { - this._uF32[0] = xValue; - }, - enumerable: true - }, - v: { - get: function () { - return this._vF32[0]; - }, - set: function (yValue) { - this._vF32[0] = yValue; - }, - enumerable: true - } - }); + + _p = cc.Tex2F.prototype; + _p._getU = function () { + return this._uF32[0]; + }; + _p._setU = function (xValue) { + this._uF32[0] = xValue; + }; + _p._getV = function () { + return this._vF32[0]; + }; + _p._setV = function (yValue) { + this._vF32[0] = yValue; + }; + /** @expose */ + _p.u; + cc.defineGetterSetter(_p, "u", _p._getU, _p._setU); + /** @expose */ + _p.v; + cc.defineGetterSetter(_p, "v", _p._getV, _p._setV); //redefine cc.Quad2 /** @@ -297,6 +294,49 @@ cc._tmp.WebGLColor = function () { */ cc.Quad2.BYTES_PER_ELEMENT = 32; + _p = cc.Quad2.prototype; + _p._getTL = function () { + return this._tl; + }; + _p._setTL = function (tlValue) { + this._tl.x = tlValue.x; + this._tl.y = tlValue.y; + }; + _p._getTR = function () { + return this._tr; + }; + _p._setTR = function (trValue) { + this._tr.x = trValue.x; + this._tr.y = trValue.y; + }; + _p._getBL = function() { + return this._bl; + }; + _p._setBL = function (blValue) { + this._bl.x = blValue.x; + this._bl.y = blValue.y; + }; + _p._getBR = function () { + return this._br; + }; + _p._setBR = function (brValue) { + this._br.x = brValue.x; + this._br.y = brValue.y; + }; + + /** @expose */ + _p.tl; + cc.defineGetterSetter(_p, "tl", _p._getTL, _p._setTL); + /** @expose */ + _p.tr; + cc.defineGetterSetter(_p, "tr", _p._getTR, _p._setTR); + /** @expose */ + _p.bl; + cc.defineGetterSetter(_p, "bl", _p._getBL, _p._setBL); + /** @expose */ + _p.br; + cc.defineGetterSetter(_p, "br", _p._getBR, _p._setBR); + /** * A 3D Quad. 4 * 3 floats * @Class cc.Quad3 @@ -313,49 +353,6 @@ cc._tmp.WebGLColor = function () { this.tr = tr1 || new cc.Vertex3F(0, 0, 0); }; - Object.defineProperties(cc.Quad2.prototype, { - tl: { - get: function () { - return this._tl; - }, - set: function (tlValue) { - this._tl.x = tlValue.x; - this._tl.y = tlValue.y; - }, - enumerable: true - }, - tr: { - get: function () { - return this._tr; - }, - set: function (trValue) { - this._tr.x = trValue.x; - this._tr.y = trValue.y; - }, - enumerable: true - }, - bl: { - get: function () { - return this._bl; - }, - set: function (blValue) { - this._bl.x = blValue.x; - this._bl.y = blValue.y; - }, - enumerable: true - }, - br: { - get: function () { - return this._br; - }, - set: function (brValue) { - this._br.x = brValue.x; - this._br.y = brValue.y; - }, - enumerable: true - } - }); - //redefine cc.V3F_C4B_T2F /** * @class cc.V3F_C4B_T2F @@ -383,43 +380,43 @@ cc._tmp.WebGLColor = function () { * @type {number} */ cc.V3F_C4B_T2F.BYTES_PER_ELEMENT = 24; - Object.defineProperties(cc.V3F_C4B_T2F.prototype, { - vertices: { - get: function () { - return this._vertices; - }, - set: function (verticesValue) { - var locVertices = this._vertices; - locVertices.x = verticesValue.x; - locVertices.y = verticesValue.y; - locVertices.z = verticesValue.z; - }, - enumerable: true - }, - colors: { - get: function () { - return this._colors; - }, - set: function (colorValue) { - var locColors = this._colors; - locColors.r = colorValue.r; - locColors.g = colorValue.g; - locColors.b = colorValue.b; - locColors.a = colorValue.a; - }, - enumerable: true - }, - texCoords: { - get: function () { - return this._texCoords; - }, - set: function (texValue) { - this._texCoords.u = texValue.u; - this._texCoords.v = texValue.v; - }, - enumerable: true - } - }); + + _p = cc.V3F_C4B_T2F.prototype; + _p._getVertices = function () { + return this._vertices; + }; + _p._setVertices = function (verticesValue) { + var locVertices = this._vertices; + locVertices.x = verticesValue.x; + locVertices.y = verticesValue.y; + locVertices.z = verticesValue.z; + }; + _p._getColor = function () { + return this._colors; + }; + _p._setColor = function (colorValue) { + var locColors = this._colors; + locColors.r = colorValue.r; + locColors.g = colorValue.g; + locColors.b = colorValue.b; + locColors.a = colorValue.a; + }; + _p._getTexCoords = function () { + return this._texCoords; + }; + _p._setTexCoords = function (texValue) { + this._texCoords.u = texValue.u; + this._texCoords.v = texValue.v; + }; + /** @expose */ + _p.vertices; + cc.defineGetterSetter(_p, "vertices", _p._getVertices, _p._setVertices); + /** @expose */ + _p.colors; + cc.defineGetterSetter(_p, "colors", _p._getColor, _p._setColor); + /** @expose */ + _p.texCoords; + cc.defineGetterSetter(_p, "texCoords", _p._getTexCoords, _p._setTexCoords); //redefine cc.V3F_C4B_T2F_Quad /** @@ -451,62 +448,63 @@ cc._tmp.WebGLColor = function () { * @type {number} */ cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT = 96; - Object.defineProperties(cc.V3F_C4B_T2F_Quad.prototype, { - tl: { - get: function () { - return this._tl; - }, - set: function (tlValue) { - var locTl = this._tl; - locTl.vertices = tlValue.vertices; - locTl.colors = tlValue.colors; - locTl.texCoords = tlValue.texCoords; - }, - enumerable: true - }, - bl: { - get: function () { - return this._bl; - }, - set: function (blValue) { - var locBl = this._bl; - locBl.vertices = blValue.vertices; - locBl.colors = blValue.colors; - locBl.texCoords = blValue.texCoords; - }, - enumerable: true - }, - tr: { - get: function () { - return this._tr; - }, - set: function (trValue) { - var locTr = this._tr; - locTr.vertices = trValue.vertices; - locTr.colors = trValue.colors; - locTr.texCoords = trValue.texCoords; - }, - enumerable: true - }, - br: { - get: function () { - return this._br; - }, - set: function (brValue) { - var locBr = this._br; - locBr.vertices = brValue.vertices; - locBr.colors = brValue.colors; - locBr.texCoords = brValue.texCoords; - }, - enumerable: true - }, - arrayBuffer: { - get: function () { - return this._arrayBuffer; - }, - enumerable: true - } - }); + _p = cc.V3F_C4B_T2F_Quad.prototype; + _p._getTL = function () { + return this._tl; + }; + _p._setTL = function (tlValue) { + var locTl = this._tl; + locTl.vertices = tlValue.vertices; + locTl.colors = tlValue.colors; + locTl.texCoords = tlValue.texCoords; + }; + _p._getBL = function () { + return this._bl; + }; + _p._setBL = function (blValue) { + var locBl = this._bl; + locBl.vertices = blValue.vertices; + locBl.colors = blValue.colors; + locBl.texCoords = blValue.texCoords; + }; + _p._getTR = function () { + return this._tr; + }; + _p._setTR = function (trValue) { + var locTr = this._tr; + locTr.vertices = trValue.vertices; + locTr.colors = trValue.colors; + locTr.texCoords = trValue.texCoords; + }; + _p._getBR = function () { + return this._br; + }; + _p._setBR = function (brValue) { + var locBr = this._br; + locBr.vertices = brValue.vertices; + locBr.colors = brValue.colors; + locBr.texCoords = brValue.texCoords; + }; + _p._getArrayBuffer = function () { + return this._arrayBuffer; + }; + + /** @expose */ + _p.tl; + cc.defineGetterSetter(_p, "tl", _p._getTL, _p._setTL); + /** @expose */ + _p.tr; + cc.defineGetterSetter(_p, "tr", _p._getTR, _p._setTR); + /** @expose */ + _p.bl; + cc.defineGetterSetter(_p, "bl", _p._getBL, _p._setBL); + /** @expose */ + _p.br; + cc.defineGetterSetter(_p, "br", _p._getBR, _p._setBR); + /** @expose */ + _p.arrayBuffer; + cc.defineGetterSetter(_p, "arrayBuffer", _p._getArrayBuffer, null); + /** * @function * @returns {cc.V3F_C4B_T2F_Quad} @@ -580,46 +578,47 @@ cc._tmp.WebGLColor = function () { this._texCoords = texCoords ? new cc.Tex2F(texCoords.u, texCoords.v, locArrayBuffer, locOffset + locElementLen + cc.Color.BYTES_PER_ELEMENT) : new cc.Tex2F(0, 0, locArrayBuffer, locOffset + locElementLen + cc.Color.BYTES_PER_ELEMENT); }; + /** * @constant * @type {number} */ cc.V2F_C4B_T2F.BYTES_PER_ELEMENT = 20; - Object.defineProperties(cc.V2F_C4B_T2F.prototype, { - vertices: { - get: function () { - return this._vertices; - }, - set: function (verticesValue) { - this._vertices.x = verticesValue.x; - this._vertices.y = verticesValue.y; - }, - enumerable: true - }, - colors: { - get: function () { - return this._colors; - }, - set: function (colorValue) { - var locColors = this._colors; - locColors.r = colorValue.r; - locColors.g = colorValue.g; - locColors.b = colorValue.b; - locColors.a = colorValue.a; - }, - enumerable: true - }, - texCoords: { - get: function () { - return this._texCoords; - }, - set: function (texValue) { - this._texCoords.u = texValue.u; - this._texCoords.v = texValue.v; - }, - enumerable: true - } - }); + _p = cc.V2F_C4B_T2F.prototype; + _p._getVertices = function () { + return this._vertices; + }; + _p._setVertices = function (verticesValue) { + this._vertices.x = verticesValue.x; + this._vertices.y = verticesValue.y; + }; + _p._getColor = function () { + return this._colors; + }; + _p._setColor = function (colorValue) { + var locColors = this._colors; + locColors.r = colorValue.r; + locColors.g = colorValue.g; + locColors.b = colorValue.b; + locColors.a = colorValue.a; + }; + _p._getTexCoords = function () { + return this._texCoords; + }; + _p._setTexCoords = function (texValue) { + this._texCoords.u = texValue.u; + this._texCoords.v = texValue.v; + }; + + /** @expose */ + _p.vertices; + cc.defineGetterSetter(_p, "vertices", _p._getVertices, _p._setVertices); + /** @expose */ + _p.colors; + cc.defineGetterSetter(_p, "colors", _p._getColor, _p._setColor); + /** @expose */ + _p.texCoords; + cc.defineGetterSetter(_p, "texCoords", _p._getTexCoords, _p._setTexCoords); //redefine cc.V2F_C4B_T2F_Triangle /** @@ -648,42 +647,42 @@ cc._tmp.WebGLColor = function () { * @type {number} */ cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT = 60; - Object.defineProperties(cc.V2F_C4B_T2F_Triangle.prototype, { - a: { - get: function () { - return this._a; - }, - set: function (aValue) { - var locA = this._a; - locA.vertices = aValue.vertices; - locA.colors = aValue.colors; - locA.texCoords = aValue.texCoords; - }, - enumerable: true - }, - b: { - get: function () { - return this._b; - }, - set: function (bValue) { - var locB = this._b; - locB.vertices = bValue.vertices; - locB.colors = bValue.colors; - locB.texCoords = bValue.texCoords; - }, - enumerable: true - }, - c: { - get: function () { - return this._c; - }, - set: function (cValue) { - var locC = this._c; - locC.vertices = cValue.vertices; - locC.colors = cValue.colors; - locC.texCoords = cValue.texCoords; - }, - enumerable: true - } - }); + _p = cc.V2F_C4B_T2F_Triangle.prototype; + _p._getA = function () { + return this._a; + }; + _p._setA = function (aValue) { + var locA = this._a; + locA.vertices = aValue.vertices; + locA.colors = aValue.colors; + locA.texCoords = aValue.texCoords; + }; + _p._getB = function () { + return this._b; + }; + _p._setB = function (bValue) { + var locB = this._b; + locB.vertices = bValue.vertices; + locB.colors = bValue.colors; + locB.texCoords = bValue.texCoords; + }; + _p._getC = function () { + return this._c; + }; + _p._setC = function (cValue) { + var locC = this._c; + locC.vertices = cValue.vertices; + locC.colors = cValue.colors; + locC.texCoords = cValue.texCoords; + }; + + /** @expose */ + _p.a; + cc.defineGetterSetter(_p, "a", _p._getA, _p._setA); + /** @expose */ + _p.b; + cc.defineGetterSetter(_p, "b", _p._getB, _p._setB); + /** @expose */ + _p.c; + cc.defineGetterSetter(_p, "c", _p._getC, _p._setC); }; \ No newline at end of file diff --git a/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js b/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js index 1f302501e1..6df19091a0 100644 --- a/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js +++ b/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js @@ -73,7 +73,7 @@ r = r || 0; g = g || 0; b = b || 0; - a = isNaN(a) ? 1 : a; + a = isNaN(a) ? 255 : a; var context = this._cacheContext.getContext(); var locCanvas = this._cacheCanvas; From b2bfd7c22b5243c3a718d96f618095522552ca53 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Wed, 11 Mar 2015 11:47:26 +0800 Subject: [PATCH 0039/1039] Loading spriteFrames from jsonObject has been supported. --- cocos2d/core/sprites/CCSpriteFrameCache.js | 80 +++++++++++++--------- 1 file changed, 49 insertions(+), 31 deletions(-) diff --git a/cocos2d/core/sprites/CCSpriteFrameCache.js b/cocos2d/core/sprites/CCSpriteFrameCache.js index 79321e5327..851a30f278 100644 --- a/cocos2d/core/sprites/CCSpriteFrameCache.js +++ b/cocos2d/core/sprites/CCSpriteFrameCache.js @@ -71,6 +71,17 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{ this._frameConfigCache[url] = dict; return dict; } + this._frameConfigCache[url] = this._parseFrameConfig(dict); + return this._frameConfigCache[url]; + }, + + _getFrameConfigByJsonObject: function(url, jsonObject) { + cc.assert(jsonObject, cc._LogInfos.spriteFrameCache__getFrameConfig_2, url); + this._frameConfigCache[url] = this._parseFrameConfig(jsonObject); + return this._frameConfigCache[url]; + }, + + _parseFrameConfig: function(dict) { var tempFrames = dict["frames"], tempMeta = dict["metadata"] || dict["meta"]; var frames = {}, meta = {}; var format = 0; @@ -125,38 +136,21 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{ } frames[key] = tempFrame; } - var cfg = this._frameConfigCache[url] = { - _inited : true, - frames : frames, - meta : meta - }; - return cfg; + return {_inited: true, frames: frames, meta: meta}; }, - /** - *

- * Adds multiple Sprite Frames from a plist or json file.
- * A texture will be loaded automatically. The texture name will composed by replacing the .plist or .json suffix with .png
- * If you want to use another texture, you should use the addSpriteFrames:texture method.
- *

- * @param {String} url file path - * @param {HTMLImageElement|cc.Texture2D|string} texture - * @example - * // add SpriteFrames to SpriteFrameCache With File - * cc.spriteFrameCache.addSpriteFrames(s_grossiniPlist); - * cc.spriteFrameCache.addSpriteFrames(s_grossiniJson); - */ - addSpriteFrames: function (url, texture) { + // Adds multiple Sprite Frames from a json object. it uses for local web view app. + _addSpriteFramesByObject: function(url, jsonObject, texture) { cc.assert(url, cc._LogInfos.spriteFrameCache_addSpriteFrames_2); - - //Is it a SpriteFrame plist? - var dict = this._frameConfigCache[url] || cc.loader.getRes(url); - if(!dict || !dict["frames"]) + if(!jsonObject || !jsonObject["frames"]) return; - var self = this; - var frameConfig = self._frameConfigCache[url] || self._getFrameConfig(url); - //self._checkConflict(frameConfig); //TODO + var frameConfig = this._frameConfigCache[url] || this._getFrameConfigByJsonObject(url, jsonObject); + //this._checkConflict(frameConfig); //TODO + this._createSpriteFrames(frameConfig, texture); + }, + + _createSpriteFrames: function(frameConfig, texture) { var frames = frameConfig.frames, meta = frameConfig.meta; if(!texture){ var texturePath = cc.path.changeBasename(url, meta.image || ".png"); @@ -170,7 +164,7 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{ } //create sprite frames - var spAliases = self._spriteFramesAliases, spriteFrames = self._spriteFrames; + var spAliases = this._spriteFramesAliases, spriteFrames = this._spriteFrames; for (var key in frames) { var frame = frames[key]; var spriteFrame = spriteFrames[key]; @@ -180,9 +174,8 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{ if(aliases){//set aliases for(var i = 0, li = aliases.length; i < li; i++){ var alias = aliases[i]; - if (spAliases[alias]) { + if (spAliases[alias]) cc.log(cc._LogInfos.spriteFrameCache_addSpriteFrames, alias); - } spAliases[alias] = key; } } @@ -202,12 +195,37 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{ spriteFrame.setRect(cc.rect(0, 0, rect.width, rect.height)); } } - spriteFrames[key] = spriteFrame; } } }, + /** + *

+ * Adds multiple Sprite Frames from a plist or json file.
+ * A texture will be loaded automatically. The texture name will composed by replacing the .plist or .json suffix with .png
+ * If you want to use another texture, you should use the addSpriteFrames:texture method.
+ *

+ * @param {String} url file path + * @param {HTMLImageElement|cc.Texture2D|string} texture + * @example + * // add SpriteFrames to SpriteFrameCache With File + * cc.spriteFrameCache.addSpriteFrames(s_grossiniPlist); + * cc.spriteFrameCache.addSpriteFrames(s_grossiniJson); + */ + addSpriteFrames: function (url, texture) { + cc.assert(url, cc._LogInfos.spriteFrameCache_addSpriteFrames_2); + + //Is it a SpriteFrame plist? + var dict = this._frameConfigCache[url] || cc.loader.getRes(url); + if(!dict || !dict["frames"]) + return; + + var frameConfig = this._frameConfigCache[url] || this._getFrameConfig(url); + //this._checkConflict(frameConfig); //TODO + this._createSpriteFrames(frameConfig, texture); + }, + // Function to check if frames to add exists already, if so there may be name conflit that must be solved _checkConflict: function (dictionary) { var framesDict = dictionary["frames"]; From d11949f3a7f7d5c1e4f2b110fba1811021ba776a Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 11 Mar 2015 14:19:59 +0800 Subject: [PATCH 0040/1039] Fixed a bug that is position error when checkbox does not pre loaded --- extensions/ccui/uiwidgets/UICheckBox.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/extensions/ccui/uiwidgets/UICheckBox.js b/extensions/ccui/uiwidgets/UICheckBox.js index 9f9f257fc4..dbe967c859 100644 --- a/extensions/ccui/uiwidgets/UICheckBox.js +++ b/extensions/ccui/uiwidgets/UICheckBox.js @@ -163,7 +163,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ * @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType */ loadTextureBackGround: function (backGround, texType) { - if (!backGround || (this._backGroundFileName == backGround && this._backGroundTexType == texType)) + if (!backGround) return; texType = texType || ccui.Widget.LOCAL_TEXTURE; @@ -206,7 +206,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ * @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType */ loadTextureBackGroundSelected: function (backGroundSelected, texType) { - if (!backGroundSelected || (this._backGroundSelectedFileName == backGroundSelected && this._backGroundSelectedTexType == texType)) + if (!backGroundSelected) return; texType = texType || ccui.Widget.LOCAL_TEXTURE; @@ -246,7 +246,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ * @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType */ loadTextureFrontCross: function (cross, texType) { - if (!cross || (this._frontCrossFileName == cross && this._frontCrossTexType == texType)) + if (!cross) return; texType = texType || ccui.Widget.LOCAL_TEXTURE; this._frontCrossFileName = cross; @@ -285,7 +285,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ * @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType */ loadTextureBackGroundDisabled: function (backGroundDisabled, texType) { - if (!backGroundDisabled || (this._backGroundDisabledFileName == backGroundDisabled && this._backGroundDisabledTexType == texType)) + if (!backGroundDisabled) return; texType = texType || ccui.Widget.LOCAL_TEXTURE; this._backGroundDisabledFileName = backGroundDisabled; @@ -324,7 +324,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ * @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType */ loadTextureFrontCrossDisabled: function (frontCrossDisabled, texType) { - if (!frontCrossDisabled || (this._frontCrossDisabledFileName == frontCrossDisabled && this._frontCrossDisabledTexType == texType)) + if (!frontCrossDisabled) return; texType = texType || ccui.Widget.LOCAL_TEXTURE; this._frontCrossDisabledFileName = frontCrossDisabled; From aa1deb903ef790045a4abf8769e06a1ae2db7252 Mon Sep 17 00:00:00 2001 From: WingGao Date: Wed, 11 Mar 2015 18:03:05 +0800 Subject: [PATCH 0041/1039] FIx getTileGIDAt If pos equals 0 it will also throw the exception --- cocos2d/tilemap/CCTMXLayer.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/tilemap/CCTMXLayer.js b/cocos2d/tilemap/CCTMXLayer.js index d9a6219398..c2e763ac64 100644 --- a/cocos2d/tilemap/CCTMXLayer.js +++ b/cocos2d/tilemap/CCTMXLayer.js @@ -370,7 +370,7 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ * @return {Number} */ getTileGIDAt:function (pos, y) { - if(!pos) + if(pos == null) throw "cc.TMXLayer.getTileGIDAt(): pos should be non-null"; if(y !== undefined) pos = cc.p(pos, y); From d009c11e3532e82ef9ee22cbd70c8221cfe53cce Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 13 Mar 2015 10:08:34 +0800 Subject: [PATCH 0042/1039] Fixed TMX setTileGID error --- cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js | 40 +++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js index 7cada6db60..d7cdc2b080 100644 --- a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js +++ b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js @@ -87,8 +87,46 @@ return; var node = this._node; + //TODO: it will implement dynamic compute child cutting automation. + var i, len, locChildren = node._children; + // quick return if not visible + if (!node._visible || !locChildren || locChildren.length === 0) + return; + + var wrapper, context; + + if (this._cacheDirty) { + var locCanvas = this._cacheCanvas, instanceID = node.__instanceId, renderer = cc.renderer; + wrapper = this._cacheContext, context = wrapper.getContext(), + //begin cache + renderer._turnToCacheMode(instanceID); + + node.sortAllChildren(); + for (i = 0, len = locChildren.length; i < len; i++) { + if (locChildren[i]){ + var selCmd = locChildren[i]._renderCmd; + if(selCmd){ + selCmd.visit(this); + selCmd._cacheDirty = false; + } + } + } + + //copy cached render cmd array to TMXLayer renderer + this._copyRendererCmds(renderer._cacheToCanvasCmds[instanceID]); + + //wrapper.save(); + context.setTransform(1, 0, 0, 1, 0, 0); + context.clearRect(0, 0, locCanvas.width, locCanvas.height); + //set the wrapper's offset + + //draw to cache canvas + renderer._renderingToCacheCanvas(wrapper, instanceID); + } + this._renderingChildToCache(scaleX, scaleY); - var wrapper = ctx || cc._renderContext, context = wrapper.getContext(); + wrapper = ctx || cc._renderContext; + context = wrapper.getContext(); wrapper.setGlobalAlpha(alpha); var posX = 0 | ( -this._anchorPointInPoints.x), posY = 0 | ( -this._anchorPointInPoints.y); From 18d0efe813caa3b50973354f9516fff60f004380 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 13 Mar 2015 11:32:48 +0800 Subject: [PATCH 0043/1039] Remove _childrenRenderCmds --- cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js | 71 ++++---------------- 1 file changed, 13 insertions(+), 58 deletions(-) diff --git a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js index d7cdc2b080..6767d78c71 100644 --- a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js +++ b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js @@ -27,7 +27,6 @@ cc.SpriteBatchNode.CanvasRenderCmd.call(this, renderable); this._needDraw = true; this._realWorldTransform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0}; - this._childrenRenderCmds = []; var locCanvas = cc._canvas; var tmpCanvas = cc.newElement('canvas'); @@ -46,17 +45,6 @@ var proto = cc.TMXLayer.CanvasRenderCmd.prototype = Object.create(cc.SpriteBatchNode.CanvasRenderCmd.prototype); proto.constructor = cc.TMXLayer.CanvasRenderCmd; - proto._copyRendererCmds = function (rendererCmds) { - if (!rendererCmds) - return; - - var locCacheCmds = this._childrenRenderCmds; - locCacheCmds.length = 0; - for (var i = 0, len = rendererCmds.length; i < len; i++) { - locCacheCmds[i] = rendererCmds[i]; - } - }; - //set the cache dirty flag for canvas proto._setNodeDirtyForCache = function () { this._cacheDirty = true; @@ -64,7 +52,7 @@ proto._renderingChildToCache = function (scaleX, scaleY) { if (this._cacheDirty) { - var locCacheCmds = this._childrenRenderCmds, wrapper = this._cacheContext, + var wrapper = this._cacheContext, context = wrapper.getContext(), locCanvas = this._cacheCanvas; //wrapper.save(); @@ -72,10 +60,18 @@ context.clearRect(0, 0, locCanvas.width, locCanvas.height); //reset the cache context - for (var i = 0, len = locCacheCmds.length; i < len; i++) { - locCacheCmds[i].rendering(wrapper, scaleX, scaleY); - locCacheCmds[i]._cacheDirty = false; + this._node.sortAllChildren(); + var locChildren = this._node._children; + for (var i = 0, len = locChildren.length; i < len; i++) { + if (locChildren[i]){ + var selCmd = locChildren[i]._renderCmd; + if(selCmd){ + selCmd.rendering(wrapper, scaleX, scaleY); + selCmd._cacheDirty = false; + } + } } + //wrapper.restore(); this._cacheDirty = false; } @@ -87,46 +83,8 @@ return; var node = this._node; - //TODO: it will implement dynamic compute child cutting automation. - var i, len, locChildren = node._children; - // quick return if not visible - if (!node._visible || !locChildren || locChildren.length === 0) - return; - - var wrapper, context; - - if (this._cacheDirty) { - var locCanvas = this._cacheCanvas, instanceID = node.__instanceId, renderer = cc.renderer; - wrapper = this._cacheContext, context = wrapper.getContext(), - //begin cache - renderer._turnToCacheMode(instanceID); - - node.sortAllChildren(); - for (i = 0, len = locChildren.length; i < len; i++) { - if (locChildren[i]){ - var selCmd = locChildren[i]._renderCmd; - if(selCmd){ - selCmd.visit(this); - selCmd._cacheDirty = false; - } - } - } - - //copy cached render cmd array to TMXLayer renderer - this._copyRendererCmds(renderer._cacheToCanvasCmds[instanceID]); - - //wrapper.save(); - context.setTransform(1, 0, 0, 1, 0, 0); - context.clearRect(0, 0, locCanvas.width, locCanvas.height); - //set the wrapper's offset - - //draw to cache canvas - renderer._renderingToCacheCanvas(wrapper, instanceID); - } - this._renderingChildToCache(scaleX, scaleY); - wrapper = ctx || cc._renderContext; - context = wrapper.getContext(); + var wrapper = ctx || cc._renderContext, context = wrapper.getContext(); wrapper.setGlobalAlpha(alpha); var posX = 0 | ( -this._anchorPointInPoints.x), posY = 0 | ( -this._anchorPointInPoints.y); @@ -199,9 +157,6 @@ } } - //copy cached render cmd array to TMXLayer renderer - this._copyRendererCmds(renderer._cacheToCanvasCmds[instanceID]); - //wrapper.save(); context.setTransform(1, 0, 0, 1, 0, 0); context.clearRect(0, 0, locCanvas.width, locCanvas.height); From 63e8675c683d38fa93bf506bca8aea58978309c3 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 13 Mar 2015 11:35:08 +0800 Subject: [PATCH 0044/1039] remove sortAllChildren --- cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js | 1 - 1 file changed, 1 deletion(-) diff --git a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js index 6767d78c71..c1a63a4924 100644 --- a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js +++ b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js @@ -60,7 +60,6 @@ context.clearRect(0, 0, locCanvas.width, locCanvas.height); //reset the cache context - this._node.sortAllChildren(); var locChildren = this._node._children; for (var i = 0, len = locChildren.length; i < len; i++) { if (locChildren[i]){ From 843c0ee4e5926f8ea16a07a113fcd8f3d01def69 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Fri, 13 Mar 2015 14:33:31 +0800 Subject: [PATCH 0045/1039] Issue #2698: rename cc.kmMat4 to cc.math.Matrix4 and refactor math library for better performance. --- cocos2d/core/CCCamera.js | 10 +- cocos2d/core/CCDirector.js | 9 +- cocos2d/core/CCDirectorWebGL.js | 21 +- .../core/base-nodes/CCNodeWebGLRenderCmd.js | 20 +- cocos2d/effects/CCGrid.js | 12 +- cocos2d/kazmath/aabb.js | 12 +- cocos2d/kazmath/gl/mat4stack.js | 75 +- cocos2d/kazmath/gl/matrix.js | 267 ++- cocos2d/kazmath/mat3.js | 9 +- cocos2d/kazmath/mat4.js | 1674 ++++++++++------- cocos2d/kazmath/quaternion.js | 2 +- cocos2d/kazmath/vec3.js | 2 +- cocos2d/kazmath/vec4.js | 2 +- cocos2d/node-grid/CCNodeGrid.js | 2 +- .../CCRenderTextureWebGLRenderCmd.js | 5 +- cocos2d/shaders/CCGLProgram.js | 10 +- .../CCProtectedNodeWebGLRenderCmd.js | 10 +- 17 files changed, 1182 insertions(+), 960 deletions(-) diff --git a/cocos2d/core/CCCamera.js b/cocos2d/core/CCCamera.js index d9189391e8..ea6c6db8c7 100644 --- a/cocos2d/core/CCCamera.js +++ b/cocos2d/core/CCCamera.js @@ -62,7 +62,7 @@ cc.Camera = cc.Class.extend({ * constructor of cc.Camera */ ctor:function () { - this._lookupMatrix = new cc.kmMat4(); + this._lookupMatrix = new cc.math.Matrix4(); this.restore(); }, @@ -103,7 +103,7 @@ cc.Camera = cc.Class.extend({ this._upY = 1.0; this._upZ = 0.0; - cc.kmMat4Identity( this._lookupMatrix ); + this._lookupMatrix.identity(); this._dirty = false; }, @@ -116,7 +116,7 @@ cc.Camera = cc.Class.extend({ var eye = new cc.math.Vec3(this._eyeX, this._eyeY , this._eyeZ), center = new cc.math.Vec3(this._centerX, this._centerY, this._centerZ), up = new cc.math.Vec3(this._upX, this._upY, this._upZ); - cc.kmMat4LookAt( this._lookupMatrix, eye, center, up); + this._lookupMatrix.lookAt(eye, center, up); this._dirty = false; } cc.kmGLMultMatrix( this._lookupMatrix); @@ -127,10 +127,10 @@ cc.Camera = cc.Class.extend({ var eye = new cc.math.Vec3(this._eyeX, this._eyeY , this._eyeZ), center = new cc.math.Vec3(this._centerX, this._centerY, this._centerZ), up = new cc.math.Vec3(this._upX, this._upY, this._upZ); - cc.kmMat4LookAt( this._lookupMatrix, eye, center, up); + this._lookupMatrix.lookAt(eye, center, up); this._dirty = false; } - cc.kmMat4Multiply(matrix, matrix, this._lookupMatrix); + matrix.multiply(this._lookupMatrix); }, /** diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js index b9cfbc1437..99988bd431 100644 --- a/cocos2d/core/CCDirector.js +++ b/cocos2d/core/CCDirector.js @@ -27,13 +27,14 @@ cc.g_NumberOfDraws = 0; cc.GLToClipTransform = function (transformOut) { - var projection = new cc.kmMat4(); - cc.kmGLGetMatrix(cc.KM_GL_PROJECTION, projection); + //var projection = new cc.math.Matrix4(); + //cc.kmGLGetMatrix(cc.KM_GL_PROJECTION, projection); + cc.kmGLGetMatrix(cc.KM_GL_PROJECTION, transformOut); - var modelview = new cc.kmMat4(); + var modelview = new cc.math.Matrix4(); cc.kmGLGetMatrix(cc.KM_GL_MODELVIEW, modelview); - cc.kmMat4Multiply(transformOut, projection, modelview); + transformOut.multiply(modelview); }; //---------------------------------------------------------------------------------------------------------------------- diff --git a/cocos2d/core/CCDirectorWebGL.js b/cocos2d/core/CCDirectorWebGL.js index 092dda5b7d..0747f31794 100644 --- a/cocos2d/core/CCDirectorWebGL.js +++ b/cocos2d/core/CCDirectorWebGL.js @@ -57,13 +57,11 @@ if (cc._renderType === cc._RENDER_TYPE_WEBGL) { case cc.Director.PROJECTION_2D: cc.kmGLMatrixMode(cc.KM_GL_PROJECTION); cc.kmGLLoadIdentity(); - var orthoMatrix = new cc.kmMat4(); - cc.kmMat4OrthographicProjection( - orthoMatrix, + var orthoMatrix = cc.math.Matrix4.createOrthographicProjection( -ox, - size.width - ox, + size.width - ox, -oy, - size.height - oy, + size.height - oy, -1024, 1024); cc.kmGLMultMatrix(orthoMatrix); cc.kmGLMatrixMode(cc.KM_GL_MODELVIEW); @@ -71,12 +69,12 @@ if (cc._renderType === cc._RENDER_TYPE_WEBGL) { break; case cc.Director.PROJECTION_3D: var zeye = _t.getZEye(); - var matrixPerspective = new cc.kmMat4(), matrixLookup = new cc.kmMat4(); + var matrixPerspective = new cc.math.Matrix4(), matrixLookup = new cc.math.Matrix4(); cc.kmGLMatrixMode(cc.KM_GL_PROJECTION); cc.kmGLLoadIdentity(); // issue #1334 - cc.kmMat4PerspectiveProjection(matrixPerspective, 60, size.width / size.height, 0.1, zeye * 2); + matrixPerspective = cc.math.Matrix4.createPerspectiveProjection(60, size.width / size.height, 0.1, zeye * 2); cc.kmGLMultMatrix(matrixPerspective); @@ -85,7 +83,7 @@ if (cc._renderType === cc._RENDER_TYPE_WEBGL) { var eye = new cc.math.Vec3(-ox + size.width / 2, -oy + size.height / 2, zeye); var center = new cc.math.Vec3( -ox + size.width / 2, -oy + size.height / 2, 0.0); var up = new cc.math.Vec3( 0.0, 1.0, 0.0); - cc.kmMat4LookAt(matrixLookup, eye, center, up); + matrixLookup.lookAt(eye, center, up); cc.kmGLMultMatrix(matrixLookup); break; case cc.Director.PROJECTION_CUSTOM: @@ -238,11 +236,10 @@ if (cc._renderType === cc._RENDER_TYPE_WEBGL) { }; _p.convertToGL = function (uiPoint) { - var transform = new cc.kmMat4(); + var transform = new cc.math.Matrix4(); cc.GLToClipTransform(transform); - var transformInv = new cc.kmMat4(); - cc.kmMat4Inverse(transformInv, transform); + var transformInv = transform.inverse(); // Calculate z=0 using -> transform*[0, 0, 0, 1]/w var zClip = transform.mat[14] / transform.mat[15]; @@ -253,7 +250,7 @@ if (cc._renderType === cc._RENDER_TYPE_WEBGL) { }; _p.convertToUI = function (glPoint) { - var transform = new cc.kmMat4(); + var transform = new cc.math.Matrix4(); cc.GLToClipTransform(transform); var clipCoord = new cc.math.Vec3(glPoint.x, glPoint.y, 0.0); diff --git a/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js b/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js index d0fc3a4afd..5342f1c3a5 100644 --- a/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js @@ -26,11 +26,11 @@ cc.Node.WebGLRenderCmd = function (renderable) { cc.Node.RenderCmd.call(this, renderable); - var mat4 = new cc.kmMat4(); - mat4.mat[2] = mat4.mat[3] = mat4.mat[6] = mat4.mat[7] = mat4.mat[8] = mat4.mat[9] = mat4.mat[11] = mat4.mat[14] = 0.0; - mat4.mat[10] = mat4.mat[15] = 1.0; + var mat4 = new cc.math.Matrix4(), mat = mat4.mat; + mat[2] = mat[3] = mat[6] = mat[7] = mat[8] = mat[9] = mat[11] = mat[14] = 0.0; + mat[10] = mat[15] = 1.0; this._transform4x4 = mat4; - this._stackMatrix = new cc.kmMat4(); + this._stackMatrix = new cc.math.Matrix4(); this._shaderProgram = null; this._camera = null; @@ -223,15 +223,15 @@ apy = 0 | apy; } //cc.kmGLTranslatef(apx, apy, 0); - var translation = new cc.kmMat4(); - cc.kmMat4Translation(translation, apx, apy, 0); - cc.kmMat4Multiply(stackMatrix, stackMatrix, translation); + var translation = cc.math.Matrix4.createByTranslation(apx, apy, 0, t4x4); //t4x4 as a temp matrix + stackMatrix.multiply(translation); node._camera._locateForRenderer(stackMatrix); - //cc.kmGLTranslatef(-apx, -apy, 0); - cc.kmMat4Translation(translation, -apx, -apy, 0); - cc.kmMat4Multiply(stackMatrix, stackMatrix, translation); + //cc.kmGLTranslatef(-apx, -apy, 0); optimize at here : kmGLTranslatef + translation = cc.math.Matrix4.createByTranslation(apx, apy, 0, translation); + stackMatrix.multiply(translation); + t4x4.identity(); //reset t4x4; } else { node._camera._locateForRenderer(stackMatrix); } diff --git a/cocos2d/effects/CCGrid.js b/cocos2d/effects/CCGrid.js index 04719e1df9..a7276fe7c4 100644 --- a/cocos2d/effects/CCGrid.js +++ b/cocos2d/effects/CCGrid.js @@ -229,16 +229,15 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{ // XXX: Camera should be applied in the AnchorPoint // //cc.kmGLTranslatef(offset.x, offset.y, 0); - var translation = new cc.kmMat4(); - cc.kmMat4Translation(translation, offset.x, offset.y, 0); - cc.kmMat4Multiply(stackMatrix, stackMatrix, translation); + var translation = cc.math.Matrix4.createByTranslation(offset.x, offset.y, 0); + stackMatrix.multiply(translation); //target.getCamera().locate(); target._camera._locateForRenderer(stackMatrix); //cc.kmGLTranslatef(-offset.x, -offset.y, 0); - cc.kmMat4Translation(translation, -offset.x, -offset.y, 0); - cc.kmMat4Multiply(stackMatrix, stackMatrix, translation); + translation = cc.math.Matrix4.createByTranslation(-offset.x, -offset.y, 0, translation); + stackMatrix.multiply(translation); } cc.glBindTexture2D(this._texture); @@ -265,8 +264,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{ cc.kmGLMatrixMode(cc.KM_GL_PROJECTION); cc.kmGLLoadIdentity(); - var orthoMatrix = new cc.kmMat4(); - cc.kmMat4OrthographicProjection(orthoMatrix, 0, winSize.width, 0, winSize.height, -1, 1); + var orthoMatrix = cc.math.Matrix4.createOrthographicProjection(0, winSize.width, 0, winSize.height, -1, 1); cc.kmGLMultMatrix(orthoMatrix); cc.kmGLMatrixMode(cc.KM_GL_MODELVIEW); diff --git a/cocos2d/kazmath/aabb.js b/cocos2d/kazmath/aabb.js index a6d207ad8b..8c5dc5b664 100644 --- a/cocos2d/kazmath/aabb.js +++ b/cocos2d/kazmath/aabb.js @@ -39,7 +39,7 @@ cc.math.AABB = function (min, max) { /** * Returns true if point is in the specified AABB, returns false otherwise. - * @param {cc.kmVec3} point + * @param {cc.math.Vec3} point * @returns {boolean} */ cc.math.AABB.prototype.containsPoint = function (point) { @@ -62,17 +62,17 @@ cc.math.AABB.containsPoint = function (pPoint, pBox) { * Assigns aabb to current AABB object * @param {cc.math.AABB} aabb */ -cc.math.AABB.prototype.assign = function(aabb){ - this.min.assign(aabb.min); - this.max.assign(aabb.max); +cc.math.AABB.prototype.assignFrom = function(aabb){ + this.min.assignFrom(aabb.min); + this.max.assignFrom(aabb.max); }; /** * Assigns pIn to pOut, returns pOut. */ cc.math.AABB.assign = function (pOut, pIn) { //cc.kmAABBAssign - pOut.min.assign(pIn.min); - pOut.max.assign(pIn.max); + pOut.min.assignFrom(pIn.min); + pOut.max.assignFrom(pIn.max); return pOut; }; diff --git a/cocos2d/kazmath/gl/mat4stack.js b/cocos2d/kazmath/gl/mat4stack.js index b87450e9c7..b11fd6b1cf 100644 --- a/cocos2d/kazmath/gl/mat4stack.js +++ b/cocos2d/kazmath/gl/mat4stack.js @@ -26,33 +26,54 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -cc.km_mat4_stack = function(capacity, item_count, top, stack){ - this.top = top ; - this.stack = stack ; -}; - -cc.km_mat4_stack.INITIAL_SIZE = 30; - -cc.km_mat4_stack_initialize = function(stack){ - stack.stack = []; //allocate the memory - stack.top = null; //Set the top to NULL -}; - -cc.km_mat4_stack_push = function(stack, item){ - stack.stack.push(stack.top); - stack.top = new cc.kmMat4(); - cc.kmMat4Assign(stack.top, item); -}; - -cc.km_mat4_stack_pop = function(stack, pOut){ - stack.top = stack.stack.pop(); -}; - -cc.km_mat4_stack_release = function(stack){ - stack.stack = null; - stack.top = null; - stack = null; -}; +(function(cc){ + /** + * The stack of cc.math.Matrix4 + * @param {cc.math.Matrix4} [top] + * @param {Array} [stack] + * @constructor + */ + cc.math.Matrix4Stack = function(top, stack) { + this.top = top; + this.stack = stack || []; + }; + cc.km_mat4_stack = cc.math.Matrix4Stack; + var proto = cc.math.Matrix4Stack.prototype; + + proto.initialize = function() { //cc.km_mat4_stack_initialize + this.stack.length = 0; + this.top = null; + }; + + //for compatibility + cc.km_mat4_stack_push = function(stack, item){ + stack.stack.push(stack.top); + stack.top = new cc.math.Matrix4(item); + }; + + cc.km_mat4_stack_pop = function(stack, pOut){ + stack.top = stack.stack.pop(); + }; + + cc.km_mat4_stack_release = function(stack){ + stack.stack = null; + stack.top = null; + }; + + proto.push = function(item) { + this.stack.push(this.top); + this.top = new cc.math.Matrix4(item); + }; + + proto.pop = function() { + this.top = this.stack.pop(); + }; + + proto.release = function(){ + this.stack = null; + this.top = null; + }; +})(cc); diff --git a/cocos2d/kazmath/gl/matrix.js b/cocos2d/kazmath/gl/matrix.js index 0431721b7c..574bd0dd5d 100644 --- a/cocos2d/kazmath/gl/matrix.js +++ b/cocos2d/kazmath/gl/matrix.js @@ -26,143 +26,142 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -cc.KM_GL_MODELVIEW = 0x1700; +(function(cc) { + cc.KM_GL_MODELVIEW = 0x1700; + cc.KM_GL_PROJECTION = 0x1701; + cc.KM_GL_TEXTURE = 0x1702; -cc.KM_GL_PROJECTION = 0x1701; + cc.modelview_matrix_stack = new cc.math.Matrix4Stack(); + cc.projection_matrix_stack = new cc.math.Matrix4Stack(); + cc.texture_matrix_stack = new cc.math.Matrix4Stack(); -cc.KM_GL_TEXTURE = 0x1702; + cc.current_stack = null; + var initialized = false; -cc.modelview_matrix_stack = new cc.km_mat4_stack(); -cc.projection_matrix_stack = new cc.km_mat4_stack(); -cc.texture_matrix_stack = new cc.km_mat4_stack(); + cc.lazyInitialize = function () { + if (!initialized) { + var identity = new cc.math.Matrix4(); //Temporary identity matrix -cc.current_stack = null; + //Initialize all 3 stacks + cc.modelview_matrix_stack.initialized(); + cc.projection_matrix_stack.initialized(); + cc.texture_matrix_stack.initialized(); -cc.initialized = false; - -cc.lazyInitialize = function () { - if (!cc.initialized) { - var identity = new cc.kmMat4(); //Temporary identity matrix - - //Initialize all 3 stacks - cc.km_mat4_stack_initialize(cc.modelview_matrix_stack); - cc.km_mat4_stack_initialize(cc.projection_matrix_stack); - cc.km_mat4_stack_initialize(cc.texture_matrix_stack); - - cc.current_stack = cc.modelview_matrix_stack; - cc.initialized = true; - cc.kmMat4Identity(identity); - - //Make sure that each stack has the identity matrix - cc.km_mat4_stack_push(cc.modelview_matrix_stack, identity); - cc.km_mat4_stack_push(cc.projection_matrix_stack, identity); - cc.km_mat4_stack_push(cc.texture_matrix_stack, identity); - } -}; - -cc.lazyInitialize(); - -cc.kmGLFreeAll = function () { - //Clear the matrix stacks - cc.km_mat4_stack_release(cc.modelview_matrix_stack); - cc.km_mat4_stack_release(cc.projection_matrix_stack); - cc.km_mat4_stack_release(cc.texture_matrix_stack); - - //Delete the matrices - cc.initialized = false; //Set to uninitialized - cc.current_stack = null; //Set the current stack to point nowhere -}; - -cc.kmGLPushMatrix = function () { - cc.km_mat4_stack_push(cc.current_stack, cc.current_stack.top); -}; - -cc.kmGLPushMatrixWitMat4 = function (saveMat) { - cc.current_stack.stack.push(cc.current_stack.top); - cc.kmMat4Assign(saveMat, cc.current_stack.top); - cc.current_stack.top = saveMat; -}; - -cc.kmGLPopMatrix = function () { - //No need to lazy initialize, you shouldnt be popping first anyway! - //cc.km_mat4_stack_pop(cc.current_stack, null); - cc.current_stack.top = cc.current_stack.stack.pop(); -}; - -cc.kmGLMatrixMode = function (mode) { - //cc.lazyInitialize(); - switch (mode) { - case cc.KM_GL_MODELVIEW: cc.current_stack = cc.modelview_matrix_stack; - break; - case cc.KM_GL_PROJECTION: - cc.current_stack = cc.projection_matrix_stack; - break; - case cc.KM_GL_TEXTURE: - cc.current_stack = cc.texture_matrix_stack; - break; - default: - throw "Invalid matrix mode specified"; //TODO: Proper error handling - break; - } -}; - -cc.kmGLLoadIdentity = function () { - //cc.lazyInitialize(); - cc.kmMat4Identity(cc.current_stack.top); //Replace the top matrix with the identity matrix -}; - -cc.kmGLLoadMatrix = function (pIn) { - //cc.lazyInitialize(); - cc.kmMat4Assign(cc.current_stack.top, pIn); -}; - -cc.kmGLMultMatrix = function (pIn) { - //cc.lazyInitialize(); - cc.kmMat4Multiply(cc.current_stack.top, cc.current_stack.top, pIn); -}; - -cc.kmGLTranslatef = function (x, y, z) { - var translation = new cc.kmMat4(); - - //Create a rotation matrix using the axis and the angle - cc.kmMat4Translation(translation, x, y, z); - - //Multiply the rotation matrix by the current matrix - cc.kmMat4Multiply(cc.current_stack.top, cc.current_stack.top, translation); -}; - -cc.kmGLRotatef = function (angle, x, y, z) { - var axis = new cc.math.Vec3(x, y, z); - var rotation = new cc.kmMat4(); - - //Create a rotation matrix using the axis and the angle - cc.kmMat4RotationAxisAngle(rotation, axis, cc.degreesToRadians(angle)); - - //Multiply the rotation matrix by the current matrix - cc.kmMat4Multiply(cc.current_stack.top, cc.current_stack.top, rotation); -}; - -cc.kmGLScalef = function (x, y, z) { - var scaling = new cc.kmMat4(); - cc.kmMat4Scaling(scaling, x, y, z); - cc.kmMat4Multiply(cc.current_stack.top, cc.current_stack.top, scaling); -}; - -cc.kmGLGetMatrix = function (mode, pOut) { - //cc.lazyInitialize(); - switch (mode) { - case cc.KM_GL_MODELVIEW: - cc.kmMat4Assign(pOut, cc.modelview_matrix_stack.top); - break; - case cc.KM_GL_PROJECTION: - cc.kmMat4Assign(pOut, cc.projection_matrix_stack.top); - break; - case cc.KM_GL_TEXTURE: - cc.kmMat4Assign(pOut, cc.texture_matrix_stack.top); - break; - default: - throw "Invalid matrix mode specified"; //TODO: Proper error handling - break; - } -}; + cc.initialized = true; + identity.identity(); + + //Make sure that each stack has the identity matrix + cc.modelview_matrix_stack.push(identity); + cc.projection_matrix_stack.push(identity); + cc.texture_matrix_stack.push(identity); + } + }; + + cc.lazyInitialize(); + + cc.kmGLFreeAll = function () { + //Clear the matrix stacks + cc.modelview_matrix_stack.release(); + cc.modelview_matrix_stack = null; + cc.projection_matrix_stack.release(); + cc.projection_matrix_stack = null; + cc.texture_matrix_stack.release(); + cc.texture_matrix_stack = null; + + //Delete the matrices + cc.initialized = false; //Set to uninitialized + cc.current_stack = null; //Set the current stack to point nowhere + }; + + cc.kmGLPushMatrix = function () { + cc.current_stack.push(cc.current_stack.top); + }; + + cc.kmGLPushMatrixWitMat4 = function (saveMat) { + cc.current_stack.stack.push(cc.current_stack.top); + saveMat.assignFrom(cc.current_stack.top); + cc.current_stack.top = saveMat; + }; + + cc.kmGLPopMatrix = function () { + //No need to lazy initialize, you shouldnt be popping first anyway! + //cc.km_mat4_stack_pop(cc.current_stack, null); + cc.current_stack.top = cc.current_stack.stack.pop(); + }; + + cc.kmGLMatrixMode = function (mode) { + //cc.lazyInitialize(); + switch (mode) { + case cc.KM_GL_MODELVIEW: + cc.current_stack = cc.modelview_matrix_stack; + break; + case cc.KM_GL_PROJECTION: + cc.current_stack = cc.projection_matrix_stack; + break; + case cc.KM_GL_TEXTURE: + cc.current_stack = cc.texture_matrix_stack; + break; + default: + throw "Invalid matrix mode specified"; //TODO: Proper error handling + break; + } + }; + + cc.kmGLLoadIdentity = function () { + //cc.lazyInitialize(); + cc.current_stack.top.identity(); //Replace the top matrix with the identity matrix + }; + + cc.kmGLLoadMatrix = function (pIn) { + //cc.lazyInitialize(); + cc.current_stack.top.assignFrom(pIn); + }; + + cc.kmGLMultMatrix = function (pIn) { + //cc.lazyInitialize(); + cc.current_stack.top.multiply(pIn); + }; + + var tempMatrix = new cc.math.Matrix4(); //an internal matrix + cc.kmGLTranslatef = function (x, y, z) { + //Create a rotation matrix using translation + var translation = cc.math.Matrix4.createByTranslation(x, y, z, tempMatrix); + + //Multiply the rotation matrix by the current matrix + cc.current_stack.top.multiply(translation); + }; + + var tempVector3 = new cc.math.Vec3(x, y, z); + cc.kmGLRotatef = function (angle, x, y, z) { + tempVector3.fill(x, y, z); + //Create a rotation matrix using the axis and the angle + var rotation = cc.math.Matrix4.createByAxisAndAngle(tempVector3, cc.degreesToRadians(angle), tempMatrix); + + //Multiply the rotation matrix by the current matrix + cc.current_stack.top.multiply(rotation); + }; + + cc.kmGLScalef = function (x, y, z) { + var scaling = cc.math.Matrix4.createByScale(x, y, z, tempMatrix); + cc.current_stack.top.multiply(scaling); + }; + + cc.kmGLGetMatrix = function (mode, pOut) { + //cc.lazyInitialize(); + switch (mode) { + case cc.KM_GL_MODELVIEW: + pOut.assignFrom(cc.modelview_matrix_stack.top); + break; + case cc.KM_GL_PROJECTION: + pOut.assignFrom(cc.projection_matrix_stack.top); + break; + case cc.KM_GL_TEXTURE: + pOut.assignFrom(cc.texture_matrix_stack.top); + break; + default: + throw "Invalid matrix mode specified"; //TODO: Proper error handling + break; + } + }; +})(cc); diff --git a/cocos2d/kazmath/mat3.js b/cocos2d/kazmath/mat3.js index 87c11a4871..737bc9b77f 100644 --- a/cocos2d/kazmath/mat3.js +++ b/cocos2d/kazmath/mat3.js @@ -30,10 +30,7 @@ var Float32Array = Float32Array || Array; (function(cc){ cc.math.Matrix3 = function(mat3) { if (mat3) { - var mat = mat3; - this.mat = new Float32Array([mat[0], mat[1], mat[2], - mat[3], mat[4], mat[5], - mat[60], mat[7], mat[8]]); + this.mat = new Float32Array(mat3); } else { this.mat = new Float32Array([0, 0, 0, 0, 0, 0, @@ -88,7 +85,7 @@ var Float32Array = Float32Array || Array; proto.inverse = function(determinate){ //cc.kmMat3Inverse if (determinate === 0.0) return this; - tmpMatrix.assign(this); + tmpMatrix.assignFrom(this); var detInv = 1.0 / determinate; this.adjugate(); this.multiplyScalar(detInv); @@ -189,7 +186,7 @@ var Float32Array = Float32Array || Array; return retMat; }; - proto.assign = function(matIn){ // cc.kmMat3Assign + proto.assignFrom = function(matIn){ // cc.kmMat3Assign if(this === matIn) { cc.log("cc.math.Matrix3.assign(): current matrix equals matIn"); return this; diff --git a/cocos2d/kazmath/mat4.js b/cocos2d/kazmath/mat4.js index f142132742..45b9a1d59b 100644 --- a/cocos2d/kazmath/mat4.js +++ b/cocos2d/kazmath/mat4.js @@ -26,779 +26,989 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/** - *

- A 4x4 matrix
-
- mat =
- | 0 4 8 12 |
- | 1 5 9 13 |
- | 2 6 10 14 |
- | 3 7 11 15 | -

- */ -cc.kmMat4 = function () { - this.mat = new Float32Array([0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0]); -}; +(function(cc) { + /** + *

+ * A 4x4 matrix
+ *
+ * mat =
+ * | 0 4 8 12 |
+ * | 1 5 9 13 |
+ * | 2 6 10 14 |
+ * | 3 7 11 15 | + *

+ * @param {cc.math.Matrix4} [mat4] + */ + cc.math.Matrix4 = function (mat4) { + if(mat4){ + this.mat = new Float32Array(mat4.mat); + } else { + this.mat = new Float32Array([0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0]); + } + }; + cc.kmMat4 = cc.math.Matrix4; + var proto = cc.math.Matrix4.prototype; -/** - * Fills a kmMat4 structure with the values from a 16 element array of floats - * @Params pOut - A pointer to the destination matrix - * @Params pMat - A 16 element array of floats - * @Return Returns pOut so that the call can be nested - */ -cc.kmMat4Fill = function (pOut, pMat) { - pOut.mat[0] = pOut.mat[1] = pOut.mat[2] =pOut.mat[3] = - pOut.mat[4] =pOut.mat[5] =pOut.mat[6] =pOut.mat[7] = - pOut.mat[8] =pOut.mat[9] =pOut.mat[10] =pOut.mat[11] = - pOut.mat[12] =pOut.mat[13] =pOut.mat[14] =pOut.mat[15] =pMat; -}; + /** + * Fills a cc.math.Matrix4 structure with the values from a 16 element array of floats + * @param {Array} scalarArr + */ + proto.fill = function(scalarArr){ //cc.kmMat4Fill + var mat = this.mat; + for(var i = 0; i < 16; i++){ + mat[i] = scalarArr[i]; + } + return this; + }; -/** - * Sets pOut to an identity matrix returns pOut - * @Params pOut - A pointer to the matrix to set to identity - * @Return Returns pOut so that the call can be nested - */ -cc.kmMat4Identity = function (pOut) { - pOut.mat[1] = pOut.mat[2] = pOut.mat[3] - = pOut.mat[4] = pOut.mat[6] = pOut.mat[7] - = pOut.mat[8] = pOut.mat[9] = pOut.mat[11] - = pOut.mat[12] = pOut.mat[13] = pOut.mat[14] = 0; - pOut.mat[0] = pOut.mat[5] = pOut.mat[10] = pOut.mat[15] = 1.0; - return pOut; -}; - -cc.kmMat4._get = function (pIn, row, col) { - return pIn.mat[row + 4 * col]; -}; - -cc.kmMat4._set = function (pIn, row, col, value) { - pIn.mat[row + 4 * col] = value; -}; - -cc.kmMat4._swap = function (pIn, r1, c1, r2, c2) { - var tmp = cc.kmMat4._get(pIn, r1, c1); - cc.kmMat4._set(pIn, r1, c1, cc.kmMat4._get(pIn, r2, c2)); - cc.kmMat4._set(pIn, r2, c2, tmp); -}; - -//Returns an upper and a lower triangular matrix which are L and R in the Gauss algorithm -cc.kmMat4._gaussj = function (a, b) { - var i, icol = 0, irow = 0, j, k, l, ll, n = 4, m = 4; - var big, dum, pivinv; - var indxc = [0, 0, 0, 0]; - var indxr = [0, 0, 0, 0]; - var ipiv = [0, 0, 0, 0]; - - /* for (j = 0; j < n; j++) { - ipiv[j] = 0; - }*/ - - for (i = 0; i < n; i++) { - big = 0.0; - for (j = 0; j < n; j++) { - if (ipiv[j] != 1) { - for (k = 0; k < n; k++) { - if (ipiv[k] == 0) { - if (Math.abs(cc.kmMat4._get(a, j, k)) >= big) { - big = Math.abs(cc.kmMat4._get(a, j, k)); - irow = j; - icol = k; + /** + * Sets pOut to an identity matrix returns pOut + * @Params pOut - A pointer to the matrix to set to identity + * @Return Returns pOut so that the call can be nested + */ + cc.kmMat4Identity = function (pOut) { + var mat = pOut.mat; + mat[1] = mat[2] = mat[3] = mat[4] = mat[6] = mat[7] + = mat[8] = mat[9] = mat[11] = mat[12] = mat[13] = mat[14] = 0; + mat[0] = mat[5] = mat[10] = mat[15] = 1.0; + return pOut; + }; + + /** + * Sets matrix to identity value. + * @returns {cc.math.Matrix4} + */ + proto.identity = function(){ + var mat = this.mat; + mat[1] = mat[2] = mat[3] = mat[4] = mat[6] = mat[7] + = mat[8] = mat[9] = mat[11] = mat[12] = mat[13] = mat[14] = 0; + mat[0] = mat[5] = mat[10] = mat[15] = 1.0; + return this; + }; + + proto.get = function(row, col){ + return this.mat[row + 4 * col]; + }; + + proto.set = function(row, col, value){ + this.mat[row + 4 * col] = value; + }; + + proto.swap = function(r1, c1, r2, c2) { +/* var tmp = this.get(r1, c1); + this.set(r1, c1, this.get(r2, c2)); + this.set(r2, c2, tmp);*/ + var mat = this.mat, tmp = mat[r1 + 4 * c1]; + mat[r1 + 4 * c1] = mat[r2 + 4 * c2]; + mat[r2 + 4 * c2] = tmp; + }; + + //Returns an upper and a lower triangular matrix which are L and R in the Gauss algorithm + cc.math.Matrix4._gaussj = function (a, b) { + var i, icol = 0, irow = 0, j, k, l, ll, n = 4, m = 4, selElement; + var big, dum, pivinv; + var indxc = [0, 0, 0, 0], indxr = [0, 0, 0, 0], ipiv = [0, 0, 0, 0]; + + /* for (j = 0; j < n; j++) { + ipiv[j] = 0; + }*/ + + for (i = 0; i < n; i++) { + big = 0.0; + for (j = 0; j < n; j++) { + if (ipiv[j] !== 1) { + for (k = 0; k < n; k++) { + if (ipiv[k] === 0) { + selElement = Math.abs(a.get(j, k)); + if (selElement >= big) { + big = selElement; + irow = j; + icol = k; + } } } } } - } - ++(ipiv[icol]); - if (irow != icol) { - for (l = 0; l < n; l++) - cc.kmMat4._swap(a, irow, l, icol, l); - for (l = 0; l < m; l++) - cc.kmMat4._swap(b, irow, l, icol, l); - } - indxr[i] = irow; - indxc[i] = icol; - if (cc.kmMat4._get(a, icol, icol) == 0.0) - return false; - - pivinv = 1.0 / cc.kmMat4._get(a, icol, icol); - cc.kmMat4._set(a, icol, icol, 1.0); - for (l = 0; l < n; l++) - cc.kmMat4._set(a, icol, l, cc.kmMat4._get(a, icol, l) * pivinv); - - for (l = 0; l < m; l++) - cc.kmMat4._set(b, icol, l, cc.kmMat4._get(b, icol, l) * pivinv); - - for (ll = 0; ll < n; ll++) { - if (ll != icol) { - dum = cc.kmMat4._get(a, ll, icol); - cc.kmMat4._set(a, ll, icol, 0.0); + ++(ipiv[icol]); + if (irow != icol) { for (l = 0; l < n; l++) - cc.kmMat4._set(a, ll, l, cc.kmMat4._get(a, ll, l) - cc.kmMat4._get(a, icol, l) * dum); - + a.swap(irow, l, icol, l); for (l = 0; l < m; l++) - cc.kmMat4._set(b, ll, l, cc.kmMat4._get(a, ll, l) - cc.kmMat4._get(b, icol, l) * dum); + b.swap(irow, l, icol, l); } - } - } -// This is the end of the main loop over columns of the reduction. It only remains to unscram- -// ble the solution in view of the column interchanges. We do this by interchanging pairs of -// columns in the reverse order that the permutation was built up. - for (l = n - 1; l >= 0; l--) { - if (indxr[l] != indxc[l]) { - for (k = 0; k < n; k++) - cc.kmMat4._swap(a, k, indxr[l], k, indxc[l]); - } - } - return true; -}; - -cc.kmMat4._identity = - new Float32Array([1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0]); - -/** - * Calculates the inverse of pM and stores the result in - * pOut. - * @Return Returns NULL if there is no inverse, else pOut - */ -cc.kmMat4Inverse = function (pOut, pM) { - var inv = new cc.kmMat4(); - var tmp = new cc.kmMat4(); + indxr[i] = irow; + indxc[i] = icol; + if (a.get(icol, icol) === 0.0) + return false; - cc.kmMat4Assign(inv, pM); - cc.kmMat4Identity(tmp); - - if (cc.kmMat4._gaussj(inv, tmp) == false) - return null; + pivinv = 1.0 / a.get(icol, icol); + a.set(icol, icol, 1.0); + for (l = 0; l < n; l++) + a.set(icol, l, a.get(icol, l) * pivinv); - cc.kmMat4Assign(pOut, inv); - return pOut; -}; + for (l = 0; l < m; l++) + b.set(icol, l, b.get(icol, l) * pivinv); -/** - * Returns KM_TRUE if pIn is an identity matrix - * KM_FALSE otherwise - */ -cc.kmMat4IsIdentity = function (pIn) { - for (var i = 0; i < 16; i++) { - if (cc.kmMat4._identity[i] != pIn.mat[i]) - return false; - } - return true; -}; + for (ll = 0; ll < n; ll++) { + if (ll != icol) { + dum = a.get(ll, icol); + a.set(ll, icol, 0.0); + for (l = 0; l < n; l++) + a.set(ll, l, a.get(ll, l) - a.get(icol, l) * dum); -/** - * Sets pOut to the transpose of pIn, returns pOut - */ -cc.kmMat4Transpose = function (pOut, pIn) { - var x, z, outArr = pOut.mat,inArr = pIn.mat; - for (z = 0; z < 4; ++z) { - for (x = 0; x < 4; ++x) - outArr[(z * 4) + x] = inArr[(x * 4) + z]; - } - return pOut; -}; + for (l = 0; l < m; l++) + b.set(ll, l, a.get(ll, l) - b.get(icol, l) * dum); + } + } + } + // This is the end of the main loop over columns of the reduction. It only remains to unscram- + // ble the solution in view of the column interchanges. We do this by interchanging pairs of + // columns in the reverse order that the permutation was built up. + for (l = n - 1; l >= 0; l--) { + if (indxr[l] != indxc[l]) { + for (k = 0; k < n; k++) + a.swap(k, indxr[l], k, indxc[l]); + } + } + return true; + }; -/** - * Multiplies pM1 with pM2, stores the result in pOut, returns pOut - */ -cc.kmMat4Multiply = function (pOut, pM1, pM2) { - // Cache the matrix values (makes for huge speed increases!) - var outArray = pOut.mat; - var a00 = pM1.mat[0], a01 = pM1.mat[1], a02 = pM1.mat[2], a03 = pM1.mat[3]; - var a10 = pM1.mat[4], a11 = pM1.mat[5], a12 = pM1.mat[6], a13 = pM1.mat[7]; - var a20 = pM1.mat[8], a21 = pM1.mat[9], a22 = pM1.mat[10], a23 = pM1.mat[11]; - var a30 = pM1.mat[12], a31 = pM1.mat[13], a32 = pM1.mat[14], a33 = pM1.mat[15]; - - var b00 = pM2.mat[0], b01 = pM2.mat[1], b02 = pM2.mat[2], b03 = pM2.mat[3]; - var b10 = pM2.mat[4], b11 = pM2.mat[5], b12 = pM2.mat[6], b13 = pM2.mat[7]; - var b20 = pM2.mat[8], b21 = pM2.mat[9], b22 = pM2.mat[10], b23 = pM2.mat[11]; - var b30 = pM2.mat[12], b31 = pM2.mat[13], b32 = pM2.mat[14], b33 = pM2.mat[15]; - - outArray[0] = b00 * a00 + b01 * a10 + b02 * a20 + b03 * a30; - outArray[1] = b00 * a01 + b01 * a11 + b02 * a21 + b03 * a31; - outArray[2] = b00 * a02 + b01 * a12 + b02 * a22 + b03 * a32; - outArray[3] = b00 * a03 + b01 * a13 + b02 * a23 + b03 * a33; - outArray[4] = b10 * a00 + b11 * a10 + b12 * a20 + b13 * a30; - outArray[5] = b10 * a01 + b11 * a11 + b12 * a21 + b13 * a31; - outArray[6] = b10 * a02 + b11 * a12 + b12 * a22 + b13 * a32; - outArray[7] = b10 * a03 + b11 * a13 + b12 * a23 + b13 * a33; - outArray[8] = b20 * a00 + b21 * a10 + b22 * a20 + b23 * a30; - outArray[9] = b20 * a01 + b21 * a11 + b22 * a21 + b23 * a31; - outArray[10] = b20 * a02 + b21 * a12 + b22 * a22 + b23 * a32; - outArray[11] = b20 * a03 + b21 * a13 + b22 * a23 + b23 * a33; - outArray[12] = b30 * a00 + b31 * a10 + b32 * a20 + b33 * a30; - outArray[13] = b30 * a01 + b31 * a11 + b32 * a21 + b33 * a31; - outArray[14] = b30 * a02 + b31 * a12 + b32 * a22 + b33 * a32; - outArray[15] = b30 * a03 + b31 * a13 + b32 * a23 + b33 * a33; - return pOut; -}; - -cc.getMat4MultiplyValue = function (pM1, pM2) { - var m1 = pM1.mat, m2 = pM2.mat; - var mat = new Float32Array(16); - - mat[0] = m1[0] * m2[0] + m1[4] * m2[1] + m1[8] * m2[2] + m1[12] * m2[3]; - mat[1] = m1[1] * m2[0] + m1[5] * m2[1] + m1[9] * m2[2] + m1[13] * m2[3]; - mat[2] = m1[2] * m2[0] + m1[6] * m2[1] + m1[10] * m2[2] + m1[14] * m2[3]; - mat[3] = m1[3] * m2[0] + m1[7] * m2[1] + m1[11] * m2[2] + m1[15] * m2[3]; - - mat[4] = m1[0] * m2[4] + m1[4] * m2[5] + m1[8] * m2[6] + m1[12] * m2[7]; - mat[5] = m1[1] * m2[4] + m1[5] * m2[5] + m1[9] * m2[6] + m1[13] * m2[7]; - mat[6] = m1[2] * m2[4] + m1[6] * m2[5] + m1[10] * m2[6] + m1[14] * m2[7]; - mat[7] = m1[3] * m2[4] + m1[7] * m2[5] + m1[11] * m2[6] + m1[15] * m2[7]; - - mat[8] = m1[0] * m2[8] + m1[4] * m2[9] + m1[8] * m2[10] + m1[12] * m2[11]; - mat[9] = m1[1] * m2[8] + m1[5] * m2[9] + m1[9] * m2[10] + m1[13] * m2[11]; - mat[10] = m1[2] * m2[8] + m1[6] * m2[9] + m1[10] * m2[10] + m1[14] * m2[11]; - mat[11] = m1[3] * m2[8] + m1[7] * m2[9] + m1[11] * m2[10] + m1[15] * m2[11]; - - mat[12] = m1[0] * m2[12] + m1[4] * m2[13] + m1[8] * m2[14] + m1[12] * m2[15]; - mat[13] = m1[1] * m2[12] + m1[5] * m2[13] + m1[9] * m2[14] + m1[13] * m2[15]; - mat[14] = m1[2] * m2[12] + m1[6] * m2[13] + m1[10] * m2[14] + m1[14] * m2[15]; - mat[15] = m1[3] * m2[12] + m1[7] * m2[13] + m1[11] * m2[14] + m1[15] * m2[15]; - - return mat; -}; - -cc.getMat4MultiplyWithMat4 = function (pM1, pM2, swapMat) { - var m1 = pM1.mat, m2 = pM2.mat; - var mat = swapMat.mat; - - mat[0] = m1[0] * m2[0] + m1[4] * m2[1] + m1[8] * m2[2] + m1[12] * m2[3]; - mat[1] = m1[1] * m2[0] + m1[5] * m2[1] + m1[9] * m2[2] + m1[13] * m2[3]; - mat[2] = m1[2] * m2[0] + m1[6] * m2[1] + m1[10] * m2[2] + m1[14] * m2[3]; - mat[3] = m1[3] * m2[0] + m1[7] * m2[1] + m1[11] * m2[2] + m1[15] * m2[3]; - - mat[4] = m1[0] * m2[4] + m1[4] * m2[5] + m1[8] * m2[6] + m1[12] * m2[7]; - mat[5] = m1[1] * m2[4] + m1[5] * m2[5] + m1[9] * m2[6] + m1[13] * m2[7]; - mat[6] = m1[2] * m2[4] + m1[6] * m2[5] + m1[10] * m2[6] + m1[14] * m2[7]; - mat[7] = m1[3] * m2[4] + m1[7] * m2[5] + m1[11] * m2[6] + m1[15] * m2[7]; - - mat[8] = m1[0] * m2[8] + m1[4] * m2[9] + m1[8] * m2[10] + m1[12] * m2[11]; - mat[9] = m1[1] * m2[8] + m1[5] * m2[9] + m1[9] * m2[10] + m1[13] * m2[11]; - mat[10] = m1[2] * m2[8] + m1[6] * m2[9] + m1[10] * m2[10] + m1[14] * m2[11]; - mat[11] = m1[3] * m2[8] + m1[7] * m2[9] + m1[11] * m2[10] + m1[15] * m2[11]; - - mat[12] = m1[0] * m2[12] + m1[4] * m2[13] + m1[8] * m2[14] + m1[12] * m2[15]; - mat[13] = m1[1] * m2[12] + m1[5] * m2[13] + m1[9] * m2[14] + m1[13] * m2[15]; - mat[14] = m1[2] * m2[12] + m1[6] * m2[13] + m1[10] * m2[14] + m1[14] * m2[15]; - mat[15] = m1[3] * m2[12] + m1[7] * m2[13] + m1[11] * m2[14] + m1[15] * m2[15]; - - return swapMat.mat; -}; + var identityMatrix = new cc.math.Matrix4().identity(); + /** + * Calculates the inverse of pM and stores the result in pOut. + * Please use matrix4's inverse function instead. + * @Return Returns NULL if there is no inverse, else pOut + */ + cc.kmMat4Inverse = function (pOut, pM) { + var inv = new cc.math.Matrix4(pM); + if (cc.math.Matrix4._gaussj(inv, identityMatrix) === false) + return null; + pOut.assignFrom(inv); + return pOut; + }; -/** - * Assigns the value of pIn to pOut - */ -cc.kmMat4Assign = function (pOut, pIn) { - if(pOut == pIn) { - cc.log("cc.kmMat4Assign(): pOut equals pIn"); + /** + * Calculates the inverse of current matrix. + * @returns {cc.math.Matrix4} Returns null if there is no inverse, else returns a new inverse matrix object + */ + proto.inverse = function(){ //cc.kmMat4Inverse + var inv = new cc.math.Matrix4(this); + if (cc.math.Matrix4._gaussj(inv, identityMatrix) === false) + return null; + return inv; + }; + + /** + * Returns true if current matrix is an identity matrix, false otherwise + */ + proto.isIdentity = function () { // cc.kmMat4IsIdentity + var mat = this.mat; + return (mat[0] === 1 && mat[1] === 0 && mat[2] === 0 && mat[3] === 0 + && mat[4] === 0 && mat[5] === 1 && mat[6] === 0 && mat[7] === 0 + && mat[8] === 0 && mat[9] === 0 && mat[10] === 1 && mat[11] === 0 + && mat[12] === 0 && mat[13] === 0 && mat[14] === 0 && mat[15] === 1); + }; + + /** + * transpose the current matrix + */ + proto.transpose = function() { // cc.kmMat4Transpose + var mat = this.mat; + var m1 = mat[1], m2 = mat[2], m3 = mat[3], + m4 = mat[4], m6 = mat[6], m7 = mat[7], + m8 = mat[8], m9 = mat[9], m11 = mat[11], + m12 = mat[12], m13 = mat[13], m14 = mat[14]; + mat[1] = m4; + mat[2] = m8; + mat[3] = m12; + + mat[4] = m1; + mat[6] = m9; + mat[7] = m13; + + mat[8] = m2; + mat[9] = m6; + mat[11] = m14; + + mat[12] = m3; + mat[13] = m7; + mat[14] = m11; + return this; + }; + + /** + * Multiplies pM1 with pM2, stores the result in pOut, returns pOut + */ + cc.kmMat4Multiply = function (pOut, pM1, pM2) { + // Cache the matrix values (makes for huge speed increases!) + var outArray = pOut.mat, mat1 = pM1.mat, mat2 = pM2.mat; + var a00 = mat1[0], a01 = mat1[1], a02 = mat1[2], a03 = mat1[3]; + var a10 = mat1[4], a11 = mat1[5], a12 = mat1[6], a13 = mat1[7]; + var a20 = mat1[8], a21 = mat1[9], a22 = mat1[10], a23 = mat1[11]; + var a30 = mat1[12], a31 = mat1[13], a32 = mat1[14], a33 = mat1[15]; + + var b00 = mat2[0], b01 = mat2[1], b02 = mat2[2], b03 = mat2[3]; + var b10 = mat2[4], b11 = mat2[5], b12 = mat2[6], b13 = mat2[7]; + var b20 = mat2[8], b21 = mat2[9], b22 = mat2[10], b23 = mat2[11]; + var b30 = mat2[12], b31 = mat2[13], b32 = mat2[14], b33 = mat2[15]; + + outArray[0] = b00 * a00 + b01 * a10 + b02 * a20 + b03 * a30; + outArray[1] = b00 * a01 + b01 * a11 + b02 * a21 + b03 * a31; + outArray[2] = b00 * a02 + b01 * a12 + b02 * a22 + b03 * a32; + outArray[3] = b00 * a03 + b01 * a13 + b02 * a23 + b03 * a33; + outArray[4] = b10 * a00 + b11 * a10 + b12 * a20 + b13 * a30; + outArray[5] = b10 * a01 + b11 * a11 + b12 * a21 + b13 * a31; + outArray[6] = b10 * a02 + b11 * a12 + b12 * a22 + b13 * a32; + outArray[7] = b10 * a03 + b11 * a13 + b12 * a23 + b13 * a33; + outArray[8] = b20 * a00 + b21 * a10 + b22 * a20 + b23 * a30; + outArray[9] = b20 * a01 + b21 * a11 + b22 * a21 + b23 * a31; + outArray[10] = b20 * a02 + b21 * a12 + b22 * a22 + b23 * a32; + outArray[11] = b20 * a03 + b21 * a13 + b22 * a23 + b23 * a33; + outArray[12] = b30 * a00 + b31 * a10 + b32 * a20 + b33 * a30; + outArray[13] = b30 * a01 + b31 * a11 + b32 * a21 + b33 * a31; + outArray[14] = b30 * a02 + b31 * a12 + b32 * a22 + b33 * a32; + outArray[15] = b30 * a03 + b31 * a13 + b32 * a23 + b33 * a33; return pOut; - } + }; - var outArr = pOut.mat; - var inArr = pIn.mat; + /** + * current matrix multiplies with other matrix mat4 + * @param {cc.math.Matrix4} mat4 + * @returns {cc.math.Matrix4} + */ + proto.multiply = function(mat4){ + // Cache the matrix values (makes for huge speed increases!) + var mat = this.mat, mat2 = mat4.mat; + var a00 = mat[0], a01 = mat[1], a02 = mat[2], a03 = mat[3]; + var a10 = mat[4], a11 = mat[5], a12 = mat[6], a13 = mat[7]; + var a20 = mat[8], a21 = mat[9], a22 = mat[10], a23 = mat[11]; + var a30 = mat[12], a31 = mat[13], a32 = mat[14], a33 = mat[15]; + + var b00 = mat2[0], b01 = mat2[1], b02 = mat2[2], b03 = mat2[3]; + var b10 = mat2[4], b11 = mat2[5], b12 = mat2[6], b13 = mat2[7]; + var b20 = mat2[8], b21 = mat2[9], b22 = mat2[10], b23 = mat2[11]; + var b30 = mat2[12], b31 = mat2[13], b32 = mat2[14], b33 = mat2[15]; + + mat[0] = b00 * a00 + b01 * a10 + b02 * a20 + b03 * a30; + mat[1] = b00 * a01 + b01 * a11 + b02 * a21 + b03 * a31; + mat[2] = b00 * a02 + b01 * a12 + b02 * a22 + b03 * a32; + mat[3] = b00 * a03 + b01 * a13 + b02 * a23 + b03 * a33; + mat[4] = b10 * a00 + b11 * a10 + b12 * a20 + b13 * a30; + mat[5] = b10 * a01 + b11 * a11 + b12 * a21 + b13 * a31; + mat[6] = b10 * a02 + b11 * a12 + b12 * a22 + b13 * a32; + mat[7] = b10 * a03 + b11 * a13 + b12 * a23 + b13 * a33; + mat[8] = b20 * a00 + b21 * a10 + b22 * a20 + b23 * a30; + mat[9] = b20 * a01 + b21 * a11 + b22 * a21 + b23 * a31; + mat[10] = b20 * a02 + b21 * a12 + b22 * a22 + b23 * a32; + mat[11] = b20 * a03 + b21 * a13 + b22 * a23 + b23 * a33; + mat[12] = b30 * a00 + b31 * a10 + b32 * a20 + b33 * a30; + mat[13] = b30 * a01 + b31 * a11 + b32 * a21 + b33 * a31; + mat[14] = b30 * a02 + b31 * a12 + b32 * a22 + b33 * a32; + mat[15] = b30 * a03 + b31 * a13 + b32 * a23 + b33 * a33; + return this; + }; + + cc.getMat4MultiplyValue = function (pM1, pM2) { + var m1 = pM1.mat, m2 = pM2.mat; + var mat = new Float32Array(16); + + mat[0] = m1[0] * m2[0] + m1[4] * m2[1] + m1[8] * m2[2] + m1[12] * m2[3]; + mat[1] = m1[1] * m2[0] + m1[5] * m2[1] + m1[9] * m2[2] + m1[13] * m2[3]; + mat[2] = m1[2] * m2[0] + m1[6] * m2[1] + m1[10] * m2[2] + m1[14] * m2[3]; + mat[3] = m1[3] * m2[0] + m1[7] * m2[1] + m1[11] * m2[2] + m1[15] * m2[3]; + + mat[4] = m1[0] * m2[4] + m1[4] * m2[5] + m1[8] * m2[6] + m1[12] * m2[7]; + mat[5] = m1[1] * m2[4] + m1[5] * m2[5] + m1[9] * m2[6] + m1[13] * m2[7]; + mat[6] = m1[2] * m2[4] + m1[6] * m2[5] + m1[10] * m2[6] + m1[14] * m2[7]; + mat[7] = m1[3] * m2[4] + m1[7] * m2[5] + m1[11] * m2[6] + m1[15] * m2[7]; + + mat[8] = m1[0] * m2[8] + m1[4] * m2[9] + m1[8] * m2[10] + m1[12] * m2[11]; + mat[9] = m1[1] * m2[8] + m1[5] * m2[9] + m1[9] * m2[10] + m1[13] * m2[11]; + mat[10] = m1[2] * m2[8] + m1[6] * m2[9] + m1[10] * m2[10] + m1[14] * m2[11]; + mat[11] = m1[3] * m2[8] + m1[7] * m2[9] + m1[11] * m2[10] + m1[15] * m2[11]; + + mat[12] = m1[0] * m2[12] + m1[4] * m2[13] + m1[8] * m2[14] + m1[12] * m2[15]; + mat[13] = m1[1] * m2[12] + m1[5] * m2[13] + m1[9] * m2[14] + m1[13] * m2[15]; + mat[14] = m1[2] * m2[12] + m1[6] * m2[13] + m1[10] * m2[14] + m1[14] * m2[15]; + mat[15] = m1[3] * m2[12] + m1[7] * m2[13] + m1[11] * m2[14] + m1[15] * m2[15]; + + return mat; + }; + + /** + * Assigns the value of pIn to pOut + */ + cc.kmMat4Assign = function (pOut, pIn) { + if (pOut === pIn) { + cc.log("cc.kmMat4Assign(): pOut equals pIn"); + return pOut; + } - outArr[0] = inArr[0]; - outArr[1] = inArr[1]; - outArr[2] = inArr[2]; - outArr[3] = inArr[3]; + var outArr = pOut.mat; + var inArr = pIn.mat; - outArr[4] = inArr[4]; - outArr[5] = inArr[5]; - outArr[6] = inArr[6]; - outArr[7] = inArr[7]; + outArr[0] = inArr[0]; + outArr[1] = inArr[1]; + outArr[2] = inArr[2]; + outArr[3] = inArr[3]; - outArr[8] = inArr[8]; - outArr[9] = inArr[9]; - outArr[10] = inArr[10]; - outArr[11] = inArr[11]; + outArr[4] = inArr[4]; + outArr[5] = inArr[5]; + outArr[6] = inArr[6]; + outArr[7] = inArr[7]; - outArr[12] = inArr[12]; - outArr[13] = inArr[13]; - outArr[14] = inArr[14]; - outArr[15] = inArr[15]; - return pOut; -}; + outArr[8] = inArr[8]; + outArr[9] = inArr[9]; + outArr[10] = inArr[10]; + outArr[11] = inArr[11]; -/** - * Returns KM_TRUE if the 2 matrices are equal (approximately) - */ -cc.kmMat4AreEqual = function (pMat1, pMat2) { - if(pMat1 == pMat2){ - cc.log("cc.kmMat4AreEqual(): pMat1 and pMat2 are same object."); - return true; - } + outArr[12] = inArr[12]; + outArr[13] = inArr[13]; + outArr[14] = inArr[14]; + outArr[15] = inArr[15]; + return pOut; + }; - for (var i = 0; i < 16; i++) { - if (!(pMat1.mat[i] + cc.math.EPSILON > pMat2.mat[i] && - pMat1.mat[i] - cc.math.EPSILON < pMat2.mat[i])) { - return false; + /** + * Assigns the value of current matrix from mat4 + * @param {cc.math.Matrix4} mat4 + * @returns {cc.math.Matrix4} + */ + proto.assignFrom = function(mat4) { + if (this == mat4) { + cc.log("cc.mat.Matrix4.assignFrom(): mat4 equals current matrix"); + return this; } - } - return true; -}; - -/** - * Builds an X-axis rotation matrix and stores it in pOut, returns pOut - */ -cc.kmMat4RotationX = function (pOut, radians) { - /* - | 1 0 0 0 | - M = | 0 cos(A) -sin(A) 0 | - | 0 sin(A) cos(A) 0 | - | 0 0 0 1 | - + var outArr = this.mat, inArr = mat4.mat; + + outArr[0] = inArr[0]; + outArr[1] = inArr[1]; + outArr[2] = inArr[2]; + outArr[3] = inArr[3]; + + outArr[4] = inArr[4]; + outArr[5] = inArr[5]; + outArr[6] = inArr[6]; + outArr[7] = inArr[7]; + + outArr[8] = inArr[8]; + outArr[9] = inArr[9]; + outArr[10] = inArr[10]; + outArr[11] = inArr[11]; + + outArr[12] = inArr[12]; + outArr[13] = inArr[13]; + outArr[14] = inArr[14]; + outArr[15] = inArr[15]; + return this; + }; + + /** + * Returns true if current matrix equal mat4 (approximately) + * @param {cc.math.Matrix4} mat4 + * @returns {boolean} */ + proto.equals = function(mat4) { + if (this === mat4) { + cc.log("cc.kmMat4AreEqual(): pMat1 and pMat2 are same object."); + return true; + } + var matA = this.mat, matB = mat4.mat, EPSILON = cc.math.EPSILON; + for (var i = 0; i < 16; i++) { + if (!(matA[i] + EPSILON > matB[i] && matA[i] - EPSILON < matB[i])) + return false; + } + return true; + }; - pOut.mat[0] = 1.0; - pOut.mat[1] = 0.0; - pOut.mat[2] = 0.0; - pOut.mat[3] = 0.0; - - pOut.mat[4] = 0.0; - pOut.mat[5] = Math.cos(radians); - pOut.mat[6] = Math.sin(radians); - pOut.mat[7] = 0.0; - - pOut.mat[8] = 0.0; - pOut.mat[9] = -Math.sin(radians); - pOut.mat[10] = Math.cos(radians); - pOut.mat[11] = 0.0; - - pOut.mat[12] = 0.0; - pOut.mat[13] = 0.0; - pOut.mat[14] = 0.0; - pOut.mat[15] = 1.0; - - return pOut; -}; - -/** - * Builds a rotation matrix using the rotation around the Y-axis - * The result is stored in pOut, pOut is returned. - */ -cc.kmMat4RotationY = function (pOut, radians) { - /* - | cos(A) 0 sin(A) 0 | - M = | 0 1 0 0 | - | -sin(A) 0 cos(A) 0 | - | 0 0 0 1 | - */ - pOut.mat[0] = Math.cos(radians); - pOut.mat[1] = 0.0; - pOut.mat[2] = -Math.sin(radians); - pOut.mat[3] = 0.0; - - pOut.mat[4] = 0.0; - pOut.mat[5] = 1.0; - pOut.mat[6] = 0.0; - pOut.mat[7] = 0.0; - - pOut.mat[8] = Math.sin(radians); - pOut.mat[9] = 0.0; - pOut.mat[10] = Math.cos(radians); - pOut.mat[11] = 0.0; - - pOut.mat[12] = 0.0; - pOut.mat[13] = 0.0; - pOut.mat[14] = 0.0; - pOut.mat[15] = 1.0; - - return pOut; -}; - -/** - * Builds a rotation matrix around the Z-axis. The resulting - * matrix is stored in pOut. pOut is returned. - */ -cc.kmMat4RotationZ = function (pOut, radians) { - /* - | cos(A) -sin(A) 0 0 | - M = | sin(A) cos(A) 0 0 | - | 0 0 1 0 | - | 0 0 0 1 | - */ - pOut.mat[0] = Math.cos(radians); - pOut.mat[1] = Math.sin(radians); - pOut.mat[2] = 0.0; - pOut.mat[3] = 0.0; - - pOut.mat[4] = -Math.sin(radians); - pOut.mat[5] = Math.cos(radians); - pOut.mat[6] = 0.0; - pOut.mat[7] = 0.0; - - pOut.mat[8] = 0.0; - pOut.mat[9] = 0.0; - pOut.mat[10] = 1.0; - pOut.mat[11] = 0.0; - - pOut.mat[12] = 0.0; - pOut.mat[13] = 0.0; - pOut.mat[14] = 0.0; - pOut.mat[15] = 1.0; - - return pOut; -}; - -/** - * Builds a rotation matrix from pitch, yaw and roll. The resulting - * matrix is stored in pOut and pOut is returned - */ -cc.kmMat4RotationPitchYawRoll = function (pOut, pitch, yaw, roll) { - var cr = Math.cos(pitch); - var sr = Math.sin(pitch); - var cp = Math.cos(yaw); - var sp = Math.sin(yaw); - var cy = Math.cos(roll); - var sy = Math.sin(roll); - var srsp = sr * sp; - var crsp = cr * sp; - - pOut.mat[0] = cp * cy; - pOut.mat[4] = cp * sy; - pOut.mat[8] = -sp; - - pOut.mat[1] = srsp * cy - cr * sy; - pOut.mat[5] = srsp * sy + cr * cy; - pOut.mat[9] = sr * cp; - - pOut.mat[2] = crsp * cy + sr * sy; - pOut.mat[6] = crsp * sy - sr * cy; - pOut.mat[10] = cr * cp; - - pOut.mat[3] = pOut.mat[7] = pOut.mat[11] = 0.0; - pOut.mat[15] = 1.0; - - return pOut; -}; - -/** Converts a quaternion to a rotation matrix, - * the result is stored in pOut, returns pOut - */ -cc.kmMat4RotationQuaternion = function (pOut, pQ) { - pOut.mat[0] = 1.0 - 2.0 * (pQ.y * pQ.y + pQ.z * pQ.z ); - pOut.mat[1] = 2.0 * (pQ.x * pQ.y + pQ.z * pQ.w); - pOut.mat[2] = 2.0 * (pQ.x * pQ.z - pQ.y * pQ.w); - pOut.mat[3] = 0.0; - - // Second row - pOut.mat[4] = 2.0 * ( pQ.x * pQ.y - pQ.z * pQ.w ); - pOut.mat[5] = 1.0 - 2.0 * ( pQ.x * pQ.x + pQ.z * pQ.z ); - pOut.mat[6] = 2.0 * (pQ.z * pQ.y + pQ.x * pQ.w ); - pOut.mat[7] = 0.0; - - // Third row - pOut.mat[8] = 2.0 * ( pQ.x * pQ.z + pQ.y * pQ.w ); - pOut.mat[9] = 2.0 * ( pQ.y * pQ.z - pQ.x * pQ.w ); - pOut.mat[10] = 1.0 - 2.0 * ( pQ.x * pQ.x + pQ.y * pQ.y ); - pOut.mat[11] = 0.0; - - // Fourth row - pOut.mat[12] = 0; - pOut.mat[13] = 0; - pOut.mat[14] = 0; - pOut.mat[15] = 1.0; - - return pOut; -}; - -/** Build a 4x4 OpenGL transformation matrix using a 3x3 rotation matrix, - * and a 3d vector representing a translation. Assign the result to pOut, - * pOut is also returned. - */ -cc.kmMat4RotationTranslation = function (pOut, rotation, translation) { - pOut.mat[0] = rotation.mat[0]; - pOut.mat[1] = rotation.mat[1]; - pOut.mat[2] = rotation.mat[2]; - pOut.mat[3] = 0.0; - - pOut.mat[4] = rotation.mat[3]; - pOut.mat[5] = rotation.mat[4]; - pOut.mat[6] = rotation.mat[5]; - pOut.mat[7] = 0.0; - - pOut.mat[8] = rotation.mat[6]; - pOut.mat[9] = rotation.mat[7]; - pOut.mat[10] = rotation.mat[8]; - pOut.mat[11] = 0.0; - - pOut.mat[12] = translation.x; - pOut.mat[13] = translation.y; - pOut.mat[14] = translation.z; - pOut.mat[15] = 1.0; - - return pOut; -}; - -/** Builds a scaling matrix */ -cc.kmMat4Scaling = function (pOut, x, y, z) { - pOut.mat[0] = x; - pOut.mat[5] = y; - pOut.mat[10] = z; - pOut.mat[15] = 1.0; - pOut.mat[1] = pOut.mat[2] = pOut.mat[3] = - pOut.mat[4] = pOut.mat[6] = pOut.mat[7] = - pOut.mat[8] = pOut.mat[9] = pOut.mat[11] = - pOut.mat[12] = pOut.mat[13] = pOut.mat[14] = 0; - return pOut; -}; - -/** - * Builds a translation matrix. All other elements in the matrix - * will be set to zero except for the diagonal which is set to 1.0 - */ -cc.kmMat4Translation = function (pOut, x, y, z) { - //FIXME: Write a test for this - pOut.mat[0] = pOut.mat[5] = pOut.mat[10] = pOut.mat[15] = 1.0; - pOut.mat[1] = pOut.mat[2] = pOut.mat[3] = - pOut.mat[4] = pOut.mat[6] = pOut.mat[7] = - pOut.mat[8] = pOut.mat[9] = pOut.mat[11] = 0.0; - pOut.mat[12] = x; - pOut.mat[13] = y; - pOut.mat[14] = z; - return pOut; -}; - -/** - * Get the up vector from a matrix. pIn is the matrix you - * wish to extract the vector from. pOut is a pointer to the - * kmVec3 structure that should hold the resulting vector - */ -cc.kmMat4GetUpVec3 = function (vec3, mat4) { - vec3.x = mat4.mat[4]; - vec3.y = mat4.mat[5]; - vec3.z = mat4.mat[6]; - return vec3.normalize(); -}; - -/** Extract the right vector from a 4x4 matrix. The result is - * stored in pOut. Returns pOut. - */ -cc.kmMat4GetRightVec3 = function (vec3, mat4) { - vec3.x = mat4.mat[0]; - vec3.y = mat4.mat[1]; - vec3.z = mat4.mat[2]; - return vec3.normalize(); -}; - -/** - * Extract the forward vector from a 4x4 matrix. The result is - * stored in pOut. Returns pOut. - */ -cc.kmMat4GetForwardVec3 = function (vec3, mat4) { - vec3.x = mat4.mat[8]; - vec3.y = mat4.mat[9]; - vec3.z = mat4.mat[10]; - return vec3.normalize(); -}; - -/** - * Creates a perspective projection matrix in the - * same way as gluPerspective - */ -cc.kmMat4PerspectiveProjection = function (pOut, fovY, aspect, zNear, zFar) { - var r = cc.degreesToRadians(fovY / 2); - var deltaZ = zFar - zNear; - var s = Math.sin(r); - - if (deltaZ == 0 || s == 0 || aspect == 0) - return null; - - //cos(r) / sin(r) = cot(r) - var cotangent = Math.cos(r) / s; - - cc.kmMat4Identity(pOut); - pOut.mat[0] = cotangent / aspect; - pOut.mat[5] = cotangent; - pOut.mat[10] = -(zFar + zNear) / deltaZ; - pOut.mat[11] = -1; - pOut.mat[14] = -2 * zNear * zFar / deltaZ; - pOut.mat[15] = 0; - - return pOut; -}; - -/** Creates an orthographic projection matrix like glOrtho */ -cc.kmMat4OrthographicProjection = function (pOut, left, right, bottom, top, nearVal, farVal) { - cc.kmMat4Identity(pOut); - pOut.mat[0] = 2 / (right - left); - pOut.mat[5] = 2 / (top - bottom); - pOut.mat[10] = -2 / (farVal - nearVal); - pOut.mat[12] = -((right + left) / (right - left)); - pOut.mat[13] = -((top + bottom) / (top - bottom)); - pOut.mat[14] = -((farVal + nearVal) / (farVal - nearVal)); - return pOut; -}; - -/** - * Builds a translation matrix in the same way as gluLookAt() - * the resulting matrix is stored in pOut. pOut is returned. - */ -cc.kmMat4LookAt = function (pOut, pEye, pCenter, pUp) { - var f = new cc.math.Vec3(pCenter), up = new cc.math.Vec3(pUp); - var translate = new cc.kmMat4(); - - f.subtract(pEye); - f.normalize(); - - up.normalize(); - - var s = new cc.math.Vec3(f); - s.cross(up); - s.normalize(); - - var u = new cc.math.Vec3(s); - u.cross(f); - s.normalize(); - - cc.kmMat4Identity(pOut); + /** + * Builds an X-axis rotation matrix and stores it in matrix, returns matrix, if matrix is null, create a new matrix + * @param {Number} radians + * @param {cc.math.Matrix4} [matrix] + * @returns {cc.math.Matrix4} + */ + cc.math.Matrix4.createByRotationX = function(radians, matrix) { //cc.kmMat4RotationX + /* + | 1 0 0 0 | + M = | 0 cos(A) -sin(A) 0 | + | 0 sin(A) cos(A) 0 | + | 0 0 0 1 | + */ + matrix = matrix || new cc.math.Matrix4(); + var mat = matrix.mat; + mat[0] = 1.0; + mat[3] = mat[2] = mat[1] = 0.0; + + mat[4] = 0.0; + mat[5] = Math.cos(radians); + mat[6] = Math.sin(radians); + mat[7] = 0.0; + + mat[8] = 0.0; + mat[9] = -Math.sin(radians); + mat[10] = Math.cos(radians); + mat[11] = 0.0; + + mat[14] = mat[13] = mat[12] = 0.0; + mat[15] = 1.0; + return matrix; + }; + + /** + * Builds a rotation matrix using the rotation around the Y-axis, The result is stored in matrix, matrix is returned. + * @param {Number} radians + * @param {cc.math.Matrix4} [matrix] + * @returns {*} + */ + cc.math.Matrix4.createByRotationY = function(radians, matrix) { // cc.kmMat4RotationY + /* + | cos(A) 0 sin(A) 0 | + M = | 0 1 0 0 | + | -sin(A) 0 cos(A) 0 | + | 0 0 0 1 | + */ + matrix = matrix || new cc.math.Matrix4(); + var mat = matrix.mat; + mat[0] = Math.cos(radians); + mat[1] = 0.0; + mat[2] = -Math.sin(radians); + mat[3] = 0.0; + + mat[7] = mat[6] = mat[4] = 0.0; + mat[5] = 1.0; + + mat[8] = Math.sin(radians); + mat[9] = 0.0; + mat[10] = Math.cos(radians); + mat[11] = 0.0; + + mat[14] = mat[13] = mat[12] = 0.0; + mat[15] = 1.0; + return matrix; + }; + + /** + * Builds a rotation matrix around the Z-axis. The resulting matrix is stored in matrix. matrix is returned. + * @param {Number} radians + * @param {cc.math.Matrix4} matrix + * @return {cc.math.Matrix4} + */ + cc.math.Matrix4.createByRotationZ = function(radians, matrix){ // cc.kmMat4RotationZ + /* + | cos(A) -sin(A) 0 0 | + M = | sin(A) cos(A) 0 0 | + | 0 0 1 0 | + | 0 0 0 1 | + */ + matrix = matrix || new cc.math.Matrix4(); + var mat = matrix.mat; + mat[0] = Math.cos(radians); + mat[1] = Math.sin(radians); + mat[3] = mat[2] = 0.0; + + mat[4] = -Math.sin(radians); + mat[5] = Math.cos(radians); + mat[7] = mat[6] = 0.0; + + mat[11] = mat[9] = mat[8] = 0.0; + mat[10] = 1.0; + + mat[14] = mat[13] = mat[12] = 0.0; + mat[15] = 1.0; + + return matrix; + }; + + /** + * Builds a rotation matrix from pitch, yaw and roll. The resulting matrix is stored in parameter matrix and returns. + * @param {Number} pitch + * @param {Number} yaw + * @param {Number} roll + * @param {cc.math.Matrix4} [matrix] if matrix is undefined, creates a new matrix. + * @returns {cc.math.Matrix4} + */ + cc.math.Matrix4.createByPitchYawRoll = function(pitch, yaw, roll, matrix) { + matrix = matrix || new cc.math.Matrix4(); + var cr = Math.cos(pitch), sr = Math.sin(pitch); + var cp = Math.cos(yaw), sp = Math.sin(yaw); + var cy = Math.cos(roll), sy = Math.sin(roll); + var srsp = sr * sp, crsp = cr * sp; + var mat = matrix.mat; + + mat[0] = cp * cy; + mat[4] = cp * sy; + mat[8] = -sp; + + mat[1] = srsp * cy - cr * sy; + mat[5] = srsp * sy + cr * cy; + mat[9] = sr * cp; + + mat[2] = crsp * cy + sr * sy; + mat[6] = crsp * sy - sr * cy; + mat[10] = cr * cp; + + mat[3] = mat[7] = mat[11] = 0.0; + mat[15] = 1.0; + return matrix; + }; + + /** + * Builds a matrix by a quaternion. + * @param {cc.math.Quaternion} quaternion + * @param {cc.math.Matrix4} [matrix] if matrix is undefined, creates a new matrix. + * @returns {cc.math.Matrix4} + */ + cc.math.Matrix4.createByQuaternion = function(quaternion, matrix) { + matrix = matrix || new cc.math.Matrix4(); + var mat = matrix.mat; + mat[0] = 1.0 - 2.0 * (quaternion.y * quaternion.y + quaternion.z * quaternion.z ); + mat[1] = 2.0 * (quaternion.x * quaternion.y + quaternion.z * quaternion.w); + mat[2] = 2.0 * (quaternion.x * quaternion.z - quaternion.y * quaternion.w); + mat[3] = 0.0; + + // Second row + mat[4] = 2.0 * ( quaternion.x * quaternion.y - quaternion.z * quaternion.w ); + mat[5] = 1.0 - 2.0 * ( quaternion.x * quaternion.x + quaternion.z * quaternion.z ); + mat[6] = 2.0 * (quaternion.z * quaternion.y + quaternion.x * quaternion.w ); + mat[7] = 0.0; + + // Third row + mat[8] = 2.0 * ( quaternion.x * quaternion.z + quaternion.y * quaternion.w ); + mat[9] = 2.0 * ( quaternion.y * quaternion.z - quaternion.x * quaternion.w ); + mat[10] = 1.0 - 2.0 * ( quaternion.x * quaternion.x + quaternion.y * quaternion.y ); + mat[11] = 0.0; + + // Fourth row + mat[14] = mat[13] = mat[12] = 0; + mat[15] = 1.0; + return matrix; + }; + + /** + * Build a 4x4 OpenGL transformation matrix using a 3x3 rotation matrix, and a 3d vector representing a translation. + * @param {cc.math.Matrix3} rotation + * @param {cc.math.Vec3} translation + * @param {cc.math.Matrix4} [matrix] if matrix is undefined, creates a new matrix. + * @returns {cc.math.Matrix4} + */ + cc.math.Matrix4.createByRotationTranslation = function(rotation, translation, matrix) { + matrix = matrix || new cc.math.Matrix4(); + var mat = matrix.mat, rMat = rotation.mat; + mat[0] = rMat[0]; + mat[1] = rMat[1]; + mat[2] = rMat[2]; + mat[3] = 0.0; + + mat[4] = rMat[3]; + mat[5] = rMat[4]; + mat[6] = rMat[5]; + mat[7] = 0.0; + + mat[8] = rMat[6]; + mat[9] = rMat[7]; + mat[10] = rMat[8]; + mat[11] = 0.0; + + mat[12] = translation.x; + mat[13] = translation.y; + mat[14] = translation.z; + mat[15] = 1.0; + return matrix; + }; + + /** + * Builds a scaling matrix + * @param {Number} x + * @param {Number} y + * @param {Number} z + * @param {cc.math.Matrix4} [matrix] if matrix is undefined, creates a new matrix. + * @returns {cc.math.Matrix4} + */ + cc.math.Matrix4.createByScale = function(x, y, z, matrix) { //cc.kmMat4Scaling + matrix = matrix || new cc.math.Matrix4(); + var mat = matrix.mat; + mat[0] = x; + mat[5] = y; + mat[10] = z; + mat[15] = 1.0; + mat[1] = mat[2] = mat[3] = mat[4] = mat[6] = mat[7] = + mat[8] = mat[9] = mat[11] = mat[12] = mat[13] = mat[14] = 0; + return matrix; + }; + + /** + * Builds a translation matrix. All other elements in the matrix + * will be set to zero except for the diagonal which is set to 1.0 + */ + cc.kmMat4Translation = function (pOut, x, y, z) { + //FIXME: Write a test for this + pOut.mat[0] = pOut.mat[5] = pOut.mat[10] = pOut.mat[15] = 1.0; + pOut.mat[1] = pOut.mat[2] = pOut.mat[3] = + pOut.mat[4] = pOut.mat[6] = pOut.mat[7] = + pOut.mat[8] = pOut.mat[9] = pOut.mat[11] = 0.0; + pOut.mat[12] = x; + pOut.mat[13] = y; + pOut.mat[14] = z; + return pOut; + }; + + /** + * Builds a translation matrix. + * @param {Number} x + * @param {Number} y + * @param {Number} z + * @param {cc.math.Matrix4} [matrix] if matrix is undefined, creates a new matrix. + * @returns {cc.math.Matrix4} + */ + cc.math.Matrix4.createByTranslation = function(x, y, z, matrix){ //cc.kmMat4Translation + matrix = matrix || new cc.math.Matrix4(); + matrix.identity(); + matrix.mat[12] = x; + matrix.mat[13] = y; + matrix.mat[14] = z; + return matrix; + }; + + /** + * Get the up vector from a matrix. + * @returns {cc.math.Vec3} + */ + proto.getUpVec3 = function() { + var mat = this.mat; + var ret = new cc.math.Vec3(mat[4],mat[5], mat[6]); + return ret.normalize(); + }; + + /** + * Extract the right vector from a 4x4 matrix. + * @returns {cc.math.Vec3} + */ + proto.getRightVec3 = function(){ + var mat = this.mat; + var ret = new cc.math.Vec3(mat[0],mat[1], mat[2]); + return ret.normalize(); + }; + + /** + * Extract the forward vector from a 4x4 matrix. + * @returns {cc.math.Vec3} + */ + proto.getForwardVec3 = function() { + var mat = this.mat; + var ret = new cc.math.Vec3(mat[8],mat[9], mat[10]); + return ret.normalize(); + }; + + /** + * Creates a perspective projection matrix in the + * same way as gluPerspective + */ + cc.kmMat4PerspectiveProjection = function (pOut, fovY, aspect, zNear, zFar) { + var r = cc.degreesToRadians(fovY / 2); + var deltaZ = zFar - zNear; + var s = Math.sin(r); + + if (deltaZ == 0 || s == 0 || aspect == 0) + return null; + + //cos(r) / sin(r) = cot(r) + var cotangent = Math.cos(r) / s; + pOut.identity(); + pOut.mat[0] = cotangent / aspect; + pOut.mat[5] = cotangent; + pOut.mat[10] = -(zFar + zNear) / deltaZ; + pOut.mat[11] = -1; + pOut.mat[14] = -2 * zNear * zFar / deltaZ; + pOut.mat[15] = 0; - pOut.mat[0] = s.x; - pOut.mat[4] = s.y; - pOut.mat[8] = s.z; + return pOut; + }; + + /** + * Creates a perspective projection matrix in the same way as gluPerspective + * @param {Number} fovY + * @param {Number} aspect + * @param {Number} zNear + * @param {Number} zFar + * @returns {cc.math.Matrix4|Null} + */ + cc.math.Matrix4.createPerspectiveProjection = function(fovY, aspect, zNear, zFar){ + var r = cc.degreesToRadians(fovY / 2), deltaZ = zFar - zNear; + var s = Math.sin(r); + + if (deltaZ == 0 || s == 0 || aspect == 0) + return null; + + //cos(r) / sin(r) = cot(r) + var cotangent = Math.cos(r) / s; + var matrix = new cc.math.Matrix4(), mat = matrix.mat; + matrix.identity(); + mat[0] = cotangent / aspect; + mat[5] = cotangent; + mat[10] = -(zFar + zNear) / deltaZ; + mat[11] = -1; + mat[14] = -2 * zNear * zFar / deltaZ; + mat[15] = 0; + return matrix; + }; + + /** Creates an orthographic projection matrix like glOrtho */ + cc.kmMat4OrthographicProjection = function (pOut, left, right, bottom, top, nearVal, farVal) { + pOut.identity(); + pOut.mat[0] = 2 / (right - left); + pOut.mat[5] = 2 / (top - bottom); + pOut.mat[10] = -2 / (farVal - nearVal); + pOut.mat[12] = -((right + left) / (right - left)); + pOut.mat[13] = -((top + bottom) / (top - bottom)); + pOut.mat[14] = -((farVal + nearVal) / (farVal - nearVal)); + return pOut; + }; + + /** + * Creates an orthographic projection matrix like glOrtho + * @param {Number} left + * @param {Number} right + * @param {Number} bottom + * @param {Number} top + * @param {Number} nearVal + * @param {Number} farVal + * @returns {cc.math.Matrix4} + */ + cc.math.Matrix4.createOrthographicProjection = function (left, right, bottom, top, nearVal, farVal) { + var matrix = new cc.math.Matrix4(), mat = matrix.mat; + matrix.identity(); + mat[0] = 2 / (right - left); + mat[5] = 2 / (top - bottom); + mat[10] = -2 / (farVal - nearVal); + mat[12] = -((right + left) / (right - left)); + mat[13] = -((top + bottom) / (top - bottom)); + mat[14] = -((farVal + nearVal) / (farVal - nearVal)); + return matrix; + }; + + /** + * Builds a translation matrix in the same way as gluLookAt() + * the resulting matrix is stored in pOut. pOut is returned. + */ + cc.kmMat4LookAt = function (pOut, pEye, pCenter, pUp) { + var f = new cc.math.Vec3(pCenter), up = new cc.math.Vec3(pUp); + f.subtract(pEye); + f.normalize(); + up.normalize(); - pOut.mat[1] = u.x; - pOut.mat[5] = u.y; - pOut.mat[9] = u.z; + var s = new cc.math.Vec3(f); + s.cross(up); + s.normalize(); - pOut.mat[2] = -f.x; - pOut.mat[6] = -f.y; - pOut.mat[10] = -f.z; + var u = new cc.math.Vec3(s); + u.cross(f); + s.normalize(); - cc.kmMat4Translation(translate, -pEye.x, -pEye.y, -pEye.z); - cc.kmMat4Multiply(pOut, pOut, translate); + pOut.identity(); - return pOut; -}; + pOut.mat[0] = s.x; + pOut.mat[4] = s.y; + pOut.mat[8] = s.z; -/** - * Build a rotation matrix from an axis and an angle. Result is stored in pOut. - * pOut is returned. - */ -cc.kmMat4RotationAxisAngle = function (pOut, axis, radians) { - var rcos = Math.cos(radians); - var rsin = Math.sin(radians); + pOut.mat[1] = u.x; + pOut.mat[5] = u.y; + pOut.mat[9] = u.z; - var normalizedAxis = new cc.math.Vec3(axis); - normalizedAxis.normalize(); + pOut.mat[2] = -f.x; + pOut.mat[6] = -f.y; + pOut.mat[10] = -f.z; - pOut.mat[0] = rcos + normalizedAxis.x * normalizedAxis.x * (1 - rcos); - pOut.mat[1] = normalizedAxis.z * rsin + normalizedAxis.y * normalizedAxis.x * (1 - rcos); - pOut.mat[2] = -normalizedAxis.y * rsin + normalizedAxis.z * normalizedAxis.x * (1 - rcos); - pOut.mat[3] = 0.0; + var translate = cc.math.Matrix4.createByTranslation(-pEye.x, -pEye.y, -pEye.z); + pOut.multiply(translate); + return pOut; + }; + + var tempMatrix = new cc.math.Matrix4(); // an internal matrix + proto.lookAt = function(eyeVec, centerVec, upVec) { + var f = new cc.math.Vec3(centerVec), up = new cc.math.Vec3(upVec), mat = this.mat; + f.subtract(eyeVec); + f.normalize(); + up.normalize(); + + var s = new cc.math.Vec3(f); + s.cross(up); + s.normalize(); + + var u = new cc.math.Vec3(s); + u.cross(f); + s.normalize(); + + this.identity(); + mat[0] = s.x; + mat[4] = s.y; + mat[8] = s.z; + + mat[1] = u.x; + mat[5] = u.y; + mat[9] = u.z; + + mat[2] = -f.x; + mat[6] = -f.y; + mat[10] = -f.z; + + tempMatrix = cc.math.Matrix4.createByTranslation(-eyeVec.x, -eyeVec.y, -eyeVec.z, tempMatrix); + this.multiply(tempMatrix); + return this; + }; + + /** + * Build a rotation matrix from an axis and an angle. Result is stored in pOut. + * pOut is returned. + */ + cc.kmMat4RotationAxisAngle = function (pOut, axis, radians) { + var rcos = Math.cos(radians), rsin = Math.sin(radians); - pOut.mat[4] = -normalizedAxis.z * rsin + normalizedAxis.x * normalizedAxis.y * (1 - rcos); - pOut.mat[5] = rcos + normalizedAxis.y * normalizedAxis.y * (1 - rcos); - pOut.mat[6] = normalizedAxis.x * rsin + normalizedAxis.z * normalizedAxis.y * (1 - rcos); - pOut.mat[7] = 0.0; + var normalizedAxis = new cc.math.Vec3(axis); + normalizedAxis.normalize(); - pOut.mat[8] = normalizedAxis.y * rsin + normalizedAxis.x * normalizedAxis.z * (1 - rcos); - pOut.mat[9] = -normalizedAxis.x * rsin + normalizedAxis.y * normalizedAxis.z * (1 - rcos); - pOut.mat[10] = rcos + normalizedAxis.z * normalizedAxis.z * (1 - rcos); - pOut.mat[11] = 0.0; + pOut.mat[0] = rcos + normalizedAxis.x * normalizedAxis.x * (1 - rcos); + pOut.mat[1] = normalizedAxis.z * rsin + normalizedAxis.y * normalizedAxis.x * (1 - rcos); + pOut.mat[2] = -normalizedAxis.y * rsin + normalizedAxis.z * normalizedAxis.x * (1 - rcos); + pOut.mat[3] = 0.0; - pOut.mat[12] = 0.0; - pOut.mat[13] = 0.0; - pOut.mat[14] = 0.0; - pOut.mat[15] = 1.0; + pOut.mat[4] = -normalizedAxis.z * rsin + normalizedAxis.x * normalizedAxis.y * (1 - rcos); + pOut.mat[5] = rcos + normalizedAxis.y * normalizedAxis.y * (1 - rcos); + pOut.mat[6] = normalizedAxis.x * rsin + normalizedAxis.z * normalizedAxis.y * (1 - rcos); + pOut.mat[7] = 0.0; - return pOut; -}; + pOut.mat[8] = normalizedAxis.y * rsin + normalizedAxis.x * normalizedAxis.z * (1 - rcos); + pOut.mat[9] = -normalizedAxis.x * rsin + normalizedAxis.y * normalizedAxis.z * (1 - rcos); + pOut.mat[10] = rcos + normalizedAxis.z * normalizedAxis.z * (1 - rcos); + pOut.mat[11] = 0.0; -/** - * Extract a 3x3 rotation matrix from the input 4x4 transformation. - * Stores the result in pOut, returns pOut - */ -cc.kmMat4ExtractRotation = function (pOut, pIn) { - pOut.mat[0] = pIn.mat[0]; - pOut.mat[1] = pIn.mat[1]; - pOut.mat[2] = pIn.mat[2]; - - pOut.mat[3] = pIn.mat[4]; - pOut.mat[4] = pIn.mat[5]; - pOut.mat[5] = pIn.mat[6]; - - pOut.mat[6] = pIn.mat[8]; - pOut.mat[7] = pIn.mat[9]; - pOut.mat[8] = pIn.mat[10]; - return pOut; -}; - -cc.kmMat4ExtractPlane = function (pOut, pIn, plane) { - switch (plane) { - case cc.math.Plane.RIGHT: - pOut.a = pIn.mat[3] - pIn.mat[0]; - pOut.b = pIn.mat[7] - pIn.mat[4]; - pOut.c = pIn.mat[11] - pIn.mat[8]; - pOut.d = pIn.mat[15] - pIn.mat[12]; - break; - case cc.math.Plane.LEFT: - pOut.a = pIn.mat[3] + pIn.mat[0]; - pOut.b = pIn.mat[7] + pIn.mat[4]; - pOut.c = pIn.mat[11] + pIn.mat[8]; - pOut.d = pIn.mat[15] + pIn.mat[12]; - break; - case cc.math.Plane.BOTTOM: - pOut.a = pIn.mat[3] + pIn.mat[1]; - pOut.b = pIn.mat[7] + pIn.mat[5]; - pOut.c = pIn.mat[11] + pIn.mat[9]; - pOut.d = pIn.mat[15] + pIn.mat[13]; - break; - case cc.math.Plane.TOP: - pOut.a = pIn.mat[3] - pIn.mat[1]; - pOut.b = pIn.mat[7] - pIn.mat[5]; - pOut.c = pIn.mat[11] - pIn.mat[9]; - pOut.d = pIn.mat[15] - pIn.mat[13]; - break; - case cc.math.Plane.FAR: - pOut.a = pIn.mat[3] - pIn.mat[2]; - pOut.b = pIn.mat[7] - pIn.mat[6]; - pOut.c = pIn.mat[11] - pIn.mat[10]; - pOut.d = pIn.mat[15] - pIn.mat[14]; - break; - case cc.math.Plane.NEAR: - pOut.a = pIn.mat[3] + pIn.mat[2]; - pOut.b = pIn.mat[7] + pIn.mat[6]; - pOut.c = pIn.mat[11] + pIn.mat[10]; - pOut.d = pIn.mat[15] + pIn.mat[14]; - break; - default: - cc.log("cc.kmMat4ExtractPlane(): Invalid plane index"); - break; - } - - var t = Math.sqrt(pOut.a * pOut.a + - pOut.b * pOut.b + - pOut.c * pOut.c); - pOut.a /= t; - pOut.b /= t; - pOut.c /= t; - pOut.d /= t; - - return pOut; -}; + pOut.mat[12] = 0.0; + pOut.mat[13] = 0.0; + pOut.mat[14] = 0.0; + pOut.mat[15] = 1.0; -/** - * Take the rotation from a 4x4 transformation matrix, and return it as an axis and an angle (in radians) - * returns the output axis. - */ -cc.kmMat4RotationToAxisAngle = function (pAxis, radians, pIn) { - /*Surely not this easy?*/ - var rotation = new cc.math.Matrix3(); - cc.kmMat4ExtractRotation(rotation, pIn); - var temp = cc.math.Quaternion.rotationMatrix(rotation); - return temp.toAxisAndAngle(); -}; + return pOut; + }; + + /** + * Build a rotation matrix from an axis and an angle. + * @param {cc.math.Vec3} axis + * @param {Number} radians + * @param {cc.math.Matrix4} [matrix] + * @returns {cc.math.Matrix4} + */ + cc.math.Matrix4.createByAxisAndAngle = function(axis, radians, matrix) { + matrix = matrix || new cc.math.Matrix4(); + var mat = this.mat, rcos = Math.cos(radians), rsin = Math.sin(radians) ; + + var normalizedAxis = new cc.math.Vec3(axis); + normalizedAxis.normalize(); + + mat[0] = rcos + normalizedAxis.x * normalizedAxis.x * (1 - rcos); + mat[1] = normalizedAxis.z * rsin + normalizedAxis.y * normalizedAxis.x * (1 - rcos); + mat[2] = -normalizedAxis.y * rsin + normalizedAxis.z * normalizedAxis.x * (1 - rcos); + mat[3] = 0.0; + + mat[4] = -normalizedAxis.z * rsin + normalizedAxis.x * normalizedAxis.y * (1 - rcos); + mat[5] = rcos + normalizedAxis.y * normalizedAxis.y * (1 - rcos); + mat[6] = normalizedAxis.x * rsin + normalizedAxis.z * normalizedAxis.y * (1 - rcos); + mat[7] = 0.0; + + mat[8] = normalizedAxis.y * rsin + normalizedAxis.x * normalizedAxis.z * (1 - rcos); + mat[9] = -normalizedAxis.x * rsin + normalizedAxis.y * normalizedAxis.z * (1 - rcos); + mat[10] = rcos + normalizedAxis.z * normalizedAxis.z * (1 - rcos); + mat[11] = 0.0; + + mat[12] = mat[13] = mat[14] = 0.0; + mat[15] = 1.0; + return matrix; + }; + + /** + * Extract a 3x3 rotation matrix from the input 4x4 transformation. + * @returns {cc.math.Matrix3} + */ + proto.extractRotation = function(){ + var matrix = new cc.math.Matrix3(), mat4 = this.mat, mat3 = matrix.mat; + mat3[0] = mat4[0]; + mat3[1] = mat4[1]; + mat3[2] = mat4[2]; + + mat3[3] = mat4[4]; + mat3[4] = mat4[5]; + mat3[5] = mat4[6]; + + mat3[6] = mat4[8]; + mat3[7] = mat4[9]; + mat3[8] = mat4[10]; + return matrix; + }; + + proto.extractPlane = function(planeType) { + var plane = new cc.math.Plane(), mat = this.mat; + switch (planeType) { + case cc.math.Plane.RIGHT: + plane.a = mat[3] - mat[0]; + plane.b = mat[7] - mat[4]; + plane.c = mat[11] - mat[8]; + plane.d = mat[15] - mat[12]; + break; + case cc.math.Plane.LEFT: + plane.a = mat[3] + mat[0]; + plane.b = mat[7] + mat[4]; + plane.c = mat[11] + mat[8]; + plane.d = mat[15] + mat[12]; + break; + case cc.math.Plane.BOTTOM: + plane.a = mat[3] + mat[1]; + plane.b = mat[7] + mat[5]; + plane.c = mat[11] + mat[9]; + plane.d = mat[15] + mat[13]; + break; + case cc.math.Plane.TOP: + plane.a = mat[3] - mat[1]; + plane.b = mat[7] - mat[5]; + plane.c = mat[11] - mat[9]; + plane.d = mat[15] - mat[13]; + break; + case cc.math.Plane.FAR: + plane.a = mat[3] - mat[2]; + plane.b = mat[7] - mat[6]; + plane.c = mat[11] - mat[10]; + plane.d = mat[15] - mat[14]; + break; + case cc.math.Plane.NEAR: + plane.a = mat[3] + mat[2]; + plane.b = mat[7] + mat[6]; + plane.c = mat[11] + mat[10]; + plane.d = mat[15] + mat[14]; + break; + default: + cc.log("cc.math.Matrix4.extractPlane: Invalid plane index"); + break; + } + var t = Math.sqrt(plane.a * plane.a + plane.b * plane.b + plane.c * plane.c); + plane.a /= t; + plane.b /= t; + plane.c /= t; + plane.d /= t; + return plane; + }; + + /** + * Take the rotation from a 4x4 transformation matrix, and return it as an axis and an angle (in radians) + * @returns {*|{axis: cc.math.Vec3, angle: number}} + */ + proto.toAxisAndAngle = function() { + /*Surely not this easy?*/ + var rotation = this.extractRotation(); + var temp = cc.math.Quaternion.rotationMatrix(rotation); + return temp.toAxisAndAngle(); + }; +})(cc); diff --git a/cocos2d/kazmath/quaternion.js b/cocos2d/kazmath/quaternion.js index 3b24830871..13e9d67ef6 100644 --- a/cocos2d/kazmath/quaternion.js +++ b/cocos2d/kazmath/quaternion.js @@ -353,7 +353,7 @@ * @param {cc.math.Quaternion} quaternion * @returns {cc.math.Quaternion} current quaternion */ - proto.assign = function(quaternion){ //=cc.kmQuaternionAssign + proto.assignFrom = function(quaternion){ //=cc.kmQuaternionAssign this.x = quaternion.x; this.y = quaternion.y; this.z = quaternion.z; diff --git a/cocos2d/kazmath/vec3.js b/cocos2d/kazmath/vec3.js index 18200dfa8b..de64594604 100644 --- a/cocos2d/kazmath/vec3.js +++ b/cocos2d/kazmath/vec3.js @@ -163,7 +163,7 @@ return this; }; - proto.assign = function(vec){ + proto.assignFrom = function(vec){ if(!vec) return this; this.x = vec.x; diff --git a/cocos2d/kazmath/vec4.js b/cocos2d/kazmath/vec4.js index bb4e2ac807..fb2e376380 100644 --- a/cocos2d/kazmath/vec4.js +++ b/cocos2d/kazmath/vec4.js @@ -137,7 +137,7 @@ (this.w < vec.w + EPSILON && this.w > vec.w - EPSILON); }; - proto.assign = function(vec) { //= cc.kmVec4Assign + proto.assignFrom = function(vec) { //= cc.kmVec4Assign this.x = vec.x; this.y = vec.y; this.z = vec.z; diff --git a/cocos2d/node-grid/CCNodeGrid.js b/cocos2d/node-grid/CCNodeGrid.js index f75ce939f8..3426e84d74 100644 --- a/cocos2d/node-grid/CCNodeGrid.js +++ b/cocos2d/node-grid/CCNodeGrid.js @@ -80,7 +80,7 @@ cc.NodeGrid = cc.Node.extend({ t4x4Mat[14] = this._vertexZ; //optimize performance for Javascript - cc.kmMat4Multiply(topMat4, topMat4, t4x4); // = cc.kmGLMultMatrix(this._transform4x4); + topMat4.multiply(t4x4) ; // = cc.kmGLMultMatrix(this._transform4x4); // XXX: Expensive calls. Camera should be integrated into the cached affine matrix if (this._camera != null && !(this.grid && this.grid.isActive())) { diff --git a/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js b/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js index 4a2e48cb63..5238694b38 100644 --- a/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js +++ b/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js @@ -239,9 +239,8 @@ var widthRatio = size.width / texSize.width; var heightRatio = size.height / texSize.height; - var orthoMatrix = new cc.kmMat4(); - cc.kmMat4OrthographicProjection(orthoMatrix, -1.0 / widthRatio, 1.0 / widthRatio, - -1.0 / heightRatio, 1.0 / heightRatio, -1, 1); + var orthoMatrix = cc.math.Matrix4.createOrthographicProjection(-1.0 / widthRatio, 1.0 / widthRatio, + -1.0 / heightRatio, 1.0 / heightRatio, -1, 1); cc.kmGLMultMatrix(orthoMatrix); //calculate viewport diff --git a/cocos2d/shaders/CCGLProgram.js b/cocos2d/shaders/CCGLProgram.js index 1b429a9734..c8812bcac4 100644 --- a/cocos2d/shaders/CCGLProgram.js +++ b/cocos2d/shaders/CCGLProgram.js @@ -543,9 +543,9 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ * will update the builtin uniforms if they are different than the previous call for this same shader program. */ setUniformsForBuiltins: function () { - var matrixP = new cc.kmMat4(); - var matrixMV = new cc.kmMat4(); - var matrixMVP = new cc.kmMat4(); + var matrixP = new cc.math.Matrix4(); + var matrixMV = new cc.math.Matrix4(); + var matrixMVP = new cc.math.Matrix4(); cc.kmGLGetMatrix(cc.KM_GL_PROJECTION, matrixP); cc.kmGLGetMatrix(cc.KM_GL_MODELVIEW, matrixMV); @@ -576,9 +576,9 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ if(!node || !node._renderCmd) return; - var matrixP = new cc.kmMat4(); + var matrixP = new cc.math.Matrix4(); //var matrixMV = new cc.kmMat4(); - var matrixMVP = new cc.kmMat4(); + var matrixMVP = new cc.math.Matrix4(); cc.kmGLGetMatrix(cc.KM_GL_PROJECTION, matrixP); //cc.kmGLGetMatrix(cc.KM_GL_MODELVIEW, node._stackMatrix); diff --git a/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js b/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js index b4581dbaaf..476c790a5f 100644 --- a/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js +++ b/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js @@ -129,15 +129,15 @@ apy = 0 | apy; } //cc.kmGLTranslatef(apx, apy, 0); - var translation = new cc.kmMat4(); - cc.kmMat4Translation(translation, apx, apy, 0); - cc.kmMat4Multiply(stackMatrix, stackMatrix, translation); + var translation = cc.math.Matrix4.createByTranslation(apx, apy, 0, t4x4); //t4x4 as a temp matrix + stackMatrix.multiply(translate); node._camera._locateForRenderer(stackMatrix); //cc.kmGLTranslatef(-apx, -apy, 0); - cc.kmMat4Translation(translation, -apx, -apy, 0); - cc.kmMat4Multiply(stackMatrix, stackMatrix, translation); + translation = cc.math.Matrix4.createByTranslation(-apx, -apy, 0, translation); + stackMatrix.multiply(translation); + t4x4.identity(); //reset t4x4; } else { node._camera._locateForRenderer(stackMatrix); } From 96e999eadaeb9829d9394bb9e0fe46faa59f379f Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Fri, 13 Mar 2015 14:56:01 +0800 Subject: [PATCH 0046/1039] Issue #2698: corrected some mistakes for refactoring. --- cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js | 2 +- cocos2d/core/sprites/CCSpriteFrameCache.js | 6 +++--- cocos2d/kazmath/gl/matrix.js | 8 ++++---- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js b/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js index 5342f1c3a5..2c70b47fd2 100644 --- a/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js @@ -229,7 +229,7 @@ node._camera._locateForRenderer(stackMatrix); //cc.kmGLTranslatef(-apx, -apy, 0); optimize at here : kmGLTranslatef - translation = cc.math.Matrix4.createByTranslation(apx, apy, 0, translation); + translation = cc.math.Matrix4.createByTranslation(-apx, -apy, 0, translation); stackMatrix.multiply(translation); t4x4.identity(); //reset t4x4; } else { diff --git a/cocos2d/core/sprites/CCSpriteFrameCache.js b/cocos2d/core/sprites/CCSpriteFrameCache.js index 851a30f278..9f4166a131 100644 --- a/cocos2d/core/sprites/CCSpriteFrameCache.js +++ b/cocos2d/core/sprites/CCSpriteFrameCache.js @@ -147,10 +147,10 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{ var frameConfig = this._frameConfigCache[url] || this._getFrameConfigByJsonObject(url, jsonObject); //this._checkConflict(frameConfig); //TODO - this._createSpriteFrames(frameConfig, texture); + this._createSpriteFrames(url, frameConfig, texture); }, - _createSpriteFrames: function(frameConfig, texture) { + _createSpriteFrames: function(url, frameConfig, texture) { var frames = frameConfig.frames, meta = frameConfig.meta; if(!texture){ var texturePath = cc.path.changeBasename(url, meta.image || ".png"); @@ -223,7 +223,7 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{ var frameConfig = this._frameConfigCache[url] || this._getFrameConfig(url); //this._checkConflict(frameConfig); //TODO - this._createSpriteFrames(frameConfig, texture); + this._createSpriteFrames(url, frameConfig, texture); }, // Function to check if frames to add exists already, if so there may be name conflit that must be solved diff --git a/cocos2d/kazmath/gl/matrix.js b/cocos2d/kazmath/gl/matrix.js index 574bd0dd5d..3975fa620c 100644 --- a/cocos2d/kazmath/gl/matrix.js +++ b/cocos2d/kazmath/gl/matrix.js @@ -43,9 +43,9 @@ var identity = new cc.math.Matrix4(); //Temporary identity matrix //Initialize all 3 stacks - cc.modelview_matrix_stack.initialized(); - cc.projection_matrix_stack.initialized(); - cc.texture_matrix_stack.initialized(); + cc.modelview_matrix_stack.initialize(); + cc.projection_matrix_stack.initialize(); + cc.texture_matrix_stack.initialize(); cc.current_stack = cc.modelview_matrix_stack; cc.initialized = true; @@ -132,7 +132,7 @@ cc.current_stack.top.multiply(translation); }; - var tempVector3 = new cc.math.Vec3(x, y, z); + var tempVector3 = new cc.math.Vec3(); cc.kmGLRotatef = function (angle, x, y, z) { tempVector3.fill(x, y, z); //Create a rotation matrix using the axis and the angle From 9f48972405e15b1cb3cd31a3718b66d7ea5b71de Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 13 Mar 2015 16:09:09 +0800 Subject: [PATCH 0047/1039] Fixed TMX scale error --- cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js index c1a63a4924..82d68230f6 100644 --- a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js +++ b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js @@ -82,7 +82,7 @@ return; var node = this._node; - this._renderingChildToCache(scaleX, scaleY); + this._renderingChildToCache(node._scaleX, node._scaleY); var wrapper = ctx || cc._renderContext, context = wrapper.getContext(); wrapper.setGlobalAlpha(alpha); @@ -145,16 +145,16 @@ //begin cache renderer._turnToCacheMode(instanceID); - node.sortAllChildren(); + node.sortAllChildren(); for (i = 0, len = locChildren.length; i < len; i++) { - if (locChildren[i]){ - var selCmd = locChildren[i]._renderCmd; + if (locChildren[i]){ + var selCmd = locChildren[i]._renderCmd; if(selCmd){ selCmd.visit(this); selCmd._cacheDirty = false; } } - } + } //wrapper.save(); context.setTransform(1, 0, 0, 1, 0, 0); From c67d5f3740a0eb87846ba711bebbab36eb91ece1 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 13 Mar 2015 16:15:00 +0800 Subject: [PATCH 0048/1039] Fixed TMX scale error --- cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js index 82d68230f6..b4f53b561a 100644 --- a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js +++ b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js @@ -50,7 +50,7 @@ this._cacheDirty = true; }; - proto._renderingChildToCache = function (scaleX, scaleY) { + proto._renderingChildToCache = function () { if (this._cacheDirty) { var wrapper = this._cacheContext, context = wrapper.getContext(), locCanvas = this._cacheCanvas; @@ -65,7 +65,7 @@ if (locChildren[i]){ var selCmd = locChildren[i]._renderCmd; if(selCmd){ - selCmd.rendering(wrapper, scaleX, scaleY); + selCmd.rendering(wrapper, 1, 1); selCmd._cacheDirty = false; } } @@ -82,7 +82,7 @@ return; var node = this._node; - this._renderingChildToCache(node._scaleX, node._scaleY); + this._renderingChildToCache(); var wrapper = ctx || cc._renderContext, context = wrapper.getContext(); wrapper.setGlobalAlpha(alpha); From db9022810bf1c86a4802ad8ca02d5d99a6490f98 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Fri, 13 Mar 2015 18:17:07 +0800 Subject: [PATCH 0049/1039] Fixed a bug of cc.LayerGradient that it doesn't work when constructor parameter is null. --- cocos2d/core/layers/CCLayer.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/layers/CCLayer.js b/cocos2d/core/layers/CCLayer.js index a6b2cf7f4e..c7fd9af7d7 100644 --- a/cocos2d/core/layers/CCLayer.js +++ b/cocos2d/core/layers/CCLayer.js @@ -349,10 +349,10 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{ if(stops && stops instanceof Array){ this._colorStops = stops; - stops.splice(0, 0, {p:0, color: start}); - stops.push({p:1, color: end}); + stops.splice(0, 0, {p:0, color: start || cc.color.BLACK}); + stops.push({p:1, color: end || cc.color.BLACK}); } else - this._colorStops = [{p:0, color: start}, {p:1, color: end}]; + this._colorStops = [{p:0, color: start || cc.color.BLACK}, {p:1, color: end || cc.color.BLACK}]; cc.LayerGradient.prototype.init.call(this, start, end, v, stops); }, From ebb9a749b8db17c9f29c6a742b798a4b04d0d17d Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 16 Mar 2015 09:45:41 +0800 Subject: [PATCH 0050/1039] Add cc.math.vec3... --- cocos2d/kazmath/vec3.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/cocos2d/kazmath/vec3.js b/cocos2d/kazmath/vec3.js index de64594604..282b34aaae 100644 --- a/cocos2d/kazmath/vec3.js +++ b/cocos2d/kazmath/vec3.js @@ -39,6 +39,10 @@ } }; + cc.math.vec3 = function(x, y, z){ + return new cc.math.Vec3(x, y, z); + }; + var proto = cc.math.Vec3.prototype; proto.fill = function (x, y, z) { // =cc.kmVec3Fill From 4f039d8036b4f09a3584e5cbd9ec9cb2b490fa4f Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 16 Mar 2015 10:12:57 +0800 Subject: [PATCH 0051/1039] Fixed a bug that is unscheduleAll is not exists. --- cocos2d/core/base-nodes/CCNode.js | 2 +- extensions/editbox/CCdomNode.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index b83d29e7ec..0094a86464 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -1155,7 +1155,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ */ setScheduler: function (scheduler) { if (this._scheduler != scheduler) { - this.unscheduleAll(); + this.unscheduleAllCallbacks(); this._scheduler = scheduler; } }, diff --git a/extensions/editbox/CCdomNode.js b/extensions/editbox/CCdomNode.js index a9b6a09c45..fb62932ed3 100644 --- a/extensions/editbox/CCdomNode.js +++ b/extensions/editbox/CCdomNode.js @@ -391,7 +391,7 @@ cc.DOM.methods = /** @lends cc.DOM# */{ cleanup:function () { // actions this.stopAllActions(); - this.unscheduleAll(); + this.unscheduleAllCallbacks(); // timers this._arrayMakeObjectsPerformSelector(this._children, cc.Node._stateCallbackType.cleanup); From 9b98619a96bee45c67fe6aa84650479803ea4f0b Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 16 Mar 2015 10:44:57 +0800 Subject: [PATCH 0052/1039] Update build.xml --- tools/XmlCheck.js | 13 +++++++++++++ tools/build.xml | 4 ++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/tools/XmlCheck.js b/tools/XmlCheck.js index 62f383d0a5..159933cd37 100644 --- a/tools/XmlCheck.js +++ b/tools/XmlCheck.js @@ -72,6 +72,19 @@ var xmlFile2 = []; })(); console.log(" The number of files in the XML file : %s", xmlFile.length); +contains = contains.map(function(a){ + return path.normalize(a); +}); +moduleFile = moduleFile.map(function(a){ + return path.normalize(a); +}); +xmlFile = xmlFile.map(function(a){ + return path.normalize(a); +}); +xmlFile2 = xmlFile2.map(function(a){ + return path.normalize(a); +}); + console.log("\x1B[0m\x1B[33m"); console.log(" warn : moduleConfig missing..."); contains.forEach(function(a){ diff --git a/tools/build.xml b/tools/build.xml index c1d0858cb8..6d50b363bc 100644 --- a/tools/build.xml +++ b/tools/build.xml @@ -5,7 +5,7 @@ classpath="./compiler/compiler.jar"/> + debug="false" output="./../lib/cocos2d-js-v3.4-beta-min.js"> @@ -298,7 +298,7 @@ + debug="false" output="./../lib/cocos2d-js-v3..4-beta-core-min.js"> From 90a5adeddf62192aba11249a13224ebcef9876c6 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 16 Mar 2015 10:47:42 +0800 Subject: [PATCH 0053/1039] Update version number --- cocos2d/core/platform/CCConfig.js | 2 +- tools/build.xml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/platform/CCConfig.js b/cocos2d/core/platform/CCConfig.js index e33721a2b8..eb24ebe368 100644 --- a/cocos2d/core/platform/CCConfig.js +++ b/cocos2d/core/platform/CCConfig.js @@ -31,7 +31,7 @@ * @type {String} * @name cc.ENGINE_VERSION */ -window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.3"; +window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.4 Beta0"; /** *

diff --git a/tools/build.xml b/tools/build.xml index 6d50b363bc..a28de92575 100644 --- a/tools/build.xml +++ b/tools/build.xml @@ -5,7 +5,7 @@ classpath="./compiler/compiler.jar"/> + debug="false" output="./../lib/cocos2d-js-v3.4-beta0-min.js"> @@ -298,7 +298,7 @@ + debug="false" output="./../lib/cocos2d-js-v3..4-beta0-core-min.js"> From 0114826428cda423438b00d52bbfaff0db6a7f11 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 16 Mar 2015 10:48:36 +0800 Subject: [PATCH 0054/1039] Update version number --- tools/build.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/build.xml b/tools/build.xml index a28de92575..ce6e9c35cf 100644 --- a/tools/build.xml +++ b/tools/build.xml @@ -298,7 +298,7 @@ + debug="false" output="./../lib/cocos2d-js-v3.4-beta0-core-min.js"> From 069d7325e155d99e0b692dd9dbf918498315e17d Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Mon, 16 Mar 2015 13:50:12 +0800 Subject: [PATCH 0055/1039] Update the ignore list of git. --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index f5e28b036a..73b9c1ae31 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ node_modules /tools/jsdoc_toolkit-2.4.0 /package /tools/jsdoc_toolkit/jsdoc_toolkit-2.4.0 +/.project From 6b7f1c1f215d4cc1f9b6a91e81c9ba5c0aa127bd Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 16 Mar 2015 14:25:51 +0800 Subject: [PATCH 0056/1039] Automatic open webgl for IOS --- CCBoot.js | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index 7543fbc756..8e2a876172 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -1598,10 +1598,13 @@ cc._initSys = function (config, CONFIG_KEY) { var renderType = cc._RENDER_TYPE_WEBGL; var tempCanvas = cc.newElement("Canvas"); cc._supportRender = true; - var notSupportGL = !window.WebGLRenderingContext || browserSupportWebGL.indexOf(sys.browserType) == -1 || osSupportWebGL.indexOf(sys.os) == -1; - if (userRenderMode === 1 || (userRenderMode === 0 && notSupportGL) || (location.origin == "file://")) { + var notSupportGL = true; + if(iOS) + notSupportGL = !window.WebGLRenderingContext || osSupportWebGL.indexOf(sys.os) == -1; + else + notSupportGL = !window.WebGLRenderingContext || browserSupportWebGL.indexOf(sys.browserType) == -1 || osSupportWebGL.indexOf(sys.os) == -1; + if (userRenderMode === 1 || (userRenderMode === 0 && notSupportGL) || (location.origin == "file://")) renderType = cc._RENDER_TYPE_CANVAS; - } sys._canUseCanvasNewBlendModes = function(){ var canvas = document.createElement('canvas'); From 1efa9d52d106154bd534fe9c454590d190601aa5 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Mon, 16 Mar 2015 15:38:01 +0800 Subject: [PATCH 0057/1039] Update the Authors for v3.4 beta0 --- AUTHORS.txt | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/AUTHORS.txt b/AUTHORS.txt index 56a564aebf..8d63894f5e 100644 --- a/AUTHORS.txt +++ b/AUTHORS.txt @@ -169,13 +169,14 @@ Asano @LaercioAsano cc.Node bug fix Bruno Assarisse @bassarisse cc.LabelBMFont bug fix -Mykyta Usikov @musikov cc.ClippingNode bug fix +Mykyta Usikov @musikov cc.ClippingNode bugs fix cc.fontLoader bug fix Inverted ClippingNode with DrawNode as stencil bug fix under canvas render mode JumpTo bug with wrong _delta position bug fix cc.ProgressTimer bugs fix cc.Scale9Sprite bugs fix cc.RenderTexture bug fix + cc.ParticleSystem bug fix Han XiaoLong @kpkhxlgy0 cc.ParticleSytem bug fix @@ -234,6 +235,15 @@ Joe Lafiosca @lafiosca Added Javascript file loader galapagosit @galapagosit ccs.actionManager bug fix +Dany Ellement @DEllement cc.FontDefinition & ccui.RichText improvements + cc.LayerGradient improvements + +IShm @IShm cc.Screen bug fix + cc.ParticleSystem bug fix + +Thomas Jablonski @thomas-jablonski cc.audioEngine bug fix + +WingGao @WingGao cc.TMXLayer bug fix Retired Core Developers: Shengxiang Chen (Nero Chan) From 4acfc3596d929134af4e08563229c2e250120146 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 16 Mar 2015 17:11:31 +0800 Subject: [PATCH 0058/1039] Fixed a bug that EGLView gets the rect error --- cocos2d/core/platform/CCEGLView.js | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos2d/core/platform/CCEGLView.js b/cocos2d/core/platform/CCEGLView.js index e5be3e63b5..75826042ff 100644 --- a/cocos2d/core/platform/CCEGLView.js +++ b/cocos2d/core/platform/CCEGLView.js @@ -75,6 +75,7 @@ switch(cc.__BrowserGetter.adaptationType){ cc.__BrowserGetter.__defineGetter__("target-densitydpi", function(){ return cc.view._targetDensityDPI; }); + case cc.sys.BROWSER_TYPE_SOUGOU: case cc.sys.BROWSER_TYPE_UC: cc.__BrowserGetter.availWidth = function(frame){ return frame.clientWidth; From 515f5a6ad98d33c75b9840178888519cf8815322 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Tue, 17 Mar 2015 10:47:46 +0800 Subject: [PATCH 0059/1039] Corrected an issue of chipmunk.js that it doesn't work after compiled. --- external/chipmunk/chipmunk.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/external/chipmunk/chipmunk.js b/external/chipmunk/chipmunk.js index 0fb3aeaa68..3be84bfc61 100644 --- a/external/chipmunk/chipmunk.js +++ b/external/chipmunk/chipmunk.js @@ -33,7 +33,7 @@ if(typeof exports === 'undefined'){ cp = {}; if(typeof window === 'object'){ - window.cp = cp; + window["cp"] = cp; } } else { cp = exports; @@ -1312,7 +1312,7 @@ var BoxShape2 = cp.BoxShape2 = function(body, box) box.l, box.b, box.l, box.t, box.r, box.t, - box.r, box.b, + box.r, box.b ]; return new PolyShape(body, verts, vzero); From 4ef6dc08c90d759cc744a9d92826994dedac0d1f Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Tue, 17 Mar 2015 17:08:28 +0800 Subject: [PATCH 0060/1039] Fixed #2742: Use '===' to replace '==' for performance. --- CCBoot.js | 116 +++++++++--------- CCDebugger.js | 10 +- cocos2d/actions/CCAction.js | 4 +- cocos2d/actions/CCActionCatmullRom.js | 6 +- cocos2d/actions/CCActionEase.js | 14 +-- cocos2d/actions/CCActionInstant.js | 2 +- cocos2d/actions/CCActionInterval.js | 10 +- cocos2d/actions3d/CCActionGrid.js | 2 +- cocos2d/actions3d/CCActionGrid3D.js | 4 +- cocos2d/actions3d/CCActionTiledGrid.js | 16 +-- cocos2d/audio/CCAudio.js | 12 +- cocos2d/clipping-nodes/CCClippingNode.js | 2 +- .../CCClippingNodeWebGLRenderCmd.js | 2 +- cocos2d/compression/base64.js | 6 +- cocos2d/compression/gzip.js | 40 +++--- cocos2d/core/CCActionManager.js | 18 +-- cocos2d/core/CCDirector.js | 12 +- cocos2d/core/CCDirectorWebGL.js | 2 +- cocos2d/core/CCDrawingPrimitivesCanvas.js | 2 +- cocos2d/core/CCDrawingPrimitivesWebGL.js | 6 +- cocos2d/core/CCScheduler.js | 38 +++--- .../base-nodes/CCAtlasNodeCanvasRenderCmd.js | 2 +- cocos2d/core/base-nodes/CCNode.js | 32 ++--- .../core/base-nodes/CCNodeCanvasRenderCmd.js | 10 +- .../core/base-nodes/CCNodeWebGLRenderCmd.js | 2 +- cocos2d/core/cocoa/CCGeometry.js | 6 +- .../core/event-manager/CCEventExtension.js | 2 +- cocos2d/core/event-manager/CCEventListener.js | 10 +- cocos2d/core/event-manager/CCEventManager.js | 58 ++++----- cocos2d/core/labelttf/CCLabelTTF.js | 34 ++--- .../labelttf/CCLabelTTFCanvasRenderCmd.js | 8 +- cocos2d/core/layers/CCLayerCanvasRenderCmd.js | 2 +- cocos2d/core/platform/CCClass.js | 8 +- cocos2d/core/platform/CCCommon.js | 22 ++-- cocos2d/core/platform/CCEGLView.js | 14 +-- cocos2d/core/platform/CCInputExtension.js | 8 +- cocos2d/core/platform/CCInputManager.js | 6 +- cocos2d/core/platform/CCLoaders.js | 2 +- cocos2d/core/platform/CCMacro.js | 4 +- cocos2d/core/platform/CCSAXParser.js | 26 ++-- cocos2d/core/platform/miniFramework.js | 2 +- cocos2d/core/sprites/CCAnimationCache.js | 2 +- cocos2d/core/sprites/CCSprite.js | 12 +- cocos2d/core/sprites/CCSpriteBatchNode.js | 16 +-- .../CCSpriteBatchNodeWebGLRenderCmd.js | 12 +- .../core/sprites/CCSpriteCanvasRenderCmd.js | 16 +-- cocos2d/core/sprites/CCSpriteFrame.js | 2 +- cocos2d/core/sprites/CCSpriteFrameCache.js | 6 +- .../core/sprites/CCSpriteWebGLRenderCmd.js | 12 +- cocos2d/core/support/CCPointExtension.js | 8 +- cocos2d/core/support/CCVertex.js | 6 +- cocos2d/core/textures/CCTexture2D.js | 4 +- cocos2d/core/textures/CCTextureAtlas.js | 8 +- cocos2d/core/textures/CCTextureCache.js | 7 +- cocos2d/core/textures/TexturesWebGL.js | 16 +-- cocos2d/core/utils/BinaryLoader.js | 8 +- cocos2d/effects/CCGrabber.js | 2 +- cocos2d/effects/CCGrid.js | 2 +- cocos2d/kazmath/mat4.js | 12 +- cocos2d/kazmath/quaternion.js | 2 +- cocos2d/labels/CCLabelAtlasCanvasRenderCmd.js | 4 +- cocos2d/labels/CCLabelBMFont.js | 22 ++-- .../labels/CCLabelBMFontCanvasRenderCmd.js | 2 +- cocos2d/menus/CCMenu.js | 20 +-- cocos2d/menus/CCMenuItem.js | 18 +-- cocos2d/motion-streak/CCMotionStreak.js | 6 +- cocos2d/node-grid/CCNodeGrid.js | 2 +- cocos2d/parallax/CCParallaxNode.js | 4 +- cocos2d/particle/CCParticleBatchNode.js | 20 +-- .../CCParticleBatchNodeWebGLRenderCmd.js | 2 +- cocos2d/particle/CCParticleSystem.js | 38 +++--- .../CCParticleSystemCanvasRenderCmd.js | 4 +- .../CCParticleSystemWebGLRenderCmd.js | 5 +- cocos2d/physics/CCPhysicsSprite.js | 4 +- cocos2d/progress-timer/CCProgressTimer.js | 4 +- .../CCProgressTimerCanvasRenderCmd.js | 6 +- .../CCProgressTimerWebGLRenderCmd.js | 14 +-- .../CCRenderTextureWebGLRenderCmd.js | 6 +- cocos2d/shaders/CCGLProgram.js | 10 +- cocos2d/shaders/CCGLStateCache.js | 6 +- cocos2d/shape-nodes/CCDrawNode.js | 8 +- .../shape-nodes/CCDrawNodeCanvasRenderCmd.js | 2 +- cocos2d/text-input/CCIMEDispatcher.js | 22 ++-- cocos2d/text-input/CCTextFieldTTF.js | 4 +- cocos2d/tilemap/CCTGAlib.js | 8 +- cocos2d/tilemap/CCTMXLayer.js | 14 +-- cocos2d/tilemap/CCTMXObjectGroup.js | 2 +- cocos2d/tilemap/CCTMXTiledMap.js | 8 +- cocos2d/tilemap/CCTMXXMLParser.js | 14 +-- cocos2d/transitions/CCTransition.js | 7 +- cocos2d/transitions/CCTransitionProgress.js | 4 +- extensions/ccb-reader/CCBAnimationManager.js | 20 ++- extensions/ccb-reader/CCBReader.js | 66 +++++----- extensions/ccb-reader/CCControlLoader.js | 76 ++++++------ extensions/ccb-reader/CCNodeLoader.js | 43 ++++--- extensions/ccb-reader/CCSpriteLoader.js | 2 +- extensions/ccpool/CCPool.js | 2 +- .../ccui/base-classes/CCProtectedNode.js | 6 +- .../CCProtectedNodeWebGLRenderCmd.js | 2 +- .../ccui/base-classes/UIScale9Sprite.js | 16 +-- .../UIScale9SpriteCanvasRenderCmd.js | 2 +- extensions/ccui/base-classes/UIWidget.js | 38 +++--- extensions/ccui/layouts/UILayout.js | 76 ++++++------ extensions/ccui/layouts/UILayoutComponent.js | 46 +++---- extensions/ccui/layouts/UILayoutManager.js | 4 +- extensions/ccui/layouts/UILayoutParameter.js | 2 +- .../ccui/layouts/UILayoutWebGLRenderCmd.js | 2 +- extensions/ccui/system/UIHelper.js | 16 +-- extensions/ccui/uiwidgets/UIButton.js | 8 +- extensions/ccui/uiwidgets/UICheckBox.js | 6 +- extensions/ccui/uiwidgets/UIImageView.js | 2 +- extensions/ccui/uiwidgets/UILoadingBar.js | 6 +- extensions/ccui/uiwidgets/UIRichText.js | 31 +++-- extensions/ccui/uiwidgets/UISlider.js | 2 +- extensions/ccui/uiwidgets/UIText.js | 4 +- extensions/ccui/uiwidgets/UITextAtlas.js | 2 +- extensions/ccui/uiwidgets/UITextBMFont.js | 2 +- extensions/ccui/uiwidgets/UITextField.js | 4 +- .../uiwidgets/scroll-widget/UIListView.js | 14 +-- .../uiwidgets/scroll-widget/UIPageView.js | 4 +- .../uiwidgets/scroll-widget/UIScrollView.js | 56 ++++----- .../cocostudio/action/CCActionManager.js | 2 +- extensions/cocostudio/action/CCActionNode.js | 20 +-- .../cocostudio/action/CCActionObject.js | 2 +- extensions/cocostudio/armature/CCArmature.js | 8 +- .../armature/CCArmatureCanvasRenderCmd.js | 2 +- .../armature/CCArmatureWebGLRenderCmd.js | 10 +- extensions/cocostudio/armature/CCBone.js | 14 +-- .../armature/animation/CCArmatureAnimation.js | 20 +-- .../armature/animation/CCProcessBase.js | 4 +- .../cocostudio/armature/animation/CCTween.js | 28 ++--- .../cocostudio/armature/datas/CCDatas.js | 4 +- .../armature/display/CCDisplayFactory.js | 9 +- .../armature/display/CCDisplayManager.js | 10 +- .../cocostudio/armature/display/CCSkin.js | 6 +- .../armature/physics/CCColliderDetector.js | 4 +- .../armature/utils/CCDataReaderHelper.js | 28 ++--- .../armature/utils/CCTransformHelp.js | 2 +- .../armature/utils/CCTweenFunction.js | 10 +- .../cocostudio/components/CCComController.js | 2 +- .../components/CCComponentContainer.js | 2 +- .../cocostudio/loader/parsers/action-1.x.js | 2 +- .../cocostudio/loader/parsers/compatible.js | 8 +- .../cocostudio/loader/parsers/scene-1.x.js | 18 +-- .../loader/parsers/timelineParser-1.x.js | 10 +- .../loader/parsers/timelineParser-2.x.js | 44 +++---- .../cocostudio/loader/parsers/uiParser-1.x.js | 4 +- .../cocostudio/timeline/ActionTimeline.js | 2 +- extensions/cocostudio/timeline/Frame.js | 22 ++-- extensions/cocostudio/timeline/Timeline.js | 13 +- extensions/cocostudio/trigger/TriggerMng.js | 10 +- extensions/cocostudio/trigger/TriggerObj.js | 4 +- extensions/editbox/CCEditBox.js | 24 ++-- extensions/editbox/CCdomNode.js | 10 +- extensions/gui/control-extension/CCControl.js | 4 +- .../gui/control-extension/CCControlButton.js | 6 +- .../CCControlColourPicker.js | 2 +- .../CCControlPotentiometer.js | 2 +- .../gui/control-extension/CCControlStepper.js | 10 +- .../gui/control-extension/CCMenuPassive.js | 2 +- .../gui/control-extension/CCScale9Sprite.js | 16 +-- .../CCScale9SpriteCanvasRenderCmd.js | 2 +- .../CCScale9SpriteWebGLRenderCmd.js | 2 +- extensions/gui/scrollview/CCScrollView.js | 30 ++--- extensions/gui/scrollview/CCSorting.js | 20 +-- extensions/gui/scrollview/CCTableView.js | 38 +++--- 166 files changed, 1031 insertions(+), 1046 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index 8e2a876172..24331d41b9 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -114,7 +114,7 @@ cc.extend = function(target) { * @returns {boolean} */ cc.isFunction = function(obj) { - return typeof obj == 'function'; + return typeof obj === 'function'; }; /** @@ -123,7 +123,7 @@ cc.isFunction = function(obj) { * @returns {boolean} */ cc.isNumber = function(obj) { - return typeof obj == 'number' || Object.prototype.toString.call(obj) == '[object Number]'; + return typeof obj === 'number' || Object.prototype.toString.call(obj) === '[object Number]'; }; /** @@ -132,7 +132,7 @@ cc.isNumber = function(obj) { * @returns {boolean} */ cc.isString = function(obj) { - return typeof obj == 'string' || Object.prototype.toString.call(obj) == '[object String]'; + return typeof obj === 'string' || Object.prototype.toString.call(obj) === '[object String]'; }; /** @@ -174,12 +174,12 @@ cc.isCrossOrigin = function (url) { return false; } var startIndex = url.indexOf("://"); - if (startIndex == -1) + if (startIndex === -1) return false; var endIndex = url.indexOf("/", startIndex + 3); - var urlOrigin = (endIndex == -1) ? url : url.substring(0, endIndex); - return urlOrigin != location.origin; + var urlOrigin = (endIndex === -1) ? url : url.substring(0, endIndex); + return urlOrigin !== location.origin; }; //+++++++++++++++++++++++++something about async begin+++++++++++++++++++++++++++++++ @@ -226,7 +226,7 @@ cc.AsyncPool = function(srcObj, limit, iterator, onEnd, target){ self._handleItem = function(){ var self = this; - if(self._pool.length == 0 || self._workingSize >= self._limit) + if(self._pool.length === 0 || self._workingSize >= self._limit) return; //return directly if the array's length = 0 or the working size great equal limit number var item = self._pool.shift(); @@ -248,7 +248,7 @@ cc.AsyncPool = function(srcObj, limit, iterator, onEnd, target){ var arr = Array.prototype.slice.call(arguments, 1); self._results[this.index] = arr[0]; - if (self.finishedSize == self.size) { + if (self.finishedSize === self.size) { if (self._onEnd) self._onEnd.call(self._onEndTarget, null, self._results); return; @@ -260,7 +260,7 @@ cc.AsyncPool = function(srcObj, limit, iterator, onEnd, target){ self.flow = function(){ var self = this; - if(self._pool.length == 0) { + if(self._pool.length === 0) { if(self._onEnd) self._onEnd.call(self._onEndTarget, null, []); return; @@ -318,7 +318,7 @@ cc.async = /** @lends cc.async# */{ function (func, index, cb1) { args.push(function (err) { args = Array.prototype.slice.call(arguments, 1); - if(tasks.length - 1 == index) lastResults = lastResults.concat(args);//while the last task + if(tasks.length - 1 === index) lastResults = lastResults.concat(args);//while the last task cb1.apply(null, arguments); }); func.apply(target, args); @@ -343,7 +343,7 @@ cc.async = /** @lends cc.async# */{ */ map : function(tasks, iterator, callback, target){ var locIterator = iterator; - if(typeof(iterator) == "object"){ + if(typeof(iterator) === "object"){ callback = iterator.cb; target = iterator.iteratorTarget; locIterator = iterator.iterator; @@ -388,7 +388,7 @@ cc.path = /** @lends cc.path# */{ var l = arguments.length; var result = ""; for (var i = 0; i < l; i++) { - result = (result + (result == "" ? "" : "/") + arguments[i]).replace(/(\/|\\\\)$/, ""); + result = (result + (result === "" ? "" : "/") + arguments[i]).replace(/(\/|\\\\)$/, ""); } return result; }, @@ -441,7 +441,7 @@ cc.path = /** @lends cc.path# */{ var result = reg.exec(pathStr.replace(/(\/|\\\\)$/, "")); if (!result) return null; var baseName = result[2]; - if (extname && pathStr.substring(pathStr.length - extname.length).toLowerCase() == extname.toLowerCase()) + if (extname && pathStr.substring(pathStr.length - extname.length).toLowerCase() === extname.toLowerCase()) return baseName.substring(0, baseName.length - extname.length); return baseName; }, @@ -499,7 +499,7 @@ cc.path = /** @lends cc.path# */{ * @returns {string} */ changeBasename: function (pathStr, basename, isSameExt) { - if (basename.indexOf(".") == 0) return this.changeExtname(pathStr, basename); + if (basename.indexOf(".") === 0) return this.changeExtname(pathStr, basename); var index = pathStr.indexOf("?"); var tempStr = ""; var ext = isSameExt ? this.extname(pathStr) : ""; @@ -545,7 +545,7 @@ cc.loader = /** @lends cc.loader# */{ if (args.length === 1) { results[1] = a0 instanceof Array ? a0 : [a0]; } else if (args.length === 2) { - if (typeof a1 == "function") { + if (typeof a1 === "function") { results[1] = a0 instanceof Array ? a0 : [a0]; results[2] = a1; } else { @@ -671,14 +671,14 @@ cc.loader = /** @lends cc.loader# */{ // IE-specific logic here xhr.setRequestHeader("Accept-Charset", "utf-8"); xhr.onreadystatechange = function () { - if(xhr.readyState == 4) - xhr.status == 200 ? cb(null, xhr.responseText) : cb(errInfo); + if(xhr.readyState === 4) + xhr.status === 200 ? cb(null, xhr.responseText) : cb(errInfo); }; } else { if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=utf-8"); xhr.onload = function () { - if(xhr.readyState == 4) - xhr.status == 200 ? cb(null, xhr.responseText) : cb(errInfo); + if(xhr.readyState === 4) + xhr.status === 200 ? cb(null, xhr.responseText) : cb(errInfo); }; } xhr.send(null); @@ -700,7 +700,7 @@ cc.loader = /** @lends cc.loader# */{ if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=utf-8"); } xhr.send(null); - if (!xhr.readyState == 4 || xhr.status != 200) { + if (!xhr.readyState === 4 || xhr.status !== 200) { return null; } return xhr.responseText; @@ -720,8 +720,8 @@ cc.loader = /** @lends cc.loader# */{ if (arrayBuffer) { window.msg = arrayBuffer; } - if(xhr.readyState == 4) - xhr.status == 200 ? cb(null, xhr.response) : cb("load " + url + " failed!"); + if(xhr.readyState === 4) + xhr.status === 200 ? cb(null, xhr.response) : cb("load " + url + " failed!"); }; xhr.send(null); @@ -766,7 +766,7 @@ cc.loader = /** @lends cc.loader# */{ isCrossOrigin: true }; if (callback !== undefined) - opt.isCrossOrigin = option.isCrossOrigin == null ? opt.isCrossOrigin : option.isCrossOrigin; + opt.isCrossOrigin = option.isCrossOrigin === null ? opt.isCrossOrigin : option.isCrossOrigin; else if (option !== undefined) callback = option; @@ -777,7 +777,7 @@ cc.loader = /** @lends cc.loader# */{ } img = new Image(); - if (opt.isCrossOrigin && location.origin != "file://") + if (opt.isCrossOrigin && location.origin !== "file://") img.crossOrigin = "Anonymous"; var loadCallback = function () { @@ -793,12 +793,12 @@ cc.loader = /** @lends cc.loader# */{ var errorCallback = function () { this.removeEventListener('error', errorCallback, false); - if(img.crossOrigin && img.crossOrigin.toLowerCase() == "anonymous"){ + if(img.crossOrigin && img.crossOrigin.toLowerCase() === "anonymous"){ opt.isCrossOrigin = false; self.release(url); cc.loader.loadImg(url, opt, callback); }else{ - typeof callback == "function" && callback("load image failed"); + typeof callback === "function" && callback("load image failed"); } }; @@ -898,20 +898,20 @@ cc.loader = /** @lends cc.loader# */{ load : function(resources, option, loadCallback){ var self = this; var len = arguments.length; - if(len == 0) + if(len === 0) throw "arguments error!"; - if(len == 3){ - if(typeof option == "function"){ - if(typeof loadCallback == "function") + if(len === 3){ + if(typeof option === "function"){ + if(typeof loadCallback === "function") option = {trigger : option, cb : loadCallback }; else option = { cb : option, cbTarget : loadCallback}; } - }else if(len == 2){ - if(typeof option == "function") + }else if(len === 2){ + if(typeof option === "function") option = {cb : option}; - }else if(len == 1){ + }else if(len === 1){ option = {}; } @@ -992,7 +992,7 @@ cc.loader = /** @lends cc.loader# */{ register: function (extNames, loader) { if (!extNames || !loader) return; var self = this; - if (typeof extNames == "string") + if (typeof extNames === "string") return this._register[extNames.trim().toLowerCase()] = loader; for (var i = 0, li = extNames.length; i < li; i++) { self._register["." + extNames[i].trim().toLowerCase()] = loader; @@ -1047,7 +1047,7 @@ cc.formatStr = function(){ var str = args[0]; var needToFormat = true; - if(typeof str == "object"){ + if(typeof str === "object"){ needToFormat = false; } for(var i = 1; i < l; ++i){ @@ -1055,7 +1055,7 @@ cc.formatStr = function(){ if(needToFormat){ while(true){ var result = null; - if(typeof arg == "number"){ + if(typeof arg === "number"){ result = str.match(/(%d)|(%s)/); if(result){ str = str.replace(/(%d)|(%s)/, arg); @@ -1527,7 +1527,7 @@ cc._initSys = function (config, CONFIG_KEY) { * @name isMobile * @type {Boolean} */ - sys.isMobile = ua.indexOf('mobile') != -1 || ua.indexOf('android') != -1; + sys.isMobile = ua.indexOf('mobile') !== -1 || ua.indexOf('android') !== -1; /** * Indicate the running platform @@ -1554,12 +1554,12 @@ cc._initSys = function (config, CONFIG_KEY) { || ua.match(/chrome|safari/i); if (browserTypes && browserTypes.length > 0) { browserType = browserTypes[0]; - if (browserType == 'micromessenger') { + if (browserType === 'micromessenger') { browserType = sys.BROWSER_TYPE_WECHAT; } else if (browserType === "safari" && (ua.match(/android.*applewebkit/))) browserType = sys.BROWSER_TYPE_ANDROID; - else if (browserType == "trident") browserType = sys.BROWSER_TYPE_IE; - else if (browserType == "360 aphone") browserType = sys.BROWSER_TYPE_360; + else if (browserType === "trident") browserType = sys.BROWSER_TYPE_IE; + else if (browserType === "360 aphone") browserType = sys.BROWSER_TYPE_360; }else if(ua.indexOf("iphone") && ua.indexOf("mobile")){ browserType = "safari"; } @@ -1575,12 +1575,12 @@ cc._initSys = function (config, CONFIG_KEY) { var iOS = ( ua.match(/(iPad|iPhone|iPod)/i) ? true : false ); var isAndroid = ua.match(/android/i) || nav.platform.match(/android/i) ? true : false; var osName = sys.OS_UNKNOWN; - if (nav.appVersion.indexOf("Win") != -1) osName = sys.OS_WINDOWS; + if (nav.appVersion.indexOf("Win") !== -1) osName = sys.OS_WINDOWS; else if (iOS) osName = sys.OS_IOS; - else if (nav.appVersion.indexOf("Mac") != -1) osName = sys.OS_OSX; - else if (nav.appVersion.indexOf("X11") != -1 && nav.appVersion.indexOf("Linux") == -1) osName = sys.OS_UNIX; + else if (nav.appVersion.indexOf("Mac") !== -1) osName = sys.OS_OSX; + else if (nav.appVersion.indexOf("X11") !== -1 && nav.appVersion.indexOf("Linux") === -1) osName = sys.OS_UNIX; else if (isAndroid) osName = sys.OS_ANDROID; - else if (nav.appVersion.indexOf("Linux") != -1) osName = sys.OS_LINUX; + else if (nav.appVersion.indexOf("Linux") !== -1) osName = sys.OS_LINUX; /** * Indicate the running os name @@ -1600,10 +1600,10 @@ cc._initSys = function (config, CONFIG_KEY) { cc._supportRender = true; var notSupportGL = true; if(iOS) - notSupportGL = !window.WebGLRenderingContext || osSupportWebGL.indexOf(sys.os) == -1; + notSupportGL = !window.WebGLRenderingContext || osSupportWebGL.indexOf(sys.os) === -1; else - notSupportGL = !window.WebGLRenderingContext || browserSupportWebGL.indexOf(sys.browserType) == -1 || osSupportWebGL.indexOf(sys.os) == -1; - if (userRenderMode === 1 || (userRenderMode === 0 && notSupportGL) || (location.origin == "file://")) + notSupportGL = !window.WebGLRenderingContext || browserSupportWebGL.indexOf(sys.browserType) === -1 || osSupportWebGL.indexOf(sys.os) === -1; + if (userRenderMode === 1 || (userRenderMode === 0 && notSupportGL) || (location.origin === "file://")) renderType = cc._RENDER_TYPE_CANVAS; sys._canUseCanvasNewBlendModes = function(){ @@ -1630,15 +1630,15 @@ cc._initSys = function (config, CONFIG_KEY) { //Whether or not the Canvas BlendModes are supported. sys._supportCanvasNewBlendModes = sys._canUseCanvasNewBlendModes(); - if (renderType == cc._RENDER_TYPE_WEBGL) { + if (renderType === cc._RENDER_TYPE_WEBGL) { if (!win.WebGLRenderingContext || !cc.create3DContext(tempCanvas, {'stencil': true, 'preserveDrawingBuffer': true })) { - if (userRenderMode == 0) renderType = cc._RENDER_TYPE_CANVAS; + if (userRenderMode === 0) renderType = cc._RENDER_TYPE_CANVAS; else cc._supportRender = false; } } - if (renderType == cc._RENDER_TYPE_CANVAS) { + if (renderType === cc._RENDER_TYPE_CANVAS) { try { tempCanvas.getContext("2d"); } catch (e) { @@ -1676,7 +1676,7 @@ cc._initSys = function (config, CONFIG_KEY) { } var capabilities = sys.capabilities = {"canvas": true}; - if (cc._renderType == cc._RENDER_TYPE_WEBGL) + if (cc._renderType === cc._RENDER_TYPE_WEBGL) capabilities["opengl"] = true; if (docEle['ontouchstart'] !== undefined || doc['ontouchstart'] !== undefined || nav.msPointerEnabled) capabilities["touches"] = true; @@ -1838,7 +1838,7 @@ cc._setup = function (el, width, height) { cc.game._setAnimFrame(); - if (element.tagName == "CANVAS") { + if (element.tagName === "CANVAS") { width = width || element.width; height = height || element.height; @@ -1849,7 +1849,7 @@ cc._setup = function (el, width, height) { localCanvas.appendTo(localContainer); localContainer.setAttribute('id', 'Cocos2dGameContainer'); } else {//we must make a new canvas and place into this element - if (element.tagName != "DIV") { + if (element.tagName !== "DIV") { cc.log("Warning: target element is not a DIV or CANVAS"); } width = width || element.clientWidth; @@ -1873,7 +1873,7 @@ cc._setup = function (el, width, height) { localConStyle.overflow = 'hidden'; localContainer.top = '100%'; - if (cc._renderType == cc._RENDER_TYPE_WEBGL) + if (cc._renderType === cc._RENDER_TYPE_WEBGL) cc._renderContext = cc.webglContext = cc.create3DContext(localCanvas, { 'stencil': true, 'preserveDrawingBuffer': true, @@ -2036,7 +2036,7 @@ cc.game = /** @lends cc.game# */{ _setAnimFrame: function () { this._lastTime = new Date(); this._frameTime = 1000 / cc.game.config[cc.game.CONFIG_KEY.frameRate]; - if((cc.sys.os === cc.sys.OS_IOS && cc.sys.browserType === cc.sys.BROWSER_TYPE_WECHAT) || cc.game.config[cc.game.CONFIG_KEY.frameRate] != 60) { + if((cc.sys.os === cc.sys.OS_IOS && cc.sys.browserType === cc.sys.BROWSER_TYPE_WECHAT) || cc.game.config[cc.game.CONFIG_KEY.frameRate] !== 60) { window.requestAnimFrame = this._stTime; window.cancelAnimationFrame = this._ctTime; } @@ -2157,7 +2157,7 @@ cc.game = /** @lends cc.game# */{ var cocos_script = document.getElementsByTagName('script'); for(var i=0;i 0) { var locGridSize = targetGrid.getGridSize(); - if (targetGrid.isActive() && (locGridSize.width == this._gridSize.width) && (locGridSize.height == this._gridSize.height)) + if (targetGrid.isActive() && (locGridSize.width === this._gridSize.width) && (locGridSize.height === this._gridSize.height)) targetGrid.reuse(); } else { if (targetGrid && targetGrid.isActive()) diff --git a/cocos2d/actions3d/CCActionGrid3D.js b/cocos2d/actions3d/CCActionGrid3D.js index d795c69b40..31be9c2e9a 100644 --- a/cocos2d/actions3d/CCActionGrid3D.js +++ b/cocos2d/actions3d/CCActionGrid3D.js @@ -184,7 +184,7 @@ cc.FlipX3D = cc.Grid3DAction.extend(/** @lends cc.FlipX3D# */{ * @return {Boolean} */ initWithSize:function (gridSize, duration) { - if (gridSize.width != 1 || gridSize.height != 1) { + if (gridSize.width !== 1 || gridSize.height !== 1) { // Grid size must be (1,1) cc.log("Grid size must be (1,1)"); return false; @@ -516,7 +516,7 @@ cc.Lens3D = cc.Grid3DAction.extend(/** @lends cc.Lens3D# */{ if (r < locRadius) { r = locRadius - r; pre_log = r / locRadius; - if (pre_log == 0) + if (pre_log === 0) pre_log = 0.001; l = Math.log(pre_log) * locLensEffect; diff --git a/cocos2d/actions3d/CCActionTiledGrid.js b/cocos2d/actions3d/CCActionTiledGrid.js index ff9b42e6be..dae3d8daa2 100644 --- a/cocos2d/actions3d/CCActionTiledGrid.js +++ b/cocos2d/actions3d/CCActionTiledGrid.js @@ -457,7 +457,7 @@ cc.FadeOutTRTiles = cc.TiledGrid3DAction.extend(/** @lends cc.FadeOutTRTiles# */ testFunc:function (pos, time) { var locX = this._gridSize.width * time; var locY = this._gridSize.height * time; - if ((locX + locY) == 0.0) + if ((locX + locY) === 0.0) return 1.0; return Math.pow((pos.width + pos.height) / (locX + locY), 6); }, @@ -516,7 +516,7 @@ cc.FadeOutTRTiles = cc.TiledGrid3DAction.extend(/** @lends cc.FadeOutTRTiles# */ locSize.width = i; locSize.height = j; distance = this.testFunc(locSize, dt); - if (distance == 0) + if (distance === 0) this.turnOffTile(locPos); else if (distance < 1) this.transformTile(locPos, distance); @@ -566,7 +566,7 @@ cc.FadeOutBLTiles = cc.FadeOutTRTiles.extend(/** @lends cc.FadeOutBLTiles# */{ testFunc:function (pos, time) { var locX = this._gridSize.width * (1.0 - time); var locY = this._gridSize.height * (1.0 - time); - if ((pos.width + pos.height) == 0) + if ((pos.width + pos.height) === 0) return 1.0; return Math.pow((locX + locY) / (pos.width + pos.height), 6); @@ -606,7 +606,7 @@ cc.FadeOutBLTiles.create = cc.fadeOutBLTiles; cc.FadeOutUpTiles = cc.FadeOutTRTiles.extend(/** @lends cc.FadeOutUpTiles# */{ testFunc:function (pos, time) { var locY = this._gridSize.height * time; - if (locY == 0.0) + if (locY === 0.0) return 1.0; return Math.pow(pos.height / locY, 6); }, @@ -657,7 +657,7 @@ cc.FadeOutUpTiles.create = cc.fadeOutUpTiles; cc.FadeOutDownTiles = cc.FadeOutUpTiles.extend(/** @lends cc.FadeOutDownTiles# */{ testFunc:function (pos, time) { var locY = this._gridSize.height * (1.0 - time); - if (pos.height == 0) + if (pos.height === 0) return 1.0; return Math.pow(locY / pos.height, 6); } @@ -1057,7 +1057,7 @@ cc.JumpTiles3D = cc.TiledGrid3DAction.extend(/** @lends cc.JumpTiles3D# */{ //var coords = this.originalTile(cc.p(i, j)); coords = locGrid.originalTile(locPos); - if (((i + j) % 2) == 0) { + if (((i + j) % 2) === 0) { coords.bl.z += sinz; coords.br.z += sinz; coords.tl.z += sinz; @@ -1150,7 +1150,7 @@ cc.SplitRows = cc.TiledGrid3DAction.extend(/** @lends cc.SplitRows# */{ coords = this.originalTile(locPos); direction = 1; - if ((j % 2 ) == 0) + if ((j % 2 ) === 0) direction = -1; coords.bl.x += direction * locWinSizeWidth * dt; @@ -1241,7 +1241,7 @@ cc.SplitCols = cc.TiledGrid3DAction.extend(/** @lends cc.SplitCols# */{ coords = this.originalTile(locPos); direction = 1; - if ((i % 2 ) == 0) + if ((i % 2 ) === 0) direction = -1; coords.bl.y += direction * locWinSizeHeight * dt; diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index 6ce489238c..e59d580ffc 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -121,7 +121,7 @@ break; case sys.BROWSER_TYPE_MIUI: version = version.match(/\d+/g); - if(version[0] < 2 || (version[0] == 2 && version[1] == 0 && version[2] <= 1)){ + if(version[0] < 2 || (version[0] === 2 && version[1] === 0 && version[2] <= 1)){ supportTable[sys.BROWSER_TYPE_MIUI].auto = false; } break; @@ -129,7 +129,7 @@ } if(cc.sys.isMobile){ - if(cc.sys.os != cc.sys.OS_IOS) + if(cc.sys.os !== cc.sys.OS_IOS) cc.__audioSupport = supportTable[sys.browserType] || supportTable["common"]; else cc.__audioSupport = supportTable[sys.BROWSER_TYPE_SAFARI]; @@ -200,7 +200,7 @@ cc.Audio = cc.Class.extend({ var playing = this._playing; this._AUDIO_TYPE = "WEBAUDIO"; - if(this._buffer && this._buffer != buffer && this.getPlaying()) + if(this._buffer && this._buffer !== buffer && this.getPlaying()) this.stop(); this._buffer = buffer; @@ -217,7 +217,7 @@ cc.Audio = cc.Class.extend({ var playing = this._playing; this._AUDIO_TYPE = "AUDIO"; - if(this._element && this._element != element && this.getPlaying()) + if(this._element && this._element !== element && this.getPlaying()) this.stop(); this._element = element; @@ -350,7 +350,7 @@ cc.Audio = cc.Class.extend({ var audio = this._element; if(audio){ audio.pause(); - if (audio.duration && audio.duration != Infinity) + if (audio.duration && audio.duration !== Infinity) audio.currentTime = 0; } }, @@ -570,7 +570,7 @@ cc.Audio = cc.Class.extend({ var termination = false; var timer = setTimeout(function(){ - if(element.readyState == 0){ + if(element.readyState === 0){ emptied(); }else{ termination = true; diff --git a/cocos2d/clipping-nodes/CCClippingNode.js b/cocos2d/clipping-nodes/CCClippingNode.js index 7d73097c3f..65a10b45cf 100644 --- a/cocos2d/clipping-nodes/CCClippingNode.js +++ b/cocos2d/clipping-nodes/CCClippingNode.js @@ -189,7 +189,7 @@ cc.ClippingNode = cc.Node.extend(/** @lends cc.ClippingNode# */{ * @param {cc.Node} stencil */ setStencil: function (stencil) { - if(this._stencil == stencil) + if(this._stencil === stencil) return; this._renderCmd.setStencil(stencil); }, diff --git a/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js b/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js index 451fb6ab7f..283df8fc46 100644 --- a/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js +++ b/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js @@ -91,7 +91,7 @@ return; } - if (cc.ClippingNode.WebGLRenderCmd._layer + 1 == cc.stencilBits) { + if (cc.ClippingNode.WebGLRenderCmd._layer + 1 === cc.stencilBits) { cc.ClippingNode.WebGLRenderCmd._visit_once = true; if (cc.ClippingNode.WebGLRenderCmd._visit_once) { cc.log("Nesting more than " + cc.stencilBits + "stencils is not supported. Everything will be drawn without stencil for this node and its children."); diff --git a/cocos2d/compression/base64.js b/cocos2d/compression/base64.js index dbbf5b9f70..adb0d68871 100644 --- a/cocos2d/compression/base64.js +++ b/cocos2d/compression/base64.js @@ -42,10 +42,10 @@ cc.Codec.Base64.decode = function Jacob__Codec__Base64__decode(input) { output.push(String.fromCharCode(chr1)); - if (enc3 != 64) { + if (enc3 !== 64) { output.push(String.fromCharCode(chr2)); } - if (enc4 != 64) { + if (enc4 !== 64) { output.push(String.fromCharCode(chr3)); } } @@ -82,7 +82,7 @@ cc.Codec.Base64.decodeAsArray = function Jacob__Codec__Base64___decodeAsArray(in }; cc.uint8ArrayToUint32Array = function(uint8Arr){ - if(uint8Arr.length % 4 != 0) + if(uint8Arr.length % 4 !== 0) return null; var arrLen = uint8Arr.length /4; diff --git a/cocos2d/compression/gzip.js b/cocos2d/compression/gzip.js index 65c7d79eda..baed633cef 100644 --- a/cocos2d/compression/gzip.js +++ b/cocos2d/compression/gzip.js @@ -157,7 +157,7 @@ cc.Codec.GZip.prototype.readBit = function () { this.bits++; carry = (this.bb & 1); this.bb >>= 1; - if (this.bb == 0) { + if (this.bb === 0) { this.bb = this.readByte(); carry = (this.bb & 1); this.bb = (this.bb >> 1) | 0x80; @@ -182,13 +182,13 @@ cc.Codec.GZip.prototype.flushBuffer = function () { cc.Codec.GZip.prototype.addBuffer = function (a) { this.buf32k[this.bIdx++] = a; this.outputArr.push(String.fromCharCode(a)); - if (this.bIdx == 0x8000) this.bIdx = 0; + if (this.bIdx === 0x8000) this.bIdx = 0; }; cc.Codec.GZip.prototype.IsPat = function () { while (1) { if (this.fpos[this.len] >= this.fmax) return -1; - if (this.flens[this.fpos[this.len]] == this.len) return this.fpos[this.len]++; + if (this.flens[this.fpos[this.len]] === this.len) return this.fpos[this.len]++; this.fpos[this.len]++; } }; @@ -197,7 +197,7 @@ cc.Codec.GZip.prototype.Rec = function () { var curplace = this.Places[this.treepos]; var tmp; //if (this.debug) document.write("
len:"+this.len+" treepos:"+this.treepos); - if (this.len == 17) { //war 17 + if (this.len === 17) { //war 17 return -1; } this.treepos++; @@ -304,7 +304,7 @@ cc.Codec.GZip.prototype.DeflateLoop = function () { last = this.readBit(); type = this.readBits(2); - if (type == 0) { + if (type === 0) { var blockLen, cSum; // Stored @@ -322,7 +322,7 @@ cc.Codec.GZip.prototype.DeflateLoop = function () { c = this.readByte(); this.addBuffer(c); } - } else if (type == 1) { + } else if (type === 1) { var j; /* Fixed Huffman tables -- fixed decode routine */ @@ -368,7 +368,7 @@ cc.Codec.GZip.prototype.DeflateLoop = function () { } if (j < 256) { this.addBuffer(j); - } else if (j == 256) { + } else if (j === 256) { /* EOF */ break; // FIXME: make this the loop-condition } else { @@ -394,7 +394,7 @@ cc.Codec.GZip.prototype.DeflateLoop = function () { } } // while - } else if (type == 2) { + } else if (type === 2) { var j, n, literalCodes, distCodes, lenCodes; var ll = new Array(288 + 32); // "static" just to preserve stack @@ -436,7 +436,7 @@ cc.Codec.GZip.prototype.DeflateLoop = function () { // if (this.debug) document.write("
"+z+" i:"+i+" decode: "+j+" bits "+this.bits+"
"); if (j < 16) { // length of code in bits (0..15) ll[i++] = j; - } else if (j == 16) { // repeat last length 3 to 6 times + } else if (j === 16) { // repeat last length 3 to 6 times var l; j = 3 + this.readBits(2); if (i + j > n) { @@ -448,7 +448,7 @@ cc.Codec.GZip.prototype.DeflateLoop = function () { ll[i++] = l; } } else { - if (j == 17) { // 3 to 10 zero length codes + if (j === 17) { // 3 to 10 zero length codes j = 3 + this.readBits(3); } else { // j == 18: 11 to 138 zero length codes j = 11 + this.readBits(7); @@ -485,7 +485,7 @@ cc.Codec.GZip.prototype.DeflateLoop = function () { if (j >= 256) { // In C64: if carry set var len, dist; j -= 256; - if (j == 0) { + if (j === 0) { // EOF break; } @@ -520,7 +520,7 @@ cc.Codec.GZip.prototype.unzipFile = function (name) { var i; this.gunzip(); for (i = 0; i < this.unzipped.length; i++) { - if (this.unzipped[i][1] == name) { + if (this.unzipped[i][1] === name) { return this.unzipped[i][0]; } } @@ -537,25 +537,25 @@ cc.Codec.GZip.prototype.nextFile = function () { tmp[1] = this.readByte(); // if (this.debug) alert("type: "+tmp[0]+" "+tmp[1]); - if (tmp[0] == 0x78 && tmp[1] == 0xda) { //GZIP + if (tmp[0] === 0x78 && tmp[1] === 0xda) { //GZIP // if (this.debug) alert("GEONExT-GZIP"); this.DeflateLoop(); // if (this.debug) alert(this.outputArr.join('')); this.unzipped[this.files] = [this.outputArr.join(''), "geonext.gxt"]; this.files++; } - if (tmp[0] == 0x1f && tmp[1] == 0x8b) { //GZIP + if (tmp[0] === 0x1f && tmp[1] === 0x8b) { //GZIP // if (this.debug) alert("GZIP"); this.skipdir(); // if (this.debug) alert(this.outputArr.join('')); this.unzipped[this.files] = [this.outputArr.join(''), "file"]; this.files++; } - if (tmp[0] == 0x50 && tmp[1] == 0x4b) { //ZIP + if (tmp[0] === 0x50 && tmp[1] === 0x4b) { //ZIP this.modeZIP = true; tmp[2] = this.readByte(); tmp[3] = this.readByte(); - if (tmp[2] == 0x03 && tmp[3] == 0x04) { + if (tmp[2] === 0x03 && tmp[3] === 0x04) { //MODE_ZIP tmp[0] = this.readByte(); tmp[1] = this.readByte(); @@ -602,7 +602,7 @@ cc.Codec.GZip.prototype.nextFile = function () { this.nameBuf = []; while (filelen--) { var c = this.readByte(); - if (c == "/" | c == ":") { + if (c === "/" | c === ":") { i = 0; } else if (i < cc.Codec.GZip.NAMEMAX - 1) { this.nameBuf[i++] = String.fromCharCode(c); @@ -622,7 +622,7 @@ cc.Codec.GZip.prototype.nextFile = function () { // //skipdir // // if (this.debug) alert("skipdir"); // } - if (method == 8) { + if (method === 8) { this.DeflateLoop(); // if (this.debug) alert(this.outputArr.join('')); this.unzipped[this.files] = [this.outputArr.join(''), this.nameBuf.join('')]; @@ -666,7 +666,7 @@ cc.Codec.GZip.prototype.skipdir = function () { if (this.modeZIP) this.nextFile(); tmp[0] = this.readByte(); - if (tmp[0] != 8) { + if (tmp[0] !== 8) { // if (this.debug) alert("Unknown compression method!"); return 0; } @@ -695,7 +695,7 @@ cc.Codec.GZip.prototype.skipdir = function () { i = 0; this.nameBuf = []; while (c = this.readByte()) { - if (c == "7" || c == ":") + if (c === "7" || c === ":") i = 0; if (i < cc.Codec.GZip.NAMEMAX - 1) this.nameBuf[i++] = c; diff --git a/cocos2d/core/CCActionManager.js b/cocos2d/core/CCActionManager.js index aeade2fe6e..ac061e3f5a 100644 --- a/cocos2d/core/CCActionManager.js +++ b/cocos2d/core/CCActionManager.js @@ -73,7 +73,7 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{ _searchElementByTarget:function (arr, target) { for (var k = 0; k < arr.length; k++) { - if (target == arr[k].target) + if (target === arr[k].target) return arr[k]; } return null; @@ -143,7 +143,7 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{ element.currentActionSalvaged = true; element.actions.length = 0; - if (this._currentTarget == element && !forceDelete) { + if (this._currentTarget === element && !forceDelete) { this._currentTargetSalvaged = true; } else { this._deleteHashElement(element); @@ -162,7 +162,7 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{ if (element) { for (var i = 0; i < element.actions.length; i++) { - if (element.actions[i] == action) { + if (element.actions[i] === action) { element.actions.splice(i, 1); break; } @@ -177,7 +177,7 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{ * @param {object} target */ removeActionByTag:function (tag, target) { - if(tag == cc.ACTION_TAG_INVALID) + if(tag === cc.ACTION_TAG_INVALID) cc.log(cc._LogInfos.ActionManager_addAction); cc.assert(target, cc._LogInfos.ActionManager_addAction); @@ -188,7 +188,7 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{ var limit = element.actions.length; for (var i = 0; i < limit; ++i) { var action = element.actions[i]; - if (action && action.getTag() === tag && action.getOriginalTarget() == target) { + if (action && action.getTag() === tag && action.getOriginalTarget() === target) { this._removeActionAtIndex(i, element); break; } @@ -202,7 +202,7 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{ * @return {cc.Action|Null} return the Action with the given tag on success */ getActionByTag:function (tag, target) { - if(tag == cc.ACTION_TAG_INVALID) + if(tag === cc.ACTION_TAG_INVALID) cc.log(cc._LogInfos.ActionManager_getActionByTag); var element = this._hashTargets[target.__instanceId]; @@ -294,7 +294,7 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{ _removeActionAtIndex:function (index, element) { var action = element.actions[index]; - if ((action == element.currentAction) && (!element.currentActionSalvaged)) + if ((action === element.currentAction) && (!element.currentActionSalvaged)) element.currentActionSalvaged = true; element.actions.splice(index, 1); @@ -303,8 +303,8 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{ if (element.actionIndex >= index) element.actionIndex--; - if (element.actions.length == 0) { - if (this._currentTarget == element) { + if (element.actions.length === 0) { + if (this._currentTarget === element) { this._currentTargetSalvaged = true; } else { this._deleteHashElement(element); diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js index 99988bd431..02141cbda5 100644 --- a/cocos2d/core/CCDirector.js +++ b/cocos2d/core/CCDirector.js @@ -365,7 +365,7 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ this._scenesStack.pop(); var c = this._scenesStack.length; - if (c == 0) + if (c === 0) this.end(); else { this._sendCleanupToScene = true; @@ -485,7 +485,7 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ * @param {Number} scaleFactor */ setContentScaleFactor: function (scaleFactor) { - if (scaleFactor != this._contentScaleFactor) { + if (scaleFactor !== this._contentScaleFactor) { this._contentScaleFactor = scaleFactor; this._createStatsLabel(); } @@ -542,7 +542,7 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ cc.renderer.childrenOrderDirty = true; this._nextScene = null; - if ((!runningIsTransition) && (this._runningScene != null)) { + if ((!runningIsTransition) && (this._runningScene !== null)) { this._runningScene.onEnter(); this._runningScene.onEnterTransitionDidFinish(); } @@ -737,7 +737,7 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ var locScenesStack = this._scenesStack; var c = locScenesStack.length; - if (c == 0) { + if (c === 0) { this.end(); return; } @@ -772,7 +772,7 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ * @param {cc.Scheduler} scheduler */ setScheduler: function (scheduler) { - if (this._scheduler != scheduler) { + if (this._scheduler !== scheduler) { this._scheduler = scheduler; } }, @@ -789,7 +789,7 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ * @param {cc.ActionManager} actionManager */ setActionManager: function (actionManager) { - if (this._actionManager != actionManager) { + if (this._actionManager !== actionManager) { this._actionManager = actionManager; } }, diff --git a/cocos2d/core/CCDirectorWebGL.js b/cocos2d/core/CCDirectorWebGL.js index 0747f31794..bdd9d62fb6 100644 --- a/cocos2d/core/CCDirectorWebGL.js +++ b/cocos2d/core/CCDirectorWebGL.js @@ -167,7 +167,7 @@ if (cc._renderType === cc._RENDER_TYPE_WEBGL) { return } - if ((cc.Director._fpsImageLoaded == null) || (cc.Director._fpsImageLoaded == false)) + if ((cc.Director._fpsImageLoaded == null) || (cc.Director._fpsImageLoaded === false)) return; var texture = new cc.Texture2D(); diff --git a/cocos2d/core/CCDrawingPrimitivesCanvas.js b/cocos2d/core/CCDrawingPrimitivesCanvas.js index 93b24ea628..a08dfbe38c 100644 --- a/cocos2d/core/CCDrawingPrimitivesCanvas.js +++ b/cocos2d/core/CCDrawingPrimitivesCanvas.js @@ -279,7 +279,7 @@ cc.DrawingPrimitiveCanvas = cc.Class.extend(/** @lends cc.DrawingPrimitiveCanvas var dt = i / segments; // border - if (dt == 1) { + if (dt === 1) { p = config.length - 1; lt = 1; } else { diff --git a/cocos2d/core/CCDrawingPrimitivesWebGL.js b/cocos2d/core/CCDrawingPrimitivesWebGL.js index f5461a01f5..c3942a9981 100644 --- a/cocos2d/core/CCDrawingPrimitivesWebGL.js +++ b/cocos2d/core/CCDrawingPrimitivesWebGL.js @@ -104,7 +104,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# * @param {Number} numberOfPoints */ drawPoints:function (points, numberOfPoints) { - if (!points || points.length == 0) + if (!points || points.length === 0) return; this.lazy_init(); @@ -395,7 +395,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# var dt = i / segments; // border - if (dt == 1) { + if (dt === 1) { p = config.length - 1; lt = 1; } else { @@ -403,7 +403,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# lt = (dt - deltaT * p) / deltaT; } - var newPos = cc.CardinalSplineAt( + var newPos = cc.cardinalSplineAt( cc.getControlPointAt(config, p - 1), cc.getControlPointAt(config, p), cc.getControlPointAt(config, p + 1), diff --git a/cocos2d/core/CCScheduler.js b/cocos2d/core/CCScheduler.js index 510b21735b..fda045ebb2 100644 --- a/cocos2d/core/CCScheduler.js +++ b/cocos2d/core/CCScheduler.js @@ -126,7 +126,7 @@ cc.Timer = cc.Class.extend(/** @lends cc.Timer# */{ this._delay = delay; this._useDelay = (this._delay > 0); this._repeat = repeat; - this._runForever = (this._repeat == cc.REPEAT_FOREVER); + this._runForever = (this._repeat === cc.REPEAT_FOREVER); }, trigger: function(){ @@ -157,7 +157,7 @@ cc.Timer = cc.Class.extend(/** @lends cc.Timer# */{ * @param {Number} dt delta time */ update:function (dt) { - if (this._elapsed == -1) { + if (this._elapsed === -1) { this._elapsed = 0; this._timesExecuted = 0; } else { @@ -328,7 +328,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ var hashElement = this._hashForUpdates[target.__instanceId]; if (hashElement){ // check if priority has changed - if (hashElement.list.priority != priority){ + if (hashElement.list.priority !== priority){ if (this._updateHashLocked){ cc.log("warning: you CANNOT change update priority in scheduled function"); hashElement.entry.markedForDeletion = false; @@ -347,7 +347,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ // most of the updates are going to be 0, that's way there // is an special list for updates with priority 0 - if (priority == 0){ + if (priority === 0){ this._appendIn(this._updates0List, callback, target, paused); }else if (priority < 0){ this._priorityIn(this._updatesNegList, callback, target, priority, paused); @@ -442,7 +442,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ */ update:function (dt) { this._updateHashLocked = true; - if(this._timeScale != 1) + if(this._timeScale !== 1) dt *= this._timeScale; var i, list, len, entry; @@ -488,7 +488,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ //elt = elt.hh.next; // only delete currentTarget if no actions were scheduled during the cycle (issue #481) - if (this._currentTargetSalvaged && this._currentTarget.timers.length == 0) + if (this._currentTargetSalvaged && this._currentTarget.timers.length === 0) this._removeHashElement(this._currentTarget); } @@ -549,7 +549,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ schedule: function(callback, target, interval, repeat, delay, paused, key){ var isSelector = false; - if(typeof callback != "function"){ + if(typeof callback !== "function"){ var selector = callback; isSelector = true; } @@ -566,7 +566,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ }else{ //selector, target, interval, repeat, delay, paused //selector, target, interval, paused - if(arguments.length == 4){ + if(arguments.length === 4){ paused = repeat; repeat = cc.REPEAT_FOREVER; delay = 0; @@ -585,7 +585,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ this._arrayForTimers.push(element); this._hashForTimers[target.__instanceId] = element; }else{ - cc.assert(element.paused == paused, ""); + cc.assert(element.paused === paused, ""); } var timer, i; @@ -594,7 +594,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ } else if(isSelector === false) { for (i = 0; i < element.timers.length; i++) { timer = element.timers[i]; - if (callback == timer._callback) { + if (callback === timer._callback) { cc.log(cc._LogInfos.Scheduler_scheduleCallbackForTarget, timer.getInterval().toFixed(4), interval.toFixed(4)); timer._interval = interval; return; @@ -603,7 +603,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ }else{ for (i = 0; i < element.timers.length; ++i){ timer =element.timers[i]; - if (timer && selector == timer.getSelector()){ + if (timer && selector === timer.getSelector()){ cc.log("CCScheduler#scheduleSelector. Selector already scheduled. Updating interval from: %.4f to %.4f", timer.getInterval(), interval); timer.setInterval(interval); return; @@ -634,11 +634,11 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ switch (typeof key){ case "number": case "string": - return key == timer.getKey(); + return key === timer.getKey(); case "function": - return key == timer._callback; + return key === timer._callback; default: - return key == timer.getSelector(); + return key === timer.getSelector(); } }, unschedule: function(key, target){ @@ -656,7 +656,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ for(var i = 0, li = timers.length; i < li; i++){ var timer = timers[i]; if (this._getUnscheduleMark(key, timer)) { - if ((timer == element.currentTimer) && (!element.currentTimerSalvaged)) { + if ((timer === element.currentTimer) && (!element.currentTimerSalvaged)) { element.currentTimerSalvaged = true; } timers.splice(i, 1); @@ -665,8 +665,8 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ element.timerIndex--; } - if (timers.length == 0) { - if (self._currentTarget == element) { + if (timers.length === 0) { + if (self._currentTarget === element) { self._currentTargetSalvaged = true; } else { self._removeHashElement(element); @@ -710,7 +710,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ // ccArrayRemoveAllObjects(element.timers); element.timers.length = 0; - if (this._currentTarget == element){ + if (this._currentTarget === element){ this._currentTargetSalvaged = true; }else{ this._removeHashElement(element); @@ -785,7 +785,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ for (var i = 0; i < timers.length; ++i){ var timer = timers[i]; - if (key == timer.getKey()){ + if (key === timer.getKey()){ return true; } } diff --git a/cocos2d/core/base-nodes/CCAtlasNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCAtlasNodeCanvasRenderCmd.js index e236ae82fb..64e557c966 100644 --- a/cocos2d/core/base-nodes/CCAtlasNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCAtlasNodeCanvasRenderCmd.js @@ -58,7 +58,7 @@ proto.setColor = function(color3){ var node = this._node; var locRealColor = node._realColor; - if ((locRealColor.r == color3.r) && (locRealColor.g == color3.g) && (locRealColor.b == color3.b)) + if ((locRealColor.r === color3.r) && (locRealColor.g === color3.g) && (locRealColor.b === color3.b)) return; this._colorUnmodified = color3; this._changeTextureColor(); diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index 0094a86464..b2888ae0fd 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -446,7 +446,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @param {Number} globalZOrder */ setGlobalZOrder: function (globalZOrder) { - if (this._globalZOrder != globalZOrder) { + if (this._globalZOrder !== globalZOrder) { this._globalZOrder = globalZOrder; cc.eventManager._setDirtyForNode(this); } @@ -966,7 +966,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @param {Boolean} newValue true if anchor point will be ignored when you position this node */ ignoreAnchorPointForPosition: function (newValue) { - if (newValue != this._ignoreAnchorPointForPosition) { + if (newValue !== this._ignoreAnchorPointForPosition) { this._ignoreAnchorPointForPosition = newValue; this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty); } @@ -1076,7 +1076,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @param {object} newValue A user cocos2d object */ setUserObject: function (newValue) { - if (this.userObject != newValue) + if (this.userObject !== newValue) this.userObject = newValue; }, @@ -1125,7 +1125,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @param {cc.ActionManager} actionManager A CCActionManager object that is used by all actions. */ setActionManager: function (actionManager) { - if (this._actionManager != actionManager) { + if (this._actionManager !== actionManager) { this.stopAllActions(); this._actionManager = actionManager; } @@ -1154,7 +1154,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @param scheduler A cc.Scheduler object that is used to schedule all "update" and timers. */ setScheduler: function (scheduler) { - if (this._scheduler != scheduler) { + if (this._scheduler !== scheduler) { this.unscheduleAllCallbacks(); this._scheduler = scheduler; } @@ -1206,10 +1206,10 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ */ getChildByTag: function (aTag) { var __children = this._children; - if (__children != null) { + if (__children !== null) { for (var i = 0; i < __children.length; i++) { var node = __children[i]; - if (node && node.tag == aTag) + if (node && node.tag === aTag) return node; } } @@ -1230,7 +1230,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ var locChildren = this._children; for(var i = 0, len = locChildren.length; i < len; i++){ - if(locChildren[i]._name == name) + if(locChildren[i]._name === name) return locChildren[i]; } return null; @@ -1378,7 +1378,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ removeAllChildren: function (cleanup) { // not using detachChild improves speed here var __children = this._children; - if (__children != null) { + if (__children !== null) { if (cleanup == null) cleanup = true; for (var i = 0; i < __children.length; i++) { @@ -1494,7 +1494,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ // Internal use only, do not call it by yourself, transformAncestors: function () { - if (this._parent != null) { + if (this._parent !== null) { this._parent.transformAncestors(); this._parent.transform(); } @@ -1678,13 +1678,13 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ var len = arguments.length; if(typeof callback === "function"){ //callback, interval, repeat, delay, key - if(len == 1){ + if(len === 1){ //callback interval = 0; repeat = cc.REPEAT_FOREVER; delay = 0; key = this.__instanceId; - }else if(len == 2){ + }else if(len === 2){ if(typeof interval === "number"){ //callback, interval repeat = cc.REPEAT_FOREVER; @@ -1709,11 +1709,11 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ //selector //selector, interval //selector, interval, repeat, delay - if(len == 1){ + if(len === 1){ interval = 0; repeat = cc.REPEAT_FOREVER; delay = 0; - }else if(len == 2){ + }else if(len === 2){ repeat = cc.REPEAT_FOREVER; delay = 0; } @@ -1740,7 +1740,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ scheduleOnce: function (callback, delay, key) { //selector, delay //callback, delay, key - if(key == undefined) + if(key === undefined) key = this.__instanceId; this.schedule(callback, 0, 0, delay, key); }, @@ -1895,7 +1895,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ getNodeToWorldTransform: function () { //TODO renderCmd has a WorldTransform var t = this.getNodeToParentTransform(); - for (var p = this._parent; p != null; p = p.parent) + for (var p = this._parent; p !== null; p = p.parent) t = cc.affineTransformConcat(t, p.getNodeToParentTransform()); return t; }, diff --git a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js index a61ba7ee65..24713c459c 100644 --- a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js @@ -456,12 +456,12 @@ cc.Node.RenderCmd.prototype = { if (this._cacheDirty === false) { this._cacheDirty = true; var cachedP = this._cachedParent; - cachedP && cachedP != this && cachedP._setNodeDirtyForCache && cachedP._setNodeDirtyForCache(); + cachedP && cachedP !== this && cachedP._setNodeDirtyForCache && cachedP._setNodeDirtyForCache(); } }; proto._setCachedParent = function (cachedParent) { - if (this._cachedParent == cachedParent) + if (this._cachedParent === cachedParent) return; this._cachedParent = cachedParent; @@ -493,11 +493,11 @@ cc.Node.RenderCmd.prototype = { if (!blendFunc) return "source-over"; else { - if (( blendFunc.src == cc.SRC_ALPHA && blendFunc.dst == cc.ONE) || (blendFunc.src == cc.ONE && blendFunc.dst == cc.ONE)) + if (( blendFunc.src === cc.SRC_ALPHA && blendFunc.dst === cc.ONE) || (blendFunc.src === cc.ONE && blendFunc.dst === cc.ONE)) return "lighter"; - else if (blendFunc.src == cc.ZERO && blendFunc.dst == cc.SRC_ALPHA) + else if (blendFunc.src === cc.ZERO && blendFunc.dst === cc.SRC_ALPHA) return "destination-in"; - else if (blendFunc.src == cc.ZERO && blendFunc.dst == cc.ONE_MINUS_SRC_ALPHA) + else if (blendFunc.src === cc.ZERO && blendFunc.dst === cc.ONE_MINUS_SRC_ALPHA) return "destination-out"; else return "source-over"; diff --git a/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js b/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js index 2c70b47fd2..ce62ce39e3 100644 --- a/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js @@ -214,7 +214,7 @@ cc.kmMat4Multiply(stackMatrix, parentMatrix, t4x4); // XXX: Expensive calls. Camera should be integrated into the cached affine matrix - if (node._camera != null && !(node.grid != null && node.grid.isActive())) { + if (node._camera !== null && !(node.grid !== null && node.grid.isActive())) { var apx = this._anchorPointInPoints.x, apy = this._anchorPointInPoints.y; var translate = (apx !== 0.0 || apy !== 0.0); if (translate){ diff --git a/cocos2d/core/cocoa/CCGeometry.js b/cocos2d/core/cocoa/CCGeometry.js index 3b047b5742..0eeffd5ad2 100644 --- a/cocos2d/core/cocoa/CCGeometry.js +++ b/cocos2d/core/cocoa/CCGeometry.js @@ -55,9 +55,9 @@ cc.p = function (x, y) { // but this one will instead flood the heap with newly allocated hash maps // giving little room for optimization by the JIT, // note: we have tested this item on Chrome and firefox, it is faster than cc.p(x, y) - if (x == undefined) + if (x === undefined) return {x: 0, y: 0}; - if (y == undefined) + if (y === undefined) return {x: x.x, y: x.y}; return {x: x, y: y}; }; @@ -120,7 +120,7 @@ cc.size = function (w, h) { * @return {Boolean} */ cc.sizeEqualToSize = function (size1, size2) { - return (size1 && size2 && (size1.width == size2.width) && (size1.height == size2.height)); + return (size1 && size2 && (size1.width === size2.width) && (size1.height === size2.height)); }; diff --git a/cocos2d/core/event-manager/CCEventExtension.js b/cocos2d/core/event-manager/CCEventExtension.js index afa4c81550..a14968f0f7 100644 --- a/cocos2d/core/event-manager/CCEventExtension.js +++ b/cocos2d/core/event-manager/CCEventExtension.js @@ -111,7 +111,7 @@ cc._EventListenerKeyboard = cc.EventListener.extend({ }, checkAvailable: function () { - if (this.onKeyPressed == null && this.onKeyReleased == null) { + if (this.onKeyPressed === null && this.onKeyReleased === null) { cc.log(cc._LogInfos._EventListenerKeyboard_checkAvailable); return false; } diff --git a/cocos2d/core/event-manager/CCEventListener.js b/cocos2d/core/event-manager/CCEventListener.js index 642d7d9e47..3c9dbab79d 100644 --- a/cocos2d/core/event-manager/CCEventListener.js +++ b/cocos2d/core/event-manager/CCEventListener.js @@ -162,7 +162,7 @@ cc.EventListener = cc.Class.extend(/** @lends cc.EventListener# */{ * @returns {boolean} */ checkAvailable: function () { - return this._onEvent != null; + return this._onEvent !== null; }, /** @@ -288,7 +288,7 @@ cc._EventListenerCustom = cc.EventListener.extend({ this._onCustomEvent = callback; var selfPointer = this; var listener = function (event) { - if (selfPointer._onCustomEvent != null) + if (selfPointer._onCustomEvent !== null) selfPointer._onCustomEvent(event); }; @@ -296,7 +296,7 @@ cc._EventListenerCustom = cc.EventListener.extend({ }, checkAvailable: function () { - return (cc.EventListener.prototype.checkAvailable.call(this) && this._onCustomEvent != null); + return (cc.EventListener.prototype.checkAvailable.call(this) && this._onCustomEvent !== null); }, clone: function () { @@ -428,8 +428,8 @@ cc._EventListenerTouchAllAtOnce = cc.EventListener.extend({ }, checkAvailable: function(){ - if (this.onTouchesBegan == null && this.onTouchesMoved == null - && this.onTouchesEnded == null && this.onTouchesCancelled == null) { + if (this.onTouchesBegan === null && this.onTouchesMoved === null + && this.onTouchesEnded === null && this.onTouchesCancelled === null) { cc.log(cc._LogInfos._EventListenerTouchAllAtOnce_checkAvailable); return false; } diff --git a/cocos2d/core/event-manager/CCEventManager.js b/cocos2d/core/event-manager/CCEventManager.js index d45126255c..84cabd26a4 100644 --- a/cocos2d/core/event-manager/CCEventManager.js +++ b/cocos2d/core/event-manager/CCEventManager.js @@ -45,7 +45,7 @@ cc._EventListenerVector = cc.Class.extend({ }, push: function (listener) { - if (listener._getFixedPriority() == 0) + if (listener._getFixedPriority() === 0) this._sceneGraphListeners.push(listener); else this._fixedListeners.push(listener); @@ -185,11 +185,11 @@ cc.eventManager = /** @lends cc.eventManager# */{ } listeners.push(listener); - if (listener._getFixedPriority() == 0) { + if (listener._getFixedPriority() === 0) { this._setDirty(listenerID, this.DIRTY_SCENE_GRAPH_PRIORITY); var node = listener._getSceneGraphPriority(); - if (node == null) + if (node === null) cc.log(cc._LogInfos.eventManager__forceAddEventListener); this._associateNodeAndEventListener(node, listener); @@ -204,7 +204,7 @@ cc.eventManager = /** @lends cc.eventManager# */{ }, _updateDirtyFlagForSceneGraph: function () { - if (this._dirtyNodes.length == 0) + if (this._dirtyNodes.length === 0) return; var locDirtyNodes = this._dirtyNodes, selListeners, selListener, locNodeListenersMap = this._nodeListenersMap; @@ -262,7 +262,7 @@ cc.eventManager = /** @lends cc.eventManager# */{ var locToAddedListeners = this._toAddedListeners, listener; for (i = 0; i < locToAddedListeners.length;) { listener = locToAddedListeners[i]; - if (listener && listener._getListenerID() == listenerID) + if (listener && listener._getListenerID() === listenerID) cc.arrayRemoveObject(locToAddedListeners, listener); else ++i; @@ -274,7 +274,7 @@ cc.eventManager = /** @lends cc.eventManager# */{ if (locFlagMap[listenerID]) dirtyFlag = locFlagMap[listenerID]; - if (dirtyFlag != this.DIRTY_NONE) { + if (dirtyFlag !== this.DIRTY_NONE) { // Clear the dirty flag first, if `rootNode` is null, then set its dirty flag of scene graph priority locFlagMap[listenerID] = this.DIRTY_NONE; @@ -385,13 +385,13 @@ cc.eventManager = /** @lends cc.eventManager# */{ if(locInDispatch > 1) return; - if (event.getType() == cc.Event.TOUCH) { + if (event.getType() === cc.Event.TOUCH) { this._onUpdateListeners(cc._EventListenerTouchOneByOne.LISTENER_ID); this._onUpdateListeners(cc._EventListenerTouchAllAtOnce.LISTENER_ID); } else this._onUpdateListeners(cc.__getListenerID(event)); - cc.assert(locInDispatch == 1, cc._LogInfos.EventManager__updateListeners_2); + cc.assert(locInDispatch === 1, cc._LogInfos.EventManager__updateListeners_2); var locListenersMap = this._listenersMap, locPriorityDirtyFlagMap = this._priorityDirtyFlagMap; for (var selKey in locListenersMap) { if (locListenersMap[selKey].empty()) { @@ -418,14 +418,14 @@ cc.eventManager = /** @lends cc.eventManager# */{ var isClaimed = false, removedIdx; var getCode = event.getEventCode(), eventCode = cc.EventTouch.EventCode; - if (getCode == eventCode.BEGAN) { + if (getCode === eventCode.BEGAN) { if (listener.onTouchBegan) { isClaimed = listener.onTouchBegan(selTouch, event); if (isClaimed && listener._registered) listener._claimedTouches.push(selTouch); } } else if (listener._claimedTouches.length > 0 - && ((removedIdx = listener._claimedTouches.indexOf(selTouch)) != -1)) { + && ((removedIdx = listener._claimedTouches.indexOf(selTouch)) !== -1)) { isClaimed = true; if(getCode === eventCode.MOVED && listener.onTouchMoved){ listener.onTouchMoved(selTouch, event); @@ -464,7 +464,7 @@ cc.eventManager = /** @lends cc.eventManager# */{ var allAtOnceListeners = this._getListeners(cc._EventListenerTouchAllAtOnce.LISTENER_ID); // If there aren't any touch listeners, return directly. - if (null == oneByOneListeners && null == allAtOnceListeners) + if (null === oneByOneListeners && null === allAtOnceListeners) return; var originalTouches = event.getTouches(), mutableTouches = cc.copyArray(originalTouches); @@ -500,13 +500,13 @@ cc.eventManager = /** @lends cc.eventManager# */{ var eventCode = cc.EventTouch.EventCode, event = callbackParams.event, touches = callbackParams.touches, getCode = event.getEventCode(); event._setCurrentTarget(listener._node); - if(getCode == eventCode.BEGAN && listener.onTouchesBegan) + if(getCode === eventCode.BEGAN && listener.onTouchesBegan) listener.onTouchesBegan(touches, event); - else if(getCode == eventCode.MOVED && listener.onTouchesMoved) + else if(getCode === eventCode.MOVED && listener.onTouchesMoved) listener.onTouchesMoved(touches, event); - else if(getCode == eventCode.ENDED && listener.onTouchesEnded) + else if(getCode === eventCode.ENDED && listener.onTouchesEnded) listener.onTouchesEnded(touches, event); - else if(getCode == eventCode.CANCELLED && listener.onTouchesCancelled) + else if(getCode === eventCode.CANCELLED && listener.onTouchesCancelled) listener.onTouchesCancelled(touches, event); // If the event was stopped, return directly. @@ -667,7 +667,7 @@ cc.eventManager = /** @lends cc.eventManager# */{ return; if (cc.isNumber(nodeOrPriority)) { - if (nodeOrPriority == 0) { + if (nodeOrPriority === 0) { cc.log(cc._LogInfos.eventManager_addListener); return; } @@ -735,7 +735,7 @@ cc.eventManager = /** @lends cc.eventManager# */{ var locToAddedListeners = this._toAddedListeners; for (var i = 0, len = locToAddedListeners.length; i < len; i++) { var selListener = locToAddedListeners[i]; - if (selListener == listener) { + if (selListener === listener) { cc.arrayRemoveObject(locToAddedListeners, selListener); selListener._setRegistered(false); break; @@ -750,14 +750,14 @@ cc.eventManager = /** @lends cc.eventManager# */{ for (var i = 0, len = listeners.length; i < len; i++) { var selListener = listeners[i]; - if (selListener == listener) { + if (selListener === listener) { selListener._setRegistered(false); if (selListener._getSceneGraphPriority() != null){ this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener); selListener._setSceneGraphPriority(null); // NULL out the node pointer so we don't have any dangling pointers to destroyed nodes. } - if (this._inDispatch == 0) + if (this._inDispatch === 0) cc.arrayRemoveObject(listeners, selListener); return true; } @@ -793,7 +793,7 @@ cc.eventManager = /** @lends cc.eventManager# */{ var locToAddedListeners = _t._toAddedListeners; for (i = 0; i < locToAddedListeners.length; ) { var listener = locToAddedListeners[i]; - if (listener._getSceneGraphPriority() == listenerType) { + if (listener._getSceneGraphPriority() === listenerType) { listener._setSceneGraphPriority(null); // Ensure no dangling ptr to the target node. listener._setRegistered(false); locToAddedListeners.splice(i, 1); @@ -807,15 +807,15 @@ cc.eventManager = /** @lends cc.eventManager# */{ _t.removeListeners(locChildren[i], true); } } else { - if (listenerType == cc.EventListener.TOUCH_ONE_BY_ONE) + if (listenerType === cc.EventListener.TOUCH_ONE_BY_ONE) _t._removeListenersForListenerID(cc._EventListenerTouchOneByOne.LISTENER_ID); - else if (listenerType == cc.EventListener.TOUCH_ALL_AT_ONCE) + else if (listenerType === cc.EventListener.TOUCH_ALL_AT_ONCE) _t._removeListenersForListenerID(cc._EventListenerTouchAllAtOnce.LISTENER_ID); - else if (listenerType == cc.EventListener.MOUSE) + else if (listenerType === cc.EventListener.MOUSE) _t._removeListenersForListenerID(cc._EventListenerMouse.LISTENER_ID); - else if (listenerType == cc.EventListener.ACCELERATION) + else if (listenerType === cc.EventListener.ACCELERATION) _t._removeListenersForListenerID(cc._EventListenerAcceleration.LISTENER_ID); - else if (listenerType == cc.EventListener.KEYBOARD) + else if (listenerType === cc.EventListener.KEYBOARD) _t._removeListenersForListenerID(cc._EventListenerKeyboard.LISTENER_ID); else cc.log(cc._LogInfos.eventManager_removeListeners); @@ -856,7 +856,7 @@ cc.eventManager = /** @lends cc.eventManager# */{ var fixedPriorityListeners = selListeners.getFixedPriorityListeners(); if (fixedPriorityListeners) { var found = fixedPriorityListeners.indexOf(listener); - if (found != -1) { + if (found !== -1) { if(listener._getSceneGraphPriority() != null) cc.log(cc._LogInfos.eventManager_setPriority); if (listener._getFixedPriority() !== fixedPriority) { @@ -897,7 +897,7 @@ cc.eventManager = /** @lends cc.eventManager# */{ this._inDispatch++; if(!event || !event.getType) throw "event is undefined"; - if (event.getType() == cc.Event.TOUCH) { + if (event.getType() === cc.Event.TOUCH) { this._dispatchTouchEvent(event); this._inDispatch--; return; @@ -972,7 +972,7 @@ cc.EventHelper.prototype = { if ( listeners[ type ] !== undefined ) { for(var i = 0, len = listeners.length; i < len ; i++){ var selListener = listeners[i]; - if(selListener.callback == listener && selListener.eventTarget == target) + if(selListener.callback === listener && selListener.eventTarget === target) return true; } } @@ -989,7 +989,7 @@ cc.EventHelper.prototype = { if ( listenerArray !== undefined ) { for(var i = 0; i < listenerArray.length ; ){ var selListener = listenerArray[i]; - if(selListener.eventTarget == target) + if(selListener.eventTarget === target) listenerArray.splice( i, 1 ); else i++ diff --git a/cocos2d/core/labelttf/CCLabelTTF.js b/cocos2d/core/labelttf/CCLabelTTF.js index 106e92bc19..fb4855e6a5 100644 --- a/cocos2d/core/labelttf/CCLabelTTF.js +++ b/cocos2d/core/labelttf/CCLabelTTF.js @@ -300,17 +300,17 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ this._shadowEnabled = true; var locShadowOffset = this._shadowOffset; - if (locShadowOffset && (locShadowOffset.x != shadowOffsetX) || (locShadowOffset._y != shadowOffsetY)) { + if (locShadowOffset && (locShadowOffset.x !== shadowOffsetX) || (locShadowOffset._y !== shadowOffsetY)) { locShadowOffset.x = shadowOffsetX; locShadowOffset.y = shadowOffsetY; } - if (this._shadowOpacity != shadowOpacity) { + if (this._shadowOpacity !== shadowOpacity) { this._shadowOpacity = shadowOpacity; } this._renderCmd._setColorsString(); - if (this._shadowBlur != shadowBlur) + if (this._shadowBlur !== shadowBlur) this._shadowBlur = shadowBlur; this._setUpdateTextureDirty(); }, @@ -339,7 +339,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ if (false === this._shadowEnabled) this._shadowEnabled = true; - if (this._shadowOffset.x != x) { + if (this._shadowOffset.x !== x) { this._shadowOffset.x = x; this._setUpdateTextureDirty(); } @@ -352,7 +352,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ if (false === this._shadowEnabled) this._shadowEnabled = true; - if (this._shadowOffset._y != y) { + if (this._shadowOffset._y !== y) { this._shadowOffset._y = y; this._setUpdateTextureDirty(); } @@ -365,7 +365,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ if (false === this._shadowEnabled) this._shadowEnabled = true; - if (this._shadowOffset.x != offset.x || this._shadowOffset.y != offset.y) { + if (this._shadowOffset.x !== offset.x || this._shadowOffset.y !== offset.y) { this._shadowOffset.x = offset.x; this._shadowOffset.y = offset.y; this._setUpdateTextureDirty(); @@ -379,7 +379,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ if (false === this._shadowEnabled) this._shadowEnabled = true; - if (this._shadowOpacity != shadowOpacity) { + if (this._shadowOpacity !== shadowOpacity) { this._shadowOpacity = shadowOpacity; this._renderCmd._setColorsString(); this._setUpdateTextureDirty(); @@ -393,7 +393,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ if (false === this._shadowEnabled) this._shadowEnabled = true; - if (this._shadowBlur != shadowBlur) { + if (this._shadowBlur !== shadowBlur) { this._shadowBlur = shadowBlur; this._setUpdateTextureDirty(); } @@ -477,7 +477,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ */ setFontFillColor: function (fillColor) { var locTextFillColor = this._textFillColor; - if (locTextFillColor.r != fillColor.r || locTextFillColor.g != fillColor.g || locTextFillColor.b != fillColor.b) { + if (locTextFillColor.r !== fillColor.r || locTextFillColor.g !== fillColor.g || locTextFillColor.b !== fillColor.b) { locTextFillColor.r = fillColor.r; locTextFillColor.g = fillColor.g; locTextFillColor.b = fillColor.b; @@ -584,7 +584,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ */ setString: function (text) { text = String(text); - if (this._originalText != text) { + if (this._originalText !== text) { this._originalText = text + ""; this._updateString(); @@ -617,7 +617,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ * @param {cc.VERTICAL_TEXT_ALIGNMENT_TOP|cc.VERTICAL_TEXT_ALIGNMENT_CENTER|cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM} verticalAlignment */ setVerticalAlignment: function (verticalAlignment) { - if (verticalAlignment != this._vAlignment) { + if (verticalAlignment !== this._vAlignment) { this._vAlignment = verticalAlignment; // Force update @@ -638,7 +638,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ } else width = dim; - if (width != this._dimensions.width || height != this._dimensions.height) { + if (width !== this._dimensions.width || height !== this._dimensions.height) { this._dimensions.width = width; this._dimensions.height = height; this._updateString(); @@ -651,7 +651,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ return this._dimensions.width; }, _setBoundingWidth: function (width) { - if (width != this._dimensions.width) { + if (width !== this._dimensions.width) { this._dimensions.width = width; this._updateString(); // Force update @@ -663,7 +663,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ return this._dimensions.height; }, _setBoundingHeight: function (height) { - if (height != this._dimensions.height) { + if (height !== this._dimensions.height) { this._dimensions.height = height; this._updateString(); // Force update @@ -689,7 +689,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ * @param {String} fontName */ setFontName: function (fontName) { - if (this._fontName && this._fontName != fontName) { + if (this._fontName && this._fontName !== fontName) { this._fontName = fontName; this._renderCmd._setFontStyle(this._fontName, this._fontSize, this._fontStyle, this._fontWeight); // Force update @@ -747,7 +747,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ //For web only _setFontStyle: function(fontStyle){ - if (this._fontStyle != fontStyle) { + if (this._fontStyle !== fontStyle) { this._fontStyle = fontStyle; this._renderCmd._setFontStyle(this._fontName, this._fontSize, this._fontStyle, this._fontWeight); this._setUpdateTextureDirty(); @@ -759,7 +759,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ }, _setFontWeight: function(fontWeight){ - if (this._fontWeight != fontWeight) { + if (this._fontWeight !== fontWeight) { this._fontWeight = fontWeight; this._renderCmd._setFontStyle(this._fontName, this._fontSize, this._fontStyle, this._fontWeight); this._setUpdateTextureDirty(); diff --git a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js index 276ef15313..d18507c02d 100644 --- a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js +++ b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js @@ -110,7 +110,7 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; locContext.font = this._fontStyleStr; this._updateTTF(); var width = locContentSize.width, height = locContentSize.height; - var flag = locLabelCanvas.width == width && locLabelCanvas.height == height; + var flag = locLabelCanvas.width === width && locLabelCanvas.height === height; locLabelCanvas.width = width; locLabelCanvas.height = height; if (flag) locContext.clearRect(0, 0, width, height); @@ -183,7 +183,7 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; locSize = cc.size(Math.ceil(locDimensionsWidth + locStrokeShadowOffsetX), Math.ceil(node._dimensions.height + locStrokeShadowOffsetY)); } } - if(node._getFontStyle() != "normal"){ //add width for 'italic' and 'oblique' + if(node._getFontStyle() !== "normal"){ //add width for 'italic' and 'oblique' locSize.width = Math.ceil(locSize.width + node._fontSize * 0.3); } node.setContentSize(locSize); @@ -204,10 +204,10 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; var locContentSizeHeight = node._contentSize.height - locStrokeShadowOffsetY, locVAlignment = node._vAlignment, locHAlignment = node._hAlignment, locStrokeSize = node._strokeSize; - context.setTransform(1, 0, 0, 1, 0 + locStrokeShadowOffsetX * 0.5, locContentSizeHeight + locStrokeShadowOffsetY * 0.5); + context.setTransform(1, 0, 0, 1, locStrokeShadowOffsetX * 0.5, locContentSizeHeight + locStrokeShadowOffsetY * 0.5); //this is fillText for canvas - if (context.font != this._fontStyleStr) + if (context.font !== this._fontStyleStr) context.font = this._fontStyleStr; context.fillStyle = this._fillColorStr; diff --git a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js index cfa224148d..2fb954e115 100644 --- a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js +++ b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js @@ -129,7 +129,7 @@ }; proto._bakeForAddChild = function(child){ - if(child._parent == this._node && this._isBaked) + if(child._parent === this._node && this._isBaked) child._renderCmd._setCachedParent(this); }; diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index cf187cad09..2aaf3e6621 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -49,7 +49,7 @@ var ClassManager = { //now we have the content of the function, replace this._super //find this._super - while(str.indexOf('this._super')!= -1) + while(str.indexOf('this._super') !== -1) { var sp = str.indexOf('this._super'); //find the first '(' from this._super) @@ -186,7 +186,7 @@ ClassManager.compileSuper.ClassManager = ClassManager; if (this.__getters__ && this.__getters__[name]) { propertyName = this.__getters__[name]; for (var i in this.__setters__) { - if (this.__setters__[i] == propertyName) { + if (this.__setters__[i] === propertyName) { setter = i; break; } @@ -196,7 +196,7 @@ ClassManager.compileSuper.ClassManager = ClassManager; if (this.__setters__ && this.__setters__[name]) { propertyName = this.__setters__[name]; for (var i in this.__getters__) { - if (this.__getters__[i] == propertyName) { + if (this.__getters__[i] === propertyName) { getter = i; break; } @@ -316,7 +316,7 @@ cc.clone = function (obj) { for (var key in obj) { var copy = obj[key]; // Beware that typeof null == "object" ! - if (((typeof copy) == "object") && copy && + if (((typeof copy) === "object") && copy && !(copy instanceof cc.Node) && !(copy instanceof HTMLElement)) { newObj[key] = cc.clone(copy); } else { diff --git a/cocos2d/core/platform/CCCommon.js b/cocos2d/core/platform/CCCommon.js index 9edef5f478..2db723b4f9 100644 --- a/cocos2d/core/platform/CCCommon.js +++ b/cocos2d/core/platform/CCCommon.js @@ -227,21 +227,21 @@ cc.FMT_UNKNOWN = 5; */ cc.getImageFormatByData = function (imgData) { // if it is a png file buffer. - if (imgData.length > 8 && imgData[0] == 0x89 - && imgData[1] == 0x50 - && imgData[2] == 0x4E - && imgData[3] == 0x47 - && imgData[4] == 0x0D - && imgData[5] == 0x0A - && imgData[6] == 0x1A - && imgData[7] == 0x0A) { + if (imgData.length > 8 && imgData[0] === 0x89 + && imgData[1] === 0x50 + && imgData[2] === 0x4E + && imgData[3] === 0x47 + && imgData[4] === 0x0D + && imgData[5] === 0x0A + && imgData[6] === 0x1A + && imgData[7] === 0x0A) { return cc.FMT_PNG; } // if it is a tiff file buffer. - if (imgData.length > 2 && ((imgData[0] == 0x49 && imgData[1] == 0x49) - || (imgData[0] == 0x4d && imgData[1] == 0x4d) - || (imgData[0] == 0xff && imgData[1] == 0xd8))) { + if (imgData.length > 2 && ((imgData[0] === 0x49 && imgData[1] === 0x49) + || (imgData[0] === 0x4d && imgData[1] === 0x4d) + || (imgData[0] === 0xff && imgData[1] === 0xd8))) { return cc.FMT_TIFF; } return cc.FMT_UNKNOWN; diff --git a/cocos2d/core/platform/CCEGLView.js b/cocos2d/core/platform/CCEGLView.js index 75826042ff..7dce4366ac 100644 --- a/cocos2d/core/platform/CCEGLView.js +++ b/cocos2d/core/platform/CCEGLView.js @@ -183,7 +183,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ _t._viewName = "Cocos2dHTML5"; var sys = cc.sys; - _t.enableRetina(sys.os == sys.OS_IOS || sys.os == sys.OS_OSX); + _t.enableRetina(sys.os === sys.OS_IOS || sys.os === sys.OS_OSX); cc.visibleRect && cc.visibleRect.init(_t._visibleRect); // Setup system default resolution policies @@ -210,7 +210,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ // Check frame size changed or not var prevFrameW = view._frameSize.width, prevFrameH = view._frameSize.height; view._initFrameSize(); - if (view._frameSize.width == prevFrameW && view._frameSize.height == prevFrameH) + if (view._frameSize.width === prevFrameW && view._frameSize.height === prevFrameH) return; // Frame size changed, do resize works @@ -418,7 +418,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ * @return {Boolean} */ isOpenGLReady: function () { - return (this._hDC != null && this._hRC != null); + return (this._hDC !== null && this._hRC !== null); }, /* @@ -591,7 +591,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ var result = policy.apply(this, this._designResolutionSize); - if(result.scale && result.scale.length == 2){ + if(result.scale && result.scale.length === 2){ this._scaleX = result.scale[0]; this._scaleY = result.scale[1]; } @@ -621,7 +621,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ cc.winSize.width = director._winSizeInPoints.width; cc.winSize.height = director._winSizeInPoints.height; - if (cc._renderType == cc._RENDER_TYPE_WEBGL) { + if (cc._renderType === cc._RENDER_TYPE_WEBGL) { // reset director's member variables to fit visible rect director._createStatsLabel(); director.setGLDefaultValues(); @@ -821,7 +821,7 @@ cc.ContainerStrategy = cc.Class.extend(/** @lends cc.ContainerStrategy# */{ _setupContainer: function (view, w, h) { var frame = view._frame; - if (cc.view._autoFullScreen && cc.sys.isMobile && frame == document.documentElement) { + if (cc.view._autoFullScreen && cc.sys.isMobile && frame === document.documentElement) { // Automatically full screen when user touches on mobile version cc.screen.autoFullScreen(frame); } @@ -897,7 +897,7 @@ cc.ContentStrategy = cc.Class.extend(/** @lends cc.ContentStrategy# */{ contentW, contentH); // Translate the content - if (cc._renderType == cc._RENDER_TYPE_CANVAS){ + if (cc._renderType === cc._RENDER_TYPE_CANVAS){ //TODO: modify something for setTransform //cc._renderContext.translate(viewport.x, viewport.y + contentH); } diff --git a/cocos2d/core/platform/CCInputExtension.js b/cocos2d/core/platform/CCInputExtension.js index 3c13edfcd0..470864db02 100644 --- a/cocos2d/core/platform/CCInputExtension.js +++ b/cocos2d/core/platform/CCInputExtension.js @@ -76,12 +76,12 @@ _p._registerAccelerometerEvent = function(){ _t._accelDeviceEvent = w.DeviceMotionEvent || w.DeviceOrientationEvent; //TODO fix DeviceMotionEvent bug on QQ Browser version 4.1 and below. - if (cc.sys.browserType == cc.sys.BROWSER_TYPE_MOBILE_QQ) + if (cc.sys.browserType === cc.sys.BROWSER_TYPE_MOBILE_QQ) _t._accelDeviceEvent = window.DeviceOrientationEvent; - var _deviceEventType = (_t._accelDeviceEvent == w.DeviceMotionEvent) ? "devicemotion" : "deviceorientation"; + var _deviceEventType = (_t._accelDeviceEvent === w.DeviceMotionEvent) ? "devicemotion" : "deviceorientation"; var ua = navigator.userAgent; - if (/Android/.test(ua) || (/Adr/.test(ua) && cc.sys.browserType == cc.BROWSER_TYPE_UC)) { + if (/Android/.test(ua) || (/Adr/.test(ua) && cc.sys.browserType === cc.BROWSER_TYPE_UC)) { _t._minus = -1; } @@ -97,7 +97,7 @@ _p.didAccelerate = function (eventData) { var x, y, z; - if (_t._accelDeviceEvent == window.DeviceMotionEvent) { + if (_t._accelDeviceEvent === window.DeviceMotionEvent) { var eventAcceleration = eventData["accelerationIncludingGravity"]; x = _t._accelMinus * eventAcceleration.x * 0.1; y = _t._accelMinus * eventAcceleration.y * 0.1; diff --git a/cocos2d/core/platform/CCInputManager.js b/cocos2d/core/platform/CCInputManager.js index 1c7a7edeaa..545d0b0d90 100644 --- a/cocos2d/core/platform/CCInputManager.js +++ b/cocos2d/core/platform/CCInputManager.js @@ -118,7 +118,7 @@ cc.inputManager = /** @lends cc.inputManager# */{ if(index == null){ var unusedIndex = this._getUnUsedIndex(); - if (unusedIndex == -1) { + if (unusedIndex === -1) { cc.log(cc._LogInfos.inputManager_handleTouchesBegin, unusedIndex); continue; } @@ -266,7 +266,7 @@ cc.inputManager = /** @lends cc.inputManager# */{ var locPreTouchPool = this._preTouchPool; var id = touch.getID(); for (var i = locPreTouchPool.length - 1; i >= 0; i--) { - if (locPreTouchPool[i].getID() == id) { + if (locPreTouchPool[i].getID() === id) { preTouch = locPreTouchPool[i]; break; } @@ -285,7 +285,7 @@ cc.inputManager = /** @lends cc.inputManager# */{ var locPreTouchPool = this._preTouchPool; var id = touch.getID(); for (var i = locPreTouchPool.length - 1; i >= 0; i--) { - if (locPreTouchPool[i].getID() == id) { + if (locPreTouchPool[i].getID() === id) { locPreTouchPool[i] = touch; find = true; break; diff --git a/cocos2d/core/platform/CCLoaders.js b/cocos2d/core/platform/CCLoaders.js index 44aefd9f00..541e3b91c5 100644 --- a/cocos2d/core/platform/CCLoaders.js +++ b/cocos2d/core/platform/CCLoaders.js @@ -96,7 +96,7 @@ cc._fontLoader = { var src = srcs[i]; type = path.extname(src).toLowerCase(); fontStr += "url('" + srcs[i] + "') format('" + TYPE[type] + "')"; - fontStr += (i == li - 1) ? ";" : ","; + fontStr += (i === li - 1) ? ";" : ","; } }else{ fontStr += "url('" + srcs + "') format('" + TYPE[type] + "');"; diff --git a/cocos2d/core/platform/CCMacro.js b/cocos2d/core/platform/CCMacro.js index 2f94ced6cf..cabb8f2c30 100644 --- a/cocos2d/core/platform/CCMacro.js +++ b/cocos2d/core/platform/CCMacro.js @@ -460,7 +460,7 @@ cc.MIRRORED_REPEAT = 0x8370; * @function */ cc.checkGLErrorDebug = function () { - if (cc.renderMode == cc._RENDER_TYPE_WEBGL) { + if (cc.renderMode === cc._RENDER_TYPE_WEBGL) { var _error = cc._renderContext.getError(); if (_error) { cc.log(cc._LogInfos.checkGLErrorDebug, _error); @@ -785,7 +785,7 @@ cc.arrayVerifyType = function (arr, type) { */ cc.arrayRemoveObject = function (arr, delObj) { for (var i = 0, l = arr.length; i < l; i++) { - if (arr[i] == delObj) { + if (arr[i] === delObj) { arr.splice(i, 1); break; } diff --git a/cocos2d/core/platform/CCSAXParser.js b/cocos2d/core/platform/CCSAXParser.js index 94ec96589d..d0088e8f26 100644 --- a/cocos2d/core/platform/CCSAXParser.js +++ b/cocos2d/core/platform/CCSAXParser.js @@ -88,14 +88,14 @@ cc.PlistParser = cc.SAXParser.extend(/** @lends cc.plistParser# */{ parse : function (xmlTxt) { var xmlDoc = this._parseXML(xmlTxt); var plist = xmlDoc.documentElement; - if (plist.tagName != 'plist') + if (plist.tagName !== 'plist') throw "Not a plist file!"; // Get first real node var node = null; for (var i = 0, len = plist.childNodes.length; i < len; i++) { node = plist.childNodes[i]; - if (node.nodeType == 1) + if (node.nodeType === 1) break; } xmlDoc = null; @@ -104,12 +104,12 @@ cc.PlistParser = cc.SAXParser.extend(/** @lends cc.plistParser# */{ _parseNode: function (node) { var data = null, tagName = node.tagName; - if(tagName == "dict"){ + if(tagName === "dict"){ data = this._parseDict(node); - }else if(tagName == "array"){ + }else if(tagName === "array"){ data = this._parseArray(node); - }else if(tagName == "string"){ - if (node.childNodes.length == 1) + }else if(tagName === "string"){ + if (node.childNodes.length === 1) data = node.firstChild.nodeValue; else { //handle Firefox's 4KB nodeValue limit @@ -117,13 +117,13 @@ cc.PlistParser = cc.SAXParser.extend(/** @lends cc.plistParser# */{ for (var i = 0; i < node.childNodes.length; i++) data += node.childNodes[i].nodeValue; } - }else if(tagName == "false"){ + }else if(tagName === "false"){ data = false; - }else if(tagName == "true"){ + }else if(tagName === "true"){ data = true; - }else if(tagName == "real"){ + }else if(tagName === "real"){ data = parseFloat(node.firstChild.nodeValue); - }else if(tagName == "integer"){ + }else if(tagName === "integer"){ data = parseInt(node.firstChild.nodeValue, 10); } return data; @@ -133,7 +133,7 @@ cc.PlistParser = cc.SAXParser.extend(/** @lends cc.plistParser# */{ var data = []; for (var i = 0, len = node.childNodes.length; i < len; i++) { var child = node.childNodes[i]; - if (child.nodeType != 1) + if (child.nodeType !== 1) continue; data.push(this._parseNode(child)); } @@ -145,11 +145,11 @@ cc.PlistParser = cc.SAXParser.extend(/** @lends cc.plistParser# */{ var key = null; for (var i = 0, len = node.childNodes.length; i < len; i++) { var child = node.childNodes[i]; - if (child.nodeType != 1) + if (child.nodeType !== 1) continue; // Grab the key, next noe should be the value - if (child.tagName == 'key') + if (child.tagName === 'key') key = child.firstChild.nodeValue; else data[key] = this._parseNode(child); // Parse the value node diff --git a/cocos2d/core/platform/miniFramework.js b/cocos2d/core/platform/miniFramework.js index 9b4d3e05bd..048a2db325 100644 --- a/cocos2d/core/platform/miniFramework.js +++ b/cocos2d/core/platform/miniFramework.js @@ -33,7 +33,7 @@ */ cc.$ = function (x) { /** @lends cc.$# */ - var parent = (this == cc) ? document : this; + var parent = (this === cc) ? document : this; var el = (x instanceof HTMLElement) ? x : parent.querySelector(x); diff --git a/cocos2d/core/sprites/CCAnimationCache.js b/cocos2d/core/sprites/CCAnimationCache.js index 23adb0a203..d156393e26 100644 --- a/cocos2d/core/sprites/CCAnimationCache.js +++ b/cocos2d/core/sprites/CCAnimationCache.js @@ -156,7 +156,7 @@ cc.animationCache = /** @lends cc.animationCache# */{ if (frames.length === 0) { cc.log(cc._LogInfos.animationCache__parseVersion1_3, key); continue; - } else if (frames.length != frameNames.length) { + } else if (frames.length !== frameNames.length) { cc.log(cc._LogInfos.animationCache__parseVersion1_4, key); } animation = new cc.Animation(frames, delay, 1); diff --git a/cocos2d/core/sprites/CCSprite.js b/cocos2d/core/sprites/CCSprite.js index 7c891aeb7d..48acbb4fa6 100644 --- a/cocos2d/core/sprites/CCSprite.js +++ b/cocos2d/core/sprites/CCSprite.js @@ -427,7 +427,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * @param {Boolean} flippedX true if the sprite should be flipped horizontally, false otherwise. */ setFlippedX:function (flippedX) { - if (this._flippedX != flippedX) { + if (this._flippedX !== flippedX) { this._flippedX = flippedX; this.setTextureRect(this._rect, this._rectRotated, this._contentSize); this.setNodeDirty(true); @@ -439,7 +439,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * @param {Boolean} flippedY true if the sprite should be flipped vertically, false otherwise. */ setFlippedY:function (flippedY) { - if (this._flippedY != flippedY) { + if (this._flippedY !== flippedY) { this._flippedY = flippedY; this.setTextureRect(this._rect, this._rectRotated, this._contentSize); this.setNodeDirty(true); @@ -534,7 +534,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ if (!this._reorderChildDirty) { this._reorderChildDirty = true; var pNode = this._parent; - while (pNode && pNode != this._batchNode) { + while (pNode && pNode !== this._batchNode) { pNode._setReorderChildDirtyRecursively(); pNode = pNode.parent; } @@ -684,7 +684,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ */ initWithTexture: function (texture, rect, rotated, counterclockwise) { var _t = this; - cc.assert(arguments.length != 0, cc._LogInfos.CCSpriteBatchNode_initWithTexture); + cc.assert(arguments.length !== 0, cc._LogInfos.CCSpriteBatchNode_initWithTexture); rotated = rotated || false; texture = this._renderCmd._handleTextureForRotatedTexture(texture, rect, rotated, counterclockwise); @@ -838,7 +838,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ newFrame.addEventListener("load", function (sender) { _t._textureLoaded = true; var locNewTexture = sender.getTexture(); - if (locNewTexture != _t._texture) + if (locNewTexture !== _t._texture) _t.texture = locNewTexture; _t.setTextureRect(sender.getRect(), sender.isRotated(), sender.getOriginalSize()); _t.dispatchEvent("load"); @@ -846,7 +846,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ }, _t); }else{ // update texture before updating texture rect - if (pNewTexture != _t._texture) + if (pNewTexture !== _t._texture) _t.texture = pNewTexture; _t.setTextureRect(newFrame.getRect(), newFrame.isRotated(), newFrame.getOriginalSize()); } diff --git a/cocos2d/core/sprites/CCSpriteBatchNode.js b/cocos2d/core/sprites/CCSpriteBatchNode.js index 12438e6048..a67c4cac19 100644 --- a/cocos2d/core/sprites/CCSpriteBatchNode.js +++ b/cocos2d/core/sprites/CCSpriteBatchNode.js @@ -217,7 +217,7 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{ } } // ignore self (batch node) - if (!pobParent == this) { + if (!pobParent === this) { pobParent.atlasIndex = index; index++; } @@ -239,7 +239,7 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{ highestAtlasIndexInChild: function (sprite) { var children = sprite.children; - if (!children || children.length == 0) + if (!children || children.length === 0) return sprite.atlasIndex; else return this.highestAtlasIndexInChild(children[children.length - 1]); @@ -252,7 +252,7 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{ */ lowestAtlasIndexInChild: function (sprite) { var children = sprite.children; - if (!children || children.length == 0) + if (!children || children.length === 0) return sprite.atlasIndex; else return this.lowestAtlasIndexInChild(children[children.length - 1]); @@ -270,21 +270,21 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{ var childIndex = brothers.indexOf(sprite); // ignore parent Z if parent is spriteSheet - var ignoreParent = selParent == this; + var ignoreParent = selParent === this; var previous = null; if (childIndex > 0 && childIndex < cc.UINT_MAX) previous = brothers[childIndex - 1]; // first child of the sprite sheet if (ignoreParent) { - if (childIndex == 0) + if (childIndex === 0) return 0; return this.highestAtlasIndexInChild(previous) + 1; } // parent is a cc.Sprite, so, it must be taken into account // first child of an cc.Sprite ? - if (childIndex == 0) { + if (childIndex === 0) { // less than parent and brothers if (nZ < 0) return selParent.atlasIndex; @@ -514,7 +514,7 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{ sprite.batchNode = null; var locDescendants = this._descendants; var index = locDescendants.indexOf(sprite); - if (index != -1) { + if (index !== -1) { locDescendants.splice(index, 1); // update all sprites beyond this one @@ -608,7 +608,7 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{ //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller while (j >= 0 && ( tempItem._localZOrder < tempChild._localZOrder || - ( tempItem._localZOrder == tempChild._localZOrder && tempItem.arrivalOrder < tempChild.arrivalOrder ))) { + ( tempItem._localZOrder === tempChild._localZOrder && tempItem.arrivalOrder < tempChild.arrivalOrder ))) { childrenArr[j + 1] = tempChild; j = j - 1; tempChild = childrenArr[j]; diff --git a/cocos2d/core/sprites/CCSpriteBatchNodeWebGLRenderCmd.js b/cocos2d/core/sprites/CCSpriteBatchNodeWebGLRenderCmd.js index 8c371d0635..d61973d7e7 100644 --- a/cocos2d/core/sprites/CCSpriteBatchNodeWebGLRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteBatchNodeWebGLRenderCmd.js @@ -90,7 +90,7 @@ proto.checkAtlasCapacity = function(index){ // make needed room var locAtlas = this._textureAtlas; - while (index >= locAtlas.capacity || locAtlas.capacity == locAtlas.totalQuads) { + while (index >= locAtlas.capacity || locAtlas.capacity === locAtlas.totalQuads) { this.increaseAtlasCapacity(); } }; @@ -169,7 +169,7 @@ oldIndex = sprite.atlasIndex; sprite.atlasIndex = curIndex; sprite.arrivalOrder = 0; - if (oldIndex != curIndex) + if (oldIndex !== curIndex) this._swap(oldIndex, curIndex); curIndex++; } else { @@ -179,7 +179,7 @@ oldIndex = sprite.atlasIndex; sprite.atlasIndex = curIndex; sprite.arrivalOrder = 0; - if (oldIndex != curIndex) + if (oldIndex !== curIndex) this._swap(oldIndex, curIndex); curIndex++; needNewIndex = false; @@ -190,7 +190,7 @@ oldIndex = sprite.atlasIndex; sprite.atlasIndex = curIndex; sprite.arrivalOrder = 0; - if (oldIndex != curIndex) { + if (oldIndex !== curIndex) { this._swap(oldIndex, curIndex); } curIndex++; @@ -204,7 +204,7 @@ oldIndex = sprite.atlasIndex; sprite.atlasIndex = curIndex; sprite.arrivalOrder = 0; - if (oldIndex != curIndex) { + if (oldIndex !== curIndex) { this._swap(oldIndex, curIndex); } curIndex++; @@ -234,7 +234,7 @@ }; proto.setTextureAtlas = function(textureAtlas){ - if (textureAtlas != this._textureAtlas) { + if (textureAtlas !== this._textureAtlas) { this._textureAtlas = textureAtlas; } }; diff --git a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js index 51ae6f1524..4eb973c819 100644 --- a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js @@ -57,7 +57,7 @@ proto._setTexture = function (texture) { var node = this._node; - if (node._texture != texture) { + if (node._texture !== texture) { if (texture) { if(texture.getHtmlElementObj() instanceof HTMLImageElement) this._originalTexture = texture; @@ -75,7 +75,7 @@ proto.isFrameDisplayed = function (frame) { //TODO there maybe has a bug var node = this._node; - if (frame.getTexture() != node._texture) + if (frame.getTexture() !== node._texture) return false; return cc.rectEqualToRect(frame.getRect(), node._rect); }; @@ -141,7 +141,7 @@ if (node._texture) { image = node._texture._htmlElementObj; - if (node._texture._pattern != "") { + if (node._texture._pattern !== "") { wrapper.setFillStyle(context.createPattern(image, node._texture._pattern)); context.fillRect(locX * scaleX, locY * scaleY, locWidth * scaleX, locHeight * scaleY); } else { @@ -221,7 +221,7 @@ this._colorized = true; if (locElement instanceof HTMLCanvasElement && !this._rectRotated && !this._newTextureWhenChangeColor - && this._originalTexture._htmlElementObj != locElement) + && this._originalTexture._htmlElementObj !== locElement) cc.Sprite.CanvasRenderCmd._generateTintImageWithMultiply(this._originalTexture._htmlElementObj, displayedColor, locRect, locElement); else { locElement = cc.Sprite.CanvasRenderCmd._generateTintImageWithMultiply(this._originalTexture._htmlElementObj, displayedColor, locRect); @@ -260,12 +260,12 @@ if (node.dirty) { // If it is not visible, or one of its ancestors is not visible, then do nothing: var locParent = node._parent; - if (!node._visible || ( locParent && locParent != node._batchNode && locParent._shouldBeHidden)) { + if (!node._visible || ( locParent && locParent !== node._batchNode && locParent._shouldBeHidden)) { node._shouldBeHidden = true; } else { node._shouldBeHidden = false; - if (!locParent || locParent == node._batchNode) { + if (!locParent || locParent === node._batchNode) { node._transformToBatch = _t.getNodeToParentTransform(); } else { //cc.assert(_t._parent instanceof cc.Sprite, "Logic error in CCSprite. Parent must be a CCSprite"); @@ -314,7 +314,7 @@ //set the texture's color after the it loaded var locColor = locRenderCmd._displayedColor; - if (locColor.r != 255 || locColor.g != 255 || locColor.b != 255) + if (locColor.r !== 255 || locColor.g !== 255 || locColor.b !== 255) locRenderCmd._updateColor(); // by default use "Self Render". @@ -348,7 +348,7 @@ renderCanvas = renderCanvas || cc.newElement("canvas"); rect = rect || cc.rect(0, 0, image.width, image.height); var context = renderCanvas.getContext("2d"); - if (renderCanvas.width != rect.width || renderCanvas.height != rect.height) { + if (renderCanvas.width !== rect.width || renderCanvas.height !== rect.height) { renderCanvas.width = rect.width; renderCanvas.height = rect.height; } else { diff --git a/cocos2d/core/sprites/CCSpriteFrame.js b/cocos2d/core/sprites/CCSpriteFrame.js index 56ca499e7c..b59154f894 100644 --- a/cocos2d/core/sprites/CCSpriteFrame.js +++ b/cocos2d/core/sprites/CCSpriteFrame.js @@ -236,7 +236,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ * @param {cc.Texture2D} texture */ setTexture:function (texture) { - if (this._texture != texture) { + if (this._texture !== texture) { var locLoaded = texture.isLoaded(); this._textureLoaded = locLoaded; this._texture = texture; diff --git a/cocos2d/core/sprites/CCSpriteFrameCache.js b/cocos2d/core/sprites/CCSpriteFrameCache.js index 9f4166a131..f6ebcf2c58 100644 --- a/cocos2d/core/sprites/CCSpriteFrameCache.js +++ b/cocos2d/core/sprites/CCSpriteFrameCache.js @@ -300,7 +300,7 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{ if (spriteFrames[key]) { delete(spriteFrames[key]); for (var alias in aliases) {//remove alias - if(aliases[alias] == key) delete aliases[alias]; + if(aliases[alias] === key) delete aliases[alias]; } } } @@ -317,10 +317,10 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{ var self = this, spriteFrames = self._spriteFrames, aliases = self._spriteFramesAliases; for (var key in spriteFrames) { var frame = spriteFrames[key]; - if (frame && (frame.getTexture() == texture)) { + if (frame && (frame.getTexture() === texture)) { delete(spriteFrames[key]); for (var alias in aliases) {//remove alias - if(aliases[alias] == key) delete aliases[alias]; + if(aliases[alias] === key) delete aliases[alias]; } } } diff --git a/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js b/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js index 56ac66f8b2..78a83f5736 100644 --- a/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js @@ -80,7 +80,7 @@ proto.isFrameDisplayed = function (frame) { var node = this._node; - return (cc.rectEqualToRect(frame.getRect(), node._rect) && frame.getTexture().getName() == node._texture.getName() + return (cc.rectEqualToRect(frame.getRect(), node._rect) && frame.getTexture().getName() === node._texture.getName() && cc.pointEqualToPoint(frame.getOffset(), node._unflippedOffsetPositionFromCenter)); }; @@ -251,7 +251,7 @@ // renders using Sprite Manager if (node._batchNode) { - if (node.atlasIndex != cc.Sprite.INDEX_NOT_INITIALIZED) { + if (node.atlasIndex !== cc.Sprite.INDEX_NOT_INITIALIZED) { node.textureAtlas.updateQuad(locQuad, node.atlasIndex) } else { // no need to set it recursively @@ -287,12 +287,12 @@ var node = this._node; // If batchnode, then texture id should be the same if (node._batchNode) { - if(node._batchNode.texture != texture){ + if(node._batchNode.texture !== texture){ cc.log(cc._LogInfos.Sprite_setTexture); return; } }else{ - if(node._texture != texture){ + if(node._texture !== texture){ node._textureLoaded = texture ? texture._textureLoaded : false; node._texture = texture; this._updateBlendFunc(); @@ -313,7 +313,7 @@ if (this._dirty) { var locQuad = _t._quad, locParent = node._parent; // If it is not visible, or one of its ancestors is not visible, then do nothing: - if (!node._visible || ( locParent && locParent != node._batchNode && locParent._shouldBeHidden)) { + if (!node._visible || ( locParent && locParent !== node._batchNode && locParent._shouldBeHidden)) { locQuad.br.vertices = locQuad.tl.vertices = locQuad.tr.vertices = locQuad.bl.vertices = {x: 0, y: 0, z: 0}; node._shouldBeHidden = true; } else { @@ -323,7 +323,7 @@ this._dirtyFlag = 0; } - if (!locParent || locParent == node._batchNode) { + if (!locParent || locParent === node._batchNode) { node._transformToBatch = _t.getNodeToParentTransform(); } else { node._transformToBatch = cc.affineTransformConcat(_t.getNodeToParentTransform(), locParent._transformToBatch); diff --git a/cocos2d/core/support/CCPointExtension.js b/cocos2d/core/support/CCPointExtension.js index cf74e24b79..9771087379 100644 --- a/cocos2d/core/support/CCPointExtension.js +++ b/cocos2d/core/support/CCPointExtension.js @@ -371,7 +371,7 @@ cc.pRotateByAngle = function (v, pivot, angle) { * @return {Boolean} */ cc.pLineIntersect = function (A, B, C, D, retP) { - if ((A.x == B.x && A.y == B.y) || (C.x == D.x && C.y == D.y)) { + if ((A.x === B.x && A.y === B.y) || (C.x === D.x && C.y === D.y)) { return false; } var BAx = B.x - A.x; @@ -386,8 +386,8 @@ cc.pLineIntersect = function (A, B, C, D, retP) { retP.x = DCx * ACy - DCy * ACx; retP.y = BAx * ACy - BAy * ACx; - if (denom == 0) { - if (retP.x == 0 || retP.y == 0) { + if (denom === 0) { + if (retP.x === 0 || retP.y === 0) { // Lines incident return true; } @@ -447,7 +447,7 @@ cc.pIntersectPoint = function (A, B, C, D) { */ cc.pSameAs = function (A, B) { if ((A != null) && (B != null)) { - return (A.x == B.x && A.y == B.y); + return (A.x === B.x && A.y === B.y); } return false; }; diff --git a/cocos2d/core/support/CCVertex.js b/cocos2d/core/support/CCVertex.js index c300506f7a..44b92f0d22 100644 --- a/cocos2d/core/support/CCVertex.js +++ b/cocos2d/core/support/CCVertex.js @@ -76,7 +76,7 @@ cc.vertexLineToPolygon = function (points, stroke, vertices, offset, nuPoints) { } // Validate vertexes - offset = (offset == 0) ? 0 : offset - 1; + offset = (offset === 0) ? 0 : offset - 1; for (i = offset; i < nuPointsMinus; i++) { idx = i * 2; var idx1 = idx + 2; @@ -117,7 +117,7 @@ cc.vertexLineIntersect = function (Ax, Ay, Bx, By, Cx, Cy, Dx, Dy) { var distAB, theCos, theSin, newX; // FAIL: Line undefined - if ((Ax == Bx && Ay == By) || (Cx == Dx && Cy == Dy)) + if ((Ax === Bx && Ay === By) || (Cx === Dx && Cy === Dy)) return {isSuccess:false, value:0}; // Translate system to make A the origin @@ -142,7 +142,7 @@ cc.vertexLineIntersect = function (Ax, Ay, Bx, By, Cx, Cy, Dx, Dy) { Dx = newX; // FAIL: Lines are parallel. - if (Cy == Dy) return {isSuccess:false, value:0}; + if (Cy === Dy) return {isSuccess:false, value:0}; // Discover the relative position of the intersection in the line AB var t = (Dx + (Cx - Dx) * Dy / (Dy - Cy)) / distAB; diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index 6d3f8a3e53..dca144d060 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -408,7 +408,7 @@ if (cc._renderType === cc._RENDER_TYPE_CANVAS) { _backupElement: null, _isGray: false, _switchToGray: function(toGray){ - if(!this._textureLoaded || this._isGray == toGray) + if(!this._textureLoaded || this._isGray === toGray) return; this._isGray = toGray; if(this._isGray){ @@ -417,7 +417,7 @@ if (cc._renderType === cc._RENDER_TYPE_CANVAS) { this._grayElementObj = cc.Texture2D._generateGrayTexture(this._htmlElementObj); this._htmlElementObj = this._grayElementObj; } else { - if(this._backupElement != null) + if(this._backupElement !== null) this._htmlElementObj = this._backupElement; } } diff --git a/cocos2d/core/textures/CCTextureAtlas.js b/cocos2d/core/textures/CCTextureAtlas.js index 4bda9fb0d2..6de91ca14f 100644 --- a/cocos2d/core/textures/CCTextureAtlas.js +++ b/cocos2d/core/textures/CCTextureAtlas.js @@ -461,7 +461,7 @@ cc.TextureAtlas = cc.Class.extend(/** @lends cc.TextureAtlas# */{ //WebGL only * @return {Boolean} */ resizeCapacity: function (newCapacity) { - if (newCapacity == this._capacity) + if (newCapacity === this._capacity) return true; var quadSize = cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT; @@ -471,7 +471,7 @@ cc.TextureAtlas = cc.Class.extend(/** @lends cc.TextureAtlas# */{ //WebGL only this._capacity = 0 | newCapacity; var i, capacity = this._capacity, locTotalQuads = this._totalQuads; - if (this._quads == null) { + if (this._quads === null) { this._quads = []; this._quadsArrayBuffer = new ArrayBuffer(quadSize * capacity); this._quadsReader = new Uint8Array(this._quadsArrayBuffer); @@ -506,7 +506,7 @@ cc.TextureAtlas = cc.Class.extend(/** @lends cc.TextureAtlas# */{ //WebGL only } } - if (this._indices == null) { + if (this._indices === null) { this._indices = new Uint16Array(capacity * 6); } else { if (capacity > oldCapacity) { @@ -552,7 +552,7 @@ cc.TextureAtlas = cc.Class.extend(/** @lends cc.TextureAtlas# */{ //WebGL only cc.assert((newIndex + amount) <= this._totalQuads, cc._LogInfos.TextureAtlas_moveQuadsFromIndex_2); cc.assert(oldIndex < this._totalQuads, cc._LogInfos.TextureAtlas_moveQuadsFromIndex_3); - if (oldIndex == newIndex) + if (oldIndex === newIndex) return; } diff --git a/cocos2d/core/textures/CCTextureCache.js b/cocos2d/core/textures/CCTextureCache.js index ad24eea7d9..8068eb485b 100644 --- a/cocos2d/core/textures/CCTextureCache.js +++ b/cocos2d/core/textures/CCTextureCache.js @@ -121,7 +121,7 @@ cc.textureCache = /** @lends cc.textureCache# */{ */ getKeyByTexture: function (texture) { for (var key in this._textures) { - if (this._textures[key] == texture) { + if (this._textures[key] === texture) { return key; } } @@ -197,7 +197,7 @@ cc.textureCache = /** @lends cc.textureCache# */{ var locTextures = this._textures; for (var selKey in locTextures) { - if (locTextures[selKey] == texture) { + if (locTextures[selKey] === texture) { locTextures[selKey].releaseTexture(); delete(locTextures[selKey]); } @@ -247,7 +247,6 @@ cc.textureCache = /** @lends cc.textureCache# */{ * @return {cc.Texture2D} */ addUIImage: function (image, key) { - cc.assert(image, cc._LogInfos.textureCache_addUIImage_2); if (key) { @@ -258,7 +257,7 @@ cc.textureCache = /** @lends cc.textureCache# */{ // prevents overloading the autorelease pool var texture = new cc.Texture2D(); texture.initWithImage(image); - if ((key != null) && (texture != null)) + if (key != null) this._textures[key] = texture; else cc.log(cc._LogInfos.textureCache_addUIImage); diff --git a/cocos2d/core/textures/TexturesWebGL.js b/cocos2d/core/textures/TexturesWebGL.js index b1667ed971..c08cd2c49d 100644 --- a/cocos2d/core/textures/TexturesWebGL.js +++ b/cocos2d/core/textures/TexturesWebGL.js @@ -571,8 +571,8 @@ cc._tmp.WebGLTexture2D = function () { if(magFilter !== undefined) texParams = {minFilter: texParams, magFilter: magFilter, wrapS: wrapS, wrapT: wrapT}; - cc.assert((_t._pixelsWide == cc.NextPOT(_t._pixelsWide) && _t._pixelsHigh == cc.NextPOT(_t._pixelsHigh)) || - (texParams.wrapS == gl.CLAMP_TO_EDGE && texParams.wrapT == gl.CLAMP_TO_EDGE), + cc.assert((_t._pixelsWide === cc.NextPOT(_t._pixelsWide) && _t._pixelsHigh === cc.NextPOT(_t._pixelsHigh)) || + (texParams.wrapS === gl.CLAMP_TO_EDGE && texParams.wrapT === gl.CLAMP_TO_EDGE), "WebGLRenderingContext.CLAMP_TO_EDGE should be used in NPOT textures"); cc.glBindTexture2D(_t); @@ -620,7 +620,7 @@ cc._tmp.WebGLTexture2D = function () { */ generateMipmap: function () { var _t = this; - cc.assert(_t._pixelsWide == cc.NextPOT(_t._pixelsWide) && _t._pixelsHigh == cc.NextPOT(_t._pixelsHigh), "Mimpap texture only works in POT textures"); + cc.assert(_t._pixelsWide === cc.NextPOT(_t._pixelsWide) && _t._pixelsHigh === cc.NextPOT(_t._pixelsHigh), "Mimpap texture only works in POT textures"); cc.glBindTexture2D(_t); cc._renderContext.generateMipmap(cc._renderContext.TEXTURE_2D); @@ -672,7 +672,7 @@ cc._tmp.WebGLTexture2D = function () { // Repack the pixel data into the right format var length = width * height; - if (pixelFormat == tex2d.PIXEL_FORMAT_RGB565) { + if (pixelFormat === tex2d.PIXEL_FORMAT_RGB565) { if (hasAlpha) { // Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGGBBBBB" tempData = new Uint16Array(width * height); @@ -696,7 +696,7 @@ cc._tmp.WebGLTexture2D = function () { (((inPixel8[i] & 0xFF) >> 3) << 0); // B } } - } else if (pixelFormat == tex2d.PIXEL_FORMAT_RGBA4444) { + } else if (pixelFormat === tex2d.PIXEL_FORMAT_RGBA4444) { // Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRGGGGBBBBAAAA" tempData = new Uint16Array(width * height); inPixel32 = uiImage.getData(); @@ -708,7 +708,7 @@ cc._tmp.WebGLTexture2D = function () { ((((inPixel32[i] >> 16) & 0xFF) >> 4) << 4) | // B ((((inPixel32[i] >> 24) & 0xFF) >> 4) << 0); // A } - } else if (pixelFormat == tex2d.PIXEL_FORMAT_RGB5A1) { + } else if (pixelFormat === tex2d.PIXEL_FORMAT_RGB5A1) { // Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGBBBBBA" tempData = new Uint16Array(width * height); inPixel32 = uiImage.getData(); @@ -720,7 +720,7 @@ cc._tmp.WebGLTexture2D = function () { ((((inPixel32[i] >> 16) & 0xFF) >> 3) << 1) | // B ((((inPixel32[i] >> 24) & 0xFF) >> 7) << 0); // A } - } else if (pixelFormat == tex2d.PIXEL_FORMAT_A8) { + } else if (pixelFormat === tex2d.PIXEL_FORMAT_A8) { // Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "AAAAAAAA" tempData = new Uint8Array(width * height); inPixel32 = uiImage.getData(); @@ -730,7 +730,7 @@ cc._tmp.WebGLTexture2D = function () { } } - if (hasAlpha && pixelFormat == tex2d.PIXEL_FORMAT_RGB888) { + if (hasAlpha && pixelFormat === tex2d.PIXEL_FORMAT_RGB888) { // Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRRRRGGGGGGGGBBBBBBBB" inPixel32 = uiImage.getData(); tempData = new Uint8Array(width * height * 3); diff --git a/cocos2d/core/utils/BinaryLoader.js b/cocos2d/core/utils/BinaryLoader.js index 9478bd06ae..013c3dee6e 100644 --- a/cocos2d/core/utils/BinaryLoader.js +++ b/cocos2d/core/utils/BinaryLoader.js @@ -41,7 +41,7 @@ cc.loader.loadBinary = function (url, cb) { // IE-specific logic here xhr.setRequestHeader("Accept-Charset", "x-user-defined"); xhr.onreadystatechange = function () { - if (xhr.readyState == 4 && xhr.status == 200) { + if (xhr.readyState === 4 && xhr.status === 200) { var fileContents = cc._convertResponseBodyToText(xhr["responseBody"]); cb(null, self._str2Uint8Array(fileContents)); } else cb(errInfo); @@ -49,7 +49,7 @@ cc.loader.loadBinary = function (url, cb) { } else { if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=x-user-defined"); xhr.onload = function () { - xhr.readyState == 4 && xhr.status == 200 ? cb(null, self._str2Uint8Array(xhr.responseText)) : cb(errInfo); + xhr.readyState === 4 && xhr.status === 200 ? cb(null, self._str2Uint8Array(xhr.responseText)) : cb(errInfo); }; } xhr.send(null); @@ -81,7 +81,7 @@ cc.loader.loadBinarySync = function (url) { if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) { req.setRequestHeader("Accept-Charset", "x-user-defined"); req.send(null); - if (req.status != 200) { + if (req.status !== 200) { cc.log(errInfo); return null; } @@ -94,7 +94,7 @@ cc.loader.loadBinarySync = function (url) { if (req.overrideMimeType) req.overrideMimeType('text\/plain; charset=x-user-defined'); req.send(null); - if (req.status != 200) { + if (req.status !== 200) { cc.log(errInfo); return null; } diff --git a/cocos2d/effects/CCGrabber.js b/cocos2d/effects/CCGrabber.js index 96f78b2fa5..427ffb57e5 100644 --- a/cocos2d/effects/CCGrabber.js +++ b/cocos2d/effects/CCGrabber.js @@ -62,7 +62,7 @@ cc.Grabber = cc.Class.extend({ // check if it worked (probably worth doing :) ) var status = locGL.checkFramebufferStatus(locGL.FRAMEBUFFER); - if (status != locGL.FRAMEBUFFER_COMPLETE) + if (status !== locGL.FRAMEBUFFER_COMPLETE) cc.log("Frame Grabber: could not attach texture to frmaebuffer"); locGL.bindFramebuffer(locGL.FRAMEBUFFER, this._oldFBO); }, diff --git a/cocos2d/effects/CCGrid.js b/cocos2d/effects/CCGrid.js index a7276fe7c4..d324338c81 100644 --- a/cocos2d/effects/CCGrid.js +++ b/cocos2d/effects/CCGrid.js @@ -150,7 +150,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{ * @param {Boolean} flipped */ setTextureFlipped:function (flipped) { - if (this._isTextureFlipped != flipped) { + if (this._isTextureFlipped !== flipped) { this._isTextureFlipped = flipped; this.calculateVertexPoints(); } diff --git a/cocos2d/kazmath/mat4.js b/cocos2d/kazmath/mat4.js index 45b9a1d59b..33882b7a98 100644 --- a/cocos2d/kazmath/mat4.js +++ b/cocos2d/kazmath/mat4.js @@ -133,7 +133,7 @@ } } ++(ipiv[icol]); - if (irow != icol) { + if (irow !== icol) { for (l = 0; l < n; l++) a.swap(irow, l, icol, l); for (l = 0; l < m; l++) @@ -153,7 +153,7 @@ b.set(icol, l, b.get(icol, l) * pivinv); for (ll = 0; ll < n; ll++) { - if (ll != icol) { + if (ll !== icol) { dum = a.get(ll, icol); a.set(ll, icol, 0.0); for (l = 0; l < n; l++) @@ -168,7 +168,7 @@ // ble the solution in view of the column interchanges. We do this by interchanging pairs of // columns in the reverse order that the permutation was built up. for (l = n - 1; l >= 0; l--) { - if (indxr[l] != indxc[l]) { + if (indxr[l] !== indxc[l]) { for (k = 0; k < n; k++) a.swap(k, indxr[l], k, indxc[l]); } @@ -378,7 +378,7 @@ * @returns {cc.math.Matrix4} */ proto.assignFrom = function(mat4) { - if (this == mat4) { + if (this === mat4) { cc.log("cc.mat.Matrix4.assignFrom(): mat4 equals current matrix"); return this; } @@ -711,7 +711,7 @@ var deltaZ = zFar - zNear; var s = Math.sin(r); - if (deltaZ == 0 || s == 0 || aspect == 0) + if (deltaZ === 0 || s === 0 || aspect === 0) return null; //cos(r) / sin(r) = cot(r) @@ -739,7 +739,7 @@ var r = cc.degreesToRadians(fovY / 2), deltaZ = zFar - zNear; var s = Math.sin(r); - if (deltaZ == 0 || s == 0 || aspect == 0) + if (deltaZ === 0 || s === 0 || aspect === 0) return null; //cos(r) / sin(r) = cot(r) diff --git a/cocos2d/kazmath/quaternion.js b/cocos2d/kazmath/quaternion.js index 13e9d67ef6..ac926ebec2 100644 --- a/cocos2d/kazmath/quaternion.js +++ b/cocos2d/kazmath/quaternion.js @@ -115,7 +115,7 @@ * @returns {boolean} */ proto.isIdentity = function(){ //=cc.kmQuaternionIsIdentity - return (this.x == 0.0 && this.y == 0.0 && this.z == 0.0 && this.w == 1.0); + return (this.x === 0.0 && this.y === 0.0 && this.z === 0.0 && this.w === 1.0); }; /** diff --git a/cocos2d/labels/CCLabelAtlasCanvasRenderCmd.js b/cocos2d/labels/CCLabelAtlasCanvasRenderCmd.js index fed5c47dbd..2be997851d 100644 --- a/cocos2d/labels/CCLabelAtlasCanvasRenderCmd.js +++ b/cocos2d/labels/CCLabelAtlasCanvasRenderCmd.js @@ -54,7 +54,7 @@ var fontChar = node.getChildByTag(i); if (!fontChar) { fontChar = new cc.Sprite(); - if (c == 32) { + if (c === 32) { fontChar.init(); fontChar.setTextureRect(cc.rect(0, 0, 10, 10), false, cc.size(0, 0)); } else @@ -62,7 +62,7 @@ cc.Node.prototype.addChild.call(node, fontChar, 0, i); } else { - if (c == 32) { + if (c === 32) { fontChar.init(); fontChar.setTextureRect(cc.rect(0, 0, 10, 10), false, cc.size(0, 0)); } else { diff --git a/cocos2d/labels/CCLabelBMFont.js b/cocos2d/labels/CCLabelBMFont.js index 0b5169d090..6ac229c8b5 100644 --- a/cocos2d/labels/CCLabelBMFont.js +++ b/cocos2d/labels/CCLabelBMFont.js @@ -305,7 +305,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ var i, locCfg = self._config, locKerningDict = locCfg.kerningDict, locCommonH = locCfg.commonHeight, locFontDict = locCfg.fontDefDictionary; for (i = 0; i < stringLen - 1; i++) { - if (locStr.charCodeAt(i) == 10) quantityOfLines++; + if (locStr.charCodeAt(i) === 10) quantityOfLines++; } var totalHeight = locCommonH * quantityOfLines; @@ -314,7 +314,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ var prev = -1; for (i = 0; i < stringLen; i++) { var key = locStr.charCodeAt(i); - if (key == 0) continue; + if (key === 0) continue; if (key === 10) { //new line @@ -564,7 +564,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ } // Step 2: Make alignment - if (self._alignment != cc.TEXT_ALIGNMENT_LEFT) { + if (self._alignment !== cc.TEXT_ALIGNMENT_LEFT) { i = 0; var lineNumber = 0; @@ -572,11 +572,11 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ var last_line = []; for (var ctr = 0; ctr < strlen; ctr++) { - if (self._string[ctr].charCodeAt(0) == 10 || self._string[ctr].charCodeAt(0) == 0) { + if (self._string[ctr].charCodeAt(0) === 10 || self._string[ctr].charCodeAt(0) === 0) { var lineWidth = 0; var line_length = last_line.length; // if last line is empty we must just increase lineNumber and work with next line - if (line_length == 0) { + if (line_length === 0) { lineNumber++; continue; } @@ -600,7 +600,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ break; } - if (shift != 0) { + if (shift !== 0) { for (j = 0; j < line_length; j++) { index = i + j + lineNumber; if (index < 0) continue; @@ -698,7 +698,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ */ setFntFile: function (fntFile) { var self = this; - if (fntFile != null && fntFile != self._fntFile) { + if (fntFile != null && fntFile !== self._fntFile) { var newConf = cc.loader.getRes(fntFile); if (!newConf) { @@ -789,9 +789,9 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ //Checking whether the character is a whitespace _isspace_unicode: function(ch){ ch = ch.charCodeAt(0); - return ((ch >= 9 && ch <= 13) || ch == 32 || ch == 133 || ch == 160 || ch == 5760 - || (ch >= 8192 && ch <= 8202) || ch == 8232 || ch == 8233 || ch == 8239 - || ch == 8287 || ch == 12288) + return ((ch >= 9 && ch <= 13) || ch === 32 || ch === 133 || ch === 160 || ch === 5760 + || (ch >= 8192 && ch <= 8202) || ch === 8232 || ch === 8233 || ch === 8239 + || ch === 8287 || ch === 12288) }, _utf8_trim_ws: function(str){ @@ -874,7 +874,7 @@ cc._fntLoader = { var key = tempStr.substring(0, index); var value = tempStr.substring(index + 1); if (value.match(this.INT_EXP)) value = parseInt(value); - else if (value[0] == '"') value = value.substring(1, value.length - 1); + else if (value[0] === '"') value = value.substring(1, value.length - 1); obj[key] = value; } } diff --git a/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js b/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js index 211932df4e..2fd0ac9792 100644 --- a/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js +++ b/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js @@ -75,7 +75,7 @@ var selChild = locChildren[i]; var cm = selChild._renderCmd; var childDColor = cm._displayedColor; - if (this._texture != cm._texture && (childDColor.r !== locDisplayedColor.r || + if (this._texture !== cm._texture && (childDColor.r !== locDisplayedColor.r || childDColor.g !== locDisplayedColor.g || childDColor.b !== locDisplayedColor.b)) continue; selChild.texture = texture; diff --git a/cocos2d/menus/CCMenu.js b/cocos2d/menus/CCMenu.js index 794ef3ed61..53c34e6a1f 100644 --- a/cocos2d/menus/CCMenu.js +++ b/cocos2d/menus/CCMenu.js @@ -88,9 +88,9 @@ cc.Menu = cc.Layer.extend(/** @lends cc.Menu# */{ cc.log("parameters should not be ending with null in Javascript"); var argc = arguments.length, items; - if (argc == 0) { + if (argc === 0) { items = []; - } else if (argc == 1) { + } else if (argc === 1) { if (menuItems instanceof Array) { items = menuItems; } @@ -315,7 +315,7 @@ cc.Menu = cc.Layer.extend(/** @lends cc.Menu# */{ if (locChildren && locChildren.length > 0) { for (i = 0, len = locChildren.length; i < len; i++) { var child = locChildren[i]; - if (rowColumns == 0) { + if (rowColumns === 0) { rowColumns = rows[row]; w = winSize.width / (1 + rowColumns); x = w; @@ -409,7 +409,7 @@ cc.Menu = cc.Layer.extend(/** @lends cc.Menu# */{ if (locChildren && locChildren.length > 0) { for (i = 0, len = locChildren.length; i < len; i++) { child = locChildren[i]; - if (columnRows == 0) { + if (columnRows === 0) { columnRows = columns[column]; y = columnHeights[column]; } @@ -447,14 +447,14 @@ cc.Menu = cc.Layer.extend(/** @lends cc.Menu# */{ return; } - if (this._selectedItem == child) + if (this._selectedItem === child) this._selectedItem = null; cc.Node.prototype.removeChild.call(this, child, cleanup); }, _onTouchBegan: function (touch, event) { var target = event.getCurrentTarget(); - if (target._state != cc.MENU_STATE_WAITING || !target._visible || !target.enabled) + if (target._state !== cc.MENU_STATE_WAITING || !target._visible || !target.enabled) return false; for (var c = target.parent; c != null; c = c.parent) { @@ -506,7 +506,7 @@ cc.Menu = cc.Layer.extend(/** @lends cc.Menu# */{ return; } var currentItem = target._itemForTouch(touch); - if (currentItem != target._selectedItem) { + if (currentItem !== target._selectedItem) { if (target._selectedItem) { target._selectedItem.unselected(); target._selectedItem.setNodeDirty(); @@ -528,7 +528,7 @@ cc.Menu = cc.Layer.extend(/** @lends cc.Menu# */{ *

*/ onExit: function () { - if (this._state == cc.MENU_STATE_TRACKING_TOUCH) { + if (this._state === cc.MENU_STATE_TRACKING_TOUCH) { if (this._selectedItem) { this._selectedItem.unselected(); this._selectedItem = null; @@ -590,9 +590,9 @@ cc.Menu.create = function (menuItems) { cc.log("parameters should not be ending with null in Javascript"); var ret; - if (argc == 0) + if (argc === 0) ret = new cc.Menu(); - else if (argc == 1) + else if (argc === 1) ret = new cc.Menu(menuItems); else ret = new cc.Menu(Array.prototype.slice.call(arguments, 0)); diff --git a/cocos2d/menus/CCMenuItem.js b/cocos2d/menus/CCMenuItem.js index 8225c03cc6..06c85bb05e 100644 --- a/cocos2d/menus/CCMenuItem.js +++ b/cocos2d/menus/CCMenuItem.js @@ -295,7 +295,7 @@ cc.MenuItemLabel = cc.MenuItem.extend(/** @lends cc.MenuItemLabel# */{ * @param {Boolean} enabled */ setEnabled: function (enabled) { - if (this._enabled != enabled) { + if (this._enabled !== enabled) { var locLabel = this._label; if (!enabled) { this._colorBackup = locLabel.color; @@ -492,7 +492,7 @@ cc.MenuItemAtlasFont = cc.MenuItemLabel.extend(/** @lends cc.MenuItemAtlasFont# * @return {Boolean} */ initWithString: function (value, charMapFile, itemWidth, itemHeight, startCharMap, callback, target) { - if (!value || value.length == 0) + if (!value || value.length === 0) throw "cc.MenuItemAtlasFont.initWithString(): value should be non-null and its length should be greater than 0"; var label = new cc.LabelAtlas(); @@ -566,7 +566,7 @@ cc.MenuItemFont = cc.MenuItemLabel.extend(/** @lends cc.MenuItemFont# */{ * @return {Boolean} */ initWithString: function (value, callback, target) { - if (!value || value.length == 0) + if (!value || value.length === 0) throw "Value should be non-null and its length should be greater than 0"; this._fontName = cc._globalFontName; @@ -760,7 +760,7 @@ cc.MenuItemSprite = cc.MenuItem.extend(/** @lends cc.MenuItemSprite# */{ * @param {cc.Sprite} normalImage */ setNormalImage: function (normalImage) { - if (this._normalImage == normalImage) { + if (this._normalImage === normalImage) { return; } if (normalImage) { @@ -798,7 +798,7 @@ cc.MenuItemSprite = cc.MenuItem.extend(/** @lends cc.MenuItemSprite# */{ * @param {cc.Sprite} selectedImage */ setSelectedImage: function (selectedImage) { - if (this._selectedImage == selectedImage) + if (this._selectedImage === selectedImage) return; if (selectedImage) { @@ -828,7 +828,7 @@ cc.MenuItemSprite = cc.MenuItem.extend(/** @lends cc.MenuItemSprite# */{ * @param {cc.Sprite} disabledImage */ setDisabledImage: function (disabledImage) { - if (this._disabledImage == disabledImage) + if (this._disabledImage === disabledImage) return; if (disabledImage) { @@ -959,7 +959,7 @@ cc.MenuItemSprite = cc.MenuItem.extend(/** @lends cc.MenuItemSprite# */{ * @param {Boolean} bEnabled */ setEnabled: function (bEnabled) { - if (this._enabled != bEnabled) { + if (this._enabled !== bEnabled) { cc.MenuItem.prototype.setEnabled.call(this, bEnabled); this._updateImagesVisibility(); } @@ -1251,7 +1251,7 @@ cc.MenuItemToggle = cc.MenuItem.extend(/** @lends cc.MenuItemToggle# */{ * @param {Number} SelectedIndex */ setSelectedIndex: function (SelectedIndex) { - if (SelectedIndex != this._selectedIndex) { + if (SelectedIndex !== this._selectedIndex) { this._selectedIndex = SelectedIndex; var currItem = this.getChildByTag(cc.CURRENT_ITEM); if (currItem) @@ -1358,7 +1358,7 @@ cc.MenuItemToggle = cc.MenuItem.extend(/** @lends cc.MenuItemToggle# */{ * @param {Boolean} enabled */ setEnabled: function (enabled) { - if (this._enabled != enabled) { + if (this._enabled !== enabled) { cc.MenuItem.prototype.setEnabled.call(this, enabled); var locItems = this.subItems; if (locItems && locItems.length > 0) { diff --git a/cocos2d/motion-streak/CCMotionStreak.js b/cocos2d/motion-streak/CCMotionStreak.js index e62727be07..13c66a0f28 100644 --- a/cocos2d/motion-streak/CCMotionStreak.js +++ b/cocos2d/motion-streak/CCMotionStreak.js @@ -129,7 +129,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ * @param {cc.Texture2D} texture */ setTexture:function (texture) { - if (this.texture != texture) + if (this.texture !== texture) this.texture = texture; }, @@ -432,7 +432,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ else if (locNuPoints > 0) { var a1 = cc.pDistanceSQ(cc.p(locPointVertexes[(locNuPoints - 1) * 2], locPointVertexes[(locNuPoints - 1) * 2 + 1]), this._positionR) < this._minSeg; - var a2 = (locNuPoints == 1) ? false : (cc.pDistanceSQ( + var a2 = (locNuPoints === 1) ? false : (cc.pDistanceSQ( cc.p(locPointVertexes[(locNuPoints - 2) * 2], locPointVertexes[(locNuPoints - 2) * 2 + 1]), this._positionR) < (this._minSeg * 2.0)); if (a1 || a2) appendNewPoint = false; @@ -473,7 +473,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ cc.vertexLineToPolygon(locPointVertexes, this._stroke, this._vertices, 0, locNuPoints); // Updated Tex Coords only if they are different than previous step - if (locNuPoints && this._previousNuPoints != locNuPoints) { + if (locNuPoints && this._previousNuPoints !== locNuPoints) { var texDelta = 1.0 / locNuPoints; var locTexCoords = this._texCoords; for (i = 0; i < locNuPoints; i++) { diff --git a/cocos2d/node-grid/CCNodeGrid.js b/cocos2d/node-grid/CCNodeGrid.js index 3426e84d74..781b8db4c8 100644 --- a/cocos2d/node-grid/CCNodeGrid.js +++ b/cocos2d/node-grid/CCNodeGrid.js @@ -83,7 +83,7 @@ cc.NodeGrid = cc.Node.extend({ topMat4.multiply(t4x4) ; // = cc.kmGLMultMatrix(this._transform4x4); // XXX: Expensive calls. Camera should be integrated into the cached affine matrix - if (this._camera != null && !(this.grid && this.grid.isActive())) { + if (this._camera !== null && !(this.grid && this.grid.isActive())) { var app = this._renderCmd._anchorPointInPoints, apx = app.x, apy = app.y, translate = (apx !== 0.0 || apy !== 0.0); diff --git a/cocos2d/parallax/CCParallaxNode.js b/cocos2d/parallax/CCParallaxNode.js index c7716ea99f..ca41c526aa 100644 --- a/cocos2d/parallax/CCParallaxNode.js +++ b/cocos2d/parallax/CCParallaxNode.js @@ -190,7 +190,7 @@ cc.ParallaxNode = cc.Node.extend(/** @lends cc.ParallaxNode# */{ var locParallaxArray = this.parallaxArray; for (var i = 0; i < locParallaxArray.length; i++) { var point = locParallaxArray[i]; - if (point.getChild() == child) { + if (point.getChild() === child) { locParallaxArray.splice(i, 1); break; } @@ -224,7 +224,7 @@ cc.ParallaxNode = cc.Node.extend(/** @lends cc.ParallaxNode# */{ _absolutePosition:function () { var ret = this._position; var cn = this; - while (cn.parent != null) { + while (cn.parent !== null) { cn = cn.parent; ret = cc.pAdd(ret, cn.getPosition()); } diff --git a/cocos2d/particle/CCParticleBatchNode.js b/cocos2d/particle/CCParticleBatchNode.js index 69809898d1..b92f11bc27 100644 --- a/cocos2d/particle/CCParticleBatchNode.js +++ b/cocos2d/particle/CCParticleBatchNode.js @@ -161,7 +161,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ zOrder = (zOrder == null) ? child.zIndex : zOrder; tag = (tag == null) ? child.tag : tag; - if(child.getTexture() != this.textureAtlas.texture) + if(child.getTexture() !== this.textureAtlas.texture) throw "cc.ParticleSystem.addChild() : the child is not using the same texture id"; // If this is the 1st children, then copy blending function @@ -169,7 +169,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ if (this._children.length === 0) this.setBlendFunc(childBlendFunc); else{ - if((childBlendFunc.src != this._blendFunc.src) || (childBlendFunc.dst != this._blendFunc.dst)){ + if((childBlendFunc.src !== this._blendFunc.src) || (childBlendFunc.dst !== this._blendFunc.dst)){ cc.log("cc.ParticleSystem.addChild() : Can't add a ParticleSystem that uses a different blending function"); return; } @@ -181,7 +181,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ //get new atlasIndex var atlasIndex = 0; - if (pos != 0) { + if (pos !== 0) { var p = this._children[pos - 1]; atlasIndex = p.getAtlasIndex() + p.getTotalParticles(); } else @@ -210,7 +210,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ } // make room for quads, not necessary for last child - if (pSystem.getAtlasIndex() + totalParticles != totalQuads) + if (pSystem.getAtlasIndex() + totalParticles !== totalQuads) locTextureAtlas.moveQuadsFromIndex(index, index + totalParticles); // increase totalParticles here for new particles, update method of particlesystem will fill the quads @@ -229,7 +229,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ if(!(child instanceof cc.ParticleSystem)) throw "cc.ParticleBatchNode.removeChild(): only supports cc.ParticleSystem as children"; - if(this._children.indexOf(child) == -1){ + if(this._children.indexOf(child) === -1){ cc.log("cc.ParticleBatchNode.removeChild(): doesn't contain the sprite. Can't remove it"); return; } @@ -264,14 +264,14 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ return; } - if (zOrder == child.zIndex) + if (zOrder === child.zIndex) return; // no reordering if only 1 child if (this._children.length > 1) { var getIndexes = this._getCurrentIndex(child, zOrder); - if (getIndexes.oldIndex != getIndexes.newIndex) { + if (getIndexes.oldIndex !== getIndexes.newIndex) { // reorder m_pChildren.array this._children.splice(getIndexes.oldIndex, 1) this._children.splice(getIndexes.newIndex, 0, child); @@ -287,7 +287,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ var locChildren = this._children; for (var i = 0; i < locChildren.length; i++) { var pNode = locChildren[i]; - if (pNode == child) { + if (pNode === child) { newAtlasIndex = child.getAtlasIndex(); break; } @@ -350,7 +350,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ // If the new texture has No premultiplied alpha, AND the blendFunc hasn't been changed, then update it var locBlendFunc = this._blendFunc; - if (texture && !texture.hasPremultipliedAlpha() && ( locBlendFunc.src == cc.BLEND_SRC && locBlendFunc.dst == cc.BLEND_DST )) { + if (texture && !texture.hasPremultipliedAlpha() && ( locBlendFunc.src === cc.BLEND_SRC && locBlendFunc.dst === cc.BLEND_DST )) { locBlendFunc.src = cc.SRC_ALPHA; locBlendFunc.dst = cc.ONE_MINUS_SRC_ALPHA; } @@ -429,7 +429,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ break; } // current index - if (child == pNode) { + if (child === pNode) { oldIndex = i; foundCurrentIdx = true; if (!foundNewIdx) diff --git a/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js b/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js index 38611de45c..16da24b496 100644 --- a/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js +++ b/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js @@ -36,7 +36,7 @@ proto.rendering = function (ctx) { var _t = this._node; - if (_t.textureAtlas.totalQuads == 0) + if (_t.textureAtlas.totalQuads === 0) return; this._shaderProgram.use(); diff --git a/cocos2d/particle/CCParticleSystem.js b/cocos2d/particle/CCParticleSystem.js index f270679a0a..85a844df33 100644 --- a/cocos2d/particle/CCParticleSystem.js +++ b/cocos2d/particle/CCParticleSystem.js @@ -1144,12 +1144,12 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ */ setBlendFunc:function (src, dst) { if (dst === undefined) { - if (this._blendFunc != src) { + if (this._blendFunc !== src) { this._blendFunc = src; this._updateBlendFunc(); } } else { - if (this._blendFunc.src != src || this._blendFunc.dst != dst) { + if (this._blendFunc.src !== src || this._blendFunc.dst !== dst) { this._blendFunc = {src:src, dst:dst}; this._updateBlendFunc(); } @@ -1182,7 +1182,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * dest blend function = GL_ONE; */ isBlendAdditive:function () { - return (( this._blendFunc.src == cc.SRC_ALPHA && this._blendFunc.dst == cc.ONE) || (this._blendFunc.src == cc.ONE && this._blendFunc.dst == cc.ONE)); + return (( this._blendFunc.src === cc.SRC_ALPHA && this._blendFunc.dst === cc.ONE) || (this._blendFunc.src === cc.ONE && this._blendFunc.dst === cc.ONE)); }, /** @@ -1364,7 +1364,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ this.emitterMode = parseInt(locValueForKey("emitterType", dictionary)); // Mode A: Gravity + tangential accel + radial accel - if (this.emitterMode == cc.ParticleSystem.MODE_GRAVITY) { + if (this.emitterMode === cc.ParticleSystem.MODE_GRAVITY) { var locModeA = this.modeA; // gravity locModeA.gravity.x = parseFloat(locValueForKey("gravityx", dictionary)); @@ -1391,7 +1391,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ // rotation is dir var locRotationIsDir = locValueForKey("rotationIsDir", dictionary).toLowerCase(); locModeA.rotationIsDir = (locRotationIsDir != null && (locRotationIsDir === "true" || locRotationIsDir === "1")); - } else if (this.emitterMode == cc.ParticleSystem.MODE_RADIUS) { + } else if (this.emitterMode === cc.ParticleSystem.MODE_RADIUS) { // or Mode B: radius movement var locModeB = this.modeB; locModeB.startRadius = parseFloat(locValueForKey("maxRadius", dictionary)); @@ -1603,9 +1603,9 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ particle.deltaRotation = (endA - startA) / locParticleTimeToLive; // position - if (this.positionType == cc.ParticleSystem.TYPE_FREE) + if (this.positionType === cc.ParticleSystem.TYPE_FREE) particle.startPos = this.convertToWorldSpace(this._pointZeroForParticle); - else if (this.positionType == cc.ParticleSystem.TYPE_RELATIVE){ + else if (this.positionType === cc.ParticleSystem.TYPE_RELATIVE){ particle.startPos.x = this._position.x; particle.startPos.y = this._position.y; } @@ -1710,15 +1710,15 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ } this._elapsed += dt; - if (this.duration != -1 && this.duration < this._elapsed) + if (this.duration !== -1 && this.duration < this._elapsed) this.stopSystem(); } this._particleIdx = 0; var currentPosition = cc.Particle.TemporaryPoints[0]; - if (this.positionType == cc.ParticleSystem.TYPE_FREE) { + if (this.positionType === cc.ParticleSystem.TYPE_FREE) { cc.pIn(currentPosition, this.convertToWorldSpace(this._pointZeroForParticle)); - } else if (this.positionType == cc.ParticleSystem.TYPE_RELATIVE) { + } else if (this.positionType === cc.ParticleSystem.TYPE_RELATIVE) { currentPosition.x = this._position.x; currentPosition.y = this._position.y; } @@ -1744,7 +1744,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ if (selParticle.timeToLive > 0) { // Mode A: gravity, direction, tangential accel & radial accel - if (this.emitterMode == cc.ParticleSystem.MODE_GRAVITY) { + if (this.emitterMode === cc.ParticleSystem.MODE_GRAVITY) { var tmp = tpc, radial = tpa, tangential = tpb; @@ -1801,7 +1801,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ // update values in quad // var newPos = tpa; - if (this.positionType == cc.ParticleSystem.TYPE_FREE || this.positionType == cc.ParticleSystem.TYPE_RELATIVE) { + if (this.positionType === cc.ParticleSystem.TYPE_FREE || this.positionType === cc.ParticleSystem.TYPE_RELATIVE) { var diff = tpb; cc.pIn(diff, currentPosition); cc.pSubIn(diff, selParticle.startPos); @@ -1838,7 +1838,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ } --this.particleCount; - if (this.particleCount == 0 && this.autoRemoveOnFinish) { + if (this.particleCount === 0 && this.autoRemoveOnFinish) { this.unscheduleUpdate(); this._parent.removeChild(this, true); return; @@ -1884,7 +1884,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ if (locTexture && locTexture instanceof cc.Texture2D) { this._opacityModifyRGB = false; var locBlendFunc = this._blendFunc; - if (locBlendFunc.src == cc.BLEND_SRC && locBlendFunc.dst == cc.BLEND_DST) { + if (locBlendFunc.src === cc.BLEND_SRC && locBlendFunc.dst === cc.BLEND_DST) { if (locTexture.hasPremultipliedAlpha()) { this._opacityModifyRGB = true; } else { @@ -1945,7 +1945,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ retParticle.setEmitterMode(this.getEmitterMode()); // Mode A: Gravity + tangential accel + radial accel - if (this.getEmitterMode() == cc.ParticleSystem.MODE_GRAVITY) { + if (this.getEmitterMode() === cc.ParticleSystem.MODE_GRAVITY) { // gravity var gra = this.getGravity(); retParticle.setGravity(cc.p(gra.x,gra.y)); @@ -1962,7 +1962,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ retParticle.setTangentialAccel(this.getTangentialAccel()); retParticle.setTangentialAccelVar(this.getTangentialAccelVar()); - } else if (this.getEmitterMode() == cc.ParticleSystem.MODE_RADIUS) { + } else if (this.getEmitterMode() === cc.ParticleSystem.MODE_RADIUS) { // or Mode B: radius movement retParticle.setStartRadius(this.getStartRadius()); retParticle.setStartRadiusVar(this.getStartRadiusVar()); @@ -2006,12 +2006,12 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ return; var locOffset = spriteFrame.getOffsetInPixels(); - if (locOffset.x != 0 || locOffset.y != 0) + if (locOffset.x !== 0 || locOffset.y !== 0) cc.log("cc.ParticleSystem.setDisplayFrame(): QuadParticle only supports SpriteFrames with no offsets"); // update texture before updating texture rect var texture = spriteFrame.getTexture(), locTexture = this._texture; - if (locTexture != texture) + if (locTexture !== texture) this.setTexture(texture); }, @@ -2022,7 +2022,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ */ setTextureWithRect: function (texture, rect) { var locTexture = this._texture; - if (locTexture != texture) { + if (locTexture !== texture) { this._texture = texture; this._updateBlendFunc(); } diff --git a/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js b/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js index ed58e9821b..7537bb94d5 100644 --- a/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js +++ b/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js @@ -55,7 +55,7 @@ }; proto.setBatchNode = function(batchNode){ - if (this._batchNode != batchNode) { + if (this._batchNode !== batchNode) { this._node._batchNode = batchNode; } }; @@ -129,7 +129,7 @@ context.save(); context.translate(0 | particle.drawPos.x, -(0 | particle.drawPos.y)); - if (node.shapeType == cc.ParticleSystem.STAR_SHAPE) { + if (node.shapeType === cc.ParticleSystem.STAR_SHAPE) { if (particle.rotation) context.rotate(cc.degreesToRadians(particle.rotation)); drawTool.drawStar(wrapper, lpx, particle.color); diff --git a/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js b/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js index 87f501510f..eb1ce063b0 100644 --- a/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js +++ b/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js @@ -45,7 +45,7 @@ proto.setBatchNode = function(batchNode){ var node = this._node; - if (node._batchNode != batchNode) { + if (node._batchNode !== batchNode) { var oldBatch = node._batchNode; node._batchNode = batchNode; //weak reference @@ -89,8 +89,7 @@ }; proto.isDifferentTexture = function(texture1, texture2){ - if(texture1 == texture2) - return true; + return (texture1 === texture2); }; proto.updateParticlePosition = function(particle, position){ diff --git a/cocos2d/physics/CCPhysicsSprite.js b/cocos2d/physics/CCPhysicsSprite.js index 913b8726e6..2fa248da8f 100644 --- a/cocos2d/physics/CCPhysicsSprite.js +++ b/cocos2d/physics/CCPhysicsSprite.js @@ -347,7 +347,7 @@ _syncPosition:function () { var locPosition = this._position, locBody = this._body; - if (locPosition.x != locBody.p.x || locPosition.y != locBody.p.y) { + if (locPosition.x !== locBody.p.x || locPosition.y !== locBody.p.y) { cc.Sprite.prototype.setPosition.call(this, locBody.p.x, locBody.p.y); } }, @@ -373,7 +373,7 @@ } }, _syncRotation:function () { - if (this._rotationX != -cc.radiansToDegrees(this._body.a)) { + if (this._rotationX !== -cc.radiansToDegrees(this._body.a)) { cc.Sprite.prototype.setRotation.call(this, -cc.radiansToDegrees(this._body.a)); } }, diff --git a/cocos2d/progress-timer/CCProgressTimer.js b/cocos2d/progress-timer/CCProgressTimer.js index b5b9fff6f3..3ad05586f0 100644 --- a/cocos2d/progress-timer/CCProgressTimer.js +++ b/cocos2d/progress-timer/CCProgressTimer.js @@ -145,7 +145,7 @@ cc.ProgressTimer = cc.Node.extend(/** @lends cc.ProgressTimer# */{ * @param {Number} percentage */ setPercentage:function (percentage) { - if (this._percentage != percentage) { + if (this._percentage !== percentage) { this._percentage = cc.clampf(percentage, 0, 100); this._renderCmd._updateProgress(); } @@ -224,7 +224,7 @@ cc.ProgressTimer = cc.Node.extend(/** @lends cc.ProgressTimer# */{ * @param {cc.Sprite} sprite */ setSprite: function(sprite){ - if (this._sprite != sprite) { + if (this._sprite !== sprite) { this._sprite = sprite; if(sprite) this.setContentSize(sprite.width,sprite.height); diff --git a/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js b/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js index c914c07267..fbb87b8ced 100644 --- a/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js +++ b/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js @@ -72,13 +72,13 @@ } //clip - if (node._type == cc.ProgressTimer.TYPE_BAR) { + if (node._type === cc.ProgressTimer.TYPE_BAR) { var locBarRect = this._barRect; context.beginPath(); context.rect(locBarRect.x * scaleX, locBarRect.y * scaleY, locBarRect.width * scaleX, locBarRect.height * scaleY); context.clip(); context.closePath(); - } else if (node._type == cc.ProgressTimer.TYPE_RADIAL) { + } else if (node._type === cc.ProgressTimer.TYPE_RADIAL) { var locOriginX = this._origin.x * scaleX; var locOriginY = this._origin.y * scaleY; context.beginPath(); @@ -113,7 +113,7 @@ var sw = locSprite.width, sh = locSprite.height; var locMidPoint = node._midPoint; - if (node._type == cc.ProgressTimer.TYPE_RADIAL) { + if (node._type === cc.ProgressTimer.TYPE_RADIAL) { this._radius = Math.round(Math.sqrt(sw * sw + sh * sh)); var locStartAngle, locEndAngle, locCounterClockWise = false, locOrigin = this._origin; locOrigin.x = sw * locMidPoint.x; diff --git a/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js b/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js index 4ca4286c07..c8b147ae8b 100644 --- a/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js +++ b/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js @@ -67,7 +67,7 @@ if (node._type === cc.ProgressTimer.TYPE_RADIAL) context.drawArrays(context.TRIANGLE_FAN, 0, this._vertexDataCount); - else if (node._type == cc.ProgressTimer.TYPE_BAR) { + else if (node._type === cc.ProgressTimer.TYPE_BAR) { if (!node._reverseDirection) context.drawArrays(context.TRIANGLE_STRIP, 0, this._vertexDataCount); else { @@ -327,12 +327,12 @@ var index = 0; var hit; - if (alpha == 0) { + if (alpha === 0) { // More efficient since we don't always need to check intersection // If the alpha is zero then the hit point is top mid and the index is 0. hit = topMid; index = 0; - } else if (alpha == 1) { + } else if (alpha === 1) { // More efficient since we don't always need to check intersection // If the alpha is one then the hit point is top mid and the index is 4. hit = topMid; @@ -352,9 +352,9 @@ // Remember that the top edge is split in half for the 12 o'clock position // Let's deal with that here by finding the correct endpoints - if (i == 0) + if (i === 0) edgePtB = cc.pLerp(edgePtA, edgePtB, 1 - locMidPoint.x); - else if (i == 4) + else if (i === 4) edgePtA = cc.pLerp(edgePtA, edgePtB, 1 - locMidPoint.x); // retPoint are returned by ccpLineIntersect @@ -362,7 +362,7 @@ if (cc.pLineIntersect(edgePtA, edgePtB, locMidPoint, percentagePt, retPoint)) { // Since our hit test is on rays we have to deal with the top edge // being in split in half so we have to test as a segment - if ((i == 0 || i == 4)) { + if ((i === 0 || i === 4)) { // s represents the point between edgePtA--edgePtB if (!(0 <= retPoint.x && retPoint.x <= 1)) continue; @@ -387,7 +387,7 @@ // The size of the vertex data is the index from the hitpoint // the 3 is for the m_tMidpoint, 12 o'clock point and hitpoint position. var sameIndexCount = true; - if (this._vertexDataCount != index + 3) { + if (this._vertexDataCount !== index + 3) { sameIndexCount = false; this._vertexData = null; this._vertexArrayBuffer = null; diff --git a/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js b/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js index 5238694b38..50bed35f16 100644 --- a/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js +++ b/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js @@ -95,7 +95,7 @@ var locChildren = node._children; for (var i = 0; i < locChildren.length; i++) { var getChild = locChildren[i]; - if (getChild != node.sprite){ + if (getChild !== node.sprite){ getChild._renderCmd.visit(node.sprite._renderCmd); //TODO it's very Strange } } @@ -130,7 +130,7 @@ proto.initWithWidthAndHeight = function(width, height, format, depthStencilFormat){ var node = this._node; - if(format == cc.Texture2D.PIXEL_FORMAT_A8) + if(format === cc.Texture2D.PIXEL_FORMAT_A8) cc.log( "cc.RenderTexture._initWithWidthAndHeightForWebGL() : only RGB and RGBA formats are valid for a render texture;"); var gl = cc._renderContext, locScaleFactor = cc.contentScaleFactor(); @@ -185,7 +185,7 @@ // associate texture with FBO gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, locTexture._webTextureObj, 0); - if (depthStencilFormat != 0) { + if (depthStencilFormat !== 0) { //create and attach depth buffer this._depthRenderBuffer = gl.createRenderbuffer(); gl.bindRenderbuffer(gl.RENDERBUFFER, this._depthRenderBuffer); diff --git a/cocos2d/shaders/CCGLProgram.js b/cocos2d/shaders/CCGLProgram.js index c8812bcac4..283a2f5390 100644 --- a/cocos2d/shaders/CCGLProgram.js +++ b/cocos2d/shaders/CCGLProgram.js @@ -101,12 +101,12 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ if (!status) { cc.log("cocos2d: ERROR: Failed to compile shader:\n" + this._glContext.getShaderSource(shader)); - if (type == this._glContext.VERTEX_SHADER) + if (type === this._glContext.VERTEX_SHADER) cc.log("cocos2d: \n" + this.vertexShaderLog()); else cc.log("cocos2d: \n" + this.fragmentShaderLog()); } - return ( status == 1 ); + return ( status === 1 ); }, /** @@ -568,7 +568,7 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ this.setUniformLocationWith4f(this._uniforms[cc.UNIFORM_COSTIME], time / 8.0, time / 4.0, time / 2.0, Math.cos(time)); } - if (this._uniforms[cc.UNIFORM_RANDOM01] != -1) + if (this._uniforms[cc.UNIFORM_RANDOM01] !== -1) this.setUniformLocationWith4f(this._uniforms[cc.UNIFORM_RANDOM01], Math.random(), Math.random(), Math.random(), Math.random()); }, @@ -601,7 +601,7 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ this.setUniformLocationWith4f(this._uniforms[cc.UNIFORM_COSTIME], time / 8.0, time / 4.0, time / 2.0, Math.cos(time)); } - if (this._uniforms[cc.UNIFORM_RANDOM01] != -1) + if (this._uniforms[cc.UNIFORM_RANDOM01] !== -1) this.setUniformLocationWith4f(this._uniforms[cc.UNIFORM_RANDOM01], Math.random(), Math.random(), Math.random(), Math.random()); }, @@ -737,7 +737,7 @@ cc.GLProgram._isHighpSupported = function(){ if(cc.GLProgram._highpSupported == null){ var ctx = cc._renderContext; var highp = ctx.getShaderPrecisionFormat(ctx.FRAGMENT_SHADER, ctx.HIGH_FLOAT); - cc.GLProgram._highpSupported = highp.precision != 0; + cc.GLProgram._highpSupported = highp.precision !== 0; } return cc.GLProgram._highpSupported; }; diff --git a/cocos2d/shaders/CCGLStateCache.js b/cocos2d/shaders/CCGLStateCache.js index 9fac3b5998..f048ce03e3 100644 --- a/cocos2d/shaders/CCGLStateCache.js +++ b/cocos2d/shaders/CCGLStateCache.js @@ -240,7 +240,7 @@ cc.glBindTexture2D = function (textureId) { * @param {cc.Texture2D} textureId */ cc.glBindTexture2DN = function (textureUnit, textureId) { - if (cc._currentBoundTexture[textureUnit] == textureId) + if (cc._currentBoundTexture[textureUnit] === textureId) return; cc._currentBoundTexture[textureUnit] = textureId; @@ -281,7 +281,7 @@ cc.glDeleteTexture = function (textureId) { */ cc.glDeleteTextureN = function (textureUnit, textureId) { if (cc.ENABLE_GL_STATE_CACHE) { - if (textureId == cc._currentBoundTexture[ textureUnit ]) + if (textureId === cc._currentBoundTexture[ textureUnit ]) cc._currentBoundTexture[ textureUnit ] = -1; } cc._renderContext.deleteTexture(textureId); @@ -298,7 +298,7 @@ cc.glBindVAO = function (vaoId) { return; if (cc.ENABLE_GL_STATE_CACHE) { - if (cc._uVAO != vaoId) { + if (cc._uVAO !== vaoId) { cc._uVAO = vaoId; //TODO need fixed //glBindVertexArray(vaoId); diff --git a/cocos2d/shape-nodes/CCDrawNode.js b/cocos2d/shape-nodes/CCDrawNode.js index 9564b6bdc9..1d222cb9e7 100644 --- a/cocos2d/shape-nodes/CCDrawNode.js +++ b/cocos2d/shape-nodes/CCDrawNode.js @@ -346,7 +346,7 @@ cc.DrawNodeCanvas = cc.Node.extend(/** @lends cc.DrawNode# */{ for (var i = 0; i < segments + 1; i++) { var dt = i / segments; // border - if (dt == 1) { + if (dt === 1) { p = config.length - 1; lt = 1; } else { @@ -632,7 +632,7 @@ cc.DrawNodeWebGL = cc.Node.extend({ var dt = i / segments; // border - if (dt == 1) { + if (dt === 1) { p = config.length - 1; lt = 1; } else { @@ -722,7 +722,7 @@ cc.DrawNodeWebGL = cc.Node.extend({ }, drawDots: function(points, radius,color) { - if(!points || points.length == 0) + if(!points || points.length === 0) return; color = color || this.getDrawColor(); if (color.a == null) @@ -911,7 +911,7 @@ cc.DrawNodeWebGL = cc.Node.extend({ } }); -cc.DrawNode = cc._renderType == cc._RENDER_TYPE_WEBGL ? cc.DrawNodeWebGL : cc.DrawNodeCanvas; +cc.DrawNode = cc._renderType === cc._RENDER_TYPE_WEBGL ? cc.DrawNodeWebGL : cc.DrawNodeCanvas; /** * Creates a DrawNode diff --git a/cocos2d/shape-nodes/CCDrawNodeCanvasRenderCmd.js b/cocos2d/shape-nodes/CCDrawNodeCanvasRenderCmd.js index a9b99147af..8631e70a71 100644 --- a/cocos2d/shape-nodes/CCDrawNodeCanvasRenderCmd.js +++ b/cocos2d/shape-nodes/CCDrawNodeCanvasRenderCmd.js @@ -45,7 +45,7 @@ //context.save(); wrapper.setGlobalAlpha(alpha); - if ((this._blendFunc && (this._blendFunc.src == cc.SRC_ALPHA) && (this._blendFunc.dst == cc.ONE))) + if ((this._blendFunc && (this._blendFunc.src === cc.SRC_ALPHA) && (this._blendFunc.dst === cc.ONE))) wrapper.setCompositeOperation('lighter'); //todo: need refactor var locBuffer = this._buffer; for (var i = 0, len = locBuffer.length; i < len; i++) { diff --git a/cocos2d/text-input/CCIMEDispatcher.js b/cocos2d/text-input/CCIMEDispatcher.js index 61786c3444..56c08d3204 100644 --- a/cocos2d/text-input/CCIMEDispatcher.js +++ b/cocos2d/text-input/CCIMEDispatcher.js @@ -178,7 +178,7 @@ cc.IMEDispatcher = cc.Class.extend(/** @lends cc.imeDispatcher# */{ if (e.keyCode === cc.KEY.tab) { e.stopPropagation(); e.preventDefault(); - } else if (e.keyCode == cc.KEY.enter) { + } else if (e.keyCode === cc.KEY.enter) { selfPointer.dispatchInsertText("\n", 1); e.stopPropagation(); e.preventDefault(); @@ -187,7 +187,7 @@ cc.IMEDispatcher = cc.Class.extend(/** @lends cc.imeDispatcher# */{ if (/msie/i.test(navigator.userAgent)) { cc._addEventListener(this._domInputControl, "keyup", function (e) { - if (e.keyCode == cc.KEY.backspace) { + if (e.keyCode === cc.KEY.backspace) { selfPointer._processDomInputString(selfPointer._domInputControl.value); } }, false); @@ -353,7 +353,7 @@ cc.IMEDispatcher = cc.Class.extend(/** @lends cc.imeDispatcher# */{ return false; // if delegate is not in delegate list, return - if (this.impl._delegateList.indexOf(delegate) == -1) + if (this.impl._delegateList.indexOf(delegate) === -1) return false; if (this.impl._delegateWithIme) { @@ -423,7 +423,7 @@ cc.IMEDispatcher = cc.Class.extend(/** @lends cc.imeDispatcher# */{ return false; // if delegate is not the current delegate attached with ime, return - if (this.impl._delegateWithIme != delegate) + if (this.impl._delegateWithIme !== delegate) return false; if (!delegate.canDetachWithIME()) @@ -447,11 +447,11 @@ cc.IMEDispatcher = cc.Class.extend(/** @lends cc.imeDispatcher# */{ return; // if delegate is not in delegate list, return - if (this.impl._delegateList.indexOf(delegate) == -1) + if (this.impl._delegateList.indexOf(delegate) === -1) return; if (this.impl._delegateWithIme) { - if (delegate == this.impl._delegateWithIme) { + if (delegate === this.impl._delegateWithIme) { this.impl._delegateWithIme = null; } } @@ -469,13 +469,13 @@ cc.IMEDispatcher = cc.Class.extend(/** @lends cc.imeDispatcher# */{ */ processKeycode:function (keyCode) { if (keyCode < 32) { - if (keyCode == cc.KEY.backspace) { + if (keyCode === cc.KEY.backspace) { this.dispatchDeleteBackward(); - } else if (keyCode == cc.KEY.enter) { + } else if (keyCode === cc.KEY.enter) { this.dispatchInsertText("\n", 1); - } else if (keyCode == cc.KEY.tab) { + } else if (keyCode === cc.KEY.tab) { //tab input - } else if (keyCode == cc.KEY.escape) { + } else if (keyCode === cc.KEY.escape) { //ESC input } } else if (keyCode < 255) { @@ -509,7 +509,7 @@ cc.IMEDispatcher.Impl = cc.Class.extend(/** @lends cc.IMEDispatcher.Impl# */{ */ findDelegate:function (delegate) { for (var i = 0; i < this._delegateList.length; i++) { - if (this._delegateList[i] == delegate) + if (this._delegateList[i] === delegate) return i; } return null; diff --git a/cocos2d/text-input/CCTextFieldTTF.js b/cocos2d/text-input/CCTextFieldTTF.js index 2624093618..3628df9e9a 100644 --- a/cocos2d/text-input/CCTextFieldTTF.js +++ b/cocos2d/text-input/CCTextFieldTTF.js @@ -356,7 +356,7 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ */ deleteBackward:function () { var strLen = this._inputText.length; - if (strLen == 0) + if (strLen === 0) return; // get the delete byte number @@ -413,7 +413,7 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ this.string = sText; } - if (pos == -1) + if (pos === -1) return; // '\n' has inserted, let delegate process first diff --git a/cocos2d/tilemap/CCTGAlib.js b/cocos2d/tilemap/CCTGAlib.js index 3bca0832f7..60a8672ca4 100644 --- a/cocos2d/tilemap/CCTGAlib.js +++ b/cocos2d/tilemap/CCTGAlib.js @@ -212,10 +212,10 @@ cc.tgaLoadRLEImageData = function (buffer, bufSize, psInfo) { for (i = 0; i < total; i++) { // if we have a run length pending, run it - if (runlength != 0) { + if (runlength !== 0) { // we do, update the run length count runlength--; - skip = (flag != 0); + skip = (flag !== 0); } else { // otherwise, read in the run length token if (step + 1 > bufSize) @@ -352,7 +352,7 @@ cc.BinaryStreamReader = cc.Class.extend({ this._offset += size; - return exponent == (bias << 1) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity + return exponent === (bias << 1) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : (1 + signal * -2) * (exponent || significand ? !exponent ? Math.pow(2, -bias + 1) * significand : Math.pow(2, exponent - bias) * (1 + significand) : 0); }, @@ -370,7 +370,7 @@ cc.BinaryStreamReader = cc.Class.extend({ }, _shl:function (a, b) { - for (++b; --b; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1){}; + for (++b; --b; a = ((a %= 0x7fffffff + 1) & 0x40000000) === 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1){}; return a; }, diff --git a/cocos2d/tilemap/CCTMXLayer.js b/cocos2d/tilemap/CCTMXLayer.js index c2e763ac64..9491fb6b70 100644 --- a/cocos2d/tilemap/CCTMXLayer.js +++ b/cocos2d/tilemap/CCTMXLayer.js @@ -452,7 +452,7 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ var currentFlags = this.getTileFlagsAt(pos); var currentGID = this.getTileGIDAt(pos); - if (currentGID != gid || currentFlags != flags) { + if (currentGID !== gid || currentFlags !== flags) { var gidAndFlags = (gid | flags) >>> 0; // setting gid=0 is equal to remove the tile if (gid === 0) @@ -662,7 +662,7 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ }, _positionForHexAt:function (pos) { - var diffY = (pos.x % 2 == 1) ? (-this._mapTileSize.height / 2) : 0; + var diffY = (pos.x % 2 === 1) ? (-this._mapTileSize.height / 2) : 0; return cc.p(pos.x * this._mapTileSize.width * 3 / 4, (this._layerSize.height - pos.y - 1) * this._mapTileSize.height + diffY); }, @@ -762,7 +762,7 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ // if cc_vertex=automatic, then tiles will be rendered using vertexz var vertexz = this.getProperty("cc_vertexz"); if (vertexz) { - if (vertexz == "automatic") { + if (vertexz === "automatic") { this._useAutomaticVertexZ = true; var alphaFuncVal = this.getProperty("cc_alpha_func"); var alphaFuncValue = 0; @@ -809,11 +809,11 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ var flag = (gid & (cc.TMX_TILE_HORIZONTAL_FLAG | cc.TMX_TILE_VERTICAL_FLAG) >>> 0) >>> 0; // handle the 4 diagonally flipped states. - if (flag == cc.TMX_TILE_HORIZONTAL_FLAG) + if (flag === cc.TMX_TILE_HORIZONTAL_FLAG) sprite.rotation = 90; - else if (flag == cc.TMX_TILE_VERTICAL_FLAG) + else if (flag === cc.TMX_TILE_VERTICAL_FLAG) sprite.rotation = 270; - else if (flag == (cc.TMX_TILE_VERTICAL_FLAG | cc.TMX_TILE_HORIZONTAL_FLAG) >>> 0) { + else if (flag === (cc.TMX_TILE_VERTICAL_FLAG | cc.TMX_TILE_HORIZONTAL_FLAG) >>> 0) { sprite.rotation = 90; sprite.setFlippedX(true); } else { @@ -861,7 +861,7 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ var locAtlasIndexArray = this._atlasIndexArray; for (var i = 0, len = locAtlasIndexArray.length; i < len; i++) { item = locAtlasIndexArray[i]; - if (item == z) + if (item === z) break; } } diff --git a/cocos2d/tilemap/CCTMXObjectGroup.js b/cocos2d/tilemap/CCTMXObjectGroup.js index 7bfcafbe32..560c690afe 100644 --- a/cocos2d/tilemap/CCTMXObjectGroup.js +++ b/cocos2d/tilemap/CCTMXObjectGroup.js @@ -131,7 +131,7 @@ cc.TMXObjectGroup = cc.Class.extend(/** @lends cc.TMXObjectGroup# */{ var locObjects = this._objects; for (var i = 0, len = locObjects.length; i < len; i++) { var name = locObjects[i]["name"]; - if (name && name == objectName) + if (name && name === objectName) return locObjects[i]; } } diff --git a/cocos2d/tilemap/CCTMXTiledMap.js b/cocos2d/tilemap/CCTMXTiledMap.js index 2344cdb9fc..97165dd3b2 100644 --- a/cocos2d/tilemap/CCTMXTiledMap.js +++ b/cocos2d/tilemap/CCTMXTiledMap.js @@ -269,7 +269,7 @@ cc.TMXTiledMap = cc.Node.extend(/** @lends cc.TMXTiledMap# */{ * map.initWithTMXFile("hello.tmx"); */ initWithTMXFile:function (tmxFile) { - if(!tmxFile || tmxFile.length == 0) + if(!tmxFile || tmxFile.length === 0) throw "cc.TMXTiledMap.initWithTMXFile(): tmxFile should be non-null or non-empty string."; this.width = 0; this.height = 0; @@ -353,7 +353,7 @@ cc.TMXTiledMap = cc.Node.extend(/** @lends cc.TMXTiledMap# */{ var locChildren = this._children; for (var i = 0; i < locChildren.length; i++) { var layer = locChildren[i]; - if (layer && layer.layerName == layerName) + if (layer && layer.layerName === layerName) return layer; } // layer not found @@ -371,7 +371,7 @@ cc.TMXTiledMap = cc.Node.extend(/** @lends cc.TMXTiledMap# */{ if (this.objectGroups) { for (var i = 0; i < this.objectGroups.length; i++) { var objectGroup = this.objectGroups[i]; - if (objectGroup && objectGroup.groupName == groupName) { + if (objectGroup && objectGroup.groupName === groupName) { return objectGroup; } } @@ -429,7 +429,7 @@ cc.TMXTiledMap = cc.Node.extend(/** @lends cc.TMXTiledMap# */{ for (var x = 0; x < size.width; x++) { var pos = x + size.width * y; var gid = layerInfo._tiles[pos]; - if (gid != 0) { + if (gid !== 0) { // Optimization: quick return // if the layer is invalid (more than 1 tileset per layer) an cc.assert will be thrown later if (((gid & cc.TMX_TILE_FLIPPED_MASK)>>>0) >= tileset.firstGid) { diff --git a/cocos2d/tilemap/CCTMXXMLParser.js b/cocos2d/tilemap/CCTMXXMLParser.js index bae661de31..478db3f2ef 100644 --- a/cocos2d/tilemap/CCTMXXMLParser.js +++ b/cocos2d/tilemap/CCTMXXMLParser.js @@ -542,15 +542,15 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ var version = map.getAttribute('version'); var orientationStr = map.getAttribute('orientation'); - if (map.nodeName == "map") { - if (version != "1.0" && version !== null) + if (map.nodeName === "map") { + if (version !== "1.0" && version !== null) cc.log("cocos2d: TMXFormat: Unsupported TMX version:" + version); - if (orientationStr == "orthogonal") + if (orientationStr === "orthogonal") this.orientation = cc.TMX_ORIENTATION_ORTHO; - else if (orientationStr == "isometric") + else if (orientationStr === "isometric") this.orientation = cc.TMX_ORIENTATION_ISO; - else if (orientationStr == "hexagonal") + else if (orientationStr === "hexagonal") this.orientation = cc.TMX_ORIENTATION_HEX; else if (orientationStr !== null) cc.log("cocos2d: TMXFomat: Unsupported orientation:" + orientationStr); @@ -693,7 +693,7 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ case null: case '': // Uncompressed - if (encoding == "base64") + if (encoding === "base64") layer._tiles = cc.Codec.Base64.decodeAsArray(nodeValue, 4); else if (encoding === "csv") { layer._tiles = []; @@ -709,7 +709,7 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ } break; default: - if(this.layerAttrs == cc.TMXLayerInfo.ATTRIB_NONE) + if(this.layerAttrs === cc.TMXLayerInfo.ATTRIB_NONE) cc.log("cc.TMXMapInfo.parseXMLFile(): Only base64 and/or gzip/zlib maps are supported"); break; } diff --git a/cocos2d/transitions/CCTransition.js b/cocos2d/transitions/CCTransition.js index 07a5bd7e8e..f5ccb82cfe 100644 --- a/cocos2d/transitions/CCTransition.js +++ b/cocos2d/transitions/CCTransition.js @@ -195,7 +195,7 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{ this._outScene.init(); } - if(this._inScene == this._outScene) + if(this._inScene === this._outScene) throw "cc.TransitionScene.initWithDuration(): Incoming scene must be different from the outgoing scene"; this._sceneOrder(); @@ -1019,7 +1019,7 @@ cc.TransitionFlipY = cc.TransitionSceneOriented.extend(/** @lends cc.TransitionF var inDeltaZ, inAngleZ, outDeltaZ, outAngleZ; - if (this._orientation == cc.TRANSITION_ORIENTATION_UP_OVER) { + if (this._orientation === cc.TRANSITION_ORIENTATION_UP_OVER) { inDeltaZ = 90; inAngleZ = 270; outDeltaZ = 90; @@ -1495,9 +1495,6 @@ cc.TransitionCrossFade = cc.TransitionScene.extend(/** @lends cc.TransitionCross // create the first render texture for inScene var inTexture = new cc.RenderTexture(winSize.width, winSize.height); - if (null == inTexture) - return; - inTexture.sprite.anchorX = 0.5; inTexture.sprite.anchorY = 0.5; inTexture.attr({ diff --git a/cocos2d/transitions/CCTransitionProgress.js b/cocos2d/transitions/CCTransitionProgress.js index ab128091c8..803fe4d20f 100644 --- a/cocos2d/transitions/CCTransitionProgress.js +++ b/cocos2d/transitions/CCTransitionProgress.js @@ -89,7 +89,7 @@ cc.TransitionProgress = cc.TransitionScene.extend(/** @lends cc.TransitionProgre texture.end(); // Since we've passed the outScene to the texture we don't need it. - if (this._sceneToBeModified == this._outScene) + if (this._sceneToBeModified === this._outScene) this.hideOutShowIn(); // We need the texture in RenderTexture. @@ -245,7 +245,7 @@ cc.TransitionProgressRadialCW = cc.TransitionProgress.extend(/** @lends cc.Trans */ cc.TransitionProgressRadialCW.create = function (t, scene) { var tempScene = new cc.TransitionProgressRadialCW(); - if ((tempScene != null) && (tempScene.initWithDuration(t, scene))) { + if ((tempScene !== null) && (tempScene.initWithDuration(t, scene))) { return tempScene; } return new cc.TransitionProgressRadialCW(t, scene); diff --git a/extensions/ccb-reader/CCBAnimationManager.js b/extensions/ccb-reader/CCBAnimationManager.js index 0b8e9cdfbc..8952fc9de7 100644 --- a/extensions/ccb-reader/CCBAnimationManager.js +++ b/extensions/ccb-reader/CCBAnimationManager.js @@ -205,7 +205,7 @@ cc.BuilderAnimationManager = cc.Class.extend({ // Move base values var locBaseValues = this._baseValues; var baseValue = locBaseValues.objectForKey(fromNode); - if(baseValue != null) { + if(baseValue !== null) { locBaseValues.setObject(baseValue, toNode); locBaseValues.removeObjectForKey(fromNode); } @@ -246,20 +246,18 @@ cc.BuilderAnimationManager = cc.Class.extend({ actions.push(callback); } else { var target; - if(selectorTarget == CCB_TARGETTYPE_DOCUMENTROOT) + if(selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT) target = this._rootNode; - else if (selectorTarget == CCB_TARGETTYPE_OWNER) + else if (selectorTarget === CCB_TARGETTYPE_OWNER) target = this._owner; if(target != null) { if(selectorName.length > 0) { var selCallFunc = 0; - var targetAsCCBSelectorResolver = target; - if(target.onResolveCCBCCCallFuncSelector != null) - selCallFunc = targetAsCCBSelectorResolver.onResolveCCBCCCallFuncSelector(target, selectorName); - if(selCallFunc == 0) + selCallFunc = target.onResolveCCBCCCallFuncSelector(target, selectorName); + if(selCallFunc === 0) cc.log("Skipping selector '" + selectorName + "' since no CCBSelectorResolver is present."); else actions.push(cc.callFunc(selCallFunc,target)); @@ -342,7 +340,7 @@ cc.BuilderAnimationManager = cc.Class.extend({ var baseKeys = nodeBaseValues.allKeys(); for(j = 0; j < baseKeys.length;j++){ var selBaseKey = baseKeys[j]; - if(seqNodePropNames.indexOf(selBaseKey) == -1){ + if(seqNodePropNames.indexOf(selBaseKey) === -1){ var value = nodeBaseValues.objectForKey(selBaseKey); if(value != null) this._setAnimatedProperty(selBaseKey,node, value, tweenDuration); @@ -539,10 +537,10 @@ cc.BuilderAnimationManager = cc.Class.extend({ // TODO only handle rotation, opacity, displayFrame, color if(propName === "rotation"){ node.setRotation(value); - } else if(propName == "rotationX") + } else if(propName === "rotationX") { node.setRotationSkewX(value); - }else if(propName == "rotationY") + }else if(propName === "rotationY") { node.setRotationSkewY(value); }else if(propName === "opacity"){ @@ -656,7 +654,7 @@ cc.BuilderAnimationManager = cc.Class.extend({ var nextSeqId = locRunningSequence.getChainedSequenceId(); this._runningSequence = null; - if (nextSeqId != -1) + if (nextSeqId !== -1) this.runAnimations(nextSeqId, 0); if (this._delegate) diff --git a/extensions/ccb-reader/CCBReader.js b/extensions/ccb-reader/CCBReader.js index cde09e6f92..e22f54decf 100644 --- a/extensions/ccb-reader/CCBReader.js +++ b/extensions/ccb-reader/CCBReader.js @@ -159,7 +159,7 @@ cc.BuilderReader = cc.Class.extend({ this._currentBit = -1; this._currentByte = -1; - if (arguments.length != 0) { + if (arguments.length !== 0) { if (ccNodeLoaderLibrary instanceof cc.BuilderReader) { var ccbReader = ccNodeLoaderLibrary; @@ -222,7 +222,7 @@ cc.BuilderReader = cc.Class.extend({ if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) { req.setRequestHeader("Accept-Charset", "x-user-defined"); req.send(null); - if (req.status != 200) { + if (req.status !== 200) { cc.log(errInfo); return null; } @@ -236,7 +236,7 @@ cc.BuilderReader = cc.Class.extend({ if (req.overrideMimeType) req.overrideMimeType('text\/plain; charset=x-user-defined'); req.send(null); - if (req.status != 200) { + if (req.status !== 200) { cc.log(errInfo); return null; } @@ -280,7 +280,7 @@ cc.BuilderReader = cc.Class.extend({ var nodeGraph = this.readFileWithCleanUp(true); - if (nodeGraph && locAnimationManager.getAutoPlaySequenceId() != -1) { + if (nodeGraph && locAnimationManager.getAutoPlaySequenceId() !== -1) { //auto play animations locAnimationManager.runAnimations(locAnimationManager.getAutoPlaySequenceId(), 0); } @@ -376,7 +376,7 @@ cc.BuilderReader = cc.Class.extend({ }, readBool:function () { - return (0 != this.readByte()); + return (0 !== this.readByte()); }, readFloat:function () { @@ -428,7 +428,7 @@ cc.BuilderReader = cc.Class.extend({ this._currentByte += size; - return exponent == (bias << 1) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity + return exponent === (bias << 1) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : (1 + signal * -2) * (exponent || significand ? !exponent ? Math.pow(2, -bias + 1) * significand : Math.pow(2, exponent - bias) * (1 + significand) : 0); }, @@ -458,7 +458,7 @@ cc.BuilderReader = cc.Class.extend({ }, _shl:function (a, b) { - for (++b; --b; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1); + for (++b; --b; a = ((a %= 0x7fffffff + 1) & 0x40000000) === 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1); return a; }, @@ -669,24 +669,24 @@ cc.BuilderReader = cc.Class.extend({ keyframe.setEasingType(easingType); keyframe.setEasingOpt(easingOpt); - if (type == CCB_PROPTYPE_CHECK) { + if (type === CCB_PROPTYPE_CHECK) { value = this.readBool(); - } else if (type == CCB_PROPTYPE_BYTE) { + } else if (type === CCB_PROPTYPE_BYTE) { value = this.readByte(); - } else if (type == CCB_PROPTYPE_COLOR3) { + } else if (type === CCB_PROPTYPE_COLOR3) { var c = cc.color(this.readByte(), this.readByte(), this.readByte()); value = cc.Color3BWapper.create(c); - } else if (type == CCB_PROPTYPE_FLOATXY) { + } else if (type === CCB_PROPTYPE_FLOATXY) { value = [this.readFloat(), this.readFloat()]; - } else if (type == CCB_PROPTYPE_DEGREES) { + } else if (type === CCB_PROPTYPE_DEGREES) { value = this.readFloat(); - } else if (type == CCB_PROPTYPE_SCALELOCK || type == CCB_PROPTYPE_POSITION || type == CCB_PROPTYPE_FLOATXY) { + } else if (type === CCB_PROPTYPE_SCALELOCK || type === CCB_PROPTYPE_POSITION || type === CCB_PROPTYPE_FLOATXY) { value = [this.readFloat(), this.readFloat()]; - } else if (type == CCB_PROPTYPE_SPRITEFRAME) { + } else if (type === CCB_PROPTYPE_SPRITEFRAME) { var spriteSheet = this.readCachedString(); var spriteFile = this.readCachedString(); - if (spriteSheet == "") { + if (spriteSheet === "") { spriteFile = this._ccbRootPath + spriteFile; var texture = cc.textureCache.addImage(spriteFile); var locContentSize = texture.getContentSize(); @@ -696,7 +696,7 @@ cc.BuilderReader = cc.Class.extend({ spriteSheet = this._ccbRootPath + spriteSheet; var frameCache = cc.spriteFrameCache; // Load the sprite sheet only if it is not loaded - if (this._loadedSpriteSheets.indexOf(spriteSheet) == -1) { + if (this._loadedSpriteSheets.indexOf(spriteSheet) === -1) { frameCache.addSpriteFrames(spriteSheet); this._loadedSpriteSheets.push(spriteSheet); } @@ -709,7 +709,7 @@ cc.BuilderReader = cc.Class.extend({ _readHeader:function () { /* If no bytes loaded, don't crash about it. */ - if (this._data == null) { + if (this._data === null) { return false; } @@ -717,13 +717,13 @@ cc.BuilderReader = cc.Class.extend({ var magicBytes = this._readStringFromBytes(this._currentByte, 4, true); this._currentByte += 4; - if (magicBytes != 'ccbi') { + if (magicBytes !== 'ccbi') { return false; } /* Read version. */ var version = this.readInt(false); - if (version != CCB_VERSION) { + if (version !== CCB_VERSION) { cc.log("WARNING! Incompatible ccbi file version (file: " + version + " reader: " + CCB_VERSION + ")"); return false; } @@ -783,7 +783,7 @@ cc.BuilderReader = cc.Class.extend({ var memberVarAssignmentType = this.readInt(false); var memberVarAssignmentName; - if (memberVarAssignmentType != CCB_TARGETTYPE_NONE) { + if (memberVarAssignmentType !== CCB_TARGETTYPE_NONE) { memberVarAssignmentName = this.readCachedString(); } @@ -799,7 +799,7 @@ cc.BuilderReader = cc.Class.extend({ if (!locActionManager.getRootNode()) locActionManager.setRootNode(node); - if (locJsControlled && node == locActionManager.getRootNode()) { + if (locJsControlled && node === locActionManager.getRootNode()) { locActionManager.setDocumentControllerName(jsControlledName); } @@ -855,7 +855,7 @@ cc.BuilderReader = cc.Class.extend({ node = embeddedNode; } var target = null, locMemberAssigner = null; - if (memberVarAssignmentType != CCB_TARGETTYPE_NONE) { + if (memberVarAssignmentType !== CCB_TARGETTYPE_NONE) { if (!locJsControlled) { if (memberVarAssignmentType === CCB_TARGETTYPE_DOCUMENTROOT) { target = locActionManager.getRootNode(); @@ -863,10 +863,10 @@ cc.BuilderReader = cc.Class.extend({ target = this._owner; } - if (target != null) { + if (target !== null) { var assigned = false; - if (target != null && (target.onAssignCCBMemberVariable)) { + if (target.onAssignCCBMemberVariable) { assigned = target.onAssignCCBMemberVariable(target, memberVarAssignmentName, node); } locMemberAssigner = this._ccbMemberVariableAssigner; @@ -875,7 +875,7 @@ cc.BuilderReader = cc.Class.extend({ } } } else { - if (memberVarAssignmentType == CCB_TARGETTYPE_DOCUMENTROOT) { + if (memberVarAssignmentType === CCB_TARGETTYPE_DOCUMENTROOT) { locActionManager.addDocumentOutletName(memberVarAssignmentName); locActionManager.addDocumentOutletNode(node); } else { @@ -928,8 +928,7 @@ cc.BuilderReader = cc.Class.extend({ }, _getBit:function () { - var bit = (this._data[this._currentByte] & (1 << this._currentBit)) != 0; - + var bit = (this._data[this._currentByte] & (1 << this._currentBit)) !== 0; this._currentBit++; if (this._currentBit >= 8) { @@ -938,7 +937,6 @@ cc.BuilderReader = cc.Class.extend({ if(this._currentByte > this._data.length) throw "out of the data bound"; } - return bit; }, @@ -980,7 +978,7 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) { ccbRootPath = ccbRootPath || cc.BuilderReader.getResourcePath(); var reader = new cc.BuilderReader(cc.NodeLoaderLibrary.newDefaultCCNodeLoaderLibrary()); reader.setCCBRootPath(ccbRootPath); - if((ccbFilePath.length < 5)||(ccbFilePath.toLowerCase().lastIndexOf(".ccbi") != ccbFilePath.length - 5)) + if((ccbFilePath.length < 5)||(ccbFilePath.toLowerCase().lastIndexOf(".ccbi") !== ccbFilePath.length - 5)) ccbFilePath = ccbFilePath + ".ccbi"; var node = reader.readNodeGraphFromFile(ccbFilePath, owner, parentSize); @@ -1072,9 +1070,9 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) { var callbackType = callbackSplit[0]; var kfCallbackName = callbackSplit[1]; - if (callbackType == 1){ // Document callback + if (callbackType === 1){ // Document callback animationManager.setCallFunc(cc.callFunc(controller[kfCallbackName], controller), keyframeCallbacks[j]); - } else if (callbackType == 2 && owner) {// Owner callback + } else if (callbackType === 2 && owner) {// Owner callback animationManager.setCallFunc(cc.callFunc(owner[kfCallbackName], owner), keyframeCallbacks[j]); } } @@ -1097,7 +1095,7 @@ cc.BuilderReader.getResourcePath = function () { cc.BuilderReader.lastPathComponent = function (pathStr) { var slashPos = pathStr.lastIndexOf("/"); - if (slashPos != -1) { + if (slashPos !== -1) { return pathStr.substring(slashPos + 1, pathStr.length - slashPos); } return pathStr; @@ -1105,7 +1103,7 @@ cc.BuilderReader.lastPathComponent = function (pathStr) { cc.BuilderReader.deletePathExtension = function (pathStr) { var dotPos = pathStr.lastIndexOf("."); - if (dotPos != -1) { + if (dotPos !== -1) { return pathStr.substring(0, dotPos); } return pathStr; @@ -1117,7 +1115,7 @@ cc.BuilderReader.toLowerCase = function (sourceStr) { cc.BuilderReader.endsWith = function (sourceStr, ending) { if (sourceStr.length >= ending.length) - return (sourceStr.lastIndexOf(ending) == 0); + return (sourceStr.lastIndexOf(ending) === 0); else return false; }; diff --git a/extensions/ccb-reader/CCControlLoader.js b/extensions/ccb-reader/CCControlLoader.js index 7e0bf1e499..901f8509dd 100644 --- a/extensions/ccb-reader/CCControlLoader.js +++ b/extensions/ccb-reader/CCControlLoader.js @@ -31,7 +31,7 @@ cc.BuilderFileLoader = cc.NodeLoader.extend({ return cc.BuilderFile.create(); }, onHandlePropTypeCCBFile:function (node, parent, propertyName, ccbFileNode, ccbReader) { - if (propertyName == PROPERTY_CCBFILE) { + if (propertyName === PROPERTY_CCBFILE) { node.setCCBFileNode(ccbFileNode); } else { cc.NodeLoader.prototype.onHandlePropTypeCCBFile.call(this, node, parent, propertyName, ccbFileNode, ccbReader); @@ -51,16 +51,16 @@ cc.ControlLoader = cc.NodeLoader.extend({ _createCCNode:function (parent, ccbReander) { }, onHandlePropTypeBlockCCControl:function (node, parent, propertyName, blockCCControlData, ccbReader) { - if (propertyName == PROPERTY_CCCONTROL) { + if (propertyName === PROPERTY_CCCONTROL) { node.addTargetWithActionForControlEvents(blockCCControlData.target, blockCCControlData.selCCControlHandler, blockCCControlData.controlEvents); } else { cc.NodeLoader.prototype.onHandlePropTypeBlockCCControl.call(this, node, parent, propertyName, blockCCControlData, ccbReader); } }, onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) { - if (propertyName == PROPERTY_ENABLED) { + if (propertyName === PROPERTY_ENABLED) { node.setEnabled(check); - } else if (propertyName == PROPERTY_SELECTED) { + } else if (propertyName === PROPERTY_SELECTED) { node.setSelected(check); } else { cc.NodeLoader.prototype.onHandlePropTypeCheck.call(this, node, parent, propertyName, check, ccbReader); @@ -93,69 +93,69 @@ cc.ControlButtonLoader = cc.ControlLoader.extend({ }, onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) { - if (propertyName == PROPERTY_ZOOMONTOUCHDOWN) { + if (propertyName === PROPERTY_ZOOMONTOUCHDOWN) { node.setZoomOnTouchDown(check); } else { cc.ControlLoader.prototype.onHandlePropTypeCheck.call(this, node, parent, propertyName, check, ccbReader); } }, onHandlePropTypeString:function (node, parent, propertyName, stringValue, ccbReader) { - if (propertyName == PROPERTY_TITLE_NORMAL) { + if (propertyName === PROPERTY_TITLE_NORMAL) { node.setTitleForState(stringValue, cc.CONTROL_STATE_NORMAL); - } else if (propertyName == PROPERTY_TITLE_HIGHLIGHTED) { + } else if (propertyName === PROPERTY_TITLE_HIGHLIGHTED) { node.setTitleForState(stringValue, cc.CONTROL_STATE_HIGHLIGHTED); - } else if (propertyName == PROPERTY_TITLE_DISABLED) { + } else if (propertyName === PROPERTY_TITLE_DISABLED) { node.setTitleForState(stringValue, cc.CONTROL_STATE_DISABLED); } else { cc.ControlLoader.prototype.onHandlePropTypeString.call(this, node, parent, propertyName, stringValue, ccbReader); } }, onHandlePropTypeFontTTF:function (node, parent, propertyName, fontTTF, ccbReader) { - if (propertyName == PROPERTY_TITLETTF_NORMAL) { + if (propertyName === PROPERTY_TITLETTF_NORMAL) { node.setTitleTTFForState(fontTTF, cc.CONTROL_STATE_NORMAL); - } else if (propertyName == PROPERTY_TITLETTF_HIGHLIGHTED) { + } else if (propertyName === PROPERTY_TITLETTF_HIGHLIGHTED) { node.setTitleTTFForState(fontTTF, cc.CONTROL_STATE_HIGHLIGHTED); - } else if (propertyName == PROPERTY_TITLETTF_DISABLED) { + } else if (propertyName === PROPERTY_TITLETTF_DISABLED) { node.setTitleTTFForState(fontTTF, cc.CONTROL_STATE_DISABLED); } else { cc.ControlLoader.prototype.onHandlePropTypeFontTTF.call(this, node, parent, propertyName, fontTTF, ccbReader); } }, onHandlePropTypeFloatScale:function (node, parent, propertyName, floatScale, ccbReader) { - if (propertyName == PROPERTY_TITLETTFSIZE_NORMAL) { + if (propertyName === PROPERTY_TITLETTFSIZE_NORMAL) { node.setTitleTTFSizeForState(floatScale, cc.CONTROL_STATE_NORMAL); - } else if (propertyName == PROPERTY_TITLETTFSIZE_HIGHLIGHTED) { + } else if (propertyName === PROPERTY_TITLETTFSIZE_HIGHLIGHTED) { node.setTitleTTFSizeForState(floatScale, cc.CONTROL_STATE_HIGHLIGHTED); - } else if (propertyName == PROPERTY_TITLETTFSIZE_DISABLED) { + } else if (propertyName === PROPERTY_TITLETTFSIZE_DISABLED) { node.setTitleTTFSizeForState(floatScale, cc.CONTROL_STATE_DISABLED); } else { cc.ControlLoader.prototype.onHandlePropTypeFloatScale.call(this, node, parent, propertyName, floatScale, ccbReader); } }, onHandlePropTypePoint:function (node, parent, propertyName, point, ccbReader) { - if (propertyName == PROPERTY_LABELANCHORPOINT) { + if (propertyName === PROPERTY_LABELANCHORPOINT) { node.setLabelAnchorPoint(point); } else { cc.ControlLoader.prototype.onHandlePropTypePoint.call(this, node, parent, propertyName, point, ccbReader); } }, onHandlePropTypeSize:function (node, parent, propertyName, size, ccbReader) { - if (propertyName == PROPERTY_PREFEREDSIZE) { + if (propertyName === PROPERTY_PREFEREDSIZE) { node.setPreferredSize(size); } else { cc.ControlLoader.prototype.onHandlePropTypeSize.call(this, node, parent, propertyName, size, ccbReader); } }, onHandlePropTypeSpriteFrame:function (node, parent, propertyName, spriteFrame, ccbReader) { - if (propertyName == PROPERTY_BACKGROUNDSPRITEFRAME_NORMAL) { + if (propertyName === PROPERTY_BACKGROUNDSPRITEFRAME_NORMAL) { if (spriteFrame != null) { node.setBackgroundSpriteFrameForState(spriteFrame, cc.CONTROL_STATE_NORMAL); } - } else if (propertyName == PROPERTY_BACKGROUNDSPRITEFRAME_HIGHLIGHTED) { + } else if (propertyName === PROPERTY_BACKGROUNDSPRITEFRAME_HIGHLIGHTED) { if (spriteFrame != null) { node.setBackgroundSpriteFrameForState(spriteFrame, cc.CONTROL_STATE_HIGHLIGHTED); } - } else if (propertyName == PROPERTY_BACKGROUNDSPRITEFRAME_DISABLED) { + } else if (propertyName === PROPERTY_BACKGROUNDSPRITEFRAME_DISABLED) { if (spriteFrame != null) { node.setBackgroundSpriteFrameForState(spriteFrame, cc.CONTROL_STATE_DISABLED); } @@ -164,11 +164,11 @@ cc.ControlButtonLoader = cc.ControlLoader.extend({ } }, onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) { - if (propertyName == PROPERTY_TITLECOLOR_NORMAL) { + if (propertyName === PROPERTY_TITLECOLOR_NORMAL) { node.setTitleColorForState(ccColor3B, cc.CONTROL_STATE_NORMAL); - } else if (propertyName == PROPERTY_TITLECOLOR_HIGHLIGHTED) { + } else if (propertyName === PROPERTY_TITLECOLOR_HIGHLIGHTED) { node.setTitleColorForState(ccColor3B, cc.CONTROL_STATE_HIGHLIGHTED); - } else if (propertyName == PROPERTY_TITLECOLOR_DISABLED) { + } else if (propertyName === PROPERTY_TITLECOLOR_DISABLED) { node.setTitleColorForState(ccColor3B, cc.CONTROL_STATE_DISABLED); } else { cc.ControlLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, ccColor3B, ccbReader); @@ -192,7 +192,7 @@ cc.ScrollViewLoader = cc.NodeLoader.extend({ }, onHandlePropTypeSize:function(node,parent,propertyName,size,ccbReader){ - if(propertyName == PROPERTY_CONTENTSIZE){ + if(propertyName === PROPERTY_CONTENTSIZE){ node.setViewSize(size); }else{ cc.NodeLoader.prototype.onHandlePropTypeSize.call(this, node,parent,propertyName,size,ccbReader); @@ -200,7 +200,7 @@ cc.ScrollViewLoader = cc.NodeLoader.extend({ }, onHandlePropTypeCCBFile:function (node, parent, propertyName, ccbFileNode, ccbReader) { - if (propertyName == PROPERTY_CONTAINER) { + if (propertyName === PROPERTY_CONTAINER) { node.setContainer(ccbFileNode); node.updateInset(); } else { @@ -208,23 +208,23 @@ cc.ScrollViewLoader = cc.NodeLoader.extend({ } }, onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) { - if (propertyName == PROPERTY_CLIPSTOBOUNDS) { + if (propertyName === PROPERTY_CLIPSTOBOUNDS) { node.setClippingToBounds(check); - } else if (propertyName == PROPERTY_BOUNCES) { + } else if (propertyName === PROPERTY_BOUNCES) { node.setBounceable(check); } else { cc.NodeLoader.prototype.onHandlePropTypeCheck.call(this, node, parent, propertyName, check, ccbReader); } }, onHandlePropTypeFloat:function (node, parent, propertyName, floatValue, ccbReader) { - if (propertyName == PROPERTY_SCALE) { + if (propertyName === PROPERTY_SCALE) { node.setScale(floatValue); } else { cc.NodeLoader.prototype.onHandlePropTypeFloat.call(this, node, parent, propertyName, floatValue, ccbReader); } }, onHandlePropTypeIntegerLabeled:function (node, parent, propertyName, integerLabeled, ccbReader) { - if (propertyName == PROPERTY_DIRECTION) { + if (propertyName === PROPERTY_DIRECTION) { node.setDirection(integerLabeled); } else { cc.NodeLoader.prototype.onHandlePropTypeIntegerLabeled.call(this, node, parent, propertyName, integerLabeled, ccbReader); @@ -256,7 +256,7 @@ cc.Scale9SpriteLoader = cc.NodeLoader.extend({ }, onHandlePropTypeColor3:function(node, parent, propertyName, ccColor3B,ccbReader){ - if(propertyName == PROPERTY_COLOR) { + if(propertyName === PROPERTY_COLOR) { if(ccColor3B.r !== 255 || ccColor3B.g !== 255 || ccColor3B.b !== 255){ node.setColor(ccColor3B); } @@ -265,14 +265,14 @@ cc.Scale9SpriteLoader = cc.NodeLoader.extend({ } }, onHandlePropTypeByte:function(node, parent, propertyName, byteValue,ccbReader){ - if(propertyName == PROPERTY_OPACITY) { + if(propertyName === PROPERTY_OPACITY) { node.setOpacity(byteValue); } else { cc.NodeLoader.prototype.onHandlePropTypeByte.call(this, node, parent, propertyName, byteValue,ccbReader); } }, onHandlePropTypeBlendFunc:function(node, parent, propertyName, ccBlendFunc,ccbReader){ - if(propertyName == PROPERTY_BLENDFUNC) { + if(propertyName === PROPERTY_BLENDFUNC) { // TODO Not exported by CocosBuilder yet! // node.setBlendFunc(ccBlendFunc); } else { @@ -280,29 +280,29 @@ cc.Scale9SpriteLoader = cc.NodeLoader.extend({ } }, onHandlePropTypeSpriteFrame:function(node, parent, propertyName, spriteFrame,ccbReader){ - if(propertyName == PROPERTY_SPRITEFRAME) { + if(propertyName === PROPERTY_SPRITEFRAME) { node.setSpriteFrame(spriteFrame); } else { cc.NodeLoader.prototype.onHandlePropTypeSpriteFrame.call(this, node, parent, propertyName, spriteFrame,ccbReader); } }, onHandlePropTypeSize:function(node, parent, propertyName, size,ccbReader){ - if(propertyName == PROPERTY_CONTENTSIZE) { + if(propertyName === PROPERTY_CONTENTSIZE) { //node.setContentSize(size); - } else if(propertyName == PROPERTY_PREFEREDSIZE) { + } else if(propertyName === PROPERTY_PREFEREDSIZE) { node.setPreferredSize(size); } else { cc.NodeLoader.prototype.onHandlePropTypeSize.call(this, node, parent, propertyName, size,ccbReader); } }, onHandlePropTypeFloat:function(node, parent, propertyName, floatValue,ccbReader){ - if(propertyName == PROPERTY_INSETLEFT) { + if(propertyName === PROPERTY_INSETLEFT) { node.setInsetLeft(floatValue); - } else if(propertyName == PROPERTY_INSETTOP) { + } else if(propertyName === PROPERTY_INSETTOP) { node.setInsetTop(floatValue); - } else if(propertyName == PROPERTY_INSETRIGHT) { + } else if(propertyName === PROPERTY_INSETRIGHT) { node.setInsetRight(floatValue); - } else if(propertyName == PROPERTY_INSETBOTTOM) { + } else if(propertyName === PROPERTY_INSETBOTTOM) { node.setInsetBottom(floatValue); } else { cc.NodeLoader.prototype.onHandlePropTypeFloat.call(this, node, parent, propertyName, floatValue,ccbReader); diff --git a/extensions/ccb-reader/CCNodeLoader.js b/extensions/ccb-reader/CCNodeLoader.js index b00c01b377..67b575f41a 100644 --- a/extensions/ccb-reader/CCNodeLoader.js +++ b/extensions/ccb-reader/CCNodeLoader.js @@ -89,9 +89,9 @@ cc.NodeLoader = cc.Class.extend({ node = node.getCCBFileNode(); //skip properties that doesn't have a value to override var getExtraPropsNames = node.userObject; - setProp = getExtraPropsNames.indexOf(propertyName) != -1; + setProp = getExtraPropsNames.indexOf(propertyName) !== -1; } - } else if(isExtraProp && node == ccbReader.getAnimationManager().getRootNode()){ + } else if(isExtraProp && node === ccbReader.getAnimationManager().getRootNode()){ var extraPropsNames = node.userObject; if(!extraPropsNames){ extraPropsNames = []; @@ -418,7 +418,7 @@ cc.NodeLoader = cc.Class.extend({ ccbReader.getAnimationManager().setBaseValue([x,y,type],node,propertyName); } - if (type == CCB_SCALETYPE_MULTIPLY_RESOLUTION) { + if (type === CCB_SCALETYPE_MULTIPLY_RESOLUTION) { x *= cc.BuilderReader.getResolutionScale(); y *= cc.BuilderReader.getResolutionScale(); } @@ -443,7 +443,7 @@ cc.NodeLoader = cc.Class.extend({ var type = ccbReader.readInt(false); - if (type == CCB_SCALETYPE_MULTIPLY_RESOLUTION) { + if (type === CCB_SCALETYPE_MULTIPLY_RESOLUTION) { f *= cc.BuilderReader.getResolutionScale(); } @@ -477,8 +477,8 @@ cc.NodeLoader = cc.Class.extend({ var spriteFile = ccbReader.readCachedString(); var spriteFrame; - if(spriteFile != null && spriteFile.length != 0){ - if(spriteSheet.length == 0){ + if(spriteFile != null && spriteFile.length !== 0){ + if(spriteSheet.length === 0){ spriteFile = ccbReader.getCCBRootPath() + spriteFile; var texture = cc.textureCache.addImage(spriteFile); @@ -489,7 +489,7 @@ cc.NodeLoader = cc.Class.extend({ var frameCache = cc.spriteFrameCache; spriteSheet = ccbReader.getCCBRootPath() + spriteSheet; //load the sprite sheet only if it is not loaded - if(ccbReader.getLoadedSpriteSheet().indexOf(spriteSheet) == -1){ + if(ccbReader.getLoadedSpriteSheet().indexOf(spriteSheet) === -1){ frameCache.addSpriteFrames(spriteSheet); ccbReader.getLoadedSpriteSheet().push(spriteSheet); } @@ -517,7 +517,7 @@ cc.NodeLoader = cc.Class.extend({ animation = cc.BuilderReader.lastPathComponent(animation); animationFile = cc.BuilderReader.lastPathComponent(animationFile); - if (animation != null && animation != "") { + if (animation != null && animation !== "") { var animationCache = cc.animationCache; animationCache.addAnimations(animationFile); @@ -529,7 +529,7 @@ cc.NodeLoader = cc.Class.extend({ parsePropTypeTexture:function (node, parent, ccbReader) { var spriteFile = ccbReader.getCCBRootPath() + ccbReader.readCachedString(); - if(spriteFile != "") + if(spriteFile !== "") return cc.textureCache.addImage(spriteFile); return null; }, @@ -624,21 +624,21 @@ cc.NodeLoader = cc.Class.extend({ target = ccbReader.getOwner(); } - if (target != null) { + if (target !== null) { if (selectorName.length > 0) { var selMenuHandler = 0; //var targetAsCCBSelectorResolver = target; - if (target != null && target.onResolveCCBCCMenuItemSelector) + if (target.onResolveCCBCCMenuItemSelector) selMenuHandler = target.onResolveCCBCCMenuItemSelector(target, selectorName); - if (selMenuHandler == 0) { + if (selMenuHandler === 0) { var ccbSelectorResolver = ccbReader.getCCBSelectorResolver(); if (ccbSelectorResolver != null) selMenuHandler = ccbSelectorResolver.onResolveCCBCCMenuItemSelector(target, selectorName); } - if (selMenuHandler == 0) { + if (selMenuHandler === 0) { cc.log("Skipping selector '" +selectorName+ "' since no CCBSelectorResolver is present."); } else { return new BlockData(selMenuHandler,target); @@ -672,27 +672,27 @@ cc.NodeLoader = cc.Class.extend({ if (selectorTarget !== CCB_TARGETTYPE_NONE) { if(!ccbReader.isJSControlled()){ var target = null; - if (selectorTarget == CCB_TARGETTYPE_DOCUMENTROOT) { + if (selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT) { target = ccbReader.getAnimationManager().getRootNode(); - } else if (selectorTarget == CCB_TARGETTYPE_OWNER) { + } else if (selectorTarget === CCB_TARGETTYPE_OWNER) { target = ccbReader.getOwner(); } - if (target != null) { + if (target !== null) { if (selectorName.length > 0) { var selCCControlHandler = 0; - if (target != null && target.onResolveCCBCCControlSelector) { + if (target.onResolveCCBCCControlSelector) { selCCControlHandler = target.onResolveCCBCCControlSelector(target, selectorName); } - if (selCCControlHandler == 0) { + if (selCCControlHandler === 0) { var ccbSelectorResolver = ccbReader.getCCBSelectorResolver(); if (ccbSelectorResolver != null) { selCCControlHandler = ccbSelectorResolver.onResolveCCBCCControlSelector(target, selectorName); } } - if (selCCControlHandler == 0) { + if (selCCControlHandler === 0) { cc.log("Skipping selector '" + selectorName + "' since no CCBSelectorResolver is present."); } else { return new BlockCCControlData(selCCControlHandler,target,controlEvents); @@ -704,7 +704,7 @@ cc.NodeLoader = cc.Class.extend({ cc.log("Unexpected NULL target for selector."); } } else { - if(selectorTarget == CCB_TARGETTYPE_DOCUMENTROOT){ + if(selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT){ ccbReader.addDocumentCallbackNode(node); ccbReader.addDocumentCallbackName(selectorName); ccbReader.addDocumentCallbackControlEvents(controlEvents); @@ -740,10 +740,9 @@ cc.NodeLoader = cc.Class.extend({ myCCBReader.getAnimationManager().setOwner(ccbReader.getOwner()); var ccbFileNode = myCCBReader.readFileWithCleanUp(false); - ccbReader.setAnimationManagers(myCCBReader.getAnimationManagers()); - if(ccbFileNode && myCCBReader.getAnimationManager().getAutoPlaySequenceId() != -1) + if(ccbFileNode && myCCBReader.getAnimationManager().getAutoPlaySequenceId() !== -1) myCCBReader.getAnimationManager().runAnimations(myCCBReader.getAnimationManager().getAutoPlaySequenceId(),0); return ccbFileNode; diff --git a/extensions/ccb-reader/CCSpriteLoader.js b/extensions/ccb-reader/CCSpriteLoader.js index b1ba28e7ac..857b2bb025 100644 --- a/extensions/ccb-reader/CCSpriteLoader.js +++ b/extensions/ccb-reader/CCSpriteLoader.js @@ -171,7 +171,7 @@ cc.LayerGradientLoader = cc.LayerLoader.extend({ onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) { if (propertyName === PROPERTY_STARTCOLOR) { node.setStartColor(ccColor3B); - } else if (propertyName == PROPERTY_ENDCOLOR) { + } else if (propertyName === PROPERTY_ENDCOLOR) { node.setEndColor(ccColor3B); } else { cc.LayerLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, ccColor3B, ccbReader); diff --git a/extensions/ccpool/CCPool.js b/extensions/ccpool/CCPool.js index 8c930642c3..205c8a2295 100644 --- a/extensions/ccpool/CCPool.js +++ b/extensions/ccpool/CCPool.js @@ -84,7 +84,7 @@ cc.pool = /** @lends cc.pool# */{ hasObject: function (objClass) { var pid = objClass.prototype.__pid; var list = this._pool[pid]; - if (!list || list.length == 0) { + if (!list || list.length === 0) { return false; } return true; diff --git a/extensions/ccui/base-classes/CCProtectedNode.js b/extensions/ccui/base-classes/CCProtectedNode.js index c9f8d9f812..ad1e3c8f90 100644 --- a/extensions/ccui/base-classes/CCProtectedNode.js +++ b/extensions/ccui/base-classes/CCProtectedNode.js @@ -85,10 +85,10 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{ * @return {cc.Node} a Node object whose tag equals to the input parameter */ getProtectedChildByTag: function(tag){ - cc.assert(tag != cc.NODE_TAG_INVALID, "Invalid tag"); + cc.assert(tag !== cc.NODE_TAG_INVALID, "Invalid tag"); var locChildren = this._protectedChildren; for(var i = 0, len = locChildren.length; i < len; i++) - if(locChildren.getTag() == tag) + if(locChildren.getTag() === tag) return locChildren[i]; return null; }, @@ -129,7 +129,7 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{ * @param {Boolean} [cleanup=true] */ removeProtectedChildByTag: function(tag, cleanup){ - cc.assert( tag != cc.NODE_TAG_INVALID, "Invalid tag"); + cc.assert( tag !== cc.NODE_TAG_INVALID, "Invalid tag"); if(cleanup == null) cleanup = true; diff --git a/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js b/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js index 476c790a5f..bcac0b4834 100644 --- a/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js +++ b/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js @@ -120,7 +120,7 @@ cc.kmMat4Multiply(stackMatrix, parentMatrix, t4x4); // XXX: Expensive calls. Camera should be integrated into the cached affine matrix - if (node._camera != null && !(node.grid != null && node.grid.isActive())) { + if (node._camera !== null && !(node.grid !== null && node.grid.isActive())) { var apx = this._anchorPointInPoints.x, apy = this._anchorPointInPoints.y; var translate = (apx !== 0.0 || apy !== 0.0); if (translate){ diff --git a/extensions/ccui/base-classes/UIScale9Sprite.js b/extensions/ccui/base-classes/UIScale9Sprite.js index e36ee5d569..813ceae5c1 100644 --- a/extensions/ccui/base-classes/UIScale9Sprite.js +++ b/extensions/ccui/base-classes/UIScale9Sprite.js @@ -150,15 +150,15 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ var leftWidth = locBottomLeftContentSize.width; var bottomHeight = locBottomLeftContentSize.height; - if (cc._renderType == cc._RENDER_TYPE_WEBGL) { + if (cc._renderType === cc._RENDER_TYPE_WEBGL) { //browser is in canvas mode, need to manually control rounding to prevent overlapping pixels var roundedRescaledWidth = Math.round(rescaledWidth); - if (rescaledWidth != roundedRescaledWidth) { + if (rescaledWidth !== roundedRescaledWidth) { rescaledWidth = roundedRescaledWidth; horizontalScale = rescaledWidth / locCenterContentSize.width; } var roundedRescaledHeight = Math.round(rescaledHeight); - if (rescaledHeight != roundedRescaledHeight) { + if (rescaledHeight !== roundedRescaledHeight) { rescaledHeight = roundedRescaledHeight; verticalScale = rescaledHeight / locCenterContentSize.height; } @@ -502,7 +502,7 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ // the texture is rotated on Canvas render mode, so isRotated always is false. var preferredSize = this._preferredSize; preferredSize = cc.size(preferredSize.width, preferredSize.height); - this.updateWithBatchNode(this._scale9Image, sender.getRect(), cc._renderType == cc._RENDER_TYPE_WEBGL && sender.isRotated(), this._capInsets); + this.updateWithBatchNode(this._scale9Image, sender.getRect(), cc._renderType === cc._RENDER_TYPE_WEBGL && sender.isRotated(), this._capInsets); this.setPreferredSize(preferredSize); this._positionsAreDirty = true; this.dispatchEvent("load"); @@ -510,7 +510,7 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ } var batchNode = new cc.SpriteBatchNode(spriteFrame.getTexture(), 9); // the texture is rotated on Canvas render mode, so isRotated always is false. - return this.initWithBatchNode(batchNode, spriteFrame.getRect(), cc._renderType == cc._RENDER_TYPE_WEBGL && spriteFrame.isRotated(), capInsets); + return this.initWithBatchNode(batchNode, spriteFrame.getRect(), cc._renderType === cc._RENDER_TYPE_WEBGL && spriteFrame.isRotated(), capInsets); }, /** @@ -592,7 +592,7 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ // Release old sprites this.removeAllChildren(true); - if (this._scale9Image != batchNode) + if (this._scale9Image !== batchNode) this._scale9Image = batchNode; if(!this._scale9Image) @@ -902,13 +902,13 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ // the texture is rotated on Canvas render mode, so isRotated always is false. var preferredSize = this._preferredSize; preferredSize = cc.size(preferredSize.width, preferredSize.height); - this.updateWithBatchNode(this._scale9Image, sender.getRect(), cc._renderType == cc._RENDER_TYPE_WEBGL && sender.isRotated(), this._capInsets); + this.updateWithBatchNode(this._scale9Image, sender.getRect(), cc._renderType === cc._RENDER_TYPE_WEBGL && sender.isRotated(), this._capInsets); this.setPreferredSize(preferredSize); this._positionsAreDirty = true; this.dispatchEvent("load"); },this); } - this.updateWithBatchNode(batchNode, spriteFrame.getRect(), cc._renderType == cc._RENDER_TYPE_WEBGL && spriteFrame.isRotated(), cc.rect(0, 0, 0, 0)); + this.updateWithBatchNode(batchNode, spriteFrame.getRect(), cc._renderType === cc._RENDER_TYPE_WEBGL && spriteFrame.isRotated(), cc.rect(0, 0, 0, 0)); // Reset insets this._insetLeft = 0; diff --git a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js index 7c5abde255..1dc9ae4734 100644 --- a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js +++ b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js @@ -105,7 +105,7 @@ var locCanvas = this._cacheCanvas, wrapper = this._cacheContext, locContext = wrapper.getContext(); var contentSizeChanged = false; - if(locCanvas.width != sizeInPixels.width || locCanvas.height != sizeInPixels.height){ + if(locCanvas.width !== sizeInPixels.width || locCanvas.height !== sizeInPixels.height){ locCanvas.width = sizeInPixels.width; locCanvas.height = sizeInPixels.height; contentSizeChanged = true; diff --git a/extensions/ccui/base-classes/UIWidget.js b/extensions/ccui/base-classes/UIWidget.js index d3cea43929..b7e7a16f76 100644 --- a/extensions/ccui/base-classes/UIWidget.js +++ b/extensions/ccui/base-classes/UIWidget.js @@ -30,7 +30,7 @@ ccui._FocusNavigationController = cc.Class.extend({ _keyboardEventPriority: 1, enableFocusNavigation: function(flag){ - if (this._enableFocusNavigation == flag) + if (this._enableFocusNavigation === flag) return; this._enableFocusNavigation = flag; @@ -46,16 +46,16 @@ ccui._FocusNavigationController = cc.Class.extend({ _onKeyPressed: function(keyCode, event){ if (this._enableFocusNavigation && this._firstFocusedWidget) { - if (keyCode == cc.KEY.dpadDown) { + if (keyCode === cc.KEY.dpadDown) { this._firstFocusedWidget = this._firstFocusedWidget.findNextFocusedWidget(ccui.Widget.DOWN, this._firstFocusedWidget); } - if (keyCode == cc.KEY.dpadUp){ + if (keyCode === cc.KEY.dpadUp){ this._firstFocusedWidget = this._firstFocusedWidget.findNextFocusedWidget(ccui.Widget.UP, this._firstFocusedWidget); } - if (keyCode == cc.KEY.dpadLeft) { + if (keyCode === cc.KEY.dpadLeft) { this._firstFocusedWidget = this._firstFocusedWidget.findNextFocusedWidget(ccui.Widget.LEFT, this._firstFocusedWidget); } - if (keyCode == cc.KEY.dpadRight) { + if (keyCode === cc.KEY.dpadRight) { this._firstFocusedWidget = this._firstFocusedWidget.findNextFocusedWidget(ccui.Widget.RIGHT, this._firstFocusedWidget); } } @@ -329,7 +329,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ this._touchListener = null; //cleanup focused widget and focus navigation controller - if (ccui.Widget._focusedWidget == this){ + if (ccui.Widget._focusedWidget === this){ ccui.Widget._focusedWidget = null; ccui.Widget._focusNavigationController = null; } @@ -542,7 +542,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ this._sizeType = type; if (this._usingLayoutComponent) { var component = this._getOrCreateLayoutComponent(); - component.setUsingPercentContentSize(this._sizeType == ccui.SIZE_PERCENT); + component.setUsingPercentContentSize(this._sizeType === ccui.SIZE_PERCENT); } }, @@ -564,7 +564,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ return; } - if(this._ignoreSize == ignore) + if(this._ignoreSize === ignore) return; this._ignoreSize = ignore; @@ -696,7 +696,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @param highlight true if the widget is highlighted, false if the widget is not highlighted. */ setHighlighted:function(highlight){ - if (highlight == this._highlight) + if (highlight === this._highlight) return; this._highlight = highlight; if (this._bright) { @@ -757,11 +757,11 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @return the next focused widget in a layout */ findNextFocusedWidget: function( direction, current){ - if (null == this.onNextFocusedWidget || null == this.onNextFocusedWidget(direction) ) { + if (null === this.onNextFocusedWidget || null == this.onNextFocusedWidget(direction) ) { var isLayout = current instanceof ccui.Layout; if (this.isFocused() || isLayout) { var layout = this.getParent(); - if (null == layout || !(layout instanceof ccui.Layout)){ + if (null === layout || !(layout instanceof ccui.Layout)){ //the outer layout's default behaviour is : loop focus if (isLayout) return current.findNextFocusedWidget(direction, current); @@ -781,7 +781,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * when a widget calls this method, it will get focus immediately. */ requestFocus: function(){ - if (this == ccui.Widget._focusedWidget) + if (this === ccui.Widget._focusedWidget) return; this.dispatchFocusEvent(ccui.Widget._focusedWidget, this); }, @@ -841,7 +841,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ if (widgetLostFocus && !widgetLostFocus.isFocused()) widgetLostFocus = ccui.Widget._focusedWidget; - if (widgetGetFocus != widgetLostFocus){ + if (widgetGetFocus !== widgetLostFocus){ if (widgetGetFocus && widgetGetFocus.onFocusChanged) widgetGetFocus.onFocusChanged(widgetLostFocus, widgetGetFocus); if (widgetLostFocus && widgetGetFocus.onFocusChanged) @@ -868,9 +868,9 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @param {Number} style BRIGHT_NORMAL the widget is normal state, BRIGHT_HIGHLIGHT the widget is height light state. */ setBrightStyle: function (style) { - if (this._brightStyle == style) { + if (this._brightStyle === style) return; - } + style = style || ccui.Widget.BRIGHT_STYLE_NORMAL; this._brightStyle = style; switch (this._brightStyle) { @@ -1136,7 +1136,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ this._positionPercent.x = 0; this._positionPercent.y = 0; } else { - if (posY == undefined) { + if (posY === undefined) { this._positionPercent.x = pos.x / pSize.width; this._positionPercent.y = pos.y / pSize.height; } else { @@ -1254,7 +1254,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ this._positionType = type; if(this._usingLayoutComponent){ var component = this._getOrCreateLayoutComponent(); - if (type == ccui.POSITION_ABSOLUTE){ + if (type === ccui.POSITION_ABSOLUTE){ component.setPositionPercentXEnabled(false); component.setPositionPercentYEnabled(false); } else { @@ -1645,7 +1645,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ var _nodes = this._nodes; for (var i = 0; i < _nodes.length; i++) { var node = _nodes[i]; - if (node && node.getTag() == tag) { + if (node && node.getTag() === tag) { return node; } } @@ -1768,7 +1768,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ return originalScale; }, getScale: function(){ - if(this.getScaleX() == this.getScaleY()) + if(this.getScaleX() === this.getScaleY()) cc.log("Widget#scale. ScaleX != ScaleY. Don't know which one to return"); return this.getScaleX(); }, diff --git a/extensions/ccui/layouts/UILayout.js b/extensions/ccui/layouts/UILayout.js index 08bb627824..99b242c2ae 100644 --- a/extensions/ccui/layouts/UILayout.js +++ b/extensions/ccui/layouts/UILayout.js @@ -176,7 +176,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ parent._isFocusPassing = true; return parent.findNextFocusedWidget(direction, this); } else if(current.isFocused() || current instanceof ccui.Layout) { - if (this._layoutType == ccui.Layout.LINEAR_HORIZONTAL) { + if (this._layoutType === ccui.Layout.LINEAR_HORIZONTAL) { switch (direction){ case ccui.Widget.LEFT: return this._getPreviousFocusedWidget(direction, current); @@ -198,7 +198,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ cc.assert(0, "Invalid Focus Direction"); return current; } - } else if (this._layoutType == ccui.Layout.LINEAR_VERTICAL) { + } else if (this._layoutType === ccui.Layout.LINEAR_VERTICAL) { switch (direction){ case ccui.Widget.LEFT: case ccui.Widget.RIGHT: @@ -340,7 +340,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * @param {Boolean} able clipping enabled. */ setClippingEnabled: function (able) { - if (able == this._clippingEnabled) + if (able === this._clippingEnabled) return; this._clippingEnabled = able; switch (this._clippingType) { @@ -367,9 +367,9 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * @param {ccui.Layout.CLIPPING_STENCIL|ccui.Layout.CLIPPING_SCISSOR} type */ setClippingType: function (type) { - if (type == this._clippingType) + if (type === this._clippingType) return; - if(cc._renderType === cc._RENDER_TYPE_CANVAS && type == ccui.Layout.CLIPPING_SCISSOR){ + if(cc._renderType === cc._RENDER_TYPE_CANVAS && type === ccui.Layout.CLIPPING_SCISSOR){ cc.log("Only supports STENCIL on canvas mode."); return; } @@ -388,7 +388,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ }, _setStencilClippingSize: function (size) { - if (this._clippingEnabled && this._clippingType == ccui.Layout.CLIPPING_STENCIL) { + if (this._clippingEnabled && this._clippingType === ccui.Layout.CLIPPING_STENCIL) { var rect = []; rect[0] = cc.p(0, 0); rect[1] = cc.p(size.width, 0); @@ -481,7 +481,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * @param {Boolean} able true that use scale9 renderer, false otherwise. */ setBackGroundImageScale9Enabled: function (able) { - if (this._backGroundScale9Enabled == able) + if (this._backGroundScale9Enabled === able) return; this.removeProtectedChild(this._backGroundImage); this._backGroundImage = null; @@ -508,7 +508,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ if (!fileName) return; texType = texType || ccui.Widget.LOCAL_TEXTURE; - if (this._backGroundImage == null){ + if (this._backGroundImage === null){ this._addBackGroundImage(); this.setBackGroundImageScale9Enabled(this._backGroundScale9Enabled); } @@ -609,7 +609,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * @param {ccui.Layout.BG_COLOR_NONE|ccui.Layout.BG_COLOR_SOLID|ccui.Layout.BG_COLOR_GRADIENT} type */ setBackGroundColorType: function (type) { - if (this._colorType == type) + if (this._colorType === type) return; switch (this._colorType) { case ccui.Layout.BG_COLOR_NONE: @@ -897,7 +897,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ var widgetCount = 0, locSize; for(var i = 0, len = children.length; i < len; i++) { var layout = children[i]; - if (null != layout && layout instanceof ccui.Layout){ + if (null !== layout && layout instanceof ccui.Layout){ locSize = layout._getLayoutAccumulatedSize(); layoutSize.width += locSize.width; layoutSize.height += locSize.height; @@ -914,10 +914,10 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ //substract extra size var type = this.getLayoutType(); - if (type == ccui.Layout.LINEAR_HORIZONTAL) + if (type === ccui.Layout.LINEAR_HORIZONTAL) layoutSize.height = layoutSize.height - layoutSize.height/widgetCount * (widgetCount-1); - if (type == ccui.Layout.LINEAR_VERTICAL) + if (type === ccui.Layout.LINEAR_VERTICAL) layoutSize.width = layoutSize.width - layoutSize.width/widgetCount * (widgetCount-1); return layoutSize; }, @@ -931,14 +931,14 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * @private */ _findNearestChildWidgetIndex: function(direction, baseWidget){ - if (baseWidget == null || baseWidget == this) + if (baseWidget == null || baseWidget === this) return this._findFirstFocusEnabledWidgetIndex(); var index = 0, locChildren = this.getChildren(); var count = locChildren.length, widgetPosition; var distance = cc.FLT_MAX, found = 0; - if (direction == ccui.Widget.LEFT || direction == ccui.Widget.RIGHT || direction == ccui.Widget.DOWN || direction == ccui.Widget.UP) { + if (direction === ccui.Widget.LEFT || direction === ccui.Widget.RIGHT || direction === ccui.Widget.DOWN || direction === ccui.Widget.UP) { widgetPosition = this._getWorldCenterPoint(baseWidget); while (index < count) { var w = locChildren[index]; @@ -967,14 +967,14 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * @private */ _findFarthestChildWidgetIndex: function(direction, baseWidget){ - if (baseWidget == null || baseWidget == this) + if (baseWidget == null || baseWidget === this) return this._findFirstFocusEnabledWidgetIndex(); var index = 0, locChildren = this.getChildren(); var count = locChildren.length; var distance = -cc.FLT_MAX, found = 0; - if (direction == ccui.Widget.LEFT || direction == ccui.Widget.RIGHT || direction == ccui.Widget.DOWN || direction == ccui.Widget.UP) { + if (direction === ccui.Widget.LEFT || direction === ccui.Widget.RIGHT || direction === ccui.Widget.DOWN || direction === ccui.Widget.UP) { var widgetPosition = this._getWorldCenterPoint(baseWidget); while (index < count) { var w = locChildren[index]; @@ -1063,16 +1063,16 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ var previousWidgetPosition = this._getWorldCenterPoint(baseWidget); var widgetPosition = this._getWorldCenterPoint(this._findFirstNonLayoutWidget()); - if (direction == ccui.Widget.LEFT) { + if (direction === ccui.Widget.LEFT) { this.onPassFocusToChild = (previousWidgetPosition.x > widgetPosition.x) ? this._findNearestChildWidgetIndex.bind(this) : this._findFarthestChildWidgetIndex.bind(this); - } else if (direction == ccui.Widget.RIGHT) { + } else if (direction === ccui.Widget.RIGHT) { this.onPassFocusToChild = (previousWidgetPosition.x > widgetPosition.x) ? this._findFarthestChildWidgetIndex.bind(this) : this._findNearestChildWidgetIndex.bind(this); - }else if(direction == ccui.Widget.DOWN) { + }else if(direction === ccui.Widget.DOWN) { this.onPassFocusToChild = (previousWidgetPosition.y > widgetPosition.y) ? this._findNearestChildWidgetIndex.bind(this) : this._findFarthestChildWidgetIndex.bind(this); - }else if(direction == ccui.Widget.UP) { + }else if(direction === ccui.Widget.UP) { this.onPassFocusToChild = (previousWidgetPosition.y < widgetPosition.y) ? this._findNearestChildWidgetIndex.bind(this) : this._findFarthestChildWidgetIndex.bind(this); }else @@ -1293,41 +1293,41 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ var container = parent.getChildren(); var index = container.indexOf(widget); - if (parent.getLayoutType() == ccui.Layout.LINEAR_HORIZONTAL) { - if (direction == ccui.Widget.LEFT) { - if (index == 0) + if (parent.getLayoutType() === ccui.Layout.LINEAR_HORIZONTAL) { + if (direction === ccui.Widget.LEFT) { + if (index === 0) return this._isLastWidgetInContainer(parent, direction); else return false; } - if (direction == ccui.Widget.RIGHT) { - if (index == container.length - 1) + if (direction === ccui.Widget.RIGHT) { + if (index === container.length - 1) return this._isLastWidgetInContainer(parent, direction); else return false; } - if (direction == ccui.Widget.DOWN) + if (direction === ccui.Widget.DOWN) return this._isLastWidgetInContainer(parent, direction); - if (direction == ccui.Widget.UP) + if (direction === ccui.Widget.UP) return this._isLastWidgetInContainer(parent, direction); - } else if(parent.getLayoutType() == ccui.Layout.LINEAR_VERTICAL){ - if (direction == ccui.Widget.UP){ - if (index == 0) + } else if(parent.getLayoutType() === ccui.Layout.LINEAR_VERTICAL){ + if (direction === ccui.Widget.UP){ + if (index === 0) return this._isLastWidgetInContainer(parent, direction); else return false; } - if (direction == ccui.Widget.DOWN) { - if (index == container.length - 1) + if (direction === ccui.Widget.DOWN) { + if (index === container.length - 1) return this._isLastWidgetInContainer(parent, direction); else return false; } - if (direction == ccui.Widget.LEFT) + if (direction === ccui.Widget.LEFT) return this._isLastWidgetInContainer(parent, direction); - if (direction == ccui.Widget.RIGHT) + if (direction === ccui.Widget.RIGHT) return this._isLastWidgetInContainer(parent, direction); } else { cc.log("invalid layout Type"); @@ -1348,14 +1348,14 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ return false; if (parent.isLoopFocus()) { var layoutType = parent.getLayoutType(); - if (layoutType == ccui.Layout.LINEAR_HORIZONTAL) { - if (direction == ccui.Widget.LEFT || direction == ccui.Widget.RIGHT) + if (layoutType === ccui.Layout.LINEAR_HORIZONTAL) { + if (direction === ccui.Widget.LEFT || direction === ccui.Widget.RIGHT) return true; else return this._isWidgetAncestorSupportLoopFocus(parent, direction); } - if (layoutType == ccui.Layout.LINEAR_VERTICAL){ - if (direction == ccui.Widget.DOWN || direction == ccui.Widget.UP) + if (layoutType === ccui.Layout.LINEAR_VERTICAL){ + if (direction === ccui.Widget.DOWN || direction === ccui.Widget.UP) return true; else return this._isWidgetAncestorSupportLoopFocus(parent, direction); diff --git a/extensions/ccui/layouts/UILayoutComponent.js b/extensions/ccui/layouts/UILayoutComponent.js index a178d9ed8d..ed7182def5 100644 --- a/extensions/ccui/layouts/UILayoutComponent.js +++ b/extensions/ccui/layouts/UILayoutComponent.js @@ -137,7 +137,7 @@ ccui.LayoutComponent = cc.Component.extend({ x = position; var parentSize = parent.getContentSize(); - if (parentSize.width != 0) + if (parentSize.width !== 0) this._positionPercentX = x / parentSize.width; else { this._positionPercentX = 0; @@ -145,7 +145,7 @@ ccui.LayoutComponent = cc.Component.extend({ x = 0; } - if (parentSize.height != 0) + if (parentSize.height !== 0) this._positionPercentY = y / parentSize.height; else { this._positionPercentY = 0; @@ -176,7 +176,7 @@ ccui.LayoutComponent = cc.Component.extend({ this._positionPercentX = percentMargin; var parent = this._getOwnerParent(); - if (parent != null) { + if (parent !== null) { this._owner.setPositionX(parent.width * this._positionPercentX); this._refreshHorizontalMargin(); } @@ -198,7 +198,7 @@ ccui.LayoutComponent = cc.Component.extend({ this._positionPercentY = percentMargin; var parent = this._getOwnerParent(); - if (parent != null) { + if (parent !== null) { this._owner.setPositionY(parent.height * this._positionPercentY); this._refreshVerticalMargin(); } @@ -209,14 +209,14 @@ ccui.LayoutComponent = cc.Component.extend({ }, setHorizontalEdge: function (hEdge) { this._horizontalEdge = hEdge; - if (this._horizontalEdge != ccui.LayoutComponent.horizontalEdge.NONE) + if (this._horizontalEdge !== ccui.LayoutComponent.horizontalEdge.NONE) this._usingPositionPercentX = false; var parent = this._getOwnerParent(); - if (parent != null) { + if (parent !== null) { var ownerPoint = this._owner.getPosition(); var parentSize = parent.getContentSize(); - if (parentSize.width != 0) + if (parentSize.width !== 0) this._positionPercentX = ownerPoint.x / parentSize.width; else { this._positionPercentX = 0; @@ -233,14 +233,14 @@ ccui.LayoutComponent = cc.Component.extend({ }, setVerticalEdge: function (vEdge) { this._verticalEdge = vEdge; - if (this._verticalEdge != ccui.LayoutComponent.verticalEdge.NONE) + if (this._verticalEdge !== ccui.LayoutComponent.verticalEdge.NONE) this._usingPositionPercentY = false; var parent = this._getOwnerParent(); - if (parent != null) { + if (parent !== null) { var ownerPoint = this._owner.getPosition(); var parentSize = parent.getContentSize(); - if (parentSize.height != 0) + if (parentSize.height !== 0) this._positionPercentY = ownerPoint.y / parentSize.height; else { this._positionPercentY = 0; @@ -286,10 +286,10 @@ ccui.LayoutComponent = cc.Component.extend({ }, setSize: function (size) { var parent = this._getOwnerParent(); - if (parent != null) { + if (parent !== null) { var ownerSize = size, parentSize = parent.getContentSize(); - if (parentSize.width != 0) + if (parentSize.width !== 0) this._percentWidth = ownerSize.width / parentSize.width; else { this._percentWidth = 0; @@ -297,7 +297,7 @@ ccui.LayoutComponent = cc.Component.extend({ ownerSize.width = 0; } - if (parentSize.height != 0) + if (parentSize.height !== 0) this._percentHeight = ownerSize.height / parentSize.height; else { this._percentHeight = 0; @@ -331,9 +331,9 @@ ccui.LayoutComponent = cc.Component.extend({ ownerSize.width = width; var parent = this._getOwnerParent(); - if (parent != null) { + if (parent !== null) { var parentSize = parent.getContentSize(); - if (parentSize.width != 0) + if (parentSize.width !== 0) this._percentWidth = ownerSize.width / parentSize.width; else { this._percentWidth = 0; @@ -353,7 +353,7 @@ ccui.LayoutComponent = cc.Component.extend({ this._percentWidth = percentWidth; var parent = this._getOwnerParent(); - if (parent != null) { + if (parent !== null) { var ownerSize = this._owner.getContentSize(); ownerSize.width = parent.width * this._percentWidth; this._owner.setContentSize(ownerSize); @@ -378,9 +378,9 @@ ccui.LayoutComponent = cc.Component.extend({ ownerSize.height = height; var parent = this._getOwnerParent(); - if (parent != null) { + if (parent !== null) { var parentSize = parent.getContentSize(); - if (parentSize.height != 0) + if (parentSize.height !== 0) this._percentHeight = ownerSize.height / parentSize.height; else { this._percentHeight = 0; @@ -401,7 +401,7 @@ ccui.LayoutComponent = cc.Component.extend({ this._percentHeight = percentHeight; var parent = this._getOwnerParent(); - if (parent != null) { + if (parent !== null) { var ownerSize = this._owner.getContentSize(); ownerSize.height = parent.height * this._percentHeight; this._owner.setContentSize(ownerSize); @@ -439,7 +439,7 @@ ccui.LayoutComponent = cc.Component.extend({ return; var parent = this._getOwnerParent(); - if (parent == null) + if (parent === null) return; var parentSize = parent.getContentSize(), locOwner = this._owner; @@ -545,7 +545,7 @@ ccui.LayoutComponent = cc.Component.extend({ }, _refreshHorizontalMargin: function () { var parent = this._getOwnerParent(); - if (parent == null) + if (parent === null) return; var ownerPoint = this._owner.getPosition(), ownerAnchor = this._owner.getAnchorPoint(); @@ -556,7 +556,7 @@ ccui.LayoutComponent = cc.Component.extend({ }, _refreshVerticalMargin: function () { var parent = this._getOwnerParent(); - if (parent == null) + if (parent === null) return; var ownerPoint = this._owner.getPosition(), ownerAnchor = this._owner.getAnchorPoint(); @@ -573,7 +573,7 @@ ccui.LayoutComponent.verticalEdge = {NONE: 0, BOTTOM: 1, TOP: 2, CENTER: 3}; ccui.LayoutComponent.NAME = "__ui_layout"; ccui.LayoutComponent.bindLayoutComponent = function (node) { var layout = node.getComponent(ccui.LayoutComponent.NAME); - if (layout != null) + if (layout !== null) return layout; layout = new ccui.LayoutComponent(); diff --git a/extensions/ccui/layouts/UILayoutManager.js b/extensions/ccui/layouts/UILayoutManager.js index d24e8996ab..e12cc31333 100644 --- a/extensions/ccui/layouts/UILayoutManager.js +++ b/extensions/ccui/layouts/UILayoutManager.js @@ -191,13 +191,13 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{ var layoutParameter = widget.getLayoutParameter(); var relativeName = layoutParameter.getRelativeToWidgetName(); - if (relativeName && relativeName.length != 0) { + if (relativeName && relativeName.length !== 0) { var locChildren = this._widgetChildren; for(var i = 0, len = locChildren.length; i < len; i++){ var child = locChildren[i]; if (child){ var rlayoutParameter = child.getLayoutParameter(); - if (rlayoutParameter && rlayoutParameter.getRelativeName() == relativeName) { + if (rlayoutParameter && rlayoutParameter.getRelativeName() === relativeName) { relativeWidget = child; this._relativeWidgetLP = rlayoutParameter; break; diff --git a/extensions/ccui/layouts/UILayoutParameter.js b/extensions/ccui/layouts/UILayoutParameter.js index c90d34de86..2ea2919426 100644 --- a/extensions/ccui/layouts/UILayoutParameter.js +++ b/extensions/ccui/layouts/UILayoutParameter.js @@ -78,7 +78,7 @@ ccui.Margin = ccui.Class.extend(/** @lends ccui.Margin# */{ * @returns {boolean} */ equals: function (target) { - return (this.left == target.left && this.top == target.top && this.right == target.right && this.bottom == target.bottom); + return (this.left === target.left && this.top === target.top && this.right === target.right && this.bottom === target.bottom); } }); diff --git a/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js b/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js index 4ec484d55e..d46e1e8939 100644 --- a/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js +++ b/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js @@ -170,7 +170,7 @@ return; // all the _stencilBits are in use? - if (ccui.Layout.WebGLRenderCmd._layer + 1 == cc.stencilBits) { + if (ccui.Layout.WebGLRenderCmd._layer + 1 === cc.stencilBits) { // warn once ccui.Layout.WebGLRenderCmd._visit_once = true; if (ccui.Layout.WebGLRenderCmd._visit_once) { diff --git a/extensions/ccui/system/UIHelper.js b/extensions/ccui/system/UIHelper.js index 2c0263b35f..70d82c9b84 100644 --- a/extensions/ccui/system/UIHelper.js +++ b/extensions/ccui/system/UIHelper.js @@ -41,7 +41,7 @@ ccui.helper = { seekWidgetByTag: function (root, tag) { if (!root) return null; - if (root.getTag() == tag) + if (root.getTag() === tag) return root; var arrayRootChildren = root.getChildren(); @@ -49,7 +49,7 @@ ccui.helper = { for (var i = 0; i < length; i++) { var child = arrayRootChildren[i]; var res = ccui.helper.seekWidgetByTag(child, tag); - if (res != null) + if (res !== null) return res; } return null; @@ -64,14 +64,14 @@ ccui.helper = { seekWidgetByName: function (root, name) { if (!root) return null; - if (root.getName() == name) + if (root.getName() === name) return root; var arrayRootChildren = root.getChildren(); var length = arrayRootChildren.length; for (var i = 0; i < length; i++) { var child = arrayRootChildren[i]; var res = ccui.helper.seekWidgetByName(child, name); - if (res != null) + if (res !== null) return res; } return null; @@ -92,7 +92,7 @@ ccui.helper = { for (var i = 0; i < length; i++) { var child = arrayRootChildren[i]; var layoutParameter = child.getLayoutParameter(ccui.LayoutParameter.RELATIVE); - if (layoutParameter && layoutParameter.getRelativeName() == name) + if (layoutParameter && layoutParameter.getRelativeName() === name) return child; } return null; @@ -107,13 +107,13 @@ ccui.helper = { seekActionWidgetByActionTag: function (root, tag) { if (!root) return null; - if (root.getActionTag() == tag) + if (root.getActionTag() === tag) return root; var arrayRootChildren = root.getChildren(); for (var i = 0; i < arrayRootChildren.length; i++) { var child = arrayRootChildren[i]; var res = ccui.helper.seekActionWidgetByActionTag(child, tag); - if (res != null) + if (res !== null) return res; } return null; @@ -132,7 +132,7 @@ ccui.helper = { node = children[i]; var com = node.getComponent(ccui.LayoutComponent.NAME); var parent = node.getParent(); - if (null != com && null != parent && com.refreshLayout) + if (null != com && null !== parent && com.refreshLayout) com.refreshLayout(); } }, diff --git a/extensions/ccui/uiwidgets/UIButton.js b/extensions/ccui/uiwidgets/UIButton.js index dd76a26d8a..3ee086fbbc 100644 --- a/extensions/ccui/uiwidgets/UIButton.js +++ b/extensions/ccui/uiwidgets/UIButton.js @@ -144,7 +144,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ */ setScale9Enabled: function (able) { //todo create Scale9Sprite - if (this._scale9Enabled == able) + if (this._scale9Enabled === able) return; this._brightStyle = ccui.Widget.BRIGHT_STYLE_NONE; @@ -750,7 +750,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ * @param {String} text */ setTitleText: function (text) { - if(text == this.getTitleText()) + if(text === this.getTitleText()) return; this._titleRenderer.setString(text); if (this._ignoreSize){ @@ -900,11 +900,11 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ _getNormalSize: function(){ var titleSize; - if (this._titleRenderer != null) + if (this._titleRenderer !== null) titleSize = this._titleRenderer.getContentSize(); var imageSize; - if (this._buttonNormalRenderer != null) + if (this._buttonNormalRenderer !== null) imageSize = this._buttonNormalRenderer.getContentSize(); var width = titleSize.width > imageSize.width ? titleSize.width : imageSize.width; var height = titleSize.height > imageSize.height ? titleSize.height : imageSize.height; diff --git a/extensions/ccui/uiwidgets/UICheckBox.js b/extensions/ccui/uiwidgets/UICheckBox.js index dbe967c859..dc4b3ed922 100644 --- a/extensions/ccui/uiwidgets/UICheckBox.js +++ b/extensions/ccui/uiwidgets/UICheckBox.js @@ -84,7 +84,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ var strNum = 0; for(var i=0; i 0 && cutWords != " "; + validLeftLength = leftLength > 0 && cutWords !== " "; } if (validLeftLength) { @@ -492,11 +491,11 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ } //Text flow horizontal alignment: - if(this._textHorizontalAlignment != cc.TEXT_ALIGNMENT_LEFT) { + if(this._textHorizontalAlignment !== cc.TEXT_ALIGNMENT_LEFT) { var offsetX = 0; - if (this._textHorizontalAlignment == cc.TEXT_ALIGNMENT_RIGHT) + if (this._textHorizontalAlignment === cc.TEXT_ALIGNMENT_RIGHT) offsetX = this._contentSize.width - nextPosX; - else if (this._textHorizontalAlignment == cc.TEXT_ALIGNMENT_CENTER) + else if (this._textHorizontalAlignment === cc.TEXT_ALIGNMENT_CENTER) offsetX = (this._contentSize.width - nextPosX) / 2; for (j = 0; j < row.length; j++) @@ -534,17 +533,17 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ nextPosX += l.getContentSize().width; } //Text flow alignment(s) - if( this._textHorizontalAlignment != cc.TEXT_ALIGNMENT_LEFT || this._textVerticalAlignment != cc.VERTICAL_TEXT_ALIGNMENT_TOP) { + if( this._textHorizontalAlignment !== cc.TEXT_ALIGNMENT_LEFT || this._textVerticalAlignment !== cc.VERTICAL_TEXT_ALIGNMENT_TOP) { var offsetX = 0; - if (this._textHorizontalAlignment == cc.TEXT_ALIGNMENT_RIGHT) + if (this._textHorizontalAlignment === cc.TEXT_ALIGNMENT_RIGHT) offsetX = this._contentSize.width - nextPosX; - else if (this._textHorizontalAlignment == cc.TEXT_ALIGNMENT_CENTER) + else if (this._textHorizontalAlignment === cc.TEXT_ALIGNMENT_CENTER) offsetX = (this._contentSize.width - nextPosX) / 2; var offsetY = 0; - if (this._textVerticalAlignment == cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM) + if (this._textVerticalAlignment === cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM) offsetY = this._customSize.height - newContentSizeHeight; - else if (this._textVerticalAlignment == cc.VERTICAL_TEXT_ALIGNMENT_CENTER) + else if (this._textVerticalAlignment === cc.VERTICAL_TEXT_ALIGNMENT_CENTER) offsetY = (this._customSize.height - newContentSizeHeight) / 2; for (j = 0; j < row.length; j++) { @@ -621,7 +620,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ * @override */ ignoreContentAdaptWithSize: function (ignore) { - if (this._ignoreSize != ignore) { + if (this._ignoreSize !== ignore) { this._formatTextDirty = true; ccui.Widget.prototype.ignoreContentAdaptWithSize.call(this, ignore); } @@ -689,7 +688,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ * @param {Number} value - example cc.TEXT_ALIGNMENT_RIGHT */ setTextHorizontalAlignment: function(value){ - if(value != this._textHorizontalAlignment) { + if(value !== this._textHorizontalAlignment) { this._textHorizontalAlignment = value; this.formatText(); } @@ -705,7 +704,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ * @param {Number} value - example cc.VERTICAL_TEXT_ALIGNMENT_CENTER */ setTextVerticalAlignment: function(value){ - if(value != this._textVerticalAlignment) { + if(value !== this._textVerticalAlignment) { this._textVerticalAlignment = value; this.formatText(); } diff --git a/extensions/ccui/uiwidgets/UISlider.js b/extensions/ccui/uiwidgets/UISlider.js index e36244fa92..3eed1abe54 100644 --- a/extensions/ccui/uiwidgets/UISlider.js +++ b/extensions/ccui/uiwidgets/UISlider.js @@ -208,7 +208,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ */ setScale9Enabled: function (able) { //todo use setScale9Enabled - if (this._scale9Enabled == able) + if (this._scale9Enabled === able) return; this._scale9Enabled = able; diff --git a/extensions/ccui/uiwidgets/UIText.js b/extensions/ccui/uiwidgets/UIText.js index d52f7bba17..5d7bfc107a 100644 --- a/extensions/ccui/uiwidgets/UIText.js +++ b/extensions/ccui/uiwidgets/UIText.js @@ -115,7 +115,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ * @param {String} text */ setString: function (text) { - if(text == this._labelRenderer.getString()) + if(text === this._labelRenderer.getString()) return; this._labelRenderer.setString(text); this._updateContentSizeWithTextureSize(this._labelRenderer.getContentSize()); @@ -392,7 +392,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ * @param glowColor */ enableGlow: function(glowColor){ - if (this._type == ccui.Text.Type.TTF) + if (this._type === ccui.Text.Type.TTF) this._labelRenderer.enableGlow(glowColor); }, diff --git a/extensions/ccui/uiwidgets/UITextAtlas.js b/extensions/ccui/uiwidgets/UITextAtlas.js index cb4ad707cc..bb7e0d27ca 100644 --- a/extensions/ccui/uiwidgets/UITextAtlas.js +++ b/extensions/ccui/uiwidgets/UITextAtlas.js @@ -95,7 +95,7 @@ ccui.TextAtlas = ccui.Widget.extend(/** @lends ccui.TextAtlas# */{ * @param {String} value */ setString: function (value) { - if(value == this._labelAtlasRenderer.getString()) + if(value === this._labelAtlasRenderer.getString()) return; this._stringValue = value; this._labelAtlasRenderer.setString(value); diff --git a/extensions/ccui/uiwidgets/UITextBMFont.js b/extensions/ccui/uiwidgets/UITextBMFont.js index b0af3462c1..e77f043765 100644 --- a/extensions/ccui/uiwidgets/UITextBMFont.js +++ b/extensions/ccui/uiwidgets/UITextBMFont.js @@ -99,7 +99,7 @@ ccui.LabelBMFont = ccui.TextBMFont = ccui.Widget.extend(/** @lends ccui.TextBMFo * @param {String} value */ setString: function (value) { - if(value == this._labelBMFontRenderer.getString()) + if(value === this._labelBMFontRenderer.getString()) return; this._stringValue = value; this._labelBMFontRenderer.setString(value); diff --git a/extensions/ccui/uiwidgets/UITextField.js b/extensions/ccui/uiwidgets/UITextField.js index 859fec09dc..8fd34e0173 100644 --- a/extensions/ccui/uiwidgets/UITextField.js +++ b/extensions/ccui/uiwidgets/UITextField.js @@ -61,7 +61,7 @@ ccui._TextFieldRenderer = cc.TextFieldTTF.extend({ }, onTextFieldInsertText: function (sender, text, len) { - if (len == 1 && text == "\n") + if (len === 1 && text === "\n") return false; this.setInsertText(true); @@ -81,7 +81,7 @@ ccui._TextFieldRenderer = cc.TextFieldTTF.extend({ insertText: function (text, len) { var input_text = text; - if (text != "\n"){ + if (text !== "\n"){ if (this._maxLengthEnabled){ var text_count = this.getString().length; if (text_count >= this._maxLength){ diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIListView.js b/extensions/ccui/uiwidgets/scroll-widget/UIListView.js index 89610664e2..370dd411b3 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIListView.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIListView.js @@ -156,7 +156,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ default: break; } - if (0 == itemIndex) + if (0 === itemIndex) layoutParameter.setMargin(ccui.MarginZero()); else layoutParameter.setMargin(new ccui.Margin(0.0, this._itemsMargin, 0.0, 0.0)); @@ -179,7 +179,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ default: break; } - if (0 == itemIndex) + if (0 === itemIndex) layoutParameter.setMargin(ccui.MarginZero()); else layoutParameter.setMargin(new ccui.Margin(this._itemsMargin, 0.0, 0.0, 0.0)); @@ -343,7 +343,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ * @param {ccui.ListView.GRAVITY_LEFT|ccui.ListView.GRAVITY_RIGHT|ccui.ListView.GRAVITY_CENTER_HORIZONTAL|ccui.ListView.GRAVITY_BOTTOM|ccui.ListView.GRAVITY_CENTER_VERTICAL} gravity */ setGravity: function (gravity) { - if (this._gravity == gravity) + if (this._gravity === gravity) return; this._gravity = gravity; this._refreshViewDirty = true; @@ -354,7 +354,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ * @param {Number} margin */ setItemsMargin: function (margin) { - if (this._itemsMargin == margin) + if (this._itemsMargin === margin) return; this._itemsMargin = margin; this._refreshViewDirty = true; @@ -445,7 +445,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ }, _selectedItemEvent: function (event) { - var eventEnum = (event == ccui.Widget.TOUCH_BEGAN) ? ccui.ListView.ON_SELECTED_ITEM_START : ccui.ListView.ON_SELECTED_ITEM_END; + var eventEnum = (event === ccui.Widget.TOUCH_BEGAN) ? ccui.ListView.ON_SELECTED_ITEM_START : ccui.ListView.ON_SELECTED_ITEM_END; if(this._listViewEventSelector){ if (this._listViewEventListener) this._listViewEventSelector.call(this._listViewEventListener, this, eventEnum); @@ -464,10 +464,10 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ */ interceptTouchEvent: function (eventType, sender, touch) { ccui.ScrollView.prototype.interceptTouchEvent.call(this, eventType, sender, touch); - if (eventType != ccui.Widget.TOUCH_MOVED) { + if (eventType !== ccui.Widget.TOUCH_MOVED) { var parent = sender; while (parent) { - if (parent && parent.getParent() == this._innerContainer) { + if (parent && parent.getParent() === this._innerContainer) { this._curSelectedIndex = this.getIndex(parent); break; } diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js b/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js index 8dd03b0b5a..ba4d69c2ff 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js @@ -138,7 +138,7 @@ ccui.PageView = ccui.Layout.extend(/** @lends ccui.PageView# */{ * @param {ccui.Layout} page */ addPage: function (page) { - if (!page || this._pages.indexOf(page) != -1) + if (!page || this._pages.indexOf(page) !== -1) return; this.addChild(page); @@ -152,7 +152,7 @@ ccui.PageView = ccui.Layout.extend(/** @lends ccui.PageView# */{ * @param {Number} idx index */ insertPage: function (page, idx) { - if (idx < 0 || !page || this._pages.indexOf(page) != -1) + if (idx < 0 || !page || this._pages.indexOf(page) !== -1) return; var pageCount = this._getPageCount(); diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js index 3bfa11913d..db3227ffbc 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js @@ -132,8 +132,8 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ * @returns {ccui.Widget} */ findNextFocusedWidget: function(direction, current){ - if (this.getLayoutType() == ccui.Layout.LINEAR_VERTICAL - || this.getLayoutType() == ccui.Layout.LINEAR_HORIZONTAL) { + if (this.getLayoutType() === ccui.Layout.LINEAR_VERTICAL + || this.getLayoutType() === ccui.Layout.LINEAR_HORIZONTAL) { return this._innerContainer.findNextFocusedWidget(direction, current); } else return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, current); @@ -656,7 +656,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ scrollEnabled = false; } this._moveChildren(realOffsetX, realOffsetY); - } else if (touchOffsetX == 0.0 && touchOffsetY > 0.0){ // bounce to top + } else if (touchOffsetX === 0.0 && touchOffsetY > 0.0){ // bounce to top realOffsetY = touchOffsetY; icTopPos = locContainer.getTopBoundary(); if (icTopPos + touchOffsetY >= this._topBoundary) { @@ -665,7 +665,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ scrollEnabled = false; } this._moveChildren(0.0, realOffsetY); - } else if (touchOffsetX == 0.0 && touchOffsetY < 0.0) {//bounce to bottom + } else if (touchOffsetX === 0.0 && touchOffsetY < 0.0) {//bounce to bottom realOffsetY = touchOffsetY; icBottomPos = locContainer.getBottomBoundary(); if (icBottomPos + touchOffsetY <= this._bottomBoundary) { @@ -674,7 +674,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ scrollEnabled = false; } this._moveChildren(0.0, realOffsetY); - } else if (touchOffsetX > 0.0 && touchOffsetY == 0.0){ //bounce to right + } else if (touchOffsetX > 0.0 && touchOffsetY === 0.0){ //bounce to right realOffsetX = touchOffsetX; icRightPos = locContainer.getRightBoundary(); if (icRightPos + realOffsetX >= this._rightBoundary) { @@ -683,7 +683,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ scrollEnabled = false; } this._moveChildren(realOffsetX, 0.0); - }else if (touchOffsetX < 0.0 && touchOffsetY == 0.0){ //bounce to left + }else if (touchOffsetX < 0.0 && touchOffsetY === 0.0){ //bounce to left realOffsetX = touchOffsetX; var icLeftPos = locContainer.getLeftBoundary(); if (icLeftPos + realOffsetX <= this._leftBoundary) { @@ -776,25 +776,25 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ touchOffsetY = locDestination.y - icTopPos; scrollEnabled = false; } - } else if (touchOffsetX == 0.0 && touchOffsetY > 0.0){ // up + } else if (touchOffsetX === 0.0 && touchOffsetY > 0.0){ // up icBottomPos = locContainer.getBottomBoundary(); if (icBottomPos + touchOffsetY >= locDestination.y) { touchOffsetY = locDestination.y - icBottomPos; scrollEnabled = false; } - } else if (touchOffsetX < 0.0 && touchOffsetY == 0.0){ // left + } else if (touchOffsetX < 0.0 && touchOffsetY === 0.0){ // left icRightPos = locContainer.getRightBoundary(); if (icRightPos + touchOffsetX <= locDestination.x) { touchOffsetX = locDestination.x - icRightPos; scrollEnabled = false; } - } else if (touchOffsetX == 0.0 && touchOffsetY < 0.0){ // down + } else if (touchOffsetX === 0.0 && touchOffsetY < 0.0){ // down icTopPos = locContainer.getTopBoundary(); if (icTopPos + touchOffsetY <= locDestination.y) { touchOffsetY = locDestination.y - icTopPos; scrollEnabled = false; } - } else if (touchOffsetX > 0.0 && touchOffsetY == 0.0){ // right + } else if (touchOffsetX > 0.0 && touchOffsetY === 0.0){ // right icLeftPos = locContainer.getLeftBoundary(); if (icLeftPos + touchOffsetX >= locDestination.x) { touchOffsetX = locDestination.x - icLeftPos; @@ -957,28 +957,28 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ this._scrollToTopEvent(); scrollEnabled = false; } - } else if (touchOffsetX == 0.0 && touchOffsetY > 0.0){ // up + } else if (touchOffsetX === 0.0 && touchOffsetY > 0.0){ // up icBottomPos = locContainer.getBottomBoundary(); if (icBottomPos + touchOffsetY >= this._bounceBottomBoundary) { realOffsetY = this._bounceBottomBoundary - icBottomPos; this._scrollToBottomEvent(); scrollEnabled = false; } - } else if (touchOffsetX < 0.0 && touchOffsetY == 0.0){ // left + } else if (touchOffsetX < 0.0 && touchOffsetY === 0.0){ // left icRightPos = locContainer.getRightBoundary(); if (icRightPos + touchOffsetX <= this._bounceRightBoundary) { realOffsetX = this._bounceRightBoundary - icRightPos; this._scrollToRightEvent(); scrollEnabled = false; } - } else if (touchOffsetX == 0.0 && touchOffsetY < 0.0){ // down + } else if (touchOffsetX === 0.0 && touchOffsetY < 0.0){ // down icTopPos = locContainer.getTopBoundary(); if (icTopPos + touchOffsetY <= this._bounceTopBoundary) { realOffsetY = this._bounceTopBoundary - icTopPos; this._scrollToTopEvent(); scrollEnabled = false; } - } else if (touchOffsetX > 0.0 && touchOffsetY == 0.0){ // right + } else if (touchOffsetX > 0.0 && touchOffsetY === 0.0){ // right icLeftPos = locContainer.getLeftBoundary(); if (icLeftPos + touchOffsetX >= this._bounceLeftBoundary) { realOffsetX = this._bounceLeftBoundary - icLeftPos; @@ -1039,28 +1039,28 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ this._scrollToTopEvent(); scrollEnabled = false; } - } else if (touchOffsetX == 0.0 && touchOffsetY > 0.0) { // up + } else if (touchOffsetX === 0.0 && touchOffsetY > 0.0) { // up icBottomPos = this._innerContainer.getBottomBoundary(); if (icBottomPos + touchOffsetY >= this._bottomBoundary) { realOffsetY = this._bottomBoundary - icBottomPos; this._scrollToBottomEvent(); scrollEnabled = false; } - } else if (touchOffsetX < 0.0 && touchOffsetY == 0.0){ // left + } else if (touchOffsetX < 0.0 && touchOffsetY === 0.0){ // left icRightPos = this._innerContainer.getRightBoundary(); if (icRightPos + touchOffsetX <= this._rightBoundary) { realOffsetX = this._rightBoundary - icRightPos; this._scrollToRightEvent(); scrollEnabled = false; } - } else if (touchOffsetX == 0.0 && touchOffsetY < 0.0){ // down + } else if (touchOffsetX === 0.0 && touchOffsetY < 0.0){ // down icTopPos = this._innerContainer.getTopBoundary(); if (icTopPos + touchOffsetY <= this._topBoundary) { realOffsetY = this._topBoundary - icTopPos; this._scrollToTopEvent(); scrollEnabled = false; } - } else if (touchOffsetX > 0.0 && touchOffsetY == 0.0){ // right + } else if (touchOffsetX > 0.0 && touchOffsetY === 0.0){ // right icLeftPos = this._innerContainer.getLeftBoundary(); if (icLeftPos + touchOffsetX >= this._leftBoundary) { realOffsetX = this._leftBoundary - icLeftPos; @@ -1117,7 +1117,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ * @param {Boolean} attenuated */ scrollToTopLeft: function (time, attenuated) { - if (this.direction != ccui.ScrollView.DIR_BOTH) { + if (this.direction !== ccui.ScrollView.DIR_BOTH) { cc.log("Scroll direction is not both!"); return; } @@ -1130,7 +1130,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ * @param {Boolean} attenuated */ scrollToTopRight: function (time, attenuated) { - if (this.direction != ccui.ScrollView.DIR_BOTH) { + if (this.direction !== ccui.ScrollView.DIR_BOTH) { cc.log("Scroll direction is not both!"); return; } @@ -1145,7 +1145,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ * @param {Boolean} attenuated */ scrollToBottomLeft: function (time, attenuated) { - if (this.direction != ccui.ScrollView.DIR_BOTH) { + if (this.direction !== ccui.ScrollView.DIR_BOTH) { cc.log("Scroll direction is not both!"); return; } @@ -1158,7 +1158,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ * @param {Boolean} attenuated */ scrollToBottomRight: function (time, attenuated) { - if (this.direction != ccui.ScrollView.DIR_BOTH) { + if (this.direction !== ccui.ScrollView.DIR_BOTH) { cc.log("Scroll direction is not both!"); return; } @@ -1195,7 +1195,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ * @param {Boolean} attenuated */ scrollToPercentBothDirection: function (percent, time, attenuated) { - if (this.direction != ccui.ScrollView.DIR_BOTH) + if (this.direction !== ccui.ScrollView.DIR_BOTH) return; var minY = this._contentSize.height - this._innerContainer.getContentSize().height; var h = -minY; @@ -1235,7 +1235,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ * Move inner container to top and left boundary of ScrollView. */ jumpToTopLeft: function () { - if (this.direction != ccui.ScrollView.DIR_BOTH) { + if (this.direction !== ccui.ScrollView.DIR_BOTH) { cc.log("Scroll direction is not both!"); return; } @@ -1246,7 +1246,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ * Move inner container to top and right boundary of ScrollView. */ jumpToTopRight: function () { - if (this.direction != ccui.ScrollView.DIR_BOTH) { + if (this.direction !== ccui.ScrollView.DIR_BOTH) { cc.log("Scroll direction is not both!"); return; } @@ -1258,7 +1258,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ * Move inner container to bottom and left boundary of ScrollView. */ jumpToBottomLeft: function () { - if (this.direction != ccui.ScrollView.DIR_BOTH) { + if (this.direction !== ccui.ScrollView.DIR_BOTH) { cc.log("Scroll direction is not both!"); return; } @@ -1269,7 +1269,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ * Move inner container to bottom and right boundary of ScrollView. */ jumpToBottomRight: function () { - if (this.direction != ccui.ScrollView.DIR_BOTH) { + if (this.direction !== ccui.ScrollView.DIR_BOTH) { cc.log("Scroll direction is not both!"); return; } @@ -1300,7 +1300,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ * @param {cc.Point} percent The destination vertical percent, accept value between 0 - 100 */ jumpToPercentBothDirection: function (percent) { - if (this.direction != ccui.ScrollView.DIR_BOTH) + if (this.direction !== ccui.ScrollView.DIR_BOTH) return; var inSize = this._innerContainer.getContentSize(); var minY = this._contentSize.height - inSize.height; diff --git a/extensions/cocostudio/action/CCActionManager.js b/extensions/cocostudio/action/CCActionManager.js index 903de51d8c..434fb83327 100644 --- a/extensions/cocostudio/action/CCActionManager.js +++ b/extensions/cocostudio/action/CCActionManager.js @@ -67,7 +67,7 @@ ccs.actionManager = /** @lends ccs.actionManager# */{ return null; for (var i = 0; i < actionList.length; i++) { var locAction = actionList[i]; - if (actionName == locAction.getName()) + if (actionName === locAction.getName()) return locAction; } return null; diff --git a/extensions/cocostudio/action/CCActionNode.js b/extensions/cocostudio/action/CCActionNode.js index 5dfb2ee28a..a4ae9a9332 100644 --- a/extensions/cocostudio/action/CCActionNode.js +++ b/extensions/cocostudio/action/CCActionNode.js @@ -256,7 +256,7 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{ }, _refreshActionProperty: function () { - if (this._object == null) + if (this._object === null) return null; var locSpawnArray = []; for (var i = 0; i < this._frameArrayNum; i++) { @@ -266,7 +266,7 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{ var locSequenceArray = []; for (var j = 0; j < locArray.length; j++) { var locFrame = locArray[j]; - if (j != 0) { + if (j !== 0) { var locSrcFrame = locArray[j - 1]; var locDuration = (locFrame.frameIndex - locSrcFrame.frameIndex) * this.getUnitTime(); var locAction = locFrame.getAction(locDuration); @@ -276,7 +276,7 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{ } if(locSequenceArray){ var locSequence = cc.sequence(locSequenceArray); - if (locSequence != null) + if (locSequence !== null) locSpawnArray.push(locSequence); } } @@ -291,7 +291,7 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{ * @param {cc.CallFunc} fun */ playAction: function (fun) { - if (this._object == null || this._actionSpawn == null) + if (this._object === null || this._actionSpawn === null) return; if(fun) this._action = cc.sequence(this._actionSpawn, fun); @@ -302,7 +302,7 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{ _runAction: function () { var node = this.getActionNode(); - if (node != null && this._action != null) + if (node !== null && this._action !== null) node.runAction(this._action); }, @@ -311,7 +311,7 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{ */ stopAction: function () { var node = this.getActionNode(); - if (node != null && this._action != null) { + if (node !== null && this._action !== null) { if(!this._action.isDone()) node.stopAction(this._action); } @@ -368,17 +368,17 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{ var locUnitTime = this.getUnitTime(); for (var i = 0; i < this._frameArrayNum; i++) { var locArray = this._frameArray[i]; - if (locArray == null) + if (locArray === null) continue; for (var j = 0; j < locArray.length; j++) { var locFrame = locArray[j]; - if (locFrame.frameIndex * locUnitTime == time) { + if (locFrame.frameIndex * locUnitTime === time) { this._easingToFrame(1.0, 1.0, locFrame); locIsFindFrame = true; break; } else if (locFrame.frameIndex * locUnitTime > time) { - if (j == 0) { + if (j === 0) { this._easingToFrame(1.0, 1.0, locFrame); locIsFindFrame = false; } else { @@ -410,7 +410,7 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{ * @returns {Boolean} that if the action is done once time */ isActionDoneOnce: function () { - if (this._action == null) + if (this._action === null) return true; return this._action.isDone(); } diff --git a/extensions/cocostudio/action/CCActionObject.js b/extensions/cocostudio/action/CCActionObject.js index 7c0ca0c9eb..88597f382e 100644 --- a/extensions/cocostudio/action/CCActionObject.js +++ b/extensions/cocostudio/action/CCActionObject.js @@ -250,7 +250,7 @@ ccs.ActionObject = ccs.Class.extend(/** @lends ccs.ActionObject# */{ } if (isEnd){ - if (this._callback != null) + if (this._callback !== null) this._callback.execute(); if (this._loop) this.play(); diff --git a/extensions/cocostudio/armature/CCArmature.js b/extensions/cocostudio/armature/CCArmature.js index d743c19b25..e2c912b02c 100644 --- a/extensions/cocostudio/armature/CCArmature.js +++ b/extensions/cocostudio/armature/CCArmature.js @@ -94,7 +94,7 @@ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{ var armatureDataManager = ccs.armatureDataManager; var animationData; - if (name != "") { + if (name !== "") { //animationData animationData = armatureDataManager.getAnimationData(name); cc.assert(animationData, "AnimationData not exist!"); @@ -279,7 +279,7 @@ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{ var locOffsetPoint = this._offsetPoint; locOffsetPoint.x = -rect.x; locOffsetPoint.y = -rect.y; - if (rect.width != 0 && rect.height != 0) + if (rect.width !== 0 && rect.height !== 0) this.setAnchorPoint(locOffsetPoint.x / rect.width, locOffsetPoint.y / rect.height); }, @@ -357,7 +357,7 @@ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{ var bone = locChildren[i]; if (bone) { var r = bone.getDisplayManager().getBoundingBox(); - if (r.x == 0 && r.y == 0 && r.width == 0 && r.height == 0) + if (r.x === 0 && r.y === 0 && r.width === 0 && r.height === 0) continue; if(first) { @@ -442,7 +442,7 @@ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{ }, setBody: function (body) { - if (this._body == body) + if (this._body === body) return; this._body = body; diff --git a/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js b/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js index ac491c13ba..4d0a4f06f3 100644 --- a/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js +++ b/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js @@ -114,7 +114,7 @@ var selBone = locChildren[i]; if (selBone && selBone.getDisplayRenderNode) { var selNode = selBone.getDisplayRenderNode(); - if (null == selNode) + if (null === selNode) continue; switch (selBone.getDisplayRenderNodeType()) { diff --git a/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js b/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js index 54bf4e762a..05e86742cd 100644 --- a/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js +++ b/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js @@ -50,7 +50,7 @@ var selBone = locChildren[i]; if (selBone && selBone.getDisplayRenderNode) { var selNode = selBone.getDisplayRenderNode(); - if (null == selNode) + if (null === selNode) continue; selNode.setShaderProgram(this._shaderProgram); switch (selBone.getDisplayRenderNodeType()) { @@ -60,10 +60,10 @@ selNode.updateTransform(); var func = selBone.getBlendFunc(); - if (func.src != alphaPremultiplied.src || func.dst != alphaPremultiplied.dst) + if (func.src !== alphaPremultiplied.src || func.dst !== alphaPremultiplied.dst) selNode.setBlendFunc(selBone.getBlendFunc()); else { - if ((node._blendFunc.src == alphaPremultiplied.src && node._blendFunc.dst == alphaPremultiplied.dst) + if ((node._blendFunc.src === alphaPremultiplied.src && node._blendFunc.dst === alphaPremultiplied.dst) && !selNode.getTexture().hasPremultipliedAlpha()) selNode.setBlendFunc(alphaNonPremultipled); else @@ -118,10 +118,10 @@ dis.updateTransform(); var func = selBone.getBlendFunc(); - if (func.src != alphaPremultiplied.src || func.dst != alphaPremultiplied.dst) + if (func.src !== alphaPremultiplied.src || func.dst !== alphaPremultiplied.dst) dis.setBlendFunc(selBone.getBlendFunc()); else { - if ((node._blendFunc.src == alphaPremultiplied.src && node_blendFunc.dst == alphaPremultiplied.dst) + if ((node._blendFunc.src === alphaPremultiplied.src && node_blendFunc.dst === alphaPremultiplied.dst) && !dis.getTexture().hasPremultipliedAlpha()) dis.setBlendFunc(alphaNonPremultipled); else diff --git a/extensions/cocostudio/armature/CCBone.js b/extensions/cocostudio/armature/CCBone.js index eb4bdff222..071ea83170 100644 --- a/extensions/cocostudio/armature/CCBone.js +++ b/extensions/cocostudio/armature/CCBone.js @@ -116,7 +116,7 @@ ccs.Bone = ccs.Node.extend(/** @lends ccs.Bone# */{ setBoneData: function (boneData) { cc.assert(boneData, "_boneData must not be null"); - if(this._boneData != boneData) + if(this._boneData !== boneData) this._boneData = boneData; this.setName(this._boneData.name); @@ -230,7 +230,7 @@ ccs.Bone = ccs.Node.extend(/** @lends ccs.Bone# */{ srcValue = blendFunc; dstValue = dst; } - if (locBlendFunc.src != srcValue || locBlendFunc.dst != dstValue) { + if (locBlendFunc.src !== srcValue || locBlendFunc.dst !== dstValue) { locBlendFunc.src = srcValue; locBlendFunc.dst = dstValue; this.blendDirty = true; @@ -242,7 +242,7 @@ ccs.Bone = ccs.Node.extend(/** @lends ccs.Bone# */{ */ updateColor: function () { var display = this._displayManager.getDisplayRenderNode(); - if (display != null) { + if (display !== null) { var cmd = this._renderCmd; display.setColor( cc.color( @@ -284,7 +284,7 @@ ccs.Bone = ccs.Node.extend(/** @lends ccs.Bone# */{ * @param {Boolean} recursion */ removeChildBone: function (bone, recursion) { - if (this._children.length > 0 && this._children.getIndex(bone) != -1 ) { + if (this._children.length > 0 && this._children.getIndex(bone) !== -1 ) { if(recursion) { var ccbones = bone._children; for(var i=0; i 0 ? this._durationTween : 1; this.movementEvent(this, ccs.MovementEventType.start, this._movementID); break; @@ -525,9 +525,9 @@ ccs.ArmatureAnimation = ccs.ProcessBase.extend(/** @lends ccs.ArmatureAnimation# * @param {Object} target */ setMovementEventCallFunc: function (callFunc, target) { - if(arguments.length == 1){ + if(arguments.length === 1){ this._movementEventListener = callFunc; - }else if(arguments.length == 2){ + }else if(arguments.length === 2){ this._movementEventTarget = target; this._movementEventCallFunc = callFunc; } @@ -539,9 +539,9 @@ ccs.ArmatureAnimation = ccs.ProcessBase.extend(/** @lends ccs.ArmatureAnimation# * @param {Object} target */ setFrameEventCallFunc: function (callFunc, target) { - if(arguments.length == 1){ + if(arguments.length === 1){ this._frameEventListener = callFunc; - }else if(arguments.length == 2){ + }else if(arguments.length === 2){ this._frameEventTarget = target; this._frameEventCallFunc = callFunc; } @@ -618,7 +618,7 @@ ccs.ArmatureAnimation = ccs.ProcessBase.extend(/** @lends ccs.ArmatureAnimation# * @param {ccs.AnimationData} data */ setAnimationData: function (data) { - if(this._animationData != data) + if(this._animationData !== data) this._animationData = data; }, diff --git a/extensions/cocostudio/armature/animation/CCProcessBase.js b/extensions/cocostudio/armature/animation/CCProcessBase.js index 9f2ec90f78..e98cb7fd94 100644 --- a/extensions/cocostudio/armature/animation/CCProcessBase.js +++ b/extensions/cocostudio/armature/animation/CCProcessBase.js @@ -220,9 +220,9 @@ ccs.ProcessBase = ccs.Class.extend(/** @lends ccs.ProcessBase# */{ */ gotoFrame: function (frameIndex) { var locLoopType = this._loopType; - if (locLoopType == ccs.ANIMATION_TYPE_NO_LOOP) + if (locLoopType === ccs.ANIMATION_TYPE_NO_LOOP) locLoopType = ccs.ANIMATION_TYPE_MAX; - else if (locLoopType == ccs.ANIMATION_TYPE_TO_LOOP_FRONT) + else if (locLoopType === ccs.ANIMATION_TYPE_TO_LOOP_FRONT) locLoopType = ccs.ANIMATION_TYPE_LOOP_FRONT; this._loopType = locLoopType; this._curFrameIndex = frameIndex; diff --git a/extensions/cocostudio/armature/animation/CCTween.js b/extensions/cocostudio/armature/animation/CCTween.js index f35dbb9f33..ce0da172cc 100644 --- a/extensions/cocostudio/armature/animation/CCTween.js +++ b/extensions/cocostudio/armature/animation/CCTween.js @@ -67,7 +67,7 @@ ccs.Tween = ccs.ProcessBase.extend(/** @lends ccs.Tween# */{ this._tweenData = this._bone.getTweenData(); this._tweenData.displayIndex = -1; - this._animation = (this._bone != null && this._bone.getArmature() != null) ? + this._animation = (this._bone !== null && this._bone.getArmature() !== null) ? this._bone.getArmature().getAnimation() : null; return true; @@ -89,7 +89,7 @@ ccs.Tween = ccs.ProcessBase.extend(/** @lends ccs.Tween# */{ this._betweenDuration = 0; this._fromIndex = this._toIndex = 0; - var difMovement = movementBoneData != this._movementBoneData; + var difMovement = movementBoneData !== this._movementBoneData; this.setMovementBoneData(movementBoneData); this._rawDuration = this._movementBoneData.duration; @@ -103,9 +103,9 @@ ccs.Tween = ccs.ProcessBase.extend(/** @lends ccs.Tween# */{ this._tweenData.scaleY += 1; } - if (this._rawDuration == 0) { + if (this._rawDuration === 0) { this._loopType = ccs.ANIMATION_TYPE_SINGLE_FRAME; - if (durationTo == 0) + if (durationTo === 0) this.setBetween(nextKeyFrame, nextKeyFrame); else this.setBetween(this._tweenData, nextKeyFrame); @@ -113,10 +113,10 @@ ccs.Tween = ccs.ProcessBase.extend(/** @lends ccs.Tween# */{ } else if (this._movementBoneData.frameList.length > 1) { this._durationTween = durationTween * this._movementBoneData.scale; - if (loop && this._movementBoneData.delay != 0) + if (loop && this._movementBoneData.delay !== 0) this.setBetween(this._tweenData, this.tweenNodeTo(this.updateFrameData(1 - this._movementBoneData.delay), this._between)); else { - if (!difMovement || durationTo == 0) + if (!difMovement || durationTo === 0) this.setBetween(nextKeyFrame, nextKeyFrame); else this.setBetween(this._tweenData, nextKeyFrame); @@ -188,7 +188,7 @@ ccs.Tween = ccs.ProcessBase.extend(/** @lends ccs.Tween# */{ locLoopType = ccs.ANIMATION_TYPE_LOOP_FRONT; this._nextFrameIndex = this._durationTween > 0 ? this._durationTween : 1; - if (this._movementBoneData.delay != 0) { + if (this._movementBoneData.delay !== 0) { this._currentFrame = (1 - this._movementBoneData.delay) * this._nextFrameIndex; locCurrentPercent = this._currentFrame / this._nextFrameIndex; } else { @@ -219,7 +219,7 @@ ccs.Tween = ccs.ProcessBase.extend(/** @lends ccs.Tween# */{ if (locLoopType > ccs.ANIMATION_TYPE_TO_LOOP_BACK) locCurrentPercent = this.updateFrameData(locCurrentPercent); - if (this._frameTweenEasing != ccs.TweenType.tweenEasingMax) + if (this._frameTweenEasing !== ccs.TweenType.tweenEasingMax) this.tweenNodeTo(locCurrentPercent); }, @@ -277,7 +277,7 @@ ccs.Tween = ccs.ProcessBase.extend(/** @lends ccs.Tween# */{ var childAramture = locBone.getChildArmature(); if (childAramture) { - if (keyFrameData.movement != "") + if (keyFrameData.movement !== "") childAramture.getAnimation().play(keyFrameData.movement); } } @@ -332,7 +332,7 @@ ccs.Tween = ccs.ProcessBase.extend(/** @lends ccs.Tween# */{ * @return {Number} */ updateFrameData:function (currentPercent) { //TODO set tweenColorTo to protected in v3.1 - if (currentPercent > 1 && this._movementBoneData.delay != 0) + if (currentPercent > 1 && this._movementBoneData.delay !== 0) currentPercent = ccs.fmodf(currentPercent,1); var playedTime = (this._rawDuration-1) * currentPercent; @@ -379,7 +379,7 @@ ccs.Tween = ccs.ProcessBase.extend(/** @lends ccs.Tween# */{ if(from.strEvent && !this._animation.isIgnoreFrameEvent()) this._animation.frameEvent(this._bone, from.strEvent,from.frameID, playedTime); - if (playedTime == from.frameID|| (this._passLastFrame && this._fromIndex == length-1)) + if (playedTime === from.frameID|| (this._passLastFrame && this._fromIndex === length-1)) break; } while (playedTime < from.frameID || playedTime >= to.frameID); @@ -391,13 +391,13 @@ ccs.Tween = ccs.ProcessBase.extend(/** @lends ccs.Tween# */{ this._betweenDuration = locBetweenDuration; this._toIndex = locToIndex; } - currentPercent = locBetweenDuration == 0 ? 0 : (playedTime - this._totalDuration) / this._betweenDuration; + currentPercent = locBetweenDuration === 0 ? 0 : (playedTime - this._totalDuration) / this._betweenDuration; /* * if frame tween easing equal to TWEEN_EASING_MAX, then it will not do tween. */ - var tweenType = (this._frameTweenEasing != ccs.TweenType.linear) ? this._frameTweenEasing : this._tweenEasing; - if (tweenType != ccs.TweenType.tweenEasingMax && tweenType != ccs.TweenType.linear && !this._passLastFrame) { + var tweenType = (this._frameTweenEasing !== ccs.TweenType.linear) ? this._frameTweenEasing : this._tweenEasing; + if (tweenType !== ccs.TweenType.tweenEasingMax && tweenType !== ccs.TweenType.linear && !this._passLastFrame) { currentPercent = ccs.TweenFunction.tweenTo(currentPercent, tweenType, this._from.easingParams); } return currentPercent; diff --git a/extensions/cocostudio/armature/datas/CCDatas.js b/extensions/cocostudio/armature/datas/CCDatas.js index ec4fad918c..bfab738d55 100644 --- a/extensions/cocostudio/armature/datas/CCDatas.js +++ b/extensions/cocostudio/armature/datas/CCDatas.js @@ -319,7 +319,7 @@ ccs.DisplayData = ccs.Class.extend(/** @lends ccs.DisplayData# */{ var textureName = displayName; var startPos = textureName.lastIndexOf("."); - if (startPos != -1) + if (startPos !== -1) textureName = textureName.substring(0, startPos); return textureName; }, @@ -580,7 +580,7 @@ ccs.FrameData = ccs.BaseData.extend(/** @lends ccs.FrameData# */{ // this.sound = frameData.sound; // this.soundEffect = frameData.soundEffect; // this.easingParams.length = 0; - if (this.easingParamNumber != 0){ + if (this.easingParamNumber !== 0){ this.easingParams.length = 0; for (var i = 0; i= ccs.CONST_VERSION_2_0) { x = frameXML.getAttribute(ccs.CONST_A_COCOS2DX_X); @@ -898,7 +898,7 @@ ccs.dataReaderHelper = /** @lends ccs.dataReaderHelper# */{ if(_easing != ccs.CONST_FL_NAN){ tweenEasing = frameXML.getAttribute(ccs.CONST_A_TWEEN_EASING); if( tweenEasing ) - frameData.tweenEasing = (tweenEasing == 2) ? ccs.TweenType.sineEaseInOut : tweenEasing; + frameData.tweenEasing = (tweenEasing === 2) ? ccs.TweenType.sineEaseInOut : tweenEasing; } else frameData.tweenEasing = ccs.TweenType.linear; } diff --git a/extensions/cocostudio/armature/utils/CCTransformHelp.js b/extensions/cocostudio/armature/utils/CCTransformHelp.js index 93084a8870..0d6228d5cd 100644 --- a/extensions/cocostudio/armature/utils/CCTransformHelp.js +++ b/extensions/cocostudio/armature/utils/CCTransformHelp.js @@ -103,7 +103,7 @@ ccs.TransformHelp.transformToParentWithoutScale = function(node, parentNode){ * @param {cc.AffineTransform} matrix */ ccs.TransformHelp.nodeToMatrix = function (node, matrix) { - if (node.skewX == -node.skewY) { + if (node.skewX === -node.skewY) { var sine = Math.sin(node.skewX); var cosine = Math.cos(node.skewX); matrix.a = node.scaleX * cosine; diff --git a/extensions/cocostudio/armature/utils/CCTweenFunction.js b/extensions/cocostudio/armature/utils/CCTweenFunction.js index 11cc1547c5..b6d62d482e 100644 --- a/extensions/cocostudio/armature/utils/CCTweenFunction.js +++ b/extensions/cocostudio/armature/utils/CCTweenFunction.js @@ -298,10 +298,10 @@ ccs.TweenFunction.quintEaseInOut = function (time) { // Expo Ease ccs.TweenFunction.expoEaseIn = function (time) { - return time == 0 ? 0 : Math.pow(2, 10 * (time - 1)) - 0.001; + return time === 0 ? 0 : Math.pow(2, 10 * (time - 1)) - 0.001; }; ccs.TweenFunction.expoEaseOut = function (time) { - return time == 1 ? 1 : (-Math.pow(2, -10 * time) + 1); + return time === 1 ? 1 : (-Math.pow(2, -10 * time) + 1); }; ccs.TweenFunction.expoEaseInOut = function (time) { time /= 0.5; @@ -342,7 +342,7 @@ ccs.TweenFunction.elasticEaseIn = function (time, easingParam) { } var newT = 0; - if (time == 0 || time == 1) { + if (time === 0 || time === 1) { newT = time; } else { @@ -361,7 +361,7 @@ ccs.TweenFunction.elasticEaseOut = function (time, easingParam) { } var newT = 0; - if (time == 0 || time == 1) { + if (time === 0 || time === 1) { newT = time; } else { @@ -379,7 +379,7 @@ ccs.TweenFunction.elasticEaseInOut = function (time, easingParam) { } var newT = 0; - if (time == 0 || time == 1) { + if (time === 0 || time === 1) { newT = time; } else { diff --git a/extensions/cocostudio/components/CCComController.js b/extensions/cocostudio/components/CCComController.js index e9bb63d719..cdd85eeb94 100644 --- a/extensions/cocostudio/components/CCComController.js +++ b/extensions/cocostudio/components/CCComController.js @@ -43,7 +43,7 @@ ccs.ComController = ccs.Component.extend(/** @lends ccs.ComController# */{ * @override */ onEnter: function () { - if (this._owner != null) + if (this._owner !== null) this._owner.scheduleUpdate(); }, diff --git a/extensions/cocostudio/components/CCComponentContainer.js b/extensions/cocostudio/components/CCComponentContainer.js index 1d54c6bc2d..c82103e7ee 100644 --- a/extensions/cocostudio/components/CCComponentContainer.js +++ b/extensions/cocostudio/components/CCComponentContainer.js @@ -152,7 +152,7 @@ cc.ComponentContainer = cc.Class.extend(/** @lends cc.ComponentContainer# */{ isEmpty: function () { if (!this._components) return true; - return this._components.length == 0; + return this._components.length === 0; } }); diff --git a/extensions/cocostudio/loader/parsers/action-1.x.js b/extensions/cocostudio/loader/parsers/action-1.x.js index c5c20446c4..e7123e7f54 100644 --- a/extensions/cocostudio/loader/parsers/action-1.x.js +++ b/extensions/cocostudio/loader/parsers/action-1.x.js @@ -55,7 +55,7 @@ if(frame) action.addTimeline(frame); - if(timeline["frameType"] == "ColorFrame"){ + if(timeline["frameType"] === "ColorFrame"){ action.addTimeline( self.parsers["AlphaFrame"].call(self, timeline, resourcePath) ); diff --git a/extensions/cocostudio/loader/parsers/compatible.js b/extensions/cocostudio/loader/parsers/compatible.js index 0969d257d5..caa681d4fc 100644 --- a/extensions/cocostudio/loader/parsers/compatible.js +++ b/extensions/cocostudio/loader/parsers/compatible.js @@ -91,9 +91,9 @@ * @returns {Number} */ getVersionInteger: function(version){ - if(!version || typeof version != "string") return 0; + if(!version || typeof version !== "string") return 0; var arr = version.split("."); - if (arr.length != 4) + if (arr.length !== 4) return 0; var num = 0; arr.forEach(function(n, i){ @@ -199,7 +199,7 @@ getNodeByTag: function(tag){ if (this._node == null) return null; - if (this._node.getTag() == tag) + if (this._node.getTag() === tag) return this._node; return this._nodeByTag(this._node, tag); }, @@ -211,7 +211,7 @@ var children = parent.getChildren(); for (var i = 0; i < children.length; i++) { var child = children[i]; - if (child && child.getTag() == tag) { + if (child && child.getTag() === tag) { retNode = child; break; } else { diff --git a/extensions/cocostudio/loader/parsers/scene-1.x.js b/extensions/cocostudio/loader/parsers/scene-1.x.js index aad9b5a73b..04569cb17f 100644 --- a/extensions/cocostudio/loader/parsers/scene-1.x.js +++ b/extensions/cocostudio/loader/parsers/scene-1.x.js @@ -92,9 +92,9 @@ "CCSprite": function(node, component, resourcePath){ var child = new cc.Sprite(); loadTexture(component["fileData"], resourcePath, function(path, type){ - if(type == 0) + if(type === 0) child.setTexture(path); - else if(type == 1){ + else if(type === 1){ var spriteFrame = cc.spriteFrameCache.getSpriteFrame(path); child.setSpriteFrame(spriteFrame); } @@ -106,7 +106,7 @@ "CCTMXTiledMap": function(node, component, resourcePath){ var child = null; loadTexture(component["fileData"], resourcePath, function(path, type){ - if(type == 0) + if(type === 0) child = new cc.TMXTiledMap(path); }); var render = new ccs.ComRender(child, "CCTMXTiledMap"); @@ -116,7 +116,7 @@ "CCParticleSystemQuad": function(node, component, resourcePath){ var child = null; loadTexture(component["fileData"], resourcePath, function(path, type){ - if(type == 0) + if(type === 0) child = new cc.ParticleSystem(path); else cc.log("unknown resourcetype on CCParticleSystemQuad!"); @@ -129,7 +129,7 @@ "CCArmature": function(node, component, resourcePath){ var child = null; loadTexture(component["fileData"], resourcePath, function(path, type){ - if(type == 0){ + if(type === 0){ var jsonDict = cc.loader.getRes(path); if (!jsonDict) cc.log("Please load the resource [%s] first!", path); var armature_data = jsonDict["armature_data"]; @@ -153,7 +153,7 @@ "CCComAudio": function(node, component, resourcePath){ var audio = null; loadTexture(component["fileData"], resourcePath, function(path, type){ - if(type == 0){ + if(type === 0){ audio = new ccs.ComAudio(); audio.preloadEffect(path); var name = component["name"]; @@ -166,9 +166,9 @@ "CCComAttribute": function(node, component, resourcePath){ var attribute = null; loadTexture(component["fileData"], resourcePath, function(path, type){ - if(type == 0){ + if(type === 0){ attribute = new ccs.ComAttribute(); - if (path != "") + if (path !== "") attribute.parse(path); node.addComponent(attribute); }else @@ -179,7 +179,7 @@ "CCBackgroundAudio": function(node, component, resourcePath){ var audio = null; loadTexture(component["fileData"], resourcePath, function(path, type){ - if(type == 0){ + if(type === 0){ audio = new ccs.ComAudio(); audio.preloadBackgroundMusic(path); audio.setFile(path);var bLoop = Boolean(component["loop"] || 0); diff --git a/extensions/cocostudio/loader/parsers/timelineParser-1.x.js b/extensions/cocostudio/loader/parsers/timelineParser-1.x.js index 5b0c849df9..c9c3efbab5 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-1.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-1.x.js @@ -33,7 +33,7 @@ }, addSpriteFrame: function(plists, pngs, resourcePath){ - if(!plists || !pngs || plists.length != pngs.length) + if(!plists || !pngs || plists.length !== pngs.length) return; for (var i = 0; i < plists.length; i++) { var plist = resourcePath + plists[i]; @@ -142,7 +142,7 @@ widget.pushBackCustomItem(child); } else { if(!(widget instanceof ccui.Layout) && child instanceof ccui.Widget) { - if(child.getPositionType() == ccui.Widget.POSITION_PERCENT) { + if(child.getPositionType() === ccui.Widget.POSITION_PERCENT) { var position = child.getPositionPercent(); var anchor = widget.getAnchorPoint(); child.setPositionPercent(cc.p(position.x + anchor.x, position.y + anchor.y)); @@ -167,7 +167,7 @@ var filePath = options["fileName"]; var node; - if (filePath && "" != filePath){ + if (filePath && "" !== filePath){ node = this.createNode(filePath); }else{ node = new ccs.Node(); @@ -219,9 +219,9 @@ var path = options["resourcePath"]; var tmx = null; - if (tmxFile && "" != tmxFile){ + if (tmxFile && "" !== tmxFile){ tmx = new cc.TMXTiledMap(tmxFile); - }else if (tmxString && "" != tmxString && path && "" != path){ + }else if (tmxString && "" !== tmxString && path && "" !== path){ tmx = new cc.TMXTiledMap(tmxString, path); } return tmx; diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index e3a9f47f3f..2eb90d429b 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -127,7 +127,7 @@ node.pushBackCustomItem(child); } else { if(!(node instanceof ccui.Layout) && child instanceof ccui.Widget) { - if(child.getPositionType() == ccui.Widget.POSITION_PERCENT) { + if(child.getPositionType() === ccui.Widget.POSITION_PERCENT) { var position = child.getPositionPercent(); var anchor = node.getAnchorPoint(); child.setPositionPercent(cc.p(position.x + anchor.x, position.y + anchor.y)); @@ -163,9 +163,9 @@ var node = new cc.Sprite(); loadTexture(json["FileData"], resourcePath, function(path, type){ - if(type == 0) + if(type === 0) node.setTexture(path); - else if(type == 1){ + else if(type === 1){ var spriteFrame = cc.spriteFrameCache.getSpriteFrame(path); node.setSpriteFrame(spriteFrame); } @@ -333,21 +333,21 @@ layoutComponent.setStretchHeightEnabled(stretchVerticalEnabled); var horizontalEdgeType = ccui.LayoutComponent.horizontalEdge.NONE; - if (horizontalEdge == "LeftEdge"){ + if (horizontalEdge === "LeftEdge"){ horizontalEdgeType = ccui.LayoutComponent.horizontalEdge.LEFT; - }else if (horizontalEdge == "RightEdge"){ + }else if (horizontalEdge === "RightEdge"){ horizontalEdgeType = ccui.LayoutComponent.horizontalEdge.RIGHT; - }else if (horizontalEdge == "BothEdge"){ + }else if (horizontalEdge === "BothEdge"){ horizontalEdgeType = ccui.LayoutComponent.horizontalEdge.CENTER; } layoutComponent.setHorizontalEdge(horizontalEdgeType); var verticalEdgeType = ccui.LayoutComponent.verticalEdge.NONE; - if (verticalEdge == "TopEdge"){ + if (verticalEdge === "TopEdge"){ verticalEdgeType = ccui.LayoutComponent.verticalEdge.TOP; - }else if (verticalEdge == "BottomEdge"){ + }else if (verticalEdge === "BottomEdge"){ verticalEdgeType = ccui.LayoutComponent.verticalEdge.BOTTOM; - }else if (verticalEdge == "BothEdge"){ + }else if (verticalEdge === "BothEdge"){ verticalEdgeType = ccui.LayoutComponent.verticalEdge.CENTER; } layoutComponent.setVerticalEdge(verticalEdgeType); @@ -696,9 +696,9 @@ widget.setInnerContainerSize(innerSize); var direction = 0; - if(json["ScrollDirectionType"] == "Vertical") direction = 1; - if(json["ScrollDirectionType"] == "Horizontal") direction = 2; - if(json["ScrollDirectionType"] == "Vertical_Horizontal") direction = 3; + if(json["ScrollDirectionType"] === "Vertical") direction = 1; + if(json["ScrollDirectionType"] === "Horizontal") direction = 2; + if(json["ScrollDirectionType"] === "Vertical_Horizontal") direction = 3; widget.setDirection(direction); var bounceEnabled = getParam(json["IsBounceEnabled"], false); @@ -795,7 +795,7 @@ ]; textureList.forEach(function(item){ loadTexture(json[item.name], resourcePath, function(path, type){ - if(type == 0 && !loader.getRes(path)) + if(type === 0 && !loader.getRes(path)) cc.log("%s need to be preloaded", path); item.handle.call(widget, path, type); }); @@ -912,19 +912,19 @@ var horizontalType = getParam(json["HorizontalType"], "Align_Top"); if(!directionType){ widget.setDirection(ccui.ScrollView.DIR_HORIZONTAL); - if(verticalType == "Align_Bottom") + if(verticalType === "Align_Bottom") widget.setGravity(ccui.ListView.GRAVITY_BOTTOM); - else if(verticalType == "Align_VerticalCenter") + else if(verticalType === "Align_VerticalCenter") widget.setGravity(ccui.ListView.GRAVITY_CENTER_VERTICAL); else widget.setGravity(ccui.ListView.GRAVITY_TOP); - }else if(directionType == "Vertical"){ + }else if(directionType === "Vertical"){ widget.setDirection(ccui.ScrollView.DIR_VERTICAL); - if (horizontalType == "") + if (horizontalType === "") widget.setGravity(ccui.ListView.GRAVITY_LEFT); - else if (horizontalType == "Align_Right") + else if (horizontalType === "Align_Right") widget.setGravity(ccui.ListView.GRAVITY_RIGHT); - else if (horizontalType == "Align_HorizontalCenter") + else if (horizontalType === "Align_HorizontalCenter") widget.setGravity(ccui.ListView.GRAVITY_CENTER_HORIZONTAL); } @@ -986,7 +986,7 @@ loadTexture(json["LabelAtlasFileImage_CNB"], resourcePath, function(path, type){ if(!cc.loader.getRes(path)) cc.log("%s need to be preloaded", path); - if(type == 0){ + if(type === 0){ widget.setProperty(stringValue, path, itemWidth, itemHeight, startCharMap); } }); @@ -1126,7 +1126,7 @@ var node = null; loadTexture(json["FileData"], resourcePath, function(path, type){ - if(type == 0) + if(type === 0) node = new cc.TMXTiledMap(path); parser.generalAttributes(node, json); @@ -1212,7 +1212,7 @@ if(json != null){ var path = json["Path"]; var type; - if(json["Type"] == "Default" || json["Type"] == "Normal") + if(json["Type"] === "Default" || json["Type"] === "Normal") type = 0; else type = 1; diff --git a/extensions/cocostudio/loader/parsers/uiParser-1.x.js b/extensions/cocostudio/loader/parsers/uiParser-1.x.js index 41500f531f..c27002bb22 100644 --- a/extensions/cocostudio/loader/parsers/uiParser-1.x.js +++ b/extensions/cocostudio/loader/parsers/uiParser-1.x.js @@ -186,7 +186,7 @@ widget.pushBackCustomItem(child); } else { if(!(widget instanceof ccui.Layout)) { - if(child.getPositionType() == ccui.Widget.POSITION_PERCENT) { + if(child.getPositionType() === ccui.Widget.POSITION_PERCENT) { var position = child.getPositionPercent(); var anchor = widget.getAnchorPoint(); child.setPositionPercent(cc.p(position.x + anchor.x, position.y + anchor.y)); @@ -203,7 +203,7 @@ var getPath = function(res, type, path, cb){ if(path){ - if(type == 0) + if(type === 0) cb(res + path, type); else cb(path, type); diff --git a/extensions/cocostudio/timeline/ActionTimeline.js b/extensions/cocostudio/timeline/ActionTimeline.js index bc5a60cc00..ec1a707419 100644 --- a/extensions/cocostudio/timeline/ActionTimeline.js +++ b/extensions/cocostudio/timeline/ActionTimeline.js @@ -368,7 +368,7 @@ ccs.ActionTimeline = cc.Action.extend({ * @param {number} delta */ step: function(delta){ - if (!this._playing || this._timelineMap.length == 0 || this._duration == 0) + if (!this._playing || this._timelineMap.length === 0 || this._duration === 0) { return; } diff --git a/extensions/cocostudio/timeline/Frame.js b/extensions/cocostudio/timeline/Frame.js index 83013aa842..460bbf86d2 100644 --- a/extensions/cocostudio/timeline/Frame.js +++ b/extensions/cocostudio/timeline/Frame.js @@ -320,7 +320,7 @@ ccs.RotationFrame = ccs.Frame.extend({ * @param {number} percent */ apply: function(percent){ - if (this._tween && this._betwennRotation != 0){ + if (this._tween && this._betwennRotation !== 0){ var rotation = this._rotation + percent * this._betwennRotation; this._node.setRotation(rotation); } @@ -406,7 +406,7 @@ ccs.SkewFrame = ccs.Frame.extend({ * @param {number} percent */ apply: function(percent){ - if (this._tween && (this._betweenSkewX != 0 || this._betweenSkewY != 0)) + if (this._tween && (this._betweenSkewX !== 0 || this._betweenSkewY !== 0)) { var skewx = this._skewX + percent * this._betweenSkewX; var skewy = this._skewY + percent * this._betweenSkewY; @@ -504,7 +504,7 @@ ccs.RotationSkewFrame = ccs.SkewFrame.extend({ * @param {number} percent */ apply: function(percent){ - if (this._tween && (this._betweenSkewX != 0 || this._betweenSkewY != 0)){ + if (this._tween && (this._betweenSkewX !== 0 || this._betweenSkewY !== 0)){ var skewx = this._skewX + percent * this._betweenSkewX; var skewy = this._skewY + percent * this._betweenSkewY; @@ -576,7 +576,7 @@ ccs.PositionFrame = ccs.Frame.extend({ * @param {number} percent */ apply: function(percent){ - if (this._tween && (this._betweenX != 0 || this._betweenY != 0)){ + if (this._tween && (this._betweenX !== 0 || this._betweenY !== 0)){ var p = cc.p(0, 0); p.x = this._position.x + this._betweenX * percent; p.y = this._position.y + this._betweenY * percent; @@ -697,7 +697,7 @@ ccs.ScaleFrame = ccs.Frame.extend({ * @param {number} percent */ apply: function(percent){ - if (this._tween && (this._betweenScaleX != 0 || this._betweenScaleY != 0)){ + if (this._tween && (this._betweenScaleX !== 0 || this._betweenScaleY !== 0)){ var scaleX = this._scaleX + this._betweenScaleX * percent; var scaleY = this._scaleY + this._betweenScaleY * percent; @@ -877,7 +877,7 @@ ccs.InnerActionFrame = ccs.Frame.extend({ */ onEnter: function(nextFrame){ var innerActiontimeline = this._node.getActionByTag(this._node.getTag()); - if (/*ccs.InnerActionType.SingleFrame*/"SingleFrame" == this._innerActionType){ + if (/*ccs.InnerActionType.SingleFrame*/"SingleFrame" === this._innerActionType){ innerActiontimeline.gotoFrameAndPause(this._singleFrameIndex); return; } @@ -885,7 +885,7 @@ ccs.InnerActionFrame = ccs.Frame.extend({ var innerStart = this._startFrameIndex; var innerEnd = this._endFrameIndex; if (this._enterWithName){ - if (this._animationName == "-- ALL --"){ + if (this._animationName === "-- ALL --"){ innerStart = 0; innerEnd = innerActiontimeline.getDuration(); } else if(innerActiontimeline.IsAnimationInfoExists(this._animationName)) { @@ -903,9 +903,9 @@ ccs.InnerActionFrame = ccs.Frame.extend({ innerEnd += odddiff; } - if (ccs.InnerActionType.NoLoopAction == this._innerActionType){ + if (ccs.InnerActionType.NoLoopAction === this._innerActionType){ innerActiontimeline.gotoFrameAndPlay(innerStart, innerEnd, false); - }else if (ccs.InnerActionType.LoopAction == this._innerActionType){ + }else if (ccs.InnerActionType.LoopAction === this._innerActionType){ innerActiontimeline.gotoFrameAndPlay(innerStart, innerEnd, true); } }, @@ -1034,7 +1034,7 @@ ccs.ColorFrame = ccs.Frame.extend({ * @param {number} percent */ apply: function(percent){ - if (this._tween && (this._betweenAlpha !=0 || this._betweenRed != 0 || this._betweenGreen != 0 || this._betweenBlue != 0)){ + if (this._tween && (this._betweenAlpha !== 0 || this._betweenRed !== 0 || this._betweenGreen !== 0 || this._betweenBlue !== 0)){ var color = cc.color(255, 255, 255); color.r = this._color.r + this._betweenRed * percent; @@ -1042,7 +1042,7 @@ ccs.ColorFrame = ccs.Frame.extend({ color.b = this._color.b + this._betweenBlue * percent; this._node.setColor(color); - if(this._alpha != null){ + if(this._alpha !== null){ var alpha = this._alpha + this._betweenAlpha * percent; this._node.setOpacity(alpha); } diff --git a/extensions/cocostudio/timeline/Timeline.js b/extensions/cocostudio/timeline/Timeline.js index 783d97fd26..273ef72a11 100644 --- a/extensions/cocostudio/timeline/Timeline.js +++ b/extensions/cocostudio/timeline/Timeline.js @@ -61,7 +61,7 @@ ccs.Timeline = ccs.Class.extend({ }, _gotoFrame: function(frameIndex){ - if(this._frames.length == 0) + if(this._frames.length === 0) return; this._binarySearchKeyFrame(frameIndex); @@ -69,7 +69,7 @@ ccs.Timeline = ccs.Class.extend({ }, _stepToFrame: function(frameIndex){ - if(this._frames.length == 0) + if(this._frames.length === 0) return; this._updateCurrentKeyFrame(frameIndex); @@ -187,7 +187,7 @@ ccs.Timeline = ccs.Class.extend({ _apply: function(frameIndex){ if (this._currentKeyFrame) { - var currentPercent = this._betweenDuration == 0 ? 0 : (frameIndex - this._currentKeyFrameIndex) / this._betweenDuration; + var currentPercent = this._betweenDuration === 0 ? 0 : (frameIndex - this._currentKeyFrameIndex) / this._betweenDuration; this._currentKeyFrame.apply(currentPercent); } }, @@ -239,15 +239,14 @@ ccs.Timeline = ccs.Class.extend({ from = this._frames[target]; to = this._frames[target+1]; - if(target == 0 && this._currentKeyFrameIndex < from.getFrameIndex()) + if(target === 0 && this._currentKeyFrameIndex < from.getFrameIndex()) needEnterFrame = true; this._currentKeyFrameIndex = from.getFrameIndex(); this._betweenDuration = to.getFrameIndex() - from.getFrameIndex(); } while (0); - if(needEnterFrame || this._currentKeyFrame != from) - { + if(needEnterFrame || this._currentKeyFrame != from) { this._currentKeyFrame = from; this._currentKeyFrame.onEnter(to); } @@ -293,7 +292,7 @@ ccs.Timeline = ccs.Class.extend({ to = this._frames[this._toIndex]; - if (frameIndex == from.getFrameIndex()) + if (frameIndex === from.getFrameIndex()) { break; } diff --git a/extensions/cocostudio/trigger/TriggerMng.js b/extensions/cocostudio/trigger/TriggerMng.js index f647e7ce6f..e0167a1ab6 100644 --- a/extensions/cocostudio/trigger/TriggerMng.js +++ b/extensions/cocostudio/trigger/TriggerMng.js @@ -78,7 +78,7 @@ ccs.triggerManager = /** @lends ccs.triggerManager# */{ var eventTriggers = this._eventTriggers[event]; if (!eventTriggers) eventTriggers = []; - if (eventTriggers.indexOf(triggerObj) == -1) { + if (eventTriggers.indexOf(triggerObj) === -1) { eventTriggers.push(triggerObj); this._eventTriggers[event] = eventTriggers; } @@ -180,7 +180,7 @@ ccs.triggerManager = /** @lends ccs.triggerManager# */{ var locAmd, hasADD = false; for (var i = 0; i < this._movementDispatches.length; i++) { locAmd = this._movementDispatches[i]; - if (locAmd && locAmd[0] == armature) { + if (locAmd && locAmd[0] === armature) { locAmd.addAnimationEventCallBack(callFunc, target); hasADD = true; } @@ -205,7 +205,7 @@ ccs.triggerManager = /** @lends ccs.triggerManager# */{ var locAmd; for (var i = 0; i < this._movementDispatches.length; i++) { locAmd = this._movementDispatches[i]; - if (locAmd && locAmd[0] == armature) + if (locAmd && locAmd[0] === armature) locAmd.removeAnimationEventCallBack(callFunc, target); } }, @@ -220,7 +220,7 @@ ccs.triggerManager = /** @lends ccs.triggerManager# */{ var locAmd; for (var i = 0; i < this._movementDispatches.length; i++) { locAmd = this._movementDispatches[i]; - if (locAmd && locAmd[0] == armature) { + if (locAmd && locAmd[0] === armature) { this._movementDispatches.splice(i, 1); break; } @@ -293,7 +293,7 @@ ccs.ArmatureMovementDispatcher = ccs.Class.extend(/** @lends ccs.ArmatureMovemen var locEventAni; for (var i = 0; i < this._mapEventAnimation.length; i++) { locEventAni = this._mapEventAnimation[i]; - if (locEventAni[0] == target) { + if (locEventAni[0] === target) { this._mapEventAnimation.splice(i, 1); } } diff --git a/extensions/cocostudio/trigger/TriggerObj.js b/extensions/cocostudio/trigger/TriggerObj.js index 5d4e36af4b..6a8e3c1226 100644 --- a/extensions/cocostudio/trigger/TriggerObj.js +++ b/extensions/cocostudio/trigger/TriggerObj.js @@ -140,7 +140,7 @@ ccs.TriggerObj = ccs.Class.extend(/** @lends ccs.TriggerObj# */{ * @returns {boolean} */ detect: function () { - if (!this._enable || this._cons.length == 0) { + if (!this._enable || this._cons.length === 0) { return true; } var ret = true; @@ -157,7 +157,7 @@ ccs.TriggerObj = ccs.Class.extend(/** @lends ccs.TriggerObj# */{ * Sets trigger's actions to done. */ done: function () { - if (!this._enable || this._acts.length == 0) + if (!this._enable || this._acts.length === 0) return; var obj; for (var i = 0; i < this._acts.length; i++) { diff --git a/extensions/editbox/CCEditBox.js b/extensions/editbox/CCEditBox.js index 561e771d77..4c68eb84c2 100644 --- a/extensions/editbox/CCEditBox.js +++ b/extensions/editbox/CCEditBox.js @@ -273,11 +273,11 @@ cc.EditBox = cc.ControlButton.extend({ } }); cc._addEventListener(tmpEdTxt, "focus", function () { - if (this.value == selfPointer._placeholderText) { + if (this.value === selfPointer._placeholderText) { this.value = ""; this.style.fontSize = selfPointer._edFontSize + "px"; this.style.color = cc.colorToHex(selfPointer._textColor); - if (selfPointer._editBoxInputFlag == cc.EDITBOX_INPUT_FLAG_PASSWORD) + if (selfPointer._editBoxInputFlag === cc.EDITBOX_INPUT_FLAG_PASSWORD) selfPointer._edTxt.type = "password"; else selfPointer._edTxt.type = "text"; @@ -287,7 +287,7 @@ cc.EditBox = cc.ControlButton.extend({ cc._addEventListener(cc._canvas, "click", onCanvasClick); }); cc._addEventListener(tmpEdTxt, "blur", function () { - if (this.value == "") { + if (this.value === "") { this.value = selfPointer._placeholderText; this.style.fontSize = selfPointer._placeholderFontSize + "px"; this.style.color = cc.colorToHex(selfPointer._placeholderColor); @@ -358,10 +358,10 @@ cc.EditBox = cc.ControlButton.extend({ }, _setFontToEditBox: function () { - if (this._edTxt.value != this._placeholderText) { + if (this._edTxt.value !== this._placeholderText) { this._edTxt.style.fontFamily = this._edFontName; this._edTxt.style.fontSize = this._edFontSize + "px"; - if (this._editBoxInputFlag == cc.EDITBOX_INPUT_FLAG_PASSWORD) + if (this._editBoxInputFlag === cc.EDITBOX_INPUT_FLAG_PASSWORD) this._edTxt.type = "password"; else this._edTxt.type = "text"; @@ -384,14 +384,14 @@ cc.EditBox = cc.ControlButton.extend({ */ setString: function (text) { if (text != null) { - if (text == "") { + if (text === "") { this._edTxt.value = this._placeholderText; this._edTxt.style.color = cc.colorToHex(this._placeholderColor); this._edTxt.type = "text"; } else { this._edTxt.value = text; this._edTxt.style.color = cc.colorToHex(this._textColor); - if (this._editBoxInputFlag == cc.EDITBOX_INPUT_FLAG_PASSWORD) + if (this._editBoxInputFlag === cc.EDITBOX_INPUT_FLAG_PASSWORD) this._edTxt.type = "password"; else this._edTxt.type = "text"; @@ -405,7 +405,7 @@ cc.EditBox = cc.ControlButton.extend({ */ setFontColor: function (color) { this._textColor = color; - if (this._edTxt.value != this._placeholderText) { + if (this._edTxt.value !== this._placeholderText) { this._edTxt.style.color = cc.colorToHex(color); } }, @@ -440,7 +440,7 @@ cc.EditBox = cc.ControlButton.extend({ if (text != null) { var oldPlaceholderText = this._placeholderText; this._placeholderText = text; - if (this._edTxt.value == oldPlaceholderText) { + if (this._edTxt.value === oldPlaceholderText) { this._edTxt.value = text; this._edTxt.style.color = cc.colorToHex(this._placeholderColor); this._setPlaceholderFontToEditText(); @@ -486,7 +486,7 @@ cc.EditBox = cc.ControlButton.extend({ }, _setPlaceholderFontToEditText: function () { - if (this._edTxt.value == this._placeholderText) { + if (this._edTxt.value === this._placeholderText) { this._edTxt.style.fontFamily = this._placeholderFontName; this._edTxt.style.fontSize = this._placeholderFontSize + "px"; this._edTxt.type = "text"; @@ -499,7 +499,7 @@ cc.EditBox = cc.ControlButton.extend({ */ setPlaceholderFontColor: function (color) { this._placeholderColor = color; - if (this._edTxt.value == this._placeholderText) { + if (this._edTxt.value === this._placeholderText) { this._edTxt.style.color = cc.colorToHex(color); } }, @@ -511,7 +511,7 @@ cc.EditBox = cc.ControlButton.extend({ */ setInputFlag: function (inputFlag) { this._editBoxInputFlag = inputFlag; - if ((this._edTxt.value !== this._placeholderText) && (inputFlag == cc.EDITBOX_INPUT_FLAG_PASSWORD)) + if ((this._edTxt.value !== this._placeholderText) && (inputFlag === cc.EDITBOX_INPUT_FLAG_PASSWORD)) this._edTxt.type = "password"; else this._edTxt.type = "text"; diff --git a/extensions/editbox/CCdomNode.js b/extensions/editbox/CCdomNode.js index fb62932ed3..c38ac03136 100644 --- a/extensions/editbox/CCdomNode.js +++ b/extensions/editbox/CCdomNode.js @@ -291,7 +291,7 @@ cc.DOM.methods = /** @lends cc.DOM# */{ * @param {Number} newRotation */ setRotation:function (newRotation) { - if (this._rotation == newRotation) + if (this._rotation === newRotation) return; this._rotationX = this._rotationY = newRotation; @@ -360,7 +360,7 @@ cc.DOM.methods = /** @lends cc.DOM# */{ //if dom does not have parent, but node has no parent and its running if (this.dom && !this.dom.parentNode) { if (!this.getParent()) { - if(this.dom.id == ""){ + if(this.dom.id === ""){ cc.DOM._createEGLViewDiv(this); }else{ this.dom.appendTo(cc.container); @@ -451,7 +451,7 @@ cc.DOM._resetEGLViewDiv = function(){ div.style.margin = 0; div.resize(view.getScaleX()/pixelRatio, view.getScaleY()/pixelRatio); - if (view.getResolutionPolicy() == view._rpNoBorder) { + if (view.getResolutionPolicy() === view._rpNoBorder) { div.style.left = (view.getFrameSize().width - designSizeWidth)/2 + "px"; div.style.bottom = (view.getFrameSize().height - designSizeHeight*view.getScaleY()/pixelRatio)/2 + "px"; } @@ -528,7 +528,7 @@ cc.DOM._createEGLViewDiv = function(p){ div.style.margin = 0; div.resize(view.getScaleX()/pixelRatio, view.getScaleY()/pixelRatio); - if (view.getResolutionPolicy() == view._rpNoBorder) { + if (view.getResolutionPolicy() === view._rpNoBorder) { div.style.left = (screenSize.width - designSizeWidth)/2 + "px"; div.style.bottom = (screenSize.height - designSizeHeight*view.getScaleY()/pixelRatio)/2 + "px"; } @@ -632,7 +632,7 @@ cc.DOM.convert = function (nodeObject) { if (arguments.length > 1) { cc.DOM.convert(arguments); return; - } else if (arguments.length == 1 && !arguments[0].length) { + } else if (arguments.length === 1 && !arguments[0].length) { cc.DOM.convert([arguments[0]]); return; } diff --git a/extensions/gui/control-extension/CCControl.js b/extensions/gui/control-extension/CCControl.js index cb4011c241..2ff72a7ee7 100644 --- a/extensions/gui/control-extension/CCControl.js +++ b/extensions/gui/control-extension/CCControl.js @@ -335,9 +335,9 @@ cc.Control = cc.Layer.extend(/** @lends cc.Control# */{ var invocation = eventInvocationList[i]; var shouldBeRemoved = true; if (target) - shouldBeRemoved = (target == invocation.getTarget()); + shouldBeRemoved = (target === invocation.getTarget()); if (action) - shouldBeRemoved = (shouldBeRemoved && (action == invocation.getAction())); + shouldBeRemoved = (shouldBeRemoved && (action === invocation.getAction())); // Remove the corresponding invocation object if (shouldBeRemoved) cc.arrayRemoveObject(eventInvocationList, invocation); diff --git a/extensions/gui/control-extension/CCControlButton.js b/extensions/gui/control-extension/CCControlButton.js index 6f198bc9a3..068a649ff8 100644 --- a/extensions/gui/control-extension/CCControlButton.js +++ b/extensions/gui/control-extension/CCControlButton.js @@ -461,7 +461,7 @@ cc.ControlButton = cc.Control.extend(/** @lends cc.ControlButton# */{ this._titleDispatchTable[state] = title || ""; // If the current state if equal to the given state we update the layout - if (this.getState() == state) + if (this.getState() === state) this.needsLayout(); }, @@ -492,7 +492,7 @@ cc.ControlButton = cc.Control.extend(/** @lends cc.ControlButton# */{ this._titleColorDispatchTable[state] = color; // If the current state if equal to the given state we update the layout - if (this.getState() == state) + if (this.getState() === state) this.needsLayout(); }, @@ -531,7 +531,7 @@ cc.ControlButton = cc.Control.extend(/** @lends cc.ControlButton# */{ this.addChild(titleLabel, 1); // If the current state if equal to the given state we update the layout - if (this.getState() == state) + if (this.getState() === state) this.needsLayout(); }, diff --git a/extensions/gui/control-extension/CCControlColourPicker.js b/extensions/gui/control-extension/CCControlColourPicker.js index 4e7a49f039..6cdfd6bcc8 100644 --- a/extensions/gui/control-extension/CCControlColourPicker.js +++ b/extensions/gui/control-extension/CCControlColourPicker.js @@ -151,7 +151,7 @@ cc.ControlColourPicker = cc.Control.extend(/** @lends cc.ControlColourPicker# */ }, setEnabled:function (enabled) { cc.Control.prototype.setEnabled.call(this, enabled); - if (this._huePicker != null) { + if (this._huePicker !== null) { this._huePicker.setEnabled(enabled); } if (this._colourPicker) { diff --git a/extensions/gui/control-extension/CCControlPotentiometer.js b/extensions/gui/control-extension/CCControlPotentiometer.js index 3fb2d8bba1..7c035efd5c 100644 --- a/extensions/gui/control-extension/CCControlPotentiometer.js +++ b/extensions/gui/control-extension/CCControlPotentiometer.js @@ -99,7 +99,7 @@ cc.ControlPotentiometer = cc.Control.extend(/** @lends cc.ControlPotentiometer# setEnabled:function (enabled) { this.setEnabled(enabled); - if (this._thumbSprite != NULL) { + if (this._thumbSprite !== null) { this._thumbSprite.setOpacity((enabled) ? 255 : 128); } }, diff --git a/extensions/gui/control-extension/CCControlStepper.js b/extensions/gui/control-extension/CCControlStepper.js index f9757cc3b2..5dbc5e5d63 100644 --- a/extensions/gui/control-extension/CCControlStepper.js +++ b/extensions/gui/control-extension/CCControlStepper.js @@ -210,8 +210,8 @@ cc.ControlStepper = cc.Control.extend(/** @lends cc.ControlStepper# */{ this._value = value; if (!this._wraps) { - this._minusLabel.setColor((value == this._minimumValue) ? cc.CONTROL_STEPPER_LABELCOLOR_DISABLED : cc.CONTROL_STEPPER_LABELCOLOR_ENABLED); - this._plusLabel.setColor((value == this._maximumValue) ? cc.CONTROL_STEPPER_LABELCOLOR_DISABLED : cc.CONTROL_STEPPER_LABELCOLOR_ENABLED); + this._minusLabel.setColor((value === this._minimumValue) ? cc.CONTROL_STEPPER_LABELCOLOR_DISABLED : cc.CONTROL_STEPPER_LABELCOLOR_ENABLED); + this._plusLabel.setColor((value === this._maximumValue) ? cc.CONTROL_STEPPER_LABELCOLOR_DISABLED : cc.CONTROL_STEPPER_LABELCOLOR_ENABLED); } if (send) { @@ -232,12 +232,12 @@ cc.ControlStepper = cc.Control.extend(/** @lends cc.ControlStepper# */{ update:function (dt) { this._autorepeatCount++; - if ((this._autorepeatCount < cc.AUTOREPEAT_INCREASETIME_INCREMENT) && (this._autorepeatCount % 3) != 0) + if ((this._autorepeatCount < cc.AUTOREPEAT_INCREASETIME_INCREMENT) && (this._autorepeatCount % 3) !== 0) return; - if (this._touchedPart == cc.CONTROL_STEPPER_PARTMINUS) { + if (this._touchedPart === cc.CONTROL_STEPPER_PARTMINUS) { this.setValueWithSendingEvent(this._value - this._stepValue, this._continuous); - } else if (this._touchedPart == cc.CONTROL_STEPPER_PARTPLUS) { + } else if (this._touchedPart === cc.CONTROL_STEPPER_PARTPLUS) { this.setValueWithSendingEvent(this._value + this._stepValue, this._continuous); } }, diff --git a/extensions/gui/control-extension/CCMenuPassive.js b/extensions/gui/control-extension/CCMenuPassive.js index f6600c1c5a..82a3fd32fe 100644 --- a/extensions/gui/control-extension/CCMenuPassive.js +++ b/extensions/gui/control-extension/CCMenuPassive.js @@ -257,7 +257,7 @@ cc.MenuPassive = cc.Layer.extend(/** @lends cc.MenuPassive# */{ if (this._children && this._children.length > 0) { for (i = 0; i < this._children.length; i++) { if (this._children[i]) { - if (rowColumns == 0) { + if (rowColumns === 0) { rowColumns = rows[row]; w = winSize.width / (1 + rowColumns); x = w; diff --git a/extensions/gui/control-extension/CCScale9Sprite.js b/extensions/gui/control-extension/CCScale9Sprite.js index 1188d28d44..abe7056ef7 100644 --- a/extensions/gui/control-extension/CCScale9Sprite.js +++ b/extensions/gui/control-extension/CCScale9Sprite.js @@ -145,15 +145,15 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ var leftWidth = locBottomLeftContentSize.width; var bottomHeight = locBottomLeftContentSize.height; - if (cc._renderType == cc._RENDER_TYPE_WEBGL) { + if (cc._renderType === cc._RENDER_TYPE_WEBGL) { //browser is in canvas mode, need to manually control rounding to prevent overlapping pixels var roundedRescaledWidth = Math.round(rescaledWidth); - if (rescaledWidth != roundedRescaledWidth) { + if (rescaledWidth !== roundedRescaledWidth) { rescaledWidth = roundedRescaledWidth; horizontalScale = rescaledWidth / locCenterContentSize.width; } var roundedRescaledHeight = Math.round(rescaledHeight); - if (rescaledHeight != roundedRescaledHeight) { + if (rescaledHeight !== roundedRescaledHeight) { rescaledHeight = roundedRescaledHeight; verticalScale = rescaledHeight / locCenterContentSize.height; } @@ -497,7 +497,7 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ // the texture is rotated on Canvas render mode, so isRotated always is false. var preferredSize = this._preferredSize; preferredSize = cc.size(preferredSize.width, preferredSize.height); - this.updateWithBatchNode(this._scale9Image, sender.getRect(), cc._renderType == cc._RENDER_TYPE_WEBGL && sender.isRotated(), this._capInsets); + this.updateWithBatchNode(this._scale9Image, sender.getRect(), cc._renderType === cc._RENDER_TYPE_WEBGL && sender.isRotated(), this._capInsets); this.setPreferredSize(preferredSize); this._positionsAreDirty = true; this.dispatchEvent("load"); @@ -505,7 +505,7 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ } var batchNode = new cc.SpriteBatchNode(spriteFrame.getTexture(), 9); // the texture is rotated on Canvas render mode, so isRotated always is false. - return this.initWithBatchNode(batchNode, spriteFrame.getRect(), cc._renderType == cc._RENDER_TYPE_WEBGL && spriteFrame.isRotated(), capInsets); + return this.initWithBatchNode(batchNode, spriteFrame.getRect(), cc._renderType === cc._RENDER_TYPE_WEBGL && spriteFrame.isRotated(), capInsets); }, /** @@ -587,7 +587,7 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ // Release old sprites this.removeAllChildren(true); - if (this._scale9Image != batchNode) + if (this._scale9Image !== batchNode) this._scale9Image = batchNode; if(!this._scale9Image) @@ -897,13 +897,13 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ // the texture is rotated on Canvas render mode, so isRotated always is false. var preferredSize = this._preferredSize; preferredSize = cc.size(preferredSize.width, preferredSize.height); - this.updateWithBatchNode(this._scale9Image, sender.getRect(), cc._renderType == cc._RENDER_TYPE_WEBGL && sender.isRotated(), this._capInsets); + this.updateWithBatchNode(this._scale9Image, sender.getRect(), cc._renderType === cc._RENDER_TYPE_WEBGL && sender.isRotated(), this._capInsets); this.setPreferredSize(preferredSize); this._positionsAreDirty = true; this.dispatchEvent("load"); },this); } - this.updateWithBatchNode(batchNode, spriteFrame.getRect(), cc._renderType == cc._RENDER_TYPE_WEBGL && spriteFrame.isRotated(), cc.rect(0, 0, 0, 0)); + this.updateWithBatchNode(batchNode, spriteFrame.getRect(), cc._renderType === cc._RENDER_TYPE_WEBGL && spriteFrame.isRotated(), cc.rect(0, 0, 0, 0)); // Reset insets this._insetLeft = 0; diff --git a/extensions/gui/control-extension/CCScale9SpriteCanvasRenderCmd.js b/extensions/gui/control-extension/CCScale9SpriteCanvasRenderCmd.js index 4d91c032d6..f0acc0bb7a 100644 --- a/extensions/gui/control-extension/CCScale9SpriteCanvasRenderCmd.js +++ b/extensions/gui/control-extension/CCScale9SpriteCanvasRenderCmd.js @@ -105,7 +105,7 @@ var locCanvas = this._cacheCanvas, wrapper = this._cacheContext, locContext = wrapper.getContext(); var contentSizeChanged = false; - if(locCanvas.width != sizeInPixels.width || locCanvas.height != sizeInPixels.height){ + if(locCanvas.width !== sizeInPixels.width || locCanvas.height !== sizeInPixels.height){ locCanvas.width = sizeInPixels.width; locCanvas.height = sizeInPixels.height; contentSizeChanged = true; diff --git a/extensions/gui/control-extension/CCScale9SpriteWebGLRenderCmd.js b/extensions/gui/control-extension/CCScale9SpriteWebGLRenderCmd.js index f133b83c7f..e0379495e0 100644 --- a/extensions/gui/control-extension/CCScale9SpriteWebGLRenderCmd.js +++ b/extensions/gui/control-extension/CCScale9SpriteWebGLRenderCmd.js @@ -89,7 +89,7 @@ proto.setState = function (state) { var scale9Image = this._node._scale9Image; - if(scale9Image == null) + if(scale9Image === null) return; if (state === cc.Scale9Sprite.state.NORMAL) { scale9Image.setShaderProgram(cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURECOLOR)); diff --git a/extensions/gui/scrollview/CCScrollView.js b/extensions/gui/scrollview/CCScrollView.js index 854bf08953..6eb3dfbdf9 100644 --- a/extensions/gui/scrollview/CCScrollView.js +++ b/extensions/gui/scrollview/CCScrollView.js @@ -227,11 +227,11 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ } var locContainer = this._container; - if (locContainer.getScale() != scale) { + if (locContainer.getScale() !== scale) { var oldCenter, newCenter; var center; - if (this._touchLength == 0.0) { + if (this._touchLength === 0.0) { var locViewSize = this._viewSize; center = cc.p(locViewSize.width * 0.5, locViewSize.height * 0.5); center = this.convertToWorldSpace(center); @@ -262,7 +262,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ setZoomScaleInDuration:function (s, dt) { if (dt > 0) { var locScale = this._container.getScale(); - if (locScale != s) { + if (locScale !== s) { var scaleAction = cc.actionTween(dt, "zoomScale", locScale, s); this.runAction(scaleAction); } @@ -421,7 +421,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ this._scrollDistance.x = 0; this._scrollDistance.y = 0; this._touchLength = 0.0; - } else if (locTouches.length == 2) { + } else if (locTouches.length === 2) { this._touchPoint = cc.pMidpoint(this.convertTouchToNodeSpace(locTouches[0]), this.convertTouchToNodeSpace(locTouches[1])); this._touchLength = cc.pDistance(locContainer.convertTouchToNodeSpace(locTouches[0]), @@ -514,7 +514,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ if (!this.isVisible()) return; - if (this._touches.length == 1 && this._touchMoved) + if (this._touches.length === 1 && this._touchMoved) this.schedule(this._deaccelerateScrolling); this._touches.length = 0; @@ -532,7 +532,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ }, setContentSize: function (size, height) { - if (this.getContainer() != null) { + if (this.getContainer() !== null) { if(height === undefined) this.getContainer().setContentSize(size); else @@ -542,14 +542,14 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ }, _setWidth: function (value) { var container = this.getContainer(); - if (container != null) { + if (container !== null) { container._setWidth(value); this.updateInset(); } }, _setHeight: function (value) { var container = this.getContainer(); - if (container != null) { + if (container !== null) { container._setHeight(value); this.updateInset(); } @@ -560,7 +560,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ }, updateInset:function () { - if (this.getContainer() != null) { + if (this.getContainer() !== null) { var locViewSize = this._viewSize; var tempOffset = this.maxContainerOffset(); this._maxInset.x = tempOffset.x + locViewSize.width * INSET_RATIO; @@ -599,7 +599,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ //child.ignoreAnchorPointForPosition(false); //child.setAnchorPoint(0, 0); - if (this._container != child) { + if (this._container !== child) { this._container.addChild(child, zOrder, tag); } else { cc.Layer.prototype.addChild.call(this, child, zOrder, tag); @@ -607,7 +607,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ }, isTouchEnabled: function(){ - return this._touchListener != null; + return this._touchListener !== null; }, setTouchEnabled:function (e) { @@ -663,12 +663,12 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ newX = Math.min(newX, max.x); } - if (locDirection == cc.SCROLLVIEW_DIRECTION_BOTH || locDirection == cc.SCROLLVIEW_DIRECTION_VERTICAL) { + if (locDirection === cc.SCROLLVIEW_DIRECTION_BOTH || locDirection === cc.SCROLLVIEW_DIRECTION_VERTICAL) { newY = Math.min(newY, max.y); newY = Math.max(newY, min.y); } - if (newY != oldPoint.y || newX != oldPoint.x) { + if (newY !== oldPoint.y || newX !== oldPoint.x) { this.setContentOffset(cc.p(newX, newY), animated); } }, @@ -709,8 +709,8 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ Math.abs(locScrollDistance.y) <= SCROLL_DEACCEL_DIST) || newY > maxInset.y || newY < minInset.y || newX > maxInset.x || newX < minInset.x || - newX == maxInset.x || newX == minInset.x || - newY == maxInset.y || newY == minInset.y) { + newX === maxInset.x || newX === minInset.x || + newY === maxInset.y || newY === minInset.y) { this.unschedule(this._deaccelerateScrolling); this._relocateContainer(true); } diff --git a/extensions/gui/scrollview/CCSorting.js b/extensions/gui/scrollview/CCSorting.js index 8d53f3c4c3..8aaf500710 100644 --- a/extensions/gui/scrollview/CCSorting.js +++ b/extensions/gui/scrollview/CCSorting.js @@ -103,14 +103,14 @@ cc.ArrayForObjectSorting = cc.Class.extend(/** @lends cc.ArrayForObjectSorting# * @param {Object} delObject Object to remove */ removeSortedObject:function (delObject) { - if (this.count() == 0) { + if (this.count() === 0) { return; } var idx = this.indexOfSortedObject(delObject); - if (idx < this.count() && idx != cc.INVALID_INDEX) { + if (idx < this.count() && idx !== cc.INVALID_INDEX) { var foundObj = this.objectAtIndex(idx); - if (foundObj.getObjectID() == delObject.getObjectID()) { + if (foundObj.getObjectID() === delObject.getObjectID()) { this.removeObjectAtIndex(idx); } } @@ -129,9 +129,9 @@ cc.ArrayForObjectSorting = cc.Class.extend(/** @lends cc.ArrayForObjectSorting# */ setObjectID_ofSortedObject:function (tag, setObject) { var idx = this.indexOfSortedObject(setObject); - if (idx < this.count() && idx != cc.INVALID_INDEX) { + if (idx < this.count() && idx !== cc.INVALID_INDEX) { var foundObj = this.objectAtIndex(idx); - if (foundObj.getObjectID() == setObject.getObjectID()) { + if (foundObj.getObjectID() === setObject.getObjectID()) { this.removeObjectAtIndex(idx); foundObj.setObjectID(tag); this.insertSortedObject(foundObj); @@ -140,16 +140,16 @@ cc.ArrayForObjectSorting = cc.Class.extend(/** @lends cc.ArrayForObjectSorting# }, objectWithObjectID:function (tag) { - if (this.count() == 0) { + if (this.count() === 0) { return null; } var foundObj = new cc.SortedObject(); foundObj.setObjectID(tag); var idx = this.indexOfSortedObject(foundObj); - if (idx < this.count() && idx != cc.INVALID_INDEX) { + if (idx < this.count() && idx !== cc.INVALID_INDEX) { foundObj = this.objectAtIndex(idx); - if (foundObj.getObjectID() != tag) + if (foundObj.getObjectID() !== tag) foundObj = null; } return foundObj; @@ -193,7 +193,7 @@ cc.ArrayForObjectSorting = cc.Class.extend(/** @lends cc.ArrayForObjectSorting# for (var i = 0; i < locObjectArr.length; i++) { var pSortableObj = locObjectArr[i]; var curObjectID = pSortableObj.getObjectID(); - if ((uOfSortObjectID == curObjectID) || + if ((uOfSortObjectID === curObjectID) || (uOfSortObjectID >= uPrevObjectID && uOfSortObjectID < curObjectID)) { break; } @@ -213,7 +213,7 @@ cc.ArrayForObjectSorting = cc.Class.extend(/** @lends cc.ArrayForObjectSorting# lastObject:function () { var locObjectArr = this._saveObjectArr; - if (locObjectArr.length == 0) + if (locObjectArr.length === 0) return null; return locObjectArr[locObjectArr.length - 1]; }, diff --git a/extensions/gui/scrollview/CCTableView.js b/extensions/gui/scrollview/CCTableView.js index f3347aa498..1c27563724 100644 --- a/extensions/gui/scrollview/CCTableView.js +++ b/extensions/gui/scrollview/CCTableView.js @@ -254,7 +254,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ locOffset.y = this.getContainer().getContentSize().height - locOffset.y; var index = this.__indexFromOffset(locOffset); - if (index != -1) { + if (index !== -1) { index = Math.max(0, index); if (index > maxIdx) index = cc.INVALID_INDEX; @@ -328,8 +328,8 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ this.setContentSize(size); - if (this._oldDirection != this._direction) { - if (this._direction == cc.SCROLLVIEW_DIRECTION_HORIZONTAL) { + if (this._oldDirection !== this._direction) { + if (this._direction === cc.SCROLLVIEW_DIRECTION_HORIZONTAL) { this.setContentOffset(cc.p(0, 0)); } else { this.setContentOffset(cc.p(0, this.minContainerOffset().y)); @@ -347,7 +347,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ cc.arrayRemoveObject(this._indices, cell.getIdx()); cell.reset(); - if (cell.getParent() == this.getContainer()) { + if (cell.getParent() === this.getContainer()) { this.getContainer().removeChild(cell, true); } }, @@ -359,12 +359,12 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ }, _addCellIfNecessary:function (cell) { - if (cell.getParent() != this.getContainer()) { + if (cell.getParent() !== this.getContainer()) { this.getContainer().addChild(cell); } this._cellsUsed.insertSortedObject(cell); var locIndices = this._indices, addIdx = cell.getIdx(); - if(locIndices.indexOf(addIdx) == -1){ + if(locIndices.indexOf(addIdx) === -1){ locIndices.push(addIdx); //sort locIndices.sort(function(a,b){return a-b;}); @@ -396,7 +396,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ * determines how cell is ordered and filled in the view. */ setVerticalFillOrder:function (fillOrder) { - if (this._vOrdering != fillOrder) { + if (this._vOrdering !== fillOrder) { this._vOrdering = fillOrder; if (this._cellsUsed.count() > 0) { this.reloadData(); @@ -428,7 +428,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ * @param idx index to find a cell */ updateCellAtIndex:function (idx) { - if (idx == cc.INVALID_INDEX || idx > this._dataSource.numberOfCellsInTableView(this) - 1) + if (idx === cc.INVALID_INDEX || idx > this._dataSource.numberOfCellsInTableView(this) - 1) return; var cell = this.cellAtIndex(idx); @@ -446,7 +446,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ * @param idx location to insert */ insertCellAtIndex:function (idx) { - if (idx == cc.INVALID_INDEX || idx > this._dataSource.numberOfCellsInTableView(this) - 1) + if (idx === cc.INVALID_INDEX || idx > this._dataSource.numberOfCellsInTableView(this) - 1) return; var newIdx, locCellsUsed = this._cellsUsed; @@ -474,7 +474,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ * @param idx index to find a cell */ removeCellAtIndex:function (idx) { - if (idx == cc.INVALID_INDEX || idx > this._dataSource.numberOfCellsInTableView(this) - 1) + if (idx === cc.INVALID_INDEX || idx > this._dataSource.numberOfCellsInTableView(this) - 1) return; var cell = this.cellAtIndex(idx); @@ -509,7 +509,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ locCellsFreed.addObject(cell); cell.reset(); - if (cell.getParent() == locContainer) + if (cell.getParent() === locContainer) locContainer.removeChild(cell, true); } @@ -545,7 +545,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ */ cellAtIndex:function (idx) { var i = this._indices.indexOf(idx); - if (i == -1) + if (i === -1) return null; return this._cellsUsed.objectWithObjectID(idx); }, @@ -556,7 +556,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ if (0 === countOfItems) return; - if (this._tableViewDelegate != null && this._tableViewDelegate.scrollViewDidScroll) + if (this._tableViewDelegate !== null && this._tableViewDelegate.scrollViewDidScroll) this._tableViewDelegate.scrollViewDidScroll(this); var idx = 0, locViewSize = this._viewSize, locContainer = this.getContainer(); @@ -611,7 +611,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ var locIndices = this._indices; for (var i = startIdx; i <= endIdx; i++) { - if (locIndices.indexOf(i) != -1) + if (locIndices.indexOf(i) !== -1) continue; this.updateCellAtIndex(i); } @@ -631,7 +631,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ bb.x = tmpOrigin.x; bb.y = tmpOrigin.y; var locTableViewDelegate = this._tableViewDelegate; - if (cc.rectContainsPoint(bb, touch.getLocation()) && locTableViewDelegate != null){ + if (cc.rectContainsPoint(bb, touch.getLocation()) && locTableViewDelegate !== null){ if(locTableViewDelegate.tableCellUnhighlight) locTableViewDelegate.tableCellUnhighlight(this, this._touchedCell); if(locTableViewDelegate.tableCellTouched) @@ -659,10 +659,10 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ else this._touchedCell = this.cellAtIndex(index); - if (this._touchedCell && this._tableViewDelegate != null && this._tableViewDelegate.tableCellHighlight) + if (this._touchedCell && this._tableViewDelegate !== null && this._tableViewDelegate.tableCellHighlight) this._tableViewDelegate.tableCellHighlight(this, this._touchedCell); } else if(this._touchedCell) { - if(this._tableViewDelegate != null && this._tableViewDelegate.tableCellUnhighlight) + if(this._tableViewDelegate !== null && this._tableViewDelegate.tableCellUnhighlight) this._tableViewDelegate.tableCellUnhighlight(this, this._touchedCell); this._touchedCell = null; } @@ -674,7 +674,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ cc.ScrollView.prototype.onTouchMoved.call(this, touch, event); if (this._touchedCell && this.isTouchMoved()) { - if(this._tableViewDelegate != null && this._tableViewDelegate.tableCellUnhighlight) + if(this._tableViewDelegate !== null && this._tableViewDelegate.tableCellUnhighlight) this._tableViewDelegate.tableCellUnhighlight(this, this._touchedCell); this._touchedCell = null; } @@ -684,7 +684,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ cc.ScrollView.prototype.onTouchCancelled.call(this, touch, event); if (this._touchedCell) { - if(this._tableViewDelegate != null && this._tableViewDelegate.tableCellUnhighlight) + if(this._tableViewDelegate !== null && this._tableViewDelegate.tableCellUnhighlight) this._tableViewDelegate.tableCellUnhighlight(this, this._touchedCell); this._touchedCell = null; } From 099a99d7d94eaa8d5d027a7f069a896ed6952856 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Wed, 18 Mar 2015 09:47:44 +0800 Subject: [PATCH 0061/1039] Fixed #2742: corrected some mistakes after using '===' to replace '==' --- cocos2d/core/base-nodes/CCNode.js | 2 ++ cocos2d/shaders/CCGLProgram.js | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index b2888ae0fd..6cb06db921 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -186,6 +186,8 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ _renderCmd:null, + _camera: null, + /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. * @function diff --git a/cocos2d/shaders/CCGLProgram.js b/cocos2d/shaders/CCGLProgram.js index 283a2f5390..4e63c3c435 100644 --- a/cocos2d/shaders/CCGLProgram.js +++ b/cocos2d/shaders/CCGLProgram.js @@ -106,7 +106,7 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ else cc.log("cocos2d: \n" + this.fragmentShaderLog()); } - return ( status === 1 ); + return ( status === true ); }, /** From fb1883a46333520c390dad5c397a89588c0f7890 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Wed, 18 Mar 2015 11:55:30 +0800 Subject: [PATCH 0062/1039] Fixed a bug of template/main.js that if loading.js doesn't add. --- template/main.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/template/main.js b/template/main.js index dcbd88808c..b0afefa923 100644 --- a/template/main.js +++ b/template/main.js @@ -1,5 +1,5 @@ cc.game.onStart = function(){ - if(!cc.sys.isNative) //If referenced loading.js, please remove it + if(!cc.sys.isNative && document.getElementById("cocosLoading")) //If referenced loading.js, please remove it document.body.removeChild(document.getElementById("cocosLoading")); var designSize = cc.size(480, 800); From 851bbbf15de23d75b584ca33f8557990a33fdf63 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Wed, 18 Mar 2015 14:20:57 +0800 Subject: [PATCH 0063/1039] Moved loading.js to res folder for Cocos console release mode. --- template/index.html | 2 +- template/{src => res}/loading.js | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename template/{src => res}/loading.js (100%) diff --git a/template/index.html b/template/index.html index 776f7d11d7..e0f577b927 100644 --- a/template/index.html +++ b/template/index.html @@ -23,7 +23,7 @@ - + \ No newline at end of file diff --git a/template/src/loading.js b/template/res/loading.js similarity index 100% rename from template/src/loading.js rename to template/res/loading.js From 9ba7709db1f80ac0a32c621180fcb29346d4583b Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Wed, 18 Mar 2015 18:07:26 +0800 Subject: [PATCH 0064/1039] Fixed a bug of Cocostudio parser that widget doesn't set layoutComponent expect Layout --- .../loader/parsers/timelineParser-2.x.js | 153 +++++++++--------- 1 file changed, 75 insertions(+), 78 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index e3a9f47f3f..540d34de2e 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -208,7 +208,7 @@ // WIDGET // //////////// - parser.widgetAttributes = function(widget, json){ + parser.widgetAttributes = function(widget, json) { widget.setCascadeColorEnabled(true); widget.setCascadeOpacityEnabled(true); @@ -218,7 +218,7 @@ setContentSize(widget, json["Size"]); var name = json["Name"]; - if(name) + if (name) widget.setName(name); var actionTag = json["ActionTag"] || 0; @@ -226,25 +226,25 @@ widget.setUserObject(new ccs.ActionTimelineData(actionTag)); var rotationSkewX = json["RotationSkewX"]; - if(rotationSkewX) + if (rotationSkewX) widget.setRotationX(rotationSkewX); var rotationSkewY = json["RotationSkewY"]; - if(rotationSkewY) + if (rotationSkewY) widget.setRotationY(rotationSkewY); //var rotation = json["Rotation"]; var flipX = json["FlipX"]; - if(flipX) + if (flipX) widget.setFlippedX(true); var flipY = json["FlipY"]; - if(flipY) + if (flipY) widget.setFlippedY(true); var zOrder = json["zOrder"]; - if(zOrder != null) + if (zOrder != null) widget.setLocalZOrder(zOrder); //var visible = json["Visible"]; @@ -253,7 +253,7 @@ widget.setVisible(visible); var alpha = json["Alpha"]; - if(alpha != null) + if (alpha != null) widget.setOpacity(alpha); widget.setTag(json["Tag"] || 0); @@ -264,19 +264,19 @@ // -- var frameEvent = json["FrameEvent"]; var callBackType = json["CallBackType"]; - if(callBackType != null) + if (callBackType != null) widget.setCallbackType(callBackType); var callBackName = json["CallBackName"]; - if(callBackName) + if (callBackName) widget.setCallbackName(callBackName); var position = json["Position"]; - if(position != null) + if (position != null) widget.setPosition(position["X"] || 0, position["Y"] || 0); var scale = json["Scale"]; - if(scale != null){ + if (scale != null) { var scaleX = getParam(scale["ScaleX"], 1); var scaleY = getParam(scale["ScaleY"], 1); widget.setScaleX(scaleX); @@ -284,80 +284,77 @@ } var anchorPoint = json["AnchorPoint"]; - if(anchorPoint != null) + if (anchorPoint != null) widget.setAnchorPoint(anchorPoint["ScaleX"] || 0, anchorPoint["ScaleY"] || 0); var color = json["CColor"]; - if(color != null) + if (color != null) widget.setColor(getColor(color)); - if(widget instanceof ccui.Layout){ - var layoutComponent = ccui.LayoutComponent.bindLayoutComponent(widget); - - var positionXPercentEnabled = json["PositionPercentXEnable"] || false; - var positionYPercentEnabled = json["PositionPercentYEnable"] || false; - var positionXPercent = 0, - positionYPercent = 0, - PrePosition = json["PrePosition"]; - if(PrePosition != null){ - positionXPercent = PrePosition["X"] || 0; - positionYPercent = PrePosition["Y"] || 0; - } - var sizeXPercentEnable = json["PercentWidthEnable"] || false; - var sizeYPercentEnable = json["PercentHeightEnable"] || false; - var sizeXPercent = 0, - sizeYPercent = 0, - PreSize = json["PreSize"]; - if(PrePosition != null){ - sizeXPercent = PreSize["X"] || 0; - sizeYPercent = PreSize["Y"] || 0; - } - var stretchHorizontalEnabled = json["StretchWidthEnable"] || false; - var stretchVerticalEnabled = json["StretchHeightEnable"] || false; - var horizontalEdge = json["HorizontalEdge"];// = ccui.LayoutComponent.horizontalEdge.LEFT; - var verticalEdge = json["VerticalEdge"]; // = ccui.LayoutComponent.verticalEdge.TOP; - var leftMargin = json["LeftMargin"] || 0; - var rightMargin = json["RightMargin"] || 0; - var topMargin = json["TopMargin"] || 0; - var bottomMargin = json["BottomMargin"] || 0; - - layoutComponent.setPositionPercentXEnabled(positionXPercentEnabled); - layoutComponent.setPositionPercentYEnabled(positionYPercentEnabled); - layoutComponent.setPositionPercentX(positionXPercent); - layoutComponent.setPositionPercentY(positionYPercent); - layoutComponent.setPercentWidthEnabled(sizeXPercentEnable); - layoutComponent.setPercentHeightEnabled(sizeYPercentEnable); - layoutComponent.setPercentWidth(sizeXPercent); - layoutComponent.setPercentHeight(sizeYPercent); - layoutComponent.setStretchWidthEnabled(stretchHorizontalEnabled); - layoutComponent.setStretchHeightEnabled(stretchVerticalEnabled); - - var horizontalEdgeType = ccui.LayoutComponent.horizontalEdge.NONE; - if (horizontalEdge == "LeftEdge"){ - horizontalEdgeType = ccui.LayoutComponent.horizontalEdge.LEFT; - }else if (horizontalEdge == "RightEdge"){ - horizontalEdgeType = ccui.LayoutComponent.horizontalEdge.RIGHT; - }else if (horizontalEdge == "BothEdge"){ - horizontalEdgeType = ccui.LayoutComponent.horizontalEdge.CENTER; - } - layoutComponent.setHorizontalEdge(horizontalEdgeType); - - var verticalEdgeType = ccui.LayoutComponent.verticalEdge.NONE; - if (verticalEdge == "TopEdge"){ - verticalEdgeType = ccui.LayoutComponent.verticalEdge.TOP; - }else if (verticalEdge == "BottomEdge"){ - verticalEdgeType = ccui.LayoutComponent.verticalEdge.BOTTOM; - }else if (verticalEdge == "BothEdge"){ - verticalEdgeType = ccui.LayoutComponent.verticalEdge.CENTER; - } - layoutComponent.setVerticalEdge(verticalEdgeType); + var layoutComponent = ccui.LayoutComponent.bindLayoutComponent(widget); - layoutComponent.setTopMargin(topMargin); - layoutComponent.setBottomMargin(bottomMargin); - layoutComponent.setLeftMargin(leftMargin); - layoutComponent.setRightMargin(rightMargin); + var positionXPercentEnabled = json["PositionPercentXEnable"] || false; + var positionYPercentEnabled = json["PositionPercentYEnable"] || false; + var positionXPercent = 0, + positionYPercent = 0, + PrePosition = json["PrePosition"]; + if (PrePosition != null) { + positionXPercent = PrePosition["X"] || 0; + positionYPercent = PrePosition["Y"] || 0; + } + var sizeXPercentEnable = json["PercentWidthEnable"] || false; + var sizeYPercentEnable = json["PercentHeightEnable"] || false; + var sizeXPercent = 0, + sizeYPercent = 0, + PreSize = json["PreSize"]; + if (PrePosition != null) { + sizeXPercent = PreSize["X"] || 0; + sizeYPercent = PreSize["Y"] || 0; + } + var stretchHorizontalEnabled = json["StretchWidthEnable"] || false; + var stretchVerticalEnabled = json["StretchHeightEnable"] || false; + var horizontalEdge = json["HorizontalEdge"];// = ccui.LayoutComponent.horizontalEdge.LEFT; + var verticalEdge = json["VerticalEdge"]; // = ccui.LayoutComponent.verticalEdge.TOP; + var leftMargin = json["LeftMargin"] || 0; + var rightMargin = json["RightMargin"] || 0; + var topMargin = json["TopMargin"] || 0; + var bottomMargin = json["BottomMargin"] || 0; + + layoutComponent.setPositionPercentXEnabled(positionXPercentEnabled); + layoutComponent.setPositionPercentYEnabled(positionYPercentEnabled); + layoutComponent.setPositionPercentX(positionXPercent); + layoutComponent.setPositionPercentY(positionYPercent); + layoutComponent.setPercentWidthEnabled(sizeXPercentEnable); + layoutComponent.setPercentHeightEnabled(sizeYPercentEnable); + layoutComponent.setPercentWidth(sizeXPercent); + layoutComponent.setPercentHeight(sizeYPercent); + layoutComponent.setStretchWidthEnabled(stretchHorizontalEnabled); + layoutComponent.setStretchHeightEnabled(stretchVerticalEnabled); + + var horizontalEdgeType = ccui.LayoutComponent.horizontalEdge.NONE; + if (horizontalEdge == "LeftEdge") { + horizontalEdgeType = ccui.LayoutComponent.horizontalEdge.LEFT; + } else if (horizontalEdge == "RightEdge") { + horizontalEdgeType = ccui.LayoutComponent.horizontalEdge.RIGHT; + } else if (horizontalEdge == "BothEdge") { + horizontalEdgeType = ccui.LayoutComponent.horizontalEdge.CENTER; + } + layoutComponent.setHorizontalEdge(horizontalEdgeType); + + var verticalEdgeType = ccui.LayoutComponent.verticalEdge.NONE; + if (verticalEdge == "TopEdge") { + verticalEdgeType = ccui.LayoutComponent.verticalEdge.TOP; + } else if (verticalEdge == "BottomEdge") { + verticalEdgeType = ccui.LayoutComponent.verticalEdge.BOTTOM; + } else if (verticalEdge == "BothEdge") { + verticalEdgeType = ccui.LayoutComponent.verticalEdge.CENTER; } + layoutComponent.setVerticalEdge(verticalEdgeType); + layoutComponent.setTopMargin(topMargin); + layoutComponent.setBottomMargin(bottomMargin); + layoutComponent.setLeftMargin(leftMargin); + layoutComponent.setRightMargin(rightMargin); }; /** From 666ce3a8a6975eff71e36b0eba0740a908f25736 Mon Sep 17 00:00:00 2001 From: igogo Date: Wed, 18 Mar 2015 12:36:55 +0200 Subject: [PATCH 0065/1039] Add support installing from bower.io --- bower.json | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 bower.json diff --git a/bower.json b/bower.json new file mode 100644 index 0000000000..9ea43d8147 --- /dev/null +++ b/bower.json @@ -0,0 +1,37 @@ +{ + "name": "cocos2d-html5", + "version": "3.4", + "homepage": "http://www.cocos2d-x.org", + "authors": [ + "AUTHORS.txt" + ], + "description": "Cocos2d-html5 is a cross-platform 2D game engine written in Javascript, based on Cocos2d-X and licensed under MIT. It incorporates the same high level api as “Cocos2d JS-binding engine” and compatible with Cocos2d-X. It currently supports canvas and will support WebGL in the future.", + "main": "README.mdown", + "keywords": [ + "cocos2d-x", + "cocos2d", + "game", + "engine", + "opengl", + "cross", + "multi", + "platform", + "iphone", + "ipad", + "android", + "windows", + "metro", + "bada", + "marmalade", + "playbook" + ], + "license": "MIT", + "private": false, + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests" + ] +} From 18c0b49bdd0d050068aa3ae80ee06b15c6ab8a87 Mon Sep 17 00:00:00 2001 From: igogo Date: Wed, 18 Mar 2015 12:42:33 +0200 Subject: [PATCH 0066/1039] . --- bower.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bower.json b/bower.json index 9ea43d8147..0c5aa5db1e 100644 --- a/bower.json +++ b/bower.json @@ -34,4 +34,4 @@ "test", "tests" ] -} +} \ No newline at end of file From 585c9622a600fb88bdc02f980d665d273b95dbfc Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 19 Mar 2015 00:06:55 +0800 Subject: [PATCH 0067/1039] Update engine version --- cocos2d/core/platform/CCConfig.js | 2 +- tools/build.xml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/platform/CCConfig.js b/cocos2d/core/platform/CCConfig.js index e33721a2b8..e7f788bd95 100644 --- a/cocos2d/core/platform/CCConfig.js +++ b/cocos2d/core/platform/CCConfig.js @@ -31,7 +31,7 @@ * @type {String} * @name cc.ENGINE_VERSION */ -window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.3"; +window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.4 beta"; /** *

diff --git a/tools/build.xml b/tools/build.xml index c1d0858cb8..2d1913ae0a 100644 --- a/tools/build.xml +++ b/tools/build.xml @@ -5,7 +5,7 @@ classpath="./compiler/compiler.jar"/> + debug="false" output="./../lib/cocos2d-js-v3.4-beta-min.js"> @@ -298,7 +298,7 @@ + debug="false" output="./../lib/cocos2d-js-v3.4-beta-core-min.js"> From 391c2841d90b985e959742c04509a46c7b93fd45 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Thu, 19 Mar 2015 09:42:53 +0800 Subject: [PATCH 0068/1039] Update the README.mdown --- README.mdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.mdown b/README.mdown index 5e3bc6adcd..3e545138cb 100644 --- a/README.mdown +++ b/README.mdown @@ -3,7 +3,7 @@ Cocos2d-html5 [Cocos2d-html5][1] is a cross-platform 2D game engine written in Javascript, based on [Cocos2d-X][2] and licensed under MIT. It incorporates the same high level api as “Cocos2d JS-binding engine” and compatible with Cocos2d-X. -It currently supports canvas and will support WebGL in the future. +It currently supports canvas and WebGL renderer. Cross Platform ------------- From a09ac4289d3b8278c0c58f37df4c83b05278bbae Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 19 Mar 2015 17:47:12 +0800 Subject: [PATCH 0069/1039] Update Changelog --- CHANGELOG.txt | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/CHANGELOG.txt b/CHANGELOG.txt index 58ea7b6413..cb53252b0c 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,5 +1,44 @@ ChangeLog: +Cocos2d-JS v3.4 Beta0 @ March 19 2015 + +* Added Windows Phone 8.0 platform support. +* Upgraded SpiderMonkey to v33, greatly improved JS object garbage collection and performance. +* Bound 3D modules including camera, light, sprite 3d, animation 3d, billboard, etc. +* Improved `cc.FontDefinition` & `ccui.RichText` in the web engine. +* Added gradient stops feature to `cc.LayerGradient` [Web exclusive]. +* Upgraded `cc.Scheduler` in the web engine with Cocos2d-x v3.4 implementation. +* Added a loading screen when scripts are loading. +* Improved performance by replacing `Object.defineProperties` with `cc.defineGetterSetter`. +* Supported loading sprite frames from json object. +* Refactored math library to improve web engine performance. +* Removed some variables from `cc` namespace to improve web engine performance. +* Added the Firefox OS Web manifest to support Firefox OS apps. +* Added `cocos` attr to the script element in templates. +* Moved loading.js to res folder for Cocos Console release mode. + +* Bug fixes: + 1. Added `getSpriteFrame` to `cc.Sprite` to fix API inconsistency. + 2. Added `getObejct` to `cc.TMXObjectGroup` to fix API inconsistency. + 3. Added `addImageAsync` to `cc.textureCache` to fix API inconsistency. + 4. Fixed a bug of `cc.text` that its default font name is incorrect. + 5. Fixed a bug of `ccui.PageView` that its `getPage` doesn't work. + 6. Fixed a bug of `ccui.ImageView` that its `loadTexture` doesn't work while it's invoked multiple times at the same frame. + 7. Fixed a bug of `ccui` that its load event callbacks have some mistakes. + 8. Fixed a bug of `cc.Layer` that its bake function doesn't work when the layer has a parent node. + 9. Fixed typos in `cc.ClippingNode.WebGLRenderCmd` and `cc.ParticleSystem.WebGLRenderCmd` creation. + 10. Fixed a bug of `cc.Sprite` in `setTextureRect`. + 11. Fixed a bug of `cc.Screen`. + 12. Fixed a bug of `cc.view` that it doesn't work on iOS 8.1.2. + 13. Fixed a bug of cc.DrawNode that its lineWidth is always to default value when set linewidth to zero. + 14. Fixed a bug in hack for particles performance on canvas. + 15. Fixed a bug of `cc.audioEngine` that it doesn't work after minified/compiled. + 16. Fixed a bug in `CCBoot.js` that WebGL is not activated in web view of iOS 8. + 17. Fixed a bug of `cc.CheckBox` that its position is incorrect when its texture isn't preloaded. + 18. Fixed a bug of `cc.TMXLayer` that it stops to work after `setTileGID` called. + 19. Fixed a bug of Cocos parser 2.x that it doesn't set widget's LayoutComponent. + 20. Fixed a bug of `cc.isObject` that it considered function as an object. + Cocos2d-JS v3.3 @ Feb.9, 2015 * Upgraded spine runtime to support the latest version and updated its test case. From f53c6dfe86061f30c9429f9d59d244888b783161 Mon Sep 17 00:00:00 2001 From: igogo Date: Thu, 19 Mar 2015 20:57:52 +0200 Subject: [PATCH 0070/1039] change description --- bower.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bower.json b/bower.json index 0c5aa5db1e..5493b6e512 100644 --- a/bower.json +++ b/bower.json @@ -5,7 +5,7 @@ "authors": [ "AUTHORS.txt" ], - "description": "Cocos2d-html5 is a cross-platform 2D game engine written in Javascript, based on Cocos2d-X and licensed under MIT. It incorporates the same high level api as “Cocos2d JS-binding engine” and compatible with Cocos2d-X. It currently supports canvas and will support WebGL in the future.", + "description": "Cocos2d-html5 is a cross-platform 2D game engine written in Javascript, based on Cocos2d-X and licensed under MIT. It incorporates the same high level api as “Cocos2d JS-binding engine” and compatible with Cocos2d-X. It currently supports canvas and WebGL renderering.", "main": "README.mdown", "keywords": [ "cocos2d-x", From 80582fb44207c566217c6b5d891a21ce061a46b7 Mon Sep 17 00:00:00 2001 From: Thomas Jablonski Date: Thu, 19 Mar 2015 20:02:18 +0100 Subject: [PATCH 0071/1039] Fixed grammatical mistakes in cocostudio logs --- extensions/cocostudio/loader/load.js | 4 ++-- extensions/cocostudio/loader/parsers/action-1.x.js | 4 ++-- extensions/cocostudio/loader/parsers/action-2.x.js | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/extensions/cocostudio/loader/load.js b/extensions/cocostudio/loader/load.js index 4a46b956b7..e47bbaec7e 100644 --- a/extensions/cocostudio/loader/load.js +++ b/extensions/cocostudio/loader/load.js @@ -35,7 +35,7 @@ ccs._load = (function(){ var json = cc.loader.getRes(file); if(!json) - return cc.log("%s is not exists", file); + return cc.log("%s does not exist", file); var ext = extname(file).toLocaleLowerCase(); if(ext !== "json" && ext !== "exportjson") return cc.log("%s load error, must be json file", file); @@ -218,4 +218,4 @@ ccs.csLoader = { createNode: function(file){ return ccs._load(file); } -}; \ No newline at end of file +}; diff --git a/extensions/cocostudio/loader/parsers/action-1.x.js b/extensions/cocostudio/loader/parsers/action-1.x.js index c5c20446c4..0c17159213 100644 --- a/extensions/cocostudio/loader/parsers/action-1.x.js +++ b/extensions/cocostudio/loader/parsers/action-1.x.js @@ -51,7 +51,7 @@ if(parser) frame = parser.call(self, timeline, resourcePath); else - cc.log("parser is not exists : %s", timeline["frameType"]); + cc.log("parser does not exist : %s", timeline["frameType"]); if(frame) action.addTimeline(frame); @@ -235,4 +235,4 @@ load.registerParser("action", "*", parser); -})(ccs._load, ccs._parser); \ No newline at end of file +})(ccs._load, ccs._parser); diff --git a/extensions/cocostudio/loader/parsers/action-2.x.js b/extensions/cocostudio/loader/parsers/action-2.x.js index 8916285cbf..ac0fccd291 100644 --- a/extensions/cocostudio/loader/parsers/action-2.x.js +++ b/extensions/cocostudio/loader/parsers/action-2.x.js @@ -52,7 +52,7 @@ if(parser) frame = parser.call(self, timeline, resourcePath); else - cc.log("parser is not exists : %s", timeline["Property"]); + cc.log("parser does not exist : %s", timeline["Property"]); if(frame) action.addTimeline(frame); }); From 28295587b478c572cb65d652bf24ad1c7db36d04 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Fri, 20 Mar 2015 09:51:30 +0800 Subject: [PATCH 0072/1039] Issue #2698: refactor cc.pointApplyAffineTransform --- cocos2d/core/CCScheduler.js | 2 +- cocos2d/core/cocoa/CCAffineTransform.js | 39 ++++++++++++-------- cocos2d/core/layers/CCLayer.js | 2 +- cocos2d/core/layers/CCLayerWebGLRenderCmd.js | 4 +- 4 files changed, 28 insertions(+), 19 deletions(-) diff --git a/cocos2d/core/CCScheduler.js b/cocos2d/core/CCScheduler.js index 510b21735b..ec341b58ff 100644 --- a/cocos2d/core/CCScheduler.js +++ b/cocos2d/core/CCScheduler.js @@ -285,7 +285,7 @@ cc.TimerTargetCallback = cc.Timer.extend({ * * @example * //register a schedule to scheduler - * cc.director.getScheduler().scheduleSelector(callback, this, interval, !this._isRunning); + * cc.director.getScheduler().schedule(callback, this, interval, !this._isRunning); */ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ _timeScale:1.0, diff --git a/cocos2d/core/cocoa/CCAffineTransform.js b/cocos2d/core/cocoa/CCAffineTransform.js index 1135c252a3..d979b9d61b 100644 --- a/cocos2d/core/cocoa/CCAffineTransform.js +++ b/cocos2d/core/cocoa/CCAffineTransform.js @@ -66,17 +66,26 @@ cc.affineTransformMake = function (a, b, c, d, tx, ty) { * Apply the affine transformation on a point. * @function * - * @param {cc.Point} point - * @param {cc.AffineTransform} t + * @param {cc.Point|Number} point or x + * @param {cc.AffineTransform|Number} transOrY transform matrix or y + * @param {cc.AffineTransform} t transform matrix or y * @return {cc.Point} */ -cc.pointApplyAffineTransform = function (point, t) { - return {x: t.a * point.x + t.c * point.y + t.tx, y: t.b * point.x + t.d * point.y + t.ty}; +cc.pointApplyAffineTransform = function (point, transOrY, t) { + var x, y; + if (t === undefined) { + t = transOrY; + x = point.x; + y = point.y; + } else { + x = point; + y = transOrY; + } + return {x: t.a * x + t.c * y + t.tx, y: t.b * x + t.d * y + t.ty}; }; -cc._pointApplyAffineTransform = function (x, y, t) { - return {x: t.a * x + t.c * y + t.tx, - y: t.b * x + t.d * y + t.ty}; +cc._pointApplyAffineTransform = function (x, y, t) { //it will remove. + return cc.pointApplyAffineTransform(x, y, t); }; /** @@ -131,10 +140,10 @@ cc.rectApplyAffineTransform = function (rect, anAffineTransform) { 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 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); @@ -150,10 +159,10 @@ cc._rectApplyAffineTransformIn = function(rect, anAffineTransform){ 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 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); diff --git a/cocos2d/core/layers/CCLayer.js b/cocos2d/core/layers/CCLayer.js index c7fd9af7d7..f80af56a0c 100644 --- a/cocos2d/core/layers/CCLayer.js +++ b/cocos2d/core/layers/CCLayer.js @@ -313,7 +313,7 @@ cc.LayerColor.create = function (color, width, height) { * @property {Number} startOpacity - Start opacity of the color gradient * @property {Number} endOpacity - End opacity of the color gradient * @property {Number} vector - Direction vector of the color gradient - * @property {Number} compresseInterpolation - Indicate whether or not the interpolation will be compressed + * @property {Number} compressedInterpolation - Indicate whether or not the interpolation will be compressed */ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{ _endColor: null, diff --git a/cocos2d/core/layers/CCLayerWebGLRenderCmd.js b/cocos2d/core/layers/CCLayerWebGLRenderCmd.js index 812c6d9394..c9314203ac 100644 --- a/cocos2d/core/layers/CCLayerWebGLRenderCmd.js +++ b/cocos2d/core/layers/CCLayerWebGLRenderCmd.js @@ -247,10 +247,10 @@ transMat = cc.affineTransformScale(transMat, tx, ty); for (i = 0; i < stopsLen; i++) { var stop = stops[i], y = stop.p * contentSize.height ; - var p0 = cc._pointApplyAffineTransform(- locAnchor.x , y - locAnchor.y, transMat); + var p0 = cc.pointApplyAffineTransform(- locAnchor.x , y - locAnchor.y, transMat); locVertices[i * 2].x = p0.x; locVertices[i * 2].y = p0.y; - var p1 = cc._pointApplyAffineTransform(contentSize.width - locAnchor.x, y - locAnchor.y, transMat); + var p1 = cc.pointApplyAffineTransform(contentSize.width - locAnchor.x, y - locAnchor.y, transMat); locVertices[i * 2 + 1].x = p1.x; locVertices[i * 2 + 1].y = p1.y; } From 7d353d56e3fec3fab9745453007b4274a8988886 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 20 Mar 2015 10:17:34 +0800 Subject: [PATCH 0073/1039] Add resource path for ccs.load. and modify path for ProjectNode. --- extensions/cocostudio/loader/load.js | 12 ++++--- .../loader/parsers/timelineParser-2.x.js | 34 +++++++++++-------- 2 files changed, 26 insertions(+), 20 deletions(-) diff --git a/extensions/cocostudio/loader/load.js b/extensions/cocostudio/loader/load.js index 4a46b956b7..1eba08cf26 100644 --- a/extensions/cocostudio/loader/load.js +++ b/extensions/cocostudio/loader/load.js @@ -28,9 +28,10 @@ ccs._load = (function(){ * load file * @param file * @param type - ccui|node|action + * @param path - Resource search path * @returns {*} */ - var load = function(file, type){ + var load = function(file, type, path){ var json = cc.loader.getRes(file); @@ -71,7 +72,7 @@ ccs._load = (function(){ return new cc.Node(); } - return currentParser.parse(file, json) || null; + return currentParser.parse(file, json, path) || null; }; var parser = { @@ -176,16 +177,17 @@ ccs._parser = cc.Class.extend({ * action 1.* - 2.* * scene 0.* - 1.* * @param {String} file + * @param {String} path Resource path * @returns {{node: cc.Node, action: cc.Action}} */ -ccs.load = function(file){ +ccs.load = function(file, path){ var object = { node: null, action: null }; - object.node = ccs._load(file); - object.action = ccs._load(file, "action"); + object.node = ccs._load(file, null, path); + object.action = ccs._load(file, "action", path); if(object.action && object.action.tag === -1 && object.node) object.action.tag = object.node.tag; return object; diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index e3a9f47f3f..1042e9ca91 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -28,8 +28,12 @@ var Parser = baseParser.extend({ - parse: function(file, json){ - var resourcePath = this._dirname(file); + parse: function(file, json, path){ + var resourcePath; + if(path !== undefined) + resourcePath = path; + else + resourcePath = this._dirname(file); this.pretreatment(json, resourcePath, file); var node = this.parseNode(this.getNodeJson(json), resourcePath); this.deferred(json, resourcePath, node, file); @@ -734,10 +738,10 @@ var scale9Width = json["Scale9Width"] || 0; var scale9Height = json["Scale9Height"] || 0; widget.setCapInsets(cc.rect( - scale9OriginX , - scale9OriginY, - scale9Width, - scale9Height + scale9OriginX , + scale9OriginY, + scale9Width, + scale9Height )); } else setContentSize(widget, json["Size"]); @@ -834,10 +838,10 @@ var scale9Width = json["Scale9Width"] || 0; var scale9Height = json["Scale9Height"] || 0; widget.setBackGroundImageCapInsets(cc.rect( - scale9OriginX, - scale9OriginY, - scale9Width, - scale9Height + scale9OriginX, + scale9OriginY, + scale9Width, + scale9Height )); } @@ -900,10 +904,10 @@ var scale9Width = json["Scale9Width"] || 0; var scale9Height = json["Scale9Height"] || 0; widget.setBackGroundImageCapInsets(cc.rect( - scale9OriginX, - scale9OriginY, - scale9Width, - scale9Height + scale9OriginX, + scale9OriginY, + scale9Width, + scale9Height )); } @@ -1146,7 +1150,7 @@ if(projectFile != null && projectFile["Path"]){ var file = resourcePath + projectFile["Path"]; if(cc.loader.getRes(file)){ - var obj = ccs.load(file); + var obj = ccs.load(file, resourcePath); parser.generalAttributes(obj.node, json); if(obj.action && obj.node){ obj.action.tag = obj.node.tag; From c5b69895879bb2441e8f31d985a4f41214f05484 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 20 Mar 2015 10:21:13 +0800 Subject: [PATCH 0074/1039] Add resource path for ccs.load. and modify path for ProjectNode. --- extensions/cocostudio/loader/load.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/extensions/cocostudio/loader/load.js b/extensions/cocostudio/loader/load.js index 1eba08cf26..8578034ee0 100644 --- a/extensions/cocostudio/loader/load.js +++ b/extensions/cocostudio/loader/load.js @@ -26,9 +26,9 @@ ccs._load = (function(){ /** * load file - * @param file - * @param type - ccui|node|action - * @param path - Resource search path + * @param {String} file + * @param {String} [type=] - ccui|node|action + * @param {String} [path=] - Resource search path * @returns {*} */ var load = function(file, type, path){ @@ -177,7 +177,7 @@ ccs._parser = cc.Class.extend({ * action 1.* - 2.* * scene 0.* - 1.* * @param {String} file - * @param {String} path Resource path + * @param {String} [path=] Resource path * @returns {{node: cc.Node, action: cc.Action}} */ ccs.load = function(file, path){ From 6bd5193d621584f4b2f3c19ec42dc28353f4c3f9 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 20 Mar 2015 11:02:08 +0800 Subject: [PATCH 0075/1039] Add ActionTimeline animationsList --- .../cocostudio/loader/parsers/action-2.x.js | 20 ++++++------- .../cocostudio/timeline/ActionTimeline.js | 30 +++++++++++++++++++ 2 files changed, 39 insertions(+), 11 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/action-2.x.js b/extensions/cocostudio/loader/parsers/action-2.x.js index 8916285cbf..287f0cbe10 100644 --- a/extensions/cocostudio/loader/parsers/action-2.x.js +++ b/extensions/cocostudio/loader/parsers/action-2.x.js @@ -63,17 +63,15 @@ }, deferred: function(json, resourcePath, action, file){ - if(cc.sys.isNative) { - var animationlist = json["Content"]["Content"]["AnimationList"]; - var length = animationlist ? animationlist.length : 0; - for (var i = 0; i < length; i++) { - var animationdata = animationlist[i]; - var info = { name: null, startIndex: null, endIndex: null }; - info.name = animationdata["Name"]; - info.startIndex = animationdata["StartIndex"]; - info.endIndex = animationdata["EndIndex"]; - action.addAnimationInfo(info); - } + var animationlist = json["Content"]["Content"]["AnimationList"]; + var length = animationlist ? animationlist.length : 0; + for (var i = 0; i < length; i++) { + var animationdata = animationlist[i]; + var info = { name: null, startIndex: null, endIndex: null }; + info.name = animationdata["Name"]; + info.startIndex = animationdata["StartIndex"]; + info.endIndex = animationdata["EndIndex"]; + action.addAnimationInfo(info); } } diff --git a/extensions/cocostudio/timeline/ActionTimeline.js b/extensions/cocostudio/timeline/ActionTimeline.js index bc5a60cc00..84b7341724 100644 --- a/extensions/cocostudio/timeline/ActionTimeline.js +++ b/extensions/cocostudio/timeline/ActionTimeline.js @@ -97,11 +97,13 @@ ccs.ActionTimeline = cc.Action.extend({ _endFrame: 0, _loop: null, _frameEventListener: null, + _animationInfos: null, ctor: function(){ cc.Action.prototype.ctor.call(this); this._timelineMap = {}; this._timelineList = []; + this._animationInfos = {}; this.init(); }, @@ -431,6 +433,34 @@ ccs.ActionTimeline = cc.Action.extend({ */ isDone: function(){ return false; + }, + + /** + * @param {String} name + * @param {Boolean} loop + */ + play: function(name, loop){ + var info = this._animationInfos[name]; + if (!info) + return cc.log("Can't find animation info for %s", name); + + this.gotoFrameAndPlay(info.startIndex, info.endIndex, loop); + }, + + /** + * Add animationInfo + * @param {Object} info + */ + addAnimationInfo: function(info){ + this._animationInfos[info.name] = info; + }, + + /** + * Remove animationInfo + * @param {String} name + */ + removeAnimationInfo: function(name){ + delete this._animationInfos[name]; } }); From 056a5356facbe5fe512d90768dcae8c7cf451b20 Mon Sep 17 00:00:00 2001 From: Tian Fei <12128735@qq.com> Date: Fri, 20 Mar 2015 11:17:07 +0800 Subject: [PATCH 0076/1039] update spine from 2.0 to 2.1 update spine from 2.0 to 2.1 --- extensions/spine/CCSkeleton.js | 2 +- extensions/spine/CCSkeletonAnimation.js | 23 +- extensions/spine/Spine.js | 954 +++++++++++++++++------- 3 files changed, 686 insertions(+), 293 deletions(-) diff --git a/extensions/spine/CCSkeleton.js b/extensions/spine/CCSkeleton.js index 28b49bebd1..2a3816a75a 100644 --- a/extensions/spine/CCSkeleton.js +++ b/extensions/spine/CCSkeleton.js @@ -185,7 +185,7 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ if (!slot.attachment || slot.attachment.type != sp.ATTACHMENT_TYPE.REGION) continue; var attachment = slot.attachment; - sp._regionAttachment_computeWorldVertices(attachment, slot.skeleton.x, slot.skeleton.y, slot.bone, vertices); + sp._regionAttachment_computeWorldVertices(attachment, slot.bone.skeleton.x, slot.bone.skeleton.y, slot.bone, vertices); minX = Math.min(minX, vertices[VERTEX.X1] * scaleX, vertices[VERTEX.X4] * scaleX, vertices[VERTEX.X2] * scaleX, vertices[VERTEX.X3] * scaleX); minY = Math.min(minY, vertices[VERTEX.Y1] * scaleY, vertices[VERTEX.Y4] * scaleY, vertices[VERTEX.Y2] * scaleY, vertices[VERTEX.Y3] * scaleY); maxX = Math.max(maxX, vertices[VERTEX.X1] * scaleX, vertices[VERTEX.X4] * scaleX, vertices[VERTEX.X2] * scaleX, vertices[VERTEX.X3] * scaleX); diff --git a/extensions/spine/CCSkeletonAnimation.js b/extensions/spine/CCSkeletonAnimation.js index 58ecb7351a..bb00ba2da5 100644 --- a/extensions/spine/CCSkeletonAnimation.js +++ b/extensions/spine/CCSkeletonAnimation.js @@ -79,11 +79,12 @@ sp._regionAttachment_computeWorldVertices = function(self, x, y, bone, vertices) sp._regionAttachment_updateQuad = function(self, slot, quad, premultipliedAlpha) { var vertices = {}; - self.computeVertices(slot.skeleton.x, slot.skeleton.y, slot, vertices); - var r = slot.skeleton.r * slot.r * 255; - var g = slot.skeleton.g * slot.g * 255; - var b = slot.skeleton.b * slot.b * 255; - var normalizedAlpha = slot.skeleton.a * slot.a; + self.computeVertices(slot.bone.skeleton.x, slot.bone.skeleton.y, slot.bone, vertices); + var r = slot.bone.skeleton.r * slot.r * 255; + var g = slot.bone.skeleton.g * slot.g * 255; + var b = slot.bone.skeleton.b * slot.b * 255; + var normalizedAlpha = slot.bone.skeleton.a * slot.a; + if (premultipliedAlpha) { r *= normalizedAlpha; g *= normalizedAlpha; @@ -118,11 +119,11 @@ sp._regionAttachment_updateQuad = function(self, slot, quad, premultipliedAlpha) sp._meshAttachment_updateQuad = function(self, slot, quad, premultipliedAlpha) { var vertices = {}; - self.computeVertices(slot.skeleton.x, slot.skeleton.y, slot, vertices); - var r = slot.skeleton.r * slot.r * 255; - var g = slot.skeleton.g * slot.g * 255; - var b = slot.skeleton.b * slot.b * 255; - var normalizedAlpha = slot.skeleton.a * slot.a; + self.computeVertices(slot.bone.x, slot.bone.y, slot.bone, vertices); + var r = slot.bone.skeleton.r * slot.r * 255; + var g = slot.bone.skeleton.g * slot.g * 255; + var b = slot.bone.skeleton.b * slot.b * 255; + var normalizedAlpha = slot.bone.skeleton.a * slot.a; if (premultipliedAlpha) { r *= normalizedAlpha; g *= normalizedAlpha; @@ -160,7 +161,7 @@ sp._regionAttachment_updateSlotForCanvas = function(self, slot, points) { return; var vertices = {}; - self.computeVertices(slot.skeleton.x, slot.skeleton.y, slot, vertices); + self.computeVertices(slot.bone.x, slot.bone.y, slot.bone, vertices); var VERTEX = sp.VERTEX_INDEX; points.length = 0; points.push(cc.p(vertices[VERTEX.X1], vertices[VERTEX.Y1])); diff --git a/extensions/spine/Spine.js b/extensions/spine/Spine.js index c446ff7247..d76f2c3dac 100644 --- a/extensions/spine/Spine.js +++ b/extensions/spine/Spine.js @@ -1,6 +1,6 @@ /****************************************************************************** * Spine Runtimes Software License - * Version 2 + * Version 2.1 * * Copyright (c) 2013, Esoteric Software * All rights reserved. @@ -8,30 +8,30 @@ * You are granted a perpetual, non-exclusive, non-sublicensable and * non-transferable license to install, execute and perform the Spine Runtimes * Software (the "Software") solely for internal use. Without the written - * permission of Esoteric Software, you may not (a) modify, translate, adapt or - * otherwise create derivative works, improvements of the Software or develop - * new applications using the Software or (b) remove, delete, alter or obscure - * any trademarks or any copyright, trademark, patent or other intellectual - * property or proprietary rights notices on or in the Software, including - * any copy thereof. Redistributions in binary or source form must include - * this license and terms. THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * permission of Esoteric Software (typically granted by licensing Spine), you + * may not (a) modify, translate, adapt or otherwise create derivative works, + * improvements of the Software or develop new applications using the Software + * or (b) remove, delete, alter or obscure any trademarks or any copyright, + * trademark, patent or other intellectual property or proprietary rights + * notices on or in the Software, including any copy thereof. Redistributions + * in binary or source form must include this license and terms. + * + * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO + * EVENT SHALL ESOTERIC SOFTARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ -var spine = spine || { +var spine = { radDeg: 180 / Math.PI, degRad: Math.PI / 180, - temp: [], - Float32Array: (typeof(Float32Array) === 'undefined') ? Array : Float32Array, - Uint16Array: (typeof(Uint16Array) === 'undefined') ? Array : Uint16Array + temp: [] }; spine.BoneData = function (name, parent) { @@ -44,13 +44,13 @@ spine.BoneData.prototype = { rotation: 0, scaleX: 1, scaleY: 1, inheritScale: true, - inheritRotation: true + inheritRotation: true, + flipX: false, flipY: false }; spine.SlotData = function (name, boneData) { this.name = name; this.boneData = boneData; - this.r = this.g = this.b = this.a = 1; //FOR google compiler Advance mode }; spine.SlotData.prototype = { r: 1, g: 1, b: 1, a: 1, @@ -58,23 +58,36 @@ spine.SlotData.prototype = { additiveBlending: false }; -spine.Bone = function (boneData, parent) { +spine.IkConstraintData = function (name) { + this.name = name; + this.bones = []; +}; +spine.IkConstraintData.prototype = { + target: null, + bendDirection: 1, + mix: 1 +}; + +spine.Bone = function (boneData, skeleton, parent) { this.data = boneData; + this.skeleton = skeleton; this.parent = parent; this.setToSetupPose(); }; spine.Bone.yDown = false; spine.Bone.prototype = { x: 0, y: 0, - rotation: 0, + rotation: 0, rotationIK: 0, scaleX: 1, scaleY: 1, + flipX: false, flipY: false, m00: 0, m01: 0, worldX: 0, // a b x m10: 0, m11: 0, worldY: 0, // c d y worldRotation: 0, worldScaleX: 1, worldScaleY: 1, - updateWorldTransform: function (flipX, flipY) { + worldFlipX: false, worldFlipY: false, + updateWorldTransform: function () { var parent = this.parent; - if (parent != null) { + if (parent) { this.worldX = this.x * parent.m00 + this.y * parent.m01 + parent.worldX; this.worldY = this.x * parent.m10 + this.y * parent.m11 + parent.worldY; if (this.data.inheritScale) { @@ -84,28 +97,35 @@ spine.Bone.prototype = { this.worldScaleX = this.scaleX; this.worldScaleY = this.scaleY; } - this.worldRotation = this.data.inheritRotation ? parent.worldRotation + this.rotation : this.rotation; + this.worldRotation = this.data.inheritRotation ? (parent.worldRotation + this.rotationIK) : this.rotationIK; + this.worldFlipX = parent.worldFlipX != this.flipX; + this.worldFlipY = parent.worldFlipY != this.flipY; } else { - this.worldX = flipX ? -this.x : this.x; - this.worldY = flipY != spine.Bone.yDown ? -this.y : this.y; + var skeletonFlipX = this.skeleton.flipX, skeletonFlipY = this.skeleton.flipY; + this.worldX = skeletonFlipX ? -this.x : this.x; + this.worldY = (skeletonFlipY != spine.Bone.yDown) ? -this.y : this.y; this.worldScaleX = this.scaleX; this.worldScaleY = this.scaleY; - this.worldRotation = this.rotation; + this.worldRotation = this.rotationIK; + this.worldFlipX = skeletonFlipX != this.flipX; + this.worldFlipY = skeletonFlipY != this.flipY; } - var radians = this.worldRotation * Math.PI / 180; + var radians = this.worldRotation * spine.degRad; var cos = Math.cos(radians); var sin = Math.sin(radians); - this.m00 = cos * this.worldScaleX; - this.m10 = sin * this.worldScaleX; - this.m01 = -sin * this.worldScaleY; - this.m11 = cos * this.worldScaleY; - if (flipX) { - this.m00 = -this.m00; - this.m01 = -this.m01; + if (this.worldFlipX) { + this.m00 = -cos * this.worldScaleX; + this.m01 = sin * this.worldScaleY; + } else { + this.m00 = cos * this.worldScaleX; + this.m01 = -sin * this.worldScaleY; } - if (flipY != spine.Bone.yDown) { - this.m10 = -this.m10; - this.m11 = -this.m11; + if (this.worldFlipY != spine.Bone.yDown) { + this.m10 = -sin * this.worldScaleX; + this.m11 = -cos * this.worldScaleY; + } else { + this.m10 = sin * this.worldScaleX; + this.m11 = cos * this.worldScaleY; } }, setToSetupPose: function () { @@ -113,14 +133,32 @@ spine.Bone.prototype = { this.x = data.x; this.y = data.y; this.rotation = data.rotation; + this.rotationIK = this.rotation; this.scaleX = data.scaleX; this.scaleY = data.scaleY; + this.flipX = data.flipX; + this.flipY = data.flipY; + }, + worldToLocal: function (world) { + var dx = world[0] - this.worldX, dy = world[1] - this.worldY; + var m00 = this.m00, m10 = this.m10, m01 = this.m01, m11 = this.m11; + if (this.worldFlipX != (this.worldFlipY != spine.Bone.yDown)) { + m00 = -m00; + m11 = -m11; + } + var invDet = 1 / (m00 * m11 - m01 * m10); + world[0] = (dx * m00 * invDet - dy * m01 * invDet); + world[1] = (dy * m11 * invDet - dx * m10 * invDet); + }, + localToWorld: function (local) { + var localX = local[0], localY = local[1]; + local[0] = localX * this.m00 + localY * this.m01 + this.worldX; + local[1] = localX * this.m10 + localY * this.m11 + this.worldY; } }; -spine.Slot = function (slotData, skeleton, bone) { +spine.Slot = function (slotData, bone) { this.data = slotData; - this.skeleton = skeleton; this.bone = bone; this.setToSetupPose(); }; @@ -128,15 +166,17 @@ spine.Slot.prototype = { r: 1, g: 1, b: 1, a: 1, _attachmentTime: 0, attachment: null, + attachmentVertices: [], setAttachment: function (attachment) { this.attachment = attachment; - this._attachmentTime = this.skeleton.time; + this._attachmentTime = this.bone.skeleton.time; + this.attachmentVertices.length = 0; }, setAttachmentTime: function (time) { - this._attachmentTime = this.skeleton.time - time; + this._attachmentTime = this.bone.skeleton.time - time; }, getAttachmentTime: function () { - return this.skeleton.time - this._attachmentTime; + return this.bone.skeleton.time - this._attachmentTime; }, setToSetupPose: function () { var data = this.data; @@ -145,16 +185,112 @@ spine.Slot.prototype = { this.b = data.b; this.a = data.a; - var slotDatas = this.skeleton.data.slots; + var slotDatas = this.bone.skeleton.data.slots; for (var i = 0, n = slotDatas.length; i < n; i++) { if (slotDatas[i] == data) { - this.setAttachment(!data.attachmentName ? null : this.skeleton.getAttachmentBySlotIndex(i, data.attachmentName)); + this.setAttachment(!data.attachmentName ? null : this.bone.skeleton.getAttachmentBySlotIndex(i, data.attachmentName)); break; } } } }; +spine.IkConstraint = function (data, skeleton) { + this.data = data; + this.mix = data.mix; + this.bendDirection = data.bendDirection; + + this.bones = []; + for (var i = 0, n = data.bones.length; i < n; i++) + this.bones.push(skeleton.findBone(data.bones[i].name)); + this.target = skeleton.findBone(data.target.name); +}; +spine.IkConstraint.prototype = { + apply: function () { + var target = this.target; + var bones = this.bones; + switch (bones.length) { + case 1: + spine.IkConstraint.apply1(bones[0], target.worldX, target.worldY, this.mix); + break; + case 2: + spine.IkConstraint.apply2(bones[0], bones[1], target.worldX, target.worldY, this.bendDirection, this.mix); + break; + } + } +}; +/** Adjusts the bone rotation so the tip is as close to the target position as possible. The target is specified in the world + * coordinate system. */ +spine.IkConstraint.apply1 = function (bone, targetX, targetY, alpha) { + var parentRotation = (!bone.data.inheritRotation || !bone.parent) ? 0 : bone.parent.worldRotation; + var rotation = bone.rotation; + var rotationIK = Math.atan2(targetY - bone.worldY, targetX - bone.worldX) * spine.radDeg - parentRotation; + bone.rotationIK = rotation + (rotationIK - rotation) * alpha; +}; +/** Adjusts the parent and child bone rotations so the tip of the child is as close to the target position as possible. The + * target is specified in the world coordinate system. + * @param child Any descendant bone of the parent. */ +spine.IkConstraint.apply2 = function (parent, child, targetX, targetY, bendDirection, alpha) { + var childRotation = child.rotation, parentRotation = parent.rotation; + if (!alpha) { + child.rotationIK = childRotation; + parent.rotationIK = parentRotation; + return; + } + var positionX, positionY, tempPosition = spine.temp; + var parentParent = parent.parent; + if (parentParent) { + tempPosition[0] = targetX; + tempPosition[1] = targetY; + parentParent.worldToLocal(tempPosition); + targetX = (tempPosition[0] - parent.x) * parentParent.worldScaleX; + targetY = (tempPosition[1] - parent.y) * parentParent.worldScaleY; + } else { + targetX -= parent.x; + targetY -= parent.y; + } + if (child.parent == parent) { + positionX = child.x; + positionY = child.y; + } else { + tempPosition[0] = child.x; + tempPosition[1] = child.y; + child.parent.localToWorld(tempPosition); + parent.worldToLocal(tempPosition); + positionX = tempPosition[0]; + positionY = tempPosition[1]; + } + var childX = positionX * parent.worldScaleX, childY = positionY * parent.worldScaleY; + var offset = Math.atan2(childY, childX); + var len1 = Math.sqrt(childX * childX + childY * childY), len2 = child.data.length * child.worldScaleX; + // Based on code by Ryan Juckett with permission: Copyright (c) 2008-2009 Ryan Juckett, http://www.ryanjuckett.com/ + var cosDenom = 2 * len1 * len2; + if (cosDenom < 0.0001) { + child.rotationIK = childRotation + (Math.atan2(targetY, targetX) * spine.radDeg - parentRotation - childRotation) * alpha; + return; + } + var cos = (targetX * targetX + targetY * targetY - len1 * len1 - len2 * len2) / cosDenom; + if (cos < -1) + cos = -1; + else if (cos > 1) + cos = 1; + var childAngle = Math.acos(cos) * bendDirection; + var adjacent = len1 + len2 * cos, opposite = len2 * Math.sin(childAngle); + var parentAngle = Math.atan2(targetY * adjacent - targetX * opposite, targetX * adjacent + targetY * opposite); + var rotation = (parentAngle - offset) * spine.radDeg - parentRotation; + if (rotation > 180) + rotation -= 360; + else if (rotation < -180) // + rotation += 360; + parent.rotationIK = parentRotation + rotation * alpha; + rotation = (childAngle + offset) * spine.radDeg - childRotation; + if (rotation > 180) + rotation -= 360; + else if (rotation < -180) // + rotation += 360; + child.rotationIK = childRotation + (rotation + parent.worldRotation - child.parent.worldRotation) * alpha; +}; + spine.Skin = function (name) { this.name = name; this.attachments = {}; @@ -205,11 +341,10 @@ spine.Animation.prototype = { timelines[i].apply(skeleton, lastTime, time, events, alpha); } }; - -spine.binarySearch = function (values, target, step) { +spine.Animation.binarySearch = function (values, target, step) { var low = 0; var high = Math.floor(values.length / step) - 2; - if (high == 0) return step; + if (!high) return step; var current = high >>> 1; while (true) { if (values[(current + 1) * step] <= target) @@ -220,69 +355,56 @@ spine.binarySearch = function (values, target, step) { current = (low + high) >>> 1; } }; -spine.linearSearch = function (values, target, step) { +spine.Animation.binarySearch1 = function (values, target) { + var low = 0; + var high = values.length - 2; + if (!high) return 1; + var current = high >>> 1; + while (true) { + if (values[current + 1] <= target) + low = current + 1; + else + high = current; + if (low == high) return low + 1; + current = (low + high) >>> 1; + } +}; +spine.Animation.linearSearch = function (values, target, step) { for (var i = 0, last = values.length - step; i <= last; i += step) if (values[i] > target) return i; return -1; }; spine.Curves = function (frameCount) { - this.curves = []; // dfx, dfy, ddfx, ddfy, dddfx, dddfy, ... - this.curves.length = (frameCount - 1) * 6; + this.curves = []; // type, x, y, ... + //this.curves.length = (frameCount - 1) * 19/*BEZIER_SIZE*/; }; spine.Curves.prototype = { setLinear: function (frameIndex) { - this.curves[frameIndex * 6] = 0/*LINEAR*/; + this.curves[frameIndex * 19/*BEZIER_SIZE*/] = 0/*LINEAR*/; }, setStepped: function (frameIndex) { - this.curves[frameIndex * 6] = -1/*STEPPED*/; + this.curves[frameIndex * 19/*BEZIER_SIZE*/] = 1/*STEPPED*/; }, /** Sets the control handle positions for an interpolation bezier curve used to transition from this keyframe to the next. * cx1 and cx2 are from 0 to 1, representing the percent of time between the two keyframes. cy1 and cy2 are the percent of * the difference between the keyframe's values. */ setCurve: function (frameIndex, cx1, cy1, cx2, cy2) { - var subdiv_step = 1 / 10/*BEZIER_SEGMENTS*/; - var subdiv_step2 = subdiv_step * subdiv_step; - var subdiv_step3 = subdiv_step2 * subdiv_step; - var pre1 = 3 * subdiv_step; - var pre2 = 3 * subdiv_step2; - var pre4 = 6 * subdiv_step2; - var pre5 = 6 * subdiv_step3; - var tmp1x = -cx1 * 2 + cx2; - var tmp1y = -cy1 * 2 + cy2; - var tmp2x = (cx1 - cx2) * 3 + 1; - var tmp2y = (cy1 - cy2) * 3 + 1; - var i = frameIndex * 6; - var curves = this.curves; - curves[i] = cx1 * pre1 + tmp1x * pre2 + tmp2x * subdiv_step3; - curves[i + 1] = cy1 * pre1 + tmp1y * pre2 + tmp2y * subdiv_step3; - curves[i + 2] = tmp1x * pre4 + tmp2x * pre5; - curves[i + 3] = tmp1y * pre4 + tmp2y * pre5; - curves[i + 4] = tmp2x * pre5; - curves[i + 5] = tmp2y * pre5; - }, - getCurvePercent: function (frameIndex, percent) { - percent = percent < 0 ? 0 : (percent > 1 ? 1 : percent); - var curveIndex = frameIndex * 6; + var subdiv1 = 1 / 10/*BEZIER_SEGMENTS*/, subdiv2 = subdiv1 * subdiv1, subdiv3 = subdiv2 * subdiv1; + var pre1 = 3 * subdiv1, pre2 = 3 * subdiv2, pre4 = 6 * subdiv2, pre5 = 6 * subdiv3; + var tmp1x = -cx1 * 2 + cx2, tmp1y = -cy1 * 2 + cy2, tmp2x = (cx1 - cx2) * 3 + 1, tmp2y = (cy1 - cy2) * 3 + 1; + var dfx = cx1 * pre1 + tmp1x * pre2 + tmp2x * subdiv3, dfy = cy1 * pre1 + tmp1y * pre2 + tmp2y * subdiv3; + var ddfx = tmp1x * pre4 + tmp2x * pre5, ddfy = tmp1y * pre4 + tmp2y * pre5; + var dddfx = tmp2x * pre5, dddfy = tmp2y * pre5; + + var i = frameIndex * 19/*BEZIER_SIZE*/; var curves = this.curves; - var dfx = curves[curveIndex]; - if (!dfx/*LINEAR*/) return percent; - if (dfx == -1/*STEPPED*/) return 0; - var dfy = curves[curveIndex + 1]; - var ddfx = curves[curveIndex + 2]; - var ddfy = curves[curveIndex + 3]; - var dddfx = curves[curveIndex + 4]; - var dddfy = curves[curveIndex + 5]; + curves[i++] = 2/*BEZIER*/; + var x = dfx, y = dfy; - var i = 10/*BEZIER_SEGMENTS*/ - 2; - while (true) { - if (x >= percent) { - var lastX = x - dfx; - var lastY = y - dfy; - return lastY + (y - lastY) * (percent - lastX) / (x - lastX); - } - if (i == 0) break; - i--; + for (var n = i + 19/*BEZIER_SIZE*/ - 1; i < n; i += 2) { + curves[i] = x; + curves[i + 1] = y; dfx += ddfx; dfy += ddfy; ddfx += dddfx; @@ -290,6 +412,31 @@ spine.Curves.prototype = { x += dfx; y += dfy; } + }, + getCurvePercent: function (frameIndex, percent) { + percent = percent < 0 ? 0 : (percent > 1 ? 1 : percent); + var curves = this.curves; + var i = frameIndex * 19/*BEZIER_SIZE*/; + var type = curves[i]; + if (type === 0/*LINEAR*/) return percent; + if (type == 1/*STEPPED*/) return 0; + i++; + var x = 0; + for (var start = i, n = i + 19/*BEZIER_SIZE*/ - 1; i < n; i += 2) { + x = curves[i]; + if (x >= percent) { + var prevX, prevY; + if (i == start) { + prevX = 0; + prevY = 0; + } else { + prevX = curves[i - 2]; + prevY = curves[i - 1]; + } + return prevY + (curves[i + 1] - prevY) * (percent - prevX) / (x - prevX); + } + } + var y = curves[i - 1]; return y + (1 - y) * (percent - x) / (1 - x); // Last point is 1,1. } }; @@ -325,19 +472,19 @@ spine.RotateTimeline.prototype = { return; } - // Interpolate between the last frame and the current frame. - var frameIndex = spine.binarySearch(frames, time, 2); - var lastFrameValue = frames[frameIndex - 1]; + // Interpolate between the previous frame and the current frame. + var frameIndex = spine.Animation.binarySearch(frames, time, 2); + var prevFrameValue = frames[frameIndex - 1]; var frameTime = frames[frameIndex]; - var percent = 1 - (time - frameTime) / (frames[frameIndex - 2/*LAST_FRAME_TIME*/] - frameTime); + var percent = 1 - (time - frameTime) / (frames[frameIndex - 2/*PREV_FRAME_TIME*/] - frameTime); percent = this.curves.getCurvePercent(frameIndex / 2 - 1, percent); - var amount = frames[frameIndex + 1/*FRAME_VALUE*/] - lastFrameValue; + var amount = frames[frameIndex + 1/*FRAME_VALUE*/] - prevFrameValue; while (amount > 180) amount -= 360; while (amount < -180) amount += 360; - amount = bone.data.rotation + (lastFrameValue + amount * percent) - bone.rotation; + amount = bone.data.rotation + (prevFrameValue + amount * percent) - bone.rotation; while (amount > 180) amount -= 360; while (amount < -180) @@ -374,16 +521,16 @@ spine.TranslateTimeline.prototype = { return; } - // Interpolate between the last frame and the current frame. - var frameIndex = spine.binarySearch(frames, time, 3); - var lastFrameX = frames[frameIndex - 2]; - var lastFrameY = frames[frameIndex - 1]; + // Interpolate between the previous frame and the current frame. + var frameIndex = spine.Animation.binarySearch(frames, time, 3); + var prevFrameX = frames[frameIndex - 2]; + var prevFrameY = frames[frameIndex - 1]; var frameTime = frames[frameIndex]; - var percent = 1 - (time - frameTime) / (frames[frameIndex + -3/*LAST_FRAME_TIME*/] - frameTime); + var percent = 1 - (time - frameTime) / (frames[frameIndex + -3/*PREV_FRAME_TIME*/] - frameTime); percent = this.curves.getCurvePercent(frameIndex / 3 - 1, percent); - bone.x += (bone.data.x + lastFrameX + (frames[frameIndex + 1/*FRAME_X*/] - lastFrameX) * percent - bone.x) * alpha; - bone.y += (bone.data.y + lastFrameY + (frames[frameIndex + 2/*FRAME_Y*/] - lastFrameY) * percent - bone.y) * alpha; + bone.x += (bone.data.x + prevFrameX + (frames[frameIndex + 1/*FRAME_X*/] - prevFrameX) * percent - bone.x) * alpha; + bone.y += (bone.data.y + prevFrameY + (frames[frameIndex + 2/*FRAME_Y*/] - prevFrameY) * percent - bone.y) * alpha; } }; @@ -410,21 +557,21 @@ spine.ScaleTimeline.prototype = { var bone = skeleton.bones[this.boneIndex]; if (time >= frames[frames.length - 3]) { // Time is after last frame. - bone.scaleX += (bone.data.scaleX - 1 + frames[frames.length - 2] - bone.scaleX) * alpha; - bone.scaleY += (bone.data.scaleY - 1 + frames[frames.length - 1] - bone.scaleY) * alpha; + bone.scaleX += (bone.data.scaleX * frames[frames.length - 2] - bone.scaleX) * alpha; + bone.scaleY += (bone.data.scaleY * frames[frames.length - 1] - bone.scaleY) * alpha; return; } - // Interpolate between the last frame and the current frame. - var frameIndex = spine.binarySearch(frames, time, 3); - var lastFrameX = frames[frameIndex - 2]; - var lastFrameY = frames[frameIndex - 1]; + // Interpolate between the previous frame and the current frame. + var frameIndex = spine.Animation.binarySearch(frames, time, 3); + var prevFrameX = frames[frameIndex - 2]; + var prevFrameY = frames[frameIndex - 1]; var frameTime = frames[frameIndex]; - var percent = 1 - (time - frameTime) / (frames[frameIndex + -3/*LAST_FRAME_TIME*/] - frameTime); + var percent = 1 - (time - frameTime) / (frames[frameIndex + -3/*PREV_FRAME_TIME*/] - frameTime); percent = this.curves.getCurvePercent(frameIndex / 3 - 1, percent); - bone.scaleX += (bone.data.scaleX - 1 + lastFrameX + (frames[frameIndex + 1/*FRAME_X*/] - lastFrameX) * percent - bone.scaleX) * alpha; - bone.scaleY += (bone.data.scaleY - 1 + lastFrameY + (frames[frameIndex + 2/*FRAME_Y*/] - lastFrameY) * percent - bone.scaleY) * alpha; + bone.scaleX += (bone.data.scaleX * (prevFrameX + (frames[frameIndex + 1/*FRAME_X*/] - prevFrameX) * percent) - bone.scaleX) * alpha; + bone.scaleY += (bone.data.scaleY * (prevFrameY + (frames[frameIndex + 2/*FRAME_Y*/] - prevFrameY) * percent) - bone.scaleY) * alpha; } }; @@ -450,31 +597,31 @@ spine.ColorTimeline.prototype = { var frames = this.frames; if (time < frames[0]) return; // Time is before first frame. - var slot = skeleton.slots[this.slotIndex]; - - if (time >= frames[frames.length - 5]) { // Time is after last frame. + var r, g, b, a; + if (time >= frames[frames.length - 5]) { + // Time is after last frame. var i = frames.length - 1; - slot.r = frames[i - 3]; - slot.g = frames[i - 2]; - slot.b = frames[i - 1]; - slot.a = frames[i]; - return; + r = frames[i - 3]; + g = frames[i - 2]; + b = frames[i - 1]; + a = frames[i]; + } else { + // Interpolate between the previous frame and the current frame. + var frameIndex = spine.Animation.binarySearch(frames, time, 5); + var prevFrameR = frames[frameIndex - 4]; + var prevFrameG = frames[frameIndex - 3]; + var prevFrameB = frames[frameIndex - 2]; + var prevFrameA = frames[frameIndex - 1]; + var frameTime = frames[frameIndex]; + var percent = 1 - (time - frameTime) / (frames[frameIndex - 5/*PREV_FRAME_TIME*/] - frameTime); + percent = this.curves.getCurvePercent(frameIndex / 5 - 1, percent); + + r = prevFrameR + (frames[frameIndex + 1/*FRAME_R*/] - prevFrameR) * percent; + g = prevFrameG + (frames[frameIndex + 2/*FRAME_G*/] - prevFrameG) * percent; + b = prevFrameB + (frames[frameIndex + 3/*FRAME_B*/] - prevFrameB) * percent; + a = prevFrameA + (frames[frameIndex + 4/*FRAME_A*/] - prevFrameA) * percent; } - - // Interpolate between the last frame and the current frame. - var frameIndex = spine.binarySearch(frames, time, 5); - var lastFrameR = frames[frameIndex - 4]; - var lastFrameG = frames[frameIndex - 3]; - var lastFrameB = frames[frameIndex - 2]; - var lastFrameA = frames[frameIndex - 1]; - var frameTime = frames[frameIndex]; - var percent = 1 - (time - frameTime) / (frames[frameIndex - 5/*LAST_FRAME_TIME*/] - frameTime); - percent = this.curves.getCurvePercent(frameIndex / 5 - 1, percent); - - var r = lastFrameR + (frames[frameIndex + 1/*FRAME_R*/] - lastFrameR) * percent; - var g = lastFrameG + (frames[frameIndex + 2/*FRAME_G*/] - lastFrameG) * percent; - var b = lastFrameB + (frames[frameIndex + 3/*FRAME_B*/] - lastFrameB) * percent; - var a = lastFrameA + (frames[frameIndex + 4/*FRAME_A*/] - lastFrameA) * percent; + var slot = skeleton.slots[this.slotIndex]; if (alpha < 1) { slot.r += (r - slot.r) * alpha; slot.g += (g - slot.g) * alpha; @@ -507,16 +654,18 @@ spine.AttachmentTimeline.prototype = { }, apply: function (skeleton, lastTime, time, firedEvents, alpha) { var frames = this.frames; - if (time < frames[0]) return; // Time is before first frame. + if (time < frames[0]) { + if (lastTime > time) this.apply(skeleton, lastTime, Number.MAX_VALUE, null, 0); + return; + } else if (lastTime > time) // + lastTime = -1; - var frameIndex; - if (time >= frames[frames.length - 1]) // Time is after last frame. - frameIndex = frames.length - 1; - else - frameIndex = spine.binarySearch(frames, time, 1) - 1; + var frameIndex = time >= frames[frames.length - 1] ? frames.length - 1 : spine.Animation.binarySearch1(frames, time) - 1; + if (frames[frameIndex] < lastTime) return; var attachmentName = this.attachmentNames[frameIndex]; - skeleton.slots[this.slotIndex].setAttachment(!attachmentName ? null : skeleton.getAttachmentBySlotIndex(this.slotIndex, attachmentName)); + skeleton.slots[this.slotIndex].setAttachment( + !attachmentName ? null : skeleton.getAttachmentBySlotIndex(this.slotIndex, attachmentName)); } }; @@ -552,7 +701,7 @@ spine.EventTimeline.prototype = { if (lastTime < frames[0]) frameIndex = 0; else { - frameIndex = spine.binarySearch(frames, lastTime, 1); + frameIndex = spine.Animation.binarySearch1(frames, lastTime); var frame = frames[frameIndex]; while (frameIndex > 0) { // Fire multiple events with the same frame. if (frames[frameIndex - 1] != frame) break; @@ -587,7 +736,7 @@ spine.DrawOrderTimeline.prototype = { if (time >= frames[frames.length - 1]) // Time is after last frame. frameIndex = frames.length - 1; else - frameIndex = spine.binarySearch(frames, time, 1) - 1; + frameIndex = spine.Animation.binarySearch1(frames, time) - 1; var drawOrder = skeleton.drawOrder; var slots = skeleton.slots; @@ -603,15 +752,185 @@ spine.DrawOrderTimeline.prototype = { } }; +spine.FfdTimeline = function (frameCount) { + this.curves = new spine.Curves(frameCount); + this.frames = []; + this.frames.length = frameCount; + this.frameVertices = []; + this.frameVertices.length = frameCount; +}; +spine.FfdTimeline.prototype = { + slotIndex: 0, + attachment: 0, + getFrameCount: function () { + return this.frames.length; + }, + setFrame: function (frameIndex, time, vertices) { + this.frames[frameIndex] = time; + this.frameVertices[frameIndex] = vertices; + }, + apply: function (skeleton, lastTime, time, firedEvents, alpha) { + var slot = skeleton.slots[slotIndex]; + if (slot.attachment != attachment) return; + + var frames = this.frames; + if (time < frames[0]) { + slot.attachmentVertices.length = 0; + return; // Time is before first frame. + } + + var frameVertices = this.frameVertices; + var vertexCount = frameVertices[0].length; + + var vertices = slot.attachmentVertices; + if (vertices.length != vertexCount) alpha = 1; + vertices.length = vertexCount; + + if (time >= frames[frames.length - 1]) { // Time is after last frame. + var lastVertices = frameVertices[frames.length - 1]; + if (alpha < 1) { + for (var i = 0; i < vertexCount; i++) + vertices[i] += (lastVertices[i] - vertices[i]) * alpha; + } else { + for (var i = 0; i < vertexCount; i++) + vertices[i] = lastVertices[i]; + } + return; + } + + // Interpolate between the previous frame and the current frame. + var frameIndex = spine.Animation.binarySearch1(frames, time); + var frameTime = frames[frameIndex]; + var percent = 1 - (time - frameTime) / (frames[frameIndex - 1] - frameTime); + percent = this.curves.getCurvePercent(frameIndex - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent)); + + var prevVertices = frameVertices[frameIndex - 1]; + var nextVertices = frameVertices[frameIndex]; + + if (alpha < 1) { + for (var i = 0; i < vertexCount; i++) { + var prev = prevVertices[i]; + vertices[i] += (prev + (nextVertices[i] - prev) * percent - vertices[i]) * alpha; + } + } else { + for (var i = 0; i < vertexCount; i++) { + var prev = prevVertices[i]; + vertices[i] = prev + (nextVertices[i] - prev) * percent; + } + } + } +}; + +spine.IkConstraintTimeline = function (frameCount) { + this.curves = new spine.Curves(frameCount); + this.frames = []; // time, mix, bendDirection, ... + this.frames.length = frameCount * 3; +}; +spine.IkConstraintTimeline.prototype = { + ikConstraintIndex: 0, + getFrameCount: function () { + return this.frames.length / 3; + }, + setFrame: function (frameIndex, time, mix, bendDirection) { + frameIndex *= 3; + this.frames[frameIndex] = time; + this.frames[frameIndex + 1] = mix; + this.frames[frameIndex + 2] = bendDirection; + }, + apply: function (skeleton, lastTime, time, firedEvents, alpha) { + var frames = this.frames; + if (time < frames[0]) return; // Time is before first frame. + + var ikConstraint = skeleton.ikConstraints[this.ikConstraintIndex]; + + if (time >= frames[frames.length - 3]) { // Time is after last frame. + ikConstraint.mix += (frames[frames.length - 2] - ikConstraint.mix) * alpha; + ikConstraint.bendDirection = frames[frames.length - 1]; + return; + } + + // Interpolate between the previous frame and the current frame. + var frameIndex = spine.Animation.binarySearch(frames, time, 3); + var prevFrameMix = frames[frameIndex + -2/*PREV_FRAME_MIX*/]; + var frameTime = frames[frameIndex]; + var percent = 1 - (time - frameTime) / (frames[frameIndex + -3/*PREV_FRAME_TIME*/] - frameTime); + percent = this.curves.getCurvePercent(frameIndex / 3 - 1, percent); + + var mix = prevFrameMix + (frames[frameIndex + 1/*FRAME_MIX*/] - prevFrameMix) * percent; + ikConstraint.mix += (mix - ikConstraint.mix) * alpha; + ikConstraint.bendDirection = frames[frameIndex + -1/*PREV_FRAME_BEND_DIRECTION*/]; + } +}; + +spine.FlipXTimeline = function (frameCount) { + this.curves = new spine.Curves(frameCount); + this.frames = []; // time, flip, ... + this.frames.length = frameCount * 2; +}; +spine.FlipXTimeline.prototype = { + boneIndex: 0, + getFrameCount: function () { + return this.frames.length / 2; + }, + setFrame: function (frameIndex, time, flip) { + frameIndex *= 2; + this.frames[frameIndex] = time; + this.frames[frameIndex + 1] = flip ? 1 : 0; + }, + apply: function (skeleton, lastTime, time, firedEvents, alpha) { + var frames = this.frames; + if (time < frames[0]) { + if (lastTime > time) this.apply(skeleton, lastTime, Number.MAX_VALUE, null, 0); + return; + } else if (lastTime > time) // + lastTime = -1; + var frameIndex = (time >= frames[frames.length - 2] ? frames.length : spine.Animation.binarySearch(frames, time, 2)) - 2; + if (frames[frameIndex] < lastTime) return; + skeleton.bones[boneIndex].flipX = frames[frameIndex + 1] != 0; + } +}; + +spine.FlipYTimeline = function (frameCount) { + this.curves = new spine.Curves(frameCount); + this.frames = []; // time, flip, ... + this.frames.length = frameCount * 2; +}; +spine.FlipYTimeline.prototype = { + boneIndex: 0, + getFrameCount: function () { + return this.frames.length / 2; + }, + setFrame: function (frameIndex, time, flip) { + frameIndex *= 2; + this.frames[frameIndex] = time; + this.frames[frameIndex + 1] = flip ? 1 : 0; + }, + apply: function (skeleton, lastTime, time, firedEvents, alpha) { + var frames = this.frames; + if (time < frames[0]) { + if (lastTime > time) this.apply(skeleton, lastTime, Number.MAX_VALUE, null, 0); + return; + } else if (lastTime > time) // + lastTime = -1; + var frameIndex = (time >= frames[frames.length - 2] ? frames.length : spine.Animation.binarySearch(frames, time, 2)) - 2; + if (frames[frameIndex] < lastTime) return; + skeleton.bones[boneIndex].flipY = frames[frameIndex + 1] != 0; + } +}; + spine.SkeletonData = function () { this.bones = []; this.slots = []; this.skins = []; this.events = []; this.animations = []; + this.ikConstraints = []; }; spine.SkeletonData.prototype = { + name: null, defaultSkin: null, + width: 0, height: 0, + version: null, hash: null, /** @return May be null. */ findBone: function (boneName) { var bones = this.bones; @@ -630,7 +949,7 @@ spine.SkeletonData.prototype = { findSlot: function (slotName) { var slots = this.slots; for (var i = 0, n = slots.length; i < n; i++) { - if (slots[i].name == slotName) return slots[i]; + if (slots[i].name == slotName) return slot[i]; } return null; }, @@ -661,6 +980,13 @@ spine.SkeletonData.prototype = { for (var i = 0, n = animations.length; i < n; i++) if (animations[i].name == animationName) return animations[i]; return null; + }, + /** @return May be null. */ + findIkConstraint: function (ikConstraintName) { + var ikConstraints = this.ikConstraints; + for (var i = 0, n = ikConstraints.length; i < n; i++) + if (ikConstraints[i].name == ikConstraintName) return ikConstraints[i]; + return null; } }; @@ -671,7 +997,7 @@ spine.Skeleton = function (skeletonData) { for (var i = 0, n = skeletonData.bones.length; i < n; i++) { var boneData = skeletonData.bones[i]; var parent = !boneData.parent ? null : this.bones[skeletonData.bones.indexOf(boneData.parent)]; - this.bones.push(new spine.Bone(boneData, parent)); + this.bones.push(new spine.Bone(boneData, this, parent)); } this.slots = []; @@ -679,10 +1005,17 @@ spine.Skeleton = function (skeletonData) { for (var i = 0, n = skeletonData.slots.length; i < n; i++) { var slotData = skeletonData.slots[i]; var bone = this.bones[skeletonData.bones.indexOf(slotData.boneData)]; - var slot = new spine.Slot(slotData, this, bone); + var slot = new spine.Slot(slotData, bone); this.slots.push(slot); this.drawOrder.push(slot); } + + this.ikConstraints = []; + for (var i = 0, n = skeletonData.ikConstraints.length; i < n; i++) + this.ikConstraints.push(new spine.IkConstraint(skeletonData.ikConstraints[i], this)); + + this.boneCache = []; + this.updateCache(); }; spine.Skeleton.prototype = { x: 0, y: 0, @@ -690,13 +1023,62 @@ spine.Skeleton.prototype = { r: 1, g: 1, b: 1, a: 1, time: 0, flipX: false, flipY: false, + /** Caches information about bones and IK constraints. Must be called if bones or IK constraints are added or removed. */ + updateCache: function () { + var ikConstraints = this.ikConstraints; + var ikConstraintsCount = ikConstraints.length; + + var arrayCount = ikConstraintsCount + 1; + var boneCache = this.boneCache; + if (boneCache.length > arrayCount) boneCache.length = arrayCount; + for (var i = 0, n = boneCache.length; i < n; i++) + boneCache[i].length = 0; + while (boneCache.length < arrayCount) + boneCache[boneCache.length] = []; + + var nonIkBones = boneCache[0]; + var bones = this.bones; + + outer: + for (var i = 0, n = bones.length; i < n; i++) { + var bone = bones[i]; + var current = bone; + do { + for (var ii = 0; ii < ikConstraintsCount; ii++) { + var ikConstraint = ikConstraints[ii]; + var parent = ikConstraint.bones[0]; + var child= ikConstraint.bones[ikConstraint.bones.length - 1]; + while (true) { + if (current == child) { + boneCache[ii].push(bone); + boneCache[ii + 1].push(bone); + continue outer; + } + if (child == parent) break; + child = child.parent; + } + } + current = current.parent; + } while (current); + nonIkBones[nonIkBones.length] = bone; + } + }, /** Updates the world transform for each bone. */ updateWorldTransform: function () { - var flipX = this.flipX; - var flipY = this.flipY; var bones = this.bones; - for (var i = 0, n = bones.length; i < n; i++) - bones[i].updateWorldTransform(flipX, flipY); + for (var i = 0, n = bones.length; i < n; i++) { + var bone = bones[i]; + bone.rotationIK = bone.rotation; + } + var i = 0, last = this.boneCache.length - 1; + while (true) { + var cacheBones = this.boneCache[i]; + for (var ii = 0, nn = cacheBones.length; ii < nn; ii++) + cacheBones[ii].updateWorldTransform(); + if (i == last) break; + this.ikConstraints[i].apply(); + i++; + } }, /** Sets the bones and slots to their setup pose values. */ setToSetupPose: function () { @@ -707,15 +1089,25 @@ spine.Skeleton.prototype = { var bones = this.bones; for (var i = 0, n = bones.length; i < n; i++) bones[i].setToSetupPose(); + + var ikConstraints = this.ikConstraints; + for (var i = 0, n = ikConstraints.length; i < n; i++) { + var ikConstraint = ikConstraints[i]; + ikConstraint.bendDirection = ikConstraint.data.bendDirection; + ikConstraint.mix = ikConstraint.data.mix; + } }, setSlotsToSetupPose: function () { var slots = this.slots; - for (var i = 0, n = slots.length; i < n; i++) + var drawOrder = this.drawOrder; + for (var i = 0, n = slots.length; i < n; i++) { + drawOrder[i] = slots[i]; slots[i].setToSetupPose(i); + } }, /** @return May return null. */ getRootBone: function () { - return this.bones.length == 0 ? null : this.bones[0]; + return this.bones.length ? this.bones[0] : null; }, /** @return May be null. */ findBone: function (boneName) { @@ -751,11 +1143,24 @@ spine.Skeleton.prototype = { this.setSkin(skin); }, /** Sets the skin used to look up attachments not found in the {@link SkeletonData#getDefaultSkin() default skin}. Attachments - * from the new skin are attached if the corresponding attachment from the old skin was attached. + * from the new skin are attached if the corresponding attachment from the old skin was attached. If there was no old skin, + * each slot's setup mode attachment is attached from the new skin. * @param newSkin May be null. */ setSkin: function (newSkin) { - if (this.skin && newSkin) { - newSkin._attachAll(this, this.skin); + if (newSkin) { + if (this.skin) + newSkin._attachAll(this, this.skin); + else { + var slots = this.slots; + for (var i = 0, n = slots.length; i < n; i++) { + var slot = slots[i]; + var name = slot.data.attachmentName; + if (name) { + var attachment = newSkin.getAttachment(i, name); + if (attachment) slot.setAttachment(attachment); + } + } + } } this.skin = newSkin; }, @@ -780,7 +1185,7 @@ spine.Skeleton.prototype = { if (slot.data.name == slotName) { var attachment = null; if (attachmentName) { - attachment = this.getAttachment(i, attachmentName); + attachment = this.getAttachmentBySlotIndex(i, attachmentName); if (!attachment) throw "Attachment not found: " + attachmentName + ", for slot: " + slotName; } slot.setAttachment(attachment); @@ -789,6 +1194,13 @@ spine.Skeleton.prototype = { } throw "Slot not found: " + slotName; }, + /** @return May be null. */ + findIkConstraint: function (ikConstraintName) { + var ikConstraints = this.ikConstraints; + for (var i = 0, n = ikConstraints.length; i < n; i++) + if (ikConstraints[i].data.name == ikConstraintName) return ikConstraints[i]; + return null; + }, update: function (delta) { this.time += delta; } @@ -797,7 +1209,6 @@ spine.Skeleton.prototype = { spine.EventData = function (name) { this.name = name; }; - spine.EventData.prototype = { intValue: 0, floatValue: 0, @@ -807,7 +1218,6 @@ spine.EventData.prototype = { spine.Event = function (data) { this.data = data; }; - spine.Event.prototype = { intValue: 0, floatValue: 0, @@ -827,15 +1237,15 @@ spine.RegionAttachment = function (name) { this.offset.length = 8; this.uvs = []; this.uvs.length = 8; - this["type"] = spine.AttachmentType.region; //FOR advance mode }; - spine.RegionAttachment.prototype = { type: spine.AttachmentType.region, x: 0, y: 0, rotation: 0, scaleX: 1, scaleY: 1, width: 0, height: 0, + r: 1, g: 1, b: 1, a: 1, + path: null, rendererObject: null, regionOffsetX: 0, regionOffsetY: 0, regionWidth: 0, regionHeight: 0, @@ -869,7 +1279,7 @@ spine.RegionAttachment.prototype = { var localY = -this.height / 2 * this.scaleY + this.regionOffsetY * regionScaleY; var localX2 = localX + this.regionWidth * regionScaleX; var localY2 = localY + this.regionHeight * regionScaleY; - var radians = this.rotation * Math.PI / 180; + var radians = this.rotation * spine.degRad; var cos = Math.cos(radians); var sin = Math.sin(radians); var localXCos = localX * cos + this.x; @@ -890,14 +1300,10 @@ spine.RegionAttachment.prototype = { offset[6/*X4*/] = localX2Cos - localYSin; offset[7/*Y4*/] = localYCos + localX2Sin; }, - computeVertices: function (x, y, slot, vertices) { - var bone = slot.bone; + computeVertices: function (x, y, bone, vertices) { x += bone.worldX; y += bone.worldY; - var m00 = bone.m00; - var m01 = bone.m01; - var m10 = bone.m10; - var m11 = bone.m11; + var m00 = bone.m00, m01 = bone.m01, m10 = bone.m10, m11 = bone.m11; var offset = this.offset; vertices[0/*X1*/] = offset[0/*X1*/] * m00 + offset[1/*Y1*/] * m01 + x; vertices[1/*Y1*/] = offset[0/*X1*/] * m10 + offset[1/*Y1*/] * m11 + y; @@ -930,35 +1336,37 @@ spine.MeshAttachment.prototype = { edges: null, width: 0, height: 0, updateUVs: function () { - var width = this.regionU2 - this.regionU, height = this.regionV2 - this.regionV; - var n = this.regionUVs.length; - if (!this.uvs || this.uvs.length != n) { - this.uvs = new spine.Float32Array(n); + var width = regionU2 - regionU, height = regionV2 - regionV; + var n = regionUVs.length; + if (!uvs || uvs.length != n) { + uvs = []; + uvs.length = n; } - if (this.regionRotate) { + if (regionRotate) { for (var i = 0; i < n; i += 2) { - this.uvs[i] = this.regionU + this.regionUVs[i + 1] * width; - this.uvs[i + 1] = this.regionV + height - this.regionUVs[i] * height; + uvs[i] = regionU + regionUVs[i + 1] * width; + uvs[i + 1] = regionV + height - regionUVs[i] * height; } } else { for (var i = 0; i < n; i += 2) { - this.uvs[i] = this.regionU + this.regionUVs[i] * width; - this.uvs[i + 1] = this.regionV + this.regionUVs[i + 1] * height; + uvs[i] = regionU + regionUVs[i] * width; + uvs[i + 1] = regionV + regionUVs[i + 1] * height; } } }, - computeVertices: function (x, y, slot, vertices) { + computeWorldVertices: function (x, y, slot, worldVertices) { var bone = slot.bone; x += bone.worldX; y += bone.worldY; var m00 = bone.m00, m01 = bone.m01, m10 = bone.m10, m11 = bone.m11; - var verticesCount = this.vertices.length; - if (slot.attachment.length == verticesCount) this.vertices = slot.attachment; + var vertices = this.vertices; + var verticesCount = vertices.length; + if (slot.attachmentVertices.length == verticesCount) vertices = slot.attachmentVertices; for (var i = 0; i < verticesCount; i += 2) { - var vx = this.vertices[i]; - var vy = this.vertices[i + 1]; - vertices[i] = vx * m00 + vy * m01 + x; - vertices[i + 1] = vx * m10 + vy * m11 + y; + var vx = vertices[i]; + var vy = vertices[i + 1]; + worldVertices[i] = vx * m00 + vy * m01 + x; + worldVertices[i + 1] = vx * m10 + vy * m11 + y; } } }; @@ -984,20 +1392,21 @@ spine.SkinnedMeshAttachment.prototype = { edges: null, width: 0, height: 0, updateUVs: function (u, v, u2, v2, rotate) { - var width = this.regionU2 - this.regionU, height = this.regionV2 - this.regionV; - var n = this.regionUVs.length; - if (!this.uvs || this.uvs.length != n) { - this.uvs = new spine.Float32Array(n); + var width = regionU2 - regionU, height = regionV2 - regionV; + var n = regionUVs.length; + if (!uvs || uvs.length != n) { + uvs = []; + uvs.length = n; } - if (this.regionRotate) { + if (regionRotate) { for (var i = 0; i < n; i += 2) { - this.uvs[i] = this.regionU + this.regionUVs[i + 1] * width; - this.uvs[i + 1] = this.regionV + height - this.regionUVs[i] * height; + uvs[i] = regionU + regionUVs[i + 1] * width; + uvs[i + 1] = regionV + height - regionUVs[i] * height; } } else { for (var i = 0; i < n; i += 2) { - this.uvs[i] = this.regionU + this.regionUVs[i] * width; - this.uvs[i + 1] = this.regionV + this.regionUVs[i + 1] * height; + uvs[i] = regionU + regionUVs[i] * width; + uvs[i + 1] = regionV + regionUVs[i + 1] * height; } } }, @@ -1048,18 +1457,13 @@ spine.SkinnedMeshAttachment.prototype = { spine.BoundingBoxAttachment = function (name) { this.name = name; this.vertices = []; - this["type"] = spine.AttachmentType.boundingBox; //FOR advance mode }; - spine.BoundingBoxAttachment.prototype = { - type: spine.AttachmentType.boundingBox, + type: spine.AttachmentType.boundingbox, computeWorldVertices: function (x, y, bone, worldVertices) { x += bone.worldX; y += bone.worldY; - var m00 = bone.m00; - var m01 = bone.m01; - var m10 = bone.m10; - var m11 = bone.m11; + var m00 = bone.m00, m01 = bone.m01, m10 = bone.m10, m11 = bone.m11; var vertices = this.vertices; for (var i = 0, n = vertices.length; i < n; i += 2) { var px = vertices[i]; @@ -1087,20 +1491,19 @@ spine.AnimationStateData.prototype = { this.animationToMixTime[from.name + ":" + to.name] = duration; }, getMix: function (from, to) { - var time = this.animationToMixTime[from.name + ":" + to.name]; - return time ? time : this.defaultMix; + var key = from.name + ":" + to.name; + return this.animationToMixTime.hasOwnProperty(key) ? this.animationToMixTime[key] : this.defaultMix; } }; -spine.TrackEntry = function () { -}; +spine.TrackEntry = function () {}; spine.TrackEntry.prototype = { next: null, previous: null, animation: null, loop: false, delay: 0, time: 0, lastTime: -1, endTime: 0, timeScale: 1, - mixTime: 0, mixDuration: 0, + mixTime: 0, mixDuration: 0, mix: 1, onStart: null, onEnd: null, onComplete: null, onEvent: null }; @@ -1109,7 +1512,6 @@ spine.AnimationState = function (stateData) { this.tracks = []; this.events = []; }; - spine.AnimationState.prototype = { onStart: null, onEnd: null, @@ -1122,16 +1524,17 @@ spine.AnimationState.prototype = { var current = this.tracks[i]; if (!current) continue; - var trackDelta = delta * current.timeScale; - current.time += trackDelta; + current.time += delta * current.timeScale; if (current.previous) { - current.previous.time += trackDelta; - current.mixTime += trackDelta; + var previousDelta = delta * current.previous.timeScale; + current.previous.time += previousDelta; + current.mixTime += previousDelta; } var next = current.next; if (next) { - if (current.lastTime >= next.delay) this.setCurrent(i, next); + next.time = current.lastTime - next.delay; + if (next.time >= 0) this.setCurrent(i, next); } else { // End non-looping animation when it reaches its end time and there is no next entry. if (!current.loop && current.lastTime >= current.endTime) this.clearTrack(i); @@ -1152,14 +1555,17 @@ spine.AnimationState.prototype = { if (!loop && time > endTime) time = endTime; var previous = current.previous; - if (!previous) - current.animation.apply(skeleton, current.lastTime, time, loop, this.events); - else { + if (!previous) { + if (current.mix == 1) + current.animation.apply(skeleton, current.lastTime, time, loop, this.events); + else + current.animation.mix(skeleton, current.lastTime, time, loop, this.events, current.mix); + } else { var previousTime = previous.time; if (!previous.loop && previousTime > previous.endTime) previousTime = previous.endTime; previous.animation.apply(skeleton, previousTime, previousTime, previous.loop, null); - var alpha = current.mixTime / current.mixDuration; + var alpha = current.mixTime / current.mixDuration * current.mix; if (alpha >= 1) { alpha = 1; current.previous = null; @@ -1169,8 +1575,8 @@ spine.AnimationState.prototype = { for (var ii = 0, nn = this.events.length; ii < nn; ii++) { var event = this.events[ii]; - if (current.onEvent != null) current.onEvent(i, event); - if (this.onEvent != null) this.onEvent(i, event); + if (current.onEvent) current.onEvent(i, event); + if (this.onEvent) this.onEvent(i, event); } // Check if completed the animation or a loop iteration. @@ -1193,8 +1599,8 @@ spine.AnimationState.prototype = { var current = this.tracks[trackIndex]; if (!current) return; - if (current.onEnd != null) current.onEnd(trackIndex); - if (this.onEnd != null) this.onEnd(trackIndex); + if (current.onEnd) current.onEnd(trackIndex); + if (this.onEnd) this.onEnd(trackIndex); this.tracks[trackIndex] = null; }, @@ -1210,8 +1616,8 @@ spine.AnimationState.prototype = { var previous = current.previous; current.previous = null; - if (current.onEnd != null) current.onEnd(index); - if (this.onEnd != null) this.onEnd(index); + if (current.onEnd) current.onEnd(index); + if (this.onEnd) this.onEnd(index); entry.mixDuration = this.data.getMix(current.animation, entry.animation); if (entry.mixDuration > 0) { @@ -1226,8 +1632,8 @@ spine.AnimationState.prototype = { this.tracks[index] = entry; - if (entry.onStart != null) entry.onStart(index); - if (this.onStart != null) this.onStart(index); + if (entry.onStart) entry.onStart(index); + if (this.onStart) this.onStart(index); }, setAnimationByName: function (trackIndex, animationName, loop) { var animation = this.data.skeletonData.findAnimation(animationName); @@ -1412,14 +1818,14 @@ spine.SkeletonJson.prototype = { var type = spine.AttachmentType[map["type"] || "region"]; var path = map["path"] || name; - + var scale = this.scale; if (type == spine.AttachmentType.region) { var region = this.attachmentLoader.newRegionAttachment(skin, name, path); if (!region) return null; region.path = path; - region.x = (map["x"] || 0) * scale; - region.y = (map["y"] || 0) * scale; + region.x = (map["x"] || 0) * this.scale; + region.y = (map["y"] || 0) * this.scale; region.scaleX = map.hasOwnProperty("scaleX") ? map["scaleX"] : 1; region.scaleY = map.hasOwnProperty("scaleY") ? map["scaleY"] : 1; region.rotation = map["rotation"] || 0; @@ -1439,7 +1845,7 @@ spine.SkeletonJson.prototype = { } else if (type == spine.AttachmentType.mesh) { var mesh = this.attachmentLoader.newMeshAttachment(skin, name, path); if (!mesh) return null; - mesh.path = path; + mesh.path = path; mesh.vertices = this.getFloatArray(map, "vertices", scale); mesh.triangles = this.getIntArray(map, "triangles"); mesh.regionUVs = this.getFloatArray(map, "uvs", 1); @@ -1464,7 +1870,7 @@ spine.SkeletonJson.prototype = { mesh.path = path; var uvs = this.getFloatArray(map, "uvs", 1); - var vertices = this.getFloatArray(map, "vertices", 1); + vertices = this.getFloatArray(map, "vertices", 1); var weights = []; var bones = []; for (var i = 0, n = vertices.length; i < n; ) { @@ -1483,7 +1889,7 @@ spine.SkeletonJson.prototype = { mesh.triangles = this.getIntArray(map, "triangles"); mesh.regionUVs = uvs; mesh.updateUVs(); - + color = map["color"]; if (color) { mesh.r = this.toColor(color, 0); @@ -1491,7 +1897,7 @@ spine.SkeletonJson.prototype = { mesh.b = this.toColor(color, 2); mesh.a = this.toColor(color, 3); } - + mesh.hullLength = (map["hull"] || 0) * 2; if (map["edges"]) mesh.edges = this.getIntArray(map, "edges"); mesh.width = (map["width"] || 0) * scale; @@ -1501,7 +1907,7 @@ spine.SkeletonJson.prototype = { var attachment = this.attachmentLoader.newBoundingBoxAttachment(skin, name); var vertices = map["vertices"]; for (var i = 0, n = vertices.length; i < n; i++) - attachment.vertices.push(vertices[i] * scale); + attachment.vertices.push(vertices[i] * this.scale); return attachment; } throw "Unknown attachment type: " + type; @@ -1655,7 +2061,7 @@ spine.SkeletonJson.prototype = { if (!attachment) throw "FFD attachment not found: " + meshName; timeline.slotIndex = slotIndex; timeline.attachment = attachment; - + var isMesh = attachment.type == spine.AttachmentType.mesh; var vertexCount; if (isMesh) @@ -1680,20 +2086,20 @@ spine.SkeletonJson.prototype = { vertices.length = vertexCount; var start = valueMap["offset"] || 0; var nn = verticesValue.length; - if (this.scale == 1) { + if (scale == 1) { for (var ii = 0; ii < nn; ii++) vertices[ii + start] = verticesValue[ii]; } else { for (var ii = 0; ii < nn; ii++) - vertices[ii + start] = verticesValue[ii] * this.scale; + vertices[ii + start] = verticesValue[ii] * scale; } if (isMesh) { var meshVertices = attachment.vertices; - for (var ii = 0, nn = vertices.length; ii < nn; ii++) + for (var ii = 0, nn = vertices.length; ii < nn; i++) vertices[ii] += meshVertices[ii]; } } - + timeline.setFrame(frameIndex, valueMap["time"], vertices); this.readCurve(timeline, frameIndex, valueMap); frameIndex++; @@ -1767,7 +2173,7 @@ spine.SkeletonJson.prototype = { }, readCurve: function (timeline, frameIndex, valueMap) { var curve = valueMap["curve"]; - if (!curve) + if (!curve) timeline.curves.setLinear(frameIndex); else if (curve == "stepped") timeline.curves.setStepped(frameIndex); @@ -1780,7 +2186,8 @@ spine.SkeletonJson.prototype = { }, getFloatArray: function (map, name, scale) { var list = map[name]; - var values = new spine.Float32Array(list.length); + var values = []; + values = list.length; var i = 0, n = list.length; if (scale == 1) { for (; i < n; i++) @@ -1793,27 +2200,14 @@ spine.SkeletonJson.prototype = { }, getIntArray: function (map, name) { var list = map[name]; - var values = new spine.Uint16Array(list.length); + var values = []; + values = list.length; for (var i = 0, n = list.length; i < n; i++) values[i] = list[i] | 0; return values; } }; -spine.SkeletonJson.readCurve = function (timeline, frameIndex, valueMap) { - var curve = valueMap["curve"]; - if (!curve) return; - if (curve == "stepped") - timeline.curves.setStepped(frameIndex); - else if (curve instanceof Array) - timeline.curves.setCurve(frameIndex, curve[0], curve[1], curve[2], curve[3]); -}; - -spine.SkeletonJson.toColor = function (hexString, colorIndex) { - if (hexString.length != 8) throw "Color hexidecimal length must be 8, recieved: " + hexString; - return parseInt(hexString.substring(colorIndex * 2, (colorIndex * 2) + 2), 16) / 255; -}; - spine.Atlas = function (atlasText, textureLoader) { this.textureLoader = textureLoader; this.pages = []; @@ -1941,23 +2335,23 @@ spine.Atlas.prototype = { }; spine.Atlas.Format = { - Alpha: 0, - Intensity: 1, - LuminanceAlpha: 2, - RGB565: 3, - RGBA4444: 4, - RGB888: 5, - RGBA8888: 6 + alpha: 0, + intensity: 1, + luminanceAlpha: 2, + rgb565: 3, + rgba4444: 4, + rgb888: 5, + rgba8888: 6 }; spine.Atlas.TextureFilter = { - Nearest: 0, - Linear: 1, - MipMap: 2, - MipMapNearestNearest: 3, - MipMapLinearNearest: 4, - MipMapNearestLinear: 5, - MipMapLinearLinear: 6 + nearest: 0, + linear: 1, + mipMap: 2, + mipMapNearestNearest: 3, + mipMapLinearNearest: 4, + mipMapNearestLinear: 5, + mipMapLinearLinear: 6 }; spine.Atlas.TextureWrap = { @@ -1966,8 +2360,7 @@ spine.Atlas.TextureWrap = { repeat: 2 }; -spine.AtlasPage = function () { -}; +spine.AtlasPage = function () {}; spine.AtlasPage.prototype = { name: null, format: null, @@ -1980,8 +2373,7 @@ spine.AtlasPage.prototype = { height: 0 }; -spine.AtlasRegion = function () { -}; +spine.AtlasRegion = function () {}; spine.AtlasRegion.prototype = { page: null, name: null, @@ -2113,7 +2505,7 @@ spine.SkeletonBounds.prototype = { for (var i = 0; i < slotCount; i++) { var slot = slots[i]; var boundingBox = slot.attachment; - if (boundingBox.type != spine.AttachmentType.boundingBox) continue; + if (boundingBox.type != spine.AttachmentType.boundingbox) continue; boundingBoxes.push(boundingBox); var poolCount = polygonPool.length, polygon; @@ -2206,7 +2598,7 @@ spine.SkeletonBounds.prototype = { return inside; }, /** Returns true if the polygon contains the line segment. */ - intersectsSegment: function (polygon, x1, y1, x2, y2) { + polygonIntersectsSegment: function (polygon, x1, y1, x2, y2) { var nn = polygon.length; var width12 = x1 - x2, height12 = y1 - y2; var det1 = x1 * y2 - y1 * x2; @@ -2236,4 +2628,4 @@ spine.SkeletonBounds.prototype = { getHeight: function () { return this.maxY - this.minY; } -}; \ No newline at end of file +}; From 42bf0201d59c9ee494a8a10235fecda73c05025b Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Fri, 20 Mar 2015 12:00:26 +0800 Subject: [PATCH 0077/1039] Issue #2756: fixed the memory leak in cc.LabelBMFont --- cocos2d/labels/CCLabelBMFont.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos2d/labels/CCLabelBMFont.js b/cocos2d/labels/CCLabelBMFont.js index 6ac229c8b5..83bdf818cf 100644 --- a/cocos2d/labels/CCLabelBMFont.js +++ b/cocos2d/labels/CCLabelBMFont.js @@ -539,6 +539,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ updateLabel: function () { var self = this; self.string = self._initialString; + var i, j, characterSprite; // process string // Step 1: Make multiline if (self._width > 0) { @@ -549,8 +550,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ for (i = 0; i < stringArr.length; i++) { oldArrLength = stringArr.length; this._checkWarp(stringArr, i, self._width * this._scaleX, newWrapNum); - if (oldArrLength < stringArr.length) - { + if (oldArrLength < stringArr.length) { newWrapNum++; } if (i > 0) From 9c6f56cc1aadbfad7c1e127c09fbcc4eb736b9b8 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 20 Mar 2015 17:36:56 +0800 Subject: [PATCH 0078/1039] Fixed a bug that scale9Sprite updateDisplayColor error --- extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js | 4 +++- .../gui/control-extension/CCScale9SpriteCanvasRenderCmd.js | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js index 1dc9ae4734..ceab4aeb03 100644 --- a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js +++ b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js @@ -85,8 +85,10 @@ var scaleChildren = scale9Image.getChildren(); for (var i = 0; i < scaleChildren.length; i++) { var selChild = scaleChildren[i]; - if (selChild) + if (selChild){ selChild._renderCmd._updateDisplayColor(parentColor); + selChild._renderCmd._updateColor(); + } } this._cacheScale9Sprite(); } diff --git a/extensions/gui/control-extension/CCScale9SpriteCanvasRenderCmd.js b/extensions/gui/control-extension/CCScale9SpriteCanvasRenderCmd.js index f0acc0bb7a..73a6514003 100644 --- a/extensions/gui/control-extension/CCScale9SpriteCanvasRenderCmd.js +++ b/extensions/gui/control-extension/CCScale9SpriteCanvasRenderCmd.js @@ -85,8 +85,10 @@ var scaleChildren = scale9Image.getChildren(); for (var i = 0; i < scaleChildren.length; i++) { var selChild = scaleChildren[i]; - if (selChild) + if (selChild){ selChild._renderCmd._updateDisplayColor(parentColor); + selChild._renderCmd._updateColor(); + } } this._cacheScale9Sprite(); } From e611228d8ca4e803e4dbe50127635df4fafc4d87 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 20 Mar 2015 17:39:50 +0800 Subject: [PATCH 0079/1039] Fixed a bug that layoutComponent is undefined --- extensions/cocostudio/loader/parsers/timelineParser-2.x.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 56b0d7c008..d11e2ff293 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -296,6 +296,8 @@ widget.setColor(getColor(color)); var layoutComponent = ccui.LayoutComponent.bindLayoutComponent(widget); + if(!layoutComponent) + return; var positionXPercentEnabled = json["PositionPercentXEnable"] || false; var positionYPercentEnabled = json["PositionPercentYEnable"] || false; From 79cf83c4587b28495c3149506f62a29262a8e7ab Mon Sep 17 00:00:00 2001 From: igogo Date: Fri, 20 Mar 2015 11:54:51 +0200 Subject: [PATCH 0080/1039] Readme changed for support installing and testing in different versions --- README.mdown | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/README.mdown b/README.mdown index 5e3bc6adcd..82d051efba 100644 --- a/README.mdown +++ b/README.mdown @@ -16,7 +16,15 @@ Documentation * Website: [www.cocos2d-x.org][3] * API References: [http://www.cocos2d-x.org/wiki/Reference] [4] -Running the tests + +Installing from [bower.io][5] (version >=3.4) +------------------ + +```shell +$ bower install cocos2d-html5 + + +Running the tests (version <3) ------------------ ```shell @@ -30,9 +38,9 @@ $ python -m SimpleHTTPServer Contact us ------------------ - * Forum: [http://forum.cocos2d-x.org][5] - * Twitter: [http://www.twitter.com/cocos2dhtml5][6] - * Sina Microblog: [http://t.sina.com.cn/cocos2dhtml5][7] + * Forum: [http://forum.cocos2d-x.org][6] + * Twitter: [http://www.twitter.com/cocos2dhtml5][7] + * Sina Microblog: [http://t.sina.com.cn/cocos2dhtml5][8] [1]: http://www.cocos2d-x.org "Cocos2d-html5" [2]: http://www.cocos2d-x.org "Cocos2d-X" From c62e73d2fd1c719b1316b1942b79dd58b5cd6225 Mon Sep 17 00:00:00 2001 From: igogo Date: Fri, 20 Mar 2015 12:25:37 +0200 Subject: [PATCH 0081/1039] Readme changed for support installing and testing in different versions --- README.mdown | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/README.mdown b/README.mdown index 82d051efba..9c6ce013e6 100644 --- a/README.mdown +++ b/README.mdown @@ -17,12 +17,12 @@ Documentation * API References: [http://www.cocos2d-x.org/wiki/Reference] [4] -Installing from [bower.io][5] (version >=3.4) +Installing from [bower][8] (version >=3.4) ------------------ ```shell $ bower install cocos2d-html5 - +``` Running the tests (version <3) ------------------ @@ -38,9 +38,9 @@ $ python -m SimpleHTTPServer Contact us ------------------ - * Forum: [http://forum.cocos2d-x.org][6] - * Twitter: [http://www.twitter.com/cocos2dhtml5][7] - * Sina Microblog: [http://t.sina.com.cn/cocos2dhtml5][8] + * Forum: [http://forum.cocos2d-x.org][5] + * Twitter: [http://www.twitter.com/cocos2dhtml5][6] + * Sina Microblog: [http://t.sina.com.cn/cocos2dhtml5][7] [1]: http://www.cocos2d-x.org "Cocos2d-html5" [2]: http://www.cocos2d-x.org "Cocos2d-X" @@ -49,3 +49,4 @@ Contact us [5]: http://forum.cocos2d-x.org "http://forum.cocos2d-x.org" [6]: http://www.twitter.com/cocos2dhtml5 "http://www.twitter.com/cocos2dhtml5" [7]: http://t.sina.com.cn/cocos2dhtml5 "http://t.sina.com.cn/cocos2dhtml5" +[8]: http://bower.io "http://bower.io" \ No newline at end of file From 8f2bb416787ded9992df1a144417de1ca816df52 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Fri, 20 Mar 2015 18:34:43 +0800 Subject: [PATCH 0082/1039] Fixed #1571: Fixed a bug of cc.MenuItemSprite that it doesn't work when parameter `selectedSprite` is a Scale9Sprite instance. --- cocos2d/menus/CCMenuItem.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/cocos2d/menus/CCMenuItem.js b/cocos2d/menus/CCMenuItem.js index 06c85bb05e..b083fca0bf 100644 --- a/cocos2d/menus/CCMenuItem.js +++ b/cocos2d/menus/CCMenuItem.js @@ -725,8 +725,8 @@ cc.MenuItemSprite = cc.MenuItem.extend(/** @lends cc.MenuItemSprite# */{ this._disabledImage = null; if (selectedSprite !== undefined) { - normalSprite = normalSprite; - selectedSprite = selectedSprite; + //normalSprite = normalSprite; + //selectedSprite = selectedSprite; var disabledImage, target, callback; //when you send 4 arguments, five is undefined if (five !== undefined) { @@ -739,9 +739,9 @@ cc.MenuItemSprite = cc.MenuItem.extend(/** @lends cc.MenuItemSprite# */{ } else if (four !== undefined && cc.isFunction(three)) { target = four; callback = three; - disabledImage = new cc.Sprite(selectedSprite.getTexture(), selectedSprite.getTextureRect()); + disabledImage = null; } else if (three === undefined) { - disabledImage = new cc.Sprite(selectedSprite.getTexture(), selectedSprite.getTextureRect()); + disabledImage = null; } this.initWithNormalSprite(normalSprite, selectedSprite, disabledImage, callback, target); } From 2905045cd4f85b04e99da05f5f23b9570febdf06 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 23 Mar 2015 11:39:13 +0800 Subject: [PATCH 0083/1039] Fixed bug that is Scale9sprite cap error when no pre loading picture --- extensions/ccui/base-classes/UIScale9Sprite.js | 9 +++++++++ extensions/gui/control-extension/CCScale9Sprite.js | 9 +++++++++ 2 files changed, 18 insertions(+) diff --git a/extensions/ccui/base-classes/UIScale9Sprite.js b/extensions/ccui/base-classes/UIScale9Sprite.js index 813ceae5c1..6b0aa9c917 100644 --- a/extensions/ccui/base-classes/UIScale9Sprite.js +++ b/extensions/ccui/base-classes/UIScale9Sprite.js @@ -466,6 +466,10 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ this._textureLoaded = locLoaded; if(!locLoaded){ texture.addEventListener("load", function(sender){ + if(this._capInsets.width === 0 && this._capInsets.height === 0){ + this._capInsets.width = sender._contentSize.width; + this._capInsets.height = sender._contentSize.height; + } // the texture is rotated on Canvas render mode, so isRotated always is false. var preferredSize = this._preferredSize; preferredSize = cc.size(preferredSize.width, preferredSize.height); @@ -475,6 +479,11 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ this._positionsAreDirty = true; this.dispatchEvent("load"); }, this); + }else{ + if(this._capInsets.width === 0 && this._capInsets.height === 0){ + capInsets.width = texture._contentSize.width; + capInsets.height = texture._contentSize.height; + } } return this.initWithBatchNode(new cc.SpriteBatchNode(file, 9), rect, false, capInsets); diff --git a/extensions/gui/control-extension/CCScale9Sprite.js b/extensions/gui/control-extension/CCScale9Sprite.js index abe7056ef7..063f4bed33 100644 --- a/extensions/gui/control-extension/CCScale9Sprite.js +++ b/extensions/gui/control-extension/CCScale9Sprite.js @@ -461,6 +461,10 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ this._textureLoaded = locLoaded; if(!locLoaded){ texture.addEventListener("load", function(sender){ + if(this._capInsets.width === 0 && this._capInsets.height === 0){ + this._capInsets.width = sender._contentSize.width; + this._capInsets.height = sender._contentSize.height; + } // the texture is rotated on Canvas render mode, so isRotated always is false. var preferredSize = this._preferredSize; preferredSize = cc.size(preferredSize.width, preferredSize.height); @@ -470,6 +474,11 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ this._positionsAreDirty = true; this.dispatchEvent("load"); }, this); + }else{ + if(this._capInsets.width === 0 && this._capInsets.height === 0){ + capInsets.width = texture._contentSize.width; + capInsets.height = texture._contentSize.height; + } } return this.initWithBatchNode(new cc.SpriteBatchNode(file, 9), rect, false, capInsets); From a5db17ec0d41044c14fdd0d9f9df8e458f99d72a Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 23 Mar 2015 14:14:26 +0800 Subject: [PATCH 0084/1039] Fixed #2753: Background color of panel from cocos studio 2 doesnt work --- .../loader/parsers/timelineParser-2.x.js | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index d11e2ff293..fb9f0fd7ec 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -422,15 +422,12 @@ } - var bgStartColor = json["FirstColor"]; - var bgEndColor = json["EndColor"]; - if(bgStartColor != null && bgEndColor != null){ - var startC = getColor(bgStartColor); - if(bgEndColor["R"] == null && bgEndColor["G"] == null && bgEndColor["B"] == null) - widget.setBackGroundColor( startC ); - else - widget.setBackGroundColor( startC, getColor(bgEndColor) ); - } + var firstColor = json["FirstColor"]; + var endColor = json["EndColor"]; + if(endColor["R"] != null && endColor["G"] != null && endColor["B"] != null) + widget.setBackGroundColor(getColor(firstColor), getColor(endColor)); + else + widget.setBackGroundColor(getColor(json["SingleColor"])); var colorVector = json["ColorVector"]; if(colorVector != null) From 192339af3e96b492291014d5646c39a11530ac11 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 23 Mar 2015 16:18:40 +0800 Subject: [PATCH 0085/1039] Fixed punchbox #16651 --- .../loader/parsers/timelineParser-2.x.js | 25 +++++++++---------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index fb9f0fd7ec..89350c2cba 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -645,6 +645,10 @@ this.widgetAttributes(widget, json); + loadTexture(json["FileData"], resourcePath, function(path, type){ + widget.setBackGroundImage(path, type); + }); + var clipEnabled = json["ClipAble"]; widget.setClippingEnabled(clipEnabled); @@ -691,10 +695,6 @@ widget.setBackGroundColorVector(cc.p(colorVectorX, colorVectorY)); } - loadTexture(json["FileData"], resourcePath, function(path, type){ - widget.setBackGroundImage(path, type); - }); - var innerNodeSize = json["InnerNodeSize"]; var innerSize = cc.size( innerNodeSize["Width"] || 0, @@ -829,6 +829,10 @@ this.widgetAttributes(widget, json); + loadTexture(json["FileData"], resourcePath, function(path, type){ + widget.setBackGroundImage(path, type); + }); + var clipEnabled = json["ClipAble"] || false; widget.setClippingEnabled(clipEnabled); @@ -869,10 +873,6 @@ if(bgColorOpacity != null) widget.setBackGroundColorOpacity(bgColorOpacity); - loadTexture(json["FileData"], resourcePath, function(path, type){ - widget.setBackGroundImage(path, type); - }); - setContentSize(widget, json["Size"]); return widget; @@ -891,6 +891,10 @@ this.widgetAttributes(widget, json); + loadTexture(json["FileData"], resourcePath, function(path, type){ + widget.setBackGroundImage(path, type); + }); + var clipEnabled = json["ClipAble"] || false; widget.setClippingEnabled(clipEnabled); @@ -964,11 +968,6 @@ if(bgColorOpacity != null) widget.setBackGroundColorOpacity(bgColorOpacity); - - loadTexture(json["FileData"], resourcePath, function(path, type){ - widget.setBackGroundImage(path, type); - }); - setContentSize(widget, json["Size"]); return widget; From 7672694bcbae9d0af199039b2e74e227e851d2c8 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Tue, 24 Mar 2015 10:20:36 +0800 Subject: [PATCH 0086/1039] Issue #2698: corrected a mistake of cc.math.Matrix in constructor. --- .../CCClippingNodeWebGLRenderCmd.js | 32 +++++++++++++------ cocos2d/kazmath/gl/mat4stack.js | 18 +++++++++++ cocos2d/kazmath/mat3.js | 8 ++--- cocos2d/kazmath/mat4.js | 7 ++-- 4 files changed, 45 insertions(+), 20 deletions(-) diff --git a/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js b/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js index 283df8fc46..0e199ff3b7 100644 --- a/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js +++ b/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js @@ -144,17 +144,29 @@ proto._drawFullScreenQuadClearStencil = function () { // draw a fullscreen solid rectangle to clear the stencil buffer - cc.kmGLMatrixMode(cc.KM_GL_PROJECTION); - cc.kmGLPushMatrix(); - cc.kmGLLoadIdentity(); - cc.kmGLMatrixMode(cc.KM_GL_MODELVIEW); - cc.kmGLPushMatrix(); - cc.kmGLLoadIdentity(); + var projStack = cc.projection_matrix_stack; + //cc.kmGLMatrixMode(cc.KM_GL_PROJECTION); + //cc.kmGLPushMatrix(); + //cc.kmGLLoadIdentity(); + projStack.push(); + projStack.top.identity(); + + //cc.kmGLMatrixMode(cc.KM_GL_MODELVIEW); + //cc.kmGLPushMatrix(); + //cc.kmGLLoadIdentity(); + var modelViewStack = cc.modelview_matrix_stack; + modelViewStack.push(); + modelViewStack.top.identity(); + cc._drawingUtil.drawSolidRect(cc.p(-1, -1), cc.p(1, 1), cc.color(255, 255, 255, 255)); - cc.kmGLMatrixMode(cc.KM_GL_PROJECTION); - cc.kmGLPopMatrix(); - cc.kmGLMatrixMode(cc.KM_GL_MODELVIEW); - cc.kmGLPopMatrix(); + + //cc.kmGLMatrixMode(cc.KM_GL_PROJECTION); + //cc.kmGLPopMatrix(); + projStack.pop(); + + //cc.kmGLMatrixMode(cc.KM_GL_MODELVIEW); + //cc.kmGLPopMatrix(); + modelViewStack.pop(); }; proto._onBeforeVisit = function(ctx){ diff --git a/cocos2d/kazmath/gl/mat4stack.js b/cocos2d/kazmath/gl/mat4stack.js index b11fd6b1cf..ecd3aceba3 100644 --- a/cocos2d/kazmath/gl/mat4stack.js +++ b/cocos2d/kazmath/gl/mat4stack.js @@ -36,6 +36,7 @@ cc.math.Matrix4Stack = function(top, stack) { this.top = top; this.stack = stack || []; + //this._matrixPool = []; // use pool in next version }; cc.km_mat4_stack = cc.math.Matrix4Stack; var proto = cc.math.Matrix4Stack.prototype; @@ -61,17 +62,34 @@ }; proto.push = function(item) { + item = item || this.top; this.stack.push(this.top); this.top = new cc.math.Matrix4(item); + //this.top = this._getFromPool(item); }; proto.pop = function() { + //this._putInPool(this.top); this.top = this.stack.pop(); }; proto.release = function(){ this.stack = null; this.top = null; + this._matrixPool = null; + }; + + proto._getFromPool = function (item) { + var pool = this._matrixPool; + if (pool.length === 0) + return new cc.math.Matrix4(item); + var ret = pool.pop(); + ret.assignFrom(item); + return ret; + }; + + proto._putInPool = function(matrix){ + this._matrixPool.push(matrix); }; })(cc); diff --git a/cocos2d/kazmath/mat3.js b/cocos2d/kazmath/mat3.js index 737bc9b77f..05cdbe1417 100644 --- a/cocos2d/kazmath/mat3.js +++ b/cocos2d/kazmath/mat3.js @@ -29,12 +29,10 @@ var Float32Array = Float32Array || Array; (function(cc){ cc.math.Matrix3 = function(mat3) { - if (mat3) { - this.mat = new Float32Array(mat3); + if (mat3 && mat3.mat) { + this.mat = new Float32Array(mat3.mat); } else { - this.mat = new Float32Array([0, 0, 0, - 0, 0, 0, - 0, 0, 0]); + this.mat = new Float32Array(9); } }; cc.kmMat3 = cc.math.Matrix3; diff --git a/cocos2d/kazmath/mat4.js b/cocos2d/kazmath/mat4.js index 33882b7a98..b1af75efc3 100644 --- a/cocos2d/kazmath/mat4.js +++ b/cocos2d/kazmath/mat4.js @@ -40,13 +40,10 @@ * @param {cc.math.Matrix4} [mat4] */ cc.math.Matrix4 = function (mat4) { - if(mat4){ + if(mat4 && mat4.mat){ this.mat = new Float32Array(mat4.mat); } else { - this.mat = new Float32Array([0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0]); + this.mat = new Float32Array(16); } }; cc.kmMat4 = cc.math.Matrix4; From 687f4436cb2d275152c57c74aba04c3ba20cae43 Mon Sep 17 00:00:00 2001 From: SijieWang Date: Tue, 24 Mar 2015 14:17:25 +0800 Subject: [PATCH 0087/1039] Revert "Fixed bug that is Scale9sprite cap error when no pre loading picture" --- extensions/ccui/base-classes/UIScale9Sprite.js | 9 --------- extensions/gui/control-extension/CCScale9Sprite.js | 9 --------- 2 files changed, 18 deletions(-) diff --git a/extensions/ccui/base-classes/UIScale9Sprite.js b/extensions/ccui/base-classes/UIScale9Sprite.js index 6b0aa9c917..813ceae5c1 100644 --- a/extensions/ccui/base-classes/UIScale9Sprite.js +++ b/extensions/ccui/base-classes/UIScale9Sprite.js @@ -466,10 +466,6 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ this._textureLoaded = locLoaded; if(!locLoaded){ texture.addEventListener("load", function(sender){ - if(this._capInsets.width === 0 && this._capInsets.height === 0){ - this._capInsets.width = sender._contentSize.width; - this._capInsets.height = sender._contentSize.height; - } // the texture is rotated on Canvas render mode, so isRotated always is false. var preferredSize = this._preferredSize; preferredSize = cc.size(preferredSize.width, preferredSize.height); @@ -479,11 +475,6 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ this._positionsAreDirty = true; this.dispatchEvent("load"); }, this); - }else{ - if(this._capInsets.width === 0 && this._capInsets.height === 0){ - capInsets.width = texture._contentSize.width; - capInsets.height = texture._contentSize.height; - } } return this.initWithBatchNode(new cc.SpriteBatchNode(file, 9), rect, false, capInsets); diff --git a/extensions/gui/control-extension/CCScale9Sprite.js b/extensions/gui/control-extension/CCScale9Sprite.js index 063f4bed33..abe7056ef7 100644 --- a/extensions/gui/control-extension/CCScale9Sprite.js +++ b/extensions/gui/control-extension/CCScale9Sprite.js @@ -461,10 +461,6 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ this._textureLoaded = locLoaded; if(!locLoaded){ texture.addEventListener("load", function(sender){ - if(this._capInsets.width === 0 && this._capInsets.height === 0){ - this._capInsets.width = sender._contentSize.width; - this._capInsets.height = sender._contentSize.height; - } // the texture is rotated on Canvas render mode, so isRotated always is false. var preferredSize = this._preferredSize; preferredSize = cc.size(preferredSize.width, preferredSize.height); @@ -474,11 +470,6 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ this._positionsAreDirty = true; this.dispatchEvent("load"); }, this); - }else{ - if(this._capInsets.width === 0 && this._capInsets.height === 0){ - capInsets.width = texture._contentSize.width; - capInsets.height = texture._contentSize.height; - } } return this.initWithBatchNode(new cc.SpriteBatchNode(file, 9), rect, false, capInsets); From aec8545deb99d7a66ce78ce9e173aee0ab552b8f Mon Sep 17 00:00:00 2001 From: Juan Carlos Date: Tue, 24 Mar 2015 18:09:00 -0500 Subject: [PATCH 0088/1039] Audio DOM loader Improved audio loader that seems to work way better when using DOM audio. --- cocos2d/audio/CCAudio.js | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index e59d580ffc..f03a888f92 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -574,12 +574,18 @@ cc.Audio = cc.Class.extend({ emptied(); }else{ termination = true; + element.pause(); + document.body.removeChild(element); cb("audio load timeout : " + realUrl, audio); } }, 10000); var success = function(){ if(!cbCheck){ + element.pause(); + try { element.currentTime = 0; + element.volume = 1; } catch (e) {} + document.body.removeChild(element); audio.setElement(element); element.removeEventListener("canplaythrough", success, false); element.removeEventListener("error", failure, false); @@ -592,6 +598,8 @@ cc.Audio = cc.Class.extend({ var failure = function(){ if(!cbCheck) return; + element.pause(); + document.body.removeChild(element); element.removeEventListener("canplaythrough", success, false); element.removeEventListener("error", failure, false); element.removeEventListener("emptied", emptied, false); @@ -612,7 +620,9 @@ cc.Audio = cc.Class.extend({ cc._addEventListener(element, "emptied", emptied, false); element.src = realUrl; - element.load(); + document.body.appendChild(element); + element.volume = 0; + element.play(); } } From 536d07a0019097d048d728a1eebbd8d5472e761d Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Wed, 25 Mar 2015 14:32:58 +0800 Subject: [PATCH 0089/1039] Issue #2760: update some spine skeleton APIs, but it doesn't support Mesh. --- extensions/spine/CCSkeleton.js | 50 ++++++-- extensions/spine/CCSkeletonAnimation.js | 124 ++++++++++++++++++- extensions/spine/CCSkeletonWebGLRenderCmd.js | 13 +- extensions/spine/Spine.js | 93 +++++++------- 4 files changed, 216 insertions(+), 64 deletions(-) diff --git a/extensions/spine/CCSkeleton.js b/extensions/spine/CCSkeleton.js index 2a3816a75a..a3c7b402b4 100644 --- a/extensions/spine/CCSkeleton.js +++ b/extensions/spine/CCSkeleton.js @@ -48,15 +48,15 @@ sp.VERTEX_INDEX = { }; /** - * The attachment type of spine. It contains three type: REGION(0), BOUNDING_BOX(1), REGION_SEQUENCE(2) and MESH(2). + * The attachment type of spine. It contains three type: REGION(0), BOUNDING_BOX(1), MESH(2) and SKINNED_MESH. * @constant * @type {{REGION: number, BOUNDING_BOX: number, REGION_SEQUENCE: number, MESH: number}} */ sp.ATTACHMENT_TYPE = { REGION: 0, BOUNDING_BOX: 1, - REGION_SEQUENCE: 2, - MESH: 2 + MESH: 2, + SKINNED_MESH:3 }; /** @@ -112,7 +112,7 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ }, /** - * Sets whether open debug solots. + * Sets whether open debug slots. * @param {boolean} enable true to open, false to close. */ setDebugSolots:function(enable){ @@ -127,12 +127,48 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ this._debugBones = enable; }, + /** + * Sets whether open debug slots. + * @param {boolean} enabled true to open, false to close. + */ + setDebugSlotsEnabled: function(enabled) { + this._debugSlots = enabled; + }, + + /** + * Gets whether open debug slots. + * @returns {boolean} true to open, false to close. + */ + getDebugSlotsEnabled: function() { + return this._debugSlots; + }, + + /** + * Sets whether open debug bones. + * @param {boolean} enabled + */ + setDebugBonesEnabled: function(enabled) { + this._debugBones = enabled; + }, + + /** + * Gets whether open debug bones. + * @returns {boolean} true to open, false to close. + */ + getDebugBonesEnabled: function() { + return this._debugBones; + }, + /** * Sets the time scale of sp.Skeleton. - * @param {Number} v + * @param {Number} scale */ - setTimeScale:function(v){ - this._timeScale = v; + setTimeScale:function(scale){ + this._timeScale = scale; + }, + + getTimeScale: function(){ + return this._timeScale; }, /** diff --git a/extensions/spine/CCSkeletonAnimation.js b/extensions/spine/CCSkeletonAnimation.js index bb00ba2da5..0d1e392a34 100644 --- a/extensions/spine/CCSkeletonAnimation.js +++ b/extensions/spine/CCSkeletonAnimation.js @@ -119,7 +119,7 @@ sp._regionAttachment_updateQuad = function(self, slot, quad, premultipliedAlpha) sp._meshAttachment_updateQuad = function(self, slot, quad, premultipliedAlpha) { var vertices = {}; - self.computeVertices(slot.bone.x, slot.bone.y, slot.bone, vertices); + self.computeWorldVertices(slot.bone.x, slot.bone.y, slot, vertices); var r = slot.bone.skeleton.r * slot.r * 255; var g = slot.bone.skeleton.g * slot.g * 255; var b = slot.bone.skeleton.b * slot.b * 255; @@ -182,6 +182,25 @@ sp.ANIMATION_EVENT_TYPE = { EVENT: 3 }; +sp.TrackEntryListeners = function(startListener, endListener, completeListener, eventListener){ + this.startListener = startListener || null; + this.endListener = endListener || null; + this.completeListener = completeListener || null; + this.eventListener = eventListener || null; +}; + +sp.TrackEntryListeners.getListeners = function(entry){ + if(!entry.rendererObject){ + entry.rendererObject = new sp.TrackEntryListeners(); + entry.listener = sp.trackEntryCallback; + } + return entry.rendererObject; +}; + +sp.trackEntryCallback = function(state, trackIndex, type, event, loopCount) { + state.rendererObject.onTrackEntryEvent(trackIndex, type, event, loopCount); +}; + /** * The skeleton animation of spine. It updates animation's state and skeleton's world transform. * @class @@ -195,12 +214,19 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ _target: null, _callback: null, + _ownsAnimationStateData: false, + _startListener: null, + _endListener: null, + _completeListener: null, + _eventListener: null, + /** * Initializes a sp.SkeletonAnimation. please do not call this function by yourself, you should pass the parameters to constructor to initialize it. * @override */ init: function () { sp.Skeleton.prototype.init.call(this); + this._ownsAnimationStateData = true; this.setAnimationStateData(new spine.AnimationStateData(this._skeleton.data)); }, @@ -210,6 +236,7 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ */ setAnimationStateData: function (stateData) { var state = new spine.AnimationState(stateData); + state.rendererObject = this; state.onStart = this._onAnimationStateStart.bind(this); state.onComplete = this._onAnimationStateComplete.bind(this); state.onEnd = this._onAnimationStateEnd.bind(this); @@ -258,10 +285,11 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ * @param {Number} trackIndex * @param {String} name * @param {Boolean} loop - * @param {Number} delay + * @param {Number} [delay=0] * @returns {spine.TrackEntry|null} */ addAnimation: function (trackIndex, name, loop, delay) { + delay = delay == null ? 0 : delay; var animation = this._skeleton.data.findAnimation(name); if (!animation) { cc.log("Spine: Animation not found:" + name); @@ -302,13 +330,102 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ */ update: function (dt) { this._super(dt); - dt *= this._timeScale; this._state.update(dt); this._state.apply(this._skeleton); this._skeleton.updateWorldTransform(); }, + /** + * Set the start event listener. + * @param {function} listener + */ + setStartListener: function(listener){ + this._startListener = listener; + }, + + /** + * Set the end event listener. + * @param {function} listener + */ + setEndListener: function(listener) { + this._endListener = listener; + }, + + setCompleteListener: function(listener) { + this._completeListener = listener; + }, + + setEventListener: function(listener){ + this._eventListener = listener; + }, + + setTrackStartListener: function(entry, listener){ + sp.TrackEntryListeners.getListeners(entry).startListener = listener; + }, + + setTrackEndListener: function(entry, listener){ + sp.TrackEntryListeners.getListeners(entry).endListener = listener; + }, + + setTrackCompleteListener: function(entry, listener){ + sp.TrackEntryListeners.getListeners(entry).completeListener = listener; + }, + + setTrackEventListener: function(entry, listener){ + sp.TrackEntryListeners.getListeners(entry).eventListener = listener; + }, + + onTrackEntryEvent: function(traceIndex, type, event, loopCount){ + var entry = this._state.getCurrent(traceIndex); + if(!entry.rendererObject) + return; + var listeners = entry.rendererObject; + switch (type){ + case sp.ANIMATION_EVENT_TYPE.START: + if(listeners.startListener) + listeners.startListener(traceIndex); + break; + case sp.ANIMATION_EVENT_TYPE.END: + if(listeners.endListener) + listeners.endListener(traceIndex); + break; + case sp.ANIMATION_EVENT_TYPE.COMPLETE: + if(listeners.completeListener) + listeners.completeListener(traceIndex, loopCount); + break; + case sp.ANIMATION_EVENT_TYPE.EVENT: + if(listeners.eventListener) + listeners.eventListener(traceIndex, event); + break; + } + }, + + onAnimationStateEvent: function(trackIndex, type, event, loopCount) { + switch(type){ + case sp.ANIMATION_EVENT_TYPE.START: + if(this._startListener) + this._startListener(trackIndex); + break; + case sp.ANIMATION_EVENT_TYPE.END: + if(this._endListener) + this._endListener(trackIndex); + break; + case sp.ANIMATION_EVENT_TYPE.COMPLETE: + if(this._completeListener) + this._completeListener(trackIndex, loopCount); + break; + case sp.ANIMATION_EVENT_TYPE.EVENT: + if(this._eventListener) + this._eventListener(trackIndex, event); + break; + } + }, + + getState: function(){ + return this._state; + }, + _onAnimationStateStart: function (trackIndex) { this._animationStateCallback(trackIndex, sp.ANIMATION_EVENT_TYPE.START, null, 0); }, @@ -322,6 +439,7 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ this._animationStateCallback(trackIndex, sp.ANIMATION_EVENT_TYPE.EVENT, event, 0); }, _animationStateCallback: function (trackIndex, type, event, loopCount) { + this.onAnimationStateEvent(trackIndex, type, event, loopCount); if (this._target && this._callback) { this._callback.call(this._target, this, trackIndex, type, event, loopCount) } diff --git a/extensions/spine/CCSkeletonWebGLRenderCmd.js b/extensions/spine/CCSkeletonWebGLRenderCmd.js index 9b78bbd0eb..83c6aa93da 100644 --- a/extensions/spine/CCSkeletonWebGLRenderCmd.js +++ b/extensions/spine/CCSkeletonWebGLRenderCmd.js @@ -82,11 +82,13 @@ switch(slot.attachment.type) { case sp.ATTACHMENT_TYPE.REGION: - sp._regionAttachment_updateQuad(attachment, slot, quad, node._premultipliedAlpha); - break; + sp._regionAttachment_updateQuad(attachment, slot, quad, node._premultipliedAlpha); + break; case sp.ATTACHMENT_TYPE.MESH: - sp._meshAttachment_updateQuad(attachment, slot, quad, node._premultipliedAlpha); - break; + sp._meshAttachment_updateQuad(attachment, slot, quad, node._premultipliedAlpha); + break; + case sp.ATTACHMENT_TYPE.SKINNED_MESH: + break; } textureAtlas.updateQuad(quad, quadCount); @@ -98,9 +100,8 @@ } if (node._debugBones || node._debugSlots) { - cc.kmGLMatrixMode(cc.KM_GL_MODELVIEW); - //cc.kmGLPushMatrixWitMat4(node._stackMatrix); + //cc.kmGLPushMatrixWitMat4(this._stackMatrix); cc.current_stack.stack.push(cc.current_stack.top); cc.current_stack.top = this._stackMatrix; diff --git a/extensions/spine/Spine.js b/extensions/spine/Spine.js index d76f2c3dac..e29bca57d0 100644 --- a/extensions/spine/Spine.js +++ b/extensions/spine/Spine.js @@ -31,7 +31,9 @@ var spine = { radDeg: 180 / Math.PI, degRad: Math.PI / 180, - temp: [] + temp: [], + Float32Array: (typeof(Float32Array) === 'undefined') ? Array : Float32Array, + Uint16Array: (typeof(Uint16Array) === 'undefined') ? Array : Uint16Array }; spine.BoneData = function (name, parent) { @@ -147,8 +149,8 @@ spine.Bone.prototype = { m11 = -m11; } var invDet = 1 / (m00 * m11 - m01 * m10); - world[0] = (dx * m00 * invDet - dy * m01 * invDet); - world[1] = (dy * m11 * invDet - dx * m10 * invDet); + world[0] = dx * m00 * invDet - dy * m01 * invDet; + world[1] = dy * m11 * invDet - dx * m10 * invDet; }, localToWorld: function (local) { var localX = local[0], localY = local[1]; @@ -224,7 +226,9 @@ spine.IkConstraint.prototype = { spine.IkConstraint.apply1 = function (bone, targetX, targetY, alpha) { var parentRotation = (!bone.data.inheritRotation || !bone.parent) ? 0 : bone.parent.worldRotation; var rotation = bone.rotation; - var rotationIK = Math.atan2(targetY - bone.worldY, targetX - bone.worldX) * spine.radDeg - parentRotation; + var rotationIK = Math.atan2(targetY - bone.worldY, targetX - bone.worldX) * spine.radDeg; + if (bone.worldFlipX != (bone.worldFlipY != spine.Bone.yDown)) rotationIK = -rotationIK; + rotationIK -= parentRotation; bone.rotationIK = rotation + (rotationIK - rotation) * alpha; }; /** Adjusts the parent and child bone rotations so the tip of the child is as close to the target position as possible. The @@ -770,14 +774,11 @@ spine.FfdTimeline.prototype = { this.frameVertices[frameIndex] = vertices; }, apply: function (skeleton, lastTime, time, firedEvents, alpha) { - var slot = skeleton.slots[slotIndex]; - if (slot.attachment != attachment) return; + var slot = skeleton.slots[this.slotIndex]; + if (slot.attachment != this.attachment) return; var frames = this.frames; - if (time < frames[0]) { - slot.attachmentVertices.length = 0; - return; // Time is before first frame. - } + if (time < frames[0]) return; // Time is before first frame. var frameVertices = this.frameVertices; var vertexCount = frameVertices[0].length; @@ -1142,9 +1143,9 @@ spine.Skeleton.prototype = { if (!skin) throw "Skin not found: " + skinName; this.setSkin(skin); }, - /** Sets the skin used to look up attachments not found in the {@link SkeletonData#getDefaultSkin() default skin}. Attachments - * from the new skin are attached if the corresponding attachment from the old skin was attached. If there was no old skin, - * each slot's setup mode attachment is attached from the new skin. + /** Sets the skin used to look up attachments before looking in the {@link SkeletonData#getDefaultSkin() default skin}. + * Attachments from the new skin are attached if the corresponding attachment from the old skin was attached. If there was + * no old skin, each slot's setup mode attachment is attached from the new skin. * @param newSkin May be null. */ setSkin: function (newSkin) { if (newSkin) { @@ -1336,21 +1337,20 @@ spine.MeshAttachment.prototype = { edges: null, width: 0, height: 0, updateUVs: function () { - var width = regionU2 - regionU, height = regionV2 - regionV; - var n = regionUVs.length; - if (!uvs || uvs.length != n) { - uvs = []; - uvs.length = n; + var width = this.regionU2 - this.regionU, height = this.regionV2 - this.regionV; + var n = this.regionUVs.length; + if (!this.uvs || this.uvs.length != n) { + this.uvs = new spine.Float32Array(n); } - if (regionRotate) { + if (this.regionRotate) { for (var i = 0; i < n; i += 2) { - uvs[i] = regionU + regionUVs[i + 1] * width; - uvs[i + 1] = regionV + height - regionUVs[i] * height; + this.uvs[i] = this.regionU + this.regionUVs[i + 1] * width; + this.uvs[i + 1] = this.regionV + height - this.regionUVs[i] * height; } } else { for (var i = 0; i < n; i += 2) { - uvs[i] = regionU + regionUVs[i] * width; - uvs[i + 1] = regionV + regionUVs[i + 1] * height; + this.uvs[i] = this.regionU + this.regionUVs[i] * width; + this.uvs[i + 1] = this.regionV + this.regionUVs[i + 1] * height; } } }, @@ -1392,21 +1392,20 @@ spine.SkinnedMeshAttachment.prototype = { edges: null, width: 0, height: 0, updateUVs: function (u, v, u2, v2, rotate) { - var width = regionU2 - regionU, height = regionV2 - regionV; - var n = regionUVs.length; - if (!uvs || uvs.length != n) { - uvs = []; - uvs.length = n; + var width = this.regionU2 - this.regionU, height = this.regionV2 - this.regionV; + var n = this.regionUVs.length; + if (!this.uvs || this.uvs.length != n) { + this.uvs = new spine.Float32Array(n); } - if (regionRotate) { + if (this.regionRotate) { for (var i = 0; i < n; i += 2) { - uvs[i] = regionU + regionUVs[i + 1] * width; - uvs[i + 1] = regionV + height - regionUVs[i] * height; + this.uvs[i] = this.regionU + this.regionUVs[i + 1] * width; + this.uvs[i + 1] = this.regionV + height - this.regionUVs[i] * height; } } else { for (var i = 0; i < n; i += 2) { - uvs[i] = regionU + regionUVs[i] * width; - uvs[i + 1] = regionV + regionUVs[i + 1] * height; + this.uvs[i] = this.regionU + this.regionUVs[i] * width; + this.uvs[i + 1] = this.regionV + this.regionUVs[i + 1] * height; } } }, @@ -1824,8 +1823,8 @@ spine.SkeletonJson.prototype = { var region = this.attachmentLoader.newRegionAttachment(skin, name, path); if (!region) return null; region.path = path; - region.x = (map["x"] || 0) * this.scale; - region.y = (map["y"] || 0) * this.scale; + region.x = (map["x"] || 0) * scale; + region.y = (map["y"] || 0) * scale; region.scaleX = map.hasOwnProperty("scaleX") ? map["scaleX"] : 1; region.scaleY = map.hasOwnProperty("scaleY") ? map["scaleY"] : 1; region.rotation = map["rotation"] || 0; @@ -1870,7 +1869,7 @@ spine.SkeletonJson.prototype = { mesh.path = path; var uvs = this.getFloatArray(map, "uvs", 1); - vertices = this.getFloatArray(map, "vertices", 1); + var vertices = this.getFloatArray(map, "vertices", 1); var weights = []; var bones = []; for (var i = 0, n = vertices.length; i < n; ) { @@ -1907,7 +1906,7 @@ spine.SkeletonJson.prototype = { var attachment = this.attachmentLoader.newBoundingBoxAttachment(skin, name); var vertices = map["vertices"]; for (var i = 0, n = vertices.length; i < n; i++) - attachment.vertices.push(vertices[i] * this.scale); + attachment.vertices.push(vertices[i] * scale); return attachment; } throw "Unknown attachment type: " + type; @@ -2086,16 +2085,16 @@ spine.SkeletonJson.prototype = { vertices.length = vertexCount; var start = valueMap["offset"] || 0; var nn = verticesValue.length; - if (scale == 1) { + if (this.scale == 1) { for (var ii = 0; ii < nn; ii++) vertices[ii + start] = verticesValue[ii]; } else { for (var ii = 0; ii < nn; ii++) - vertices[ii + start] = verticesValue[ii] * scale; + vertices[ii + start] = verticesValue[ii] * this.scale; } if (isMesh) { var meshVertices = attachment.vertices; - for (var ii = 0, nn = vertices.length; ii < nn; i++) + for (var ii = 0, nn = vertices.length; ii < nn; ii++) vertices[ii] += meshVertices[ii]; } } @@ -2186,8 +2185,7 @@ spine.SkeletonJson.prototype = { }, getFloatArray: function (map, name, scale) { var list = map[name]; - var values = []; - values = list.length; + var values = new spine.Float32Array(list.length); var i = 0, n = list.length; if (scale == 1) { for (; i < n; i++) @@ -2200,8 +2198,7 @@ spine.SkeletonJson.prototype = { }, getIntArray: function (map, name) { var list = map[name]; - var values = []; - values = list.length; + var values = new spine.Uint16Array(list.length); for (var i = 0, n = list.length; i < n; i++) values[i] = list[i] | 0; return values; @@ -2428,7 +2425,7 @@ spine.AtlasAttachmentLoader = function (atlas) { }; spine.AtlasAttachmentLoader.prototype = { newRegionAttachment: function (skin, name, path) { - var region = this.atlas.findRegion(name); + var region = this.atlas.findRegion(path); if (!region) throw "Region not found in atlas: " + path + " (region attachment: " + name + ")"; var attachment = new spine.RegionAttachment(name); attachment.rendererObject = region; @@ -2442,7 +2439,7 @@ spine.AtlasAttachmentLoader.prototype = { return attachment; }, newMeshAttachment: function (skin, name, path) { - var region = this.atlas.findRegion(name); + var region = this.atlas.findRegion(path); if (!region) throw "Region not found in atlas: " + path + " (mesh attachment: " + name + ")"; var attachment = new spine.MeshAttachment(name); attachment.rendererObject = region; @@ -2460,7 +2457,7 @@ spine.AtlasAttachmentLoader.prototype = { return attachment; }, newSkinnedMeshAttachment: function (skin, name, path) { - var region = this.atlas.findRegion(name); + var region = this.atlas.findRegion(path); if (!region) throw "Region not found in atlas: " + path + " (skinned mesh attachment: " + name + ")"; var attachment = new spine.SkinnedMeshAttachment(name); attachment.rendererObject = region; @@ -2628,4 +2625,4 @@ spine.SkeletonBounds.prototype = { getHeight: function () { return this.maxY - this.minY; } -}; +}; \ No newline at end of file From 038d25b729dfddd8292753da511d88fbe7272af4 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 25 Mar 2015 15:42:26 +0800 Subject: [PATCH 0090/1039] Fixed a bug context["createGain"] error of 360browser --- cocos2d/audio/CCAudio.js | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index e59d580ffc..ccc1853d56 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -516,10 +516,16 @@ cc.Audio = cc.Class.extend({ return cb(null, loader.cache[url]); if(SWA){ - var volume = context["createGain"](); - volume["gain"].value = 1; - volume["connect"](context["destination"]); - audio = new cc.Audio(context, volume, realUrl); + try{ + var volume = context["createGain"](); + volume["gain"].value = 1; + volume["connect"](context["destination"]); + audio = new cc.Audio(context, volume, realUrl); + }catch(err){ + SWA = false; + cc.log("browser don't support webAudio"); + audio = new cc.Audio(null, null, realUrl); + } }else{ audio = new cc.Audio(null, null, realUrl); } From 3ee128946d4014bda1f52ee6ad88e2a58b4cbdac Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 25 Mar 2015 16:28:40 +0800 Subject: [PATCH 0091/1039] Sync the latest OS info --- CCBoot.js | 110 ++++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 81 insertions(+), 29 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index 8e2a876172..040ffe09a2 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -1321,32 +1321,32 @@ cc._initSys = function (config, CONFIG_KEY) { /** * @memberof cc.sys - * @name OS_WINDOWS + * @name OS_IOS * @constant * @type {string} */ - sys.OS_WINDOWS = "Windows"; + sys.OS_IOS = "iOS"; /** * @memberof cc.sys - * @name OS_IOS + * @name OS_ANDROID * @constant * @type {string} */ - sys.OS_IOS = "iOS"; + sys.OS_ANDROID = "Android"; /** * @memberof cc.sys - * @name OS_OSX + * @name OS_WINDOWS * @constant * @type {string} */ - sys.OS_OSX = "OS X"; + sys.OS_WINDOWS = "Windows"; /** * @memberof cc.sys - * @name OS_UNIX + * @name OS_MARMALADE * @constant * @type {string} */ - sys.OS_UNIX = "UNIX"; + sys.OS_MARMALADE = "Marmalade"; /** * @memberof cc.sys * @name OS_LINUX @@ -1356,11 +1356,39 @@ cc._initSys = function (config, CONFIG_KEY) { sys.OS_LINUX = "Linux"; /** * @memberof cc.sys - * @name OS_ANDROID + * @name OS_BADA * @constant * @type {string} */ - sys.OS_ANDROID = "Android"; + sys.OS_BADA = "Bada"; + /** + * @memberof cc.sys + * @name OS_BLACKBERRY + * @constant + * @type {string} + */ + sys.OS_BLACKBERRY = "Blackberry"; + /** + * @memberof cc.sys + * @name OS_OSX + * @constant + * @type {string} + */ + sys.OS_OSX = "OS X"; + /** + * @memberof cc.sys + * @name OS_WP8 + * @constant + * @type {string} + */ + sys.OS_WP8 = "WP8"; + /** + * @memberof cc.sys + * @name OS_WINRT + * @constant + * @type {string} + */ + sys.OS_WINRT = "WINRT"; /** * @memberof cc.sys * @name OS_UNKNOWN @@ -1371,52 +1399,60 @@ cc._initSys = function (config, CONFIG_KEY) { /** * @memberof cc.sys - * @name WINDOWS + * @name UNKNOWN * @constant * @default * @type {Number} */ - sys.WINDOWS = 0; + sys.UNKNOWN = 0; /** * @memberof cc.sys - * @name LINUX + * @name IOS * @constant * @default * @type {Number} */ - sys.LINUX = 1; + sys.IOS = 1; /** * @memberof cc.sys - * @name MACOS + * @name ANDROID * @constant * @default * @type {Number} */ - sys.MACOS = 2; + sys.ANDROID = 2; /** * @memberof cc.sys - * @name ANDROID + * @name WIN32 + * @constant + * @default + * @type {Number} + */ + sys.WIN32 = 3; + /** + * @memberof cc.sys + * @name MARMALADE * @constant * @default * @type {Number} */ - sys.ANDROID = 3; + sys.MARMALADE = 4; /** * @memberof cc.sys - * @name IPHONE + * @name LINUX * @constant * @default * @type {Number} */ - sys.IPHONE = 4; + sys.LINUX = 5; /** * @memberof cc.sys - * @name IPAD + * @name BADA * @constant * @default * @type {Number} */ - sys.IPAD = 5; + sys.BADA = 6; /** * @memberof cc.sys * @name BLACKBERRY @@ -1424,7 +1460,15 @@ cc._initSys = function (config, CONFIG_KEY) { * @default * @type {Number} */ - sys.BLACKBERRY = 6; + sys.BLACKBERRY = 7; + /** + * @memberof cc.sys + * @name MACOS + * @constant + * @default + * @type {Number} + */ + sys.MACOS = 8; /** * @memberof cc.sys * @name NACL @@ -1432,7 +1476,7 @@ cc._initSys = function (config, CONFIG_KEY) { * @default * @type {Number} */ - sys.NACL = 7; + sys.NACL = 9; /** * @memberof cc.sys * @name EMSCRIPTEN @@ -1440,7 +1484,7 @@ cc._initSys = function (config, CONFIG_KEY) { * @default * @type {Number} */ - sys.EMSCRIPTEN = 8; + sys.EMSCRIPTEN = 10; /** * @memberof cc.sys * @name TIZEN @@ -1448,15 +1492,15 @@ cc._initSys = function (config, CONFIG_KEY) { * @default * @type {Number} */ - sys.TIZEN = 9; + sys.TIZEN = 11; /** * @memberof cc.sys - * @name WINRT + * @name QT5 * @constant * @default * @type {Number} */ - sys.WINRT = 10; + sys.QT5 = 12; /** * @memberof cc.sys * @name WP8 @@ -1464,7 +1508,15 @@ cc._initSys = function (config, CONFIG_KEY) { * @default * @type {Number} */ - sys.WP8 = 11; + sys.WP8 = 13; + /** + * @memberof cc.sys + * @name WINRT + * @constant + * @default + * @type {Number} + */ + sys.WINRT = 14; /** * @memberof cc.sys * @name MOBILE_BROWSER From 937166250a563769be4b9b8033f85b5a2ab88a3c Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Wed, 25 Mar 2015 16:35:28 +0800 Subject: [PATCH 0092/1039] Corrected a mistake of cc.Scheduler in _schedulePerFrame that the hasElement hasn't priority because it's an array. --- cocos2d/core/CCScheduler.js | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/cocos2d/core/CCScheduler.js b/cocos2d/core/CCScheduler.js index 947db33029..75c955a2cd 100644 --- a/cocos2d/core/CCScheduler.js +++ b/cocos2d/core/CCScheduler.js @@ -59,7 +59,7 @@ cc.ListEntry = function (prev, next, callback, target, priority, paused, markedF * A update entry list * @Class * @name cc.HashUpdateEntry - * @param {cc.ListEntry} list Which list does it belong to ? + * @param {Array} list Which list does it belong to ? * @param {cc.ListEntry} entry entry in the list * @param {cc.Class} target hash key (retained) * @param {function} callback @@ -193,7 +193,6 @@ cc.Timer = cc.Class.extend(/** @lends cc.Timer# */{ }); cc.TimerTargetSelector = cc.Timer.extend({ - _target: null, _selector: null, @@ -326,9 +325,9 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ _schedulePerFrame: function(callback, target, priority, paused){ var hashElement = this._hashForUpdates[target.__instanceId]; - if (hashElement){ + if (hashElement && hashElement.entry){ // check if priority has changed - if (hashElement.list.priority !== priority){ + if (hashElement.entry.priority !== priority){ if (this._updateHashLocked){ cc.log("warning: you CANNOT change update priority in scheduled function"); hashElement.entry.markedForDeletion = false; From 0824be041a4ac4594348f5ff579fd0804a33b309 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Wed, 25 Mar 2015 17:37:51 +0800 Subject: [PATCH 0093/1039] Fixed #2776: Fixed a bug of cc.ClippingNode that it doesn't work when set Inverted to true on Canvas Mode. --- cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js b/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js index 5e237d7c48..988af800f2 100644 --- a/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js +++ b/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js @@ -104,8 +104,8 @@ if(!stencil) return; var node = this._node; - if(stencil._renderCmd && stencil._renderCmd._setBlendFuncStr) - stencil._renderCmd._setBlendFuncStr(node.inverted ? "destination-out" : "destination-in"); + if(stencil._renderCmd && stencil._renderCmd._blendFuncStr) + stencil._renderCmd._blendFuncStr = (node.inverted ? "destination-out" : "destination-in"); if(!stencil._children) return; From 8e13665d74dcc23e8a687f3658c3e185742146e6 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Wed, 25 Mar 2015 17:42:54 +0800 Subject: [PATCH 0094/1039] Removed the unused function from cc.Sprite. --- cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js | 2 +- cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js | 5 ----- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js b/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js index 988af800f2..9a0a0d8d2d 100644 --- a/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js +++ b/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js @@ -104,7 +104,7 @@ if(!stencil) return; var node = this._node; - if(stencil._renderCmd && stencil._renderCmd._blendFuncStr) + if(stencil._renderCmd && stencil._renderCmd._blendFuncStr) //it is a hack way. stencil._renderCmd._blendFuncStr = (node.inverted ? "destination-out" : "destination-in"); if(!stencil._children) diff --git a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js index 4eb973c819..1dac4df749 100644 --- a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js @@ -46,11 +46,6 @@ proto._init = function () {}; - proto._setBlendFuncStr = function(compositeOperation){ - //a hack function for clippingNode - this._blendFuncStr = compositeOperation; - }; - proto.setDirtyRecursively = function (value) {}; proto._resetForBatchNode = function () {}; From f821b69d08b9e17755a2b47f827573bca7914656 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 26 Mar 2015 11:10:27 +0800 Subject: [PATCH 0095/1039] Issue #1565: TTF font haven't been set when parser Label --- .../cocostudio/loader/parsers/uiParser-1.x.js | 26 ++++++++++++++++--- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/uiParser-1.x.js b/extensions/cocostudio/loader/parsers/uiParser-1.x.js index c27002bb22..c14763e875 100644 --- a/extensions/cocostudio/loader/parsers/uiParser-1.x.js +++ b/extensions/cocostudio/loader/parsers/uiParser-1.x.js @@ -458,6 +458,7 @@ /** * Text parser (UIText) */ + var regTTF = /\.ttf$/; parser.TextAttributes = function(widget, options, resourcePath){ var touchScaleChangeAble = options["touchScaleEnable"]; widget.setTouchScaleChangeEnabled(touchScaleChangeAble); @@ -469,7 +470,15 @@ } var fn = options["fontName"]; if (fn != null){ - widget.setFontName(options["fontName"]); + if(cc.sys.isNative){ + if(regTTF.test(fn)){ + widget.setFontName(cc.path.join(cc.loader.resPath, resourcePath, fn)); + }else{ + widget.setFontName(fn); + } + }else{ + widget.setFontName(fn.replace(regTTF, '')); + } } var aw = options["areaWidth"]; var ah = options["areaHeight"]; @@ -599,7 +608,7 @@ /** * TextField parser (UITextField) */ - parser.TextFieldAttributes = function(widget, options, resoutcePath){ + parser.TextFieldAttributes = function(widget, options, resourcePath){ var ph = options["placeHolder"]; if(ph) widget.setPlaceHolder(ph); @@ -608,8 +617,17 @@ if(fs) widget.setFontSize(fs); var fn = options["fontName"]; - if(fn) - widget.setFontName(fn); + if (fn != null){ + if(cc.sys.isNative){ + if(regTTF.test(fn)){ + widget.setFontName(cc.path.join(cc.loader.resPath, resourcePath, fn)); + }else{ + widget.setFontName(fn); + } + }else{ + widget.setFontName(fn.replace(regTTF, '')); + } + } var tsw = options["touchSizeWidth"]; var tsh = options["touchSizeHeight"]; if(tsw!=null && tsh!=null) From c0de7f261dfa12b77e9676945f347ad6c168b4c8 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Thu, 26 Mar 2015 12:01:18 +0800 Subject: [PATCH 0096/1039] Fixed a bug of Scale9Sprite that it doesn't work when texture doesn't preload. --- extensions/ccui/base-classes/UIScale9Sprite.js | 18 +++++++++--------- .../gui/control-extension/CCScale9Sprite.js | 18 +++++++++--------- 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/extensions/ccui/base-classes/UIScale9Sprite.js b/extensions/ccui/base-classes/UIScale9Sprite.js index 813ceae5c1..f828457d2d 100644 --- a/extensions/ccui/base-classes/UIScale9Sprite.js +++ b/extensions/ccui/base-classes/UIScale9Sprite.js @@ -467,11 +467,11 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ if(!locLoaded){ texture.addEventListener("load", function(sender){ // the texture is rotated on Canvas render mode, so isRotated always is false. - var preferredSize = this._preferredSize; - preferredSize = cc.size(preferredSize.width, preferredSize.height); + var preferredSize = this._preferredSize, restorePreferredSize = preferredSize.width !== 0 && preferredSize.height !== 0; + if (restorePreferredSize) preferredSize = cc.size(preferredSize.width, preferredSize.height); var size = sender.getContentSize(); this.updateWithBatchNode(this._scale9Image, cc.rect(0,0,size.width,size.height), false, this._capInsets); - this.setPreferredSize(preferredSize); + if (restorePreferredSize)this.setPreferredSize(preferredSize); this._positionsAreDirty = true; this.dispatchEvent("load"); }, this); @@ -500,10 +500,10 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ if(!locLoaded){ spriteFrame.addEventListener("load", function(sender){ // the texture is rotated on Canvas render mode, so isRotated always is false. - var preferredSize = this._preferredSize; - preferredSize = cc.size(preferredSize.width, preferredSize.height); + var preferredSize = this._preferredSize, restorePreferredSize = preferredSize.width !== 0 && preferredSize.height !== 0; + if (restorePreferredSize) preferredSize = cc.size(preferredSize.width, preferredSize.height); this.updateWithBatchNode(this._scale9Image, sender.getRect(), cc._renderType === cc._RENDER_TYPE_WEBGL && sender.isRotated(), this._capInsets); - this.setPreferredSize(preferredSize); + if (restorePreferredSize)this.setPreferredSize(preferredSize); this._positionsAreDirty = true; this.dispatchEvent("load"); },this); @@ -900,10 +900,10 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ if(!locLoaded){ spriteFrame.addEventListener("load", function(sender){ // the texture is rotated on Canvas render mode, so isRotated always is false. - var preferredSize = this._preferredSize; - preferredSize = cc.size(preferredSize.width, preferredSize.height); + var preferredSize = this._preferredSize, restorePreferredSize = preferredSize.width !== 0 && preferredSize.height !== 0; + if (restorePreferredSize) preferredSize = cc.size(preferredSize.width, preferredSize.height); this.updateWithBatchNode(this._scale9Image, sender.getRect(), cc._renderType === cc._RENDER_TYPE_WEBGL && sender.isRotated(), this._capInsets); - this.setPreferredSize(preferredSize); + if (restorePreferredSize)this.setPreferredSize(preferredSize); this._positionsAreDirty = true; this.dispatchEvent("load"); },this); diff --git a/extensions/gui/control-extension/CCScale9Sprite.js b/extensions/gui/control-extension/CCScale9Sprite.js index abe7056ef7..917ccd0332 100644 --- a/extensions/gui/control-extension/CCScale9Sprite.js +++ b/extensions/gui/control-extension/CCScale9Sprite.js @@ -462,11 +462,11 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ if(!locLoaded){ texture.addEventListener("load", function(sender){ // the texture is rotated on Canvas render mode, so isRotated always is false. - var preferredSize = this._preferredSize; - preferredSize = cc.size(preferredSize.width, preferredSize.height); + var preferredSize = this._preferredSize, restorePreferredSize = (preferredSize.width !== 0 || preferredSize.height !== 0); + if(restorePreferredSize)preferredSize = cc.size(preferredSize.width, preferredSize.height); var size = sender.getContentSize(); this.updateWithBatchNode(this._scale9Image, cc.rect(0,0,size.width,size.height), false, this._capInsets); - this.setPreferredSize(preferredSize); + if(restorePreferredSize)this.setPreferredSize(preferredSize); this._positionsAreDirty = true; this.dispatchEvent("load"); }, this); @@ -495,10 +495,10 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ if(!locLoaded){ spriteFrame.addEventListener("load", function(sender){ // the texture is rotated on Canvas render mode, so isRotated always is false. - var preferredSize = this._preferredSize; - preferredSize = cc.size(preferredSize.width, preferredSize.height); + var preferredSize = this._preferredSize, restorePreferredSize = (preferredSize.width !== 0 || preferredSize.height !== 0); + if(restorePreferredSize)preferredSize = cc.size(preferredSize.width, preferredSize.height); this.updateWithBatchNode(this._scale9Image, sender.getRect(), cc._renderType === cc._RENDER_TYPE_WEBGL && sender.isRotated(), this._capInsets); - this.setPreferredSize(preferredSize); + if(restorePreferredSize)this.setPreferredSize(preferredSize); this._positionsAreDirty = true; this.dispatchEvent("load"); },this); @@ -895,10 +895,10 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ if(!locLoaded){ spriteFrame.addEventListener("load", function(sender){ // the texture is rotated on Canvas render mode, so isRotated always is false. - var preferredSize = this._preferredSize; - preferredSize = cc.size(preferredSize.width, preferredSize.height); + var preferredSize = this._preferredSize, restorePreferredSize = (preferredSize.width !== 0 || preferredSize.height !== 0); + if(restorePreferredSize)preferredSize = cc.size(preferredSize.width, preferredSize.height); this.updateWithBatchNode(this._scale9Image, sender.getRect(), cc._renderType === cc._RENDER_TYPE_WEBGL && sender.isRotated(), this._capInsets); - this.setPreferredSize(preferredSize); + if(restorePreferredSize)this.setPreferredSize(preferredSize); this._positionsAreDirty = true; this.dispatchEvent("load"); },this); From 72a8a85a979d7b58cdccb4a79eb87c493e7f759e Mon Sep 17 00:00:00 2001 From: joshuastray Date: Thu, 26 Mar 2015 13:52:44 +0800 Subject: [PATCH 0097/1039] make particle can be created from a object --- cocos2d/particle/CCParticleSystem.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cocos2d/particle/CCParticleSystem.js b/cocos2d/particle/CCParticleSystem.js index 85a844df33..1c3a310adf 100644 --- a/cocos2d/particle/CCParticleSystem.js +++ b/cocos2d/particle/CCParticleSystem.js @@ -341,8 +341,10 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ var ton = plistFile || 100; this.setDrawMode(cc.ParticleSystem.TEXTURE_MODE); this.initWithTotalParticles(ton); - } else if (plistFile) { + } else if (cc.isString(plistFile)) { this.initWithFile(plistFile); + } else if (cc.isObject(plistFile)) { + this.initWithDictionary(plistFile, ""); } }, From 8cdd3254b09e9a524ba11b14cc4cdb549b821a43 Mon Sep 17 00:00:00 2001 From: jianglong0156 Date: Thu, 26 Mar 2015 16:44:00 +0800 Subject: [PATCH 0098/1039] fix labelAtlas recover old label --- cocos2d/labels/CCLabelAtlas.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cocos2d/labels/CCLabelAtlas.js b/cocos2d/labels/CCLabelAtlas.js index 4e649f6881..e922ddc2d6 100644 --- a/cocos2d/labels/CCLabelAtlas.js +++ b/cocos2d/labels/CCLabelAtlas.js @@ -143,9 +143,10 @@ cc.LabelAtlas = cc.AtlasNode.extend(/** @lends cc.LabelAtlas# */{ var locLoaded = texture.isLoaded(); this._textureLoaded = locLoaded; if (!locLoaded) { + this._string = label; texture.addEventListener("load", function (sender) { this.initWithTexture(texture, width, height, label.length); - this.string = label; + this.string = this._string; this.setColor(this._renderCmd._displayedColor); this.dispatchEvent("load"); }, this); From 5dc60c280d4add59d8b3c13adf13008767a017df Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Fri, 27 Mar 2015 09:51:15 +0800 Subject: [PATCH 0099/1039] Issue #2751: added some functions to cc.Grid3D and cc.PageTurn3D --- cocos2d/actions3d/CCActionGrid.js | 53 ++++++++++++-- cocos2d/actions3d/CCActionPageTurn3D.js | 14 +++- cocos2d/effects/CCGrid.js | 92 +++++++++++++++++++++++-- 3 files changed, 148 insertions(+), 11 deletions(-) diff --git a/cocos2d/actions3d/CCActionGrid.js b/cocos2d/actions3d/CCActionGrid.js index faaa31f7fe..38b5c8a37f 100644 --- a/cocos2d/actions3d/CCActionGrid.js +++ b/cocos2d/actions3d/CCActionGrid.js @@ -33,6 +33,7 @@ */ cc.GridAction = cc.ActionInterval.extend(/** @lends cc.GridAction# */{ _gridSize:null, + _gridNodeTarget:null, /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. @@ -47,6 +48,8 @@ cc.GridAction = cc.ActionInterval.extend(/** @lends cc.GridAction# */{ gridSize && this.initWithDuration(duration, gridSize); }, + _cacheTargetAsGridNode: function(){}, + /** * to copy object with deep copy. * returns a clone of action. @@ -155,20 +158,40 @@ cc.Grid3DAction = cc.GridAction.extend(/** @lends cc.Grid3DAction# */{ }, /** - * returns the vertex than belongs to certain position in the grid + * returns the vertex than belongs to certain position in the grid.
+ * It will be deprecated in future, please use getVertex instead. * @param {cc.Point} position * @return {cc.Vertex3F} */ vertex:function (position) { - return this.target.grid.vertex(position); + return this.getVertex(position); }, /** - * returns the non-transformed vertex than belongs to certain position in the grid + * returns the vertex than belongs to certain position in the grid + * @param {cc.Point} position + * @return {cc.Vertex3F} + */ + getVertex: function(position){ + return this.target.grid.getVertex(position); + }, + + /** + * returns the non-transformed vertex than belongs to certain position in the grid
+ * It will be deprecated in future, please use getVertex instead. * @param {cc.Point} position * @return {cc.Vertex3F} */ originalVertex:function (position) { + return this.getOriginalVertex(position); + }, + + /** + * returns the non-transformed vertex than belongs to certain position in the grid + * @param {cc.Point} position + * @return {cc.Vertex3F} + */ + getOriginalVertex:function (position) { return this.target.grid.originalVertex(position); }, @@ -211,20 +234,40 @@ cc.Grid3DAction.create = cc.grid3DAction; cc.TiledGrid3DAction = cc.GridAction.extend(/** @lends cc.TiledGrid3DAction# */{ /** - * returns the tile that belongs to a certain position of the grid + * returns the tile that belongs to a certain position of the grid
+ * It will be deprecated in future, please use getTile instead. * @param {cc.Point} position * @return {cc.Quad3} */ tile:function (position) { + return this.getTile(position); + }, + + /** + * returns the tile that belongs to a certain position of the grid + * @param {cc.Point} position + * @return {cc.Quad3} + */ + getTile:function (position) { return this.target.grid.tile(position); }, /** - * returns the non-transformed tile that belongs to a certain position of the grid + * returns the non-transformed tile that belongs to a certain position of the grid
+ * It will be deprecated in future, please use getOriginalTile instead. * @param {cc.Point} position * @return {cc.Quad3} */ originalTile:function (position) { + return this.getOriginalTile(position); + }, + + /** + * returns the non-transformed tile that belongs to a certain position of the grid + * @param {cc.Point} position + * @return {cc.Quad3} + */ + getOriginalTile:function (position) { return this.target.grid.originalTile(position); }, diff --git a/cocos2d/actions3d/CCActionPageTurn3D.js b/cocos2d/actions3d/CCActionPageTurn3D.js index 367531662c..a28f0d4852 100644 --- a/cocos2d/actions3d/CCActionPageTurn3D.js +++ b/cocos2d/actions3d/CCActionPageTurn3D.js @@ -36,6 +36,18 @@ * @extends cc.Grid3DAction */ cc.PageTurn3D = cc.Grid3DAction.extend(/** @lends cc.PageTurn3D# */{ + getGrid: function(){ + var result = new cc.Grid3D(this._gridSize); + result.setNeedDepthTestForBlit(true); + return result; + }, + + clone: function(){ + var ret = new cc.PageTurn3D(); + ret.initWithDuration(this._duration, this._gridSize); + return ret; + }, + /** * Update each tick
* Time is the percentage of the way through the duration @@ -58,7 +70,7 @@ cc.PageTurn3D = cc.Grid3DAction.extend(/** @lends cc.PageTurn3D# */{ locVer.x = i; locVer.y = j; // Get original vertex - var p = this.originalVertex(locVer); + var p = this.getOriginalVertex(locVer); var R = Math.sqrt((p.x * p.x) + ((p.y - ay) * (p.y - ay))); var r = R * sinTheta; diff --git a/cocos2d/effects/CCGrid.js b/cocos2d/effects/CCGrid.js index d324338c81..3a0ec265c9 100644 --- a/cocos2d/effects/CCGrid.js +++ b/cocos2d/effects/CCGrid.js @@ -241,7 +241,15 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{ } cc.glBindTexture2D(this._texture); + this.beforeBlit(); this.blit(target); + this.afterBlit(); + }, + + beforeBlit: function () { + }, + + afterBlit: function () { }, blit:function () { @@ -300,6 +308,10 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{ _verticesBuffer:null, _indicesBuffer:null, + _needDepthTestForBlit: false, + _oldDepthTestValue: false, + _oldDepthWriteValue: false, + /** * create one Grid3D object * Constructor of cc.Grid3D @@ -323,11 +335,21 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{ }, /** - * returns the vertex at a given position + * returns the vertex at a given position
+ * It will be deprecated in future, please use getVertex instead. * @param {cc.Point} pos * @return {cc.Vertex3F} */ vertex:function (pos) { + return this.getVertex(pos); + }, + + /** + * returns the vertex at a given position + * @param {cc.Point} pos + * @return {cc.Vertex3F} + */ + getVertex: function(pos){ if(pos.x !== (0| pos.x) || pos.y !== (0| pos.y)) cc.log("cc.Grid3D.vertex() : Numbers must be integers"); var index = 0 | ((pos.x * (this._gridSize.height + 1) + pos.y) * 3); @@ -336,11 +358,21 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{ }, /** - * returns the original (non-transformed) vertex at a given position + * returns the original (non-transformed) vertex at a given position
+ * It will be deprecated in future, please use getOriginalVertex instead. * @param {cc.Point} pos * @return {cc.Vertex3F} */ originalVertex:function (pos) { + return this.getOriginalVertex(pos); + }, + + /** + * returns the original (non-transformed) vertex at a given position + * @param {cc.Point} pos + * @return {cc.Vertex3F} + */ + getOriginalVertex: function(pos) { if(pos.x !== (0| pos.x) || pos.y !== (0| pos.y)) cc.log("cc.Grid3D.originalVertex() : Numbers must be integers"); var index = 0 | ((pos.x * (this._gridSize.height + 1) + pos.y) * 3); @@ -364,6 +396,28 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{ this._dirty = true; }, + beforeBlit: function () { + if (this._needDepthTestForBlit) { + var gl = cc._renderContext; + this._oldDepthTestValue = gl.isEnabled(gl.DEPTH_TEST); + this._oldDepthWriteValue = gl.getParameter(gl.DEPTH_WRITEMASK); + //CHECK_GL_ERROR_DEBUG(); + gl.enable(gl.DEPTH_TEST); + gl.depthMask(true); + } + }, + + afterBlit: function () { + if (this._needDepthTestForBlit) { + var gl = cc._renderContext; + if (this._oldDepthTestValue) + gl.enable(gl.DEPTH_TEST); + else + gl.disable(gl.DEPTH_TEST); + gl.depthMask(this._oldDepthWriteValue); + } + }, + blit:function (target) { var n = this._gridSize.width * this._gridSize.height; cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POSITION | cc.VERTEX_ATTRIB_FLAG_TEX_COORDS); @@ -480,6 +534,14 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indicesBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this._indices, gl.STATIC_DRAW); this._dirty = true; + }, + + setNeedDepthTestForBlit: function(needDepthTest){ + this._needDepthTestForBlit = needDepthTest; + }, + + getNeedDepthTestForBlit: function(){ + return this._needDepthTestForBlit; } }); @@ -534,11 +596,21 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{ }, /** - * returns the tile at the given position + * returns the tile at the given position
+ * It will be deprecated in future, please use getTile instead. * @param {cc.Point} pos * @return {cc.Quad3} */ tile:function (pos) { + return this.getTile(pos); + }, + + /** + * returns the tile at the given position + * @param {cc.Point} pos + * @return {cc.Quad3} + */ + getTile: function(pos){ if(pos.x !== (0| pos.x) || pos.y !== (0| pos.y)) cc.log("cc.TiledGrid3D.tile() : Numbers must be integers"); @@ -555,7 +627,7 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{ * @param {cc.Point} pos * @return {cc.Quad3} */ - originalTile:function (pos) { + getOriginalTile:function (pos) { if(pos.x !== (0| pos.x) || pos.y !== (0| pos.y)) cc.log("cc.TiledGrid3D.originalTile() : Numbers must be integers"); @@ -567,6 +639,16 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{ new cc.Vertex3F(locOriginalVertices[idx + 9], locOriginalVertices[idx + 10], locOriginalVertices[idx + 11])); }, + /** + * returns the original tile (untransformed) at the given position.
+ * It will be deprecated in future, please use getOriginalTile instead. + * @param {cc.Point} pos + * @return {cc.Quad3} + */ + originalTile: function(pos) { + return this.getOriginalTile(pos); + }, + /** * sets a new tile * @param {cc.Point} pos @@ -593,7 +675,7 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{ this._dirty = true; }, - blit:function (target) { + blit: function (target) { var n = this._gridSize.width * this._gridSize.height; this._shaderProgram.use(); From 39f2e0b1d02ef54b9c336c4e7f421d6ccc37de2a Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Fri, 27 Mar 2015 15:34:27 +0800 Subject: [PATCH 0100/1039] Fixed #2786: fixed a bug of ccs.Armature that its name changes to animation name when loading from json files. --- extensions/cocostudio/armature/CCArmature.js | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/extensions/cocostudio/armature/CCArmature.js b/extensions/cocostudio/armature/CCArmature.js index e2c912b02c..7e8c58c3c9 100644 --- a/extensions/cocostudio/armature/CCArmature.js +++ b/extensions/cocostudio/armature/CCArmature.js @@ -89,8 +89,7 @@ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{ this._boneDic = {}; this._topBoneList.length = 0; - - this._name = name || ""; + //this._name = name || ""; var armatureDataManager = ccs.armatureDataManager; var animationData; @@ -131,15 +130,15 @@ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{ this.update(0); this.updateOffsetPoint(); } else { - this._name = "new_armature"; + name = "new_armature"; this.armatureData = new ccs.ArmatureData(); - this.armatureData.name = this._name; + this.armatureData.name = name; animationData = new ccs.AnimationData(); - animationData.name = this._name; + animationData.name = name; - armatureDataManager.addArmatureData(this._name, this.armatureData); - armatureDataManager.addAnimationData(this._name, animationData); + armatureDataManager.addArmatureData(name, this.armatureData); + armatureDataManager.addAnimationData(name, animationData); this.animation.setAnimationData(animationData); } From 6e25cdfcbca795fcf0ba310bb8bcce66f905d452 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Fri, 27 Mar 2015 16:43:48 +0800 Subject: [PATCH 0101/1039] Fixed 2786: Added a tip message function to cc.TextField on mobile browser. --- cocos2d/text-input/CCIMEDispatcher.js | 4 +++- cocos2d/text-input/CCTextFieldTTF.js | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/cocos2d/text-input/CCIMEDispatcher.js b/cocos2d/text-input/CCIMEDispatcher.js index 56c08d3204..4b713086e5 100644 --- a/cocos2d/text-input/CCIMEDispatcher.js +++ b/cocos2d/text-input/CCIMEDispatcher.js @@ -387,7 +387,9 @@ cc.IMEDispatcher = cc.Class.extend(/** @lends cc.imeDispatcher# */{ delegate.didAttachWithIME(); //prompt this._currentInputString = delegate.string || ""; - var userInput = prompt("please enter your word:", this._currentInputString); + + var tipMessage = delegate.getTipMessage ? delegate.getTipMessage() : "please enter your word:"; + var userInput = prompt(tipMessage, this._currentInputString); if(userInput != null) this._processDomInputString(userInput); this.dispatchInsertText("\n", 1); diff --git a/cocos2d/text-input/CCTextFieldTTF.js b/cocos2d/text-input/CCTextFieldTTF.js index 3628df9e9a..b5c9fb1283 100644 --- a/cocos2d/text-input/CCTextFieldTTF.js +++ b/cocos2d/text-input/CCTextFieldTTF.js @@ -387,6 +387,25 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ cc.imeDispatcher.removeDelegate(this); }, + _tipMessage: "please enter your word:", + /** + * Sets the input tip message to show on mobile browser. (mobile Web only) + * @param {string} tipMessage + */ + setTipMessage: function (tipMessage) { + if (tipMessage == null) + return; + this._tipMessage = tipMessage; + }, + + /** + * Gets the input tip message to show on mobile browser. (mobile Web only) + * @returns {string} + */ + getTipMessage: function () { + return this._tipMessage; + }, + /** * Append the text.
* Input the character. From 5cb3f16b60f15bab4085f755c716e41049819994 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Sat, 28 Mar 2015 16:27:06 +0800 Subject: [PATCH 0102/1039] Fixed a bug that UILayoutComponent.js --- extensions/ccui/layouts/UILayoutComponent.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/ccui/layouts/UILayoutComponent.js b/extensions/ccui/layouts/UILayoutComponent.js index ed7182def5..96a9dbf3fa 100644 --- a/extensions/ccui/layouts/UILayoutComponent.js +++ b/extensions/ccui/layouts/UILayoutComponent.js @@ -573,7 +573,7 @@ ccui.LayoutComponent.verticalEdge = {NONE: 0, BOTTOM: 1, TOP: 2, CENTER: 3}; ccui.LayoutComponent.NAME = "__ui_layout"; ccui.LayoutComponent.bindLayoutComponent = function (node) { var layout = node.getComponent(ccui.LayoutComponent.NAME); - if (layout !== null) + if (layout !== undefined) return layout; layout = new ccui.LayoutComponent(); From bcc0ed3a78b4c5449625074744168619cb0b4f10 Mon Sep 17 00:00:00 2001 From: Igor Shmulyan Date: Sat, 28 Mar 2015 22:58:37 +0200 Subject: [PATCH 0103/1039] fixed canceling child touch during moving of page view --- extensions/ccui/uiwidgets/scroll-widget/UIPageView.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js b/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js index 8dd03b0b5a..233fdebf78 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js @@ -508,7 +508,7 @@ ccui.PageView = ccui.Layout.extend(/** @lends ccui.PageView# */{ var offset = 0; offset = Math.abs(sender.getTouchBeganPosition().x - touchPoint.x); if (offset > this._childFocusCancelOffset) { - sender.setFocused(false); + sender.setHighlighted(false); this._handleMoveLogic(touch); } break; From 6bad3e1b9fb720c972db4310a459f07adb4164c8 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 30 Mar 2015 09:49:06 +0800 Subject: [PATCH 0104/1039] Change the version number --- cocos2d/core/platform/CCConfig.js | 2 +- tools/build.xml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/platform/CCConfig.js b/cocos2d/core/platform/CCConfig.js index eb24ebe368..96753a2e8f 100644 --- a/cocos2d/core/platform/CCConfig.js +++ b/cocos2d/core/platform/CCConfig.js @@ -31,7 +31,7 @@ * @type {String} * @name cc.ENGINE_VERSION */ -window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.4 Beta0"; +window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.4"; /** *

diff --git a/tools/build.xml b/tools/build.xml index ce6e9c35cf..0f5b80ac2f 100644 --- a/tools/build.xml +++ b/tools/build.xml @@ -5,7 +5,7 @@ classpath="./compiler/compiler.jar"/> + debug="false" output="./../lib/cocos2d-js-v3.4-min.js"> @@ -298,7 +298,7 @@ + debug="false" output="./../lib/cocos2d-js-v3.4-core-min.js"> From b8efc5f958b78a8100723cea5e7a385e10895543 Mon Sep 17 00:00:00 2001 From: feijing566 Date: Mon, 30 Mar 2015 10:14:30 +0800 Subject: [PATCH 0105/1039] Fixed a bug about CCAudio Fixed a bug about CCAudio --- cocos2d/audio/CCAudio.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index ccc1853d56..4312a527d7 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -255,7 +255,7 @@ cc.Audio = cc.Class.extend({ return true; }else{ var sourceNode = this._currentSource; - if(!this._playing && !sourceNode) + if(!this._playing || !sourceNode) return true; if(sourceNode["playbackState"] == null) return this._playing; From 28aa5043970dd7ac29534ef0c442d2a69663d674 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 30 Mar 2015 10:56:06 +0800 Subject: [PATCH 0106/1039] Fixed CCScheduler repeat error --- cocos2d/core/CCScheduler.js | 2 +- cocos2d/core/base-nodes/CCNode.js | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/cocos2d/core/CCScheduler.js b/cocos2d/core/CCScheduler.js index 75c955a2cd..a1abe6f467 100644 --- a/cocos2d/core/CCScheduler.js +++ b/cocos2d/core/CCScheduler.js @@ -159,7 +159,7 @@ cc.Timer = cc.Class.extend(/** @lends cc.Timer# */{ update:function (dt) { if (this._elapsed === -1) { this._elapsed = 0; - this._timesExecuted = 0; + this._timesExecuted = 1; } else { this._elapsed += dt; if (this._runForever && !this._useDelay) {//standard timer usage diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index 6cb06db921..590a751414 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -1700,9 +1700,14 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ delay = 0; } }else if(len === 3){ - //callback, interval, key - key = repeat; - repeat = cc.REPEAT_FOREVER; + if(typeof repeat === "string"){ + //callback, interval, key + key = repeat; + repeat = cc.REPEAT_FOREVER; + }else{ + //callback, interval, repeat + key = this.__instanceId; + } delay = 0; }else if(len === 4){ key = this.__instanceId; From 9a3215ffff2b4b618c1195fd33af8ced8185db99 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 30 Mar 2015 11:35:16 +0800 Subject: [PATCH 0107/1039] Fixed CCScheduler repeat error --- cocos2d/core/CCScheduler.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/CCScheduler.js b/cocos2d/core/CCScheduler.js index a1abe6f467..75c955a2cd 100644 --- a/cocos2d/core/CCScheduler.js +++ b/cocos2d/core/CCScheduler.js @@ -159,7 +159,7 @@ cc.Timer = cc.Class.extend(/** @lends cc.Timer# */{ update:function (dt) { if (this._elapsed === -1) { this._elapsed = 0; - this._timesExecuted = 1; + this._timesExecuted = 0; } else { this._elapsed += dt; if (this._runForever && !this._useDelay) {//standard timer usage From 65ec96f44a5ea3c01b56bdb5b0c381d08f309c87 Mon Sep 17 00:00:00 2001 From: joshuastray Date: Mon, 30 Mar 2015 11:35:24 +0800 Subject: [PATCH 0108/1039] add cc.sys.OpenURL --- CCBoot.js | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/CCBoot.js b/CCBoot.js index b67dd68d0b..ac316ccd3c 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -1797,6 +1797,16 @@ cc._initSys = function (config, CONFIG_KEY) { str += "platform : " + self.platform + "\r\n"; cc.log(str); } + + /** + * Open a url in browser + * @memberof cc.sys + * @name openURL + * @param {String} url + */ + sys.openURL = function(url){ + window.open(url); + } }; //+++++++++++++++++++++++++something about sys end+++++++++++++++++++++++++++++ From d942918530e5d21846a294ae54a0d6dab2b77063 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 30 Mar 2015 14:46:31 +0800 Subject: [PATCH 0109/1039] Fixed spine collapse. (canvas) --- extensions/spine/CCSkeletonCanvasRenderCmd.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/extensions/spine/CCSkeletonCanvasRenderCmd.js b/extensions/spine/CCSkeletonCanvasRenderCmd.js index d887f6d791..ff31b3d0e9 100644 --- a/extensions/spine/CCSkeletonCanvasRenderCmd.js +++ b/extensions/spine/CCSkeletonCanvasRenderCmd.js @@ -155,10 +155,10 @@ bone.worldY + attachment.x * bone.m10 + attachment.y * bone.m11); selSprite.setScale(bone.worldScaleX, bone.worldScaleY); selSprite.setRotation(-(slot.bone.worldRotation + attachment.rotation)); - selSprite.setOpacity(0 | (slot.skeleton.a * slot.a * 255)); - var r = 0 | (slot.skeleton.r * slot.r * 255); - var g = 0 | (slot.skeleton.g * slot.g * 255); - var b = 0 | (slot.skeleton.b * slot.b * 255); + selSprite.setOpacity(0 | (node._skeleton.a * slot.a * 255)); + var r = 0 | (node._skeleton.r * slot.r * 255); + var g = 0 | (node._skeleton.g * slot.g * 255); + var b = 0 | (node._skeleton.b * slot.b * 255); selSprite.setColor(cc.color(r,g,b)); } }; From d773bbf00322fe6a8b0e7f67f78e021d5a4ba242 Mon Sep 17 00:00:00 2001 From: feijing566 Date: Mon, 30 Mar 2015 15:00:41 +0800 Subject: [PATCH 0110/1039] Update CCAudio.js remove the check because this._playing alway is true --- cocos2d/audio/CCAudio.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index 4312a527d7..34f412f60d 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -255,7 +255,7 @@ cc.Audio = cc.Class.extend({ return true; }else{ var sourceNode = this._currentSource; - if(!this._playing || !sourceNode) + if(!sourceNode) return true; if(sourceNode["playbackState"] == null) return this._playing; From e9c40c3a611dd403fe77fd4d83e6244e55118c33 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 30 Mar 2015 20:13:45 +0800 Subject: [PATCH 0111/1039] Fixed unscheduler error --- cocos2d/core/base-nodes/CCNode.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index 6cb06db921..f4d4fa05b1 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -1759,7 +1759,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ if (!callback_fn) return; - this.scheduler.unschedule(this.__instanceId, this, callback_fn); + this.scheduler.unschedule(callback_fn, this); }, /** From b2e07cf7fb338355b118c81e6984d00478d28570 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Tue, 31 Mar 2015 16:44:04 +0800 Subject: [PATCH 0112/1039] Update the authors --- AUTHORS.txt | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/AUTHORS.txt b/AUTHORS.txt index 8d63894f5e..933701bb3e 100644 --- a/AUTHORS.txt +++ b/AUTHORS.txt @@ -240,11 +240,18 @@ Dany Ellement @DEllement cc.FontDefinition & ccui.RichText improvemen IShm @IShm cc.Screen bug fix cc.ParticleSystem bug fix + ccui.PageView bug fix Thomas Jablonski @thomas-jablonski cc.audioEngine bug fix + Cocostudio typo fix WingGao @WingGao cc.TMXLayer bug fix +Skliar Ihor @igogo5yo Add Bower support + +feijing566 @feijing566 cc.Audio bug fix + + Retired Core Developers: Shengxiang Chen (Nero Chan) Xingsen Ma From ecaa1aed18c4fc4b0d71c862c1259530c85075d3 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 31 Mar 2015 22:03:38 +0800 Subject: [PATCH 0113/1039] Update Engine version --- cocos2d/core/platform/CCConfig.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/platform/CCConfig.js b/cocos2d/core/platform/CCConfig.js index 96753a2e8f..4a6ba3834b 100644 --- a/cocos2d/core/platform/CCConfig.js +++ b/cocos2d/core/platform/CCConfig.js @@ -31,7 +31,7 @@ * @type {String} * @name cc.ENGINE_VERSION */ -window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.4"; +window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.5"; /** *

From 97e739cc1fce776c082747ff7a278617fc7a9548 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 1 Apr 2015 10:51:20 +0800 Subject: [PATCH 0114/1039] [Cocos2d-JS v3.5] Added changelog --- CHANGELOG.txt | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/CHANGELOG.txt b/CHANGELOG.txt index cb53252b0c..6f25c68923 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,5 +1,35 @@ ChangeLog: +Cocos2d-JS v3.5 @ April 1 2015 + +* Upgraded Cocos Studio parser to support Cocos Studio v2.2. +* Upgraded Spine support to v2.1, added spine test case with FFD. FFD is supported in native but not in web, both engine can parse the new version file correctly, but the web engine will ignore FFD informations. +* Replaced '==' with '===' for better performance. +* Added `path` parameter in `ccs.load` to support modifying cocostudio project resource path. +* Added animationList to Cocostudio ActionTimeline to support playing animation by name. +* Made ParticleSystem support creation from an map object. +* Added missing functions to `cc.Grid3D` and `cc.PageTurn3D`. +* Added tip message functions to `cc.TextFieldTTF` for mobile browser. +* Added a function `cc.sys.openURL`. +* Disabled retina display by default for better performance. +* Added Bower support. +* Updated `cc.sys.OS_XXX` informations for supported systems. + +* Bug fixes: + 1. Fixed a bug of chipmunk.js that it doesn't work under closure compiler advanced mode. + 2. Fixed a bug of Cocos Studio parser that widget didn't set its layout component. + 3. Fixed grammatical mistakes in cocostudio parser logs. + 4. Fixed memory leak issue in `cc.LabelBMFont`. + 5. Fixed a bug of `cc.Scale9Sprite` that its `updateDisplayColor` doesn't take effect. + 6. Fixed a bug of Cocos Studio parser that `cc.Scale9Sprite` doesn't display correctly if its texture isn't preloaded. + 7. Fixed a bug of `cc.MenuItemSprite` that the construction will fail when parameter `selectedSprite` is a Scale9Sprite instance. + 8. Fixed a bug of Cocos Studio parser that the background color of `ccui.Layout` can't be parsed correctly. + 9. Fixed a bug of `cc.ClippingNode` that it doesn't work when set `inverted` to true in Canvas Mode. + 10. Fixed a bug of `ccs.Armature` that its name was modified to animation name when loading from json files. + 11. Fixed a bug of `ccui.PageView` that it cancel child touch during movment of page view. + 12. Fixed a bug of `cc.Scheduler` that its parameter `repeat` is invalid in schedule function. + 13. Fixed a bug of `cc.Scheduler` that `unschedule` function may fail. + Cocos2d-JS v3.4 Beta0 @ March 19 2015 * Added Windows Phone 8.0 platform support. From 31c397cb0c60d923f49ac056d0fd6e28b02110be Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 1 Apr 2015 14:34:38 +0800 Subject: [PATCH 0115/1039] Update build.xml --- tools/build.xml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tools/build.xml b/tools/build.xml index 0f5b80ac2f..29c6abadb1 100644 --- a/tools/build.xml +++ b/tools/build.xml @@ -5,8 +5,8 @@ classpath="./compiler/compiler.jar"/> - + debug="false" output="./../lib/cocos2d-js-v3.5-min.js"> + @@ -298,8 +298,8 @@ - + debug="false" output="./../lib/cocos2d-js-v3.5-core-min.js"> + From 2354cc8e111bc7092f8380aed644dcc6f2ab52b0 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 1 Apr 2015 14:36:40 +0800 Subject: [PATCH 0116/1039] Fixed a bug that scheduleUpdate error when cc.ActionManager is null --- cocos2d/core/CCDirector.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js index 02141cbda5..cd84958624 100644 --- a/cocos2d/core/CCDirector.js +++ b/cocos2d/core/CCDirector.js @@ -154,8 +154,12 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ //scheduler this._scheduler = new cc.Scheduler(); //action manager - this._actionManager = cc.ActionManager ? new cc.ActionManager() : null; - this._scheduler.scheduleUpdate(this._actionManager, cc.Scheduler.PRIORITY_SYSTEM, false); + if(cc.ActionManager){ + this._actionManager = new cc.ActionManager(); + this._scheduler.scheduleUpdate(this._actionManager, cc.Scheduler.PRIORITY_SYSTEM, false); + }else{ + this._actionManager = null; + } this._eventAfterDraw = new cc.EventCustom(cc.Director.EVENT_AFTER_DRAW); this._eventAfterDraw.setUserData(this); From 2bc070301dcca4c865836ab55ebf847f7eff9ba0 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Wed, 1 Apr 2015 15:46:35 +0800 Subject: [PATCH 0117/1039] Fixed a bug of cc.LabelTTF that its enableShadow doesn't work. --- cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js | 2 +- cocos2d/core/labelttf/CCLabelTTFWebGLRenderCmd.js | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js index d18507c02d..b6bddd9636 100644 --- a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js +++ b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js @@ -413,7 +413,7 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; locShadowColor = node._shadowColor || this._displayedColor; var locStrokeColor = node._strokeColor, locFontFillColor = node._textFillColor; - this._shadowColorStr = "rgba(" + (0 | (locShadowColor.r * 0.5)) + "," + (0 | (locShadowColor.g * 0.5)) + "," + (0 | (locShadowColor.b * 0.5)) + "," + node._shadowOpacity + ")"; + this._shadowColorStr = "rgba(" + (0 | (locShadowColor.r)) + "," + (0 | (locShadowColor.g)) + "," + (0 | (locShadowColor.b)) + "," + node._shadowOpacity + ")"; this._fillColorStr = "rgba(" + (0 | (locDisplayColor.r / 255 * locFontFillColor.r)) + "," + (0 | (locDisplayColor.g / 255 * locFontFillColor.g)) + "," + (0 | (locDisplayColor.b / 255 * locFontFillColor.b)) + ", 1)"; //use globalOpacity + locDisplayedOpacity / 255 + ")"; this._strokeColorStr = "rgba(" + (0 | (locDisplayColor.r / 255 * locStrokeColor.r)) + "," + (0 | (locDisplayColor.g / 255 * locStrokeColor.g)) + "," diff --git a/cocos2d/core/labelttf/CCLabelTTFWebGLRenderCmd.js b/cocos2d/core/labelttf/CCLabelTTFWebGLRenderCmd.js index 12a70b54f5..dfa2893e61 100644 --- a/cocos2d/core/labelttf/CCLabelTTFWebGLRenderCmd.js +++ b/cocos2d/core/labelttf/CCLabelTTFWebGLRenderCmd.js @@ -37,8 +37,9 @@ proto._setColorsString = function () { this.setDirtyFlag(cc.Node._dirtyFlags.textDirty); var node = this._node; - var locStrokeColor = node._strokeColor, locFontFillColor = node._textFillColor; - this._shadowColorStr = "rgba(128,128,128," + node._shadowOpacity + ")"; + var locStrokeColor = node._strokeColor, locFontFillColor = node._textFillColor, + locShadowColor = node._shadowColor || this._displayedColor; + this._shadowColorStr = "rgba(" + (0 | locShadowColor.r) + "," + (0 | locShadowColor.g) + "," + (0 | locShadowColor.b) + "," + node._shadowOpacity + ")"; this._fillColorStr = "rgba(" + (0 | locFontFillColor.r) + "," + (0 | locFontFillColor.g) + "," + (0 | locFontFillColor.b) + ", 1)"; this._strokeColorStr = "rgba(" + (0 | locStrokeColor.r) + "," + (0 | locStrokeColor.g) + "," + (0 | locStrokeColor.b) + ", 1)"; }; From df97e0e8935bef7e436384965fd112688e147ede Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 1 Apr 2015 16:56:36 +0800 Subject: [PATCH 0118/1039] Fixed a bug that LoadingBar texture error without pre load. --- extensions/ccui/uiwidgets/UILoadingBar.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/extensions/ccui/uiwidgets/UILoadingBar.js b/extensions/ccui/uiwidgets/UILoadingBar.js index 4a3235aa87..0b9b90eaed 100644 --- a/extensions/ccui/uiwidgets/UILoadingBar.js +++ b/extensions/ccui/uiwidgets/UILoadingBar.js @@ -124,7 +124,8 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{ var self = this; if(!barRenderer._textureLoaded){ barRenderer.addEventListener("load", function(){ - self.loadTexture(self._renderBarTexType, self._textureFile); + self.loadTexture(self._textureFile, self._renderBarTexType); + self._setPercent(self._percent); }); } @@ -236,6 +237,10 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{ if (percent === this._percent) return; this._percent = percent; + this._setPercent(percent); + }, + + _setPercent: function(percent){ if (this._totalLength <= 0) return; var res = this._percent / 100.0; From c8af0a9e5b704e3532d5e5a55413cedd05452e88 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Wed, 1 Apr 2015 17:00:36 +0800 Subject: [PATCH 0119/1039] Fixed a bug of cc.LabelTTF that its setColor doesn't set shadowColor on CanvasMode --- cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js index b6bddd9636..fa687f865a 100644 --- a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js +++ b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js @@ -412,12 +412,14 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; var locDisplayColor = this._displayedColor, node = this._node, locShadowColor = node._shadowColor || this._displayedColor; var locStrokeColor = node._strokeColor, locFontFillColor = node._textFillColor; - - this._shadowColorStr = "rgba(" + (0 | (locShadowColor.r)) + "," + (0 | (locShadowColor.g)) + "," + (0 | (locShadowColor.b)) + "," + node._shadowOpacity + ")"; - this._fillColorStr = "rgba(" + (0 | (locDisplayColor.r / 255 * locFontFillColor.r)) + "," + (0 | (locDisplayColor.g / 255 * locFontFillColor.g)) + "," - + (0 | (locDisplayColor.b / 255 * locFontFillColor.b)) + ", 1)"; //use globalOpacity + locDisplayedOpacity / 255 + ")"; - this._strokeColorStr = "rgba(" + (0 | (locDisplayColor.r / 255 * locStrokeColor.r)) + "," + (0 | (locDisplayColor.g / 255 * locStrokeColor.g)) + "," - + (0 | (locDisplayColor.b / 255 * locStrokeColor.b)) + ", 1)"; //use globalOpacity + locDisplayedOpacity / 255 + ")"; + var dr = locDisplayColor.r / 255, dg = locDisplayColor.g / 255, db = locDisplayColor.b / 255; + + this._shadowColorStr = "rgba(" + (0 | (dr * locShadowColor.r)) + "," + (0 | ( dg * locShadowColor.g)) + "," + + (0 | (db * locShadowColor.b)) + "," + node._shadowOpacity + ")"; + this._fillColorStr = "rgba(" + (0 | (dr * locFontFillColor.r)) + "," + (0 | (dg * locFontFillColor.g)) + "," + + (0 | (db * locFontFillColor.b)) + ", 1)"; + this._strokeColorStr = "rgba(" + (0 | (dr * locStrokeColor.r)) + "," + (0 | (dg * locStrokeColor.g)) + "," + + (0 | (db * locStrokeColor.b)) + ", 1)"; }; proto._updateColor = function(){ From 51f52789bec4792673924520a13012974aadc3a6 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 2 Apr 2015 14:55:11 +0800 Subject: [PATCH 0120/1039] Repair a bug that is callback can't running. (cocosbuilder) --- extensions/ccb-reader/CCBReader.js | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/extensions/ccb-reader/CCBReader.js b/extensions/ccb-reader/CCBReader.js index e22f54decf..32e8d8919f 100644 --- a/extensions/ccb-reader/CCBReader.js +++ b/extensions/ccb-reader/CCBReader.js @@ -709,9 +709,8 @@ cc.BuilderReader = cc.Class.extend({ _readHeader:function () { /* If no bytes loaded, don't crash about it. */ - if (this._data === null) { + if (!this._data) return false; - } /* Read magic bytes */ var magicBytes = this._readStringFromBytes(this._currentByte, 4, true); @@ -866,9 +865,9 @@ cc.BuilderReader = cc.Class.extend({ if (target !== null) { var assigned = false; - if (target.onAssignCCBMemberVariable) { + if (!target && (target.onAssignCCBMemberVariable)) assigned = target.onAssignCCBMemberVariable(target, memberVarAssignmentName, node); - } + locMemberAssigner = this._ccbMemberVariableAssigner; if (!assigned && locMemberAssigner != null && locMemberAssigner.onAssignCCBMemberVariable) { locMemberAssigner.onAssignCCBMemberVariable(target, memberVarAssignmentName, node); @@ -1070,9 +1069,9 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) { var callbackType = callbackSplit[0]; var kfCallbackName = callbackSplit[1]; - if (callbackType === 1){ // Document callback + if (callbackType == 1){ // Document callback animationManager.setCallFunc(cc.callFunc(controller[kfCallbackName], controller), keyframeCallbacks[j]); - } else if (callbackType === 2 && owner) {// Owner callback + } else if (callbackType == 2 && owner) {// Owner callback animationManager.setCallFunc(cc.callFunc(owner[kfCallbackName], owner), keyframeCallbacks[j]); } } From 4460d7fba7edb2e6403436368563998dcf8bffda Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 2 Apr 2015 14:58:25 +0800 Subject: [PATCH 0121/1039] Repair a bug that is callback can't running. (cocosbuilder) --- extensions/ccb-reader/CCBReader.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/ccb-reader/CCBReader.js b/extensions/ccb-reader/CCBReader.js index 32e8d8919f..657f68f607 100644 --- a/extensions/ccb-reader/CCBReader.js +++ b/extensions/ccb-reader/CCBReader.js @@ -862,10 +862,10 @@ cc.BuilderReader = cc.Class.extend({ target = this._owner; } - if (target !== null) { + if (!target) { var assigned = false; - if (!target && (target.onAssignCCBMemberVariable)) + if (target.onAssignCCBMemberVariable) assigned = target.onAssignCCBMemberVariable(target, memberVarAssignmentName, node); locMemberAssigner = this._ccbMemberVariableAssigner; From f111b1cd7860d0da623569ead42b7bf6764ff9c1 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 2 Apr 2015 16:51:09 +0800 Subject: [PATCH 0122/1039] Fixed a bug that cancel error of cc.TimerTargetCallback --- cocos2d/core/CCScheduler.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/CCScheduler.js b/cocos2d/core/CCScheduler.js index 75c955a2cd..df5849dd5c 100644 --- a/cocos2d/core/CCScheduler.js +++ b/cocos2d/core/CCScheduler.js @@ -263,7 +263,7 @@ cc.TimerTargetCallback = cc.Timer.extend({ cancel: function(){ //override - this._scheduler.unschedule(this._key, this._target); + this._scheduler.unschedule(this._callback, this._target); } }); From ee232559111a4748fd2a2661809ff119a35a84ff Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 3 Apr 2015 13:33:23 +0800 Subject: [PATCH 0123/1039] Fixed a bug that TMX Objects position error when set ContentScaleFactor --- cocos2d/tilemap/CCTMXXMLParser.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/cocos2d/tilemap/CCTMXXMLParser.js b/cocos2d/tilemap/CCTMXXMLParser.js index 478db3f2ef..63b295d0e7 100644 --- a/cocos2d/tilemap/CCTMXXMLParser.js +++ b/cocos2d/tilemap/CCTMXXMLParser.js @@ -748,6 +748,7 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ } var objects = selGroup.querySelectorAll('object'); + var getContentScaleFactor = cc.director.getContentScaleFactor(); if (objects) { for (j = 0; j < objects.length; j++) { var selObj = objects[j]; @@ -761,15 +762,14 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ // Assign all the attributes as key/name pairs in the properties dictionary objectProp["type"] = selObj.getAttribute('type') || ""; - objectProp["x"] = parseInt(selObj.getAttribute('x') || 0) + objectGroup.getPositionOffset().x; - var y = parseInt(selObj.getAttribute('y') || 0) + objectGroup.getPositionOffset().y; - objectProp["width"] = parseInt(selObj.getAttribute('width')) || 0; objectProp["height"] = parseInt(selObj.getAttribute('height')) || 0; + objectProp["x"] = (((selObj.getAttribute('x') || 0) | 0) + objectGroup.getPositionOffset().x) / getContentScaleFactor; + var y = ((selObj.getAttribute('y') || 0) | 0) + objectGroup.getPositionOffset().y / getContentScaleFactor; // Correct y position. (Tiled uses Flipped, cocos2d uses Standard) - objectProp["y"] = parseInt(this.getMapSize().height * this.getTileSize().height) - y - objectProp["height"]; - + objectProp["y"] = (parseInt(this.getMapSize().height * this.getTileSize().height) - y - objectProp["height"]) / cc.director.getContentScaleFactor(); + objectProp["rotation"] = parseInt(selObj.getAttribute('rotation')) || 0; var docObjProps = selObj.querySelectorAll("properties > property"); From 6c7666513a729dd09b467a9fb567d3a4dbf92483 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 3 Apr 2015 14:19:10 +0800 Subject: [PATCH 0124/1039] Fixed a bug that TMX position error on canvas --- cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js index b4f53b561a..fd6896e866 100644 --- a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js +++ b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js @@ -86,7 +86,6 @@ var wrapper = ctx || cc._renderContext, context = wrapper.getContext(); wrapper.setGlobalAlpha(alpha); - var posX = 0 | ( -this._anchorPointInPoints.x), posY = 0 | ( -this._anchorPointInPoints.y); var locCacheCanvas = this._cacheCanvas; //direct draw image by canvas drawImage if (locCacheCanvas && locCacheCanvas.width !== 0 && locCacheCanvas.height !== 0) { @@ -95,10 +94,10 @@ if (node.layerOrientation === cc.TMX_ORIENTATION_HEX) { var halfTileSize = node._mapTileSize.height * 0.5 * scaleY; context.drawImage(locCacheCanvas, 0, 0, locCacheCanvas.width, locCacheCanvas.height, - posX, -(posY + locCanvasHeight) + halfTileSize, locCacheCanvas.width * scaleX, locCanvasHeight); + 0, -locCanvasHeight + halfTileSize, locCacheCanvas.width * scaleX, locCanvasHeight); } else { context.drawImage(locCacheCanvas, 0, 0, locCacheCanvas.width, locCacheCanvas.height, - posX, -(posY + locCanvasHeight), locCacheCanvas.width * scaleX, locCanvasHeight); + 0, -locCanvasHeight, locCacheCanvas.width * scaleX, locCanvasHeight); } } cc.g_NumberOfDraws++; From 57fe80299954319ea2f5187998e8758dae51767c Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 3 Apr 2015 14:41:01 +0800 Subject: [PATCH 0125/1039] Update TMX transform to support RotationX and RotationY --- cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js index fd6896e866..6589bb2643 100644 --- a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js +++ b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js @@ -182,11 +182,8 @@ worldT.c = t.c * pt.a + t.d * pt.c; //c worldT.d = t.c * pt.b + t.d * pt.d; //d - var plt = parentCmd._transform; - var xOffset = -(plt.b + plt.c) * t.ty; - var yOffset = -(plt.b + plt.c) * t.tx; - worldT.tx = (t.tx * pt.a + t.ty * pt.c + pt.tx + xOffset); //tx - worldT.ty = (t.tx * pt.b + t.ty * pt.d + pt.ty + yOffset); //ty + worldT.tx = pt.a * t.tx + pt.c * t.ty + pt.tx; + worldT.ty = pt.d * t.ty + pt.ty + pt.b * t.tx; } else { worldT.a = t.a; worldT.b = t.b; From be3f4f1008b8b0d77268cb78124c85530ba3a4ab Mon Sep 17 00:00:00 2001 From: RackovychV Date: Fri, 3 Apr 2015 13:08:47 +0300 Subject: [PATCH 0126/1039] fix scheduler pauseAllTargetsWithMinPriority --- cocos2d/core/CCScheduler.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/cocos2d/core/CCScheduler.js b/cocos2d/core/CCScheduler.js index df5849dd5c..75ba323127 100644 --- a/cocos2d/core/CCScheduler.js +++ b/cocos2d/core/CCScheduler.js @@ -827,8 +827,8 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ entry = this._updatesNegList[i]; if (entry) { if(entry.priority >= minPriority){ - element.paused = true; - idsWithSelectors.push(element.target); + entry.paused = true; + idsWithSelectors.push(entry.target); } } } @@ -838,8 +838,8 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ for(i=0; i= minPriority){ - element.paused = true; - idsWithSelectors.push(element.target); + entry.paused = true; + idsWithSelectors.push(entry.target); } } } From 9748f03aa7781f4a45f7871efc9902b015112729 Mon Sep 17 00:00:00 2001 From: RackovychV Date: Mon, 6 Apr 2015 16:42:18 +0300 Subject: [PATCH 0127/1039] fix scheduler unscheduleAllWithMinPriority --- cocos2d/core/CCScheduler.js | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/CCScheduler.js b/cocos2d/core/CCScheduler.js index 75ba323127..95e3208d2f 100644 --- a/cocos2d/core/CCScheduler.js +++ b/cocos2d/core/CCScheduler.js @@ -734,27 +734,41 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ // Updates selectors var entry; + var temp_length = 0; if(minPriority < 0){ - for(i=0; i= minPriority){ this.unscheduleUpdate(entry.target); } } + + if (temp_length == this._updatesNegList.length) + { + i++; + } } } if(minPriority <= 0){ - for(i=0; i= minPriority) @@ -762,6 +776,11 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ this.unscheduleUpdate(entry.target); } } + + if (temp_length == this._updatesPosList.length) + { + i++; + } } }, From 5ba96c3f5e8a1d7df577ef3972b2577a3d836f65 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Tue, 7 Apr 2015 10:20:26 +0800 Subject: [PATCH 0128/1039] Issue: add test case and refactor spine skeleton --- extensions/spine/CCSkeletonAnimation.js | 2 +- extensions/spine/CCSkeletonCanvasRenderCmd.js | 59 ++++++++++++++----- extensions/spine/CCSkeletonWebGLRenderCmd.js | 28 ++++----- template/project.json | 4 +- template/src/myApp.js | 9 +++ template/src/resource.js | 3 + 6 files changed, 73 insertions(+), 32 deletions(-) diff --git a/extensions/spine/CCSkeletonAnimation.js b/extensions/spine/CCSkeletonAnimation.js index 0d1e392a34..ef844c83fe 100644 --- a/extensions/spine/CCSkeletonAnimation.js +++ b/extensions/spine/CCSkeletonAnimation.js @@ -161,7 +161,7 @@ sp._regionAttachment_updateSlotForCanvas = function(self, slot, points) { return; var vertices = {}; - self.computeVertices(slot.bone.x, slot.bone.y, slot.bone, vertices); + self.computeVertices(slot.bone.skeleton.x, slot.bone.skeleton.y, slot.bone, vertices); var VERTEX = sp.VERTEX_INDEX; points.length = 0; points.push(cc.p(vertices[VERTEX.X1], vertices[VERTEX.Y1])); diff --git a/extensions/spine/CCSkeletonCanvasRenderCmd.js b/extensions/spine/CCSkeletonCanvasRenderCmd.js index ff31b3d0e9..5833881bc1 100644 --- a/extensions/spine/CCSkeletonCanvasRenderCmd.js +++ b/extensions/spine/CCSkeletonCanvasRenderCmd.js @@ -33,11 +33,29 @@ var proto = sp.Skeleton.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); proto.constructor = sp.Skeleton.CanvasRenderCmd; + proto._drawSkeleton = function(){ + + }; + proto.rendering = function (wrapper, scaleX, scaleY) { - var node = this._node, i, n, sprites = this._skeletonSprites, selSpriteCmd; + var node = this._node, i, n; wrapper = wrapper || cc._renderContext; - //draw skeleton sprite by it self + var locSkeleton = node._skeleton,color = node.getColor(); + locSkeleton.r = color.r / 255; + locSkeleton.g = color.g / 255; + locSkeleton.b = color.b / 255; + locSkeleton.a = this.getDisplayedOpacity() / 255; + if (node._premultipliedAlpha) { + locSkeleton.r *= locSkeleton.a; + locSkeleton.g *= locSkeleton.a; + locSkeleton.b *= locSkeleton.a; + } + + wrapper.setTransform(this._worldTransform, scaleX, scaleY); + wrapper.save(); + +/* //draw skeleton sprite by it self wrapper.save(); //set to armature mode (spine need same way to draw) wrapper._switchToArmatureMode(true, this._worldTransform, scaleX, scaleY); @@ -49,14 +67,24 @@ } } wrapper._switchToArmatureMode(false); + wrapper.restore();*/ + + //draw skeleton by itself. + var slot, attachment; + for (i = 0, n = locSkeleton.drawOrder.length; i < n; i++) { + slot = locSkeleton.drawOrder[i]; + if (!slot.attachment) + continue; + + attachment = slot.attachment; + var regionTextureAtlas = node.getTextureAtlas(attachment); + } wrapper.restore(); if (!node._debugSlots && !node._debugBones) return; - wrapper.setTransform(this._worldTransform, scaleX, scaleY); - var locSkeleton = node._skeleton; - var attachment, slot, drawingUtil = cc._drawingUtil; + var drawingUtil = cc._drawingUtil; if (node._debugSlots) { // Slots. drawingUtil.setDrawColor(0, 0, 255, 255); @@ -124,8 +152,9 @@ proto._updateChild = function(){ var node = this._node; - var locSkeleton = node._skeleton; + var locSkeleton = node._skeleton, locSkeletonSprites = this._skeletonSprites; locSkeleton.updateWorldTransform(); + locSkeletonSprites.length = 0; var drawOrder = node._skeleton.drawOrder; for (var i = 0, n = drawOrder.length; i < n; i++) { var slot = drawOrder[i]; @@ -135,17 +164,19 @@ selSprite.setVisible(false); continue; } + var rendererObject = attachment.rendererObject; + var rect = cc.rect(rendererObject.x, rendererObject.y, rendererObject.width,rendererObject.height); if(!selSprite){ - var rendererObject = attachment.rendererObject; - var rect = cc.rect(rendererObject.x, rendererObject.y, rendererObject.width,rendererObject.height); var sprite = new cc.Sprite(); - sprite.initWithTexture(rendererObject.page._texture, rect, rendererObject.rotate, false); - sprite._rect.width = attachment.width; - sprite._rect.height = attachment.height; - sprite.setContentSize(attachment.width, attachment.height); - this._skeletonSprites.push(sprite); + locSkeletonSprites.push(sprite); selSprite = slot.currentSprite = sprite; - } + }else + locSkeletonSprites.push(selSprite); + selSprite.initWithTexture(rendererObject.page._texture, rect, rendererObject.rotate, false); + selSprite.setContentSize(attachment.width, attachment.height); + selSprite._rect.width = attachment.width; + selSprite._rect.height = attachment.height; + selSprite.setVisible(true); //update color and blendFunc selSprite.setBlendFunc(cc.BLEND_SRC, slot.data.additiveBlending ? cc.ONE : cc.BLEND_DST); diff --git a/extensions/spine/CCSkeletonWebGLRenderCmd.js b/extensions/spine/CCSkeletonWebGLRenderCmd.js index 83c6aa93da..91bbff1145 100644 --- a/extensions/spine/CCSkeletonWebGLRenderCmd.js +++ b/extensions/spine/CCSkeletonWebGLRenderCmd.js @@ -27,13 +27,14 @@ cc.Node.WebGLRenderCmd.call(this, renderableObject); this._needDraw = true; this.setShaderProgram(cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURECOLOR)); + this._tmpQuad = new cc.V3F_C4B_T2F_Quad(); }; var proto = sp.Skeleton.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype); proto.constructor = sp.Skeleton.WebGLRenderCmd; proto.rendering = function (ctx) { - var node = this._node; + var node = this._node, tmpQuad = this._tmpQuad; this._shaderProgram.use(); this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix); // cc.glBlendFunc(this._blendFunc.src, this._blendFunc.dst); @@ -48,11 +49,11 @@ locSkeleton.b *= locSkeleton.a; } - var additive, textureAtlas, attachment, slot, i, n, - quad = new cc.V3F_C4B_T2F_Quad(); + var additive, textureAtlas, attachment, slot, i, n; var locBlendFunc = node._blendFunc; - for (i = 0, n = locSkeleton.slots.length; i < n; i++) { + //for (i = 0, n = locSkeleton.slots.length; i < n; i++) { + for (i = 0, n = locSkeleton.drawOrder.length; i < n; i++) { slot = locSkeleton.drawOrder[i]; if (!slot.attachment) continue; @@ -82,16 +83,16 @@ switch(slot.attachment.type) { case sp.ATTACHMENT_TYPE.REGION: - sp._regionAttachment_updateQuad(attachment, slot, quad, node._premultipliedAlpha); + sp._regionAttachment_updateQuad(attachment, slot, tmpQuad, node._premultipliedAlpha); break; case sp.ATTACHMENT_TYPE.MESH: - sp._meshAttachment_updateQuad(attachment, slot, quad, node._premultipliedAlpha); + sp._meshAttachment_updateQuad(attachment, slot, tmpQuad, node._premultipliedAlpha); break; case sp.ATTACHMENT_TYPE.SKINNED_MESH: break; } - textureAtlas.updateQuad(quad, quadCount); + textureAtlas.updateQuad(tmpQuad, quadCount); } if (textureAtlas) { @@ -104,7 +105,6 @@ //cc.kmGLPushMatrixWitMat4(this._stackMatrix); cc.current_stack.stack.push(cc.current_stack.top); cc.current_stack.top = this._stackMatrix; - var drawingUtil = cc._drawingUtil; if (node._debugSlots) { @@ -117,14 +117,13 @@ if (!slot.attachment || slot.attachment.type != sp.ATTACHMENT_TYPE.REGION) continue; attachment = slot.attachment; - quad = new cc.V3F_C4B_T2F_Quad(); - sp._regionAttachment_updateQuad(attachment, slot, quad); + sp._regionAttachment_updateQuad(attachment, slot, tmpQuad); var points = []; - points.push(cc.p(quad.bl.vertices.x, quad.bl.vertices.y)); - points.push(cc.p(quad.br.vertices.x, quad.br.vertices.y)); - points.push(cc.p(quad.tr.vertices.x, quad.tr.vertices.y)); - points.push(cc.p(quad.tl.vertices.x, quad.tl.vertices.y)); + points.push(cc.p(tmpQuad.bl.vertices.x, tmpQuad.bl.vertices.y)); + points.push(cc.p(tmpQuad.br.vertices.x, tmpQuad.br.vertices.y)); + points.push(cc.p(tmpQuad.tr.vertices.x, tmpQuad.tr.vertices.y)); + points.push(cc.p(tmpQuad.tl.vertices.x, tmpQuad.tl.vertices.y)); drawingUtil.drawPoly(points, 4, true); } @@ -155,7 +154,6 @@ } } } - cc.kmGLPopMatrix(); } }; diff --git a/template/project.json b/template/project.json index a4a9435aab..2db719e811 100644 --- a/template/project.json +++ b/template/project.json @@ -4,10 +4,10 @@ "showFPS" : true, "frameRate" : 60, "id" : "gameCanvas", - "renderMode" : 0, + "renderMode" : 1, "engineDir":"../", - "modules" : ["cocos2d"], + "modules" : ["cocos2d", "extensions"], "jsList" : [ "src/resource.js", diff --git a/template/src/myApp.js b/template/src/myApp.js index f91b7c40af..3794fac45e 100644 --- a/template/src/myApp.js +++ b/template/src/myApp.js @@ -44,6 +44,15 @@ var MyLayer = cc.Layer.extend({ this.sprite.setPosition(size.width / 2, size.height / 2); this.sprite.setScale(size.height / this.sprite.getContentSize().height); this.addChild(this.sprite, 0); + + var spineBoy = new sp.SkeletonAnimation('skeleton.json', 'skeleton.atlas'); + spineBoy.setPosition(cc.p(size.width / 2, size.height / 2 - 150)); + this.addChild(spineBoy, 10); + spineBoy.setAnimation(0, 'attack1', true); + spineBoy.setTimeScale(0.1); + //spineBoy.setDebugBonesEnabled(true); + spineBoy.setDebugSlotsEnabled(true); + window.spineBoy = spineBoy; } }); diff --git a/template/src/resource.js b/template/src/resource.js index 94284083d1..377ed46234 100644 --- a/template/src/resource.js +++ b/template/src/resource.js @@ -6,6 +6,9 @@ var g_resources = [ //image s_HelloWorld, s_CloseNormal, + "skeleton-1.png", + "skeleton.atlas", + "skeleton.json", s_CloseSelected //plist From 5c95cdd96af3c673cd160b0702bf9c7ea60404ad Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 7 Apr 2015 10:42:00 +0800 Subject: [PATCH 0129/1039] Formatting (#2810) --- cocos2d/core/CCScheduler.js | 27 +++++---------------------- 1 file changed, 5 insertions(+), 22 deletions(-) diff --git a/cocos2d/core/CCScheduler.js b/cocos2d/core/CCScheduler.js index 95e3208d2f..688726099e 100644 --- a/cocos2d/core/CCScheduler.js +++ b/cocos2d/core/CCScheduler.js @@ -739,16 +739,10 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ for(i=0; i= minPriority){ - this.unscheduleUpdate(entry.target); - } - } - + if(entry && entry.priority >= minPriority) + this.unscheduleUpdate(entry.target); if (temp_length == this._updatesNegList.length) - { i++; - } } } @@ -756,31 +750,20 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ for(i=0; i= minPriority) - { - this.unscheduleUpdate(entry.target); - } - } - + if(entry && entry.priority >= minPriority) + this.unscheduleUpdate(entry.target); if (temp_length == this._updatesPosList.length) - { i++; - } } }, From 5c112425e2461e24c7c14f3ee03865e343a8f075 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Tue, 7 Apr 2015 14:44:10 +0800 Subject: [PATCH 0130/1039] Fixed #2811: fixed a bug of cc.eventManager that its sorted order is incorrect when some nodes haven't add to scene graph or remove from parent without cleanup. --- cocos2d/core/event-manager/CCEventManager.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/event-manager/CCEventManager.js b/cocos2d/core/event-manager/CCEventManager.js index 84cabd26a4..46ba136659 100644 --- a/cocos2d/core/event-manager/CCEventManager.js +++ b/cocos2d/core/event-manager/CCEventManager.js @@ -311,8 +311,9 @@ cc.eventManager = /** @lends cc.eventManager# */{ }, _sortEventListenersOfSceneGraphPriorityDes : function(l1, l2){ - var locNodePriorityMap = cc.eventManager._nodePriorityMap; - if(!l1 || !l2 || !l1._getSceneGraphPriority() || !l2._getSceneGraphPriority()) + var locNodePriorityMap = cc.eventManager._nodePriorityMap, node1 = l1._getSceneGraphPriority(), + node2 = l2._getSceneGraphPriority(); + if(!l1 || !l2 || !node1 || !node2 || !locNodePriorityMap[node1.__instanceId] || !locNodePriorityMap[node2.__instanceId]) return -1; return locNodePriorityMap[l2._getSceneGraphPriority().__instanceId] - locNodePriorityMap[l1._getSceneGraphPriority().__instanceId]; }, From bab3a57a19ef00b3d8b9147b4bc147bdab6b8fb8 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 7 Apr 2015 15:58:39 +0800 Subject: [PATCH 0131/1039] Add notes for CCSprite.js --- cocos2d/core/sprites/CCSprite.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/sprites/CCSprite.js b/cocos2d/core/sprites/CCSprite.js index 48acbb4fa6..a21206b5fe 100644 --- a/cocos2d/core/sprites/CCSprite.js +++ b/cocos2d/core/sprites/CCSprite.js @@ -558,7 +558,10 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ // Init with a sprite frame name var frameName = fileName.substr(1, fileName.length - 1); var spriteFrame = cc.spriteFrameCache.getSpriteFrame(frameName); - this.initWithSpriteFrame(spriteFrame); + if(spriteFrame) + this.initWithSpriteFrame(spriteFrame); + else + cc.log("%s does not exist", fileName); } else { // Init with filename and rect cc.Sprite.prototype.init.call(this, fileName, rect); From a05860d55f995f5052bddf3f987dee32805332cd Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 7 Apr 2015 16:03:43 +0800 Subject: [PATCH 0132/1039] Add notes for CCSprite.js --- cocos2d/core/sprites/CCSprite.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/cocos2d/core/sprites/CCSprite.js b/cocos2d/core/sprites/CCSprite.js index a21206b5fe..810d7392a3 100644 --- a/cocos2d/core/sprites/CCSprite.js +++ b/cocos2d/core/sprites/CCSprite.js @@ -558,10 +558,10 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ // Init with a sprite frame name var frameName = fileName.substr(1, fileName.length - 1); var spriteFrame = cc.spriteFrameCache.getSpriteFrame(frameName); - if(spriteFrame) - this.initWithSpriteFrame(spriteFrame); - else - cc.log("%s does not exist", fileName); + if (spriteFrame) + this.initWithSpriteFrame(spriteFrame); + else + cc.log("%s does not exist", fileName); } else { // Init with filename and rect cc.Sprite.prototype.init.call(this, fileName, rect); From bfaa8a1542a77ea1f69e8630fce9c3c1533f61fe Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 8 Apr 2015 14:55:52 +0800 Subject: [PATCH 0133/1039] Fix a bug that is pause has stopped audio can be resume. --- cocos2d/audio/CCAudio.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index b55a04c309..4a8296e365 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -356,6 +356,8 @@ cc.Audio = cc.Class.extend({ }, pause: function(){ + if(this.getPlaying() === false) + return; this._playing = false; this._pause = true; if(this._AUDIO_TYPE === "AUDIO"){ From 6301dad4bc296a79765a3e8499f9b54f287f2720 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 8 Apr 2015 17:28:41 +0800 Subject: [PATCH 0134/1039] Fixed a bug that is isObject error --- cocos2d/core/sprites/CCSprite.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/sprites/CCSprite.js b/cocos2d/core/sprites/CCSprite.js index 810d7392a3..cf138f0633 100644 --- a/cocos2d/core/sprites/CCSprite.js +++ b/cocos2d/core/sprites/CCSprite.js @@ -566,7 +566,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ // Init with filename and rect cc.Sprite.prototype.init.call(this, fileName, rect); } - } else if (cc.isObject(fileName)) { + } else if (typeof fileName === "object") { if (fileName instanceof cc.Texture2D) { // Init with texture and rect this.initWithTexture(fileName, rect, rotated); From cf6c8111aae01ffff1c81c6c64c81ab43da01679 Mon Sep 17 00:00:00 2001 From: Igor Mats Date: Wed, 8 Apr 2015 21:45:17 +0300 Subject: [PATCH 0135/1039] Add setStroke method. --- cocos2d/motion-streak/CCMotionStreak.js | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/cocos2d/motion-streak/CCMotionStreak.js b/cocos2d/motion-streak/CCMotionStreak.js index 13c66a0f28..3add251835 100644 --- a/cocos2d/motion-streak/CCMotionStreak.js +++ b/cocos2d/motion-streak/CCMotionStreak.js @@ -222,6 +222,14 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ this.startingPositionInitialized = startingPositionInitialized; }, + /** + * Set stroke. + * @param {Number} stroke + */ + setStroke:function (stroke) { + this._stroke = stroke; + }, + /** * initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture filename or texture * @param {Number} fade time to fade From 4469edb558dd2a2d800006d8078c0a1211d3db62 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Thu, 9 Apr 2015 12:02:37 +0800 Subject: [PATCH 0136/1039] Issue #2806: refactor cc.SkeletonCanvasRenderCmd --- extensions/spine/CCSkeleton.js | 16 ++- extensions/spine/CCSkeletonAnimation.js | 112 ------------------ extensions/spine/CCSkeletonCanvasRenderCmd.js | 92 ++++++++++---- extensions/spine/CCSkeletonWebGLRenderCmd.js | 85 ++++++++++++- extensions/spine/Spine.js | 4 +- template/src/myApp.js | 2 +- template/src/resource.js | 2 +- 7 files changed, 167 insertions(+), 146 deletions(-) diff --git a/extensions/spine/CCSkeleton.js b/extensions/spine/CCSkeleton.js index a3c7b402b4..a0132b0f43 100644 --- a/extensions/spine/CCSkeleton.js +++ b/extensions/spine/CCSkeleton.js @@ -221,7 +221,7 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ if (!slot.attachment || slot.attachment.type != sp.ATTACHMENT_TYPE.REGION) continue; var attachment = slot.attachment; - sp._regionAttachment_computeWorldVertices(attachment, slot.bone.skeleton.x, slot.bone.skeleton.y, slot.bone, vertices); + this._computeRegionAttachmentWorldVertices(attachment, slot.bone.skeleton.x, slot.bone.skeleton.y, slot.bone, vertices); minX = Math.min(minX, vertices[VERTEX.X1] * scaleX, vertices[VERTEX.X4] * scaleX, vertices[VERTEX.X2] * scaleX, vertices[VERTEX.X3] * scaleX); minY = Math.min(minY, vertices[VERTEX.Y1] * scaleY, vertices[VERTEX.Y4] * scaleY, vertices[VERTEX.Y2] * scaleY, vertices[VERTEX.Y3] * scaleY); maxX = Math.max(maxX, vertices[VERTEX.X1] * scaleX, vertices[VERTEX.X4] * scaleX, vertices[VERTEX.X2] * scaleX, vertices[VERTEX.X3] * scaleX); @@ -231,6 +231,20 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ return cc.rect(position.x + minX, position.y + minY, maxX - minX, maxY - minY); }, + _computeRegionAttachmentWorldVertices : function(self, x, y, bone, vertices){ + var offset = self.offset, vertexIndex = sp.VERTEX_INDEX; + x += bone.worldX; + y += bone.worldY; + vertices[vertexIndex.X1] = offset[vertexIndex.X1] * bone.m00 + offset[vertexIndex.Y1] * bone.m01 + x; + vertices[vertexIndex.Y1] = offset[vertexIndex.X1] * bone.m10 + offset[vertexIndex.Y1] * bone.m11 + y; + vertices[vertexIndex.X2] = offset[vertexIndex.X2] * bone.m00 + offset[vertexIndex.Y2] * bone.m01 + x; + vertices[vertexIndex.Y2] = offset[vertexIndex.X2] * bone.m10 + offset[vertexIndex.Y2] * bone.m11 + y; + vertices[vertexIndex.X3] = offset[vertexIndex.X3] * bone.m00 + offset[vertexIndex.Y3] * bone.m01 + x; + vertices[vertexIndex.Y3] = offset[vertexIndex.X3] * bone.m10 + offset[vertexIndex.Y3] * bone.m11 + y; + vertices[vertexIndex.X4] = offset[vertexIndex.X4] * bone.m00 + offset[vertexIndex.Y4] * bone.m01 + x; + vertices[vertexIndex.Y4] = offset[vertexIndex.X4] * bone.m10 + offset[vertexIndex.Y4] * bone.m11 + y; + }, + /** * Computes the world SRT from the local SRT for each bone. */ diff --git a/extensions/spine/CCSkeletonAnimation.js b/extensions/spine/CCSkeletonAnimation.js index ef844c83fe..e60465ec30 100644 --- a/extensions/spine/CCSkeletonAnimation.js +++ b/extensions/spine/CCSkeletonAnimation.js @@ -58,118 +58,6 @@ sp._atlasLoader = { } }; -sp._regionAttachment_computeWorldVertices = function(self, x, y, bone, vertices){ - var offset = self.offset; - x += bone.worldX; - y += bone.worldY; - var vertexIndex = sp.VERTEX_INDEX; - vertices[vertexIndex.X1] = offset[vertexIndex.X1] * bone.m00 + offset[vertexIndex.Y1] * bone.m01 + x; - vertices[vertexIndex.Y1] = offset[vertexIndex.X1] * bone.m10 + offset[vertexIndex.Y1] * bone.m11 + y; - vertices[vertexIndex.X2] = offset[vertexIndex.X2] * bone.m00 + offset[vertexIndex.Y2] * bone.m01 + x; - vertices[vertexIndex.Y2] = offset[vertexIndex.X2] * bone.m10 + offset[vertexIndex.Y2] * bone.m11 + y; - vertices[vertexIndex.X3] = offset[vertexIndex.X3] * bone.m00 + offset[vertexIndex.Y3] * bone.m01 + x; - vertices[vertexIndex.Y3] = offset[vertexIndex.X3] * bone.m10 + offset[vertexIndex.Y3] * bone.m11 + y; - vertices[vertexIndex.X4] = offset[vertexIndex.X4] * bone.m00 + offset[vertexIndex.Y4] * bone.m01 + x; - vertices[vertexIndex.Y4] = offset[vertexIndex.X4] * bone.m10 + offset[vertexIndex.Y4] * bone.m11 + y; -}; - -/*cc._spCallback = function(state, trackIndex, type,event, loopCount){ - state.context.onAnimationStateEvent(trackIndex, type, event, loopCount); - };*/ - -sp._regionAttachment_updateQuad = function(self, slot, quad, premultipliedAlpha) { - var vertices = {}; - self.computeVertices(slot.bone.skeleton.x, slot.bone.skeleton.y, slot.bone, vertices); - var r = slot.bone.skeleton.r * slot.r * 255; - var g = slot.bone.skeleton.g * slot.g * 255; - var b = slot.bone.skeleton.b * slot.b * 255; - var normalizedAlpha = slot.bone.skeleton.a * slot.a; - - if (premultipliedAlpha) { - r *= normalizedAlpha; - g *= normalizedAlpha; - b *= normalizedAlpha; - } - var a = normalizedAlpha * 255; - - quad.bl.colors.r = quad.tl.colors.r = quad.tr.colors.r = quad.br.colors.r = r; - quad.bl.colors.g = quad.tl.colors.g = quad.tr.colors.g = quad.br.colors.g = g; - quad.bl.colors.b = quad.tl.colors.b = quad.tr.colors.b = quad.br.colors.b = b; - quad.bl.colors.a = quad.tl.colors.a = quad.tr.colors.a = quad.br.colors.a = a; - - var VERTEX = sp.VERTEX_INDEX; - quad.bl.vertices.x = vertices[VERTEX.X1]; - quad.bl.vertices.y = vertices[VERTEX.Y1]; - quad.tl.vertices.x = vertices[VERTEX.X2]; - quad.tl.vertices.y = vertices[VERTEX.Y2]; - quad.tr.vertices.x = vertices[VERTEX.X3]; - quad.tr.vertices.y = vertices[VERTEX.Y3]; - quad.br.vertices.x = vertices[VERTEX.X4]; - quad.br.vertices.y = vertices[VERTEX.Y4]; - - quad.bl.texCoords.u = self.uvs[VERTEX.X1]; - quad.bl.texCoords.v = self.uvs[VERTEX.Y1]; - quad.tl.texCoords.u = self.uvs[VERTEX.X2]; - quad.tl.texCoords.v = self.uvs[VERTEX.Y2]; - quad.tr.texCoords.u = self.uvs[VERTEX.X3]; - quad.tr.texCoords.v = self.uvs[VERTEX.Y3]; - quad.br.texCoords.u = self.uvs[VERTEX.X4]; - quad.br.texCoords.v = self.uvs[VERTEX.Y4]; -}; - -sp._meshAttachment_updateQuad = function(self, slot, quad, premultipliedAlpha) { - var vertices = {}; - self.computeWorldVertices(slot.bone.x, slot.bone.y, slot, vertices); - var r = slot.bone.skeleton.r * slot.r * 255; - var g = slot.bone.skeleton.g * slot.g * 255; - var b = slot.bone.skeleton.b * slot.b * 255; - var normalizedAlpha = slot.bone.skeleton.a * slot.a; - if (premultipliedAlpha) { - r *= normalizedAlpha; - g *= normalizedAlpha; - b *= normalizedAlpha; - } - var a = normalizedAlpha * 255; - - quad.bl.colors.r = quad.tl.colors.r = quad.tr.colors.r = quad.br.colors.r = r; - quad.bl.colors.g = quad.tl.colors.g = quad.tr.colors.g = quad.br.colors.g = g; - quad.bl.colors.b = quad.tl.colors.b = quad.tr.colors.b = quad.br.colors.b = b; - quad.bl.colors.a = quad.tl.colors.a = quad.tr.colors.a = quad.br.colors.a = a; - - var VERTEX = sp.VERTEX_INDEX; - quad.bl.vertices.x = vertices[VERTEX.X1]; - quad.bl.vertices.y = vertices[VERTEX.Y1]; - quad.tl.vertices.x = vertices[VERTEX.X2]; - quad.tl.vertices.y = vertices[VERTEX.Y2]; - quad.tr.vertices.x = vertices[VERTEX.X3]; - quad.tr.vertices.y = vertices[VERTEX.Y3]; - quad.br.vertices.x = vertices[VERTEX.X4]; - quad.br.vertices.y = vertices[VERTEX.Y4]; - - quad.bl.texCoords.u = self.uvs[VERTEX.X1]; - quad.bl.texCoords.v = self.uvs[VERTEX.Y1]; - quad.tl.texCoords.u = self.uvs[VERTEX.X2]; - quad.tl.texCoords.v = self.uvs[VERTEX.Y2]; - quad.tr.texCoords.u = self.uvs[VERTEX.X3]; - quad.tr.texCoords.v = self.uvs[VERTEX.Y3]; - quad.br.texCoords.u = self.uvs[VERTEX.X4]; - quad.br.texCoords.v = self.uvs[VERTEX.Y4]; -}; - -sp._regionAttachment_updateSlotForCanvas = function(self, slot, points) { - if(!points) - return; - - var vertices = {}; - self.computeVertices(slot.bone.skeleton.x, slot.bone.skeleton.y, slot.bone, vertices); - var VERTEX = sp.VERTEX_INDEX; - points.length = 0; - points.push(cc.p(vertices[VERTEX.X1], vertices[VERTEX.Y1])); - points.push(cc.p(vertices[VERTEX.X4], vertices[VERTEX.Y4])); - points.push(cc.p(vertices[VERTEX.X3], vertices[VERTEX.Y3])); - points.push(cc.p(vertices[VERTEX.X2], vertices[VERTEX.Y2])); -}; - /** * The event type of spine skeleton animation. It contains event types: START(0), END(1), COMPLETE(2), EVENT(3). * @constant diff --git a/extensions/spine/CCSkeletonCanvasRenderCmd.js b/extensions/spine/CCSkeletonCanvasRenderCmd.js index 5833881bc1..b27ee8ae10 100644 --- a/extensions/spine/CCSkeletonCanvasRenderCmd.js +++ b/extensions/spine/CCSkeletonCanvasRenderCmd.js @@ -33,13 +33,10 @@ var proto = sp.Skeleton.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); proto.constructor = sp.Skeleton.CanvasRenderCmd; - proto._drawSkeleton = function(){ - - }; - proto.rendering = function (wrapper, scaleX, scaleY) { var node = this._node, i, n; wrapper = wrapper || cc._renderContext; + var context = wrapper.getContext(); var locSkeleton = node._skeleton,color = node.getColor(); locSkeleton.r = color.r / 255; @@ -52,16 +49,43 @@ locSkeleton.b *= locSkeleton.a; } - wrapper.setTransform(this._worldTransform, scaleX, scaleY); - wrapper.save(); + /*wrapper.setTransform(this._worldTransform, scaleX, scaleY); + context.save(); + //draw skeleton by itself. + var slot, attachment, selTexture, selBone, rendererObject; + for (i = 0, n = locSkeleton.drawOrder.length; i < n; i++) { + slot = locSkeleton.drawOrder[i]; + if (!slot.attachment) + continue; -/* //draw skeleton sprite by it self - wrapper.save(); + attachment = slot.attachment; + rendererObject = attachment.rendererObject; + selTexture = rendererObject.page._texture; + if(!selTexture || !selTexture._textureLoaded || !slot.bone) + continue; + + selBone = slot.bone; + //context.transform(selBone.m00, selBone.m01, selBone.m10, selBone.m11, selBone.worldX, selBone.worldY); + context.translate(selBone.worldX, selBone.worldY); + context.scale(selBone.worldScaleX, selBone.worldScaleY); + console.log(selBone); + context.rotate(selBone.worldRotation); + context.drawImage(selTexture._htmlElementObj, + rendererObject.x, rendererObject.y, rendererObject.width, rendererObject.height, + //locX * scaleX, locY * scaleY, locWidth * scaleX, locHeight * scaleY); + 0, 0, rendererObject.width * scaleX, rendererObject.height * scaleY); + + } + context.restore();*/ + + //draw skeleton sprite by it self +/* wrapper.save(); //set to armature mode (spine need same way to draw) wrapper._switchToArmatureMode(true, this._worldTransform, scaleX, scaleY); - for(i = 0, n = sprites.length; i < n; i++){ + var sprites = this._skeletonSprites, slot, selSpriteCmd,attachment; + for (i = 0, n = sprites.length; i < n; i++) { selSpriteCmd = sprites[i]._renderCmd; - if(sprites[i]._visible && selSpriteCmd && selSpriteCmd.rendering){ + if (sprites[i]._visible && selSpriteCmd && selSpriteCmd.rendering) { selSpriteCmd.rendering(wrapper, scaleX, scaleY); selSpriteCmd._dirtyFlag = 0; } @@ -69,21 +93,20 @@ wrapper._switchToArmatureMode(false); wrapper.restore();*/ - //draw skeleton by itself. - var slot, attachment; - for (i = 0, n = locSkeleton.drawOrder.length; i < n; i++) { - slot = locSkeleton.drawOrder[i]; - if (!slot.attachment) - continue; - - attachment = slot.attachment; - var regionTextureAtlas = node.getTextureAtlas(attachment); + //set to armature mode (spine need same way to draw) + var sprites = this._skeletonSprites, slot, selSpriteCmd,attachment; + for (i = 0, n = sprites.length; i < n; i++) { + selSpriteCmd = sprites[i]._renderCmd; + if (sprites[i]._visible && selSpriteCmd && selSpriteCmd.rendering) { + selSpriteCmd.transform(this, false); + selSpriteCmd.rendering(wrapper, scaleX, scaleY); + selSpriteCmd._dirtyFlag = 0; + } } - wrapper.restore(); if (!node._debugSlots && !node._debugBones) return; - + wrapper.setTransform(this._worldTransform, scaleX, scaleY); var drawingUtil = cc._drawingUtil; if (node._debugSlots) { // Slots. @@ -91,12 +114,14 @@ drawingUtil.setLineWidth(1); var points = []; - for (i = 0, n = locSkeleton.slots.length; i < n; i++) { + var drawOrder = node._skeleton.drawOrder; + for (i = 0, n = drawOrder.length; i < n; i++) { + //for (i = 0, n = locSkeleton.slots.length; i < n; i++) { slot = locSkeleton.drawOrder[i]; if (!slot.attachment || slot.attachment.type != sp.ATTACHMENT_TYPE.REGION) continue; attachment = slot.attachment; - sp._regionAttachment_updateSlotForCanvas(attachment, slot, points); + this._updateRegionAttachmentSlot(attachment, slot, points); drawingUtil.drawPoly(points, 4, true); } } @@ -129,6 +154,19 @@ } }; + proto._updateRegionAttachmentSlot = function(attachment, slot, points) { + if(!points) + return; + + var vertices = {}, VERTEX = sp.VERTEX_INDEX, bone = slot.bone; + attachment.computeVertices(bone.skeleton.x, bone.skeleton.y, bone, vertices); + points.length = 0; + points.push(cc.p(vertices[VERTEX.X1], vertices[VERTEX.Y1])); + points.push(cc.p(vertices[VERTEX.X4], vertices[VERTEX.Y4])); + points.push(cc.p(vertices[VERTEX.X3], vertices[VERTEX.Y3])); + points.push(cc.p(vertices[VERTEX.X2], vertices[VERTEX.Y2])); + }; + proto._createChildFormSkeletonData = function(){ var node = this._node; var locSkeleton = node._skeleton, rendererObject, rect; @@ -182,11 +220,13 @@ selSprite.setBlendFunc(cc.BLEND_SRC, slot.data.additiveBlending ? cc.ONE : cc.BLEND_DST); var bone = slot.bone; - selSprite.setPosition(bone.worldX + attachment.x * bone.m00 + attachment.y * bone.m01, - bone.worldY + attachment.x * bone.m10 + attachment.y * bone.m11); + selSprite.setPosition(bone.worldX, bone.worldY); selSprite.setScale(bone.worldScaleX, bone.worldScaleY); - selSprite.setRotation(-(slot.bone.worldRotation + attachment.rotation)); + //selSprite.setRotation(-(slot.bone.worldRotation + attachment.rotation)); + selSprite.setRotation(-bone.worldRotation); selSprite.setOpacity(0 | (node._skeleton.a * slot.a * 255)); + selSprite.setFlippedX(bone.flipX); + selSprite.setFlippedY(bone.flipY); var r = 0 | (node._skeleton.r * slot.r * 255); var g = 0 | (node._skeleton.g * slot.g * 255); var b = 0 | (node._skeleton.b * slot.b * 255); diff --git a/extensions/spine/CCSkeletonWebGLRenderCmd.js b/extensions/spine/CCSkeletonWebGLRenderCmd.js index 91bbff1145..4aa0c4b93d 100644 --- a/extensions/spine/CCSkeletonWebGLRenderCmd.js +++ b/extensions/spine/CCSkeletonWebGLRenderCmd.js @@ -83,10 +83,10 @@ switch(slot.attachment.type) { case sp.ATTACHMENT_TYPE.REGION: - sp._regionAttachment_updateQuad(attachment, slot, tmpQuad, node._premultipliedAlpha); + this._updateRegionAttachmentQuad(attachment, slot, tmpQuad, node._premultipliedAlpha); break; case sp.ATTACHMENT_TYPE.MESH: - sp._meshAttachment_updateQuad(attachment, slot, tmpQuad, node._premultipliedAlpha); + this._updateMeshAttachmentQuad(attachment, slot, tmpQuad, node._premultipliedAlpha); break; case sp.ATTACHMENT_TYPE.SKINNED_MESH: break; @@ -117,7 +117,7 @@ if (!slot.attachment || slot.attachment.type != sp.ATTACHMENT_TYPE.REGION) continue; attachment = slot.attachment; - sp._regionAttachment_updateQuad(attachment, slot, tmpQuad); + this._updateRegionAttachmentQuad(attachment, slot, tmpQuad); var points = []; points.push(cc.p(tmpQuad.bl.vertices.x, tmpQuad.bl.vertices.y)); @@ -161,4 +161,83 @@ proto._createChildFormSkeletonData = function(){}; proto._updateChild = function(){}; + + proto._updateRegionAttachmentQuad = function(self, slot, quad, premultipliedAlpha) { + var vertices = {}; + self.computeVertices(slot.bone.skeleton.x, slot.bone.skeleton.y, slot.bone, vertices); + var r = slot.bone.skeleton.r * slot.r * 255; + var g = slot.bone.skeleton.g * slot.g * 255; + var b = slot.bone.skeleton.b * slot.b * 255; + var normalizedAlpha = slot.bone.skeleton.a * slot.a; + + if (premultipliedAlpha) { + r *= normalizedAlpha; + g *= normalizedAlpha; + b *= normalizedAlpha; + } + var a = normalizedAlpha * 255; + + quad.bl.colors.r = quad.tl.colors.r = quad.tr.colors.r = quad.br.colors.r = r; + quad.bl.colors.g = quad.tl.colors.g = quad.tr.colors.g = quad.br.colors.g = g; + quad.bl.colors.b = quad.tl.colors.b = quad.tr.colors.b = quad.br.colors.b = b; + quad.bl.colors.a = quad.tl.colors.a = quad.tr.colors.a = quad.br.colors.a = a; + + var VERTEX = sp.VERTEX_INDEX; + quad.bl.vertices.x = vertices[VERTEX.X1]; + quad.bl.vertices.y = vertices[VERTEX.Y1]; + quad.tl.vertices.x = vertices[VERTEX.X2]; + quad.tl.vertices.y = vertices[VERTEX.Y2]; + quad.tr.vertices.x = vertices[VERTEX.X3]; + quad.tr.vertices.y = vertices[VERTEX.Y3]; + quad.br.vertices.x = vertices[VERTEX.X4]; + quad.br.vertices.y = vertices[VERTEX.Y4]; + + quad.bl.texCoords.u = self.uvs[VERTEX.X1]; + quad.bl.texCoords.v = self.uvs[VERTEX.Y1]; + quad.tl.texCoords.u = self.uvs[VERTEX.X2]; + quad.tl.texCoords.v = self.uvs[VERTEX.Y2]; + quad.tr.texCoords.u = self.uvs[VERTEX.X3]; + quad.tr.texCoords.v = self.uvs[VERTEX.Y3]; + quad.br.texCoords.u = self.uvs[VERTEX.X4]; + quad.br.texCoords.v = self.uvs[VERTEX.Y4]; + }; + + proto._updateMeshAttachmentQuad = function(self, slot, quad, premultipliedAlpha) { + var vertices = {}; + self.computeWorldVertices(slot.bone.x, slot.bone.y, slot, vertices); + var r = slot.bone.skeleton.r * slot.r * 255; + var g = slot.bone.skeleton.g * slot.g * 255; + var b = slot.bone.skeleton.b * slot.b * 255; + var normalizedAlpha = slot.bone.skeleton.a * slot.a; + if (premultipliedAlpha) { + r *= normalizedAlpha; + g *= normalizedAlpha; + b *= normalizedAlpha; + } + var a = normalizedAlpha * 255; + + quad.bl.colors.r = quad.tl.colors.r = quad.tr.colors.r = quad.br.colors.r = r; + quad.bl.colors.g = quad.tl.colors.g = quad.tr.colors.g = quad.br.colors.g = g; + quad.bl.colors.b = quad.tl.colors.b = quad.tr.colors.b = quad.br.colors.b = b; + quad.bl.colors.a = quad.tl.colors.a = quad.tr.colors.a = quad.br.colors.a = a; + + var VERTEX = sp.VERTEX_INDEX; + quad.bl.vertices.x = vertices[VERTEX.X1]; + quad.bl.vertices.y = vertices[VERTEX.Y1]; + quad.tl.vertices.x = vertices[VERTEX.X2]; + quad.tl.vertices.y = vertices[VERTEX.Y2]; + quad.tr.vertices.x = vertices[VERTEX.X3]; + quad.tr.vertices.y = vertices[VERTEX.Y3]; + quad.br.vertices.x = vertices[VERTEX.X4]; + quad.br.vertices.y = vertices[VERTEX.Y4]; + + quad.bl.texCoords.u = self.uvs[VERTEX.X1]; + quad.bl.texCoords.v = self.uvs[VERTEX.Y1]; + quad.tl.texCoords.u = self.uvs[VERTEX.X2]; + quad.tl.texCoords.v = self.uvs[VERTEX.Y2]; + quad.tr.texCoords.u = self.uvs[VERTEX.X3]; + quad.tr.texCoords.v = self.uvs[VERTEX.Y3]; + quad.br.texCoords.u = self.uvs[VERTEX.X4]; + quad.br.texCoords.v = self.uvs[VERTEX.Y4]; + }; })(); \ No newline at end of file diff --git a/extensions/spine/Spine.js b/extensions/spine/Spine.js index e29bca57d0..7a25bab80e 100644 --- a/extensions/spine/Spine.js +++ b/extensions/spine/Spine.js @@ -887,7 +887,7 @@ spine.FlipXTimeline.prototype = { lastTime = -1; var frameIndex = (time >= frames[frames.length - 2] ? frames.length : spine.Animation.binarySearch(frames, time, 2)) - 2; if (frames[frameIndex] < lastTime) return; - skeleton.bones[boneIndex].flipX = frames[frameIndex + 1] != 0; + skeleton.bones[this.boneIndex].flipX = frames[frameIndex + 1] != 0; } }; @@ -915,7 +915,7 @@ spine.FlipYTimeline.prototype = { lastTime = -1; var frameIndex = (time >= frames[frames.length - 2] ? frames.length : spine.Animation.binarySearch(frames, time, 2)) - 2; if (frames[frameIndex] < lastTime) return; - skeleton.bones[boneIndex].flipY = frames[frameIndex + 1] != 0; + skeleton.bones[this.boneIndex].flipY = frames[frameIndex + 1] != 0; } }; diff --git a/template/src/myApp.js b/template/src/myApp.js index 3794fac45e..16ad0863c0 100644 --- a/template/src/myApp.js +++ b/template/src/myApp.js @@ -48,7 +48,7 @@ var MyLayer = cc.Layer.extend({ var spineBoy = new sp.SkeletonAnimation('skeleton.json', 'skeleton.atlas'); spineBoy.setPosition(cc.p(size.width / 2, size.height / 2 - 150)); this.addChild(spineBoy, 10); - spineBoy.setAnimation(0, 'attack1', true); + spineBoy.setAnimation(0, 'attack5', true); spineBoy.setTimeScale(0.1); //spineBoy.setDebugBonesEnabled(true); spineBoy.setDebugSlotsEnabled(true); diff --git a/template/src/resource.js b/template/src/resource.js index 377ed46234..f9016890a0 100644 --- a/template/src/resource.js +++ b/template/src/resource.js @@ -6,7 +6,7 @@ var g_resources = [ //image s_HelloWorld, s_CloseNormal, - "skeleton-1.png", + "skeleton.png", "skeleton.atlas", "skeleton.json", s_CloseSelected From cdb52adcd6c08ae52ff15ee82619d27f00eeaff3 Mon Sep 17 00:00:00 2001 From: jianglong0156 Date: Thu, 9 Apr 2015 15:27:28 +0800 Subject: [PATCH 0137/1039] add clone positionType --- cocos2d/particle/CCParticleSystem.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cocos2d/particle/CCParticleSystem.js b/cocos2d/particle/CCParticleSystem.js index 1c3a310adf..7136f5335e 100644 --- a/cocos2d/particle/CCParticleSystem.js +++ b/cocos2d/particle/CCParticleSystem.js @@ -1938,6 +1938,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ retParticle.setPosition(cc.p(this.x, this.y)); retParticle.setPosVar(cc.p(this.getPosVar().x,this.getPosVar().y)); + retParticle.setPositionType(this.getPositionType()); + // Spinning retParticle.setStartSpin(this.getStartSpin()||0); retParticle.setStartSpinVar(this.getStartSpinVar()||0); From 1e97cce80e4efa7b2a0fe5db87f315e13fc511ca Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 9 Apr 2015 15:42:55 +0800 Subject: [PATCH 0138/1039] Fix undefined parameter check in CCNode --- cocos2d/core/base-nodes/CCNode.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index 8222e5c042..50af27bddc 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -1304,7 +1304,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ */ removeFromParent: function (cleanup) { if (this._parent) { - if (cleanup == null) + if (cleanup === undefined) cleanup = true; this._parent.removeChild(this, cleanup); } @@ -1335,7 +1335,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ if (this._children.length === 0) return; - if (cleanup == null) + if (cleanup === undefined) cleanup = true; if (this._children.indexOf(child) > -1) this._detachChild(child, cleanup); @@ -1357,7 +1357,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ cc.log(cc._LogInfos.Node_removeChildByTag); var child = this.getChildByTag(tag); - if (child == null) + if (!child) cc.log(cc._LogInfos.Node_removeChildByTag_2, tag); else this.removeChild(child, cleanup); @@ -1381,7 +1381,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ // not using detachChild improves speed here var __children = this._children; if (__children !== null) { - if (cleanup == null) + if (cleanup === undefined) cleanup = true; for (var i = 0; i < __children.length; i++) { var node = __children[i]; @@ -1869,7 +1869,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * spriteB.setAdditionalTransform(t); */ setAdditionalTransform: function (additionalTransform) { - if(additionalTransform == null) + if(additionalTransform === undefined) return this._additionalTransformDirty = false; this._additionalTransform = additionalTransform; this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty); @@ -2255,7 +2255,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ _getBoundingBoxToCurrentNode: function (parentTransform) { var rect = cc.rect(0, 0, this._contentSize.width, this._contentSize.height); - var trans = (parentTransform == null) ? this.getNodeToParentTransform() : cc.affineTransformConcat(this.getNodeToParentTransform(), parentTransform); + var trans = (parentTransform === undefined) ? this.getNodeToParentTransform() : cc.affineTransformConcat(this.getNodeToParentTransform(), parentTransform); rect = cc.rectApplyAffineTransform(rect, trans); //query child's BoundingBox From 969f865d616765df76eb407fcf6db6fafb793fb5 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 9 Apr 2015 16:07:34 +0800 Subject: [PATCH 0139/1039] To prevent the object does not exist error --- extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js | 2 ++ extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js | 2 ++ extensions/ccui/layouts/UILayoutWebGLRenderCmd.js | 2 ++ extensions/cocostudio/armature/CCBone.js | 2 ++ 4 files changed, 8 insertions(+) diff --git a/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js b/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js index bcac0b4834..0074027217 100644 --- a/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js +++ b/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js @@ -23,6 +23,8 @@ ****************************************************************************/ (function(){ + if(!cc.Node.WebGLRenderCmd) + return; cc.ProtectedNode.WebGLRenderCmd = function (renderable) { cc.Node.WebGLRenderCmd.call(this, renderable); }; diff --git a/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js b/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js index 8b8949d82f..dc0c477997 100644 --- a/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js +++ b/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js @@ -23,6 +23,8 @@ ****************************************************************************/ (function() { + if(!cc.Node.WebGLRenderCmd) + return; ccui.Scale9Sprite.WebGLRenderCmd = function (renderable) { cc.Node.WebGLRenderCmd.call(this, renderable); this._cachedParent = null; diff --git a/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js b/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js index d46e1e8939..baf4773fca 100644 --- a/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js +++ b/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js @@ -24,6 +24,8 @@ ****************************************************************************/ (function(){ + if(!ccui.ProtectedNode.WebGLRenderCmd) + return; ccui.Layout.WebGLRenderCmd = function(renderable){ ccui.ProtectedNode.WebGLRenderCmd.call(this, renderable); this._needDraw = false; diff --git a/extensions/cocostudio/armature/CCBone.js b/extensions/cocostudio/armature/CCBone.js index 071ea83170..32f12553f5 100644 --- a/extensions/cocostudio/armature/CCBone.js +++ b/extensions/cocostudio/armature/CCBone.js @@ -700,6 +700,8 @@ ccs.Bone.RenderCmd = { })(); (function(){ + if(!cc.Node.WebGLRenderCmd) + return; ccs.Bone.WebGLRenderCmd = function(renderable){ cc.Node.WebGLRenderCmd.call(this, renderable); this._needDraw = false; From 40588d0ab9a75609462ea5d04fab984a2524381a Mon Sep 17 00:00:00 2001 From: Igor Mats Date: Thu, 9 Apr 2015 12:03:52 +0300 Subject: [PATCH 0140/1039] Add getStroke method. --- cocos2d/motion-streak/CCMotionStreak.js | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/cocos2d/motion-streak/CCMotionStreak.js b/cocos2d/motion-streak/CCMotionStreak.js index 3add251835..85b43531dd 100644 --- a/cocos2d/motion-streak/CCMotionStreak.js +++ b/cocos2d/motion-streak/CCMotionStreak.js @@ -222,6 +222,14 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ this.startingPositionInitialized = startingPositionInitialized; }, + /** + * Get stroke. + * @returns {Number} stroke + */ + getStroke:function () { + return this._stroke; + }, + /** * Set stroke. * @param {Number} stroke From e8064f514c8977a62f05bc4f2568aa58a34e94af Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 9 Apr 2015 17:28:39 +0800 Subject: [PATCH 0141/1039] Fixed a bug that adaptation value error of IOS --- cocos2d/core/platform/CCEGLView.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/cocos2d/core/platform/CCEGLView.js b/cocos2d/core/platform/CCEGLView.js index 7dce4366ac..01c58088ed 100644 --- a/cocos2d/core/platform/CCEGLView.js +++ b/cocos2d/core/platform/CCEGLView.js @@ -61,6 +61,9 @@ cc.__BrowserGetter = { if(window.navigator.userAgent.indexOf("OS 8_1_") > -1) //this mistake like MIUI, so use of MIUI treatment method cc.__BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_MIUI; +if(cc.sys.os === cc.sys.OS_IOS) // All browsers are WebView + cc.__BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_SAFARI; + switch(cc.__BrowserGetter.adaptationType){ case cc.sys.BROWSER_TYPE_SAFARI: cc.__BrowserGetter.meta["minimal-ui"] = "true"; From 010c8cffcec102393517331dc76e406841610c6e Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 10 Apr 2015 18:22:37 +0800 Subject: [PATCH 0142/1039] Issue #1642: Fixed a bug that is setter is error of editBox --- extensions/editbox/CCdomNode.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/editbox/CCdomNode.js b/extensions/editbox/CCdomNode.js index c38ac03136..25085855eb 100644 --- a/extensions/editbox/CCdomNode.js +++ b/extensions/editbox/CCdomNode.js @@ -48,7 +48,7 @@ cc.DOM._addMethods = function (node) { cc.defineGetterSetter(node, "anchorY", node._getAnchorY, node._setAnchorY); cc.defineGetterSetter(node, "scale", node.getScale, node.setScale); cc.defineGetterSetter(node, "scaleX", node.getScaleX, node.setScaleX); - cc.defineGetterSetter(node, "scaleY", node.getScaleY, node.getScaleY); + cc.defineGetterSetter(node, "scaleY", node.getScaleY, node.setScaleY); cc.defineGetterSetter(node, "rotation", node.getRotation, node.setRotation); cc.defineGetterSetter(node, "skewX", node.getSkewX, node.setSkewX); cc.defineGetterSetter(node, "skewY", node.getSkewY, node.setSkewY); From 8407361ff4ee63e70e91432283b723ed36a6e4af Mon Sep 17 00:00:00 2001 From: mutoo Date: Mon, 13 Apr 2015 11:50:48 +0800 Subject: [PATCH 0143/1039] remove bind from UIWidget.onFocusChanged; --- extensions/ccui/base-classes/UIWidget.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/ccui/base-classes/UIWidget.js b/extensions/ccui/base-classes/UIWidget.js index b7e7a16f76..d3463eebaf 100644 --- a/extensions/ccui/base-classes/UIWidget.js +++ b/extensions/ccui/base-classes/UIWidget.js @@ -186,7 +186,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ this._initRenderer(); this.setBright(true); - this.onFocusChanged = this.onFocusChange.bind(this); + this.onFocusChanged = this.onFocusChange; this.onNextFocusedWidget = null; this.setAnchorPoint(cc.p(0.5, 0.5)); From 5d140daecf66b286144c6f136e6dc2bbb899ada2 Mon Sep 17 00:00:00 2001 From: mutoo Date: Mon, 13 Apr 2015 11:55:15 +0800 Subject: [PATCH 0144/1039] remove bind from UILayout.onPassFocusToChild; --- extensions/ccui/layouts/UILayout.js | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/extensions/ccui/layouts/UILayout.js b/extensions/ccui/layouts/UILayout.js index 99b242c2ae..67b6d62db9 100644 --- a/extensions/ccui/layouts/UILayout.js +++ b/extensions/ccui/layouts/UILayout.js @@ -246,7 +246,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ this.ignoreContentAdaptWithSize(false); this.setContentSize(cc.size(0, 0)); this.setAnchorPoint(0, 0); - this.onPassFocusToChild = this._findNearestChildWidgetIndex.bind(this); + this.onPassFocusToChild = this._findNearestChildWidgetIndex; return true; } return false; @@ -1065,16 +1065,16 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ var widgetPosition = this._getWorldCenterPoint(this._findFirstNonLayoutWidget()); if (direction === ccui.Widget.LEFT) { this.onPassFocusToChild = (previousWidgetPosition.x > widgetPosition.x) ? this._findNearestChildWidgetIndex.bind(this) - : this._findFarthestChildWidgetIndex.bind(this); + : this._findFarthestChildWidgetIndex; } else if (direction === ccui.Widget.RIGHT) { - this.onPassFocusToChild = (previousWidgetPosition.x > widgetPosition.x) ? this._findFarthestChildWidgetIndex.bind(this) - : this._findNearestChildWidgetIndex.bind(this); + this.onPassFocusToChild = (previousWidgetPosition.x > widgetPosition.x) ? this._findFarthestChildWidgetIndex + : this._findNearestChildWidgetIndex; }else if(direction === ccui.Widget.DOWN) { - this.onPassFocusToChild = (previousWidgetPosition.y > widgetPosition.y) ? this._findNearestChildWidgetIndex.bind(this) - : this._findFarthestChildWidgetIndex.bind(this); + this.onPassFocusToChild = (previousWidgetPosition.y > widgetPosition.y) ? this._findNearestChildWidgetIndex + : this._findFarthestChildWidgetIndex; }else if(direction === ccui.Widget.UP) { - this.onPassFocusToChild = (previousWidgetPosition.y < widgetPosition.y) ? this._findNearestChildWidgetIndex.bind(this) - : this._findFarthestChildWidgetIndex.bind(this); + this.onPassFocusToChild = (previousWidgetPosition.y < widgetPosition.y) ? this._findNearestChildWidgetIndex + : this._findFarthestChildWidgetIndex; }else cc.log("invalid direction!"); }, From 8b5bdf0a0d100296ec67d14dc9001bf77cf5db0c Mon Sep 17 00:00:00 2001 From: mutoo Date: Mon, 13 Apr 2015 11:58:55 +0800 Subject: [PATCH 0145/1039] filter out non-Widget; --- extensions/ccui/layouts/UILayoutManager.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/ccui/layouts/UILayoutManager.js b/extensions/ccui/layouts/UILayoutManager.js index e12cc31333..d69a36618c 100644 --- a/extensions/ccui/layouts/UILayoutManager.js +++ b/extensions/ccui/layouts/UILayoutManager.js @@ -176,7 +176,7 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{ locWidgetChildren.length = 0; for (var i = 0, len = container.length; i < len; i++){ var child = container[i]; - if (child) { + if (child && child instanceof ccui.Widget) { var layoutParameter = child.getLayoutParameter(); layoutParameter._put = false; this._unlayoutChildCount++; From 841b91bc5dbc732c044d0217d8b00306d1f78871 Mon Sep 17 00:00:00 2001 From: mutoo Date: Mon, 13 Apr 2015 12:34:48 +0800 Subject: [PATCH 0146/1039] specify a parmaeter for item.getLayoutParameter in UIListView._remedyLayoutParameter; --- extensions/ccui/uiwidgets/scroll-widget/UIListView.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIListView.js b/extensions/ccui/uiwidgets/scroll-widget/UIListView.js index 370dd411b3..d77bfbf215 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIListView.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIListView.js @@ -118,7 +118,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ _remedyLayoutParameter: function (item) { cc.assert(null != item, "ListView Item can't be nil!"); - var linearLayoutParameter = item.getLayoutParameter(); + var linearLayoutParameter = item.getLayoutParameter(ccui.LayoutParameter.LINEAR); var isLayoutParameterExists = true; if (!linearLayoutParameter) { linearLayoutParameter = new ccui.LinearLayoutParameter(); From b403b4efac7eb484046ca7596f9b6a196d977ec1 Mon Sep 17 00:00:00 2001 From: mutoo Date: Mon, 13 Apr 2015 12:37:45 +0800 Subject: [PATCH 0147/1039] fix interceptTouchEvent; --- extensions/ccui/uiwidgets/scroll-widget/UIListView.js | 2 ++ extensions/ccui/uiwidgets/scroll-widget/UIPageView.js | 2 ++ extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js | 2 ++ 3 files changed, 6 insertions(+) diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIListView.js b/extensions/ccui/uiwidgets/scroll-widget/UIListView.js index d77bfbf215..e00458cf65 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIListView.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIListView.js @@ -463,6 +463,8 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ * @param {cc.Touch} touch */ interceptTouchEvent: function (eventType, sender, touch) { + if (!this.isTouchEnabled()) return; + ccui.ScrollView.prototype.interceptTouchEvent.call(this, eventType, sender, touch); if (eventType !== ccui.Widget.TOUCH_MOVED) { var parent = sender; diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js b/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js index 49210ef9b2..a2cafab90d 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js @@ -495,6 +495,8 @@ ccui.PageView = ccui.Layout.extend(/** @lends ccui.PageView# */{ * @param {cc.Touch} touch */ interceptTouchEvent: function (eventType, sender, touch) { + if (!this.isTouchEnabled()) return; + var touchPoint = touch.getLocation(); switch (eventType) { case ccui.Widget.TOUCH_BEGAN: diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js index db3227ffbc..d5961d464c 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js @@ -1452,6 +1452,8 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ * @param {cc.Touch} touch */ interceptTouchEvent: function (event, sender, touch) { + if (!this.isTouchEnabled()) return; + var touchPoint = touch.getLocation(); switch (event) { case ccui.Widget.TOUCH_BEGAN: From 188ff29e4d485fe95acfad660a76804b330f5da5 Mon Sep 17 00:00:00 2001 From: mutoo Date: Mon, 13 Apr 2015 12:46:30 +0800 Subject: [PATCH 0148/1039] correct CCActionNode's postion; --- extensions/cocostudio/action/CCActionNode.js | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/extensions/cocostudio/action/CCActionNode.js b/extensions/cocostudio/action/CCActionNode.js index a4ae9a9332..c6c18f3c25 100644 --- a/extensions/cocostudio/action/CCActionNode.js +++ b/extensions/cocostudio/action/CCActionNode.js @@ -63,6 +63,7 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{ */ initWithDictionary: function (dic, root) { this.setActionTag(dic["ActionTag"]); + this._initActionNodeFromRoot(root); var actionFrameList = dic["actionframelist"]; for (var i = 0; i < actionFrameList.length; i++) { var actionFrameDic = actionFrameList[i]; @@ -86,7 +87,19 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{ actionFrame.frameIndex = frameIndex; actionFrame.setEasingType(frameTweenType); actionFrame.setEasingParameter(frameTweenParameter); - actionFrame.setPosition(positionX, positionY); + + var actionNode = this.getActionNode(); + if (actionNode && actionNode.getParent()) { + var actionNodeParentAnchorInPoints = actionNode.getParent().getAnchorPointInPoints(); + actionFrame.setPosition( + positionX + actionNodeParentAnchorInPoints.x, + positionY + actionNodeParentAnchorInPoints.y + ); + } + else { + actionFrame.setPosition(positionX, positionY); + } + actionArray = this._frameArray[ccs.FRAME_TYPE_MOVE]; actionArray.push(actionFrame); } @@ -140,7 +153,6 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{ } actionFrameDic = null; } - this._initActionNodeFromRoot(root); }, _initActionNodeFromRoot: function (root) { From 49c39cf438463bda3533ab24aea398762a5553e8 Mon Sep 17 00:00:00 2001 From: mutoo Date: Mon, 13 Apr 2015 12:55:52 +0800 Subject: [PATCH 0149/1039] Child armature shuld be playing with its parent. --- .../cocostudio/armature/animation/CCArmatureAnimation.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/extensions/cocostudio/armature/animation/CCArmatureAnimation.js b/extensions/cocostudio/armature/animation/CCArmatureAnimation.js index 870ba7ed0f..09ab2fe7b0 100644 --- a/extensions/cocostudio/armature/animation/CCArmatureAnimation.js +++ b/extensions/cocostudio/armature/animation/CCArmatureAnimation.js @@ -292,8 +292,11 @@ ccs.ArmatureAnimation = ccs.ProcessBase.extend(/** @lends ccs.ArmatureAnimation# tween.play(movementBoneData, durationTo, durationTween, loop, tweenEasing); tween.setProcessScale(this._processScale); - if (bone.getChildArmature()) + if (bone.getChildArmature()) { bone.getChildArmature().getAnimation().setSpeedScale(this._processScale); + if (!bone.getChildArmature().getAnimation().isPlaying()) + bone.getChildArmature().getAnimation().playWithIndex(0); + } } else { if(!bone.isIgnoreMovementBoneData()){ //! this bone is not include in this movement, so hide it From 5f2183d656bcc15baad1ac9a6525336dd6cbf7fe Mon Sep 17 00:00:00 2001 From: mutoo Date: Mon, 13 Apr 2015 12:57:49 +0800 Subject: [PATCH 0150/1039] more compatiblity for isTween parameter; --- extensions/cocostudio/armature/utils/CCDataReaderHelper.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/cocostudio/armature/utils/CCDataReaderHelper.js b/extensions/cocostudio/armature/utils/CCDataReaderHelper.js index cc3ffb62a3..60816852cc 100644 --- a/extensions/cocostudio/armature/utils/CCDataReaderHelper.js +++ b/extensions/cocostudio/armature/utils/CCDataReaderHelper.js @@ -790,7 +790,7 @@ ccs.dataReaderHelper = /** @lends ccs.dataReaderHelper# */{ frameData.soundEffect = frameData.strSoundEffect; var isTween = frameXML.getAttribute(ccs.CONST_A_TWEEN_FRAME); - frameData.isTween = !(isTween != undefined && isTween === "false"); + frameData.isTween = !(isTween != undefined && (isTween === "false" || isTween == "0")); if (dataInfo.flashToolVersion >= ccs.CONST_VERSION_2_0) { x = frameXML.getAttribute(ccs.CONST_A_COCOS2DX_X); From 65e4177a65b1fe0c2c09b6c35145c06a310fe67a Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 13 Apr 2015 13:53:08 +0800 Subject: [PATCH 0151/1039] Arrangement the render mode --- CCBoot.js | 75 ++++++++++++++++++++++++++++++------------------------- 1 file changed, 41 insertions(+), 34 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index ac316ccd3c..75740d3825 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -1563,13 +1563,6 @@ cc._initSys = function (config, CONFIG_KEY) { */ sys.isNative = false; - var browserSupportWebGL = [sys.BROWSER_TYPE_BAIDU, sys.BROWSER_TYPE_OPERA, sys.BROWSER_TYPE_FIREFOX, sys.BROWSER_TYPE_CHROME, sys.BROWSER_TYPE_SAFARI]; - var osSupportWebGL = [sys.OS_IOS, sys.OS_WINDOWS, sys.OS_OSX, sys.OS_LINUX]; - var multipleAudioWhiteList = [ - sys.BROWSER_TYPE_BAIDU, sys.BROWSER_TYPE_OPERA, sys.BROWSER_TYPE_FIREFOX, sys.BROWSER_TYPE_CHROME, sys.BROWSER_TYPE_BAIDU_APP, - sys.BROWSER_TYPE_SAFARI, sys.BROWSER_TYPE_UC, sys.BROWSER_TYPE_QQ, sys.BROWSER_TYPE_MOBILE_QQ, sys.BROWSER_TYPE_IE - ]; - var win = window, nav = win.navigator, doc = document, docEle = doc.documentElement; var ua = nav.userAgent.toLowerCase(); @@ -1642,21 +1635,51 @@ cc._initSys = function (config, CONFIG_KEY) { */ sys.os = osName; + var multipleAudioWhiteList = [ + sys.BROWSER_TYPE_BAIDU, sys.BROWSER_TYPE_OPERA, sys.BROWSER_TYPE_FIREFOX, sys.BROWSER_TYPE_CHROME, sys.BROWSER_TYPE_BAIDU_APP, + sys.BROWSER_TYPE_SAFARI, sys.BROWSER_TYPE_UC, sys.BROWSER_TYPE_QQ, sys.BROWSER_TYPE_MOBILE_QQ, sys.BROWSER_TYPE_IE + ]; + sys._supportMultipleAudio = multipleAudioWhiteList.indexOf(sys.browserType) > -1; //++++++++++++++++++something about cc._renderTYpe and cc._supportRender begin++++++++++++++++++++++++++++ - var userRenderMode = parseInt(config[CONFIG_KEY.renderMode]); - var renderType = cc._RENDER_TYPE_WEBGL; - var tempCanvas = cc.newElement("Canvas"); - cc._supportRender = true; - var notSupportGL = true; - if(iOS) - notSupportGL = !window.WebGLRenderingContext || osSupportWebGL.indexOf(sys.os) === -1; - else - notSupportGL = !window.WebGLRenderingContext || browserSupportWebGL.indexOf(sys.browserType) === -1 || osSupportWebGL.indexOf(sys.os) === -1; - if (userRenderMode === 1 || (userRenderMode === 0 && notSupportGL) || (location.origin === "file://")) - renderType = cc._RENDER_TYPE_CANVAS; + + (function(sys, config){ + var userRenderMode = config[CONFIG_KEY.renderMode] - 0; + if(isNaN(userRenderMode) || userRenderMode > 2 || userRenderMode < 0) + userRenderMode = 0; + var shieldOs = [sys.OS_ANDROID]; + var shieldBrowser = []; + var tmpCanvas = cc.newElement("canvas"); + cc._renderType = cc._RENDER_TYPE_CANVAS; + cc._supportRender = true; + + var supportWebGL = win.WebGLRenderingContext; + if(userRenderMode === 0){ + if(supportWebGL && shieldOs.indexOf(sys.os) === -1 && shieldBrowser.indexOf(sys.browserType)) + userRenderMode = 2; + else + userRenderMode = 1; + } + + if(userRenderMode === 2) + try{ + cc.create3DContext(tmpCanvas, {'stencil': true, 'preserveDrawingBuffer': true }); + cc._renderType = cc._RENDER_TYPE_WEBGL; + }catch(e){ + cc.log("Browsers doesn‘t support WebGL"); + userRenderMode = 1; + } + + if(userRenderMode === 1) + try { + tmpCanvas.getContext("2d"); + cc._renderType = cc._RENDER_TYPE_CANVAS; + } catch (e) { + cc._supportRender = false; + } + })(sys, config); sys._canUseCanvasNewBlendModes = function(){ var canvas = document.createElement('canvas'); @@ -1682,22 +1705,6 @@ cc._initSys = function (config, CONFIG_KEY) { //Whether or not the Canvas BlendModes are supported. sys._supportCanvasNewBlendModes = sys._canUseCanvasNewBlendModes(); - if (renderType === cc._RENDER_TYPE_WEBGL) { - if (!win.WebGLRenderingContext - || !cc.create3DContext(tempCanvas, {'stencil': true, 'preserveDrawingBuffer': true })) { - if (userRenderMode === 0) renderType = cc._RENDER_TYPE_CANVAS; - else cc._supportRender = false; - } - } - - if (renderType === cc._RENDER_TYPE_CANVAS) { - try { - tempCanvas.getContext("2d"); - } catch (e) { - cc._supportRender = false; - } - } - cc._renderType = renderType; //++++++++++++++++++something about cc._renderType and cc._supportRender end++++++++++++++++++++++++++++++ // check if browser supports Web Audio From c18f6862542527e5da1fbd199d10595f0b246141 Mon Sep 17 00:00:00 2001 From: mutoo Date: Mon, 13 Apr 2015 13:54:34 +0800 Subject: [PATCH 0152/1039] rename CCTMXLayer.getTileSet/setTileSet to keep the same API with jsb; --- cocos2d/tilemap/CCTMXLayer.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos2d/tilemap/CCTMXLayer.js b/cocos2d/tilemap/CCTMXLayer.js index 9491fb6b70..9147574a1d 100644 --- a/cocos2d/tilemap/CCTMXLayer.js +++ b/cocos2d/tilemap/CCTMXLayer.js @@ -205,7 +205,7 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ * Tile set information for the layer * @return {cc.TMXTilesetInfo} */ - getTileset:function () { + getTileSet:function () { return this.tileset; }, @@ -213,7 +213,7 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ * Tile set information for the layer * @param {cc.TMXTilesetInfo} Var */ - setTileset:function (Var) { + setTileSet:function (Var) { this.tileset = Var; }, From 997d2d7967c3e6b6309caa13f90d63800824fd87 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 13 Apr 2015 14:02:53 +0800 Subject: [PATCH 0153/1039] Arrangement the render mode --- CCBoot.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CCBoot.js b/CCBoot.js index 75740d3825..4e1d5fd438 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -1657,7 +1657,7 @@ cc._initSys = function (config, CONFIG_KEY) { var supportWebGL = win.WebGLRenderingContext; if(userRenderMode === 0){ - if(supportWebGL && shieldOs.indexOf(sys.os) === -1 && shieldBrowser.indexOf(sys.browserType)) + if(supportWebGL && shieldOs.indexOf(sys.os) === -1 && shieldBrowser.indexOf(sys.browserType) === -1) userRenderMode = 2; else userRenderMode = 1; From ff63de504e7e1a7b54fdb599081b0be949187055 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 13 Apr 2015 14:20:21 +0800 Subject: [PATCH 0154/1039] Arrangement the render mode --- CCBoot.js | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index 4e1d5fd438..ff7b5aed87 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -1665,8 +1665,13 @@ cc._initSys = function (config, CONFIG_KEY) { if(userRenderMode === 2) try{ - cc.create3DContext(tmpCanvas, {'stencil': true, 'preserveDrawingBuffer': true }); - cc._renderType = cc._RENDER_TYPE_WEBGL; + var context = cc.create3DContext(tmpCanvas, {'stencil': true, 'preserveDrawingBuffer': true }); + if(context){ + cc._renderType = cc._RENDER_TYPE_WEBGL; + }else{ + cc.log("Browsers doesn‘t support WebGL"); + userRenderMode = 1; + } }catch(e){ cc.log("Browsers doesn‘t support WebGL"); userRenderMode = 1; From c967b3f0ed41245545e030e534597395a79b8e3e Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 13 Apr 2015 14:48:29 +0800 Subject: [PATCH 0155/1039] Arrangement the render mode --- CCBoot.js | 21 ++++++--------------- 1 file changed, 6 insertions(+), 15 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index ff7b5aed87..0fc02c4b06 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -1656,28 +1656,19 @@ cc._initSys = function (config, CONFIG_KEY) { cc._supportRender = true; var supportWebGL = win.WebGLRenderingContext; - if(userRenderMode === 0){ - if(supportWebGL && shieldOs.indexOf(sys.os) === -1 && shieldBrowser.indexOf(sys.browserType) === -1) - userRenderMode = 2; - else - userRenderMode = 1; - } - if(userRenderMode === 2) + if(userRenderMode === 2 || (userRenderMode === 0 && supportWebGL && shieldOs.indexOf(sys.os) === -1 && shieldBrowser.indexOf(sys.browserType) === -1)) try{ var context = cc.create3DContext(tmpCanvas, {'stencil': true, 'preserveDrawingBuffer': true }); - if(context){ + if(context) cc._renderType = cc._RENDER_TYPE_WEBGL; - }else{ - cc.log("Browsers doesn‘t support WebGL"); - userRenderMode = 1; - } + else + cc._supportRender = false; }catch(e){ - cc.log("Browsers doesn‘t support WebGL"); - userRenderMode = 1; + cc._supportRender = false; } - if(userRenderMode === 1) + if(userRenderMode === 1 || (userRenderMode === 0 && cc._supportRender === false)) try { tmpCanvas.getContext("2d"); cc._renderType = cc._RENDER_TYPE_CANVAS; From a2047b9c53cbcad57f04ab1c696d13424621c1a8 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 13 Apr 2015 15:06:08 +0800 Subject: [PATCH 0156/1039] Arrangement the render mode --- CCBoot.js | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index 0fc02c4b06..8c6b92c9fb 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -1653,28 +1653,25 @@ cc._initSys = function (config, CONFIG_KEY) { var shieldBrowser = []; var tmpCanvas = cc.newElement("canvas"); cc._renderType = cc._RENDER_TYPE_CANVAS; - cc._supportRender = true; + cc._supportRender = false; var supportWebGL = win.WebGLRenderingContext; if(userRenderMode === 2 || (userRenderMode === 0 && supportWebGL && shieldOs.indexOf(sys.os) === -1 && shieldBrowser.indexOf(sys.browserType) === -1)) try{ var context = cc.create3DContext(tmpCanvas, {'stencil': true, 'preserveDrawingBuffer': true }); - if(context) + if(context){ cc._renderType = cc._RENDER_TYPE_WEBGL; - else - cc._supportRender = false; - }catch(e){ - cc._supportRender = false; - } + cc._supportRender = true; + } + }catch(e){} if(userRenderMode === 1 || (userRenderMode === 0 && cc._supportRender === false)) try { tmpCanvas.getContext("2d"); cc._renderType = cc._RENDER_TYPE_CANVAS; - } catch (e) { - cc._supportRender = false; - } + cc._supportRender = true; + } catch (e) {} })(sys, config); sys._canUseCanvasNewBlendModes = function(){ From 6da998a3593b3635eee1b73cd2eb3d4b3a27dad3 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Tue, 14 Apr 2015 10:36:26 +0800 Subject: [PATCH 0157/1039] Fixed #2806: fixed a bug of cc.SkeletonAnimation that its canvas renderCmd doesn't work --- extensions/spine/CCSkeleton.js | 4 +- extensions/spine/CCSkeletonAnimation.js | 1 + extensions/spine/CCSkeletonCanvasRenderCmd.js | 231 ++++++++---------- template/project.json | 2 +- template/src/myApp.js | 9 - template/src/resource.js | 3 - 6 files changed, 108 insertions(+), 142 deletions(-) diff --git a/extensions/spine/CCSkeleton.js b/extensions/spine/CCSkeleton.js index a0132b0f43..27e1ac1763 100644 --- a/extensions/spine/CCSkeleton.js +++ b/extensions/spine/CCSkeleton.js @@ -105,7 +105,7 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ */ init: function () { cc.Node.prototype.init.call(this); - this.setOpacityModifyRGB(true); + //this.setOpacityModifyRGB(true); this._blendFunc.src = cc.ONE; this._blendFunc.dst = cc.ONE_MINUS_SRC_ALPHA; this.scheduleUpdate(); @@ -345,6 +345,7 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ this.setContentSize(skeletonData.width / cc.director.getContentScaleFactor(), skeletonData.height / cc.director.getContentScaleFactor()); this._skeleton = new spine.Skeleton(skeletonData); + this._skeleton.updateWorldTransform(); this._rootBone = this._skeleton.getRootBone(); this._ownsSkeletonData = ownsSkeletonData; @@ -390,7 +391,6 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ */ update: function (dt) { this._skeleton.update(dt); - this._renderCmd._updateChild(); } }); diff --git a/extensions/spine/CCSkeletonAnimation.js b/extensions/spine/CCSkeletonAnimation.js index e60465ec30..f351d83c80 100644 --- a/extensions/spine/CCSkeletonAnimation.js +++ b/extensions/spine/CCSkeletonAnimation.js @@ -222,6 +222,7 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ this._state.update(dt); this._state.apply(this._skeleton); this._skeleton.updateWorldTransform(); + this._renderCmd._updateChild(); }, /** diff --git a/extensions/spine/CCSkeletonCanvasRenderCmd.js b/extensions/spine/CCSkeletonCanvasRenderCmd.js index b27ee8ae10..1b4f873cd1 100644 --- a/extensions/spine/CCSkeletonCanvasRenderCmd.js +++ b/extensions/spine/CCSkeletonCanvasRenderCmd.js @@ -26,97 +26,39 @@ sp.Skeleton.CanvasRenderCmd = function(renderableObject){ cc.Node.CanvasRenderCmd.call(this, renderableObject); this._needDraw = true; - - this._skeletonSprites = []; }; var proto = sp.Skeleton.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); proto.constructor = sp.Skeleton.CanvasRenderCmd; proto.rendering = function (wrapper, scaleX, scaleY) { - var node = this._node, i, n; + var node = this._node, i, n, slot, slotNode; wrapper = wrapper || cc._renderContext; - var context = wrapper.getContext(); - - var locSkeleton = node._skeleton,color = node.getColor(); - locSkeleton.r = color.r / 255; - locSkeleton.g = color.g / 255; - locSkeleton.b = color.b / 255; - locSkeleton.a = this.getDisplayedOpacity() / 255; - if (node._premultipliedAlpha) { - locSkeleton.r *= locSkeleton.a; - locSkeleton.g *= locSkeleton.a; - locSkeleton.b *= locSkeleton.a; - } - - /*wrapper.setTransform(this._worldTransform, scaleX, scaleY); - context.save(); - //draw skeleton by itself. - var slot, attachment, selTexture, selBone, rendererObject; - for (i = 0, n = locSkeleton.drawOrder.length; i < n; i++) { - slot = locSkeleton.drawOrder[i]; - if (!slot.attachment) - continue; - attachment = slot.attachment; - rendererObject = attachment.rendererObject; - selTexture = rendererObject.page._texture; - if(!selTexture || !selTexture._textureLoaded || !slot.bone) - continue; - - selBone = slot.bone; - //context.transform(selBone.m00, selBone.m01, selBone.m10, selBone.m11, selBone.worldX, selBone.worldY); - context.translate(selBone.worldX, selBone.worldY); - context.scale(selBone.worldScaleX, selBone.worldScaleY); - console.log(selBone); - context.rotate(selBone.worldRotation); - context.drawImage(selTexture._htmlElementObj, - rendererObject.x, rendererObject.y, rendererObject.width, rendererObject.height, - //locX * scaleX, locY * scaleY, locWidth * scaleX, locHeight * scaleY); - 0, 0, rendererObject.width * scaleX, rendererObject.height * scaleY); - - } - context.restore();*/ - - //draw skeleton sprite by it self -/* wrapper.save(); - //set to armature mode (spine need same way to draw) - wrapper._switchToArmatureMode(true, this._worldTransform, scaleX, scaleY); - var sprites = this._skeletonSprites, slot, selSpriteCmd,attachment; - for (i = 0, n = sprites.length; i < n; i++) { - selSpriteCmd = sprites[i]._renderCmd; - if (sprites[i]._visible && selSpriteCmd && selSpriteCmd.rendering) { - selSpriteCmd.rendering(wrapper, scaleX, scaleY); - selSpriteCmd._dirtyFlag = 0; - } - } - wrapper._switchToArmatureMode(false); - wrapper.restore();*/ - - //set to armature mode (spine need same way to draw) - var sprites = this._skeletonSprites, slot, selSpriteCmd,attachment; - for (i = 0, n = sprites.length; i < n; i++) { - selSpriteCmd = sprites[i]._renderCmd; - if (sprites[i]._visible && selSpriteCmd && selSpriteCmd.rendering) { - selSpriteCmd.transform(this, false); - selSpriteCmd.rendering(wrapper, scaleX, scaleY); - selSpriteCmd._dirtyFlag = 0; + var locSkeleton = node._skeleton, drawOrder = locSkeleton.drawOrder; + for(i = 0, n = drawOrder.length; i < n; i++){ + slot = drawOrder[i]; + slotNode = slot._slotNode; + if(slotNode._visible && slotNode._renderCmd && slot.currentSprite){ + slotNode._renderCmd.transform(this, true); + slot.currentSprite._renderCmd.rendering(wrapper, scaleX, scaleY); + slotNode._renderCmd._dirtyFlag = slot.currentSprite._renderCmd._dirtyFlag = 0; } } if (!node._debugSlots && !node._debugBones) return; + wrapper.setTransform(this._worldTransform, scaleX, scaleY); - var drawingUtil = cc._drawingUtil; + wrapper.setGlobalAlpha(1); + var attachment, drawingUtil = cc._drawingUtil; if (node._debugSlots) { // Slots. drawingUtil.setDrawColor(0, 0, 255, 255); drawingUtil.setLineWidth(1); var points = []; - var drawOrder = node._skeleton.drawOrder; - for (i = 0, n = drawOrder.length; i < n; i++) { - //for (i = 0, n = locSkeleton.slots.length; i < n; i++) { + for (i = 0, n = locSkeleton.slots.length; i < n; i++) { slot = locSkeleton.drawOrder[i]; if (!slot.attachment || slot.attachment.type != sp.ATTACHMENT_TYPE.REGION) continue; @@ -169,68 +111,103 @@ proto._createChildFormSkeletonData = function(){ var node = this._node; - var locSkeleton = node._skeleton, rendererObject, rect; - for (var i = 0, n = locSkeleton.drawOrder.length; i < n; i++) { - var slot = locSkeleton.drawOrder[i]; - var attachment = slot.attachment; - if (!(attachment instanceof spine.RegionAttachment)) - continue; - rendererObject = attachment.rendererObject; - rect = cc.rect(rendererObject.x, rendererObject.y, rendererObject.width,rendererObject.height); - var sprite = new cc.Sprite(); - sprite.initWithTexture(rendererObject.page._texture, rect, rendererObject.rotate, false); - sprite._rect.width = attachment.width; - sprite._rect.height = attachment.height; - sprite.setContentSize(attachment.width, attachment.height); - sprite.setRotation(-(slot.bone.worldRotation + attachment.rotation)); - this._skeletonSprites.push(sprite); - slot.currentSprite = sprite; + var locSkeleton = node._skeleton, spriteName, sprite; + for (var i = 0, n = locSkeleton.slots.length; i < n; i++) { + var slot = locSkeleton.slots[i], attachment = slot.attachment; + var slotNode = new cc.Node(); + slot._slotNode = slotNode; + + if(attachment instanceof spine.RegionAttachment){ + spriteName = attachment.rendererObject.name; + sprite = this._createSprite(slot, attachment); + slot.currentSprite = sprite; + slot.currentSpriteName = spriteName; + slotNode.addChild(sprite); + } else if(attachment instanceof spine.MeshAttachment){ + //todo for mesh + } } }; + proto._createSprite = function(slot, attachment){ + var rendererObject = attachment.rendererObject; + var texture = rendererObject.page._texture; + var rect = new cc.Rect(rendererObject.x, rendererObject.y, rendererObject.width, rendererObject.height); + var sprite = new cc.Sprite(); + sprite.initWithTexture(rendererObject.page._texture, rect, rendererObject.rotate, false); + sprite._rect.width = attachment.width; + sprite._rect.height = attachment.height; + sprite.setContentSize(attachment.width, attachment.height); + sprite.setRotation(-attachment.rotation); + sprite.setScale(rendererObject.width / rendererObject.originalWidth * attachment.scaleX, + rendererObject.height / rendererObject.originalHeight * attachment.scaleY); + + slot.sprites = slot.sprites || {}; + slot.sprites[rendererObject.name] = sprite; + + return sprite; + }; + proto._updateChild = function(){ - var node = this._node; - var locSkeleton = node._skeleton, locSkeletonSprites = this._skeletonSprites; - locSkeleton.updateWorldTransform(); - locSkeletonSprites.length = 0; - var drawOrder = node._skeleton.drawOrder; - for (var i = 0, n = drawOrder.length; i < n; i++) { - var slot = drawOrder[i]; - var attachment = slot.attachment, selSprite = slot.currentSprite; - if (!(attachment instanceof spine.RegionAttachment)) { - if(selSprite) - selSprite.setVisible(false); + var locSkeleton = this._node._skeleton, slots = locSkeleton.slots; + var i, n, selSprite; + + var slot, attachment, slotNode; + for(i = 0, n = slots.length; i < n; i++){ + slot = slots[i]; + attachment = slot.attachment; + slotNode = slot._slotNode; + if(!attachment){ + slotNode.setVisible(false); + continue; + } + var type = attachment.type; + if (type === spine.AttachmentType.region){ + if(attachment.rendererObject){ + if(!slot.currentSpriteName || slot.currentSpriteName !== attachment.name){ + var spriteName = attachment.rendererObject.name; + if(slot.currentSprite !== undefined) + slot.currentSprite.setVisible(false); + slot.sprites = slot.sprites ||{}; + if(slot.sprites[spriteName] !== undefined) + slot.sprites[spriteName].setVisible(true); + else{ + var sprite = this._createSprite(slot, attachment); + slotNode.addChild(sprite); + } + slot.currentSprite = slot.sprites[spriteName]; + slot.currentSpriteName = spriteName; + } + } + var bone = slot.bone; + slotNode.setPosition(bone.worldX + attachment.x * bone.m00 + attachment.y * bone.m01, + bone.worldY + attachment.x * bone.m10 + attachment.y * bone.m11); + slotNode.setScale(bone.worldScaleX, bone.worldScaleY); + + //set the color and opacity + selSprite = slot.currentSprite; + selSprite._flippedX = bone.worldFlipX; + selSprite._flippedY = bone.worldFlipY; + if(selSprite._flippedY || selSprite._flippedX){ + slotNode.setRotation(bone.worldRotation); + selSprite.setRotation(attachment.rotation); + }else{ + slotNode.setRotation(-bone.worldRotation); + selSprite.setRotation(-attachment.rotation); + } + + //hack for sprite + selSprite._renderCmd._displayedOpacity = 0 | (locSkeleton.a * slot.a * 255); + var r = 0 | (locSkeleton.r * slot.r * 255), g = 0 | (locSkeleton.g * slot.g * 255), b = 0 | (locSkeleton.b * slot.b * 255); + selSprite.setColor(cc.color(r,g,b)); + selSprite._renderCmd._updateColor(); + } else if (type === spine.AttachmentType.skinnedmesh) { + //todo for mesh + } else { + slotNode.setVisible(false); continue; } - var rendererObject = attachment.rendererObject; - var rect = cc.rect(rendererObject.x, rendererObject.y, rendererObject.width,rendererObject.height); - if(!selSprite){ - var sprite = new cc.Sprite(); - locSkeletonSprites.push(sprite); - selSprite = slot.currentSprite = sprite; - }else - locSkeletonSprites.push(selSprite); - selSprite.initWithTexture(rendererObject.page._texture, rect, rendererObject.rotate, false); - selSprite.setContentSize(attachment.width, attachment.height); - selSprite._rect.width = attachment.width; - selSprite._rect.height = attachment.height; - - selSprite.setVisible(true); - //update color and blendFunc - selSprite.setBlendFunc(cc.BLEND_SRC, slot.data.additiveBlending ? cc.ONE : cc.BLEND_DST); - - var bone = slot.bone; - selSprite.setPosition(bone.worldX, bone.worldY); - selSprite.setScale(bone.worldScaleX, bone.worldScaleY); - //selSprite.setRotation(-(slot.bone.worldRotation + attachment.rotation)); - selSprite.setRotation(-bone.worldRotation); - selSprite.setOpacity(0 | (node._skeleton.a * slot.a * 255)); - selSprite.setFlippedX(bone.flipX); - selSprite.setFlippedY(bone.flipY); - var r = 0 | (node._skeleton.r * slot.r * 255); - var g = 0 | (node._skeleton.g * slot.g * 255); - var b = 0 | (node._skeleton.b * slot.b * 255); - selSprite.setColor(cc.color(r,g,b)); + slotNode.setVisible(true); } }; })(); \ No newline at end of file diff --git a/template/project.json b/template/project.json index 2db719e811..29de061423 100644 --- a/template/project.json +++ b/template/project.json @@ -4,7 +4,7 @@ "showFPS" : true, "frameRate" : 60, "id" : "gameCanvas", - "renderMode" : 1, + "renderMode" : 0, "engineDir":"../", "modules" : ["cocos2d", "extensions"], diff --git a/template/src/myApp.js b/template/src/myApp.js index 16ad0863c0..f91b7c40af 100644 --- a/template/src/myApp.js +++ b/template/src/myApp.js @@ -44,15 +44,6 @@ var MyLayer = cc.Layer.extend({ this.sprite.setPosition(size.width / 2, size.height / 2); this.sprite.setScale(size.height / this.sprite.getContentSize().height); this.addChild(this.sprite, 0); - - var spineBoy = new sp.SkeletonAnimation('skeleton.json', 'skeleton.atlas'); - spineBoy.setPosition(cc.p(size.width / 2, size.height / 2 - 150)); - this.addChild(spineBoy, 10); - spineBoy.setAnimation(0, 'attack5', true); - spineBoy.setTimeScale(0.1); - //spineBoy.setDebugBonesEnabled(true); - spineBoy.setDebugSlotsEnabled(true); - window.spineBoy = spineBoy; } }); diff --git a/template/src/resource.js b/template/src/resource.js index f9016890a0..94284083d1 100644 --- a/template/src/resource.js +++ b/template/src/resource.js @@ -6,9 +6,6 @@ var g_resources = [ //image s_HelloWorld, s_CloseNormal, - "skeleton.png", - "skeleton.atlas", - "skeleton.json", s_CloseSelected //plist From 801bcb4cf3309e81e39940f40f2b5bcc72c4088a Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Tue, 14 Apr 2015 10:43:53 +0800 Subject: [PATCH 0158/1039] Fixed #2806: remove the test codes. --- template/project.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/template/project.json b/template/project.json index 29de061423..a4a9435aab 100644 --- a/template/project.json +++ b/template/project.json @@ -7,7 +7,7 @@ "renderMode" : 0, "engineDir":"../", - "modules" : ["cocos2d", "extensions"], + "modules" : ["cocos2d"], "jsList" : [ "src/resource.js", From 8e5df94fb15ce8491c8e44cc3a924576dcffeb22 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 14 Apr 2015 18:10:36 +0800 Subject: [PATCH 0159/1039] The width of the labelBMFont parsing error --- extensions/cocostudio/loader/parsers/timelineParser-2.x.js | 1 + 1 file changed, 1 insertion(+) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 89350c2cba..542fb9b5eb 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -1020,6 +1020,7 @@ cc.log("%s need to be pre loaded", path); widget.setFntFile(path); }); + widget.ignoreContentAdaptWithSize(true); return widget; }; From 494672b1c424e8f9124b64fadf82fac04b1df3ac Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 14 Apr 2015 18:21:23 +0800 Subject: [PATCH 0160/1039] Update -x timeline and parser --- extensions/cocostudio/action/CCActionFrame.js | 16 +- .../cocostudio/loader/parsers/action-2.x.js | 35 ++- .../loader/parsers/timelineParser-2.x.js | 51 +++- .../cocostudio/timeline/ActionTimeline.js | 28 +++ extensions/cocostudio/timeline/Frame.js | 232 ++++++++++++++++-- 5 files changed, 321 insertions(+), 41 deletions(-) diff --git a/extensions/cocostudio/action/CCActionFrame.js b/extensions/cocostudio/action/CCActionFrame.js index 04c1dfa450..755cbbd578 100644 --- a/extensions/cocostudio/action/CCActionFrame.js +++ b/extensions/cocostudio/action/CCActionFrame.js @@ -99,9 +99,9 @@ ccs.FrameEaseType = { Circ_EaseOut : 20, Circ_EaseInOut : 21, - Elastic_EaesIn : 22, - Elastic_EaesOut : 23, - Elastic_EaesInOut : 24, + Elastic_EaseIn : 22, + Elastic_EaseOut : 23, + Elastic_EaseInOut : 24, Back_EaseIn : 25, Back_EaseOut : 26, @@ -109,7 +109,9 @@ ccs.FrameEaseType = { Bounce_EaseIn : 28, Bounce_EaseOut : 29, - Bounce_EaseInOut : 30 + Bounce_EaseInOut : 30, + + TWEEN_EASING_MAX: 1000 }; @@ -227,13 +229,13 @@ ccs.ActionFrame = ccs.Class.extend(/** @lends ccs.ActionFrame# */{ case ccs.FrameEaseType.Circ_EaseInOut: resultAction = action.easing(cc.easeCircleActionInOut()); break; - case ccs.FrameEaseType.Elastic_EaesIn: + case ccs.FrameEaseType.Elastic_EaseIn: resultAction = action.easing(cc.easeElasticIn()); break; - case ccs.FrameEaseType.Elastic_EaesOut: + case ccs.FrameEaseType.Elastic_EaseOut: resultAction = action.easing(cc.easeElasticOut()); break; - case ccs.FrameEaseType.Elastic_EaesInOut: + case ccs.FrameEaseType.Elastic_EaseInOut: resultAction = action.easing(cc.easeElasticInOut()); break; case ccs.FrameEaseType.Back_EaseIn: diff --git a/extensions/cocostudio/loader/parsers/action-2.x.js b/extensions/cocostudio/loader/parsers/action-2.x.js index d7ff403256..58d5801c5c 100644 --- a/extensions/cocostudio/loader/parsers/action-2.x.js +++ b/extensions/cocostudio/loader/parsers/action-2.x.js @@ -65,14 +65,14 @@ deferred: function(json, resourcePath, action, file){ var animationlist = json["Content"]["Content"]["AnimationList"]; var length = animationlist ? animationlist.length : 0; - for (var i = 0; i < length; i++) { - var animationdata = animationlist[i]; - var info = { name: null, startIndex: null, endIndex: null }; - info.name = animationdata["Name"]; - info.startIndex = animationdata["StartIndex"]; - info.endIndex = animationdata["EndIndex"]; - action.addAnimationInfo(info); - } + for (var i = 0; i < length; i++){ + var animationdata = animationlist[i]; + var info = { name: null, startIndex: null, endIndex: null }; + info.name = animationdata["Name"]; + info.startIndex = animationdata["StartIndex"]; + info.endIndex = animationdata["EndIndex"]; + action.addAnimationInfo(info); + } } }); @@ -220,7 +220,7 @@ }, { name: "ActionValue", - handle: function(options){ + handle: function (options) { var frame = new ccs.InnerActionFrame(); var innerActionType = options["InnerActionType"]; @@ -229,6 +229,10 @@ var singleFrameIndex = options["SingleFrameIndex"]; + var frameIndex = options["FrameIndex"]; + if(frameIndex !== undefined) + frame.setFrameIndex(frameIndex); + frame.setInnerActionType(ccs.InnerActionType[innerActionType]); frame.setSingleFrameIndex(singleFrameIndex); @@ -240,6 +244,15 @@ } ]; + var loadEasingDataWithFlatBuffers = function(frame, options){ + var type = options["Type"]; + frame.setTweenType(type); + var points = options["Points"]; + if(points){ + frame.setEasingParams(points); + } + }; + frameList.forEach(function(item){ parser.registerParser(item.name, function(options, resourcePath){ var timeline = new ccs.Timeline(); @@ -252,6 +265,10 @@ frame.setFrameIndex(frameData["FrameIndex"]); var tween = frameData["Tween"] != null ? frameData["Tween"] : true; frame.setTween(tween); + //https://github.com/cocos2d/cocos2d-x/pull/11388/files + var easingData = options["EasingData"]; + if(easingData) + loadEasingDataWithFlatBuffers(frame, easingData); timeline.addFrame(frame); }); } diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 542fb9b5eb..fe4bd63ef8 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -111,7 +111,13 @@ node.setTag(json["Tag"] || 0); - node.setUserObject(new ccs.ActionTimelineData(json["ActionTag"] || 0)); + var actionTag = json["ActionTag"] || 0; + var extensionData = new ccs.ObjectExtensionData(); + var customProperty = json["UserData"]; + if(customProperty !== undefined) + extensionData.setCustomProperty(customProperty); + extensionData.setActionTag(actionTag); + node.setUserObject(extensionData); node.setCascadeColorEnabled(true); node.setCascadeOpacityEnabled(true); @@ -175,6 +181,16 @@ } }); + var blendData = json["BlendFunc"]; + if(json["BlendFunc"]) { + var blendFunc = cc.BlendFunc.ALPHA_PREMULTIPLIED; + if (blendData["Src"] !== undefined) + blendFunc.src = blendData["Src"]; + if (blendData["Dst"] !== undefined) + blendFunc.dst = blendData["Dst"]; + node.setBlendFunc(new cc.BlendFunc()); + } + if(json["FlipX"]) node.setFlippedX(true); if(json["FlipY"]) @@ -203,6 +219,16 @@ node = new cc.ParticleSystem(path); self.generalAttributes(node, json); !cc.sys.isNative && node.setDrawMode(cc.ParticleSystem.TEXTURE_MODE); + + var blendData = json["BlendFunc"]; + if(json["BlendFunc"]){ + var blendFunc = cc.BlendFunc.ALPHA_PREMULTIPLIED; + if(blendData["Src"] !== undefined) + blendFunc.src = blendData["Src"]; + if(blendData["Dst"] !== undefined) + blendFunc.dst = blendData["Dst"]; + node.setBlendFunc(new cc.BlendFunc()); + } }); return node; }; @@ -227,7 +253,12 @@ var actionTag = json["ActionTag"] || 0; widget.setActionTag(actionTag); - widget.setUserObject(new ccs.ActionTimelineData(actionTag)); + var extensionData = new ccs.ObjectExtensionData(); + var customProperty = json["UserData"]; + if(customProperty !== undefined) + extensionData.setCustomProperty(customProperty); + extensionData.setActionTag(actionTag); + widget.setUserObject(extensionData); var rotationSkewX = json["RotationSkewX"]; if (rotationSkewX) @@ -492,6 +523,16 @@ } widget.setTextVerticalAlignment(v_alignment); + if(json["OutlineEnabled"] && json["OutlineColor"]) + widget.enableOutline(getColor(json["OutlineColor"]), json["OutlineSize"] || 0); + + if(json["ShadowEnabled"] && json["ShadowColor"]) + widget.enableShadow( + getColor(json["ShadowColor"]), + cc.size(getParam(json["ShadowOffsetX"], 2), getParam(json["ShadowOffsetY"], -2)), + json["ShadowBlurRadius"] || 0 + ); + //todo check it var isCustomSize = json["IsCustomSize"]; if(isCustomSize != null) @@ -1157,6 +1198,9 @@ parser.generalAttributes(obj.node, json); if(obj.action && obj.node){ obj.action.tag = obj.node.tag; + var InnerActionSpeed = json["InnerActionSpeed"]; + if(InnerActionSpeed !== undefined) + obj.action.setTimeSpeed(InnerActionSpeed); obj.node.runAction(obj.action); obj.action.gotoFrameAndPause(0); } @@ -1245,7 +1289,8 @@ var r = json["R"] != null ? json["R"] : 255; var g = json["G"] != null ? json["G"] : 255; var b = json["B"] != null ? json["B"] : 255; - return cc.color(r, g, b); + var a = json["A"] != null ? json["A"] : 255; + return cc.color(r, g, b, a); }; var setContentSize = function(node, size){ diff --git a/extensions/cocostudio/timeline/ActionTimeline.js b/extensions/cocostudio/timeline/ActionTimeline.js index 0bada129ee..9109c60ea7 100644 --- a/extensions/cocostudio/timeline/ActionTimeline.js +++ b/extensions/cocostudio/timeline/ActionTimeline.js @@ -60,6 +60,34 @@ ccs.ActionTimelineData = ccs.Class.extend({ }); +ccs.ObjectExtensionData = ccs.Class.extend({ + + _customProperty: null, + _timelineData: null, + + ctor: function(){ + this._init(); + }, + + _init: function(){ + this._timelineData = new ccs.ActionTimelineData(0); + return true; + }, + + setActionTag: function(actionTag){ + this._timelineData.setActionTag(actionTag); + }, + + getActionTag: function(){ + return this._timelineData.getActionTag(); + } +}); + +ccs.ObjectExtensionData.create = function(){ + var ret = new ccs.ObjectExtensionData(); + return ret; +}; + /** * Create new ActionTimelineData. * diff --git a/extensions/cocostudio/timeline/Frame.js b/extensions/cocostudio/timeline/Frame.js index 460bbf86d2..b76f1e1328 100644 --- a/extensions/cocostudio/timeline/Frame.js +++ b/extensions/cocostudio/timeline/Frame.js @@ -33,12 +33,15 @@ ccs.Frame = ccs.Class.extend({ _tween: null, _timeline: null, _node: null, + _tweenType: null, + _easingParam: null, ctor: function(){ this._frameIndex = 0; this._tween = true; this._timeline = null; this._node = null; + this._easingParam = []; }, _emitEvent: function(){ @@ -50,6 +53,8 @@ ccs.Frame = ccs.Class.extend({ _cloneProperty: function(frame){ this._frameIndex = frame.getFrameIndex(); this._tween = frame.isTween(); + this._tweenType = frame.getTweenType(); + this.setEasingParams(frame.getEasingParams()); }, /** @@ -131,6 +136,15 @@ ccs.Frame = ccs.Class.extend({ * @param {number} percent */ apply: function(percent){ + if(!this._tween) + return; + if(this._tweenType !== ccs.FrameEaseType.TWEEN_EASING_MAX && this._tweenType !== ccs.FrameEaseType.Linear) + percent = this.tweenPercent(percent); + this._onApply(percent); + }, + + _onApply: function(percent){ + }, /** @@ -140,6 +154,140 @@ ccs.Frame = ccs.Class.extend({ * @return {ccs.Frame} */ clone: function(){ // = 0 + }, + + tweenPercent: function(percent){ + return this._tweenTo(percent, this._tweenType, this._easingParam); + }, + + setEasingParams: function(easingParams){ + if(easingParams){ + this._easingParam.length = 0; + for(var i=0; i Date: Tue, 14 Apr 2015 18:26:54 +0800 Subject: [PATCH 0161/1039] Update -x timeline and parser --- .../cocostudio/loader/parsers/action-2.x.js | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/action-2.x.js b/extensions/cocostudio/loader/parsers/action-2.x.js index 58d5801c5c..8e27788733 100644 --- a/extensions/cocostudio/loader/parsers/action-2.x.js +++ b/extensions/cocostudio/loader/parsers/action-2.x.js @@ -65,14 +65,14 @@ deferred: function(json, resourcePath, action, file){ var animationlist = json["Content"]["Content"]["AnimationList"]; var length = animationlist ? animationlist.length : 0; - for (var i = 0; i < length; i++){ - var animationdata = animationlist[i]; - var info = { name: null, startIndex: null, endIndex: null }; - info.name = animationdata["Name"]; - info.startIndex = animationdata["StartIndex"]; - info.endIndex = animationdata["EndIndex"]; - action.addAnimationInfo(info); - } + for (var i = 0; i < length; i++){ + var animationdata = animationlist[i]; + var info = { name: null, startIndex: null, endIndex: null }; + info.name = animationdata["Name"]; + info.startIndex = animationdata["StartIndex"]; + info.endIndex = animationdata["EndIndex"]; + action.addAnimationInfo(info); + } } }); From b9217d8e858fb3a0dc1bac9b36005cd277f14329 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 15 Apr 2015 11:23:05 +0800 Subject: [PATCH 0162/1039] Add enumerateChildren for cc.Node --- cocos2d/core/base-nodes/CCNode.js | 87 +++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index 50af27bddc..ac7fbc5740 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -2426,6 +2426,93 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ return new cc.Node.CanvasRenderCmd(this); else return new cc.Node.WebGLRenderCmd(this); + }, + + enumerateChildren: function(name, callback){ + cc.assert(name.length != 0, "Invalid name"); + cc.assert(name.length != null, "Invalid callback function"); + + var length = name.length; + var subStrStartPos = 0; + var subStrlength = length; + + // Starts with '//'? + var searchRecursively = false; + if(length > 2 && name[0] === "/" && name[1] === "/"){ + searchRecursively = true; + subStrStartPos = 2; + subStrlength -= 2; + } + + var searchFromParent = false; + if(length > 3 && name[length-3] === "/" && name[length-2] === "." && name[length-1] === "."){ + searchFromParent = true; + subStrlength -= 3; + } + + var newName = name.substr(subStrStartPos, subStrlength); + + if(searchFromParent) + newName = "[[:alnum:]]+/" + newName; + + if(searchRecursively) + this.doEnumerateRecursive(this, newName, callback); + else + this.doEnumerate(newName, callback); + }, + + doEnumerateRecursive: function(node, name, callback){ + var ret = false; + if(node.doEnumerate(name,callback)){ + ret = true; + }else{ + var child, + children = node.getChildren(), + length = children.length; + // search its children + for (var i=0; i Date: Wed, 15 Apr 2015 14:58:17 +0800 Subject: [PATCH 0163/1039] Add enumerateChildren for cc.Node --- cocos2d/core/base-nodes/CCNode.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index ac7fbc5740..0f6969ca1b 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -2429,8 +2429,8 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ }, enumerateChildren: function(name, callback){ - cc.assert(name.length != 0, "Invalid name"); - cc.assert(name.length != null, "Invalid callback function"); + cc.assert(name && name.length != 0, "Invalid name"); + cc.assert(callback != null, "Invalid callback function"); var length = name.length; var subStrStartPos = 0; From 690a06c79d0c3d3ba2d6d35cb600145e7127ba84 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 15 Apr 2015 14:59:21 +0800 Subject: [PATCH 0164/1039] Add notes --- cocos2d/core/base-nodes/CCNode.js | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index 0f6969ca1b..e57c63e92f 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -2428,6 +2428,32 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ return new cc.Node.WebGLRenderCmd(this); }, + /** Search the children of the receiving node to perform processing for nodes which share a name. + * + * @param name The name to search for, supports c++11 regular expression. + * Search syntax options: + * `//`: Can only be placed at the begin of the search string. This indicates that it will search recursively. + * `..`: The search should move up to the node's parent. Can only be placed at the end of string. + * `/` : When placed anywhere but the start of the search string, this indicates that the search should move to the node's children. + * + * @code + * enumerateChildren("//MyName", ...): This searches the children recursively and matches any node with the name `MyName`. + * enumerateChildren("[[:alnum:]]+", ...): This search string matches every node of its children. + * enumerateChildren("A[[:digit:]]", ...): This searches the node's children and returns any child named `A0`, `A1`, ..., `A9`. + * enumerateChildren("Abby/Normal", ...): This searches the node's grandchildren and returns any node whose name is `Normal` + * and whose parent is named `Abby`. + * enumerateChildren("//Abby/Normal", ...): This searches recursively and returns any node whose name is `Normal` and whose + * parent is named `Abby`. + * @endcode + * + * @warning Only support alpha or number for name, and not support unicode. + * + * @param callback A callback function to execute on nodes that match the `name` parameter. The function takes the following arguments: + * `node` + * A node that matches the name + * And returns a boolean result. Your callback can return `true` to terminate the enumeration. + * + */ enumerateChildren: function(name, callback){ cc.assert(name && name.length != 0, "Invalid name"); cc.assert(callback != null, "Invalid callback function"); From 51af269ed9e2f152d4e932dbf38f585669c800b7 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 15 Apr 2015 15:21:44 +0800 Subject: [PATCH 0165/1039] Update -x timeline and parser --- extensions/cocostudio/loader/parsers/action-2.x.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/extensions/cocostudio/loader/parsers/action-2.x.js b/extensions/cocostudio/loader/parsers/action-2.x.js index 8e27788733..dfe69dc51f 100644 --- a/extensions/cocostudio/loader/parsers/action-2.x.js +++ b/extensions/cocostudio/loader/parsers/action-2.x.js @@ -249,6 +249,9 @@ frame.setTweenType(type); var points = options["Points"]; if(points){ + points = points.map(function(p){ + return cc.p(p["X"], p["Y"]); + }); frame.setEasingParams(points); } }; @@ -266,7 +269,7 @@ var tween = frameData["Tween"] != null ? frameData["Tween"] : true; frame.setTween(tween); //https://github.com/cocos2d/cocos2d-x/pull/11388/files - var easingData = options["EasingData"]; + var easingData = frameData["EasingData"]; if(easingData) loadEasingDataWithFlatBuffers(frame, easingData); timeline.addFrame(frame); From 8d8c2004a203e547c8cbfe09b2c00b2b34092aa1 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 15 Apr 2015 15:38:16 +0800 Subject: [PATCH 0166/1039] Update -x timeline and parser --- extensions/cocostudio/loader/parsers/timelineParser-2.x.js | 2 +- extensions/cocostudio/timeline/ActionTimeline.js | 7 +------ 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index fe4bd63ef8..cae39cfa3d 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -188,7 +188,7 @@ blendFunc.src = blendData["Src"]; if (blendData["Dst"] !== undefined) blendFunc.dst = blendData["Dst"]; - node.setBlendFunc(new cc.BlendFunc()); + node.setBlendFunc(blendFunc); } if(json["FlipX"]) diff --git a/extensions/cocostudio/timeline/ActionTimeline.js b/extensions/cocostudio/timeline/ActionTimeline.js index 9109c60ea7..3712238878 100644 --- a/extensions/cocostudio/timeline/ActionTimeline.js +++ b/extensions/cocostudio/timeline/ActionTimeline.js @@ -66,10 +66,6 @@ ccs.ObjectExtensionData = ccs.Class.extend({ _timelineData: null, ctor: function(){ - this._init(); - }, - - _init: function(){ this._timelineData = new ccs.ActionTimelineData(0); return true; }, @@ -84,8 +80,7 @@ ccs.ObjectExtensionData = ccs.Class.extend({ }); ccs.ObjectExtensionData.create = function(){ - var ret = new ccs.ObjectExtensionData(); - return ret; + return new ccs.ObjectExtensionData(); }; /** From ed70bb073a97612b62656927160ec5300f7409c3 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 15 Apr 2015 16:53:08 +0800 Subject: [PATCH 0167/1039] Fix ccs.TweenType naming issue --- .../armature/animation/CCProcessBase.js | 2 +- .../cocostudio/armature/animation/CCTween.js | 10 +- .../cocostudio/armature/datas/CCDatas.js | 4 +- .../armature/utils/CCDataReaderHelper.js | 12 +- .../armature/utils/CCTweenFunction.js | 130 +++++++++--------- 5 files changed, 79 insertions(+), 79 deletions(-) diff --git a/extensions/cocostudio/armature/animation/CCProcessBase.js b/extensions/cocostudio/armature/animation/CCProcessBase.js index e98cb7fd94..a4707d3854 100644 --- a/extensions/cocostudio/armature/animation/CCProcessBase.js +++ b/extensions/cocostudio/armature/animation/CCProcessBase.js @@ -112,7 +112,7 @@ ccs.ProcessBase = ccs.Class.extend(/** @lends ccs.ProcessBase# */{ this._durationTween = 0; this._rawDuration = 0; this._loopType = ccs.ANIMATION_TYPE_LOOP_BACK; - this._tweenEasing = ccs.TweenType.linear; + this._tweenEasing = ccs.TweenType.LINEAR; this.animationInternal = 1 / 60; this._curFrameIndex = 0; this._durationTween = 0; diff --git a/extensions/cocostudio/armature/animation/CCTween.js b/extensions/cocostudio/armature/animation/CCTween.js index ce0da172cc..5706d1d595 100644 --- a/extensions/cocostudio/armature/animation/CCTween.js +++ b/extensions/cocostudio/armature/animation/CCTween.js @@ -49,7 +49,7 @@ ccs.Tween = ccs.ProcessBase.extend(/** @lends ccs.Tween# */{ ctor:function (bone) { ccs.ProcessBase.prototype.ctor.call(this); - this._frameTweenEasing = ccs.TweenType.linear; + this._frameTweenEasing = ccs.TweenType.LINEAR; ccs.Tween.prototype.init.call(this, bone); }, @@ -109,7 +109,7 @@ ccs.Tween = ccs.ProcessBase.extend(/** @lends ccs.Tween# */{ this.setBetween(nextKeyFrame, nextKeyFrame); else this.setBetween(this._tweenData, nextKeyFrame); - this._frameTweenEasing = ccs.TweenType.linear; + this._frameTweenEasing = ccs.TweenType.LINEAR; } else if (this._movementBoneData.frameList.length > 1) { this._durationTween = durationTween * this._movementBoneData.scale; @@ -219,7 +219,7 @@ ccs.Tween = ccs.ProcessBase.extend(/** @lends ccs.Tween# */{ if (locLoopType > ccs.ANIMATION_TYPE_TO_LOOP_BACK) locCurrentPercent = this.updateFrameData(locCurrentPercent); - if (this._frameTweenEasing !== ccs.TweenType.tweenEasingMax) + if (this._frameTweenEasing !== ccs.TweenType.TWEEN_EASING_MAX) this.tweenNodeTo(locCurrentPercent); }, @@ -396,8 +396,8 @@ ccs.Tween = ccs.ProcessBase.extend(/** @lends ccs.Tween# */{ /* * if frame tween easing equal to TWEEN_EASING_MAX, then it will not do tween. */ - var tweenType = (this._frameTweenEasing !== ccs.TweenType.linear) ? this._frameTweenEasing : this._tweenEasing; - if (tweenType !== ccs.TweenType.tweenEasingMax && tweenType !== ccs.TweenType.linear && !this._passLastFrame) { + var tweenType = (this._frameTweenEasing !== ccs.TweenType.LINEAR) ? this._frameTweenEasing : this._tweenEasing; + if (tweenType !== ccs.TweenType.TWEEN_EASING_MAX && tweenType !== ccs.TweenType.LINEAR && !this._passLastFrame) { currentPercent = ccs.TweenFunction.tweenTo(currentPercent, tweenType, this._from.easingParams); } return currentPercent; diff --git a/extensions/cocostudio/armature/datas/CCDatas.js b/extensions/cocostudio/armature/datas/CCDatas.js index bfab738d55..6aa958b36a 100644 --- a/extensions/cocostudio/armature/datas/CCDatas.js +++ b/extensions/cocostudio/armature/datas/CCDatas.js @@ -549,7 +549,7 @@ ccs.FrameData = ccs.BaseData.extend(/** @lends ccs.FrameData# */{ ctor:function () { ccs.BaseData.prototype.ctor.call(this); this.duration = 1; - this.tweenEasing = ccs.TweenType.linear; + this.tweenEasing = ccs.TweenType.LINEAR; this.easingParamNumber = 0; this.easingParams = []; this.displayIndex = 0; @@ -675,7 +675,7 @@ ccs.MovementData = function(){ * Which tween easing effect the movement use * TWEEN_EASING_MAX : use the value from MovementData get from flash design panel */ - this.tweenEasing = ccs.TweenType.linear; + this.tweenEasing = ccs.TweenType.LINEAR; this.movBoneDataDic = {}; }; diff --git a/extensions/cocostudio/armature/utils/CCDataReaderHelper.js b/extensions/cocostudio/armature/utils/CCDataReaderHelper.js index cc3ffb62a3..e23fad1aa4 100644 --- a/extensions/cocostudio/armature/utils/CCDataReaderHelper.js +++ b/extensions/cocostudio/armature/utils/CCDataReaderHelper.js @@ -559,9 +559,9 @@ ccs.dataReaderHelper = /** @lends ccs.dataReaderHelper# */{ if (easing) { if (easing != ccs.CONST_FL_NAN) { tweenEasing = easing == null ? 0 : parseFloat(easing); - movementData.tweenEasing = tweenEasing === 2 ? ccs.TweenType.sineEaseInOut : tweenEasing; + movementData.tweenEasing = tweenEasing === 2 ? ccs.TweenType.SINE_EASEINOUT : tweenEasing; } else - movementData.tweenEasing = ccs.TweenType.linear; + movementData.tweenEasing = ccs.TweenType.LINEAR; } var movBonesXml = movementXML.querySelectorAll(ccs.CONST_MOVEMENT + " > " + ccs.CONST_BONE); @@ -610,7 +610,7 @@ ccs.dataReaderHelper = /** @lends ccs.dataReaderHelper# */{ movementData.scale = json[ccs.CONST_A_MOVEMENT_SCALE] == null ? 1 : json[ccs.CONST_A_MOVEMENT_SCALE]; } - movementData.tweenEasing = json[ccs.CONST_A_TWEEN_EASING] == null ? ccs.TweenType.linear : json[ccs.CONST_A_TWEEN_EASING]; + movementData.tweenEasing = json[ccs.CONST_A_TWEEN_EASING] == null ? ccs.TweenType.LINEAR : json[ccs.CONST_A_TWEEN_EASING]; var name = json[ccs.CONST_A_NAME]; if(name) movementData.name = name; @@ -898,9 +898,9 @@ ccs.dataReaderHelper = /** @lends ccs.dataReaderHelper# */{ if(_easing != ccs.CONST_FL_NAN){ tweenEasing = frameXML.getAttribute(ccs.CONST_A_TWEEN_EASING); if( tweenEasing ) - frameData.tweenEasing = (tweenEasing === 2) ? ccs.TweenType.sineEaseInOut : tweenEasing; + frameData.tweenEasing = (tweenEasing === 2) ? ccs.TweenType.SINE_EASEINOUT : tweenEasing; } else - frameData.tweenEasing = ccs.TweenType.linear; + frameData.tweenEasing = ccs.TweenType.LINEAR; } if (parentFrameXml) { @@ -935,7 +935,7 @@ ccs.dataReaderHelper = /** @lends ccs.dataReaderHelper# */{ this.decodeNodeFromJson(frameData, json, dataInfo); - frameData.tweenEasing = json[ccs.CONST_A_TWEEN_EASING] || ccs.TweenType.linear; + frameData.tweenEasing = json[ccs.CONST_A_TWEEN_EASING] || ccs.TweenType.LINEAR; frameData.displayIndex = json[ccs.CONST_A_DISPLAY_INDEX]; var bd_src = json[ccs.CONST_A_BLEND_SRC] == null ? cc.BLEND_SRC : json[ccs.CONST_A_BLEND_SRC]; var bd_dst = json[ccs.CONST_A_BLEND_DST] == null ? cc.BLEND_DST : json[ccs.CONST_A_BLEND_DST]; diff --git a/extensions/cocostudio/armature/utils/CCTweenFunction.js b/extensions/cocostudio/armature/utils/CCTweenFunction.js index b6d62d482e..7ced7fad96 100644 --- a/extensions/cocostudio/armature/utils/CCTweenFunction.js +++ b/extensions/cocostudio/armature/utils/CCTweenFunction.js @@ -28,50 +28,50 @@ * @type Object */ ccs.TweenType = { - customEasing: -1, - linear: 0, + CUSTOM_EASING: -1, + LINEAR: 0, - sineEaseIn: 1, - sineEaseOut: 2, - sineEaseInOut: 3, + SINE_EASEIN: 1, + SINE_EASEOUT: 2, + SINE_EASEINOUT: 3, - quadEaseIn: 4, - quadEaseOut: 5, - quadEaseInOut: 6, + QUAD_EASEIN: 4, + QUAD_EASEOUT: 5, + QUAD_EASEINOUT: 6, - cubicEaseIn: 7, - cubicEaseOut: 8, - cubicEaseInOut: 9, + CUBIC_EASEIN: 7, + CUBIC_EASEOUT: 8, + CUBIC_EASEINOUT: 9, - quartEaseIn: 10, - quartEaseOut: 11, - quartEaseInOut: 12, + QUART_EASEIN: 10, + QUART_EASEOUT: 11, + QUART_EASEINOUT: 12, - quintEaseIn: 13, - quintEaseOut: 14, - quintEaseInOut: 15, + QUINT_EASEIN: 13, + QUINT_EASEOUT: 14, + QUINT_EASEINOUT: 15, - expoEaseIn: 16, - expoEaseOut: 17, - expoEaseInOut: 18, + EXPO_EASEIN: 16, + EXPO_EASEOUT: 17, + EXPO_EASEINOUT: 18, - circEaseIn: 19, - eircEaseOut: 20, - circEaseInOut: 21, + CIRC_EASEIN: 19, + CIRC_EASEOUT: 20, + CIRC_EASEINOUT: 21, - elasticEaseIn: 22, - elasticEaseOut: 23, - elasticEaseInOut: 24, + ELASTIC_EASEIN: 22, + ELASTIC_EASEOUT: 23, + ELASTIC_EASEINOUT: 24, - backEaseIn: 25, - backEaseOut: 26, - backEaseInOut: 27, + BACK_EASEIN: 25, + BACK_EASEOUT: 26, + BACK_EASEINOUT: 27, - bounceEaseIn: 28, - bounceEaseOut: 29, - bounceEaseInOut: 30, + BOUNCE_EASEIN: 28, + BOUNCE_EASEOUT: 29, + BOUNCE_EASEINOUT: 30, - tweenEasingMax: 10000 + TWEEN_EASING_MAX: 10000 }; ccs.TweenFunction = ccs.TweenFunction || ccs.Class.extend({}); @@ -84,97 +84,97 @@ ccs.TweenFunction.tweenTo = function (time, type, easingParam) { var delta = 0; switch (type) { - case ccs.TweenType.customEasing: + case ccs.TweenType.CUSTOM_EASING: delta = this.customEase(time, easingParam); break; - case ccs.TweenType.linear: + case ccs.TweenType.LINEAR: delta = this.linear(time); break; - case ccs.TweenType.sineEaseIn: + case ccs.TweenType.SINE_EASEIN: delta = this.sineEaseIn(time); break; - case ccs.TweenType.sineEaseOut: + case ccs.TweenType.SINE_EASEOUT: delta = this.sineEaseOut(time); break; - case ccs.TweenType.sineEaseInOut: + case ccs.TweenType.SINE_EASEINOUT: delta = this.sineEaseInOut(time); break; - case ccs.TweenType.quadEaseIn: + case ccs.TweenType.QUAD_EASEIN: delta = this.quadEaseIn(time); break; - case ccs.TweenType.quadEaseOut: + case ccs.TweenType.QUAD_EASEOUT: delta = this.quadEaseOut(time); break; - case ccs.TweenType.quadEaseInOut: + case ccs.TweenType.QUAD_EASEINOUT: delta = this.quadEaseInOut(time); break; - case ccs.TweenType.cubicEaseIn: + case ccs.TweenType.CUBIC_EASEIN: delta = this.cubicEaseIn(time); break; - case ccs.TweenType.cubicEaseOut: + case ccs.TweenType.CUBIC_EASEOUT: delta = this.cubicEaseOut(time); break; - case ccs.TweenType.cubicEaseInOut: + case ccs.TweenType.CUBIC_EASEINOUT: delta = this.cubicEaseInOut(time); break; - case ccs.TweenType.quartEaseIn: + case ccs.TweenType.QUART_EASEIN: delta = this.quartEaseIn(time); break; - case ccs.TweenType.quartEaseOut: + case ccs.TweenType.QUART_EASEOUT: delta = this.quartEaseOut(time); break; - case ccs.TweenType.quartEaseInOut: + case ccs.TweenType.QUART_EASEINOUT: delta = this.quartEaseInOut(time); break; - case ccs.TweenType.quintEaseIn: + case ccs.TweenType.QUINT_EASEIN: delta = this.quintEaseIn(time); break; - case ccs.TweenType.quintEaseOut: + case ccs.TweenType.QUINT_EASEOUT: delta = this.quintEaseOut(time); break; - case ccs.TweenType.quintEaseInOut: + case ccs.TweenType.QUINT_EASEINOUT: delta = this.quintEaseInOut(time); break; - case ccs.TweenType.expoEaseIn: + case ccs.TweenType.EXPO_EASEIN: delta = this.expoEaseIn(time); break; - case ccs.TweenType.expoEaseOut: + case ccs.TweenType.EXPO_EASEOUT: delta = this.expoEaseOut(time); break; - case ccs.TweenType.expoEaseInOut: + case ccs.TweenType.EXPO_EASEINOUT: delta = this.expoEaseInOut(time); break; - case ccs.TweenType.circEaseIn: + case ccs.TweenType.CIRC_EASEIN: delta = this.circEaseIn(time); break; - case ccs.TweenType.eircEaseOut: + case ccs.TweenType.CIRC_EASEOUT: delta = this.circEaseOut(time); break; - case ccs.TweenType.circEaseInOut: + case ccs.TweenType.CIRC_EASEINOUT: delta = this.circEaseInOut(time); break; - case ccs.TweenType.elasticEaseIn: + case ccs.TweenType.ELASTIC_EASEIN: var period = 0.3; if(null != easingParam && easingParam.length > 0){ period = easingParam[0]; } delta = this.elasticEaseIn(time, period); break; - case ccs.TweenType.elasticEaseOut: + case ccs.TweenType.ELASTIC_EASEOUT: var period = 0.3; if(null != easingParam && easingParam.length > 0){ period = easingParam[0]; } delta = this.elasticEaseOut(time, period); break; - case ccs.TweenType.elasticEaseInOut: + case ccs.TweenType.ELASTIC_EASEINOUT: var period = 0.3; if(null != easingParam && easingParam.length > 0){ period = easingParam[0]; @@ -182,23 +182,23 @@ ccs.TweenFunction.tweenTo = function (time, type, easingParam) { delta = this.elasticEaseInOut(time, period); break; - case ccs.TweenType.backEaseIn: + case ccs.TweenType.BACK_EASEIN: delta = this.backEaseIn(time); break; - case ccs.TweenType.backEaseOut: + case ccs.TweenType.BACK_EASEOUT: delta = this.backEaseOut(time); break; - case ccs.TweenType.backEaseInOut: + case ccs.TweenType.BACK_EASEINOUT: delta = this.backEaseInOut(time); break; - case ccs.TweenType.bounceEaseIn: + case ccs.TweenType.BOUNCE_EASEIN: delta = this.bounceEaseIn(time); break; - case ccs.TweenType.bounceEaseOut: + case ccs.TweenType.BOUNCE_EASEOUT: delta = this.bounceEaseOut(time); break; - case ccs.TweenType.bounceEaseInOut: + case ccs.TweenType.BOUNCE_EASEINOUT: delta = this.bounceEaseInOut(time); break; From f6a6e460a643e88223e10fe414844453f71783c0 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 16 Apr 2015 11:57:08 +0800 Subject: [PATCH 0168/1039] Optimization of ccs.frame --- extensions/cocostudio/timeline/Frame.js | 166 +++++++++--------------- 1 file changed, 59 insertions(+), 107 deletions(-) diff --git a/extensions/cocostudio/timeline/Frame.js b/extensions/cocostudio/timeline/Frame.js index b76f1e1328..bcc155c22b 100644 --- a/extensions/cocostudio/timeline/Frame.js +++ b/extensions/cocostudio/timeline/Frame.js @@ -157,7 +157,11 @@ ccs.Frame = ccs.Class.extend({ }, tweenPercent: function(percent){ - return this._tweenTo(percent, this._tweenType, this._easingParam); + var func = ccs.Frame.tweenToMap[this._tweenType]; + if(func) + return func(percent, this._easingParam); + else + return percent; }, setEasingParams: function(easingParams){ @@ -182,115 +186,63 @@ ccs.Frame = ccs.Class.extend({ isEnterWhenPassed: function(){ return this._enterWhenPassed; - }, - - _tweenTo: function(time, type, easingParam){ - var period = 0.3; - switch (type) { - case ccs.FrameEaseType.Custom: - case ccs.FrameEaseType.Linear: - break; - case ccs.FrameEaseType.Sine_EaseIn: - time = cc._easeSineInObj.easing(time); - break; - case ccs.FrameEaseType.Sine_EaseOut: - time = cc._easeSineOutObj.easing(time); - break; - case ccs.FrameEaseType.Sine_EaseInOut: - time = cc._easeSineInOutObj.easing(time); - break; - case ccs.FrameEaseType.Quad_EaseIn: - time = cc._easeQuadraticActionIn.easing(time); - break; - case ccs.FrameEaseType.Quad_EaseOut: - time = cc._easeQuadraticActionOut.easing(time); - break; - case ccs.FrameEaseType.Quad_EaseInOut: - time = cc._easeQuadraticActionInOut.easing(time); - break; - case ccs.FrameEaseType.Cubic_EaseIn: - time = cc._easeCubicActionIn.easing(time); - break; - case ccs.FrameEaseType.Cubic_EaseOut: - time = cc._easeCubicActionOut.easing(time); - break; - case ccs.FrameEaseType.Cubic_EaseInOut: - time = cc._easeCubicActionInOut.easing(time); - break; - case ccs.FrameEaseType.Quart_EaseIn: - time = cc._easeQuarticActionIn.easing(time); - break; - case ccs.FrameEaseType.Quart_EaseOut: - time = cc._easeQuarticActionOut.easing(time); - break; - case ccs.FrameEaseType.Quart_EaseInOut: - time = cc._easeQuarticActionInOut.easing(time); - break; - case ccs.FrameEaseType.Quint_EaseIn: - time = cc._easeQuinticActionIn.easing(time); - break; - case ccs.FrameEaseType.Quint_EaseOut: - time = cc._easeQuinticActionOut.easing(time); - break; - case ccs.FrameEaseType.Quint_EaseInOut: - time = cc._easeQuinticActionInOut.easing(time); - break; - case ccs.FrameEaseType.Expo_EaseIn: - time = cc._easeExponentialInObj.easing(time); - break; - case ccs.FrameEaseType.Expo_EaseOut: - time = cc._easeExponentialOutObj.easing(time); - break; - case ccs.FrameEaseType.Expo_EaseInOut: - time = cc._easeExponentialInOutObj.easing(time); - break; - case ccs.FrameEaseType.Circ_EaseIn: - time = cc._easeCircleActionIn.easing(time); - break; - case ccs.FrameEaseType.Circ_EaseOut: - time = cc._easeCircleActionOut.easing(time); - break; - case ccs.FrameEaseType.Circ_EaseInOut: - time = cc._easeCircleActionInOut.easing(time); - break; - case ccs.FrameEaseType.Elastic_EaseIn: - if(easingParam) - period = easingParam[0]; - time = cc.easeElasticIn(period).easing(time); - break; - case ccs.FrameEaseType.Elastic_EaseOut: - if(easingParam) - period = easingParam[0]; - time = cc.easeElasticOut(period).easing(time); - break; - case ccs.FrameEaseType.Elastic_EaseInOut: - if(easingParam) - period = easingParam[0]; - time = cc.easeElasticInOut(period).easing(time); - break; - case ccs.FrameEaseType.Back_EaseIn: - time = cc._easeBackInObj.easing(time); - break; - case ccs.FrameEaseType.Back_EaseOut: - time = cc._easeBackOutObj.easing(time); - break; - case ccs.FrameEaseType.Back_EaseInOut: - time = cc._easeBackInOutObj.easing(time); - break; - case ccs.FrameEaseType.Bounce_EaseIn: - time = cc._easeBounceInObj.easing(time); - break; - case ccs.FrameEaseType.Bounce_EaseOut: - time = cc._easeBounceOutObj.easing(time); - break; - case ccs.FrameEaseType.Bounce_EaseInOut: - time = cc._easeBounceInOutObj.easing(time); - break; - } - return time; } }); +ccs.Frame.tweenToMap = { + 1: cc._easeSineInObj.easing,//Sine_EaseIn + 2: cc._easeSineOutObj.easing,//Sine_EaseOut + 3: cc._easeSineInOutObj.easing,//Sine_EaseInOut + + 4: cc._easeQuadraticActionIn.easing,//Quad_EaseIn + 5: cc._easeQuadraticActionOut.easing,//Quad_EaseOut + 6: cc._easeQuadraticActionInOut.easing,//Quad_EaseInOut + + 7: cc._easeCubicActionIn.easing, //Cubic_EaseIn + 8: cc._easeCubicActionOut.easing,//Cubic_EaseOut + 9: cc._easeCubicActionInOut.easing,//Cubic_EaseInOut + + 10: cc._easeCubicActionIn.easing,//Cubic_EaseIn + 11: cc._easeCubicActionOut.easing,//Cubic_EaseOut + 12: cc._easeCubicActionInOut.easing,//Cubic_EaseInOut + + 13: cc._easeQuinticActionIn.easing,//Quint_EaseIn + 14: cc._easeQuinticActionOut.easing,//Quint_EaseOut + 15: cc._easeQuinticActionInOut.easing,//Quint_EaseInOut + + 16: cc._easeExponentialInObj.easing,//Expo_EaseIn + 17: cc._easeExponentialOutObj.easing,//Expo_EaseOut + 18: cc._easeExponentialInOutObj.easing,//Expo_EaseInOut + + 19: cc._easeCircleActionIn.easing,//Circ_EaseIn + 20: cc._easeCircleActionOut.easing,//Circ_EaseOut + 21: cc._easeCircleActionInOut.easing,//Circ_EaseInOut + + 22: function(time, easingParam){ + var period = 0.3; + easingParam != null && ( period = easingParam[0] ); + return cc.easeElasticIn(period).easing(time); + },//Elastic_EaesIn + 23: function(time, easingParam){ + var period = 0.3; + easingParam != null && ( period = easingParam[0] ); + return cc.easeElasticOut(period).easing(time); + },//Elastic_EaesOut + 24: function(time, easingParam){ + var period = 0.3; + easingParam != null && ( period = easingParam[0] ); + return cc.easeElasticInOut(period).easing(time); + },//Elastic_EaesInOut + + 25: cc._easeBackInObj.easing, //Back_EaseIn + 26: cc._easeBackOutObj.easing, //Back_EaseOut + 27: cc._easeBackInOutObj.easing, //Back_EaseInOut + + 28: cc._easeBounceInObj.easing, //Bounce_EaseIn + 29: cc._easeBounceOutObj.easing, //Bounce_EaseOut + 30: cc._easeBounceInOutObj.easing //Bounce_EaseInOut +}; + /** * Visible frame * To control the display state From 110c2ca379bf79d10f750308f09d93f534e5e26e Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 17 Apr 2015 13:49:15 +0800 Subject: [PATCH 0169/1039] Fixed a bug about the spine draw the not supported mode --- extensions/spine/CCSkeletonWebGLRenderCmd.js | 25 +++++++++++--------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/extensions/spine/CCSkeletonWebGLRenderCmd.js b/extensions/spine/CCSkeletonWebGLRenderCmd.js index 83c6aa93da..5ca4b72113 100644 --- a/extensions/spine/CCSkeletonWebGLRenderCmd.js +++ b/extensions/spine/CCSkeletonWebGLRenderCmd.js @@ -57,6 +57,20 @@ if (!slot.attachment) continue; attachment = slot.attachment; + + switch(slot.attachment.type) { + case sp.ATTACHMENT_TYPE.REGION: + sp._regionAttachment_updateQuad(attachment, slot, quad, node._premultipliedAlpha); + break; + case sp.ATTACHMENT_TYPE.MESH: + sp._meshAttachment_updateQuad(attachment, slot, quad, node._premultipliedAlpha); + break; + case sp.ATTACHMENT_TYPE.SKINNED_MESH: + break; + default: + continue; + } + var regionTextureAtlas = node.getTextureAtlas(attachment); if (slot.data.additiveBlending != additive) { @@ -80,17 +94,6 @@ return; } - switch(slot.attachment.type) { - case sp.ATTACHMENT_TYPE.REGION: - sp._regionAttachment_updateQuad(attachment, slot, quad, node._premultipliedAlpha); - break; - case sp.ATTACHMENT_TYPE.MESH: - sp._meshAttachment_updateQuad(attachment, slot, quad, node._premultipliedAlpha); - break; - case sp.ATTACHMENT_TYPE.SKINNED_MESH: - break; - } - textureAtlas.updateQuad(quad, quadCount); } From 8df2b8149029c33833404a694f95708bf3aa9e99 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 17 Apr 2015 14:19:23 +0800 Subject: [PATCH 0170/1039] Remove todo... --- extensions/cocostudio/loader/parsers/timelineParser-2.x.js | 1 - 1 file changed, 1 deletion(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index cae39cfa3d..aa03d488bc 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -533,7 +533,6 @@ json["ShadowBlurRadius"] || 0 ); - //todo check it var isCustomSize = json["IsCustomSize"]; if(isCustomSize != null) widget.ignoreContentAdaptWithSize(!isCustomSize); From a7a5677a11fdd793435ebdfa2753b543687ada37 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 20 Apr 2015 15:13:35 +0800 Subject: [PATCH 0171/1039] Fixed a bug that is Particle BlendFunc error --- extensions/cocostudio/loader/parsers/timelineParser-2.x.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index aa03d488bc..c3e8ccc0f4 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -227,7 +227,7 @@ blendFunc.src = blendData["Src"]; if(blendData["Dst"] !== undefined) blendFunc.dst = blendData["Dst"]; - node.setBlendFunc(new cc.BlendFunc()); + node.setBlendFunc(blendFunc); } }); return node; From 714ccda1b074ae2abfbc1c1523a3e560dba53cb3 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 20 Apr 2015 17:14:55 +0800 Subject: [PATCH 0172/1039] Synchronization - https://github.com/cocos2d/cocos2d-x/pull/11510 --- .../cocostudio/loader/parsers/timelineParser-2.x.js | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index c3e8ccc0f4..0c2664c57c 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -601,6 +601,17 @@ if(textColor != null) widget.setTitleColor(getColor(textColor)); + var label = widget.getTitleRenderer(); + if(label && json["ShadowEnabled"] && json["ShadowColor"]){ + label.enableShadow( + getColor(json["ShadowColor"]), + cc.size(getParam(json["ShadowOffsetX"], 2), getParam(json["ShadowOffsetY"], -2)), + json["ShadowBlurRadius"] || 0 + ); + } + if(label && json["OutlineEnabled"] && json["OutlineColor"]) + label.enableOutline(getColor(json["OutlineColor"]), json["OutlineSize"] || 0); + var displaystate = getParam(json["DisplayState"], true); widget.setBright(displaystate); widget.setEnabled(displaystate); From 52f7dd217af18a396ae8c1ce735115e4015a3b0b Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 21 Apr 2015 11:48:55 +0800 Subject: [PATCH 0173/1039] To prevent an problem that is function does not exist --- .../cocostudio/loader/parsers/timelineParser-2.x.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 0c2664c57c..99a57fbc0a 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -523,10 +523,10 @@ } widget.setTextVerticalAlignment(v_alignment); - if(json["OutlineEnabled"] && json["OutlineColor"]) + if(json["OutlineEnabled"] && json["OutlineColor"] && widget.enableOutline) widget.enableOutline(getColor(json["OutlineColor"]), json["OutlineSize"] || 0); - if(json["ShadowEnabled"] && json["ShadowColor"]) + if(json["ShadowEnabled"] && json["ShadowColor"] && widget.enableShadow) widget.enableShadow( getColor(json["ShadowColor"]), cc.size(getParam(json["ShadowOffsetX"], 2), getParam(json["ShadowOffsetY"], -2)), @@ -602,14 +602,14 @@ widget.setTitleColor(getColor(textColor)); var label = widget.getTitleRenderer(); - if(label && json["ShadowEnabled"] && json["ShadowColor"]){ + if(label && json["ShadowEnabled"] && json["ShadowColor"] && label.enableShadow){ label.enableShadow( getColor(json["ShadowColor"]), cc.size(getParam(json["ShadowOffsetX"], 2), getParam(json["ShadowOffsetY"], -2)), json["ShadowBlurRadius"] || 0 ); } - if(label && json["OutlineEnabled"] && json["OutlineColor"]) + if(label && json["OutlineEnabled"] && json["OutlineColor"] && label.enableOutline) label.enableOutline(getColor(json["OutlineColor"]), json["OutlineSize"] || 0); var displaystate = getParam(json["DisplayState"], true); From aafdb898ed3a3f4199f74cb3fac54b7046d46a91 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 21 Apr 2015 13:42:45 +0800 Subject: [PATCH 0174/1039] Fix ccs.displayFactory usage issue --- extensions/cocostudio/armature/display/CCDisplayManager.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/cocostudio/armature/display/CCDisplayManager.js b/extensions/cocostudio/armature/display/CCDisplayManager.js index 6be772a0cb..5ea12a0fe7 100644 --- a/extensions/cocostudio/armature/display/CCDisplayManager.js +++ b/extensions/cocostudio/armature/display/CCDisplayManager.js @@ -83,7 +83,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{ } if(display instanceof ccs.DisplayData){ - cc.displayFactory.addDisplay(this._bone, decoDisplay, display); + ccs.displayFactory.addDisplay(this._bone, decoDisplay, display); //! if changed display index is current display index, then change current display to the new display if(index === this._displayIndex) { this._displayIndex = -1; From eb623926aad882db33589e2a0fa6575d2ea1dfac Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 21 Apr 2015 13:42:53 +0800 Subject: [PATCH 0175/1039] Update engine version --- cocos2d/core/platform/CCConfig.js | 2 +- tools/build.xml | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/cocos2d/core/platform/CCConfig.js b/cocos2d/core/platform/CCConfig.js index 4a6ba3834b..ead1460436 100644 --- a/cocos2d/core/platform/CCConfig.js +++ b/cocos2d/core/platform/CCConfig.js @@ -31,7 +31,7 @@ * @type {String} * @name cc.ENGINE_VERSION */ -window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.5"; +window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.6 Beta"; /** *

diff --git a/tools/build.xml b/tools/build.xml index 29c6abadb1..8c05c73ab9 100644 --- a/tools/build.xml +++ b/tools/build.xml @@ -5,8 +5,8 @@ classpath="./compiler/compiler.jar"/> - + debug="false" output="./../lib/cocos2d-js-v3.6-Beta-min.js"> + @@ -298,8 +298,8 @@ - + debug="false" output="./../lib/cocos2d-js-v3.6-Beta-core-min.js"> + From 5502c627269288c167daa160c23d244193ed6bf6 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 21 Apr 2015 16:07:16 +0800 Subject: [PATCH 0176/1039] To fix a problem that is no preload scale9sprite display error --- extensions/ccui/base-classes/UIScale9Sprite.js | 14 ++++++++------ extensions/gui/control-extension/CCScale9Sprite.js | 14 ++++++++------ 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/extensions/ccui/base-classes/UIScale9Sprite.js b/extensions/ccui/base-classes/UIScale9Sprite.js index f828457d2d..e9afd7b658 100644 --- a/extensions/ccui/base-classes/UIScale9Sprite.js +++ b/extensions/ccui/base-classes/UIScale9Sprite.js @@ -601,6 +601,14 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ var tmpTexture = batchNode.getTexture(); var locLoaded = tmpTexture.isLoaded(); this._textureLoaded = locLoaded; + + //this._capInsets = capInsets; + var locCapInsets = this._capInsets; + locCapInsets.x = capInsets.x; + locCapInsets.y = capInsets.y; + locCapInsets.width = capInsets.width; + locCapInsets.height = capInsets.height; + if(!locLoaded){ tmpTexture.addEventListener("load", function(sender){ this._positionsAreDirty = true; @@ -611,12 +619,6 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ var locScale9Image = this._scale9Image; locScale9Image.removeAllChildren(true); - //this._capInsets = capInsets; - var locCapInsets = this._capInsets; - locCapInsets.x = capInsets.x; - locCapInsets.y = capInsets.y; - locCapInsets.width = capInsets.width; - locCapInsets.height = capInsets.height; this._spriteFrameRotated = rotated; var selTexture = locScale9Image.getTexture(); diff --git a/extensions/gui/control-extension/CCScale9Sprite.js b/extensions/gui/control-extension/CCScale9Sprite.js index 917ccd0332..9e1fefa38a 100644 --- a/extensions/gui/control-extension/CCScale9Sprite.js +++ b/extensions/gui/control-extension/CCScale9Sprite.js @@ -596,6 +596,14 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ var tmpTexture = batchNode.getTexture(); var locLoaded = tmpTexture.isLoaded(); this._textureLoaded = locLoaded; + + //this._capInsets = capInsets; + var locCapInsets = this._capInsets; + locCapInsets.x = capInsets.x; + locCapInsets.y = capInsets.y; + locCapInsets.width = capInsets.width; + locCapInsets.height = capInsets.height; + if(!locLoaded){ tmpTexture.addEventListener("load", function(sender){ this._positionsAreDirty = true; @@ -606,12 +614,6 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ var locScale9Image = this._scale9Image; locScale9Image.removeAllChildren(true); - //this._capInsets = capInsets; - var locCapInsets = this._capInsets; - locCapInsets.x = capInsets.x; - locCapInsets.y = capInsets.y; - locCapInsets.width = capInsets.width; - locCapInsets.height = capInsets.height; this._spriteFrameRotated = rotated; var selTexture = locScale9Image.getTexture(); From b70ed3c78bf158ca9df0bb1f098ffd36a0277163 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 21 Apr 2015 16:46:20 +0800 Subject: [PATCH 0177/1039] Change the default value --- extensions/cocostudio/loader/parsers/timelineParser-2.x.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 99a57fbc0a..fd1f20da33 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -610,7 +610,7 @@ ); } if(label && json["OutlineEnabled"] && json["OutlineColor"] && label.enableOutline) - label.enableOutline(getColor(json["OutlineColor"]), json["OutlineSize"] || 0); + label.enableOutline(getColor(json["OutlineColor"]), json["OutlineSize"] || 1); var displaystate = getParam(json["DisplayState"], true); widget.setBright(displaystate); From bdbf527b540125bbc31ce11a4bf1e3a758e2b6fd Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 21 Apr 2015 16:47:39 +0800 Subject: [PATCH 0178/1039] Change the default value --- extensions/cocostudio/loader/parsers/timelineParser-2.x.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index fd1f20da33..2bf55fba5c 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -610,7 +610,7 @@ ); } if(label && json["OutlineEnabled"] && json["OutlineColor"] && label.enableOutline) - label.enableOutline(getColor(json["OutlineColor"]), json["OutlineSize"] || 1); + label.enableOutline(getColor(json["OutlineColor"]), getParam(json["OutlineSize"], 1)); var displaystate = getParam(json["DisplayState"], true); widget.setBright(displaystate); From 7bbe07126d1b3876a6798be9ef447d2bb4dbc7d4 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 21 Apr 2015 17:22:29 +0800 Subject: [PATCH 0179/1039] Change the default value --- extensions/cocostudio/loader/parsers/timelineParser-2.x.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 2bf55fba5c..9288442532 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -524,7 +524,7 @@ widget.setTextVerticalAlignment(v_alignment); if(json["OutlineEnabled"] && json["OutlineColor"] && widget.enableOutline) - widget.enableOutline(getColor(json["OutlineColor"]), json["OutlineSize"] || 0); + widget.enableOutline(getColor(json["OutlineColor"]), getParam(json["OutlineSize"], 1)); if(json["ShadowEnabled"] && json["ShadowColor"] && widget.enableShadow) widget.enableShadow( From 770e08e344ca89048b5709e1eee25d0364034de4 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 21 Apr 2015 18:11:48 +0800 Subject: [PATCH 0180/1039] Add cc.sys.isObjectValid --- CCBoot.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/CCBoot.js b/CCBoot.js index 8c6b92c9fb..1be2d4ff3b 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -1780,6 +1780,21 @@ cc._initSys = function (config, CONFIG_KEY) { // N/A in cocos2d-html5 }; + /** + * Check whether an object is valid, + * In web engine, it will return true if the object exist + * In native engine, it will return true if the JS object and the correspond native object are both valid + * @memberof cc.sys + * @name isObjectValid + * @param {Object} obj + * @return {boolean} Validity of the object + * @function + */ + sys.isObjectValid = function (obj) { + if (obj) return true; + else return false; + }; + /** * Dump system informations * @memberof cc.sys From 6c4381369aa6726ac3b64f9e1c769bd558ccb6ba Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Wed, 22 Apr 2015 11:08:31 +0800 Subject: [PATCH 0181/1039] Fixed #2846: fixed a bug of ccs.ActionTimeline.setCurrentFrame. --- extensions/cocostudio/timeline/ActionTimeline.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/cocostudio/timeline/ActionTimeline.js b/extensions/cocostudio/timeline/ActionTimeline.js index 3712238878..a0500514c3 100644 --- a/extensions/cocostudio/timeline/ActionTimeline.js +++ b/extensions/cocostudio/timeline/ActionTimeline.js @@ -278,7 +278,7 @@ ccs.ActionTimeline = cc.Action.extend({ * Set current frame index, this will cause action plays to this frame. */ setCurrentFrame: function(frameIndex){ - if (frameIndex >= this._startFrame && frameIndex >= this._endFrame){ + if (frameIndex >= this._startFrame && frameIndex <= this._endFrame){ this._currentFrame = frameIndex; this._time = this._currentFrame * this._frameInternal; }else{ From c9357bfbc9f47276b9921320781ab144dee60bdf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A2=A8=E6=B0=B4?= Date: Wed, 22 Apr 2015 14:34:51 +0800 Subject: [PATCH 0182/1039] Fixed a bug of CCNode.setPosition --- cocos2d/core/base-nodes/CCNode.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index e57c63e92f..977d3f9339 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -656,7 +656,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ locPosition.x = newPosOrxValue.x; locPosition.y = newPosOrxValue.y; } else { - if(locPosition.x === newPosOrxValue.x && locPosition.y === yValue) + if(locPosition.x === newPosOrxValue && locPosition.y === yValue) return; locPosition.x = newPosOrxValue; locPosition.y = yValue; From 02cb2409c225db2aa3071d8431e49f8882223545 Mon Sep 17 00:00:00 2001 From: wuzhiming Date: Wed, 22 Apr 2015 15:45:37 +0800 Subject: [PATCH 0183/1039] #2849:add cocosruntime loaderlayer support for v3 --- extensions/runtime/CCLoaderLayer.js | 952 ++++++++++++++++++++++++++++ moduleConfig.json | 4 + 2 files changed, 956 insertions(+) create mode 100644 extensions/runtime/CCLoaderLayer.js diff --git a/extensions/runtime/CCLoaderLayer.js b/extensions/runtime/CCLoaderLayer.js new file mode 100644 index 0000000000..d28dc9b52f --- /dev/null +++ b/extensions/runtime/CCLoaderLayer.js @@ -0,0 +1,952 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ +cc.INT_MAX = Number.MAX_VALUE; +cc.LoaderLayer = cc.Layer.extend({ + _backgroundSprite: null, + _progressBackgroundSprite: null, + _progressBarSprite: null, + _logoSprite: null, + _titleSprite: null, + _groupname: null, + _callback: null, + _selector: null, + _preloadCount: 0, + _isPreloadFromFailed: false, + _progressOriginalWidth: 0, + _isDefaultProgress: true, + _isLandScape: false, + _scaleFactor: null, + + ctor: function (config) { + this._super(); + this._setConfig(config); + }, + _setConfig: function (config) { + if (config) { + cc.LoaderLayer._userConfig = config; + } + }, + onEnter: function () { + this._super(); + this.initData(); + this.initView(); + var config = this._finalConfig; + if (config.onEnter) { + config.onEnter(this); + } + }, + onExit: function () { + this._super(); + var config = this._finalConfig; + if (config.logo.action) { + config.logo.action.release(); + } + if(config.title.action){ + config.title.action.release(); + } + if (config.onExit) { + config.onExit(this); + } + }, + initData: function () { + this._finalConfig = cc.cloneObject(cc.LoaderLayer._config); + var config = this._finalConfig; + if (cc.LoaderLayer._userConfig != null) { + var uConfig = cc.LoaderLayer._userConfig; + if (uConfig.background && uConfig.background.res) { + config.background.res = uConfig.background.res; + } + if (uConfig.title) { + var uTitle = uConfig.title; + var title = config.title; + title.show = typeof uTitle.show != "undefined" ? uTitle.show : title.show; + title.res = uTitle.res ? uTitle.res : title.res; + title.position = uTitle.position ? uTitle.position : title.position; + title.action = uTitle.action ? uTitle.action : title.action; + if (title.action) { + title.action = uTitle.action; + title.action.retain(); + } + } + if (uConfig.logo) { + var uLogo = uConfig.logo; + var logo = config.logo; + logo.show = typeof uLogo.show != "undefined" ? uLogo.show : logo.show; + logo.res = uLogo.res ? uLogo.res : logo.res; + logo.position = uLogo.position ? uLogo.position : logo.position; + if (typeof uLogo.action != "undefined") { + logo.action = uLogo.action; + if (logo.action) { + logo.action.retain(); + } + } + } + if (uConfig.progressBar) { + var uProgress = uConfig.progressBar; + var progress = config.progressBar; + progress.show = typeof uProgress.show != "undefined" ? uProgress.show : progress.show; + if (uProgress.res) { + progress.res = uProgress.res; + this._isDefaultProgress = false; + } + progress.offset = uProgress.offset ? uProgress.offset : progress.offset; + progress.position = uProgress.position ? uProgress.position : progress.position; + progress.barBackgroundRes = uProgress.barBackgroundRes ? uProgress.barBackgroundRes : progress.barBackgroundRes; + } + if (uConfig.tips) { + var uTips = uConfig.tips; + var tips = config.tips; + tips.show = typeof uTips.show != "undefined" ? uTips.show : tips.show; + tips.res = uTips.res ? uTips.res : tips.res; + tips.offset = uTips.offset ? uTips.offset : tips.offset; + tips.fontSize = uTips.fontSize ? uTips.fontSize : tips.fontSize; + tips.position = uTips.position ? uTips.position : tips.position; + tips.color = uTips.color ? uTips.color : tips.color; + if (uConfig.tips.tipsProgress && typeof uConfig.tips.tipsProgress == "function") { + tips.tipsProgress = uConfig.tips.tipsProgress; + } + } + if (typeof uConfig.onEnter == "function") { + config.onEnter = uConfig.onEnter; + } + if (typeof uConfig.onExit == "function") { + config.onExit = uConfig.onExit; + } + } + + if (typeof config.logo.action == "undefined" && cc.LoaderLayer._useDefaultSource) { + config.logo.action = cc.sequence( + cc.spawn(cc.moveBy(0.4, cc.p(0, 40)).easing(cc.easeIn(0.5)), cc.scaleTo(0.4, 0.95, 1.05).easing(cc.easeIn(0.5))), + cc.delayTime(0.08), + cc.spawn(cc.moveBy(0.4, cc.p(0, -40)).easing(cc.easeOut(0.5)), cc.scaleTo(0.4, 1.05, 0.95).easing(cc.easeOut(0.5))) + ).repeatForever(); + config.logo.action.retain(); + } + if (!config.tips.color) { + config.tips.color = cc.color(255, 255, 255); + } + }, + initView: function () { + var config = this._finalConfig; + this._contentLayer = new cc.Layer(); + this._isLandScape = cc.winSize.width > cc.winSize.height; + this._scaleFactor = !cc.LoaderLayer._useDefaultSource ? 1 : cc.winSize.width > cc.winSize.height ? cc.winSize.width / 720 : cc.winSize.width / 480; + + //background + this.backgroundSprite = new cc.Sprite(config.background.res); + this.addChild(this.backgroundSprite); + this.backgroundSprite.x = 0, this.backgroundSprite.y = 0, this.backgroundSprite.anchorX = 0, this.backgroundSprite.anchorY = 0; + if (cc.LoaderLayer._useDefaultSource) { + this.backgroundSprite.scaleX = cc.winSize.width / this.backgroundSprite.width; + this.backgroundSprite.scaleY = cc.winSize.height / this.backgroundSprite.height; + } + + //title + if (config.title.show) { + this.titleSprite = new cc.Sprite(config.title.res); + var defaultTitlePosition = cc.pAdd(cc.visibleRect.center, cc.p(0, this._scaleFactor < 1 ? 0 : this._isLandScape ? -80 : 30)); + this.titleSprite.setPosition(config.title.position ? config.title.position : defaultTitlePosition); + this._contentLayer.addChild(this.titleSprite); + if (config.title.action) { + this.titleSprite.runAction(config.title.action); + } + } + + //logo + if (config.logo.show) { + this.logoSprite = new cc.Sprite(config.logo.res); + var defaultLogoPosition = cc.pAdd(cc.visibleRect.top, cc.p(0, this._scaleFactor < 1 ? 0 : -this.logoSprite.height / 2 - (this._isLandScape ? 56 : 76))); + this.logoSprite.setPosition(config.logo.position ? config.logo.position : defaultLogoPosition); + this._contentLayer.addChild(this.logoSprite); + if (config.logo.action) { + this.logoSprite.runAction(config.logo.action); + } + } + + //progressbar + if (config.progressBar.show) { + this.progressBarSprite = new cc.Sprite(config.progressBar.res); + this._progressOriginalWidth = this.progressBarSprite.width; + this.progressBackgroundSprite = new cc.Sprite(config.progressBar.barBackgroundRes); + this.progressBarSprite.anchorX = 0; + this.progressBarSprite.anchorY = 0; + if (this._isDefaultProgress) { + this._barPoint = new cc.Sprite(config.progressBar.barPoint); + this.progressBarSprite.addChild(this._barPoint); + } + if (config.progressBar.barBackgroundRes == null) { + this.progressBackgroundSprite.setTextureRect(cc.rect(0, 0, this.progressBarSprite.width, this.progressBarSprite.height)); + } + if (config.progressBar.offset == null) { + var deltaProgressWithX = (this.progressBackgroundSprite.width - this.progressBarSprite.width) / 2; + var deltaProgressWithY = (this.progressBackgroundSprite.height - this.progressBarSprite.height) / 2; + config.progressBar.offset = cc.p(deltaProgressWithX, deltaProgressWithY); + } + this.progressBarSprite.setPosition(config.progressBar.offset); + this.progressBackgroundSprite.addChild(this.progressBarSprite); + var defaultProgressPosition = cc.pAdd(cc.visibleRect.bottom, cc.p(0, this.progressBarSprite.height / 2 + this._isLandScape ? 60 : 80)); + this.progressBackgroundSprite.setPosition(config.progressBar.position ? config.progressBar.position : defaultProgressPosition); + this._contentLayer.addChild(this.progressBackgroundSprite); + this._setProgress(0); + } + + //tips + if (config.tips.show) { + this.tipsLabel = new cc.LabelTTF("100%", "Arial", config.tips.fontSize); + this.tipsLabel.setColor(config.tips.color); + this.tipsLabel.setPosition(config.tips.position ? config.tips.position : this.progressBackgroundSprite ? cc.p(this.progressBackgroundSprite.x, this.progressBackgroundSprite.y + this.progressBackgroundSprite.height / 2 + 20) : cc.pAdd(cc.visibleRect.bottom, cc.p(0, 100))); + this._contentLayer.addChild(this.tipsLabel); + } + this.addChild(this._contentLayer); + if (this._scaleFactor < 1) { + this._contentLayer.setScale(this._scaleFactor); + this._contentLayer.setPosition(cc.pAdd(this._contentLayer.getPosition(), cc.p(0, -50))); + } + + }, + _setProgress: function (percent) { + if (this.progressBarSprite) { + percent < 1 ? percent : 1; + var width = percent * this._progressOriginalWidth; + this.progressBarSprite.setTextureRect(cc.rect(0, 0, width, this.progressBarSprite.height)); + if (this._isDefaultProgress) { + this._barPoint.setPosition(cc.p(this.progressBarSprite.width, this.progressBarSprite.height / 2)); + } + } + }, + setTipsString: function (str) { + if (this.tipsLabel != null) { + this.tipsLabel.setString(str); + } + }, + getProgressBar: function () { + return this.progressBarSprite; + }, + getTipsLabel: function () { + return this.tipsLabel; + }, + getLogoSprite: function () { + return this.logoSprite; + }, + getTitleSprite: function () { + return this.titleSprite; + }, + updateGroup: function (groupname, callback, target) { + this._groupname = groupname; + this._callback = callback; + this._selector = target; + }, + _resetLoadingLabel: function () { + this.setTipsString(""); + this._setProgress(0); + }, + _preloadSource: function () { + cc.log("_preloadSource: " + this._groupname); + this._resetLoadingLabel(); + if (cc.sys.isNative) { + cc.Loader.preload(this._groupname, this._preload_native, this); + } else { + this._preload_html5(); + } + }, + _preload_html5: function () { + var res = ""; + var groupIndex = []; + var config = this._finalConfig; + if (cc.isString(this._groupname)) { + if (this._groupname.indexOf(".") != -1) { + res = [this._groupname]; + } else { + res = window[this._groupname]; + } + } else if (cc.isArray(this._groupname)) { + res = []; + for (var i = 0; i < this._groupname.length; i++) { + var group = window[this._groupname[i]]; + var preCount = i > 0 ? groupIndex[i - 1] : 0; + groupIndex.push(preCount + group.length); + res = res.concat(group); + } + } + var self = this; + //var progressFunction = self.config.progressCallback ? self.config.progressCallback : null; + cc.loader.load(res, function (result, count, loadedCount) { + var checkGroupName = function (loadedCount) { + for (var i = 0; i < groupIndex.length; i++) { + if (groupIndex[i] >= loadedCount) { + return self._groupname[i]; + } + } + }; + var groupName = checkGroupName(loadedCount); + var status = { + groupName: groupName, + isCompleted: false, + percent: (loadedCount / count * 100) | 0,//(float), + stage: 1, //(1 download,2 unzip) + isFailed: false + } + if (status.percent != 0) { + self._setProgress(status.percent / 100); + } + config.tips.tipsProgress(status, self); + }, function () { + self.removeFromParent(); + self._preloadCount--; + if (self._callback) { + if (self._selector) { + self._callback(self._selector, true); + } else { + self._callback(true); + } + } + self._callback.call(this._target, !status.isFailed); + }); + }, + _preload_native: function (status) { + cc.log(JSON.stringify(status)); + var config = this._finalConfig; + if (status.percent) { + this._setProgress(status.percent / 100); + } + if (config.tips.tipsProgress) { + config.tips.tipsProgress(status, this); + } + if (status.isCompleted || status.isFailed) { + this._preloadCount--; + + if (status.isCompleted) { + cc.log("preload finish!"); + this._isPreloadFromFailed = false; + } + if (status.isFailed) { + cc.log("preload failed!"); + this._isPreloadFromFailed = true; + } + + // Remove loading layer from scene after loading was done. + if (this._preloadCount == 0 && !this._isPreloadFromFailed) { + this.removeFromParent(); + if (cc.LoaderLayer._useDefaultSource) { + var _config = cc.runtime.config.design_resolution || {width: 480, height: 720, policy: "SHOW_ALL"}; + cc.view.setDesignResolutionSize(_config.width, _config.height, cc.ResolutionPolicy[_config.policy]); + } + } + + // Callback must be invoked after removeFromParent. + this._callback.call(this._target, status); + } + }, + _addToScene: function () { + if (this._preloadCount == 0 && !this._isPreloadFromFailed) { + if (cc.sys.isNative && cc.LoaderLayer._useDefaultSource) { + var config = cc.runtime.config.design_resolution; + var isLandscape = false; + var isLargeThanResource = false; + if (config) { + var orientation = cc.runtime.config.orientation; + cc.log("_addToScene orientation is " + orientation); + if (orientation == "landscape") { + isLandscape = true; + isLargeThanResource = config.width > 720 || config.height > 480; + } else { + isLargeThanResource = config.width > 480 || config.height > 720; + } + } + cc.log("isLargeThanResource is " + isLargeThanResource); + cc.view.setDesignResolutionSize(isLargeThanResource ? config.width : isLandscape ? 720 : 480, isLargeThanResource ? config.height : isLandscape ? 480 : 720, cc.ResolutionPolicy["FIXED_HEIGHT"]); + } + cc.director.getRunningScene().addChild(this, cc.INT_MAX - 1); + } + this._preloadCount++; + } +}); +cc.LoaderLayer._config = {//default setting for loaderlayer + background: { + res: "res_engine/preload_bg.jpg" + }, + title: { + show: true, + res: "res_engine/preload_title.png", + position: null, + action: null + }, + logo: { + res: "res_engine/preload_logo.png", + show: true, + position: null + }, + progressBar: { + show: true, + res: "res_engine/progress_bar.png", + offset: null, + position: null, + barBackgroundRes: "res_engine/progress_bg.png", + barPoint: "res_engine/progress_light.png", + barShadow: "res_engine/shadow.png" + }, + tips: { + show: true, + fontSize: 22, + position: null, + color: null, + tipsProgress: function (status, loaderlayer) { + if(loaderlayer.getTipsLabel()){ + var statusStr = "正在"; + if (status.stage == cc.network.preloadstatus.DOWNLOAD) { + statusStr += "下载"; + } else if (status.stage == cc.network.preloadstatus.UNZIP) { + statusStr += "解压"; + } + if (status.groupName) { + statusStr += status.groupName; + } + statusStr += "进度:" + status.percent.toFixed(2) + "%"; + loaderlayer.getTipsLabel().setString(statusStr); + } + } + }, + progressCallback: function (progress) { + + }, + onEnter: function (layer) { + cc.log("LoaderLayer onEnter"); + }, + onExit: function (layer) { + cc.log("LoaderLayer onExit"); + } +} +cc.LoaderLayer.preload = function (groupname, callback, target) { + var loaderLayer = new cc.LoaderLayer(); + var preloadCb = function (status) { + if (status.isFailed) { + var tips, conirmfunc, cancelfunc; + switch (status.errorCode) { + case "err_no_space": + { + tips = "空间不足,请清理磁盘空间"; + conirmfunc = function () { + callPreload(); + }; + cancelfunc = function () { + cc.director.end(); + }; + break; + } + case "err_verify": + { + tips = "校验失败,是否重新下载?"; + conirmfunc = function () { + callPreload(); + } + cancelfunc = function () { + cc.director.end(); + } + break; + } + case "err_network": + { + tips = "网络异常是否重新下载"; + conirmfunc = function () { + callPreload(); + } + cancelfunc = function () { + cc.director.end(); + } + break; + } + default : + { + conirmfunc = cancelfunc = function () { + + } + } + } + cc._NetworkErrorDialog._show(status.errorCode, tips, conirmfunc, cancelfunc); + } else { + if (callback) { + if (target) { + callback.call(target, !status.isFailed); + } else { + callback(!status.isFailed) + } + } + } + } + var callPreload = function () { + if (cc.director.getRunningScene()) { + loaderLayer.updateGroup(groupname, preloadCb, target); + loaderLayer._addToScene(); + loaderLayer._preloadSource(); + } else { + cc.log("Current scene is null we can't start preload"); + } + }; + callPreload(); +} +cc.LoaderLayer._useDefaultSource = true; +cc.LoaderLayer.setUseDefaultSource = function (status) { + cc.LoaderLayer._useDefaultSource = status; +} +cc.LoaderLayer._userConfig = null; +cc.LoaderLayer.setConfig = function (config) { + if(config.title && config.title.action){ + config.title.action.retain(); + } + if(config.logo && config.logo.action){ + config.logo.action.retain(); + } + cc.LoaderLayer._userConfig = config; +} + +cc.Dialog = cc.Layer.extend({ + _userConfig: null, + _finalConfig: null, + _defaultConfig: null, + backgroundSprite: null, + _menuItemConfirm: null, + _menuItemCancel: null, + _messageLabel: null, + _eventListener: null, + _scaleFactor: null, + + ctor: function (config) { + this._super(); + this.setConfig(config); + }, + setConfig: function (config) { + if (config) { + this._userConfig = config; + } + this.removeAllChildren(); + this.initData(); + }, + initData: function () { + this._finalConfig = cc.cloneObject(cc.Dialog._defaultConfig); + var config = this._finalConfig; + if (this._userConfig != null) { + var uConfig = this._userConfig; + if (uConfig.position) { + config.position = uConfig.position; + } + if (uConfig.action) { + config.action = uConfig.action; + } + if (uConfig.background && uConfig.background.res) { + config.background = uConfig.background; + } + if (uConfig.confirmBtn) { + var uConfirmBtn = uConfig.confirmBtn; + var confirmBtn = config.confirmBtn; + confirmBtn.normalRes = uConfirmBtn.normalRes ? uConfirmBtn.normalRes : confirmBtn.normalRes; + confirmBtn.pressRes = uConfirmBtn.pressRes ? uConfirmBtn.pressRes : confirmBtn.pressRes; + confirmBtn.text = typeof uConfirmBtn.text != "undefined" ? uConfirmBtn.text : confirmBtn.text; + confirmBtn.textColor = uConfirmBtn.textColor ? uConfirmBtn.textColor : confirmBtn.textColor; + confirmBtn.fontSize = uConfirmBtn.fontSize ? uConfirmBtn.fontSize : confirmBtn.fontSize; + confirmBtn.position = uConfirmBtn.position ? uConfirmBtn.position : confirmBtn.position; + confirmBtn.callback = uConfirmBtn.callback ? uConfirmBtn.callback : confirmBtn.callback; + } + if (uConfig.cancelBtn) { + var uCancelBtn = uConfig.cancelBtn; + var cancelBtn = config.cancelBtn; + cancelBtn.normalRes = uCancelBtn.normalRes ? uCancelBtn.normalRes : cancelBtn.normalRes; + cancelBtn.pressRes = uCancelBtn.pressRes ? uCancelBtn.pressRes : cancelBtn.pressRes; + cancelBtn.text = typeof uCancelBtn.text != "undefined" ? uCancelBtn.text : cancelBtn.text; + cancelBtn.textColor = uCancelBtn.textColor ? uCancelBtn.textColor : cancelBtn.textColor; + cancelBtn.fontSize = uCancelBtn.fontSize ? uCancelBtn.fontSize : cancelBtn.fontSize; + cancelBtn.position = uCancelBtn.position ? uCancelBtn.position : cancelBtn.position; + cancelBtn.callback = uCancelBtn.callback ? uCancelBtn.callback : cancelBtn.callback; + } + if (uConfig.messageLabel) { + var uMessageLabel = uConfig.messageLabel; + var messageLabel = config.messageLabel; + messageLabel.text = typeof uMessageLabel.text != "undefined" ? uMessageLabel.text : messageLabel.text; + messageLabel.color = uMessageLabel.color ? uMessageLabel.color : messageLabel.color; + messageLabel.fontSize = uMessageLabel.fontSize ? uMessageLabel.fontSize : messageLabel.fontSize; + messageLabel.position = uMessageLabel.position ? uMessageLabel.position : messageLabel.position; + messageLabel.dimensions = uMessageLabel.dimensions ? uMessageLabel.dimensions : messageLabel.dimensions; + } + if (uConfig.target) { + config.target = uConfig.target; + } + if (typeof uConfig.onEnter == "function") { + config.onEnter = uConfig.onEnter; + } + if (typeof uConfig.onExit == "function") { + config.onExit = uConfig.onExit; + } + } + + if (!config.cancelBtn.textColor) { + config.cancelBtn.textColor = cc.color(255, 255, 255); + } + if (!config.confirmBtn.textColor) { + config.confirmBtn.textColor = cc.color(255, 255, 255); + } + + }, + initView: function () { + var useDefaultSource = cc.Dialog._useDefaultSource; + var winSize = cc.director.getWinSize(); + this._scaleFactor = !useDefaultSource ? 1 : winSize.width > winSize.height ? winSize.width / 720 : winSize.width / 480; + var config = this._finalConfig; + + //bg + this.backgroundSprite = new cc.Scale9Sprite(config.background.res); + this._setScale(this.backgroundSprite); + if (this._scaleFactor < 1) { + this.backgroundSprite.setScale(this._scaleFactor); + } + this.backgroundSprite.setPosition(config.position ? config.position : cc.p(winSize.width / 2, winSize.height / 2)); + + //menu + this.menuItemConfirm = this._createMenuItemSprite(config.confirmBtn, this._confirmCallback); + this.menuItemCancel = this._createMenuItemSprite(config.cancelBtn, this._cancelCallback); + this.menuItemCancel.setPosition(config.cancelBtn.position ? config.cancelBtn.position : cc.p(this.backgroundSprite.width / 2 - this.menuItemCancel.width / 2 - 20, this.menuItemCancel.height + 20)); + this.menuItemConfirm.setPosition(config.confirmBtn.position ? config.confirmBtn.position : cc.p(this.backgroundSprite.width / 2 + this.menuItemConfirm.width / 2 + 20, this.menuItemConfirm.height + 20)); + var menu = new cc.Menu(this.menuItemConfirm, this.menuItemCancel); + menu.setPosition(cc.p(0, 0)); + this.backgroundSprite.addChild(menu); + + //message + var fontSize = config.messageLabel.fontSize ? config.messageLabel.fontSize : this._scaleFactor > 1 ? 16 * this._scaleFactor : 16; + this.messageLabel = new cc.LabelTTF(config.messageLabel.text, "Arial", fontSize); + this.messageLabel.setDimensions(config.messageLabel.dimensions ? config.messageLabel.dimensions : cc.size(this.backgroundSprite.width - 30, this.backgroundSprite.height - this.menuItemConfirm.y - 10)); + this.messageLabel.setColor(config.messageLabel.color ? config.messageLabel.color : cc.color(255, 255, 255)); + this.messageLabel.setPosition(config.messageLabel.position ? config.messageLabel.position : cc.p(this.backgroundSprite.width / 2, this.backgroundSprite.height - this.messageLabel.height / 2 - 20)); + this.backgroundSprite.addChild(this.messageLabel); + if (!config.action) { + var action = cc.sequence(cc.EaseIn.create(cc.scaleTo(0.1, this.backgroundSprite.scale + 0.02), 0.4), cc.EaseOut.create(cc.scaleTo(0.1, this.backgroundSprite.scale), 0.3)); + this.backgroundSprite.runAction(action); + } else { + this.backgroundSprite.runAction(config.action); + } + this.addChild(this.backgroundSprite); + + }, + _createMenuItemSprite: function (res, callback) { + var spriteNormal = new cc.Scale9Sprite(res.normalRes); + var spritePress = new cc.Scale9Sprite(res.pressRes); + this._setScale(spriteNormal); + this._setScale(spritePress); + var fontSize = res.fontSize ? res.fontSize : this._scaleFactor > 1 ? 16 * this._scaleFactor : 16; + var menuLabel = new cc.LabelTTF(res.text, "Arial", fontSize); + menuLabel.setColor(res.textColor); + var menuItem = new cc.MenuItemSprite(spriteNormal, spritePress, callback, this); + menuLabel.setPosition(cc.p(menuItem.width / 2, menuItem.height / 2)); + menuItem.addChild(menuLabel); + return menuItem; + }, + _setScale: function (s9Sprite) { + if (this._scaleFactor > 1) { + s9Sprite.setContentSize(cc.size(this._scaleFactor * s9Sprite.width, this._scaleFactor * s9Sprite.height)); + } + }, + _confirmCallback: function () { + var config = this._finalConfig; + if (config.confirmBtn.callback) { + if (config.target) { + config.confirmBtn.callback.call(config.target, this); + } else { + config.confirmBtn.callback(this); + } + } + this.removeFromParent(); + }, + _cancelCallback: function () { + var config = this._finalConfig; + if (config.cancelBtn.callback) { + if (config.target) { + config.cancelBtn.callback.call(config.target, this); + } else { + config.cancelBtn.callback(this); + } + } + this.removeFromParent(); + }, + onEnter: function () { + this._super(); + var config = this._finalConfig; + this.initView(); + config.onEnter(this); + var self = this; + self._eventListener = cc.EventListener.create({ + event: cc.EventListener.TOUCH_ONE_BY_ONE, + swallowTouches: true, + onTouchBegan: function (touch, event) { + return true; + } + }); + cc.eventManager.addListener(self._eventListener, self); + }, + onExit: function () { + this._super(); + var config = this._finalConfig; + config.onExit(this); + this.removeAllChildren(); + cc.Dialog._dialog = null; + cc.eventManager.removeListener(this._eventListener); + } +}); + +cc.Dialog._dialog = null; +cc.Dialog._clearDialog = function () { + if (cc.Dialog._dialog != null) { + cc.Dialog._dialog.removeFromParent(); + cc.Dialog._dialog = null; + } +} + +cc.Dialog.show = function (tips, confirmCb, cancelCb) { + if (cc.Dialog._dialog != null) { + cc.log("other dialog is on the screen,this dialog can't show now"); + return; + } + + var conf; + if (typeof tips == "string") { + conf = { + messageLabel: { + text: tips + }, + confirmBtn: { + callback: confirmCb + }, + cancelBtn: { + callback: cancelCb + } + } + } else if (typeof tips == "object") { + conf = tips; + } else { + cc.log("tips is invalid"); + return; + } + + cc.Dialog._dialog = new cc.Dialog(conf); + if (cc.director.getRunningScene()) { + cc.director.getRunningScene().addChild(cc.Dialog._dialog, cc.INT_MAX); + } else { + cc.log("Current scene is null we can't show dialog"); + } +}; +cc.Dialog._useDefaultSource = true; +cc.Dialog.setUseDefaultSource = function (status) { + cc.Dialog._useDefaultSource = status; +} +cc.Dialog._defaultConfig = { + position: null, + target: null, + action: null, + background: { + res: "res_engine/dialog_bg.png" + }, + confirmBtn: { + normalRes: "res_engine/dialog_confirm_normal.png", + pressRes: "res_engine/dialog_confirm_press.png", + text: "确定", + textColor: null, + fontSize: null, + position: null, + callback: function () { + cc.log("this is confirm callback"); + } + }, + cancelBtn: { + normalRes: "res_engine/dialog_cancel_normal.png", + pressRes: "res_engine/dialog_cancel_press.png", + text: "取消", + textColor: null, + position: null, + fontSize: null, + callback: function () { + cc.log("this is cancel callback"); + } + }, + messageLabel: { + text: "", + color: null, + dimensions: null, + fontSize: null, + position: null + }, + onEnter: function (dialog) { + cc.log("dialog call onEnter"); + }, + onExit: function (dialog) { + cc.log("dialog call onExit"); + } +}; +cc._NetworkErrorDialog = function () { + cc.Dialog._clearDialog(); + cc.Dialog._dialog = new cc.Dialog(cc._NetworkErrorDialog._config); + return cc.Dialog._dialog; +} +cc._NetworkErrorDialog._config = { + networkError: {}, + spaceError: {}, + verifyError: {} +}; +cc._NetworkErrorDialog._show = function (type, tips, confirmCb, cancelCb) { + var networkDialog = cc._NetworkErrorDialog(); + var config; + switch (type) { + case "err_network": + { + config = cc._NetworkErrorDialog._config.networkError; + break; + } + case "err_no_space": + { + config = cc._NetworkErrorDialog._config.spaceError; + break; + } + case "err_verify": + { + config = cc._NetworkErrorDialog._config.verifyError; + break; + } + default: + { + cc.log("type is not found"); + return; + } + } + if (!networkDialog.getParent()) { + + config.confirmBtn = config.confirmBtn || {}; + config.confirmBtn.callback = function () { + if (confirmCb) + confirmCb(); + } + + config.cancelBtn = config.cancelBtn || {}; + config.cancelBtn.callback = function () { + if (cancelCb) + cancelCb(); + } + + config.messageLabel = config.messageLabel || {}; + if (typeof config.messageLabel.text == "undefined") { + config.messageLabel.text = tips; + } + + networkDialog.setConfig(config); + if (cc.director.getRunningScene()) { + cc.director.getRunningScene().addChild(networkDialog, cc.INT_MAX); + } else { + cc.log("Current scene is null we can't show dialog"); + } + } +} + +cc._NetworkErrorDialog._setConfig = function (key, config) { + if (key && config) { + switch (key) { + case "err_network": + { + cc._NetworkErrorDialog._config.networkError = config; + break; + } + case "err_no_space": + { + cc._NetworkErrorDialog._config.spaceError = config; + break; + } + case "err_verify": + { + cc._NetworkErrorDialog._config.verifyError = config; + break; + } + } + } +} + +cc.runtime = cc.runtime || {}; + +cc.runtime.setOption = function (promptype, config) { + if (config) { + switch (promptype) { + case "network_error_dialog": + { + cc._NetworkErrorDialog._setConfig("err_network", config); + break; + } + case "no_space_error_dialog": + { + cc._NetworkErrorDialog._setConfig("err_no_space", config); + break; + } + case "verify_error_dialog": + { + cc._NetworkErrorDialog._setConfig("err_verify", config); + break; + } + default : + { + cc.log("promptype not found please check your promptype"); + } + } + } else { + cc.log("config is null please check your config"); + } +} + +cc.cloneObject = function (obj) { + var o, obj; + if (obj.constructor == Object) { + o = new obj.constructor(); + } else { + o = new obj.constructor(obj.valueOf()); + } + for (var key in obj) { + if (o[key] != obj[key]) { + if (typeof(obj[key]) == 'object') { + o[key] = cc.cloneObject(obj[key]); + } else { + o[key] = obj[key]; + } + } + } + o.toString = obj.toString; + o.valueOf = obj.valueOf; + return o; +} +/** + * only use in JSB get network type + * @type {{}|*|cc.network} + */ +cc.network = cc.network || {}; +cc.network.type = { + NO_NETWORK: -1, + MOBILE: 0, + WIFI: 1 +} +cc.network.preloadstatus = { + DOWNLOAD: 1, + UNZIP: 2 +} +cc.runtime.network = cc.network; \ No newline at end of file diff --git a/moduleConfig.json b/moduleConfig.json index 0419870439..60bfbf3eb6 100644 --- a/moduleConfig.json +++ b/moduleConfig.json @@ -444,6 +444,10 @@ "external/chipmunk/chipmunk.js" ], + "runtime":[ + "core", + "extensions/runtime/CCLoaderLayer.js" + ], "socketio" : [ "external/socketio/socket.io.min.js" ], From 76a9c01dad1268df8880c644101a3227b89c6aec Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 22 Apr 2015 18:23:06 +0800 Subject: [PATCH 0184/1039] Fixed a bug that is spine merge error --- extensions/spine/CCSkeletonWebGLRenderCmd.js | 15 ++------------- 1 file changed, 2 insertions(+), 13 deletions(-) diff --git a/extensions/spine/CCSkeletonWebGLRenderCmd.js b/extensions/spine/CCSkeletonWebGLRenderCmd.js index 726f5bd986..ca0f14b613 100644 --- a/extensions/spine/CCSkeletonWebGLRenderCmd.js +++ b/extensions/spine/CCSkeletonWebGLRenderCmd.js @@ -61,10 +61,10 @@ switch(slot.attachment.type) { case sp.ATTACHMENT_TYPE.REGION: - sp._regionAttachment_updateQuad(attachment, slot, quad, node._premultipliedAlpha); + this._updateRegionAttachmentQuad(attachment, slot, tmpQuad, node._premultipliedAlpha); break; case sp.ATTACHMENT_TYPE.MESH: - sp._meshAttachment_updateQuad(attachment, slot, quad, node._premultipliedAlpha); + this._updateMeshAttachmentQuad(attachment, slot, tmpQuad, node._premultipliedAlpha); break; case sp.ATTACHMENT_TYPE.SKINNED_MESH: break; @@ -95,17 +95,6 @@ return; } - switch(slot.attachment.type) { - case sp.ATTACHMENT_TYPE.REGION: - this._updateRegionAttachmentQuad(attachment, slot, tmpQuad, node._premultipliedAlpha); - break; - case sp.ATTACHMENT_TYPE.MESH: - this._updateMeshAttachmentQuad(attachment, slot, tmpQuad, node._premultipliedAlpha); - break; - case sp.ATTACHMENT_TYPE.SKINNED_MESH: - break; - } - textureAtlas.updateQuad(tmpQuad, quadCount); } From 9114dce74d88d82fc45f16b25b1ac68b14330365 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 22 Apr 2015 21:53:33 +0800 Subject: [PATCH 0185/1039] Updated docs --- AUTHORS.txt | 15 ++++++++++----- CHANGELOG.txt | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 5 deletions(-) diff --git a/AUTHORS.txt b/AUTHORS.txt index 933701bb3e..e61d18e5cb 100644 --- a/AUTHORS.txt +++ b/AUTHORS.txt @@ -12,11 +12,11 @@ Core Developers: Ricardo Quesada - Huabin LING (pandamicro) + Huabin LING (@pandamicro) - Sijie Wang + Sijie Wang (@VisualSJ) - Jialong Zhai + Jialong Zhai (@JoshuaAstray) Contributors: Name GithubID Main contribution @@ -86,8 +86,9 @@ Kang-Hao Lu(Opera/Oupeng) @kennyluck Optimize John Resig's inheritance patter Mark Henderson @MarkEHenderson Code review, LabelTTF and Scale9Sprite bug fix Jing Wang @06wj CCScheduler improvements - Js file loading image add - cc.RectApplyAffineTransform improvements + Js file loading image add + cc.RectApplyAffineTransform improvements + Fixed a bug of cc.Node.setPosition that parameter check is incorrect Ze Wang @WanderWang Fix crash when BrowserTypes match nothing from navigator.userAgent LabelTTF improvements @@ -222,6 +223,7 @@ Robert Rouhani @Robmaister cc.TMXMapInfo bug fix Igor Mats @IgorMats cc.Scale9Sprite bug fix Spine runtime update + Add getStroke and setStroke method to cc.MotionStreak Tim @duhaibo0404 ccs.csLoader bug fix @@ -251,6 +253,9 @@ Skliar Ihor @igogo5yo Add Bower support feijing566 @feijing566 cc.Audio bug fix +RackovychV @RackovychV Fixed a bug of `cc.Scheduler`'s `pauseAllTargetsWithMinPriority` + + Retired Core Developers: Shengxiang Chen (Nero Chan) diff --git a/CHANGELOG.txt b/CHANGELOG.txt index 6f25c68923..ec7c62b829 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,5 +1,41 @@ ChangeLog: +Cocos2d-JS v3.6 Beta @ April 22 2015 + +* Improved TMX transform to support RotationX and RotationY. +* Refactored Spine skeleton render command. +* Added checks to prevent issues when `cc.Node.WebGLRenderCmd` is not exist. +* Improved iOS browsers detection. +* Added getter setter function for `cc.MotionStreak`'s stroke property. +* Improved the detection of render mode. +* Upgraded Action Timeline and parser for the latest version of Cocos editor. +* Added `enumerateChildren` function for `cc.Node`. +* Make `cc.Scale9Sprite` support unpreloaded texture. +* Added `cc.sys.isObjectValid` to detect whether an object is still valid (in web and native engine). + +* Bug fixes: + 1. Fixed a bug that `cc.Scheduler`'s `scheduleOnce` runs multiply times. + 2. Fixed a bug of `cc.Scheduler`'s `pauseAllTargetsWithMinPriority`. + 3. Fixed a bug of `cc.eventManager` that its event listeners' order is incorrect when some nodes haven't been added to the scene graph or have been removed from parent without cleanup. + 4. Fixed a bug of `cc.LabelTTF` that `enableShadow` doesn't work. + 5. Fixed a bug of `cc.LabelTTF` that `setColor` doesn't set shadow color under Canvas render mode. + 6. Fixed a bug that stopped audios can be resume after invoking pause on them. + 7. Fixed a bug that `ccui.LoadingBar`'s texture renders incorrectly without preload. + 8. Fixed a bug that cocos builder's callback doesn't get invoked. + 9. Fixed a bug that TMX objects' position is incorrect when content scale factor is modified. + 10. Fixed a mistaken usage of `cc.isObject` in `cc.Sprite` implementation. + 11. Fixed a bug that position type haven't been copied in `cc.ParticleSystem`'s `clone` function. + 12. Fixed some undefined parameter check issues in `cc.Node`. + 13. Fixed a bug that setter for `scaleY` of `cc.EditBox` is incorrect. + 14. Fixed a bug of `cc.SkeletonAnimation` that its canvas render command doesn't work correctly. + 15. Fixed a parsing issue for the width of `cc.LabelBMFont`. + 16. Fixed `ccs.TweenType`'s constants naming issue. + 17. Fixed a bug that the spine skeleton may be rendered under the unsupported mode. + 18. Fixed a bug when setting `cc.ParticleSystem`'s blend function in the ActionTimeline parser. + 19. Added check to prevent issues that functions may not exist in the ActionTimeline parser. + 20. Fixed a typo of `ccs.displayFactory`. + 21. Fixed a bug of `cc.Node.setPosition` that parameter check is incorrect. + Cocos2d-JS v3.5 @ April 1 2015 * Upgraded Cocos Studio parser to support Cocos Studio v2.2. From 1f3f3b31a14593d338a315790843e5918c3eb497 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 23 Apr 2015 15:45:58 +0800 Subject: [PATCH 0186/1039] Fixed a bug that is Outline error(Text|Button) --- .../loader/parsers/timelineParser-2.x.js | 51 ++++++++++--------- 1 file changed, 26 insertions(+), 25 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 9288442532..954b036d89 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -523,20 +523,6 @@ } widget.setTextVerticalAlignment(v_alignment); - if(json["OutlineEnabled"] && json["OutlineColor"] && widget.enableOutline) - widget.enableOutline(getColor(json["OutlineColor"]), getParam(json["OutlineSize"], 1)); - - if(json["ShadowEnabled"] && json["ShadowColor"] && widget.enableShadow) - widget.enableShadow( - getColor(json["ShadowColor"]), - cc.size(getParam(json["ShadowOffsetX"], 2), getParam(json["ShadowOffsetY"], -2)), - json["ShadowBlurRadius"] || 0 - ); - - var isCustomSize = json["IsCustomSize"]; - if(isCustomSize != null) - widget.ignoreContentAdaptWithSize(!isCustomSize); - var fontResource = json["FontResource"]; if(fontResource != null){ var path = fontResource["Path"]; @@ -552,6 +538,20 @@ } } + if(json["OutlineEnabled"] && json["OutlineColor"] && widget.enableOutline) + widget.enableOutline(getColor(json["OutlineColor"]), getParam(json["OutlineSize"], 1)); + + if(json["ShadowEnabled"] && json["ShadowColor"] && widget.enableShadow) + widget.enableShadow( + getColor(json["ShadowColor"]), + cc.size(getParam(json["ShadowOffsetX"], 2), getParam(json["ShadowOffsetY"], -2)), + json["ShadowBlurRadius"] || 0 + ); + + var isCustomSize = json["IsCustomSize"]; + if(isCustomSize != null) + widget.ignoreContentAdaptWithSize(!isCustomSize); + widget.setUnifySizeEnabled(false); if(widget.isIgnoreContentAdaptWithSize()) @@ -601,17 +601,6 @@ if(textColor != null) widget.setTitleColor(getColor(textColor)); - var label = widget.getTitleRenderer(); - if(label && json["ShadowEnabled"] && json["ShadowColor"] && label.enableShadow){ - label.enableShadow( - getColor(json["ShadowColor"]), - cc.size(getParam(json["ShadowOffsetX"], 2), getParam(json["ShadowOffsetY"], -2)), - json["ShadowBlurRadius"] || 0 - ); - } - if(label && json["OutlineEnabled"] && json["OutlineColor"] && label.enableOutline) - label.enableOutline(getColor(json["OutlineColor"]), getParam(json["OutlineSize"], 1)); - var displaystate = getParam(json["DisplayState"], true); widget.setBright(displaystate); widget.setEnabled(displaystate); @@ -630,6 +619,18 @@ widget.setTitleFontName(fontName); } } + + var label = widget.getTitleRenderer(); + if(label && json["ShadowEnabled"] && json["ShadowColor"] && label.enableShadow){ + label.enableShadow( + getColor(json["ShadowColor"]), + cc.size(getParam(json["ShadowOffsetX"], 2), getParam(json["ShadowOffsetY"], -2)), + json["ShadowBlurRadius"] || 0 + ); + } + if(label && json["OutlineEnabled"] && json["OutlineColor"] && label.enableOutline) + label.enableOutline(getColor(json["OutlineColor"]), getParam(json["OutlineSize"], 1)); + this.widgetAttributes(widget, json); if(scale9Enabled) { From efdf1a6e897edfdbaefb2f59510ca6a027d88667 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 24 Apr 2015 13:39:48 +0800 Subject: [PATCH 0187/1039] Adding Gaf --- external/gaf/GAFBoot.js | 24 + external/gaf/GAFMacros.js | 33 ++ external/gaf/Library/GAFAsset.js | 429 ++++++++++++++ external/gaf/Library/GAFAssetPreload.js | 270 +++++++++ external/gaf/Library/GAFAtlasLoader.js | 50 ++ external/gaf/Library/GAFDataReader.js | 229 ++++++++ external/gaf/Library/GAFLoader.js | 75 +++ external/gaf/Library/GAFMask.js | 36 ++ external/gaf/Library/GAFMaskProto.js | 16 + external/gaf/Library/GAFObject.js | 426 ++++++++++++++ external/gaf/Library/GAFShaderManager.js | 63 ++ external/gaf/Library/GAFShaders.js | 58 ++ external/gaf/Library/GAFSprite.js | 100 ++++ .../gaf/Library/GAFSpriteCanvasRenderCmd.js | 233 ++++++++ external/gaf/Library/GAFSpriteProto.js | 36 ++ .../gaf/Library/GAFSpriteWebGLRenderCmd.js | 132 +++++ external/gaf/Library/GAFTags.js | 378 ++++++++++++ external/gaf/Library/GAFTextField.js | 6 + external/gaf/Library/GAFTimeLine.js | 547 ++++++++++++++++++ external/gaf/Library/GAFTimeLineProto.js | 32 + external/gaf/gaf_viewer.css | 42 ++ external/gaf/gaf_viewer.html | 21 + external/gaf/gaf_viewer.js | 219 +++++++ moduleConfig.json | 26 +- 24 files changed, 3480 insertions(+), 1 deletion(-) create mode 100644 external/gaf/GAFBoot.js create mode 100644 external/gaf/GAFMacros.js create mode 100644 external/gaf/Library/GAFAsset.js create mode 100644 external/gaf/Library/GAFAssetPreload.js create mode 100644 external/gaf/Library/GAFAtlasLoader.js create mode 100644 external/gaf/Library/GAFDataReader.js create mode 100644 external/gaf/Library/GAFLoader.js create mode 100644 external/gaf/Library/GAFMask.js create mode 100644 external/gaf/Library/GAFMaskProto.js create mode 100644 external/gaf/Library/GAFObject.js create mode 100644 external/gaf/Library/GAFShaderManager.js create mode 100644 external/gaf/Library/GAFShaders.js create mode 100644 external/gaf/Library/GAFSprite.js create mode 100644 external/gaf/Library/GAFSpriteCanvasRenderCmd.js create mode 100644 external/gaf/Library/GAFSpriteProto.js create mode 100644 external/gaf/Library/GAFSpriteWebGLRenderCmd.js create mode 100644 external/gaf/Library/GAFTags.js create mode 100644 external/gaf/Library/GAFTextField.js create mode 100644 external/gaf/Library/GAFTimeLine.js create mode 100644 external/gaf/Library/GAFTimeLineProto.js create mode 100644 external/gaf/gaf_viewer.css create mode 100644 external/gaf/gaf_viewer.html create mode 100644 external/gaf/gaf_viewer.js diff --git a/external/gaf/GAFBoot.js b/external/gaf/GAFBoot.js new file mode 100644 index 0000000000..0baccc7ecd --- /dev/null +++ b/external/gaf/GAFBoot.js @@ -0,0 +1,24 @@ +var gaf = gaf || {}; +gaf._tmp = gaf._tmp || {}; +gaf._initialized = false; + +gaf.CCGAFLoader = function() +{ + this.load = function(realUrl, url, item, cb) + { + if(!gaf._initialized) + { + gaf._setup(); + } + var loader = new gaf.Loader(); + loader.LoadFile(realUrl, function(data){cb(null, data)}); + }; +}; + +gaf._setup = function() +{ + gaf._setupShaders(); + gaf._initialized = true; +}; + +cc.loader.register('.gaf', new gaf.CCGAFLoader()); diff --git a/external/gaf/GAFMacros.js b/external/gaf/GAFMacros.js new file mode 100644 index 0000000000..ef34cc8f5d --- /dev/null +++ b/external/gaf/GAFMacros.js @@ -0,0 +1,33 @@ +var gaf = gaf || {}; + +gaf.COMPRESSION_NONE = 0x00474146; +gaf.COMPRESSION_ZIP = 0x00474143; + +gaf.IDNONE = 0xffffffff; +gaf.FIRST_FRAME_INDEX = 0; + +gaf.EFFECT_DROP_SHADOW = 0; +gaf.EFFECT_BLUR = 1; +gaf.EFFECT_GLOW = 2; +gaf.EFFECT_COLOR_MATRIX = 6; + +gaf.ACTION_STOP = 0; +gaf.ACTION_PLAY = 1; +gaf.ACTION_GO_TO_AND_STOP = 2; +gaf.ACTION_GO_TO_AND_PLAY = 3; +gaf.ACTION_DISPATCH_EVENT = 4; + +gaf.PI_FRAME = 0; +gaf.PI_EVENT_TYPE = 0; + +gaf.TYPE_TEXTURE = 0; +gaf.TYPE_TEXT_FIELD = 1; +gaf.TYPE_TIME_LINE = 2; + +gaf.UNIFORM_BLUR_TEXEL_OFFSET = "u_step"; +gaf.UNIFORM_GLOW_TEXEL_OFFSET = "u_step"; +gaf.UNIFORM_GLOW_COLOR = "u_glowColor"; +gaf.UNIFORM_ALPHA_TINT_MULT = "colorTransformMult"; +gaf.UNIFORM_ALPHA_TINT_OFFSET = "colorTransformOffsets"; +gaf.UNIFORM_ALPHA_COLOR_MATRIX_BODY = "colorMatrix"; +gaf.UNIFORM_ALPHA_COLOR_MATRIX_APPENDIX = "colorMatrix2"; diff --git a/external/gaf/Library/GAFAsset.js b/external/gaf/Library/GAFAsset.js new file mode 100644 index 0000000000..23804e61ff --- /dev/null +++ b/external/gaf/Library/GAFAsset.js @@ -0,0 +1,429 @@ +var gaf = gaf || {}; + +gaf.Asset = cc.Class.extend +({ + _className: "GAFAsset", + + // Private members + _header: null, + _timeLines: null, + _textFields: null, + _protos: null, + _objects: null, + _masks: null, + + _rootTimeLine: null, + _textureLoadDelegate: null, + _sceneFps: 60, + _sceneWidth: 0, + _sceneHeight: 0, + _sceneColor: 0, + _gafData: null, + _desiredAtlasScale: 1, + _usedAtlasScale: 0, + + _atlases: null, + _onLoadTasks: null, + _atlasScales: null, + _textureLoaded: false, // For async loading with cc.event manager + _atlasesToLoad: null, // Atlases that are not yet loaded + _gafName: null, + + /** + * @method initWithGAFFile + * @param {String} filePath - path to .gaf file + * @param {String function(String)} textureLoadDelegate - is used to change atlas path, e.g. to load `atlas.tga` instead of `atlas.png` + * @return {bool} + */ + initWithGAFFile: function (filePath, textureLoadDelegate) { + var self = this; + this._textureLoadDelegate = textureLoadDelegate; + this._gafName = filePath; + var gafData = cc.loader.getRes(filePath); + if(!gafData) + { + cc.loader.load(filePath, function(err, data){ + if(!err) + { + self._init(data[0]); + } + }); + } + else { + return this._init(gafData); + } + return false; + }, + + /** + * @method initWithGAFBundle + * @param {String} zipFilePath - path to the archive with .gaf and its textures + * @param {String} entryFile - name of the .gaf file in archive + * @param {function({path:String})} delegate - is used to change atlas path, e.g. to load `atlas.tga` instead of `atlas.png` + * @return {bool} + */ + initWithGAFBundle: function (zipFilePath, entryFile, delegate) + { + cc.assert(false, "initWithGAFBundle is not yet implemented"); + return false; + }, + + /** + * @method setRootTimelineWithName + * @param {String} name + */ + setRootTimelineWithName: function (name) + { + for(var i = 0, end = this._timeLines.length; i < end; ++i) + { + var object = this._timeLines[i]; + if (object && object.getLinkageName() === name) + { + this._setRootTimeline(object); + return; + } + } + }, + +/* addEventListener: function(name, listener) + {},*/ + + isAssetVersionPlayable: function () + { + return true; + }, + + /** + * Desired atlas scale. + * Default is 1.0f + * @returns {number} + */ + desiredAtlasScale : function(){ + return this._desiredAtlasScale; + }, + + /** + * Sets desired atlas scale. Will choose nearest atlas scale from available. + * Default is 1.0f + * @param scale + */ + setDesiredAtlasScale : function(desiredAtlasScale){ + this._desiredAtlasScale = desiredAtlasScale; + for(var currentScale in this._atlasScales)if(this._atlasScales.hasOwnProperty(currentScale)) + { + if( (this._usedAtlasScale === 0) || + (Math.abs(this._usedAtlasScale - desiredAtlasScale) > Math.abs(currentScale - desiredAtlasScale) )) + { + this._usedAtlasScale = currentScale; + } + + } + }, + + /** + * @method createObject + * @return {gaf.Object} + */ + createObject: function () + { + return this._instantiateGaf(this._gafData); + }, + + /** + * @method createObjectAndRun + * @param {boolean} arg0 - run looped + * @return {gaf.Object} + */ + createObjectAndRun: function (looped) + { + cc.assert(arguments.length === 1, "GAFAsset::createObjectAndRun should have one param"); + var object = this._instantiateGaf(this._gafData); + object.setLooped(looped, true); + object.start(); + return object; + }, + + /** + * @method setTextureLoadDelegate + * @param {function} delegate + */ + setTextureLoadDelegate: function (delegate) + { + debugger; + }, + + + /** + * @method getSceneFps + * @return {uint} + */ + getSceneFps: function () + { + return this._sceneFps; + }, + + /** + * @method getSceneWidth + * @return {uint} + */ + getSceneWidth: function () + { + debugger; + }, + + /** + * @method getSceneHeight + * @return {uint} + */ + getSceneHeight: function () + { + debugger; + }, + + /** + * @method getSceneColor + * @return {cc.color4b} + */ + getSceneColor: function () + { + debugger; + }, + + /** + * @method setSceneFps + * @param {uint} fps + */ + setSceneFps: function (fps) + { + this._sceneFps = fps; + }, + + /** + * @method setSceneWidth + * @param {uint} width + */ + setSceneWidth: function (width) + { + debugger; + }, + + /** + * @method setSceneHeight + * @param {uint} height + */ + setSceneHeight: function (height) + { + debugger; + }, + + /** + * @method setSceneColor + * @param {color4b_object} arg0 + */ + setSceneColor: function (color4B) + { + debugger; + }, + + /** + * @method getHeader + * @return {GAFHeader} + */ + getHeader: function () + { + return this._header; + }, + + getGAFFileName: function() + { + return this._gafName; + }, + + // Private + + ctor : function() + { + this._header = {}; + this._timeLines = []; + this._textFields = []; + this._objects = []; + this._masks = []; + this._protos = []; + this._atlases = {}; + this._onLoadTasks = []; + this._atlasScales = {}; + this._atlasesToLoad = {}; + + if(arguments.length > 0) + this.initWithGAFFile.apply(this, arguments); + }, + + _getProtos: function() + { + return this._protos; + }, + + _setRootTimeline : function(timeLine) + { + this._rootTimeLine = timeLine; + this._header.pivot = timeLine.getPivot(); + this._header.frameSize = timeLine.getRect(); + }, + + _setHeader : function (gafHeader) + { + for(var prop in gafHeader) + { + if(gafHeader.hasOwnProperty(prop)) + { + this._header[prop] = gafHeader[prop]; + } + } + }, + + _getMajorVerison : function() + { + return this._header.versionMajor; + }, + + _init : function(gafData) + { + var self = this; + this._gafData = gafData; + this._setHeader(gafData.header); + this._timeLinesToLink = []; + if(this._getMajorVerison() < 4) + { + this._pushTimeLine(new gaf._TimeLineProto(this, this._header.framesCount, this._header.frameSize, this._header.pivot)); + } + gaf._AssetPreload.Tags(this, gafData.tags, this._rootTimeLine); + + //Link and create + this._objects.forEach(function(item) + { + switch(item.type) + { + case gaf.TYPE_TEXTURE: + // Create gaf sprite proto if it is not yet created + if(!self._protos[item.objectId]) + { + self._protos[item.objectId] = new gaf._SpriteProto(self, self._atlasScales, item.elementAtlasIdRef); + } + break; + case gaf.TYPE_TIME_LINE: + // All time line protos are already created, just copy reference + self._protos[item.objectId] = self._timeLines[item.elementAtlasIdRef]; + break; + case gaf.TYPE_TEXT_FIELD: + // All text field protos are already created, just copy reference + self._protos[item.objectId] = self._textFields[item.elementAtlasIdRef]; + break; + default: + cc.log("Unknown object type: " + item.type); + break; + } + }); + this._masks.forEach(function(item) + { + if(self._protos[item.objectId]) + { + return; // this is continue + } + var proto = null; + switch(item.type) + { + case gaf.TYPE_TEXTURE: + // Create gaf sprite proto if it is not yet created + proto = new gaf._SpriteProto(self, self._atlasScales, item.elementAtlasIdRef); + break; + case gaf.TYPE_TIME_LINE: + // All time line protos are already created, just copy reference + proto = self._timeLines[item.elementAtlasIdRef]; + break; + case gaf.TYPE_TEXT_FIELD: + // All text field protos are already created, just copy reference + proto = self._textFields[item.elementAtlasIdRef]; + break; + } + self._protos[item.objectId] = new gaf._MaskProto(self, proto, item.elementAtlasIdRef); + }); + this.setDesiredAtlasScale(this._desiredAtlasScale); + + if(Object.keys(this._atlasesToLoad).length === 0) + { + this._textureLoaded = true; + this.dispatchEvent("load"); + } + }, + + _pushTimeLine : function(timeLine) + { + this._timeLines[timeLine.getId()] = timeLine; + + if(timeLine.getId() === 0) + { + this._setRootTimeline(timeLine); + } + }, + + _instantiateGaf : function() + { + var root = null; + root = this._rootTimeLine._gafConstruct(); + return root; + }, + + _onAtlasLoaded : function(id, atlas) + { + this._atlases[id] = atlas; + delete this._atlasesToLoad[id]; + if(Object.keys(this._atlasesToLoad).length === 0) + { + this._onLoadTasks.forEach(function(fn){fn()}); + this._onLoadTasks.length = 0; + this._textureLoaded = true; + this.dispatchEvent("load"); + } + }, + + isLoaded : function() + { + return this._textureLoaded; + }, + + _getSearchPaths: function(imageUrl) + { + var extendedPath = this.getGAFFileName().split('/'); + extendedPath[extendedPath.length-1] = imageUrl; + var alternativeUrl = extendedPath.join('/'); + + return [imageUrl, alternativeUrl]; + } +}); + +/** + * @method initWithGAFFile + * @param {String} gafFilePath - path to .gaf file + * @param {function({path:String})} delegate - is used to change atlas path, e.g. to load `atlas.tga` instead of `atlas.png` + * @return {gaf.Asset} + */ +gaf.Asset.create = function (gafFilePath, delegate) +{ + return new gaf.Asset(gafFilePath, delegate); +}; + +/** + * @method createWithBundle + * @param {String} zipFilePath - path to the archive with .gaf and its textures + * @param {String} entryFile - name of the .gaf file in archive + * @param {function({path:String})} delegate - is used to change atlas path, e.g. to load `atlas.tga` instead of `atlas.png` + * @return {gaf.Asset} + */ +gaf.Asset.createWithBundle = function (zipFilePath, entryFile, delegate) +{ + var asset = new gaf.Asset(); + asset.initWithGAFBundle(zipFilePath, entryFile, delegate); + return asset; +}; + +cc.EventHelper.prototype.apply(gaf.Asset.prototype); diff --git a/external/gaf/Library/GAFAssetPreload.js b/external/gaf/Library/GAFAssetPreload.js new file mode 100644 index 0000000000..8514e09f2d --- /dev/null +++ b/external/gaf/Library/GAFAssetPreload.js @@ -0,0 +1,270 @@ + +gaf.CGAffineTransformCocosFormatFromFlashFormat = function(transform) +{ + var t = {}; + t.a = transform.a; + t.b = -transform.b; + t.c = -transform.c; + t.d = transform.d; + t.tx = transform.tx; + t.ty = -transform.ty; + return t; +}; + +gaf._AssetPreload = function() +{ + this["0"] = this.End; + this["1"] = this.Atlases; + this["2"] = this.AnimationMasks; + this["3"] = this.AnimationObjects; + this["4"] = this.AnimationFrames; + this["5"] = this.NamedParts; + this["6"] = this.Sequences; + this["7"] = this.TextFields; + this["8"] = this.Atlases; // 2 + this["9"] = this.Stage; + this["10"] = this.AnimationObjects; //2 + this["11"] = this.AnimationMasks; // 2 + this["12"] = this.AnimationFrames; // 2 + this["13"] = this.TimeLine; +}; + +gaf._AssetPreload.prototype.End = function(asset, content, timeLine){ + if(timeLine) + { + timeLine.getFps = function() + { + return asset.getSceneFps(); + }; + } +}; + +gaf._AssetPreload.prototype.Tag = function(asset, tag, timeLine) +{ + (this[tag.tagId]).call(this, asset, tag.content, timeLine); +}; + +gaf._AssetPreload.prototype.Tags = function(asset, tags, timeLine) +{ + var self = this; + tags.forEach(function(tag) + { + self.Tag(asset, tag, timeLine); + }); +}; + +gaf._AssetPreload.prototype.AtlasCreateFrames = function(elements, asset, spriteFrames) +{ + elements.forEach(function (item) { + var texture = asset._atlases[item.atlasId]; + var rect = cc.rect(item.origin.x, item.origin.y, item.size.x, item.size.y); + var frame = new cc.SpriteFrame(texture, rect); + frame._gafAnchor = + { + x: (0 - (0 - (item.pivot.x / item.size.x))), + y: (0 + (1 - (item.pivot.y / item.size.y))) + }; + spriteFrames[item.elementAtlasId] = frame; + // 9 grid + }); +}; + + + +gaf._AssetPreload.prototype.Atlases = function(asset, content, timeLine) +{ + var spriteFrames = asset._atlasScales[content.scale] = asset._atlasScales[content.scale] || []; + var csf = cc.Director._getInstance().getContentScaleFactor(); + + content.atlases.forEach(function(item) + { + var atlasId = item.id; + var finalizeLoading = function() + { + gaf._AssetPreload.AtlasCreateFrames(content.elements, asset, spriteFrames); + }; + + var atlasPath = ""; + item.sources.forEach(function(atlasSource) + { + if(atlasSource.csf === csf) + { + atlasPath = atlasSource.source; + } + }); + cc.assert(atlasPath, "GAF Error. Texture for current CSF not found. Reconvert animation with correct parameters."); + + if(asset._textureLoadDelegate) + { + atlasPath = asset._textureLoadDelegate(atlasPath); + } + + var loaded = false; + var paths = asset._getSearchPaths(atlasPath); + for(var i = 0, len = paths.length; i < len; ++i){ + var path = paths[i]; + var atlas = cc.textureCache.getTextureForKey(path); + if(atlas && atlas.isLoaded()) + { + atlas.handleLoadedTexture(true); + loaded = true; + asset._atlases[atlasId] = atlas; + finalizeLoading(); + break; + } + } + // Need to load atlases async + if(!loaded) + { + var success = function (atlas) { + atlas.handleLoadedTexture(true); + asset._onAtlasLoaded(atlasId, atlas); + }; + + var fail = function () { + cc.log("GAF Error. Couldn't find `" + atlasPath + "` required by `" + asset.getGAFFileName() + "`"); + }; + + if(!asset._atlasesToLoad.hasOwnProperty(atlasId)) + { + gaf._AtlasLoader.loadArray(paths, success, fail); + asset._atlasesToLoad[atlasId] = {}; + } + asset._onLoadTasks.push(finalizeLoading); + } + }); +}; + +gaf._AssetPreload.prototype.AnimationObjects = function(asset, content, timeLine) +{ + content.forEach(function(item) + { + item.type = (item.type === undefined) ? gaf.TYPE_TEXTURE : item.type; + timeLine._objects.push(item.objectId); + asset._objects[item.objectId] = item; + }); +}; + +gaf._AssetPreload.prototype.convertTint = function(mat, alpha) +{ + if(!mat) + return null; + return { + mult: + { + r: mat.redMultiplier * 255, + g: mat.greenMultiplier * 255, + b: mat.blueMultiplier * 255, + a: alpha * 255 + }, + offset: + { + r: mat.redOffset * 255, + g: mat.greenOffset * 255, + b: mat.blueOffset * 255, + a: mat.alphaOffset * 255 + } + }; +}; + +gaf._AssetPreload.prototype.convertState = function(state) +{ + return { + hasColorTransform: state.hasColorTransform, + hasMask: state.hasMask, + hasEffect: state.hasEffect, + objectIdRef: state.objectIdRef, + depth: state.depth, + alpha: state.alpha * 255, + matrix: gaf.CGAffineTransformCocosFormatFromFlashFormat(state.matrix), + colorTransform: this.convertTint(state.colorTransform, state.alpha), + effect: state.effect, + maskObjectIdRef: state.maskObjectIdRef + }; +}; + +gaf._AssetPreload.prototype.AnimationFrames = function(asset, content, timeLine) +{ + var self = this; + cc.assert(timeLine, "Error. Time Line should not be null."); + var statesForId = {}; + var frames = []; + var lastFrame = {}; + for(var i = 0, len = content.length; i < len; ++i) + { + var frame = content[i]; + if(frame.state) + { + frame.state.forEach(function (state) + { + if (state.alpha !== 0) + { + statesForId[state.objectIdRef] = self.convertState(state); + } + else + { + statesForId[state.objectIdRef] = null; + } + }); + } + var stateArray = []; + for(var obj in statesForId){ if(statesForId.hasOwnProperty(obj) && statesForId[obj]) + { + stateArray.push(statesForId[obj]); + }} + lastFrame = frame; + frames[frame.frame - 1] = {states: stateArray, actions: frame.actions || null}; + } + timeLine.getFrames = function(){return frames}; +}; + +gaf._AssetPreload.prototype.NamedParts = function(asset, content, timeLine) +{ + var parts = {}; + content.forEach(function(item) + { + parts[item.name] = item.objectId; + }); + timeLine.getNamedParts = function(){return parts}; +}; + +gaf._AssetPreload.prototype.Sequences = function(asset, content, timeLine) +{ + var sequences = {}; + content.forEach(function(item){ + sequences[item.id] = {start: item.start - 1, end: item.end}; + }); + timeLine.getSequences = function(){return sequences}; +}; + +gaf._AssetPreload.prototype.TextFields = function(asset, content, timeLine) +{ + debugger; +}; + +gaf._AssetPreload.prototype.Stage = function(asset, content, timeLine) +{ + asset._sceneFps = content.fps; + asset._sceneColor = content.color; + asset._sceneWidth = content.width; + asset._sceneHeight = content.height; +}; + +gaf._AssetPreload.prototype.AnimationMasks = function(asset, content, timeLine) +{ + content.forEach(function(item) + { + item.type = (item.type === undefined) ? gaf.TYPE_TEXTURE : item.type; + timeLine._objects.push(item.objectId); + asset._masks[item.objectId] = item; + }); +}; + +gaf._AssetPreload.prototype.TimeLine = function(asset, content, timeLine) +{ + var result = new gaf._TimeLineProto(asset, content.animationFrameCount, content.boundingBox, content.pivotPoint, content.id, content.linkageName); + asset._pushTimeLine(result); + this.Tags(asset, content.tags, result); +}; + +gaf._AssetPreload = new gaf._AssetPreload(); diff --git a/external/gaf/Library/GAFAtlasLoader.js b/external/gaf/Library/GAFAtlasLoader.js new file mode 100644 index 0000000000..152bba0788 --- /dev/null +++ b/external/gaf/Library/GAFAtlasLoader.js @@ -0,0 +1,50 @@ +/** + * Created by admiral on 19.02.2015. + */ + +gaf._AtlasLoader = {}; +gaf._AtlasLoader.execute = function(condition, success, fail) +{ + condition() ? success() : fail(); +}; + +gaf._AtlasLoader.checkAtlas = function(atlas) // curried function +{ + return function(){return atlas && typeof atlas !== "string" && atlas.isLoaded()}; +}; + +gaf._AtlasLoader.load = function(path, success, fail) +{ + cc.textureCache.addImage(path, function(atlas){ + gaf._AtlasLoader.execute( + gaf._AtlasLoader.checkAtlas(atlas), + function(){success(atlas)}, + fail + ); + }); +}; + +gaf._AtlasLoader.loadFront = function(arr, success, fail) +{ + // Call recursively this function for each element starting from the first + // stops on first success, or fails after last element + return function() + { + if (arr.length > 0){ + gaf._AtlasLoader.load( + arr[0], + success, + gaf._AtlasLoader.loadFront( + arr.slice(1), + success, + fail + ));} + else + fail(); + } +}; + +gaf._AtlasLoader.loadArray = function(array, success, fail) +{ + gaf._AtlasLoader.loadFront(array, success, fail)(); +}; diff --git a/external/gaf/Library/GAFDataReader.js b/external/gaf/Library/GAFDataReader.js new file mode 100644 index 0000000000..3affbe1335 --- /dev/null +++ b/external/gaf/Library/GAFDataReader.js @@ -0,0 +1,229 @@ +gaf.DataReader = function(data) { + this.dataRaw = data; + this.buf = new DataView(data); + this.offset = [0]; +}; + +gaf.DataReader.prototype.constructor = gaf.DataReader; + +gaf.DataReader.prototype.newOffset = function(size){ + this.offset[this.offset.length - 1] += size; + if(this.getOffset() > this.maxOffset()){ + throw new Error("GAF format error"); + } + return this.offset[this.offset.length - 1] - size; +}; + +gaf.DataReader.prototype.maxOffset = function(){ + if(this.offset.length == 1){ + return this.buf.byteLength; + } + else{ + return this.offset[this.offset.length - 2]; + } +}; + +gaf.DataReader.prototype.getOffset = function(size){ + return this.offset[this.offset.length - 1]; +}; + +gaf.DataReader.prototype.Ubyte = function() { + return this.buf.getUint8(this.newOffset(1)); +}; + +gaf.DataReader.prototype.Boolean = function() { + var result = this.buf.getUint8(this.newOffset(1)); + if(result > 1){ + throw new Error("GAF format error"); + } + return result; +}; + +gaf.DataReader.prototype.Uint = function() { + return this.buf.getUint32(this.newOffset(4), true); +}; + +gaf.DataReader.prototype.Int = function() { + return this.buf.getInt32(this.newOffset(4), true); +}; + +gaf.DataReader.prototype.color = function() { + return { + b: this.Ubyte(), + g: this.Ubyte(), + r: this.Ubyte(), + a: this.Ubyte() + }; +}; + +gaf.DataReader.prototype.Ushort = function() { + return this.buf.getUint16(this.newOffset(2), true); +}; + +gaf.DataReader.prototype.Float = function() { + return this.buf.getFloat32(this.newOffset(4), true); +}; + +gaf.DataReader.prototype.String = function() { + var strLen = this.Ushort(); + var from = this.newOffset(strLen); + var to = this.getOffset(); + + try + { + var str = this.dataRaw.slice(from, to); + } + catch(e) + { + // Internet Explorer 10 T.T + if(e.message == "Object doesn't support property or method 'slice'") + { + str = []; + for(var i = from; i < to; ++i) + str.push(this.buf.getUint8(i)); + } + else + { + throw(e); + } + } + return decodeURIComponent(escape(String.fromCharCode.apply(null, new Uint8Array(str)))); + +}; + +gaf.DataReader.prototype.startNestedBuffer = function(length) { + this.offset.push(this.offset[this.offset.length-1]); + this.offset[this.offset.length-2] += length; +}; + +gaf.DataReader.prototype.endNestedBuffer = function() { + if (this.offset.length == 1) throw new Error('No nested buffer available'); + this.offset.pop(); +}; + +gaf.DataReader.prototype.Point = function(){ + return { + x: this.Float(), + y: this.Float() + }; +}; + +gaf.DataReader.prototype.Rect = function(){ + return { + x: this.Float(), + y: this.Float(), + width: this.Float(), + height: this.Float() + }; +}; + +gaf.DataReader.prototype.Matrix = function(){ + return { + a: this.Float(), + b: this.Float(), + c: this.Float(), + d: this.Float(), + tx: this.Float(), + ty: this.Float() + }; +}; + +gaf.DataReader.prototype.seek = function(pos){ + this.offset[this.offset.length-1] = pos; +}; + +gaf.DataReader.prototype.tell = function(){ + return this.offset[this.offset.length-1]; +}; + +/* Creates a fields parsing function +* @ returns a function that will read from DataReader `field` of type `type` +* @`key` - key for read data to be stored +* @`data` - data to store. Can be DataReader function name or a function that will return a value +* Note. Parameters pair `key` and `data` can be repeated any number of times*/ + +gaf.DataReader.prototype.fields = function(){ + var self = this; + var arguments_ = arguments; + return function(){ + arguments.callee.result = {}; + var i = 0; + if(arguments_.length % 2){ + throw new Error('Number of arguments is not even'); + } + while(i < arguments_.length){ + var field = arguments_[i++]; + var func = arguments_[i++]; + if(typeof func === 'function'){ + arguments.callee.result[field] = func(); + } + else if (func in self && typeof self[func] === 'function'){ + arguments.callee.result[field] = self[func].call(self); + } + else{ + throw new Error('Object DataReader has no function `' + func + '`'); + } + } + return arguments.callee.result; + } +}; + +/* +* Creates a parsing function +* @ returns function that will execute expression if caller's `result` field has `key` equal to `value` parameter +* @ `key` - key in caller's `result` element +* @ `value` - expected value of the `key` or a comparator function +* @ `func` - function to execute if condition is true +* */ + +gaf.DataReader.prototype.condition = function(key, value, func){ + var arguments_ = arguments; + return function() { + if(arguments_.length != 3){ + throw new Error('Condition function'); + } + var parent = arguments.callee.caller; + if(!('result' in parent)){ + throw new Error('Condition function caller has no key `result`'); + } + var container = parent.result; + var field = arguments_[0]; + var value = arguments_[1]; + var exec = arguments_[2]; + + var evaluate = null; + if(typeof value === 'function'){ + evaluate = function(){return value(container[field]);}; + } + else{ + evaluate = function(){return value == container[field];}; + } + if(evaluate()){ + return exec(); + } + else{ + return null; + } + } +}; + +/* +* Creates an array parsing function +* @ returns function that will execute `func` number of times read from DataReader +* @ `type` - type of count number +* @ `func` - function to be executed +* */ + +gaf.DataReader.prototype.array = function(){ + var self = this; + var arguments_ = arguments; + return function() { + arguments.callee.result = []; + var length = self[arguments_[0]].call(self); + for (var i = 0; i < length; ++i) { + var r = arguments_[1].call(); + arguments.callee.result.push(r); + } + return arguments.callee.result; + } +}; diff --git a/external/gaf/Library/GAFLoader.js b/external/gaf/Library/GAFLoader.js new file mode 100644 index 0000000000..3e40c33947 --- /dev/null +++ b/external/gaf/Library/GAFLoader.js @@ -0,0 +1,75 @@ +var gaf = gaf || {}; + +//@Private class +gaf.Loader = function(){ + + var readHeaderBegin = function(stream, header){ + header.compression = stream.Uint(); + header.versionMajor = stream.Ubyte(); + header.versionMinor = stream.Ubyte(); + header.fileLength = stream.Uint(); + }; + + var readHeaderEndV3 = function(stream, header) { + header.framesCount = stream.Ushort(); + header.frameSize = stream.Rect(); + header.pivot = stream.Point(); + }; + + var readHeaderEndV4 = function(stream, header){ + var scaleCount = stream.Uint(); + header.scaleValues = []; + for(var i = 0; i < scaleCount; ++i){ + header.scaleValues.push(stream.Float()); + } + var csfCount = stream.Uint(); + header.csfValues = []; + for(var i = 0; i < csfCount; ++i){ + header.csfValues.push(stream.Float()); + } + }; + + this.LoadFile = function(filePath, onLoaded){ + var oReq = new XMLHttpRequest(); + oReq.open("GET", filePath, true); + var self = this; + oReq.responseType = "arraybuffer"; + oReq.onload = function(oEvent) { + var gaf_data = new gaf.DataReader(oReq.response); + var gafFile = self.LoadStream(gaf_data); + if(onLoaded) + onLoaded(gafFile); + }; + oReq.send(); + }; + + this.LoadStream = function(stream){ + var header = {}; + readHeaderBegin(stream, header); + if(header.compression == gaf.COMPRESSION_NONE) { // GAF + } + else if(header.compression == gaf.COMPRESSION_ZIP){ // GAC + var compressed = stream.dataRaw.slice(stream.tell()); + + var inflate = new window.Zlib.Inflate(new Uint8Array(compressed)); + var decompressed = inflate.decompress(); + stream = new gaf.DataReader(decompressed.buffer); + } + else{ + throw new Error("GAF syntax error."); + } + + if(header.versionMajor < 4){ + readHeaderEndV3(stream, header); + } + else{ + readHeaderEndV4(stream, header); + } + + var tags = gaf.ReadTags(stream); + return { + header: header, + tags: tags + }; + }; +}; diff --git a/external/gaf/Library/GAFMask.js b/external/gaf/Library/GAFMask.js new file mode 100644 index 0000000000..34ca20681c --- /dev/null +++ b/external/gaf/Library/GAFMask.js @@ -0,0 +1,36 @@ + +gaf.Mask = gaf.Object.extend +({ + _className: "GAFMask", + _clippingNode: null, + + ctor : function(gafSpriteProto) + { + this._super(); + cc.assert(gafSpriteProto, "Error! Missing mandatory parameter."); + this._gafproto = gafSpriteProto; + }, + + _init : function() + { + var maskNodeProto = this._gafproto.getMaskNodeProto(); + cc.assert(maskNodeProto, "Error. Mask node for id ref " + this._gafproto.getIdRef() + " not found."); + this._maskNode = maskNodeProto._gafConstruct(); + this._clippingNode = cc.ClippingNode.create(this._maskNode); + this._clippingNode.setAlphaThreshold(0.5); + this.addChild(this._clippingNode); + }, + + setExternalTransform : function(affineTransform) + { + if(!cc.affineTransformEqualToTransform(this._maskNode._additionalTransform, affineTransform)) + { + this._maskNode.setAdditionalTransform(affineTransform); + } + }, + + _getNode : function() + { + return this._clippingNode; + } +}); \ No newline at end of file diff --git a/external/gaf/Library/GAFMaskProto.js b/external/gaf/Library/GAFMaskProto.js new file mode 100644 index 0000000000..6074fd1279 --- /dev/null +++ b/external/gaf/Library/GAFMaskProto.js @@ -0,0 +1,16 @@ + +gaf._MaskProto = function(asset, mask, idRef) +{ + this.getIdRef = function(){return idRef}; + this.getMaskNodeProto = function() {return mask}; + + /* + * Will construct GAFMask + */ + this._gafConstruct = function() + { + var ret = new gaf.Mask(this); + ret._init(); + return ret; + }; +}; diff --git a/external/gaf/Library/GAFObject.js b/external/gaf/Library/GAFObject.js new file mode 100644 index 0000000000..7d5375abe5 --- /dev/null +++ b/external/gaf/Library/GAFObject.js @@ -0,0 +1,426 @@ +var gaf = gaf || {}; + +gaf._stateHasCtx = function(state) +{ + // Check for tint color offset + if( state.hasColorTransform && + (state.colorTransform.offset.r > 0 || + state.colorTransform.offset.g > 0 || + state.colorTransform.offset.b > 0 || + state.colorTransform.offset.a > 0) + ) + { + return true; + } + + // Check for color transform filter + if(state.hasEffect) + { + for(var i = 0, total = state.effect.length; i < total; ++i) + { + if(state.effect[i].type === gaf.EFFECT_COLOR_MATRIX) + return true; + } + } + return false; +}; + +gaf.Object = cc.Node.extend +({ + _asset : null, + _className : "GAFObject", + _id : gaf.IDNONE, + _gafproto : null, + _parentTimeLine : null, + _lastVisibleInFrame : 0, + _filterStack : null, + _cascadeColorMult : null, + _cascadeColorOffset : null, + _needsCtx : false, + _usedAtlasScale: 1, + + // Public methods + ctor: function(scale) + { + if(arguments.length == 1) + { + this._usedAtlasScale = scale; + } + this._super(); + this._cascadeColorMult = cc.color(255, 255, 255, 255); + this._cascadeColorOffset = cc.color(0, 0, 0, 0); + this._filterStack = []; + }, + + /** + * @method setAnimationStartedNextLoopDelegate + * @param {function(Object)} delegate + */ + setAnimationStartedNextLoopDelegate : function (delegate) {}, + + /** + * @method setAnimationFinishedPlayDelegate + * @param {function(Object)} delegate + */ + setAnimationFinishedPlayDelegate : function (delegate) {}, + + /** + * @method setLooped + * @param {bool} looped + */ + setLooped : function (looped) {}, + + /** + * @method getBoundingBoxForCurrentFrame + * @return {cc.Rect} + */ + getBoundingBoxForCurrentFrame : function () {return null;}, + + /** + * @method setFps + * @param {uint} fps + */ + setFps : function (fps) {}, + + /** + * @method getObjectByName + * @param {String} name - name of the object to find + * @return {gaf.Object} + */ + getObjectByName : function (name) {return null;}, + + /** + * @method clearSequence + */ + clearSequence : function () {}, + + /** + * @method getIsAnimationRunning + * @return {bool} + */ + getIsAnimationRunning : function () {return false;}, + + /** + * @method getSequences + * @return [string] - list of sequences if has any + */ + getSequences : function(){return [];}, + + + /** + * @method gotoAndStop + * @param {uint|String} value - label ot frame number + * @return {bool} + */ + gotoAndStop : function (value) {}, + + /** + * @method getStartFrame + * @param {String} frameLabel + * @return {uint} + */ + getStartFrame : function (frameLabel) {return gaf.IDNONE;}, + + /** + * @method setFramePlayedDelegate + * @param {function(Object, frame)} delegate + */ + setFramePlayedDelegate : function (delegate) {}, + + /** + * @method getCurrentFrameIndex + * @return {uint} + */ + getCurrentFrameIndex : function () { + return gaf.IDNONE; + }, + + /** + * @method getTotalFrameCount + * @return {uint} + */ + getTotalFrameCount : function () {return 0;}, + + /** + * @method start + */ + start : function () {}, + + /** + * @method stop + */ + stop : function () {}, + + /** + * @method isVisibleInCurrentFrame + * @return {bool} + */ + isVisibleInCurrentFrame : function () + { + /*if (this._parentTimeLine && + ((this._parentTimeLine.getCurrentFrameIndex() + 1) != this._lastVisibleInFrame)) + { + return false; + } + else + { + return true; + }*/ + return !(this._parentTimeLine && ((this._parentTimeLine.getCurrentFrameIndex() + 1) != this._lastVisibleInFrame)); + }, + + /** + * @method isDone + * @return {bool} + */ + isDone : function () {return true;}, + + /** + * @method playSequence + * @param {String} name - name of the sequence to play + * @param {bool} looped - play looped + * @param {bool} resume - whether to resume animation if stopped. True by default + * @return {bool} + */ + playSequence : function (name, looped, resume) {return false;}, + + /** + * @method isReversed + * @return {bool} + */ + isReversed : function () {return false;}, + + /** + * @method setSequenceDelegate + * @param {function(Object, sequenceName)} delegate + */ + setSequenceDelegate : function (delegate) {}, + + /** + * @method setFrame + * @param {uint} index + * @return {bool} + */ + setFrame : function (index) {return false;}, + + /** + * @method setControlDelegate + * @param {function} func + */ + setControlDelegate : function (func) {}, + + /** + * @method getEndFrame + * @param {String} frameLabel + * @return {uint} + */ + getEndFrame : function (frameLabel) {return gaf.IDNONE;}, + + /** + * @method pauseAnimation + */ + pauseAnimation : function () {}, + + /** + * @method gotoAndPlay + * @param {uint|String} value - label ot frame number + * @return {bool} + */ + gotoAndPlay : function (value) {}, + + /** + * @method isLooped + * @return {bool} + */ + isLooped : function () {return false;}, + + /** + * @method resumeAnimation + */ + resumeAnimation : function () {}, + + /** + * @method setReversed + * @param {bool} reversed + */ + setReversed : function (reversed) {}, + + /** + * @method hasSequences + * @return {bool} + */ + hasSequences : function () {return false;}, + + /** + * @method getFps + * @return {uint} + */ + getFps : function () {return 60;}, + + /** + * @method setLocator + * @param {bool} locator + * Locator object will not draw itself, but its children will be drawn + */ + setLocator : function (locator){}, + + setExternalTransform : function(affineTransform) + { + if(!cc.affineTransformEqualToTransform(this._additionalTransform, affineTransform)) + { + this.setAdditionalTransform(affineTransform); + } + }, + + getExternalTransform : function() + { + return this._additionalTransform; + }, + + setAnimationRunning: function () {}, + + //////////////// + // Private + //////////////// + _enableTick: function(val){}, + + _resetState : function() + {}, + + _updateVisibility : function(state, parent) + { + var alphaOffset = state.hasColorTransform ? state.colorTransform.offset.a : 0; + this.setOpacity(state.alpha + alphaOffset); + //return this.isVisible(); + }, + + // @Override + isVisible : function() + { + return this.getOpacity() > 0; + }, + + // @Override + visit: function(parentCmd) + { + if(this.isVisibleInCurrentFrame()) + { + this._super(parentCmd); + } + }, + + _getFilters : function(){return null}, + + _processAnimation : function(){}, + + + _applyState : function(state, parent) + { + this._applyStateSuper(state, parent); + }, + + _applyStateSuper : function(state, parent) + { + this._needsCtx = parent._needsCtx; + this._filterStack.length = 0; // clear + this._parentTimeLine = parent; // only gaf time line can call applyState. Assign it as parent + if(this._usedAtlasScale != 1) + { + var newMat = cc.clone(state.matrix); + newMat.tx *= this._usedAtlasScale; + newMat.ty *= this._usedAtlasScale; + this.setExternalTransform(newMat); // apply transformations of the state + } + else + { + this.setExternalTransform(state.matrix); // apply transformations of the state + } + // Cascade filters + // TODO: apply more than one filter + if (state.hasEffect) { + this._filterStack = this._filterStack.concat(state.effect); + this._needsCtx = true; + } + if (parent._filterStack && parent._filterStack.length > 0) { + this._filterStack = this._filterStack.concat(parent._filterStack); + } + + if(this._filterStack.length > 0 && this._filterStack[0].type === gaf.EFFECT_COLOR_MATRIX) + { + this._needsCtx = true; + } + + // Cascade color transformations + + // If state has a tint, then we should process it + if (state.hasColorTransform) + { + this._cascadeColorMult.r = state.colorTransform.mult.r * parent._cascadeColorMult.r / 255; + this._cascadeColorMult.g = state.colorTransform.mult.g * parent._cascadeColorMult.g / 255; + this._cascadeColorMult.b = state.colorTransform.mult.b * parent._cascadeColorMult.b / 255; + this._cascadeColorMult.a = state.colorTransform.mult.a * parent._cascadeColorMult.a / 255; + + this._cascadeColorOffset.r = state.colorTransform.offset.r + parent._cascadeColorOffset.r; + this._cascadeColorOffset.g = state.colorTransform.offset.g + parent._cascadeColorOffset.g; + this._cascadeColorOffset.b = state.colorTransform.offset.b + parent._cascadeColorOffset.b; + this._cascadeColorOffset.a = state.colorTransform.offset.a + parent._cascadeColorOffset.a; + } + else + { + this._cascadeColorMult.r = parent._cascadeColorMult.r; + this._cascadeColorMult.g = parent._cascadeColorMult.g; + this._cascadeColorMult.b = parent._cascadeColorMult.b; + this._cascadeColorMult.a = state.alpha * (parent._cascadeColorMult.a / 255); + + this._cascadeColorOffset.r = parent._cascadeColorOffset.r; + this._cascadeColorOffset.g = parent._cascadeColorOffset.g; + this._cascadeColorOffset.b = parent._cascadeColorOffset.b; + this._cascadeColorOffset.a = parent._cascadeColorOffset.a; + } + + if (this._cascadeColorOffset.r > 0 || + this._cascadeColorOffset.g > 0 || + this._cascadeColorOffset.b > 0 || + this._cascadeColorOffset.a > 0) + { + this._needsCtx = true; + } + }, + + _initRendererCmd: function() + { + this._renderCmd = cc.renderer.getRenderCmd(this); + this._renderCmd._visit = this._renderCmd.visit; + var self = this; + this._renderCmd.visit = function(parentCmd) { + if(self.isVisibleInCurrentFrame()){ + this._visit(parentCmd); + } + } + }, + + _getNode : function() + { + return this; + }, + + setAnchorPoint : function(point, y) + { + if (y === undefined) + { + this._super(point.x, point.y - 1); + } + else + { + this._super(point, y - 1); + } + } + +}); + +gaf.Object._createNullObject = function() +{ + var ret = new gaf.Object(); + ret.isVisible = function(){return true}; + return ret; +}; diff --git a/external/gaf/Library/GAFShaderManager.js b/external/gaf/Library/GAFShaderManager.js new file mode 100644 index 0000000000..fd72f79825 --- /dev/null +++ b/external/gaf/Library/GAFShaderManager.js @@ -0,0 +1,63 @@ + +gaf._glShaderInit = function() { + gaf._Uniforms = { + ColorTransformMult: -1, + ColorTransformOffset: -1, + ColorMatrixBody: -1, + ColorMatrixAppendix: -1, + BlurTexelOffset: -1, + GlowTexelOffset: -1, + GlowColor: -1 + }; + + gaf._shaderCreate = function (fs, vs) { + var program = new cc.GLProgram(); + var result = program.initWithVertexShaderByteArray(vs, fs); + cc.assert(result, "Shader init error"); + program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION); + program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR); + program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS); + result = program.link(); + cc.assert(result, "Shader linking error"); + program.updateUniforms(); + return program; + }; + + gaf._shaderCreateAlpha = function () { + var program = gaf._shaderCreate(gaf.SHADER_COLOR_MATRIX_FRAG, cc.SHADER_POSITION_TEXTURE_COLOR_VERT); + gaf._Uniforms.ColorTransformMult = program.getUniformLocationForName(gaf.UNIFORM_ALPHA_TINT_MULT); + gaf._Uniforms.ColorTransformOffset = program.getUniformLocationForName(gaf.UNIFORM_ALPHA_TINT_OFFSET); + gaf._Uniforms.ColorMatrixBody = program.getUniformLocationForName(gaf.UNIFORM_ALPHA_COLOR_MATRIX_BODY); + gaf._Uniforms.ColorMatrixAppendix = program.getUniformLocationForName(gaf.UNIFORM_ALPHA_COLOR_MATRIX_APPENDIX); + return program; + }; + + gaf._shaderCreateBlur = function () { + var program = gaf._shaderCreate(gaf.SHADER_GAUSSIAN_BLUR_FRAG, cc.SHADER_POSITION_TEXTURE_COLOR_VERT); + gaf._Uniforms.BlurTexelOffset = program._glContext.getUniformLocation(program._programObj, gaf.UNIFORM_BLUR_TEXEL_OFFSET); + + return program; + }; + + gaf._shaderCreateGlow = function () { + var program = gaf._shaderCreate(gaf.SHADER_GLOW_FRAG, cc.SHADER_POSITION_TEXTURE_COLOR_VERT); + gaf._Uniforms.GlowTexelOffset = program._glContext.getUniformLocation(program._programObj, gaf.UNIFORM_GLOW_TEXEL_OFFSET); + gaf._Uniforms.GlowColor = program._glContext.getUniformLocation(program._programObj, gaf.UNIFORM_GLOW_COLOR); + return program; + }; + + gaf._Shaders = { + Alpha: gaf._shaderCreateAlpha(), + Blur: gaf._shaderCreateBlur(), + Glow: gaf._shaderCreateGlow() + }; +}; + +gaf._setupShaders = function() { + if (cc._renderType === cc._RENDER_TYPE_WEBGL) { + gaf._glShaderInit(); + } + else { + delete gaf._glShaderInit; + } +}; diff --git a/external/gaf/Library/GAFShaders.js b/external/gaf/Library/GAFShaders.js new file mode 100644 index 0000000000..7d91537285 --- /dev/null +++ b/external/gaf/Library/GAFShaders.js @@ -0,0 +1,58 @@ +gaf.SHADER_GAUSSIAN_BLUR_FRAG = + "varying mediump vec2 v_texCoord;\n" + + "uniform mediump vec2 u_step;\n" + + "void main()\n" + + "{ \n" + + " mediump vec4 sum = vec4(0.0); \n" + + " sum += texture2D(CC_Texture0, v_texCoord - u_step * 4.0) * 0.05; \n" + + " sum += texture2D(CC_Texture0, v_texCoord - u_step * 3.0) * 0.09; \n" + + " sum += texture2D(CC_Texture0, v_texCoord - u_step * 2.0) * 0.12; \n" + + " sum += texture2D(CC_Texture0, v_texCoord - u_step * 1.0) * 0.15; \n" + + " sum += texture2D(CC_Texture0, v_texCoord + u_step * 0.0) * 0.18; \n" + + " sum += texture2D(CC_Texture0, v_texCoord + u_step * 1.0) * 0.15; \n" + + " sum += texture2D(CC_Texture0, v_texCoord + u_step * 2.0) * 0.12; \n" + + " sum += texture2D(CC_Texture0, v_texCoord + u_step * 3.0) * 0.09; \n" + + " sum += texture2D(CC_Texture0, v_texCoord + u_step * 4.0) * 0.05; \n" + + " gl_FragColor = sum; \n" + + "} \n"; + +gaf.SHADER_GLOW_FRAG = + "varying mediump vec2 v_texCoord;\n" + + "uniform mediump vec2 u_step;\n" + + "uniform mediump vec4 u_glowColor;\n" + + "void main()\n" + + "{ \n" + + " mediump vec4 sum = vec4(0.0); \n" + + " sum += texture2D(CC_Texture0, v_texCoord - u_step * 4.0) * 0.05; \n" + + " sum += texture2D(CC_Texture0, v_texCoord - u_step * 3.0) * 0.09; \n" + + " sum += texture2D(CC_Texture0, v_texCoord - u_step * 2.0) * 0.12; \n" + + " sum += texture2D(CC_Texture0, v_texCoord - u_step * 1.0) * 0.15; \n" + + " sum += texture2D(CC_Texture0, v_texCoord + u_step * 0.0) * 0.18; \n" + + " sum += texture2D(CC_Texture0, v_texCoord + u_step * 1.0) * 0.15; \n" + + " sum += texture2D(CC_Texture0, v_texCoord + u_step * 2.0) * 0.12; \n" + + " sum += texture2D(CC_Texture0, v_texCoord + u_step * 3.0) * 0.09; \n" + + " sum += texture2D(CC_Texture0, v_texCoord + u_step * 4.0) * 0.05; \n" + + " gl_FragColor = sum * u_glowColor; \n" + + "} \n"; + +gaf.SHADER_COLOR_MATRIX_FRAG = + "varying mediump vec2 v_texCoord;\n" + + "varying mediump vec4 v_fragmentColor;\n" + + "uniform mediump vec4 colorTransformMult;\n" + + "uniform mediump vec4 colorTransformOffsets;\n" + + "uniform mediump mat4 colorMatrix;\n" + + "uniform mediump vec4 colorMatrix2;\n" + + "void main()\n" + + "{ \n" + + " vec4 texColor = texture2D(CC_Texture0, v_texCoord); \n" + + " const float kMinimalAlphaAllowed = 1.0e-8; \n" + + " if (texColor.a > kMinimalAlphaAllowed) \n" + + " { \n" + + " texColor = vec4(texColor.rgb / texColor.a, texColor.a); \n" + + " vec4 ctxColor = texColor * colorTransformMult + colorTransformOffsets; \n" + + " vec4 adjustColor = colorMatrix * ctxColor + colorMatrix2; \n" + + " adjustColor *= v_fragmentColor; \n" + + " texColor = vec4(adjustColor.rgb * adjustColor.a, adjustColor.a); \n" + + " } \n" + + " gl_FragColor = texColor; \n" + + "}\n"; diff --git a/external/gaf/Library/GAFSprite.js b/external/gaf/Library/GAFSprite.js new file mode 100644 index 0000000000..07ea732f44 --- /dev/null +++ b/external/gaf/Library/GAFSprite.js @@ -0,0 +1,100 @@ + +gaf.Sprite = gaf.Object.extend +({ + _className: "GAFSprite", + + _hasCtx: false, + _hasFilter: false, + + ctor : function(gafSpriteProto, usedScale) + { + this._super(usedScale); + cc.assert(gafSpriteProto, "Error! Missing mandatory parameter."); + this._gafproto = gafSpriteProto; + }, + + // Private + + _init : function() + { + var frame = this._gafproto.getFrame(); + cc.assert(frame instanceof cc.SpriteFrame, "Error. Wrong object type."); + + // Create sprite with custom render command from frame + this._sprite = new cc.Sprite(); + this._sprite._renderCmd = this._gafCreateRenderCmd(this._sprite); + this._sprite.initWithSpriteFrame(frame); + + this._sprite.setAnchorPoint(this._gafproto.getAnchor()); + this.addChild(this._sprite); + //this._sprite.setCascadeColorEnabled(true); + //this._sprite.setCascadeOpacityEnabled(true); + this._sprite.setOpacityModifyRGB(true); + + if(cc._renderType === cc._RENDER_TYPE_WEBGL) + this._sprite.setBlendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + }, + + _applyState : function(state, parent) + { + this._applyStateSuper(state, parent); + if(this._needsCtx) + { + // Enable ctx state if wasn't enabled + if(!this._hasCtx) + { + this._enableCtx(); + this._hasCtx = true; + } + // Set ctx shader + this._applyCtxState(state); + } + else + { + // Disable ctx state if was enabled + if(this._hasCtx) + { + this._disableCtx(); + this._hasCtx = false; + } + // Apply color + if(!cc.colorEqual(this._sprite._realColor, this._cascadeColorMult)) + { + this._sprite.setColor(this._cascadeColorMult); + } + // Apply opacity + if(this._sprite.getOpacity() != this._cascadeColorMult.a) + { + this._sprite.setOpacity(this._cascadeColorMult.a); + } + + } + }, + + _enableCtx: function() + { + this._sprite._renderCmd._enableCtx(); + }, + + _disableCtx: function() + { + this._sprite._renderCmd._disableCtx(); + }, + + _applyCtxState: function(state){ + this._sprite._renderCmd._applyCtxState(this); + }, + + getBoundingBoxForCurrentFrame: function () + { + var result = this._sprite.getBoundingBox(); + return cc._rectApplyAffineTransformIn(result, this.getNodeToParentTransform()); + }, + + _gafCreateRenderCmd: function(item){ + if(cc._renderType === cc._RENDER_TYPE_CANVAS) + return new gaf.Sprite.CanvasRenderCmd(item); + else + return new gaf.Sprite.WebGLRenderCmd(item); + } +}); diff --git a/external/gaf/Library/GAFSpriteCanvasRenderCmd.js b/external/gaf/Library/GAFSpriteCanvasRenderCmd.js new file mode 100644 index 0000000000..26f7b0ed18 --- /dev/null +++ b/external/gaf/Library/GAFSpriteCanvasRenderCmd.js @@ -0,0 +1,233 @@ + +(function() { + gaf.Sprite.CanvasRenderCmd = function (renderable) { + cc.Sprite.CanvasRenderCmd.call(this, renderable); + this._hasTintMult = false; + this._hasTintOffset = false; + this._hasCtx = false; + this._tintMult = cc.color(255,255,255,255); + this._tintOffset = cc.color(0,0,0,0); + this._textureDirty = false; + }; + var proto = gaf.Sprite.CanvasRenderCmd.prototype = Object.create(cc.Sprite.CanvasRenderCmd.prototype); + proto.constructor = gaf.Sprite.CanvasRenderCmd; + + proto._disableCtx = function(){ + this._hasTintOffset = false; + this._hasCtx = false; + this._textureDirty = true; + this.setDirtyFlag(cc.Node._dirtyFlags.colorDirty); + this._tintMult = cc.color(255,255,255,255); + this._tintOffset = cc.color(0,0,0,0); + }; + + proto._enableCtx = function(){ + + }; + + proto._applyCtxState = function(gafObject){ + + var tintMult = gafObject._cascadeColorMult; + var tintOffset = gafObject._cascadeColorOffset; + var opacity = tintMult.a; + + // Apply opacity + if(this._node.getOpacity() != opacity) + { + this._node.setOpacity(opacity); + } + + // Check Tint multiplicator + var multDirty = !cc.colorEqual(this._tintMult, tintMult); + if(multDirty) + { + this._node.setColor(tintMult); + this._tintMult = tintMult; + this._hasTintMult = + (tintMult.r !== 255 || + tintMult.g !== 255 || + tintMult.b !== 255 ); + } + + // Check Tint offset + var offfsetDirty = + (this._tintOffset.r != tintOffset.r) || + (this._tintOffset.g != tintOffset.g) || + (this._tintOffset.b != tintOffset.b) || + (this._tintOffset.a != tintOffset.a); + + if(offfsetDirty) + { + this._tintOffset = tintOffset; + this._hasTintOffset = + (tintOffset.r !== 0 || + tintOffset.g !== 0 || + tintOffset.b !== 0 || + tintOffset.a !== 0 ); + } + + // Update dirty flag + this._textureDirty = multDirty || offfsetDirty; + if(this._textureDirty) + { + this.setDirtyFlag(cc.Node._dirtyFlags.colorDirty); + } + + + this._hasCtx = gafObject._filterStack.length > 0 && gafObject._filterStack[0].type === gaf.EFFECT_COLOR_MATRIX; + + }; + + proto.rendering = function(ctx, scaleX, scaleY) + { + var node = this._node; + var locTextureCoord = this._textureCoord, + alpha = (this._displayedOpacity / 255); + + if ((node._texture && ((locTextureCoord.width === 0 || locTextureCoord.height === 0) //set texture but the texture isn't loaded. + || !node._texture._textureLoaded)) || alpha === 0) + return; + + var wrapper = ctx || cc._renderContext, + context = wrapper.getContext(); + var locX = node._offsetPosition.x, + locHeight = node._rect.height, + locWidth = node._rect.width, + locY = -node._offsetPosition.y - locHeight, + image; + + wrapper.setTransform(this._worldTransform, scaleX, scaleY); + wrapper.setCompositeOperation(this._blendFuncStr); + wrapper.setGlobalAlpha(alpha); + + if(node._flippedX || node._flippedY) + wrapper.save(); + if (node._flippedX) { + locX = -locX - locWidth; + context.scale(-1, 1); + } + if (node._flippedY) { + locY = node._offsetPosition.y; + context.scale(1, -1); + } + + image = node._texture._htmlElementObj; + + if (this._colorized) { + context.drawImage(image, + 0, 0, locTextureCoord.width,locTextureCoord.height, + locX * scaleX,locY * scaleY, locWidth * scaleX, locHeight * scaleY); + } else { + context.drawImage(image, + locTextureCoord.renderX, locTextureCoord.renderY, locTextureCoord.width, locTextureCoord.height, + locX * scaleX, locY * scaleY, locWidth * scaleX, locHeight * scaleY); + } + + if(node._flippedX || node._flippedY) + wrapper.restore(); + cc.g_NumberOfDraws++; + }; + + if(cc.sys._supportCanvasNewBlendModes){ + proto._updateColor = function () { + var displayedColor = this._displayedColor, node = this._node; + this._hasTintMult |= (displayedColor.r !== 255 || displayedColor.g !== 255 || displayedColor.b !== 255); + + // If no color changes + if(this._textureDirty) + { + this._textureDirty = false; + if (this._colorized) { + this._colorized = false; + node.texture = this._originalTexture; + } + } + else + { + return; + } + + var locElement, locTexture = node._texture, locRect = this._textureCoord; + if(this._hasTintMult) + { + if (locTexture && locRect.validRect && this._originalTexture) { + locElement = locTexture.getHtmlElementObj(); + if (!locElement) + return; + + this._colorized = true; + if (this._hasTintOffset || this._hasCtx) displayedColor = this._tintMult; + + locElement = cc.Sprite.CanvasRenderCmd._generateTintImageWithMultiply(this._originalTexture._htmlElementObj, displayedColor, locRect); + locTexture = new cc.Texture2D(); + locTexture.initWithElement(locElement); + locTexture.handleLoadedTexture(); + node.texture = locTexture; + } + } + + locTexture = node._texture; + if(this._hasTintOffset) + { + var cacheTextureForColor = cc.textureCache.getTextureColors(this._originalTexture.getHtmlElementObj()); + if (locTexture && locRect.validRect && this._originalTexture) { + locElement = locTexture.getHtmlElementObj(); + if (!locElement) + return; + if(this._colorized) + var texRect = cc.rect(0,0,locRect.width, locRect.height); + else + texRect = locRect; + locElement = this._gafGenerateTintImage(node.texture._htmlElementObj, texRect, cacheTextureForColor, this._tintOffset, locRect); + locTexture = new cc.Texture2D(); + locTexture.initWithElement(locElement); + locTexture.handleLoadedTexture(); + node.texture = locTexture; + this._colorized = true; + } + } + + + }; + + proto._gafGenerateTintImage = function(texture, texRect, tintedImgCache, color, rect, renderCanvas){ + if (!rect) + rect = cc.rect(0, 0, texture.width, texture.height); + + // Create a new buffer if required + var w = Math.min(rect.width, tintedImgCache[0].width); + var h = Math.min(rect.height, tintedImgCache[0].height); + var buff = renderCanvas, ctx; + if (!buff) { + buff = cc.newElement("canvas"); + buff.width = w; + buff.height = h; + ctx = buff.getContext("2d"); + } else { + ctx = buff.getContext("2d"); + ctx.clearRect(0, 0, w, h); + } + ctx.save(); + + // draw a channel with alpha of the original image + ctx.globalCompositeOperation = 'source-over'; + //ctx.globalAlpha = 1; + ctx.drawImage(tintedImgCache[2], rect.x, rect.y, w, h, 0, 0, w, h); + + // draw a rect of specified color + ctx.globalCompositeOperation = 'source-in'; + ctx.fillStyle = 'rgba(' + Math.round(color.r) + ',' + Math.round(color.g) + ',' + Math.round(color.b) + ',1)'; + ctx.fillRect(0, 0, w, h); + + // add the desired image to the drawn + ctx.globalCompositeOperation = 'lighter'; + ctx.drawImage(texture, texRect.x, texRect.y, w, h, 0, 0, w, h); + + + ctx.restore(); + return buff; + + }; + } + +})(); diff --git a/external/gaf/Library/GAFSpriteProto.js b/external/gaf/Library/GAFSpriteProto.js new file mode 100644 index 0000000000..6e33fa7d5f --- /dev/null +++ b/external/gaf/Library/GAFSpriteProto.js @@ -0,0 +1,36 @@ + +gaf._SpriteProto = function(asset, atlasFrames, elementAtlasIdRef) +{ + //this._anchor = atlasFrame._gafAnchor; + //delete atlasFrame._gafAnchor; + + this.getFrames = function(){return atlasFrames}; + this.getIdRef = function(){return elementAtlasIdRef}; + //this.getAnchor = function() {return this._anchor}; + this.getAsset = function() {return asset}; + + /* + * Will construct GAFSprite + */ + this._gafConstruct = function() + { + var usedScale = this.getAsset()._usedAtlasScale; + var ret = new gaf.Sprite(this, usedScale); + ret._init(); + return ret; + }; +}; + +gaf._SpriteProto.prototype.getFrame = function() +{ + var usedScale = this.getAsset()._usedAtlasScale; + cc.assert(usedScale, "Error. Atlas scale zero."); + var frames = this.getFrames()[usedScale]; + cc.assert(frames, "Error. No frames found for used scale `"+usedScale+"`"); + return frames[this.getIdRef()]; +}; + +gaf._SpriteProto.prototype.getAnchor = function() +{ + return this.getFrame()._gafAnchor; +}; diff --git a/external/gaf/Library/GAFSpriteWebGLRenderCmd.js b/external/gaf/Library/GAFSpriteWebGLRenderCmd.js new file mode 100644 index 0000000000..eabe25b0c9 --- /dev/null +++ b/external/gaf/Library/GAFSpriteWebGLRenderCmd.js @@ -0,0 +1,132 @@ + +(function(){ + gaf.Sprite.WebGLRenderCmd = function (renderable) { + cc.Sprite.WebGLRenderCmd.call(this, renderable); + this._defualtShader = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURECOLOR); + this._customShader = gaf._Shaders.Alpha; + + //this._shaderProgram = this._defualtShader; + + this._tintMult = null; + this._tintOffset = null; + this._ctxMatrixBody = null; + this._ctxMatrixAppendix = null; + }; + + var proto = gaf.Sprite.WebGLRenderCmd.prototype = Object.create(cc.Sprite.WebGLRenderCmd.prototype); + proto.constructor = gaf.Sprite.WebGLRenderCmd; + + proto._identityVec = [1.0, 1.0, 1.0, 1.0]; + proto._zeroVec = [0.0, 0.0, 0.0, 0.0]; + proto._identityMat = [ + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + ]; + + proto._disableCtx = function(){ + this.setShaderProgram(this._defualtShader); + }; + + proto._enableCtx = function(){ + this.setShaderProgram(this._customShader); + }; + + proto._applyCtxState = function(gafObject){ + var tintMult = gafObject._cascadeColorMult; + this._tintMult = [ + tintMult.r / 255, + tintMult.g / 255, + tintMult.b / 255, + tintMult.a / 255 + ]; + + var tintOffset = gafObject._cascadeColorOffset; + this._tintOffset = [ + tintOffset.r / 255, + tintOffset.g / 255, + tintOffset.b / 255, + tintOffset.a / 255 + ]; + + var filterStack = gafObject._filterStack; + if(filterStack && filterStack.length > 0 && filterStack[0].type === gaf.EFFECT_COLOR_MATRIX) + { + var m = filterStack[0].colorMatrix; + this._ctxMatrixBody = [ + m.rr, m.rg, m.rb, m.ra, + m.gr, m.gg, m.gb, m.ga, + m.br, m.bg, m.bb, m.ba, + m.ar, m.ag, m.ab, m.aa + ]; + this._ctxMatrixAppendix = [ + m.r / 255, + m.g / 255, + m.b / 255, + m.a / 255 + ]; + } + else + { + this._ctxMatrixBody = null; + this._ctxMatrixAppendix = null; + } + }; + + proto._setUniforms = function() + { + if(this._shaderProgram === this._customShader) + { + this._shaderProgram.use(); + { + this._shaderProgram.setUniformLocationWith4fv( + gaf._Uniforms.ColorTransformMult, + this._tintMult, + 1 + ); + this._shaderProgram.setUniformLocationWith4fv( + gaf._Uniforms.ColorTransformOffset, + this._tintOffset, + 1 + ); + } + + if(this._ctxMatrixBody && this._ctxMatrixAppendix) + { + this._shaderProgram.setUniformLocationWithMatrix4fv( + gaf._Uniforms.ColorMatrixBody, + this._ctxMatrixBody, + 1 + ); + this._shaderProgram.setUniformLocationWith4fv( + gaf._Uniforms.ColorMatrixAppendix, + this._ctxMatrixAppendix, + 1 + ); + } + else + { + this._shaderProgram.setUniformLocationWithMatrix4fv( + gaf._Uniforms.ColorMatrixBody, + this._identityMat, + 1 + ); + this._shaderProgram.setUniformLocationWith4fv( + gaf._Uniforms.ColorMatrixAppendix, + this._zeroVec, + 1 + ); + } + } + }; + + proto.rendering = function(ctx) + { + this._setUniforms(); + + // Super call + cc.Sprite.WebGLRenderCmd.prototype.rendering.call(this, ctx); + }; + +})(); diff --git a/external/gaf/Library/GAFTags.js b/external/gaf/Library/GAFTags.js new file mode 100644 index 0000000000..09f8186538 --- /dev/null +++ b/external/gaf/Library/GAFTags.js @@ -0,0 +1,378 @@ + +gaf.ReadSingleTag = function(stream){ + var tagId = stream.Ushort(); + var tag = gaf.Tags[tagId]; + var result = {}; + if(typeof tag === "undefined"){ + console.log("GAF. Non implemented tag detected."); + gaf.Tags.Default.parse(stream, tagId); + } + else{ + //console.log("tag " + tag.tagName); + result = tag.parse(stream, tagId); + } + return result; +}; + +gaf.ReadTags = function(stream){ + var tags = []; + try { + do { + var tag = gaf.ReadSingleTag(stream); + tags.push(tag); + } while (tag.tagId != 0); + } + catch (e){ + if (e instanceof Error && e.message == "GAF format error"){ + console.log("GAF format error:\n" + e.stack); + // Tag will be closed and parser will continue from where it should. + } + else{ + console.log(e.stack); + throw e; + } + } + return tags; +}; + + +gaf.Tag = function(){ + this.Default = Object.create(gaf.Tag.base); + this["0"] = Object.create(gaf.Tag.End); + this["1"] = Object.create(gaf.Tag.DefineAtlas); + this["2"] = Object.create(gaf.Tag.DefineAnimationMasks); + this["3"] = Object.create(gaf.Tag.DefineAnimationObjects); + this["4"] = Object.create(gaf.Tag.DefineAnimationFrames); + this["5"] = Object.create(gaf.Tag.DefineNamedParts); + this["6"] = Object.create(gaf.Tag.DefineSequences); + this["7"] = Object.create(gaf.Tag.DefineTextFields); + this["8"] = Object.create(gaf.Tag.DefineAtlas2); + this["9"] = Object.create(gaf.Tag.DefineStage); + this["10"] = Object.create(gaf.Tag.DefineAnimationObjects2); + this["11"] = Object.create(gaf.Tag.DefineAnimationMasks2); + this["12"] = Object.create(gaf.Tag.DefineAnimationFrames2); + this["13"] = Object.create(gaf.Tag.DefineTimeline); +}; + +gaf.Tag.base = function() {}; +gaf.Tag.base.parse = function(stream, tagId){ + var size = stream.Uint(); + + stream.startNestedBuffer(size); + var result = this.doParse(stream); + stream.endNestedBuffer(); + + result.tagName = this.tagName; + result.tagId = tagId; + return result; +}; +gaf.Tag.base.doParse = function(stream){ + return {}; + }; + +gaf.Tag.End = Object.create(gaf.Tag.base); +gaf.Tag.End.tagName = "TagEnd"; + +gaf.Tag.DefineAtlas = Object.create(gaf.Tag.base); +gaf.Tag.DefineAtlas.tagName = "TagDefineAtlas"; +gaf.Tag.DefineAtlas.doParse = function (s) { + var exec = s.fields( + 'scale', 'Float', + 'atlases', s.array('Ubyte', s.fields( + 'id', 'Uint', + 'sources', s.array('Ubyte', s.fields( + 'source', 'String', + 'csf', 'Float' + )) + )), + 'elements', s.array('Uint', s.fields( + 'pivot', 'Point', + 'origin', 'Point', + 'scale', 'Float', + 'size', 'Point', + 'atlasId', 'Uint', + 'elementAtlasId', 'Uint' + )) + ); + return {'content': exec()}; +}; + +gaf.Tag.DefineAnimationMasks = Object.create(gaf.Tag.base); +gaf.Tag.DefineAnimationMasks.tagName = "TagDefineAnimationMasks"; +gaf.Tag.DefineAnimationMasks.doParse = function (s) { + var exec = s.array('Uint', s.fields( + 'objectId', 'Uint', + 'elementAtlasIdRef', 'Uint' + )); + var result = {'content': exec()}; + debugger; + return result; +}; + +gaf.Tag.DefineAnimationObjects = Object.create(gaf.Tag.base); +gaf.Tag.DefineAnimationObjects.tagName = "TagDefineAnimationObjects"; +gaf.Tag.DefineAnimationObjects.doParse = function (s) { + var exec = s.array('Uint', s.fields( + 'objectId', 'Uint', + 'elementAtlasIdRef', 'Uint' + )); + return {'content': exec()}; +}; + +gaf.Tag.DefineAnimationFrames = Object.create(gaf.Tag.base); +gaf.Tag.DefineAnimationFrames.tagName = "TagDefineAnimationFrames"; +gaf.Tag.DefineAnimationFrames.doParse = function(s){ + var exec = s.array('Uint', s.fields( + 'frame', 'Uint', + 'state', s.array('Uint', s.fields( + 'hasColorTransform', 'Ubyte', + 'hasMask', 'Ubyte', + 'hasEffect', 'Ubyte', + 'objectIdRef', 'Uint', + 'depth', 'Int', + 'alpha', 'Float', + 'matrix', 'Matrix', + 'colorTransform', s.condition('hasColorTransform', 1, s.fields( + 'alphaOffset', 'Float', + 'redMultiplier', 'Float', + 'redOffset', 'Float', + 'greenMultiplier', 'Float', + 'greenOffset', 'Float', + 'blueMultiplier', 'Float', + 'blueOffset', 'Float' + )), + 'effect', s.condition('hasEffect', 1, s.array('Ubyte', gaf.Tag._readFilter(s))), + 'maskObjectIdRef', s.condition('hasMask', 1, s.fields( + 'maskObjectIdRef', 'Uint' + )) + )) + )); + return {'content': exec()}; +}; + +gaf.Tag.DefineNamedParts = Object.create(gaf.Tag.base); +gaf.Tag.DefineNamedParts.tagName = "TagDefineNamedParts"; +gaf.Tag.DefineNamedParts.doParse = function(s) { + var exec = s.array('Uint', s.fields( + 'objectId', 'Uint', + 'name', 'String' + )); + return {'content': exec()}; +}; + +gaf.Tag.DefineSequences = Object.create(gaf.Tag.base); +gaf.Tag.DefineSequences.tagName = "TagDefineSequences"; +gaf.Tag.DefineSequences.doParse = function(s) { + var exec = s.array('Uint', s.fields( + 'id', 'String', + 'start', 'Ushort', + 'end', 'Ushort' + )); + return {'content': exec()}; +}; + +gaf.Tag.DefineTextFields = Object.create(gaf.Tag.base); +gaf.Tag.DefineTextFields.tagName = "TagDefineTextFields"; +gaf.Tag.DefineTextFields.doParse = function(s) { + var exec = s.array('Uint', s.fields( + 'id', 'Uint', + 'pivot', 'Point', + 'end', 'Ushort', + 'width', 'Float', + 'height', 'Float', + 'text', 'String', + 'embedFonts', 'Boolean', + 'multiline', 'Boolean', + 'wordWrap', 'Boolean', + 'hasRestrict', 'Boolean', + 'restrict', s.condition('hasRestrict', 1, function (){return s['String'];}), + 'editable', 'Boolean', + 'selectable', 'Boolean', + 'displayAsPassword', 'Boolean', + 'maxChars', 'Uint', + 'align', 'Uint', + 'blockIndent', 'Uint', + 'bold', 'Boolean', + 'bullet', 'Boolean', + 'color', 'color', + 'font', 'String', + 'indent', 'Uint', + 'italic', 'Boolean', + 'kerning', 'Boolean', + 'leading', 'Uint', + 'leftMargin', 'Uint', + 'letterSpacing', 'Float', + 'rightMargin', 'Uint', + 'size', 'Uint', + 'tabStops', s.array('Uint', s.fields( + 'value', 'Uint' + )), + 'target', 'string', + 'underline', 'Boolean', + 'url', 'String' + )); + return {'content': exec()}; +}; + +gaf.Tag.DefineAtlas2 = Object.create(gaf.Tag.base); +gaf.Tag.DefineAtlas2.tagName = "TagDefineAtlas2"; +gaf.Tag.DefineAtlas2.doParse = function(s) { + var exec = s.fields( + 'scale', 'Float', + 'atlases', s.array('Ubyte', s.fields( + 'id', 'Uint', + 'sources', s.array('Ubyte', s.fields( + 'source', 'String', + 'csf', 'Float' + )) + )), + 'elements', s.array('Uint', s.fields( + 'pivot', 'Point', + 'origin', 'Point', + 'scale', 'Float', + 'size', 'Point', + 'atlasId', 'Uint', + 'elementAtlasId', 'Uint', + 'hasScale9Grid', 'Boolean', + 'scale9GridRect', s.condition('hasScale9Grid', 1, function(){return s.Rect();}) + )) + ); + return {'content': exec()}; +}; + +gaf.Tag.DefineStage = Object.create(gaf.Tag.base); +gaf.Tag.DefineStage.tagName = "TagDefineStage"; +gaf.Tag.DefineStage.doParse = function(s) { + var exec = s.fields( + 'fps', 'Ubyte', + 'color', 'color', + 'width', 'Ushort', + 'height', 'Ushort' + ); + return {'content': exec()}; +}; + +gaf.Tag.DefineAnimationObjects2 = Object.create(gaf.Tag.base); +gaf.Tag.DefineAnimationObjects2.tagName = "TagDefineAnimationObjects2"; +gaf.Tag.DefineAnimationObjects2.doParse = function(s) { + var exec = s.array('Uint', s.fields( + 'objectId', 'Uint', + 'elementAtlasIdRef', 'Uint', + 'type', 'Ushort' + )); + return {'content': exec()}; +}; + +gaf.Tag.DefineAnimationMasks2 = Object.create(gaf.Tag.base); +gaf.Tag.DefineAnimationMasks2.tagName = "TagDefineAnimationMasks2"; +gaf.Tag.DefineAnimationMasks2.doParse = function(s) { + var exec = s.array('Uint', s.fields( + 'objectId', 'Uint', + 'elementAtlasIdRef', 'Uint', + 'type', 'Ushort' + )); + return {'content': exec()}; +}; + +gaf.Tag.DefineAnimationFrames2 = Object.create(gaf.Tag.base); +gaf.Tag.DefineAnimationFrames2.tagName = "TagDefineAnimationFrames2"; +gaf.Tag.DefineAnimationFrames2.doParse = function(s) { + var exec = s.array('Uint', s.fields( + 'frame', 'Uint', + 'hasChangesInDisplayList', 'Boolean', + 'hasActions', 'Boolean', + 'state', s.condition('hasChangesInDisplayList', 1, s.array('Uint', s.fields( + 'hasColorTransform', 'Boolean', + 'hasMask', 'Boolean', + 'hasEffect', 'Boolean', + 'objectIdRef', 'Uint', + 'depth', 'Int', + 'alpha', 'Float', + 'matrix', 'Matrix', + 'colorTransform', s.condition('hasColorTransform', 1, s.fields( + 'alphaOffset', 'Float', + 'redMultiplier', 'Float', + 'redOffset', 'Float', + 'greenMultiplier', 'Float', + 'greenOffset', 'Float', + 'blueMultiplier', 'Float', + 'blueOffset', 'Float' + )), + 'effect', s.condition('hasEffect', 1, s.array('Ubyte', gaf.Tag._readFilter(s))), + 'maskObjectIdRef', s.condition('hasMask', 1, function(){return s.Uint()}) + ))), + 'actions', s.condition('hasActions', 1, s.array('Uint', s.fields( + 'type', 'Uint', + 'scope', 'String', + 'params', gaf.Tag._readActionArguments(s) + ))) + )); + return {'content': exec()}; +}; + +gaf.Tag.DefineTimeline = Object.create(gaf.Tag.base); +gaf.Tag.DefineTimeline.tagName = "TagDefineTimeline"; +gaf.Tag.DefineTimeline.doParse = function(s) { + var exec = s.fields( + 'id', 'Uint', + 'animationFrameCount', 'Uint', + 'boundingBox', 'Rect', + 'pivotPoint', 'Point', + 'hasLinkage', 'Boolean', + 'linkageName', s.condition('hasLinkage', 1, function () { + return s.String(); + }) + ); + var result = {'content': exec()}; + result.content.tags = gaf.ReadTags(s); + return result; +}; + +gaf.Tag._readActionArguments = function(s){ + return function(){ + var size = s.Uint(); + var ret = []; + s.startNestedBuffer(size); + while(s.maxOffset() < s.tell()){ + ret.push(s.String()); + } + s.endNestedBuffer(); + return ret; + }; +}; + +gaf.Tag._readFilter = function(s){ + return s.fields( + 'type', 'Uint', + 'dropShadow', s.condition('type', gaf.EFFECT_DROP_SHADOW, s.fields( // DropShadow + 'color', 'color', + 'blurX', 'Float', + 'blurY', 'Float', + 'angle', 'Float', + 'distance', 'Float', + 'strength', 'Float', + 'inner', 'Boolean', + 'knockout', 'Boolean' + )), + 'blur', s.condition('type', gaf.EFFECT_BLUR, s.fields( // Blur + 'blurX', 'Float', + 'blurY', 'Float' + )), + 'glow', s.condition('type', gaf.EFFECT_GLOW, s.fields( // Glow + 'color', 'color', + 'blurX', 'Float', + 'blurY', 'Float', + 'strength', 'Float', + 'inner', 'Boolean', + 'knockout', 'Boolean' + )), + 'colorMatrix', s.condition('type', gaf.EFFECT_COLOR_MATRIX, s.fields( // ColorMatrix + 'rr', 'Float', 'gr', 'Float', 'br', 'Float', 'ar', 'Float', 'r', 'Float', + 'rg', 'Float', 'gg', 'Float', 'bg', 'Float', 'ag', 'Float', 'g', 'Float', + 'rb', 'Float', 'gb', 'Float', 'bb', 'Float', 'ab', 'Float', 'b', 'Float', + 'ra', 'Float', 'ga', 'Float', 'ba', 'Float', 'aa', 'Float', 'a', 'Float' + )) + ) +}; + +gaf.Tags = new gaf.Tag(); diff --git a/external/gaf/Library/GAFTextField.js b/external/gaf/Library/GAFTextField.js new file mode 100644 index 0000000000..04f9744920 --- /dev/null +++ b/external/gaf/Library/GAFTextField.js @@ -0,0 +1,6 @@ + +gaf.TextField = gaf.Object.extend +({ + _className: "GAFTextField" + +}); \ No newline at end of file diff --git a/external/gaf/Library/GAFTimeLine.js b/external/gaf/Library/GAFTimeLine.js new file mode 100644 index 0000000000..ef9387aa46 --- /dev/null +++ b/external/gaf/Library/GAFTimeLine.js @@ -0,0 +1,547 @@ + +gaf.TimeLine = gaf.Object.extend +({ + _className: "GAFTimeLine", + _objects: null, + _container: null, + _animationStartedNextLoopDelegate: null, + _animationFinishedPlayDelegate: null, + _framePlayedDelegate: null, + _sequenceDelegate: null, + _fps: 60, + _frameTime: 1/60, + _currentSequenceStart: gaf.FIRST_FRAME_INDEX, + _currentSequenceEnd: gaf.FIRST_FRAME_INDEX, + _totalFrameCount: 0, + _isRunning: false, + _isLooped: false, + _isReversed: false, + _timeDelta: 0, + _animationsSelectorScheduled: false, + _currentFrame: gaf.FIRST_FRAME_INDEX, + + + setAnimationStartedNextLoopDelegate: function (delegate) + { + this._animationStartedNextLoopDelegate = delegate; + }, + setAnimationFinishedPlayDelegate: function (delegate) + { + this._animationFinishedPlayDelegate = delegate; + }, + setLooped: function (looped, recursively) + { + this._isLooped = looped; + if (recursively) + { + this._objects.forEach(function (item) + { + item.setLooped(looped, recursively); + }); + } + }, + getBoundingBoxForCurrentFrame: function () + { + var result = null;//cc.rect(); + var isFirstObj = true; + this._objects.forEach(function (item) { + if(item.isVisibleInCurrentFrame() && item.isVisible()) + { + var bb = item.getBoundingBoxForCurrentFrame(); + if(!bb) + { + bb = item.getBoundingBox(); + } + if (isFirstObj) + { + isFirstObj = false; + result = bb; + } + else + { + result = cc.rectUnion(result, bb); + } + } + }); + return cc._rectApplyAffineTransformIn(result, this._container.getNodeToParentTransform()); + }, + setFps: function (fps) + { + cc.assert(fps !== 0, 'Error! Fps is set to zero.'); + this._fps = fps; + this._frameTime = 1/fps; + }, + getObjectByName: function (name) + { + var elements = name.split('.'); + var result = null; + var retId = -1; + var timeLine = this; + var BreakException = {}; + try + { + elements.forEach(function(element) + { + var parts = timeLine._gafproto.getNamedParts(); + if(parts.hasOwnProperty(element)) + { + retId = parts[element]; + } + else + { + // Sequence is incorrect + BreakException.lastElement = element; + throw BreakException; + } + result = timeLine._objects[retId]; + timeLine = result; + }); + } + catch (e) + { + if (e!==BreakException) + { + throw e; + } + cc.log("Sequence incorrect: `" + name + "` At: `" + BreakException.lastElement + "`"); + return null; + } + return result; + }, + clearSequence: function () + { + this._currentSequenceStart = gaf.FIRST_FRAME_INDEX; + this._currentSequenceEnd = this._gafproto.getTotalFrames(); + }, + getIsAnimationRunning: function () + { + return this._isRunning; + }, + gotoAndStop: function (value) + { + var frame = 0; + if (typeof value === 'string') + { + frame = this.getStartFrame(value); + } + else + { + frame = value; + } + if (this.setFrame(frame)) + { + this.setAnimationRunning(false, false); + return true; + } + return false; + }, + gotoAndPlay: function (value) + { + var frame = 0; + if (typeof value === 'string') + { + frame = this.getStartFrame(value); + } + else + { + frame = value; + } + if (this.setFrame(frame)) + { + this.setAnimationRunning(true, false); + return true; + } + return false; + }, + getStartFrame: function (frameLabel) + { + var seq = this._gafproto.getSequences()[frameLabel]; + if (seq) + { + return seq.start; + } + return gaf.IDNONE; + }, + getEndFrame: function (frameLabel) + { + var seq = this._gafproto.getSequences()[frameLabel]; + if (seq) + { + return seq.end; + } + return gaf.IDNONE; + }, + setFramePlayedDelegate: function (delegate) + { + this._framePlayedDelegate = delegate; + }, + getCurrentFrameIndex: function () + { + return this._showingFrame; + }, + getTotalFrameCount: function () + { + return this._gafproto.getTotalFrames(); + }, + start: function () + { + this._enableTick(true); + if (!this._isRunning) + { + this._currentFrame = gaf.FIRST_FRAME_INDEX; + this.setAnimationRunning(true, true); + } + }, + stop: function () + { + this._enableTick(false); + if (this._isRunning) + { + this._currentFrame = gaf.FIRST_FRAME_INDEX; + this.setAnimationRunning(false, true); + } + }, + isDone: function () + { + if (this._isLooped) + { + return false; + } + else + { + if (!this._isReversed) + { + return this._currentFrame > this._totalFrameCount; + } + else + { + return this._currentFrame < gaf.FIRST_FRAME_INDEX - 1; + } + } + }, + getSequences: function() + { + return this._gafproto.getSequences(); + }, + playSequence: function (name, looped) + { + var s = this.getStartFrame(name); + var e = this.getEndFrame(name); + if (gaf.IDNONE === s || gaf.IDNONE === e) + { + return false; + } + this._currentSequenceStart = s; + this._currentSequenceEnd = e; + if (this._currentFrame < this._currentSequenceStart || this._currentFrame > this._currentSequenceEnd) + { + this._currentFrame = this._currentSequenceStart; + } + else + { + this._currentFrame = this._currentSequenceStart; + } + this.setLooped(looped, false); + this.resumeAnimation(); + return true; + }, + isReversed: function () + { + return this._isReversed; + }, + setSequenceDelegate: function (delegate) + { + this._sequenceDelegate = delegate; + }, + setFrame: function (index) + { + if (index >= gaf.FIRST_FRAME_INDEX && index < this._totalFrameCount) + { + this._showingFrame = index; + this._currentFrame = index; + this._processAnimation(); + return true; + } + return false; + }, + + pauseAnimation: function () + { + if (this._isRunning) + { + this.setAnimationRunning(false, false); + } + }, + isLooped: function () + { + return this._isLooped; + }, + resumeAnimation: function () + { + if (!this._isRunning) + { + this.setAnimationRunning(true, false); + } + }, + setReversed: function (reversed) + { + this._isReversed = reversed; + }, + hasSequences: function () + { + return this._gafproto.getSequences().length > 0; + }, + getFps: function () + { + return this._fps; + }, + + + // Private + + ctor: function(gafTimeLineProto, scale) + { + this._super(scale); + this._objects = []; + cc.assert(gafTimeLineProto, "Error! Missing mandatory parameter."); + this._gafproto = gafTimeLineProto; + }, + + setExternalTransform: function(affineTransform) + { + if(!cc.affineTransformEqualToTransform(this._container._additionalTransform, affineTransform)) + { + this._container.setAdditionalTransform(affineTransform); + } + }, + + _init: function() + { + this.setContentSize(this._gafproto.getBoundingBox()); + this._currentSequenceEnd = this._gafproto.getTotalFrames(); + this._totalFrameCount = this._currentSequenceEnd; + this.setFps(this._gafproto.getFps()); + this._container = new cc.Node(); + this.addChild(this._container); + + var self = this; + var asset = this._gafproto.getAsset(); + + // Construct objects for current time line + this._gafproto.getObjects().forEach(function(object) + { + var objectProto = asset._getProtos()[object]; + cc.assert(objectProto, "Error. GAF proto for type: " + object.type + " and reference id: " + object + " not found."); + self._objects[object] = objectProto._gafConstruct(); + }); + }, + + _enableTick: function(val) + { + if (!this._animationsSelectorScheduled && val) + { + this.schedule(this._processAnimations); + this._animationsSelectorScheduled = true; + } + else if (this._animationsSelectorScheduled && !val) + { + this.unschedule(this._processAnimations); + this._animationsSelectorScheduled = false; + } + }, + + _processAnimations: function (dt) + { + this._timeDelta += dt; + while (this._timeDelta >= this._frameTime) + { + this._timeDelta -= this._frameTime; + this._step(); + } + }, + + _step: function () + { + this._showingFrame = this._currentFrame; + + if(!this.getIsAnimationRunning()) + { + this._processAnimation(); + return; + } + + if(this._sequenceDelegate) + { + var seq; + if(!this._isReversed) + { + seq = this._getSequenceByLastFrame(this._currentFrame); + } + else + { + seq = this._getSequenceByFirstFrame(this._currentFrame + 1); + } + + if (seq) + { + this._sequenceDelegate(this, seq); + } + } + if (this._isCurrentFrameLastInSequence()) + { + if(this._isLooped) + { + if(this._animationStartedNextLoopDelegate) + this._animationStartedNextLoopDelegate(this); + } + else + { + this.setAnimationRunning(false, false); + if(this._animationFinishedPlayDelegate) + this._animationFinishedPlayDelegate(this); + } + } + this._processAnimation(); + this._currentFrame = this._nextFrame(); + }, + + _isCurrentFrameLastInSequence: function() + { + if (this._isReversed) + return this._currentFrame == this._currentSequenceStart; + return this._currentFrame == this._currentSequenceEnd - 1; + }, + + _nextFrame: function() + { + if (this._isCurrentFrameLastInSequence()) + { + if (!this._isLooped) + return this._currentFrame; + + if (this._isReversed) + return this._currentSequenceEnd - 1; + else + return this._currentSequenceStart; + } + + return this._currentFrame + (this._isReversed ? -1 : 1); + }, + + _processAnimation: function () + { + //var id = this._gafproto.getId(); + this._realizeFrame(this._container, this._currentFrame); + if (this._framePlayedDelegate) + { + this._framePlayedDelegate(this, this._currentFrame); + } + }, + _realizeFrame: function(out, frameIndex) + { + var self = this; + var objects = self._objects; + var frames = self._gafproto.getFrames(); + if(frameIndex > frames.length) + { + return; + } + var currentFrame = frames[frameIndex]; + if(!currentFrame) + { + return; + } + var states = currentFrame.states; + for(var stateIdx = 0, total = states.length; stateIdx < total; ++stateIdx) + { + var state = states[stateIdx]; + var object = objects[state.objectIdRef]; + if(!object) + { + return; + } + if(state.alpha < 0) + { + object._resetState(); + } + object._updateVisibility(state, self); + if(!object.isVisible()) + { + continue; + } + object._applyState(state, self); + var parent = out; + if(state.hasMask) + { + parent = objects[state.maskObjectIdRef]._getNode(); + cc.assert(parent, "Error! Mask not found."); + } + object._lastVisibleInFrame = 1 + frameIndex; + gaf.TimeLine.rearrangeSubobject(parent, object, state.depth); + if(object._step) + { + object._step(); + } + } + }, + setAnimationRunning: function (value, recursively) + { + this._isRunning = value; + if(recursively) + { + this._objects.forEach(function (obj) + { + if (obj && obj.setAnimationRunning) + { + obj.setAnimationRunning(value, recursively); + } + }); + } + }, + + _getSequenceByLastFrame: function(){ + var sequences = this._gafproto.getSequences(); + for(var item in sequences){ + if(sequences.hasOwnProperty(item)){ + if(sequences[item].end === frame + 1) + { + return item; + } + } + } + return ""; + }, + + _resetState : function() + { + this._super(); + this._currentFrame = this._currentSequenceStart; + }, + + _getSequenceByFirstFrame: function(){ + var sequences = this._gafproto.getSequences(); + for(var item in sequences){ + if(sequences.hasOwnProperty(item)){ + if(sequences[item].start === frame) + { + return item; + } + } + } + return ""; + } +}); + +gaf.TimeLine.rearrangeSubobject = function(out, object, depth) +{ + var parent = object.getParent(); + if (parent !== out) + { + object.removeFromParent(false); + out.addChild(object, depth); + } + else + { + object.setLocalZOrder(depth); + } +}; diff --git a/external/gaf/Library/GAFTimeLineProto.js b/external/gaf/Library/GAFTimeLineProto.js new file mode 100644 index 0000000000..9d78b219d9 --- /dev/null +++ b/external/gaf/Library/GAFTimeLineProto.js @@ -0,0 +1,32 @@ + +gaf._TimeLineProto = function(asset, animationFrameCount, boundingBox, pivotPoint, id, linkageName) +{ + id = typeof id != 'undefined' ? id : 0; + linkageName = linkageName || ""; + + this._objects = []; + + this.getTotalFrames = function(){return animationFrameCount}; + this.getBoundingBox = function() {return boundingBox}; + this.getId = function() {return id}; + this.getLinkageName = function() {return linkageName}; + this.getPivot = function(){return pivotPoint}; + this.getRect = function(){return boundingBox}; + this.getNamedParts = function() {return {}}; // Map name -> id + this.getSequences = function() {return {}}; // Map name -> {start, end} + this.getFrames = function(){return []}; // Array {states, actions} + this.getFps = function(){return 60}; + this.getObjects = function(){return this._objects}; + this.getAsset = function(){return asset}; + + /* + * Will construct GAFTimeLine + */ + this._gafConstruct = function() + { + var usedScale = this.getAsset()._usedAtlasScale; + var ret = new gaf.TimeLine(this, usedScale); + ret._init(); + return ret; + }; +}; diff --git a/external/gaf/gaf_viewer.css b/external/gaf/gaf_viewer.css new file mode 100644 index 0000000000..60933161d2 --- /dev/null +++ b/external/gaf/gaf_viewer.css @@ -0,0 +1,42 @@ +#drop_zone { + border: 2px dashed #bbb; + -moz-border-radius: 5px; + -webkit-border-radius: 5px; + border-radius: 5px; + padding: 25px; + text-align: center; + font: 20pt bold 'Vollkorn'; + color: #bbb; + +} +.renderjson a { + text-decoration: none; +} +.renderjson .disclosure { + color: crimson; + font-size: 150%; +} +.renderjson .syntax { + color: grey; +} +.renderjson .string { + color: darkred; +} +.renderjson .number { + color: darkcyan; +} +.renderjson .boolean { + color: blueviolet; +} +.renderjson .key { + color: darkblue; +} +.renderjson .keyword { + color: blue; +} +.renderjson .object.syntax { + color: lightseagreen; +} +.renderjson .array.syntax { + color: orange; +} diff --git a/external/gaf/gaf_viewer.html b/external/gaf/gaf_viewer.html new file mode 100644 index 0000000000..2c66aeb05f --- /dev/null +++ b/external/gaf/gaf_viewer.html @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + +

Drop GAF here
+ + + + + + \ No newline at end of file diff --git a/external/gaf/gaf_viewer.js b/external/gaf/gaf_viewer.js new file mode 100644 index 0000000000..db5bdbea7f --- /dev/null +++ b/external/gaf/gaf_viewer.js @@ -0,0 +1,219 @@ + /* + * Created by Teivaz on 29.11.2014. + * Thanks to David Caldwell for `renderjson` + */ +function handleFileSelect(evt) { + evt.stopPropagation(); + evt.preventDefault(); + + var files = evt.dataTransfer.files; + + var output = []; + for (var i = 0, f; f = files[i]; i++) { + var name = escape(f.name); + var ext = name.split('.').pop(); + if (ext == 'gaf') { + var reader = new FileReader(); + reader.onload = (function(theFile) { + return function(req) { + var arrayBuffer = new gaf.DataReader(req.target.result); + var loader = new gaf.Loader(); + var data = loader.LoadStream(arrayBuffer); + document.getElementById('list').appendChild(renderjson(data)); + }; + })(f); + reader.readAsArrayBuffer(f); + } + } +} + +function handleDragOver(evt) { + evt.stopPropagation(); + evt.preventDefault(); + evt.dataTransfer.dropEffect = 'copy'; +} + +var dropZone = document.getElementById('drop_zone'); +dropZone.addEventListener('dragover', handleDragOver, false); +dropZone.addEventListener('drop', handleFileSelect, false); + +var module; +(module || {}).exports = renderjson = (function() { + var themetext = function( /* [class, text]+ */ ) { + var spans = []; + while (arguments.length) + spans.push(append(span(Array.prototype.shift.call(arguments)), + text(Array.prototype.shift.call(arguments)))); + return spans; + }; + var append = function( /* el, ... */ ) { + var el = Array.prototype.shift.call(arguments); + for (var a = 0; a < arguments.length; a++) + if (arguments[a].constructor == Array) + append.apply(this, [el].concat(arguments[a])); + else + el.appendChild(arguments[a]); + return el; + }; + var prepend = function(el, child) { + el.insertBefore(child, el.firstChild); + return el; + }; + var isempty = function(obj) { + for (var k in obj) + if (obj.hasOwnProperty(k)) return false; + return true; + }; + var text = function(txt) { + return document.createTextNode(txt) + }; + var div = function() { + return document.createElement("div") + }; + var span = function(classname) { + var s = document.createElement("span"); + if (classname) s.className = classname; + return s; + }; + var A = function A(txt, classname, callback) { + var a = document.createElement("a"); + if (classname) a.className = classname; + a.appendChild(text(txt)); + a.href = '#'; + a.onclick = function() { + callback(); + return false; + }; + return a; + }; + + function _renderjson(json, indent, dont_indent, show_level, sort_objects) { + var my_indent = dont_indent ? "" : indent; + + if (json === null) return themetext(null, my_indent, "keyword", "null"); + if (json === void 0) return themetext(null, my_indent, "keyword", "undefined"); + if (typeof(json) != "object") // Strings, numbers and bools + return themetext(null, my_indent, typeof(json), JSON.stringify(json)); + + var disclosure = function(open, close, type, builder) { + var content; + var empty = span(type); + var show = function() { + if (!content) append(empty.parentNode, + content = prepend(builder(), + A(renderjson.hide, "disclosure", + function() { + content.style.display = "none"; + empty.style.display = "inline"; + }))); + content.style.display = "inline"; + empty.style.display = "none"; + }; + + function isColor(a){ + return a.hasOwnProperty('a') && a.hasOwnProperty('r') && a.hasOwnProperty('g') && a.hasOwnProperty('b'); + } + + var color_rect = span(); + if (json.hasOwnProperty("tagName")) + var placeholder = json.tagName; + else if (json.hasOwnProperty("header")) + placeholder = " GAF v" + json.header.versionMajor + "." + json.header.versionMinor + " "; + else if (json.constructor == Array) + placeholder = " " + json.length + " "; + else if (json.hasOwnProperty("id")) + placeholder = " id:" + json.id + " ... "; + else if (json.hasOwnProperty("objectId")) + placeholder = " id:" + json.objectId + " ... "; + else if (json.hasOwnProperty("frame")) + placeholder = " frame:" + json.frame + " ... "; + else if(isColor(json)){ + color_rect.style.backgroundColor = "rgba("+json.r+","+json.g+","+json.b+","+json.a / 255.0+")";// parseInt(json.r).toString(16) + parseInt(json.g).toString(16) + parseInt(json.b).toString(16); + color_rect.style.height = '10px'; + color_rect.style.width = '10px'; + color_rect.style.display = 'inline-block'; + color_rect.style.margin = '0 4px'; + color_rect.style.border = '1px solid #7f7f7f'; + } + + placeholder = placeholder || ' ... '; + append(empty, + A(renderjson.show, "disclosure", show), + color_rect, + themetext(type + " syntax", open), + A(placeholder, null, show), + themetext(type + " syntax", close)); + + var el = append(span(), text(my_indent.slice(0, -1)), empty); + if (show_level > 0) + show(); + return el; + }; + + if (json.constructor == Array) { + if (json.length == 0) return themetext(null, my_indent, "array syntax", "[]"); + + return disclosure("[", "]", "array", function() { + var as = append(span("array"), themetext("array syntax", "[", null, "\n")); + for (var i = 0; i < json.length; i++) + append(as, + _renderjson(json[i], indent + " ", false, show_level - 1, sort_objects), + i != json.length - 1 ? themetext("syntax", ",") : [], + text("\n")); + append(as, themetext(null, indent, "array syntax", "]")); + return as; + }); + } + + // object + if (isempty(json)) + return themetext(null, my_indent, "object syntax", "{}"); + + + return disclosure("{", "}", "object", function() { + var os = append(span("object"), themetext("object syntax", "{", null, "\n")); + for (var k in json) var last = k; + var keys = Object.keys(json); + if (sort_objects) + keys = keys.sort(); + for (var i in keys) { + var k = keys[i]; + append(os, themetext(null, indent + " ", "key", '"' + k + '"', "object syntax", ': '), + _renderjson(json[k], indent + " ", true, show_level - 1, sort_objects), + k != last ? themetext("syntax", ",") : [], + text("\n")); + } + append(os, themetext(null, indent, "object syntax", "}")); + return os; + }); + } + + var renderjson = function renderjson(json) { + var pre = append(document.createElement("pre"), _renderjson(json, "", false, renderjson.show_to_level, renderjson.sort_objects)); + pre.className = "renderjson"; + return pre; + }; + renderjson.set_icons = function(show, hide) { + renderjson.show = show; + renderjson.hide = hide; + return renderjson; + }; + renderjson.set_show_to_level = function(level) { + renderjson.show_to_level = typeof level == "string" && + level.toLowerCase() === "all" ? Number.MAX_VALUE : level; + return renderjson; + }; + renderjson.set_sort_objects = function(sort_bool) { + renderjson.sort_objects = sort_bool; + return renderjson; + }; + // Backwards compatiblity. Use set_show_to_level() for new code. + renderjson.set_show_by_default = function(show) { + renderjson.show_to_level = show ? Number.MAX_VALUE : 0; + return renderjson; + }; + renderjson.set_icons('⊕', '⊖'); + renderjson.set_show_by_default(false); + renderjson.set_sort_objects(false); + return renderjson; +})(); \ No newline at end of file diff --git a/moduleConfig.json b/moduleConfig.json index 0419870439..a089e198d8 100644 --- a/moduleConfig.json +++ b/moduleConfig.json @@ -432,6 +432,30 @@ "extensions/spine/CCSkeletonCanvasRenderCmd.js", "extensions/spine/CCSkeletonWebGLRenderCmd.js" ], + "gaf":[ + "core", + + "external/gaf/GAFMacros.js", + "external/gaf/GAFBoot.js", + "external/gaf/Library/GAFAssetPreload.js", + "external/gaf/Library/GAFAsset.js", + "external/gaf/Library/GAFObject.js", + "external/gaf/Library/GAFTimeLine.js", + "external/gaf/Library/GAFTextField.js", + "external/gaf/Library/GAFSprite.js", + "external/gaf/Library/GAFMask.js", + "external/gaf/Library/GAFSpriteCanvasRenderCmd.js", + "external/gaf/Library/GAFSpriteWebGLRenderCmd.js", + "external/gaf/Library/GAFTimeLineProto.js", + "external/gaf/Library/GAFSpriteProto.js", + "external/gaf/Library/GAFMaskProto.js", + "external/gaf/Library/GAFTags.js", + "external/gaf/Library/GAFLoader.js", + "external/gaf/Library/GAFDataReader.js", + "external/gaf/Library/GAFShaders.js", + "external/gaf/Library/GAFShaderManager.js", + "external/gaf/Library/GAFAtlasLoader.js" + ], "extensions" : ["gui", "ccbreader", "editbox", "cocostudio", "spine", "ccpool"], "box2d" : [ @@ -447,7 +471,7 @@ "socketio" : [ "external/socketio/socket.io.min.js" ], - "external" : ["box2d", "chipmunk", "socketio", "pluginx"] + "external" : ["box2d", "chipmunk", "socketio", "pluginx", "gaf"] }, "bootFile" : "CCBoot.js" } \ No newline at end of file From cc90c2a13e94fb758862dc3d3dde43efde846aa0 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 24 Apr 2015 16:20:21 +0800 Subject: [PATCH 0188/1039] Fixed a bug that resume audio error --- cocos2d/audio/CCAudio.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index 4a8296e365..e3890afd59 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -280,7 +280,7 @@ cc.Audio = cc.Class.extend({ audio["connect"](this._volume); audio.loop = this.loop; this._startTime = this._context.currentTime; - this._currentTime = 0; + this._currentTime = offset || 0; /* * Safari on iOS 6 only supports noteOn(), noteGrainOn(), and noteOff() now.(iOS 6.1.3) From 6a9327c2734ea5b6627ccc8d775edf0237b77eb3 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 24 Apr 2015 17:03:59 +0800 Subject: [PATCH 0189/1039] To fix a bug about the Sprite set texture cann't update contentsize --- cocos2d/core/sprites/CCSprite.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/cocos2d/core/sprites/CCSprite.js b/cocos2d/core/sprites/CCSprite.js index cf138f0633..7dd5fede71 100644 --- a/cocos2d/core/sprites/CCSprite.js +++ b/cocos2d/core/sprites/CCSprite.js @@ -962,8 +962,6 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ _changeRectWithTexture: function(rect){ if(!rect || (!rect.width && !rect.height)) return; - var textureRect = this.getTextureRect(); - if(textureRect.height || textureRect.width) return; rect.x = rect.x || 0; rect.y = rect.y || 0; rect.width = rect.width || 0; From 3d0f26a33e573386b759012c3af15ad48f649888 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 24 Apr 2015 17:39:42 +0800 Subject: [PATCH 0190/1039] To fix a bug about the Sprite set texture cann't update contentsize --- cocos2d/core/sprites/CCSprite.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cocos2d/core/sprites/CCSprite.js b/cocos2d/core/sprites/CCSprite.js index 7dd5fede71..cf138f0633 100644 --- a/cocos2d/core/sprites/CCSprite.js +++ b/cocos2d/core/sprites/CCSprite.js @@ -962,6 +962,8 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ _changeRectWithTexture: function(rect){ if(!rect || (!rect.width && !rect.height)) return; + var textureRect = this.getTextureRect(); + if(textureRect.height || textureRect.width) return; rect.x = rect.x || 0; rect.y = rect.y || 0; rect.width = rect.width || 0; From 4fd5b40015787ca335aca2582a38bedebf94343d Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 24 Apr 2015 18:03:38 +0800 Subject: [PATCH 0191/1039] To fix a bug about the Sprite set texture cann't update contentsize --- cocos2d/core/sprites/CCSprite.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/cocos2d/core/sprites/CCSprite.js b/cocos2d/core/sprites/CCSprite.js index cf138f0633..b6662b3455 100644 --- a/cocos2d/core/sprites/CCSprite.js +++ b/cocos2d/core/sprites/CCSprite.js @@ -941,12 +941,14 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ if(!texture._textureLoaded){ texture.addEventListener("load", function(){ + this._clearRect(); this._renderCmd._setTexture(texture); this._changeRectWithTexture(texture.getContentSize()); this.setColor(this._realColor); this._textureLoaded = true; }, this); }else{ + this._clearRect(); this._renderCmd._setTexture(texture); this._changeRectWithTexture(texture.getContentSize()); this.setColor(this._realColor); @@ -955,11 +957,25 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ }else{ // CCSprite: setTexture doesn't work when the sprite is rendered using a CCSpriteSheet cc.assert(texture instanceof cc.Texture2D, cc._LogInfos.Sprite_setTexture_2); + this._clearRect(); this._changeRectWithTexture(texture.getContentSize()); this._renderCmd._setTexture(texture); } }, + _clearRect: function(){ + var texture = this._texture; + if(texture){ + var textureRect = texture._contentSize; + var spriteRect = this._rect; + if( + textureRect.width === spriteRect.width && + textureRect.height === spriteRect.height + ) + spriteRect.width = spriteRect.height = 0; + } + }, + _changeRectWithTexture: function(rect){ if(!rect || (!rect.width && !rect.height)) return; var textureRect = this.getTextureRect(); From 6f46817c467085bae801e86be4dec1a1a716b438 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Sun, 26 Apr 2015 08:50:43 +0800 Subject: [PATCH 0192/1039] Fixed Scale9Sprite's children doesn't get transformed recursively --- extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js | 2 +- .../gui/control-extension/CCScale9SpriteCanvasRenderCmd.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js index ceab4aeb03..33dca3d05a 100644 --- a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js +++ b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js @@ -73,7 +73,7 @@ var children = node._children; for(var i=0; i Date: Sun, 26 Apr 2015 16:17:30 +0800 Subject: [PATCH 0193/1039] Fixed cocos2d/cocos2d-js#1703: Fix constants naming issue for ccs.FrameEaseType --- extensions/cocostudio/action/CCActionFrame.js | 130 +++++++++--------- extensions/cocostudio/timeline/Frame.js | 2 +- 2 files changed, 66 insertions(+), 66 deletions(-) diff --git a/extensions/cocostudio/action/CCActionFrame.js b/extensions/cocostudio/action/CCActionFrame.js index 755cbbd578..2571031de9 100644 --- a/extensions/cocostudio/action/CCActionFrame.js +++ b/extensions/cocostudio/action/CCActionFrame.js @@ -67,49 +67,49 @@ ccs.FRAME_TYPE_MAX = 5; * @type {Object} */ ccs.FrameEaseType = { - Custom : -1, + CUSTOM : -1, - Linear : 0, + LINEAR : 0, - Sine_EaseIn : 1, - Sine_EaseOut : 2, - Sine_EaseInOut : 3, + SINE_EASEIN : 1, + SINE_EASEOUT : 2, + SINE_EASEINOUT : 3, - Quad_EaseIn : 4, - Quad_EaseOut : 5, - Quad_EaseInOut : 6, + QUAD_EASEIN : 4, + QUAD_EASEOUT : 5, + QUAD_EASEINOUT : 6, - Cubic_EaseIn : 7, - Cubic_EaseOut : 8, - Cubic_EaseInOut : 9, + CUBIC_EASEIN : 7, + CUBIC_EASEOUT : 8, + CUBIC_EASEINOUT : 9, - Quart_EaseIn : 10, - Quart_EaseOut : 11, - Quart_EaseInOut : 12, + QUART_EASEIN : 10, + QUART_EASEOUT : 11, + QUART_EASEINOUT : 12, - Quint_EaseIn : 13, - Quint_EaseOut : 14, - Quint_EaseInOut : 15, + QUINT_EASEIN : 13, + QUINT_EASEOUT : 14, + QUINT_EASEINOUT : 15, - Expo_EaseIn : 16, - Expo_EaseOut : 17, - Expo_EaseInOut : 18, + EXPO_EASEIN : 16, + EXPO_EASEOUT : 17, + EXPO_EASEINOUT : 18, - Circ_EaseIn : 19, - Circ_EaseOut : 20, - Circ_EaseInOut : 21, + CIRC_EASEIN : 19, + CIRC_EASEOUT : 20, + CIRC_EASEINOUT : 21, - Elastic_EaseIn : 22, - Elastic_EaseOut : 23, - Elastic_EaseInOut : 24, + ELASTIC_EASEIN : 22, + ELASTIC_EASEOUT : 23, + ELASTIC_EASEINOUT : 24, - Back_EaseIn : 25, - Back_EaseOut : 26, - Back_EaseInOut : 27, + BACK_EASEIN : 25, + BACK_EASEOUT : 26, + BACK_EASEINOUT : 27, - Bounce_EaseIn : 28, - Bounce_EaseOut : 29, - Bounce_EaseInOut : 30, + BOUNCE_EASEIN : 28, + BOUNCE_EASEOUT : 29, + BOUNCE_EASEINOUT : 30, TWEEN_EASING_MAX: 1000 }; @@ -137,7 +137,7 @@ ccs.ActionFrame = ccs.Class.extend(/** @lends ccs.ActionFrame# */{ */ ctor: function () { this.frameType = 0; - this.easingType = ccs.FrameEaseType.Linear; + this.easingType = ccs.FrameEaseType.LINEAR; this.frameIndex = 0; this.time = 0; }, @@ -161,99 +161,99 @@ ccs.ActionFrame = ccs.Class.extend(/** @lends ccs.ActionFrame# */{ var resultAction; switch (this.easingType) { - case ccs.FrameEaseType.Custom: + case ccs.FrameEaseType.CUSTOM: break; - case ccs.FrameEaseType.Linear: + case ccs.FrameEaseType.LINEAR: resultAction = action; break; - case ccs.FrameEaseType.Sine_EaseIn: + case ccs.FrameEaseType.SINE_EASEIN: resultAction = action.easing(cc.easeSineIn()); break; - case ccs.FrameEaseType.Sine_EaseOut: + case ccs.FrameEaseType.SINE_EASEOUT: resultAction = action.easing(cc.easeSineOut()); break; - case ccs.FrameEaseType.Sine_EaseInOut: + case ccs.FrameEaseType.SINE_EASEINOUT: resultAction = action.easing(cc.easeSineInOut()); break; - case ccs.FrameEaseType.Quad_EaseIn: + case ccs.FrameEaseType.QUAD_EASEIN: resultAction = action.easing(cc.easeQuadraticActionIn()); break; - case ccs.FrameEaseType.Quad_EaseOut: + case ccs.FrameEaseType.QUAD_EASEOUT: resultAction = action.easing(cc.easeQuadraticActionOut()); break; - case ccs.FrameEaseType.Quad_EaseInOut: + case ccs.FrameEaseType.QUAD_EASEINOUT: resultAction = action.easing(cc.easeQuadraticActionInOut()); break; - case ccs.FrameEaseType.Cubic_EaseIn: + case ccs.FrameEaseType.CUBIC_EASEIN: resultAction = action.easing(cc.easeCubicActionIn()); break; - case ccs.FrameEaseType.Cubic_EaseOut: + case ccs.FrameEaseType.CUBIC_EASEOUT: resultAction = action.easing(cc.easeCubicActionOut()); break; - case ccs.FrameEaseType.Cubic_EaseInOut: + case ccs.FrameEaseType.CUBIC_EASEINOUT: resultAction = action.easing(cc.easeCubicActionInOut()); break; - case ccs.FrameEaseType.Quart_EaseIn: + case ccs.FrameEaseType.QUART_EASEIN: resultAction = action.easing(cc.easeQuarticActionIn()); break; - case ccs.FrameEaseType.Quart_EaseOut: + case ccs.FrameEaseType.QUART_EASEOUT: resultAction = action.easing(cc.easeQuarticActionOut()); break; - case ccs.FrameEaseType.Quart_EaseInOut: + case ccs.FrameEaseType.QUART_EASEINOUT: resultAction = action.easing(cc.easeQuarticActionInOut()); break; - case ccs.FrameEaseType.Quint_EaseIn: + case ccs.FrameEaseType.QUINT_EASEIN: resultAction = action.easing(cc.easeQuinticActionIn()); break; - case ccs.FrameEaseType.Quint_EaseOut: + case ccs.FrameEaseType.QUINT_EASEOUT: resultAction = action.easing(cc.easeQuinticActionOut()); break; - case ccs.FrameEaseType.Quint_EaseInOut: + case ccs.FrameEaseType.QUINT_EASEINOUT: resultAction = action.easing(cc.easeQuinticActionInOut()); break; - case ccs.FrameEaseType.Expo_EaseIn: + case ccs.FrameEaseType.EXPO_EASEIN: resultAction = action.easing(cc.easeExponentialIn()); break; - case ccs.FrameEaseType.Expo_EaseOut: + case ccs.FrameEaseType.EXPO_EASEOUT: resultAction = action.easing(cc.easeExponentialOut()); break; - case ccs.FrameEaseType.Expo_EaseInOut: + case ccs.FrameEaseType.EXPO_EASEINOUT: resultAction = action.easing(cc.easeExponentialInOut()); break; - case ccs.FrameEaseType.Circ_EaseIn: + case ccs.FrameEaseType.CIRC_EASEIN: resultAction = action.easing(cc.easeCircleActionIn()); break; - case ccs.FrameEaseType.Circ_EaseOut: + case ccs.FrameEaseType.CIRC_EASEOUT: resultAction = action.easing(cc.easeCircleActionOut()); break; - case ccs.FrameEaseType.Circ_EaseInOut: + case ccs.FrameEaseType.CIRC_EASEINOUT: resultAction = action.easing(cc.easeCircleActionInOut()); break; - case ccs.FrameEaseType.Elastic_EaseIn: + case ccs.FrameEaseType.ELASTIC_EASEIN: resultAction = action.easing(cc.easeElasticIn()); break; - case ccs.FrameEaseType.Elastic_EaseOut: + case ccs.FrameEaseType.ELASTIC_EASEOUT: resultAction = action.easing(cc.easeElasticOut()); break; - case ccs.FrameEaseType.Elastic_EaseInOut: + case ccs.FrameEaseType.ELASTIC_EASEINOUT: resultAction = action.easing(cc.easeElasticInOut()); break; - case ccs.FrameEaseType.Back_EaseIn: + case ccs.FrameEaseType.BACK_EASEIN: resultAction = action.easing(cc.easeBackIn()); break; - case ccs.FrameEaseType.Back_EaseOut: + case ccs.FrameEaseType.BACK_EASEOUT: resultAction = action.easing(cc.easeBackOut()); break; - case ccs.FrameEaseType.Back_EaseInOut: + case ccs.FrameEaseType.BACK_EASEINOUT: resultAction = action.easing(cc.easeBackInOut()); break; - case ccs.FrameEaseType.Bounce_EaseIn: + case ccs.FrameEaseType.BOUNCE_EASEIN: resultAction = action.easing(cc.easeBounceIn()); break; - case ccs.FrameEaseType.Bounce_EaseOut: + case ccs.FrameEaseType.BOUNCE_EASEOUT: resultAction = action.easing(cc.easeBounceOut()); break; - case ccs.FrameEaseType.Bounce_EaseInOut: + case ccs.FrameEaseType.BOUNCE_EASEINOUT: resultAction = action.easing(cc.easeBounceInOut()); break; } diff --git a/extensions/cocostudio/timeline/Frame.js b/extensions/cocostudio/timeline/Frame.js index bcc155c22b..f165d5686f 100644 --- a/extensions/cocostudio/timeline/Frame.js +++ b/extensions/cocostudio/timeline/Frame.js @@ -138,7 +138,7 @@ ccs.Frame = ccs.Class.extend({ apply: function(percent){ if(!this._tween) return; - if(this._tweenType !== ccs.FrameEaseType.TWEEN_EASING_MAX && this._tweenType !== ccs.FrameEaseType.Linear) + if(this._tweenType !== ccs.FrameEaseType.TWEEN_EASING_MAX && this._tweenType !== ccs.FrameEaseType.LINEAR) percent = this.tweenPercent(percent); this._onApply(percent); }, From 50e470d1746db184396c7663e2930d84c52b624f Mon Sep 17 00:00:00 2001 From: pandamicro Date: Sun, 26 Apr 2015 16:28:53 +0800 Subject: [PATCH 0194/1039] Fixed cocos2d/cocos2d-js#1650: cc.LoaderScene.preload API inconsistency --- cocos2d/core/scenes/CCLoaderScene.js | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/cocos2d/core/scenes/CCLoaderScene.js b/cocos2d/core/scenes/CCLoaderScene.js index 51417498c3..562b71ff30 100644 --- a/cocos2d/core/scenes/CCLoaderScene.js +++ b/cocos2d/core/scenes/CCLoaderScene.js @@ -34,6 +34,8 @@ cc.LoaderScene = cc.Scene.extend({ _interval : null, _label : null, _className:"LoaderScene", + cb: null, + target: null, /** * Contructor of cc.LoaderScene * @returns {boolean} @@ -101,12 +103,14 @@ cc.LoaderScene = cc.Scene.extend({ * init with resources * @param {Array} resources * @param {Function|String} cb + * @param {Object} target */ - initWithResources: function (resources, cb) { + initWithResources: function (resources, cb, target) { if(cc.isString(resources)) resources = [resources]; this.resources = resources || []; this.cb = cb; + this.target = target; }, _startLoading: function () { @@ -120,7 +124,7 @@ cc.LoaderScene = cc.Scene.extend({ self._label.setString("Loading... " + percent + "%"); }, function () { if (self.cb) - self.cb(); + self.cb.call(self.target); }); } }); @@ -129,6 +133,7 @@ cc.LoaderScene = cc.Scene.extend({ *

when all the resource are downloaded it will invoke call function

* @param resources * @param cb + * @param target * @returns {cc.LoaderScene|*} * @example * //Example @@ -136,13 +141,13 @@ cc.LoaderScene = cc.Scene.extend({ cc.director.runScene(new HelloWorldScene()); }, this); */ -cc.LoaderScene.preload = function(resources, cb){ +cc.LoaderScene.preload = function(resources, cb, target){ var _cc = cc; if(!_cc.loaderScene) { _cc.loaderScene = new cc.LoaderScene(); _cc.loaderScene.init(); } - _cc.loaderScene.initWithResources(resources, cb); + _cc.loaderScene.initWithResources(resources, cb, target); cc.director.runScene(_cc.loaderScene); return _cc.loaderScene; From 71ddb495a1df838c8d747b7488d2a00c51cc74eb Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 27 Apr 2015 09:41:37 +0800 Subject: [PATCH 0195/1039] Fixed a bug that is Frame InnerActionFrame error --- .../cocostudio/timeline/ActionTimeline.js | 8 ++++++++ extensions/cocostudio/timeline/Frame.js | 18 +++++++++--------- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/extensions/cocostudio/timeline/ActionTimeline.js b/extensions/cocostudio/timeline/ActionTimeline.js index 3712238878..1b1348c2c4 100644 --- a/extensions/cocostudio/timeline/ActionTimeline.js +++ b/extensions/cocostudio/timeline/ActionTimeline.js @@ -484,6 +484,14 @@ ccs.ActionTimeline = cc.Action.extend({ */ removeAnimationInfo: function(name){ delete this._animationInfos[name]; + }, + + IsAnimationInfoExists: function(name){ + return this._animationInfos[name]; + }, + + getAnimationInfo: function(name){ + return this._animationInfos[name]; } }); diff --git a/extensions/cocostudio/timeline/Frame.js b/extensions/cocostudio/timeline/Frame.js index bcc155c22b..818ef18bb9 100644 --- a/extensions/cocostudio/timeline/Frame.js +++ b/extensions/cocostudio/timeline/Frame.js @@ -976,12 +976,13 @@ ccs.InnerActionFrame = ccs.Frame.extend({ _endFrameIndex:0, _singleFrameIndex: 0, - _enterWithName: false, + _enterWithName: null, _animationName: "", ctor: function(){ ccs.Frame.prototype.ctor.call(this); + this._enterWithName = false; this._innerActionType = ccs.InnerActionType.LoopAction; this._startFrameIndex = 0; }, @@ -991,10 +992,10 @@ ccs.InnerActionFrame = ccs.Frame.extend({ * @param {ccs.Frame} nextFrame */ onEnter: function(nextFrame){ - if(!this._node) - return; + if(!this._node) return; var innerActiontimeline = this._node.getActionByTag(this._node.getTag()); - if (/*ccs.InnerActionType.SingleFrame*/"SingleFrame" === this._innerActionType){ + if(!innerActiontimeline) return; + if (ccs.InnerActionType.SingleFrame === this._innerActionType){ innerActiontimeline.gotoFrameAndPause(this._singleFrameIndex); return; } @@ -1028,11 +1029,7 @@ ccs.InnerActionFrame = ccs.Frame.extend({ }, setAnimationName: function(animationName){ - if(!this._enterWithName){ - cc.log(" cannot set aniamtioname when enter frame with index. setEnterWithName true firstly!"); - }else{ - this._animationName = animationName; - } + this._animationName = animationName; }, setSingleFrameIndex: function(frameIndex){ @@ -1060,6 +1057,9 @@ ccs.InnerActionFrame = ccs.Frame.extend({ var frame = new ccs.InnerActionFrame(); frame.setInnerActionType(this._innerActionType); frame.setStartFrameIndex(this._startFrameIndex); + frame.setEnterWithName(this._enterWithName); + frame.setAnimationName(this._animationName); + frame.setSingleFrameIndex(this._singleFrameIndex); frame._cloneProperty(this); From 35a6b0fee0151baa9b83f5cb0371ebf805227f40 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 27 Apr 2015 09:55:07 +0800 Subject: [PATCH 0196/1039] Fixed a bug that is Frame InnerActionFrame error --- extensions/cocostudio/timeline/ActionTimeline.js | 2 +- extensions/cocostudio/timeline/Frame.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/cocostudio/timeline/ActionTimeline.js b/extensions/cocostudio/timeline/ActionTimeline.js index 1b1348c2c4..75aecd0415 100644 --- a/extensions/cocostudio/timeline/ActionTimeline.js +++ b/extensions/cocostudio/timeline/ActionTimeline.js @@ -486,7 +486,7 @@ ccs.ActionTimeline = cc.Action.extend({ delete this._animationInfos[name]; }, - IsAnimationInfoExists: function(name){ + isAnimationInfoExists: function(name){ return this._animationInfos[name]; }, diff --git a/extensions/cocostudio/timeline/Frame.js b/extensions/cocostudio/timeline/Frame.js index 818ef18bb9..58910b7ffd 100644 --- a/extensions/cocostudio/timeline/Frame.js +++ b/extensions/cocostudio/timeline/Frame.js @@ -1006,7 +1006,7 @@ ccs.InnerActionFrame = ccs.Frame.extend({ if (this._animationName === "-- ALL --"){ innerStart = 0; innerEnd = innerActiontimeline.getDuration(); - } else if(innerActiontimeline.IsAnimationInfoExists(this._animationName)) { + } else if(innerActiontimeline.isAnimationInfoExists(this._animationName)) { var info = innerActiontimeline.getAnimationInfo(this._animationName); innerStart = info.startIndex; innerEnd = info.endIndex; From 6a88df5b875f51b6e729a7879ffbe3319e8c541c Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 27 Apr 2015 10:28:41 +0800 Subject: [PATCH 0197/1039] To fix a bug on the slider within the scaleX may be not 1 --- extensions/ccui/uiwidgets/UISlider.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/ccui/uiwidgets/UISlider.js b/extensions/ccui/uiwidgets/UISlider.js index 3eed1abe54..5b1f8f38b4 100644 --- a/extensions/ccui/uiwidgets/UISlider.js +++ b/extensions/ccui/uiwidgets/UISlider.js @@ -458,7 +458,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ var spriteRenderer = this._progressBarRenderer; var rect = spriteRenderer.getTextureRect(); spriteRenderer.setTextureRect( - cc.rect(rect.x, rect.y, dis, rect.height), + cc.rect(rect.x, rect.y, dis / spriteRenderer._scaleX, rect.height), spriteRenderer.isTextureRectRotated() ); } From 0bef4ccbafd479c8d5c755989cc2a8186b2a6b4d Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 27 Apr 2015 11:07:24 +0800 Subject: [PATCH 0198/1039] To fix a problem about the UIButton after enable scale9sprite --- extensions/ccui/uiwidgets/UIButton.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/extensions/ccui/uiwidgets/UIButton.js b/extensions/ccui/uiwidgets/UIButton.js index 3ee086fbbc..3d6a21103d 100644 --- a/extensions/ccui/uiwidgets/UIButton.js +++ b/extensions/ccui/uiwidgets/UIButton.js @@ -437,11 +437,11 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ var x = capInsets.x, y = capInsets.y; var width = capInsets.width, height = capInsets.height; - if (this._normalTextureSize.width < width) { + if (this._pressedTextureSize.width < width) { x = 0; width = 0; } - if (this._normalTextureSize.height < height) { + if (this._pressedTextureSize.height < height) { y = 0; height = 0; } @@ -474,11 +474,11 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ var x = capInsets.x, y = capInsets.y; var width = capInsets.width, height = capInsets.height; - if (this._normalTextureSize.width < width) { + if (this._disabledTextureSize.width < width) { x = 0; width = 0; } - if (this._normalTextureSize.height < height) { + if (this._disabledTextureSize.height < height) { y = 0; height = 0; } From 5481fb10064378da18d6c8c0470b9d8489d01e8d Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 27 Apr 2015 11:54:39 +0800 Subject: [PATCH 0199/1039] Fixed a bug that is UIText set ContentSize --- .../cocostudio/loader/parsers/timelineParser-2.x.js | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 954b036d89..ee015658ee 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -238,14 +238,14 @@ // WIDGET // //////////// - parser.widgetAttributes = function (widget, json) { + parser.widgetAttributes = function (widget, json, enableContent) { widget.setCascadeColorEnabled(true); widget.setCascadeOpacityEnabled(true); widget.setUnifySizeEnabled(false); //widget.setLayoutComponentEnabled(true); widget.ignoreContentAdaptWithSize(false); - setContentSize(widget, json["Size"]); + !enableContent && setContentSize(widget, json["Size"]); var name = json["Name"]; if (name) @@ -476,8 +476,6 @@ var widget = new ccui.Text(); - this.widgetAttributes(widget, json); - var touchScaleEnabled = json["TouchScaleChangeAble"]; if(touchScaleEnabled != null) widget.setTouchScaleChangeEnabled(touchScaleEnabled); @@ -554,8 +552,7 @@ widget.setUnifySizeEnabled(false); - if(widget.isIgnoreContentAdaptWithSize()) - setContentSize(widget, json["Size"]); + this.widgetAttributes(widget, json, widget.isIgnoreContentAdaptWithSize()); return widget; From d0f21d3508fa038e8a7db236d201ec105d2d5097 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 27 Apr 2015 14:14:16 +0800 Subject: [PATCH 0200/1039] Repair the button can't set the Outline --- .../cocostudio/loader/parsers/timelineParser-2.x.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index ee015658ee..e1dec00399 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -625,8 +625,12 @@ json["ShadowBlurRadius"] || 0 ); } - if(label && json["OutlineEnabled"] && json["OutlineColor"] && label.enableOutline) - label.enableOutline(getColor(json["OutlineColor"]), getParam(json["OutlineSize"], 1)); + if(label && json["OutlineEnabled"] && json["OutlineColor"]){ + if(label.enableOutline) + label.enableOutline(getColor(json["OutlineColor"]), getParam(json["OutlineSize"], 1)); + if(label.enableStroke) + label.enableStroke(getColor(json["OutlineColor"]), getParam(json["OutlineSize"], 1)); + } this.widgetAttributes(widget, json); From 481fd2b08e075f2a7c4de70eb25acc83d43a5253 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 27 Apr 2015 14:17:31 +0800 Subject: [PATCH 0201/1039] [v3.6] Update engine version --- cocos2d/core/platform/CCConfig.js | 2 +- tools/build.xml | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/cocos2d/core/platform/CCConfig.js b/cocos2d/core/platform/CCConfig.js index ead1460436..d22450daad 100644 --- a/cocos2d/core/platform/CCConfig.js +++ b/cocos2d/core/platform/CCConfig.js @@ -31,7 +31,7 @@ * @type {String} * @name cc.ENGINE_VERSION */ -window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.6 Beta"; +window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.6"; /** *

diff --git a/tools/build.xml b/tools/build.xml index 8c05c73ab9..326af567d2 100644 --- a/tools/build.xml +++ b/tools/build.xml @@ -5,8 +5,8 @@ classpath="./compiler/compiler.jar"/> - + debug="false" output="./../lib/cocos2d-js-v3.6-min.js"> + @@ -298,8 +298,8 @@ - + debug="false" output="./../lib/cocos2d-js-v3.6-core-min.js"> + From 7617f3195b1a1d47cbdbebcad750c6858becb9c5 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 27 Apr 2015 14:33:11 +0800 Subject: [PATCH 0202/1039] Repair the button can't set the Outline --- extensions/cocostudio/loader/parsers/timelineParser-2.x.js | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index e1dec00399..fa9809dd5d 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -625,12 +625,8 @@ json["ShadowBlurRadius"] || 0 ); } - if(label && json["OutlineEnabled"] && json["OutlineColor"]){ - if(label.enableOutline) - label.enableOutline(getColor(json["OutlineColor"]), getParam(json["OutlineSize"], 1)); - if(label.enableStroke) + if(label && json["OutlineEnabled"] && json["OutlineColor"] && label.enableStroke) label.enableStroke(getColor(json["OutlineColor"]), getParam(json["OutlineSize"], 1)); - } this.widgetAttributes(widget, json); From ba26ad0f4260e505155ce012ea5916d5d8155177 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 27 Apr 2015 14:34:24 +0800 Subject: [PATCH 0203/1039] Repair the button can't set the Outline --- extensions/cocostudio/loader/parsers/timelineParser-2.x.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index fa9809dd5d..12e26f4c5b 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -626,7 +626,7 @@ ); } if(label && json["OutlineEnabled"] && json["OutlineColor"] && label.enableStroke) - label.enableStroke(getColor(json["OutlineColor"]), getParam(json["OutlineSize"], 1)); + label.enableStroke(getColor(json["OutlineColor"]), getParam(json["OutlineSize"], 1)); this.widgetAttributes(widget, json); From 5ca3365697034421cd662ed07869d330343c8721 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 27 Apr 2015 16:26:02 +0800 Subject: [PATCH 0204/1039] Fix the background color set wrong --- .../loader/parsers/timelineParser-2.x.js | 81 ++++++------------- 1 file changed, 26 insertions(+), 55 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 12e26f4c5b..e6c2a4bbe8 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -401,6 +401,23 @@ layoutComponent.setRightMargin(rightMargin); }; + var setLayoutBackground = function(layout, single, first, end){ + if( layout.getBackGroundColorType() === 2 ){ + first = first || {}; + end = end || {}; + layout.setBackGroundColor(getColor(first), getColor(end)); + }else{ + single = single || {}; + layout.setBackGroundColor(getColor(single)); + } + }; + + var setLayoutBackgroundVector = function(widget, vector){ + var x = vector["ScaleX"] || 0; + var y = vector["ScaleY"] || 0; + widget.setBackGroundColorVector(cc.p(x, y)); + }; + /** * Layout * @param json @@ -453,16 +470,8 @@ } - var firstColor = json["FirstColor"]; - var endColor = json["EndColor"]; - if(endColor["R"] != null && endColor["G"] != null && endColor["B"] != null) - widget.setBackGroundColor(getColor(firstColor), getColor(endColor)); - else - widget.setBackGroundColor(getColor(json["SingleColor"])); - - var colorVector = json["ColorVector"]; - if(colorVector != null) - widget.setBackGroundColorVector(cc.p(colorVector["ScaleX"], colorVector["ScaleY"])); + setLayoutBackground(widget, json["SingleColor"], json["FirstColor"], json["EndColor"]); + setLayoutBackgroundVector(widget, json["ColorVector"]); return widget; }; @@ -725,24 +734,8 @@ setContentSize(widget, json["Size"]); } - var firstColor = json["FirstColor"]; - var endColor = json["EndColor"]; - if(firstColor && endColor){ - if(endColor["R"] != null && endColor["G"] != null && endColor["B"] != null) - widget.setBackGroundColor(getColor(firstColor), getColor(endColor)); - else - widget.setBackGroundColor(getColor(firstColor)); - }else{ - widget.setBackGroundColor(getColor(json["SingleColor"])); - } - - - var colorVector = json["ColorVector"]; - if(colorVector){ - var colorVectorX = getParam(colorVector["ScaleX"], 1); - var colorVectorY = getParam(colorVector["ScaleY"], 1); - widget.setBackGroundColorVector(cc.p(colorVectorX, colorVectorY)); - } + setLayoutBackground(widget, json["SingleColor"], json["FirstColor"], json["EndColor"]); + setLayoutBackgroundVector(widget, json["ColorVector"]); var innerNodeSize = json["InnerNodeSize"]; var innerSize = cc.size( @@ -904,21 +897,10 @@ var colorType = getParam(json["ComboBoxIndex"], 0); widget.setBackGroundColorType(colorType); - var bgColorOpacity = json["BackColorAlpha"]; - var firstColor = json["FirstColor"]; - var endColor = json["EndColor"]; - if(firstColor && endColor){ - if(endColor["R"] != null && endColor["G"] != null && endColor["B"] != null) - widget.setBackGroundColor(getColor(firstColor), getColor(endColor)); - else - widget.setBackGroundColor(getColor(firstColor)); - }else{ - widget.setBackGroundColor(getColor(json["SingleColor"])); - } + setLayoutBackground(widget, json["SingleColor"], json["FirstColor"], json["EndColor"]); + setLayoutBackgroundVector(widget, json["ColorVector"]); - var colorVector = json["ColorVector"]; - if(colorVector != null && colorVector["ScaleX"] != null && colorVector["ScaleY"] != null) - widget.setBackGroundColorVector(cc.p(colorVector["ScaleX"], colorVector["ScaleY"])); + var bgColorOpacity = json["BackColorAlpha"]; if(bgColorOpacity != null) widget.setBackGroundColorOpacity(bgColorOpacity); @@ -1000,20 +982,9 @@ if(innerSize != null) widget.setInnerContainerSize(cc.size(innerSize["Widget"]||0, innerSize["Height"]||0)); - var firstColor = json["FirstColor"]; - var endColor = json["EndColor"]; - if(firstColor && endColor){ - if(endColor["R"] != null && endColor["G"] != null && endColor["B"] != null) - widget.setBackGroundColor(getColor(firstColor), getColor(endColor)); - else - widget.setBackGroundColor(getColor(firstColor)); - }else{ - widget.setBackGroundColor(getColor(json["SingleColor"])); - } + setLayoutBackground(widget, json["SingleColor"], json["FirstColor"], json["EndColor"]); + setLayoutBackgroundVector(widget, json["ColorVector"]); - var colorVector = json["ColorVector"]; - if(colorVector != null && colorVector["ScaleX"] != null && colorVector["ScaleY"] != null) - widget.setBackGroundColorVector(cc.p(colorVector["ScaleX"], colorVector["ScaleY"])); if(bgColorOpacity != null) widget.setBackGroundColorOpacity(bgColorOpacity); From 661c62987fc230c7ad8d06de106ac8ea0e9c241a Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 28 Apr 2015 14:10:03 +0800 Subject: [PATCH 0205/1039] Fix removeAllChildren issue that it doesn't notify the renderer to update --- cocos2d/core/base-nodes/CCNode.js | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index 977d3f9339..81f5dc51dc 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -1386,20 +1386,11 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ for (var i = 0; i < __children.length; i++) { var node = __children[i]; if (node) { - // IMPORTANT: - // -1st do onExit - // -2nd cleanup - if (this._running) { - node.onExitTransitionDidStart(); - node.onExit(); - } - if (cleanup) - node.cleanup(); - // set parent nil at the end - node.parent = null; + this._detachChild(node, cleanup); } } this._children.length = 0; + cc.renderer.childrenOrderDirty = true; } }, From 0bb25cec0a8be634b3056a17e622bf7cabe5d813 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 28 Apr 2015 14:43:01 +0800 Subject: [PATCH 0206/1039] Repair the infinite loop --- cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js | 1 - 1 file changed, 1 deletion(-) diff --git a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js index 1dac4df749..dd08d36c00 100644 --- a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js @@ -332,7 +332,6 @@ if(this._colorized){ this._node._texture = this._originalTexture; this._colorized = false; - this._updateColor(); } }; From 61c4e3dc4e850b9859b9e8d7bbad8520e0e7e786 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 28 Apr 2015 15:44:48 +0800 Subject: [PATCH 0207/1039] Fix array delete issue in removeAllChildren --- cocos2d/core/base-nodes/CCNode.js | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index 81f5dc51dc..5184a42b9c 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -1386,7 +1386,18 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ for (var i = 0; i < __children.length; i++) { var node = __children[i]; if (node) { - this._detachChild(node, cleanup); + if (this._running) { + node.onExitTransitionDidStart(); + node.onExit(); + } + + // If you don't do cleanup, the node's actions will not get removed and the + if (cleanup) + node.cleanup(); + + // set parent nil at the end + node.parent = null; + node._renderCmd.detachFromParent(); } } this._children.length = 0; From 37a963bd21aa182cd3932d2acd7d47fc21dfa8cc Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 28 Apr 2015 18:34:07 +0800 Subject: [PATCH 0208/1039] [Cocos2d-JS] v3.6 changelog --- CHANGELOG.txt | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/CHANGELOG.txt b/CHANGELOG.txt index ec7c62b829..50b7feade2 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,5 +1,25 @@ ChangeLog: +Cocos2d-JS v3.6 @ April 29 2015 + +* Added GAF web runtime to the web engine, the native support will be merged in future version. +* Synchronised Cocos2d-x v3.6. + +* Bug fixes: + 1. Fixed a bug of Cocos Studio parser that it doesn't parse correctly the outline of text widget and button widget. + 2. Fixed a bug of Cocos Studio parser that it doesn't support inner action correctly. + 3. Fixed a bug of Cocos Studio parser that `ccui.Text`'s content size is set incorrectly. + 4. Fixed a bug of Cocos Studio parser that `ccui.Layout`'s background color is set incorrectly. + 5. Fixed a bug of `cc.Node`'s `removeAllChildren` that it doesn't notify the renderer to update. + 6. Fixed a bug of audio system that the resume of music may start from the beginning. + 7. Fixed a bug that sprite's `setTexture` fails to update its content size. + 8. Fixed a bug that Scale9Sprite's children doesn't get transformed recursively. + 9. Fixed constant naming issue of `ccs.FrameEaseType`. + 10. Fixed `cc.LoaderScene.preload` API inconsistency between web engine and native engine. + 11. Fixed a bug that `ccui.Slider` doesn't act correctly when it's scaled. + 12. Fixed a bug that `ccui.Button` renders incorrectly when scale9sprite option enabled. + 13. Fixed circular invocation issue in `cc.Sprite`'s canvas render command. + Cocos2d-JS v3.6 Beta @ April 22 2015 * Improved TMX transform to support RotationX and RotationY. From a81d0011732b35daf9b9372c43cbbdc1ab857079 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 29 Apr 2015 17:40:37 +0800 Subject: [PATCH 0209/1039] The positionType error of particleSystem - timelineParser-2.x --- extensions/cocostudio/loader/parsers/timelineParser-2.x.js | 1 + 1 file changed, 1 insertion(+) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index e6c2a4bbe8..e5644ccada 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -218,6 +218,7 @@ cc.log("%s need to be preloaded", path); node = new cc.ParticleSystem(path); self.generalAttributes(node, json); + node.setPositionType(cc.ParticleSystem.TYPE_GROUPED); !cc.sys.isNative && node.setDrawMode(cc.ParticleSystem.TEXTURE_MODE); var blendData = json["BlendFunc"]; From 3c599bfc445a143c8eeeeac0b9070cd184f78520 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 29 Apr 2015 22:56:09 +0800 Subject: [PATCH 0210/1039] Fix parser's setAnimationName issue while the property is undefined --- extensions/cocostudio/loader/parsers/action-2.x.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/extensions/cocostudio/loader/parsers/action-2.x.js b/extensions/cocostudio/loader/parsers/action-2.x.js index dfe69dc51f..3329106e25 100644 --- a/extensions/cocostudio/loader/parsers/action-2.x.js +++ b/extensions/cocostudio/loader/parsers/action-2.x.js @@ -237,7 +237,8 @@ frame.setSingleFrameIndex(singleFrameIndex); frame.setEnterWithName(true); - frame.setAnimationName(currentAnimationFrame); + if (currentAnimationFrame) + frame.setAnimationName(currentAnimationFrame); return frame; } From 4144cc57244477c0e657ab1fba23e9f225eb0ee1 Mon Sep 17 00:00:00 2001 From: ZippoLag Date: Sun, 3 May 2015 13:48:04 -0300 Subject: [PATCH 0211/1039] objectNamed missing a return objectNamed missing a return statement (hence always returning null) --- cocos2d/tilemap/CCTMXObjectGroup.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/tilemap/CCTMXObjectGroup.js b/cocos2d/tilemap/CCTMXObjectGroup.js index 560c690afe..b5d41dbc9a 100644 --- a/cocos2d/tilemap/CCTMXObjectGroup.js +++ b/cocos2d/tilemap/CCTMXObjectGroup.js @@ -117,7 +117,7 @@ cc.TMXObjectGroup = cc.Class.extend(/** @lends cc.TMXObjectGroup# */{ * @return {object|Null} */ objectNamed:function (objectName) { - this.getObject(objectName); + return this.getObject(objectName); }, /** From 59063bb66b1292babd4cff7fe4afeb2a231e25af Mon Sep 17 00:00:00 2001 From: giuseppelt Date: Mon, 4 May 2015 13:41:08 +0200 Subject: [PATCH 0212/1039] Fixed TransitionSlideX callback sequence It fixes the missing array brackets in the sequence call and moves the callback to the inScene because outScene can be optional (very first scene) so the engine will miss the callback, with bad consequences like disabled events. --- cocos2d/transitions/CCTransition.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos2d/transitions/CCTransition.js b/cocos2d/transitions/CCTransition.js index f5ccb82cfe..7d8c65c228 100644 --- a/cocos2d/transitions/CCTransition.js +++ b/cocos2d/transitions/CCTransition.js @@ -652,8 +652,8 @@ cc.TransitionSlideInL = cc.TransitionScene.extend(/** @lends cc.TransitionSlideI var inA = this.action(); var outA = this.action(); - var inAction = this.easeActionWithAction(inA); - var outAction = cc.sequence(this.easeActionWithAction(outA), cc.callFunc(this.finish, this)); + var inAction = cc.sequence([this.easeActionWithAction(inA), cc.callFunc(this.finish, this)]); + var outAction = this.easeActionWithAction(outA); this._inScene.runAction(inAction); this._outScene.runAction(outAction); }, From b158fdcf49b3a080c84ee59512a6a420f3672af7 Mon Sep 17 00:00:00 2001 From: yshumov Date: Tue, 5 May 2015 12:29:04 +0300 Subject: [PATCH 0213/1039] Fixed music end event. By issue https://github.com/cocos2d/cocos2d-html5/issues/2841 --- cocos2d/audio/CCAudio.js | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index e3890afd59..8e7c5e0059 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -671,6 +671,14 @@ cc.Audio = cc.Class.extend({ } audio.play(0, loop); audio.setVolume(this._musicVolume); + function cbEnd(){ + if (!this._currMusic._pause) { + this.stopMusic(); + } + } + var cbEndWithContext = cbEnd.bind(this); + audio._currentSource.onended = cbEndWithContext; + this._currMusic = audio; }, From 66f0a2957b735c97a19e91e8e55a5f308c6fd52b Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 6 May 2015 10:00:22 +0800 Subject: [PATCH 0214/1039] Audio load didn't use the search path --- cocos2d/audio/CCAudio.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index e3890afd59..220273ae81 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -503,6 +503,9 @@ cc.Audio = cc.Class.extend({ var i; + if(cc.loader.audioPath) + realUrl = cc.path.join(cc.loader.audioPath, realUrl); + var extname = cc.path.extname(realUrl); var typeList = [extname]; From e308189256dd67e3e65017e7790fa61ed2d9c478 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 6 May 2015 15:35:43 +0800 Subject: [PATCH 0215/1039] LayerColor's color will disappear when update transform after open bake --- cocos2d/core/layers/CCLayerCanvasRenderCmd.js | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js index 2fb954e115..c80fc3f574 100644 --- a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js +++ b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js @@ -223,6 +223,7 @@ var bakeContext = locBakeSprite.getCacheContext(); var ctx = bakeContext.getContext(); locBakeSprite.resetCanvasSize(boundingBox.width, boundingBox.height); + ctx.fillStyle = bakeContext._currentFillStyle; bakeContext.setOffset(0 - boundingBox.x, ctx.canvas.height - boundingBox.height + boundingBox.y ); locBakeSprite.setPosition(boundingBox.x, boundingBox.y); From 774484ca791cfff81c983b20692761c0294764a3 Mon Sep 17 00:00:00 2001 From: SPACELAN Date: Wed, 6 May 2015 16:23:38 +0800 Subject: [PATCH 0216/1039] Found a bug in cc.math.Matrix4().inverse() and fixed it The `cc.math.Matrix4._gaussj` function changes the global var `identityMatrix` and makes the following calculations wrong. --- cocos2d/kazmath/mat4.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/cocos2d/kazmath/mat4.js b/cocos2d/kazmath/mat4.js index b1af75efc3..d211589531 100644 --- a/cocos2d/kazmath/mat4.js +++ b/cocos2d/kazmath/mat4.js @@ -181,7 +181,8 @@ */ cc.kmMat4Inverse = function (pOut, pM) { var inv = new cc.math.Matrix4(pM); - if (cc.math.Matrix4._gaussj(inv, identityMatrix) === false) + var tmp = new cc.math.Matrix4(identityMatrix); + if (cc.math.Matrix4._gaussj(inv, tmp) === false) return null; pOut.assignFrom(inv); return pOut; @@ -193,7 +194,8 @@ */ proto.inverse = function(){ //cc.kmMat4Inverse var inv = new cc.math.Matrix4(this); - if (cc.math.Matrix4._gaussj(inv, identityMatrix) === false) + var tmp = new cc.math.Matrix4(identityMatrix); + if (cc.math.Matrix4._gaussj(inv, tmp) === false) return null; return inv; }; From 7dab18778bec49232b731fc667d4192680c96d4a Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 6 May 2015 18:23:51 +0800 Subject: [PATCH 0217/1039] Delete the redundant variables defined and cc.log --- extensions/ccui/uiwidgets/UIRichText.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/extensions/ccui/uiwidgets/UIRichText.js b/extensions/ccui/uiwidgets/UIRichText.js index a92b642063..61f72cc08e 100644 --- a/extensions/ccui/uiwidgets/UIRichText.js +++ b/extensions/ccui/uiwidgets/UIRichText.js @@ -471,6 +471,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ var newContentSizeHeight = 0, locRenderersContainer = this._elementRenderersContainer; var locElementRenders = this._elementRenders; var i, j, row, nextPosX, l; + var lineHeight, offsetX; if (this._ignoreSize) { var newContentSizeWidth = 0; row = locElementRenders[0]; @@ -482,7 +483,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ l.setPosition(nextPosX, 0); locRenderersContainer.addChild(l, 1, j); - var lineHeight = l.getLineHeight ? l.getLineHeight() : newContentSizeHeight; + lineHeight = l.getLineHeight ? l.getLineHeight() : newContentSizeHeight; var iSize = l.getContentSize(); newContentSizeWidth += iSize.width; @@ -492,7 +493,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ //Text flow horizontal alignment: if(this._textHorizontalAlignment !== cc.TEXT_ALIGNMENT_LEFT) { - var offsetX = 0; + offsetX = 0; if (this._textHorizontalAlignment === cc.TEXT_ALIGNMENT_RIGHT) offsetX = this._contentSize.width - nextPosX; else if (this._textHorizontalAlignment === cc.TEXT_ALIGNMENT_CENTER) @@ -510,8 +511,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ var maxHeight = 0; for (j = 0; j < row.length; j++) { l = row[j]; - var lineHeight = l.getLineHeight ? l.getLineHeight() : l.getContentSize().height; - cc.log(lineHeight); + lineHeight = l.getLineHeight ? l.getLineHeight() : l.getContentSize().height; maxHeight = Math.max(Math.min(l.getContentSize().height, lineHeight), maxHeight); } maxHeights[i] = maxHeight; @@ -534,7 +534,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ } //Text flow alignment(s) if( this._textHorizontalAlignment !== cc.TEXT_ALIGNMENT_LEFT || this._textVerticalAlignment !== cc.VERTICAL_TEXT_ALIGNMENT_TOP) { - var offsetX = 0; + offsetX = 0; if (this._textHorizontalAlignment === cc.TEXT_ALIGNMENT_RIGHT) offsetX = this._contentSize.width - nextPosX; else if (this._textHorizontalAlignment === cc.TEXT_ALIGNMENT_CENTER) From 8f89482d279b7c19eed92e9523f1358a400b6300 Mon Sep 17 00:00:00 2001 From: mutoo Date: Fri, 8 May 2015 17:44:10 +0800 Subject: [PATCH 0218/1039] fix a typo in uiParser; --- extensions/cocostudio/loader/parsers/uiParser-1.x.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/uiParser-1.x.js b/extensions/cocostudio/loader/parsers/uiParser-1.x.js index c14763e875..ff0ee42066 100644 --- a/extensions/cocostudio/loader/parsers/uiParser-1.x.js +++ b/extensions/cocostudio/loader/parsers/uiParser-1.x.js @@ -613,7 +613,7 @@ if(ph) widget.setPlaceHolder(ph); widget.setString(options["text"]||""); - var fs = options["fontSize1"]; + var fs = options["fontSize"]; if(fs) widget.setFontSize(fs); var fn = options["fontName"]; @@ -695,4 +695,4 @@ load.registerParser("ccui", "*", parser); -})(ccs._load, ccs._parser); \ No newline at end of file +})(ccs._load, ccs._parser); From 2e3dab38452410aaa077da72acb43b5b90f8fb8c Mon Sep 17 00:00:00 2001 From: Patricio Date: Fri, 8 May 2015 12:17:03 +0200 Subject: [PATCH 0219/1039] Animations with only one frame are allowed now. --- extensions/cocostudio/action/CCActionNode.js | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/extensions/cocostudio/action/CCActionNode.js b/extensions/cocostudio/action/CCActionNode.js index a4ae9a9332..238a49541c 100644 --- a/extensions/cocostudio/action/CCActionNode.js +++ b/extensions/cocostudio/action/CCActionNode.js @@ -266,13 +266,17 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{ var locSequenceArray = []; for (var j = 0; j < locArray.length; j++) { var locFrame = locArray[j]; + var locAction = null; if (j !== 0) { var locSrcFrame = locArray[j - 1]; var locDuration = (locFrame.frameIndex - locSrcFrame.frameIndex) * this.getUnitTime(); - var locAction = locFrame.getAction(locDuration); - if(locAction) - locSequenceArray.push(locAction); + locAction = locFrame.getAction(locDuration); } + else { + locAction = locFrame.getAction(0); + } + if(locAction) + locSequenceArray.push(locAction); } if(locSequenceArray){ var locSequence = cc.sequence(locSequenceArray); @@ -414,4 +418,4 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{ return true; return this._action.isDone(); } -}); \ No newline at end of file +}); From c1c36a7d0fe8be091354a87300e7223d24f47fee Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 12 May 2015 14:31:13 +0800 Subject: [PATCH 0220/1039] Add ccui.VideoPlayer --- cocos2d/core/platform/CCEGLView.js | 24 ++ extensions/ccui/uiwidgets/UIVideoPlayer.js | 426 +++++++++++++++++++++ moduleConfig.json | 1 + 3 files changed, 451 insertions(+) create mode 100644 extensions/ccui/uiwidgets/UIVideoPlayer.js diff --git a/cocos2d/core/platform/CCEGLView.js b/cocos2d/core/platform/CCEGLView.js index 01c58088ed..064e0324a3 100644 --- a/cocos2d/core/platform/CCEGLView.js +++ b/cocos2d/core/platform/CCEGLView.js @@ -164,6 +164,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ __resizeWithBrowserSize: false, _isAdjustViewPort: true, _targetDensityDPI: null, + _resizeCallbackList: null, /** * Constructor of cc.EGLView @@ -199,6 +200,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ _t._hDC = cc._canvas; _t._hRC = cc._renderContext; _t._targetDensityDPI = cc.DENSITYDPI_HIGH; + _t._resizeCallbackList = []; }, // Resize helper functions @@ -224,6 +226,11 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ var height = view._originalDesignResolutionSize.height; if (width > 0) view.setDesignResolutionSize(width, height, view._resolutionPolicy); + + for(var i= 0, len= view._resizeCallbackList.length; i Date: Tue, 12 May 2015 17:44:27 +0800 Subject: [PATCH 0221/1039] To prevent the events are covered --- cocos2d/audio/CCAudio.js | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index 8e7c5e0059..faab5b2215 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -315,7 +315,10 @@ cc.Audio = cc.Class.extend({ if(self._ignoreEnded){ self._ignoreEnded = false; }else{ - self._playing = false; + if(!self._pause) + self.stop(); + else + self._playing = false; } }; }, @@ -671,13 +674,6 @@ cc.Audio = cc.Class.extend({ } audio.play(0, loop); audio.setVolume(this._musicVolume); - function cbEnd(){ - if (!this._currMusic._pause) { - this.stopMusic(); - } - } - var cbEndWithContext = cbEnd.bind(this); - audio._currentSource.onended = cbEndWithContext; this._currMusic = audio; }, From 6c424c7182502488564437d69ea081277d5d432d Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 12 May 2015 17:57:25 +0800 Subject: [PATCH 0222/1039] Repair the webaudio loop attribute is invalid for chrome 42 --- cocos2d/audio/CCAudio.js | 82 ++++++++++++++++++++++++---------------- 1 file changed, 50 insertions(+), 32 deletions(-) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index 220273ae81..9f61d718a1 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -33,6 +33,7 @@ * replay : The first music will fail, must be replay after touchstart * emptied : Whether to use the emptied event to replace load callback * delay : delay created the context object - only webAudio + * manualLoop : WebAudio loop attribute failure, need to manually perform loop * * May be modifications for a few browser version */ @@ -109,43 +110,48 @@ console.log(e); } + if(cc.sys.isMobile){ + if(cc.sys.os !== cc.sys.OS_IOS) + cc.__audioSupport = supportTable[sys.browserType] || supportTable["common"]; + else + cc.__audioSupport = supportTable[sys.BROWSER_TYPE_SAFARI]; + }else{ + switch(sys.browserType){ + case sys.BROWSER_TYPE_IE: + cc.__audioSupport = supportTable[sys.BROWSER_TYPE_IE]; + break; + case sys.BROWSER_TYPE_FIREFOX: + cc.__audioSupport = supportTable[sys.BROWSER_TYPE_FIREFOX]; + break; + default: + cc.__audioSupport = supportTable["common"]; + } + } + /////////////////////////// // Browser compatibility// /////////////////////////// if(version){ switch(sys.browserType){ case sys.BROWSER_TYPE_CHROME: - if(parseInt(version) < 30){ - supportTable[sys.BROWSER_TYPE_CHROME] = {multichannel: false , webAudio: true , auto: false}; + version = parseInt(version); + if(version < 30){ + cc.__audioSupport = {multichannel: false , webAudio: true , auto: false}; + }else if(version === 42){ + cc.__audioSupport.manualLoop = true; } break; case sys.BROWSER_TYPE_MIUI: - version = version.match(/\d+/g); - if(version[0] < 2 || (version[0] === 2 && version[1] === 0 && version[2] <= 1)){ - supportTable[sys.BROWSER_TYPE_MIUI].auto = false; + if(cc.sys.isMobile){ + version = version.match(/\d+/g); + if(version[0] < 2 || (version[0] === 2 && version[1] === 0 && version[2] <= 1)){ + cc.__audioSupport.auto = false; + } } break; } } - if(cc.sys.isMobile){ - if(cc.sys.os !== cc.sys.OS_IOS) - cc.__audioSupport = supportTable[sys.browserType] || supportTable["common"]; - else - cc.__audioSupport = supportTable[sys.BROWSER_TYPE_SAFARI]; - }else{ - switch(sys.browserType){ - case sys.BROWSER_TYPE_IE: - cc.__audioSupport = supportTable[sys.BROWSER_TYPE_IE]; - break; - case sys.BROWSER_TYPE_FIREFOX: - cc.__audioSupport = supportTable[sys.BROWSER_TYPE_FIREFOX]; - break; - default: - cc.__audioSupport = supportTable["common"]; - } - } - if(DEBUG){ setTimeout(function(){ cc.log("browse type: " + sys.browserType); @@ -181,6 +187,7 @@ cc.Audio = cc.Class.extend({ _volume: null, _ignoreEnded: false, + _manualLoop: false, //DOM Audio _element: null, @@ -278,7 +285,10 @@ cc.Audio = cc.Class.extend({ var audio = this._context["createBufferSource"](); audio.buffer = this._buffer; audio["connect"](this._volume); - audio.loop = this.loop; + if(this._manualLoop) + audio.loop = false; + else + audio.loop = this.loop; this._startTime = this._context.currentTime; this._currentTime = offset || 0; @@ -312,6 +322,11 @@ cc.Audio = cc.Class.extend({ this._currentSource = audio; var self = this; audio["onended"] = function(){ + if(self._manualLoop && self._playing && self.loop){ + self.stop(); + self.play(); + return; + } if(self._ignoreEnded){ self._ignoreEnded = false; }else{ @@ -526,6 +541,8 @@ cc.Audio = cc.Class.extend({ volume["gain"].value = 1; volume["connect"](context["destination"]); audio = new cc.Audio(context, volume, realUrl); + if(polyfill.manualLoop) + audio._manualLoop = true; }catch(err){ SWA = false; cc.log("browser don't support webAudio"); @@ -585,18 +602,18 @@ cc.Audio = cc.Class.extend({ emptied(); }else{ termination = true; - element.pause(); - document.body.removeChild(element); + element.pause(); + document.body.removeChild(element); cb("audio load timeout : " + realUrl, audio); } }, 10000); var success = function(){ if(!cbCheck){ - element.pause(); - try { element.currentTime = 0; - element.volume = 1; } catch (e) {} - document.body.removeChild(element); + element.pause(); + try { element.currentTime = 0; + element.volume = 1; } catch (e) {} + document.body.removeChild(element); audio.setElement(element); element.removeEventListener("canplaythrough", success, false); element.removeEventListener("error", failure, false); @@ -609,8 +626,8 @@ cc.Audio = cc.Class.extend({ var failure = function(){ if(!cbCheck) return; - element.pause(); - document.body.removeChild(element); + element.pause(); + document.body.removeChild(element); element.removeEventListener("canplaythrough", success, false); element.removeEventListener("error", failure, false); element.removeEventListener("emptied", emptied, false); @@ -674,6 +691,7 @@ cc.Audio = cc.Class.extend({ } audio.play(0, loop); audio.setVolume(this._musicVolume); + this._currMusic = audio; }, From 84299a7edadda661a81d1dcf263cf404ea1d6f92 Mon Sep 17 00:00:00 2001 From: Igor Shmulyan Date: Tue, 12 May 2015 14:59:30 +0300 Subject: [PATCH 0223/1039] fixed crash when character not found into BMP font --- cocos2d/labels/CCLabelBMFont.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/cocos2d/labels/CCLabelBMFont.js b/cocos2d/labels/CCLabelBMFont.js index 83bdf818cf..1a4a018471 100644 --- a/cocos2d/labels/CCLabelBMFont.js +++ b/cocos2d/labels/CCLabelBMFont.js @@ -439,7 +439,12 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ return 0; } var curTextFirstSprite = this.getChildByTag(startIndex); - var curTextLastSprite = this.getChildByTag(startIndex + endIndex); + var curTextLastSpriteId = startIndex + endIndex; + var curTextLastSprite = this.getChildByTag(curTextLastSpriteId); + while (!curTextLastSprite && 0 < curTextLastSpriteId) { + curTextLastSpriteId--; + curTextLastSprite = this.getChildByTag(curTextLastSpriteId); + } return this._getLetterPosXLeft(curTextLastSprite) - this._getLetterPosXLeft(curTextFirstSprite); }, From a6e029f035293ee1e14f98d51341db75710ce4e2 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 13 May 2015 11:13:18 +0800 Subject: [PATCH 0224/1039] Repair the positioning error problem --- extensions/ccui/uiwidgets/UIVideoPlayer.js | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/extensions/ccui/uiwidgets/UIVideoPlayer.js b/extensions/ccui/uiwidgets/UIVideoPlayer.js index b150bf7a2b..8106563f49 100644 --- a/extensions/ccui/uiwidgets/UIVideoPlayer.js +++ b/extensions/ccui/uiwidgets/UIVideoPlayer.js @@ -325,10 +325,8 @@ ccui.VideoPlayer = ccui.Widget.extend({ b = t.b, c = t.c, d = t.d * scaleY, - tx = t.tx - cw/2 + cw*node._scaleX/2, - ty = t.ty - ch/2 + ch*node._scaleY/2; - //tx = (t.tx + ax*node._scaleX)*scaleX - (1-scaleX)*clientWidth/2 - (clientWidth - ax)*scaleX, - //ty = (t.ty + ay*node._scaleX)*scaleY - (1-scaleY)*clientHeight/2 - (clientHeight - ay)*scaleY; + tx = t.tx*scaleX - cw/2 + cw*node._scaleX/2*scaleX, + ty = t.ty*scaleY - ch/2 + ch*node._scaleY/2*scaleY; var matrix = "matrix(" + a + "," + b + "," + c + "," + d + "," + tx + "," + -ty + ")"; this._video.style["transform"] = matrix; this._video.style["-webkit-transform"] = matrix; From 043312dc8d3af12e894cf2a7e6aeeda37c3b79da Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 13 May 2015 11:32:19 +0800 Subject: [PATCH 0225/1039] Fix spine js parser issue to avoid NaN duration --- extensions/spine/Spine.js | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/extensions/spine/Spine.js b/extensions/spine/Spine.js index 7a25bab80e..047db2b5ac 100644 --- a/extensions/spine/Spine.js +++ b/extensions/spine/Spine.js @@ -1941,7 +1941,7 @@ spine.SkeletonJson.prototype = { frameIndex++; } timelines.push(timeline); - duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 5 - 5]); + duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 5 - 5] || 0); } else if (timelineName == "attachment") { var timeline = new spine.AttachmentTimeline(values.length); @@ -1953,7 +1953,7 @@ spine.SkeletonJson.prototype = { timeline.setFrame(frameIndex++, valueMap["time"], valueMap["name"]); } timelines.push(timeline); - duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]); + duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1] || 0); } else throw "Invalid timeline type for a slot: " + timelineName + " (" + slotName + ")"; @@ -1982,7 +1982,7 @@ spine.SkeletonJson.prototype = { frameIndex++; } timelines.push(timeline); - duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 2 - 2]); + duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 2 - 2] || 0); } else if (timelineName == "translate" || timelineName == "scale") { var timeline; @@ -2005,7 +2005,7 @@ spine.SkeletonJson.prototype = { frameIndex++; } timelines.push(timeline); - duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 3 - 3]); + duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 3 - 3] || 0); } else if (timelineName == "flipX" || timelineName == "flipY") { var x = timelineName == "flipX"; @@ -2020,7 +2020,7 @@ spine.SkeletonJson.prototype = { frameIndex++; } timelines.push(timeline); - duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 2 - 2]); + duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 2 - 2] || 0); } else throw "Invalid timeline type for a bone: " + timelineName + " (" + boneName + ")"; } @@ -2043,7 +2043,7 @@ spine.SkeletonJson.prototype = { frameIndex++; } timelines.push(timeline); - duration = Math.max(duration, timeline.frames[timeline.frameCount * 3 - 3]); + duration = Math.max(duration, timeline.frames[timeline.frameCount * 3 - 3] || 0); } var ffd = map["ffd"]; @@ -2104,7 +2104,7 @@ spine.SkeletonJson.prototype = { frameIndex++; } timelines[timelines.length] = timeline; - duration = Math.max(duration, timeline.frames[timeline.frameCount - 1]); + duration = Math.max(duration, timeline.frames[timeline.frameCount - 1] || 0); } } } @@ -2147,7 +2147,7 @@ spine.SkeletonJson.prototype = { timeline.setFrame(frameIndex++, drawOrderMap["time"], drawOrder); } timelines.push(timeline); - duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]); + duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1] || 0); } var events = map["events"]; @@ -2165,7 +2165,7 @@ spine.SkeletonJson.prototype = { timeline.setFrame(frameIndex++, eventMap["time"], event); } timelines.push(timeline); - duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]); + duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1] || 0); } skeletonData.animations.push(new spine.Animation(name, timelines, duration)); From 1b1ca189d228bd4059e8736a0ef6c9ae0c338e72 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 13 May 2015 13:35:54 +0800 Subject: [PATCH 0226/1039] Fix LabelTTF multiline detection --- cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js index fa687f865a..ceab041b9e 100644 --- a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js +++ b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js @@ -153,7 +153,7 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; } } - if (this._strings.length > 0) + if (this._strings.length > 1) this._isMultiLine = true; var locSize, locStrokeShadowOffsetX = 0, locStrokeShadowOffsetY = 0; From ea4f525ef58a2cb8a314e2beead6ce5a6858e38a Mon Sep 17 00:00:00 2001 From: giuseppelt Date: Wed, 13 May 2015 16:29:14 +0200 Subject: [PATCH 0227/1039] TransitionSlide removed brackets from sequence call --- cocos2d/transitions/CCTransition.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/transitions/CCTransition.js b/cocos2d/transitions/CCTransition.js index 7d8c65c228..f14fa41ad2 100644 --- a/cocos2d/transitions/CCTransition.js +++ b/cocos2d/transitions/CCTransition.js @@ -652,7 +652,7 @@ cc.TransitionSlideInL = cc.TransitionScene.extend(/** @lends cc.TransitionSlideI var inA = this.action(); var outA = this.action(); - var inAction = cc.sequence([this.easeActionWithAction(inA), cc.callFunc(this.finish, this)]); + var inAction = cc.sequence(this.easeActionWithAction(inA), cc.callFunc(this.finish, this)); var outAction = this.easeActionWithAction(outA); this._inScene.runAction(inAction); this._outScene.runAction(outAction); From cb57063d0262a3d4cfe88fcf4c8b22523dd58a3a Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 13 May 2015 23:01:59 +0800 Subject: [PATCH 0228/1039] Fix issue in ccui.Widget#getScale --- extensions/ccui/base-classes/UIWidget.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/ccui/base-classes/UIWidget.js b/extensions/ccui/base-classes/UIWidget.js index b7e7a16f76..bf4af67728 100644 --- a/extensions/ccui/base-classes/UIWidget.js +++ b/extensions/ccui/base-classes/UIWidget.js @@ -1768,7 +1768,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ return originalScale; }, getScale: function(){ - if(this.getScaleX() === this.getScaleY()) + if(this.getScaleX() !== this.getScaleY()) cc.log("Widget#scale. ScaleX != ScaleY. Don't know which one to return"); return this.getScaleX(); }, From 736a00bf6c9fd0e959ec776bab2cc226e3c4aa68 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 14 May 2015 10:41:40 +0800 Subject: [PATCH 0229/1039] Improve property declaration of cc.Texture2D --- cocos2d/core/textures/CCTexture2D.js | 1 - cocos2d/core/textures/TexturesPropertyDefine.js | 11 +++++++++-- cocos2d/core/textures/TexturesWebGL.js | 1 - 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index dca144d060..38c59d2434 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -110,7 +110,6 @@ if (cc._renderType === cc._RENDER_TYPE_CANVAS) { * @extends cc.Class * * @property {WebGLTexture} name - <@readonly> WebGLTexture Object - * @property {Number} defaultPixelFormat - The default pixel format * @property {Number} pixelFormat - <@readonly> Pixel format of the texture * @property {Number} pixelsWidth - <@readonly> Width in pixels * @property {Number} pixelsHeight - <@readonly> Height in pixels diff --git a/cocos2d/core/textures/TexturesPropertyDefine.js b/cocos2d/core/textures/TexturesPropertyDefine.js index fe1eef3801..518a5f5139 100644 --- a/cocos2d/core/textures/TexturesPropertyDefine.js +++ b/cocos2d/core/textures/TexturesPropertyDefine.js @@ -152,6 +152,15 @@ cc._tmp.PrototypeTexture2D = function () { */ _c.PIXEL_FORMAT_DEFAULT = _c.PIXEL_FORMAT_RGBA8888; + /** + * The default pixel format + * @memberOf cc.Texture2D + * @name PIXEL_FORMAT_PVRTC2 + * @static + * @type {Number} + */ + _c.defaultPixelFormat = _c.PIXEL_FORMAT_DEFAULT; + var _M = cc.Texture2D._M = {}; _M[_c.PIXEL_FORMAT_RGBA8888] = "RGBA8888"; _M[_c.PIXEL_FORMAT_RGB888] = "RGB888"; @@ -198,8 +207,6 @@ cc._tmp.PrototypeTexture2D = function () { /** @expose */ _p.height; cc.defineGetterSetter(_p, "height", _p._getHeight); - - _c.defaultPixelFormat = _c.PIXEL_FORMAT_DEFAULT; }; cc._tmp.PrototypeTextureAtlas = function () { diff --git a/cocos2d/core/textures/TexturesWebGL.js b/cocos2d/core/textures/TexturesWebGL.js index c08cd2c49d..c2dc3b3683 100644 --- a/cocos2d/core/textures/TexturesWebGL.js +++ b/cocos2d/core/textures/TexturesWebGL.js @@ -38,7 +38,6 @@ cc._tmp.WebGLTexture2D = function () { * @extends cc.Class * * @property {WebGLTexture} name - <@readonly> WebGLTexture Object - * @property {Number} defaultPixelFormat - The default pixel format * @property {Number} pixelFormat - <@readonly> Pixel format of the texture * @property {Number} pixelsWidth - <@readonly> Width in pixels * @property {Number} pixelsHeight - <@readonly> Height in pixels From aacb872b7c96f5b81b8b4a25f2756b5566709f06 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 14 May 2015 15:40:00 +0800 Subject: [PATCH 0230/1039] Unified management event trigger --- cocos2d/core/event-manager/CCEventManager.js | 21 ++++ extensions/ccui/uiwidgets/UIVideoPlayer.js | 119 ++++++++----------- tools/build.xml | 1 + 3 files changed, 72 insertions(+), 69 deletions(-) diff --git a/cocos2d/core/event-manager/CCEventManager.js b/cocos2d/core/event-manager/CCEventManager.js index 46ba136659..d01b3527aa 100644 --- a/cocos2d/core/event-manager/CCEventManager.js +++ b/cocos2d/core/event-manager/CCEventManager.js @@ -745,6 +745,27 @@ cc.eventManager = /** @lends cc.eventManager# */{ } }, + _removeListenerInCallback: function(listeners, callback){ + if (listeners == null) + return false; + + for (var i = 0, len = listeners.length; i < len; i++) { + var selListener = listeners[i]; + if (selListener._onCustomEvent === callback || selListener._onEvent === callback) { + selListener._setRegistered(false); + if (selListener._getSceneGraphPriority() != null){ + this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener); + selListener._setSceneGraphPriority(null); // NULL out the node pointer so we don't have any dangling pointers to destroyed nodes. + } + + if (this._inDispatch === 0) + cc.arrayRemoveObject(listeners, selListener); + return true; + } + } + return false; + }, + _removeListenerInVector : function(listeners, listener){ if (listeners == null) return false; diff --git a/extensions/ccui/uiwidgets/UIVideoPlayer.js b/extensions/ccui/uiwidgets/UIVideoPlayer.js index 8106563f49..18f68d4f00 100644 --- a/extensions/ccui/uiwidgets/UIVideoPlayer.js +++ b/extensions/ccui/uiwidgets/UIVideoPlayer.js @@ -24,14 +24,10 @@ ccui.VideoPlayer = ccui.Widget.extend({ - _EventList: null, - ctor: function(path){ ccui.Widget.prototype.ctor.call(this); if(path) this.setURL(path); - - this._EventList = {};//play | pause | stop | complete }, _createRenderCmd: function(){ @@ -63,24 +59,6 @@ ccui.VideoPlayer = ccui.Widget.extend({ return ""; }, - /** - * Set the video address - * Automatically replace extname - * All supported video formats will be added to the video - * @param {String} path - */ - setFileName: function(path){ - this.setURL(path); - }, - - /** - * Get the video path - * @returns {String} - */ - getFileName: function(){ - this.getURL(path); - }, - /** * Play the video */ @@ -120,10 +98,7 @@ ccui.VideoPlayer = ccui.Widget.extend({ } setTimeout(function(){ - var list = self._EventList["stop"]; - if(list) - for(var i=0; i + From 2f6cd3d7d084bc53ec28ec25969cb201c3bc3f46 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 14 May 2015 15:40:13 +0800 Subject: [PATCH 0231/1039] Unified management event trigger --- CCBoot.js | 1 + 1 file changed, 1 insertion(+) diff --git a/CCBoot.js b/CCBoot.js index 1be2d4ff3b..6181745665 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -2049,6 +2049,7 @@ cc.game = /** @lends cc.game# */{ EVENT_HIDE: "game_on_hide", EVENT_SHOW: "game_on_show", + EVENT_RESIZE: "game_on_resize", _eventHide: null, _eventShow: null, _onBeforeStartArr: [], From 23b4e36988f53fbfd5eaf1d519e2b874766aaa1c Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 14 May 2015 15:43:04 +0800 Subject: [PATCH 0232/1039] Unified management event trigger --- cocos2d/core/platform/CCEGLView.js | 1 - extensions/ccui/uiwidgets/UIVideoPlayer.js | 6 +++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/cocos2d/core/platform/CCEGLView.js b/cocos2d/core/platform/CCEGLView.js index 064e0324a3..1800830f75 100644 --- a/cocos2d/core/platform/CCEGLView.js +++ b/cocos2d/core/platform/CCEGLView.js @@ -200,7 +200,6 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ _t._hDC = cc._canvas; _t._hRC = cc._renderContext; _t._targetDensityDPI = cc.DENSITYDPI_HIGH; - _t._resizeCallbackList = []; }, // Resize helper functions diff --git a/extensions/ccui/uiwidgets/UIVideoPlayer.js b/extensions/ccui/uiwidgets/UIVideoPlayer.js index 18f68d4f00..3fdbcef822 100644 --- a/extensions/ccui/uiwidgets/UIVideoPlayer.js +++ b/extensions/ccui/uiwidgets/UIVideoPlayer.js @@ -38,10 +38,10 @@ ccui.VideoPlayer = ccui.Widget.extend({ * Set the video address * Automatically replace extname * All supported video formats will be added to the video - * @param {String} path + * @param {String} address */ - setURL: function(path){ - this._renderCmd.updateURL(path); + setURL: function(address){ + this._renderCmd.updateURL(address); }, /** From 9c0a6507492b48202abb96535bb6016cd9622fd5 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 14 May 2015 17:06:54 +0800 Subject: [PATCH 0233/1039] Add the WebView --- extensions/ccui/uiwidgets/UIWebView.js | 355 +++++++++++++++++++++++++ moduleConfig.json | 1 + tools/build.xml | 1 + 3 files changed, 357 insertions(+) create mode 100644 extensions/ccui/uiwidgets/UIWebView.js diff --git a/extensions/ccui/uiwidgets/UIWebView.js b/extensions/ccui/uiwidgets/UIWebView.js new file mode 100644 index 0000000000..f64e11908a --- /dev/null +++ b/extensions/ccui/uiwidgets/UIWebView.js @@ -0,0 +1,355 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +ccui.WebView = ccui.Widget.extend({ + + ctor: function(path){ + ccui.Widget.prototype.ctor.call(this); + if(path) + this.loadURL(path); + this._EventList = {}; + }, + + + 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); + cc.eventManager.dispatchCustomEvent(ccui.WebView.EventType.LOADING); + }, + + /** + * Stop loading + */ + stopLoading: function(){ + cc.log("Web does not support loading"); + }, + 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"); + }, + + /** + * Determine whether to go forward + */ + canGoForward: function(){ + cc.log("Web does not support query history"); + }, + + /** + * go back + */ + goBack: function(){ + var iframe = this._renderCmd._iframe; + if(iframe){ + var win = iframe.contentWindow; + if(win && win.location) + win.history.back(); + } + }, + + /** + * go forward + */ + goForward: function(){ + var iframe = this._renderCmd._iframe; + if(iframe){ + var win = iframe.contentWindow; + if(win && win.location) + win.history.forward(); + } + }, + + /** + * In the webview execution within a period of js string + * @param str + */ + evaluateJS: function(str){ + var iframe = this._renderCmd._iframe; + if(iframe){ + var win = iframe.contentWindow; + try{ + win.eval(str); + }catch(err){ + console.error(err); + } + } + }, + + /** + * Limited scale + */ + setScalesPageToFit: function(){ + cc.log("Web does not support zoom"); + }, + + /** + * The binding event + * @param event string: load | loading | error Or: ccui.WebView.EventType + * @param callback + */ + addEventListener: function(event, callback){ + if(!/^ui_webview_/.test(event)) + event = "ui_webview_" + event; + return cc.eventManager.addCustomListener(event, callback); + }, + + /** + * Delete events + * @param event + * @param callbackOrListener + */ + removeEventListener: function(event, callbackOrListener){ + var map, list; + if(!/^ui_webview_/.test(event)) + event = "ui_webview_" + event; + if(typeof callbackOrListener === "function"){ + map = cc.eventManager._listenersMap[event]; + if(map){ + list = map.getFixedPriorityListeners(); + list && cc.eventManager._removeListenerInCallback(list, callbackOrListener); + } + }else{ + map = cc.eventManager._listenersMap[event]; + if(map){ + list = map.getFixedPriorityListeners(); + list && cc.eventManager._removeListenerInVector(list, callbackOrListener); + } + } + }, + + //setOnShouldStartLoading: function(callback){}, + //setOnDidFinishLoading: function(){}, + //setOnDidFailLoading: function(){}, + //setOnJSCallback: function(){}, + + //getOnShouldStartLoading: function(){}, + //getOnDidFinishLoading: function(){}, + //getOnDidFailLoading: function(){}, + //getOnJSCallback: function(){}, + + _createRenderCmd: function(){ + return new ccui.WebView.RenderCmd(this); + }, + + setContentSize: function(w, h){ + ccui.Widget.prototype.setContentSize.call(this, w, h); + if(h === undefined){ + h = w.height; + w = w.width; + } + this._renderCmd.changeSize(w, h); + }, + + cleanup: function(){ + this._renderCmd.removeDom(); + this.stopAllActions(); + this.unscheduleAllCallbacks(); + } +}); + +ccui.WebView.EventType = { + LOADING: "ui_webview_loading", + LOADED: "ui_webview_load", + ERROR: "ui_webview_error" +}; + +(function(){ + + ccui.WebView.polyfill = { + devicePixelRatio: false, + enableDiv: false + }; + + if(cc.sys.os === cc.sys.OS_IOS) + ccui.WebView.polyfill.enableDiv = true; + +})(); + +(function(polyfill){ + + ccui.WebView.RenderCmd = function(node){ + cc.Node.CanvasRenderCmd.call(this, node); + + this._div = null; + this._iframe = null; + + if(polyfill.enableDiv){ + this._div = document.createElement("div"); + this._div.style["-webkit-overflow"] = "auto"; + this._div.style["-webkit-overflow-scrolling"] = "touch"; + this._iframe = document.createElement("iframe"); + this._div.appendChild(this._iframe); + }else{ + this._div = this._iframe = document.createElement("iframe"); + } + this._iframe.addEventListener("load", function(){ + cc.eventManager.dispatchCustomEvent(ccui.WebView.EventType.LOADED); + }); + this._iframe.addEventListener("error", function(){ + cc.eventManager.dispatchCustomEvent(ccui.WebView.EventType.ERROR); + }); + this._div.style["background-color"] = "#FFF"; + this._div.style.height = "200px"; + this._div.style.width = "300px"; + this._div.style.overflow = "scroll"; + this._listener = null; + this.initStyle(); + }; + + var proto = ccui.WebView.RenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); + proto.constructor = ccui.WebView.RenderCmd; + + proto.updateStatus = function(){ + polyfill.devicePixelRatio = cc.view.isRetinaEnabled(); + var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag; + if(locFlag & flags.transformDirty){ + //update the transform + this.transform(this.getParentRenderCmd(), true); + this.updateMatrix(this._worldTransform, cc.view._scaleX, cc.view._scaleY); + this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.transformDirty ^ this._dirtyFlag; + } + }; + + proto.visit = function(){ + var self = this, + container = cc.container, + eventManager = cc.eventManager; + if(this._node._visible){ + container.appendChild(this._div); + if(this._listener === null) + this._listener = eventManager.addCustomListener(cc.game.EVENT_RESIZE, function () { + self.resize(); + }); + }else{ + var hasChild = false; + if('contains' in container) { + hasChild = container.contains(this._div); + }else { + hasChild = container.compareDocumentPosition(this._div) % 16; + } + if(hasChild) + container.removeChild(this._div); + var list = eventManager._listenersMap[cc.game.EVENT_RESIZE].getFixedPriorityListeners(); + eventManager._removeListenerInVector(list, this._listener); + this._listener = null; + } + this.updateStatus(); + this.resize(cc.view); + }; + + proto.resize = function(view){ + view = view || cc.view; + var node = this._node, + eventManager = cc.eventManager; + if(node._parent && node._visible) + this.updateMatrix(this._worldTransform, view._scaleX, view._scaleY); + else{ + var list = eventManager._listenersMap[cc.game.EVENT_RESIZE].getFixedPriorityListeners(); + eventManager._removeListenerInVector(list, this._listener); + this._listener = null; + } + }; + + proto.updateMatrix = function(t, scaleX, scaleY){ + var node = this._node; + if(polyfill.devicePixelRatio && scaleX !== 1 && scaleX !== 1){ + var dpr = window.devicePixelRatio; + scaleX = scaleX / dpr; + scaleY = scaleY / dpr; + } + if(this._loaded === false) return; + var cw = node._contentSize.width, + ch = node._contentSize.height; + var a = t.a * scaleX, + b = t.b, + c = t.c, + d = t.d * scaleY, + tx = t.tx*scaleX - cw/2 + cw*node._scaleX/2*scaleX, + ty = t.ty*scaleY - ch/2 + ch*node._scaleY/2*scaleY; + var matrix = "matrix(" + a + "," + b + "," + c + "," + d + "," + tx + "," + -ty + ")"; + this._div.style["transform"] = matrix; + this._div.style["-webkit-transform"] = matrix; + }; + + proto.initStyle = function(){ + if(!this._div) return; + var div = this._div; + div.style.position = "absolute"; + div.style.bottom = "0px"; + div.style.left = "0px"; + }; + + proto.updateURL = function(url){ + var iframe = this._iframe; + iframe.src = url; + var self = this; + var cb = function(){ + self._loaded = true; + iframe.removeEventListener("load", cb); + }; + iframe.addEventListener("load", cb); + }; + + proto.changeSize = function(w, h){ + var div = this._div; + if(div){ + div.style["width"] = w+"px"; + div.style["height"] = h+"px"; + } + }; + + proto.removeDom = function(){ + var div = this._div; + if(div){ + var hasChild = false; + if('contains' in cc.container) { + hasChild = cc.container.contains(div); + }else { + hasChild = cc.container.compareDocumentPosition(div) % 16; + } + if(hasChild) + cc.container.removeChild(div); + } + }; + +})(ccui.WebView.polyfill); \ No newline at end of file diff --git a/moduleConfig.json b/moduleConfig.json index a089e198d8..d665e1842a 100644 --- a/moduleConfig.json +++ b/moduleConfig.json @@ -323,6 +323,7 @@ "extensions/ccui/uiwidgets/UITextBMFont.js", "extensions/ccui/uiwidgets/UITextField.js", "extensions/ccui/uiwidgets/UIRichText.js", + "extensions/ccui/uiwidgets/UIWebView.js", "extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js", "extensions/ccui/uiwidgets/scroll-widget/UIListView.js", "extensions/ccui/uiwidgets/scroll-widget/UIPageView.js" diff --git a/tools/build.xml b/tools/build.xml index 326af567d2..4cb0fecae1 100644 --- a/tools/build.xml +++ b/tools/build.xml @@ -224,6 +224,7 @@ + From f58b64259f88f36666b71bc5b02dfbe58dc9d39b Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 14 May 2015 18:10:43 +0800 Subject: [PATCH 0234/1039] Unified management event trigger --- cocos2d/core/platform/CCEGLView.js | 22 ---------------------- 1 file changed, 22 deletions(-) diff --git a/cocos2d/core/platform/CCEGLView.js b/cocos2d/core/platform/CCEGLView.js index 1800830f75..1360857192 100644 --- a/cocos2d/core/platform/CCEGLView.js +++ b/cocos2d/core/platform/CCEGLView.js @@ -164,7 +164,6 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ __resizeWithBrowserSize: false, _isAdjustViewPort: true, _targetDensityDPI: null, - _resizeCallbackList: null, /** * Constructor of cc.EGLView @@ -226,10 +225,6 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ if (width > 0) view.setDesignResolutionSize(width, height, view._resolutionPolicy); - for(var i= 0, len= view._resizeCallbackList.length; i Date: Thu, 14 May 2015 14:19:47 +0200 Subject: [PATCH 0235/1039] Fixed TransitionShrinkGrow callback sequence --- cocos2d/transitions/CCTransition.js | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/cocos2d/transitions/CCTransition.js b/cocos2d/transitions/CCTransition.js index f14fa41ad2..b2dd0a1f1e 100644 --- a/cocos2d/transitions/CCTransition.js +++ b/cocos2d/transitions/CCTransition.js @@ -879,10 +879,8 @@ cc.TransitionShrinkGrow = cc.TransitionScene.extend(/** @lends cc.TransitionShri var scaleOut = cc.scaleTo(this._duration, 0.01); var scaleIn = cc.scaleTo(this._duration, 1.0); - this._inScene.runAction(this.easeActionWithAction(scaleIn)); - this._outScene.runAction( - cc.sequence(this.easeActionWithAction(scaleOut), cc.callFunc(this.finish, this)) - ); + this._inScene.runAction(cc.sequence(this.easeActionWithAction(scaleIn), cc.callFunc(this.finish, this)); + this._outScene.runAction(this.easeActionWithAction(scaleOut)); }, /** From 89a721e110cb5c4f10d81eb32ea79362d4741aa8 Mon Sep 17 00:00:00 2001 From: Ningxin Hu Date: Fri, 15 May 2015 12:43:15 +0800 Subject: [PATCH 0236/1039] Add SIMD version of kazmath functions Contributors: pan.han@intel.com yuhang.lan@intel.com --- cocos2d/kazmath/mat4.js | 424 ++++++++++++++++++++++++++++++++++++++++ cocos2d/kazmath/vec3.js | 24 +++ 2 files changed, 448 insertions(+) diff --git a/cocos2d/kazmath/mat4.js b/cocos2d/kazmath/mat4.js index d211589531..41eb3677c4 100644 --- a/cocos2d/kazmath/mat4.js +++ b/cocos2d/kazmath/mat4.js @@ -188,6 +188,11 @@ return pOut; }; + cc.kmMat4InverseSIMD = function (pOut, pM) { + pOut = pM.inverseSIMD(); + return pOut; + }; + /** * Calculates the inverse of current matrix. * @returns {cc.math.Matrix4} Returns null if there is no inverse, else returns a new inverse matrix object @@ -199,6 +204,133 @@ return null; return inv; }; + + proto.inverseSIMD = function(){ + var inv = new cc.math.Matrix4(); + var src = this.mat; + var dest = inv.mat; + var src0, src1, src2, src3; + var row0, row1, row2, row3; + var tmp1; + var minor0, minor1, minor2, minor3; + var det; + + // Load the 4 rows + var src0 = SIMD.float32x4.load(src, 0); + var src1 = SIMD.float32x4.load(src, 4); + var src2 = SIMD.float32x4.load(src, 8); + var src3 = SIMD.float32x4.load(src, 12); + + // Transpose the source matrix. Sort of. Not a true transpose operation + + tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5); + row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5); + row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6); + row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7); + + tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7); + row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7); + row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6); + row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7); + + // This is a true transposition, but it will lead to an incorrect result + + //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5); + //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5); + //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6); + //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7); + + //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7); + //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7); + //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6); + //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7); + + // ---- + tmp1 = SIMD.float32x4.mul(row2, row3); + tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001 + minor0 = SIMD.float32x4.mul(row1, tmp1); + minor1 = SIMD.float32x4.mul(row0, tmp1); + tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110 + minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0); + minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1); + minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110 + + // ---- + tmp1 = SIMD.float32x4.mul(row1, row2); + tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001 + minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0); + minor3 = SIMD.float32x4.mul(row0, tmp1); + tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110 + minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1)); + minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3); + minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110 + + // ---- + tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110 + tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001 + row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110 + minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0); + minor2 = SIMD.float32x4.mul(row0, tmp1); + tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110 + minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1)); + minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2); + minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110 + + // ---- + tmp1 = SIMD.float32x4.mul(row0, row1); + tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001 + minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2); + minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3); + tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110 + minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2); + minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1)); + + // ---- + tmp1 = SIMD.float32x4.mul(row0, row3); + tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001 + minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1)); + minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2); + tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110 + minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1); + minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1)); + + // ---- + tmp1 = SIMD.float32x4.mul(row0, row2); + tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001 + minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1); + minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1)); + tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110 + minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1)); + minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3); + + // Compute determinant + det = SIMD.float32x4.mul(row0, minor0); + det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110 + det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001 + tmp1 = SIMD.float32x4.reciprocalApproximation(det); + det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1))); + det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0); + + // These shuffles aren't necessary if the faulty transposition is done + // up at the top of this function. + //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3); + //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3); + //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3); + //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3); + + // Compute final values by multiplying with 1/det + minor0 = SIMD.float32x4.mul(det, minor0); + minor1 = SIMD.float32x4.mul(det, minor1); + minor2 = SIMD.float32x4.mul(det, minor2); + minor3 = SIMD.float32x4.mul(det, minor3); + + SIMD.float32x4.store(dest, 0, minor0); + SIMD.float32x4.store(dest, 4, minor1); + SIMD.float32x4.store(dest, 8, minor2); + SIMD.float32x4.store(dest, 12, minor3); + + return inv; + }; /** * Returns true if current matrix is an identity matrix, false otherwise @@ -211,6 +343,33 @@ && mat[12] === 0 && mat[13] === 0 && mat[14] === 0 && mat[15] === 1); }; + proto.isIdentitySIMD = function () { + var inx4 = SIMD.float32x4.load(this.mat, 0); + var identityx4 = SIMD.float32x4.load(identityMatrix.mat, 0); + var ret = SIMD.float32x4.equal(inx4, identityx4); + if(ret.signMask === 0x00) + return false; + + inx4 = SIMD.float32x4.load(this.mat, 4); + identityx4 = SIMD.float32x4.load(identityMatrix.mat, 4); + ret = SIMD.float32x4.equal(inx4, identityx4); + if(ret.signMask === 0x00) + return false; + + inx4 = SIMD.float32x4.load(this.mat, 8); + identityx4 = SIMD.float32x4.load(identityMatrix.mat, 8); + ret = SIMD.float32x4.equal(inx4, identityx4); + if(ret.signMask === 0x00) + return false; + + inx4 = SIMD.float32x4.load(this.mat, 12); + identityx4 = SIMD.float32x4.load(identityMatrix.mat, 12); + ret = SIMD.float32x4.equal(inx4, identityx4); + if(ret.signMask === 0x00) + return false; + return true; + }; + /** * transpose the current matrix */ @@ -238,6 +397,36 @@ return this; }; + proto.transposeSIMD = function () { + var outArr = this.mat, inArr = this.mat; + var src0 = SIMD.float32x4.load(inArr, 0); + var src1 = SIMD.float32x4.load(inArr, 4); + var src2 = SIMD.float32x4.load(inArr, 8); + var src3 = SIMD.float32x4.load(inArr, 12); + var dst0; + var dst1; + var dst2; + var dst3; + var tmp01; + var tmp23; + + tmp01 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5); + tmp23 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5); + dst0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6); + dst1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7); + + tmp01 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7); + tmp23 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7); + dst2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6); + dst3 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7); + + SIMD.float32x4.store(outArr, 0, dst0); + SIMD.float32x4.store(outArr, 4, dst1); + SIMD.float32x4.store(outArr, 8, dst2); + SIMD.float32x4.store(outArr, 12, dst3); + return this; + }; + /** * Multiplies pM1 with pM2, stores the result in pOut, returns pOut */ @@ -273,6 +462,11 @@ return pOut; }; + cc.kmMat4MultiplySIMD = function (pOut, pM1, pM2) { + pOut = new cc.math.Matrix4(pM1); + return pOut.multiplySIMD(pM2); + }; + /** * current matrix multiplies with other matrix mat4 * @param {cc.math.Matrix4} mat4 @@ -310,6 +504,55 @@ return this; }; + proto.multiplySIMD = function(mat4) { + var a = this.mat; + var b = mat4.mat; + var out = this.mat; + + var a0 = SIMD.float32x4.load(a,0); + var a1 = SIMD.float32x4.load(a,4); + var a2 = SIMD.float32x4.load(a,8); + var a3 = SIMD.float32x4.load(a,12); + var b0 = SIMD.float32x4.load(b, 0); + SIMD.float32x4.store(out, 0, SIMD.float32x4.add( + SIMD.float32x4.mul( + SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3))))); + var b1 = SIMD.float32x4.load(b, 4); + SIMD.float32x4.store(out, 4, SIMD.float32x4.add( + SIMD.float32x4.mul( + SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3))))); + var b2 = SIMD.float32x4.load(b, 8); + SIMD.float32x4.store(out, 8, SIMD.float32x4.add( + SIMD.float32x4.mul( + SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3))))); + var b3 = SIMD.float32x4.load(b, 12); + SIMD.float32x4.store(out, 12, SIMD.float32x4.add( + SIMD.float32x4.mul( + SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3))))); + + return this; + }; + cc.getMat4MultiplyValue = function (pM1, pM2) { var m1 = pM1.mat, m2 = pM2.mat; var mat = new Float32Array(16); @@ -337,6 +580,11 @@ return mat; }; + cc.getMat4MultiplyValueSIMD = function (pM1, pM2) { + var mat = new cc.math.Matrix4(pM1); + return mat.multiplySIMD(pM2); + }; + /** * Assigns the value of pIn to pOut */ @@ -371,6 +619,15 @@ return pOut; }; + cc.kmMat4AssignSIMD = function (pOut, pIn) { + if(pOut == pIn) { + cc.log("cc.kmMat4Assign(): pOut equals pIn");//TODO: ADD SIMD? + return pOut; + } + + return pOut.assignFromSIMD(pIn); + }; + /** * Assigns the value of current matrix from mat4 * @param {cc.math.Matrix4} mat4 @@ -405,6 +662,23 @@ return this; }; + proto.assignFromSIMD = function (mat4) { + if(this == mat4) { + cc.log("cc.mat.Matrix4.assignFrom(): mat4 equals current matrix");//TODO: ADD SIMD? + return this; + } + + var outArr = this.mat; + var inArr = mat4.mat; + + SIMD.float32x4.store(outArr, 0, SIMD.float32x4.load(inArr, 0)); + SIMD.float32x4.store(outArr, 4, SIMD.float32x4.load(inArr, 4)); + SIMD.float32x4.store(outArr, 8, SIMD.float32x4.load(inArr, 8)); + SIMD.float32x4.store(outArr, 12, SIMD.float32x4.load(inArr, 12)); + + return this; + }; + /** * Returns true if current matrix equal mat4 (approximately) * @param {cc.math.Matrix4} mat4 @@ -423,6 +697,40 @@ return true; }; + proto.equalsSIMD = function (mat4) { + if(this === mat4){ + cc.log("cc.kmMat4AreEqual(): pMat1 and pMat2 are same object."); + return true; + } + var m10 = SIMD.float32x4.load(this.mat, 0); + var m20 = SIMD.float32x4.load(mat4.mat, 0); + + var epsilon = SIMD.float32x4.splat(cc.math.EPSILON); + + var ret = SIMD.float32x4.lessThanOrEqual(SIMD.float32x4.abs(SIMD.float32x4.sub(m10, m20)), epsilon); + if (ret.signMask === 0) + return false; + + var m11 = SIMD.float32x4.load(this.mat, 4); + var m21 = SIMD.float32x4.load(mat4.mat, 4); + ret = SIMD.float32x4.lessThanOrEqual(SIMD.float32x4.abs(SIMD.float32x4.sub(m11, m21)), epsilon); + if (ret.signMask === 0) + return false; + + var m12 = SIMD.float32x4.load(this.mat, 8); + var m22 = SIMD.float32x4.load(mat4.mat, 8); + ret = SIMD.float32x4.lessThanOrEqual(SIMD.float32x4.abs(SIMD.float32x4.sub(m12, m22)), epsilon); + if (ret.signMask === 0) + return false; + + var m13 = SIMD.float32x4.load(this.mat, 12); + var m23 = SIMD.float32x4.load(mat4.mat, 12); + ret = SIMD.float32x4.lessThanOrEqual(SIMD.float32x4.abs(SIMD.float32x4.sub(m13, m23)), epsilon); + if (ret.signMask === 0) + return false; + return true; + }; + /** * Builds an X-axis rotation matrix and stores it in matrix, returns matrix, if matrix is null, create a new matrix * @param {Number} radians @@ -825,6 +1133,10 @@ return pOut; }; + cc.kmMat4LookAtSIMD = function (pOut, pEye, pCenter, pUp) { + return pOut.lookAtSIMD(pEye, pCenter, pUp); + }; + var tempMatrix = new cc.math.Matrix4(); // an internal matrix proto.lookAt = function(eyeVec, centerVec, upVec) { var f = new cc.math.Vec3(centerVec), up = new cc.math.Vec3(upVec), mat = this.mat; @@ -858,6 +1170,107 @@ return this; }; + proto.lookAtSIMD = function(eyeVec, centerVec, upVec) { + var out = this.mat; + + var center = SIMD.float32x4(centerVec.x, centerVec.y, centerVec.z, 0.0); + var eye = SIMD.float32x4(eyeVec.x, eyeVec.y, eyeVec.z, 0.0); + var up = SIMD.float32x4(upVec.x, upVec.y, upVec.z, 0.0); + + // cc.kmVec3Subtract(f, pCenter, pEye); + var f = SIMD.float32x4.sub(center, eye); + // cc.kmVec3Normalize(f, f); + var tmp = SIMD.float32x4.mul(f, f); + tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3))); + f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp)); + + // cc.kmVec3Assign(up, pUp); + // cc.kmVec3Normalize(up, up); + tmp = SIMD.float32x4.mul(up, up); + tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3))); + up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp)); + + // cc.kmVec3Cross(s, f, up); + var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)), + SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3))); + // cc.kmVec3Normalize(s, s); + tmp = SIMD.float32x4.mul(s, s); + tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3))); + s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp)); + + // cc.kmVec3Cross(u, s, f); + var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)), + SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3))); + // cc.kmVec3Normalize(s, s); + tmp = SIMD.float32x4.mul(s, s); + tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3))); + s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp)); + + //cc.kmMat4Identity(pOut); + //pOut.mat[0] = s.x; + //pOut.mat[4] = s.y; + //pOut.mat[8] = s.z; + //pOut.mat[1] = u.x; + //pOut.mat[5] = u.y; + //pOut.mat[9] = u.z; + //pOut.mat[2] = -f.x; + //pOut.mat[6] = -f.y; + //pOut.mat[10] = -f.z; + var zero = SIMD.float32x4.splat(0.0); + f = SIMD.float32x4.neg(f); + var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5); + var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5); + var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6); + var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7); + + var tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7); + var tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7); + var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6); + var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0); + + // cc.kmMat4Translation(translate, -pEye.x, -pEye.y, -pEye.z); + var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0); + var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0); + var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0); + var b3 = SIMD.float32x4.neg(eye); + b3 = SIMD.float32x4.withW(b3, 1.0); + + // cc.kmMat4Multiply(pOut, pOut, translate); + SIMD.float32x4.store(out, 0, SIMD.float32x4.add( + SIMD.float32x4.mul( + SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3))))); + SIMD.float32x4.store(out, 4, SIMD.float32x4.add( + SIMD.float32x4.mul( + SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3))))); + SIMD.float32x4.store(out, 8, SIMD.float32x4.add( + SIMD.float32x4.mul( + SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3))))); + SIMD.float32x4.store(out, 12, SIMD.float32x4.add( + SIMD.float32x4.mul( + SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3))))); + return this; + }; + /** * Build a rotation matrix from an axis and an angle. Result is stored in pOut. * pOut is returned. @@ -1007,6 +1420,17 @@ var temp = cc.math.Quaternion.rotationMatrix(rotation); return temp.toAxisAndAngle(); }; + + if(typeof(SIMD) !== 'undefined' && cc.doNotUseSIMD !== true) { + proto.inverse = proto.inverseSIMD; + proto.isIdentity = proto.isIdentitySIMD; + proto.transpose = proto.transposeSIMD; + proto.multiply = proto.multiplySIMD; + proto.getMat4MultiplyValue = proto.getMat4MultiplyValueSIMD; + proto.assignFrom = proto.assignFromSIMD; + proto.equals = proto.equalsSIMD; + proto.lookAt = proto.lookAtSIMD; + } })(cc); diff --git a/cocos2d/kazmath/vec3.js b/cocos2d/kazmath/vec3.js index 282b34aaae..46bb0abea2 100644 --- a/cocos2d/kazmath/vec3.js +++ b/cocos2d/kazmath/vec3.js @@ -136,6 +136,26 @@ return this; }; + proto.transformCoordSIMD = function(mat4){ + var vec = SIMD.float32x4(this.x, this.y, this.z, 0.0); + var mat0 = SIMD.float32x4.load(mat4.mat, 0); + var mat1 = SIMD.float32x4.load(mat4.mat, 4); + var mat2 = SIMD.float32x4.load(mat4.mat, 8); + var mat3 = SIMD.float32x4.load(mat4.mat, 12); + + //cc.kmVec4Transform(v, inV,pM); + var out = SIMD.float32x4.add( + SIMD.float32x4.add(SIMD.float32x4.mul(mat0, SIMD.float32x4.swizzle(vec, 0, 0, 0, 0)), + SIMD.float32x4.mul(mat1, SIMD.float32x4.swizzle(vec, 1, 1, 1, 1))), + SIMD.float32x4.add(SIMD.float32x4.mul(mat2, SIMD.float32x4.swizzle(vec, 2, 2, 2, 2)), + mat3)); + + out = SIMD.float32x4.div(out, SIMD.float32x4.swizzle(out, 3, 3, 3, 3)); + this.fill(out); + + return this; + }; + proto.scale = function(scale){ // = cc.kmVec3Scale this.x *= scale; this.y *= scale; @@ -188,6 +208,10 @@ tyArr[2] = this.z; return tyArr; }; + + if(typeof(SIMD) !== 'undefined' && cc.doNotUseSIMD !== true) { + proto.transformCoord = proto.transformCoordSIMD; + } })(cc); From 244322cc979d5abe6b357671b18fcec1e6d09dc7 Mon Sep 17 00:00:00 2001 From: SPACELAN Date: Tue, 12 May 2015 12:52:54 +0800 Subject: [PATCH 0237/1039] Add SIMD benchmarks for kazmath --- cocos2d/kazmath/simd_benchmark/base.js | 139 ++++++++++++++++++ cocos2d/kazmath/simd_benchmark/index.html | 43 ++++++ .../kazmath/simd_benchmark/kernel-template.js | 64 ++++++++ .../kazmath/simd_benchmark/kmMat4AreEqual.js | 77 ++++++++++ .../kazmath/simd_benchmark/kmMat4Assign.js | 68 +++++++++ .../kazmath/simd_benchmark/kmMat4Inverse.js | 116 +++++++++++++++ .../simd_benchmark/kmMat4IsIdentity.js | 65 ++++++++ .../kazmath/simd_benchmark/kmMat4LookAt.js | 94 ++++++++++++ .../kazmath/simd_benchmark/kmMat4Multiply.js | 74 ++++++++++ .../kazmath/simd_benchmark/kmMat4Transpose.js | 82 +++++++++++ .../simd_benchmark/kmVec3TransformCoord.js | 65 ++++++++ cocos2d/kazmath/simd_benchmark/run.js | 38 +++++ cocos2d/kazmath/simd_benchmark/run_browser.js | 80 ++++++++++ 13 files changed, 1005 insertions(+) create mode 100644 cocos2d/kazmath/simd_benchmark/base.js create mode 100644 cocos2d/kazmath/simd_benchmark/index.html create mode 100644 cocos2d/kazmath/simd_benchmark/kernel-template.js create mode 100644 cocos2d/kazmath/simd_benchmark/kmMat4AreEqual.js create mode 100644 cocos2d/kazmath/simd_benchmark/kmMat4Assign.js create mode 100644 cocos2d/kazmath/simd_benchmark/kmMat4Inverse.js create mode 100644 cocos2d/kazmath/simd_benchmark/kmMat4IsIdentity.js create mode 100644 cocos2d/kazmath/simd_benchmark/kmMat4LookAt.js create mode 100644 cocos2d/kazmath/simd_benchmark/kmMat4Multiply.js create mode 100644 cocos2d/kazmath/simd_benchmark/kmMat4Transpose.js create mode 100644 cocos2d/kazmath/simd_benchmark/kmVec3TransformCoord.js create mode 100644 cocos2d/kazmath/simd_benchmark/run.js create mode 100644 cocos2d/kazmath/simd_benchmark/run_browser.js diff --git a/cocos2d/kazmath/simd_benchmark/base.js b/cocos2d/kazmath/simd_benchmark/base.js new file mode 100644 index 0000000000..d01857c77e --- /dev/null +++ b/cocos2d/kazmath/simd_benchmark/base.js @@ -0,0 +1,139 @@ +// SIMD Kernel Benchmark Harness +// Author: Peter Jensen + +function Benchmark (config) { + this.config = config; + this.initOk = true; // Initialize all properties used on a Benchmark object + this.cleanupOk = true; + this.useAutoIterations = true; + this.autoIterations = 0; + this.actualIterations = 0; + this.simdTime = 0; + this.nonSimdTime = 0; +} + +function Benchmarks () { + this.benchmarks = []; +} + +Benchmarks.prototype.add = function (benchmark) { + this.benchmarks.push (benchmark); + return this.benchmarks.length - 1; +} + +Benchmarks.prototype.runOne = function (benchmark) { + + function timeKernel(kernel, iterations) { + var start, stop; + start = Date.now(); + kernel(iterations); + stop = Date.now(); + return stop - start; + } + + function computeIterations() { + var desiredRuntime = 1000; // milliseconds for longest running kernel + var testIterations = 10; // iterations used to determine time for desiredRuntime + + // Make the slowest kernel run for at least 500ms + var simdTime = timeKernel(benchmark.config.kernelSimd, testIterations); + var nonSimdTime = timeKernel(benchmark.config.kernelNonSimd, testIterations); + var maxTime = simdTime > nonSimdTime ? simdTime : nonSimdTime; + while (maxTime < 500) { + testIterations *= 2; + simdTime = timeKernel(benchmark.config.kernelSimd, testIterations); + nonSimdTime = timeKernel(benchmark.config.kernelNonSimd, testIterations); + maxTime = simdTime > nonSimdTime ? simdTime : nonSimdTime; + } + maxTime = simdTime > nonSimdTime ? simdTime : nonSimdTime; + + // Compute iteration count for 1 second run of slowest kernel + var iterations = Math.ceil(desiredRuntime * testIterations / maxTime); + return iterations; + } + + // Initialize the kernels and check the correctness status + if (!benchmark.config.kernelInit()) { + benchmark.initOk = false; + return false; + } + + // Determine how many iterations to use. + if (benchmark.useAutoIterations) { + benchmark.autoIterations = computeIterations(); + benchmark.actualIterations = benchmark.autoIterations; + } + else { + benchmark.actualIterations = benchmark.config.kernelIterations; + } + + // Run the SIMD kernel + benchmark.simdTime = timeKernel(benchmark.config.kernelSimd, benchmark.actualIterations); + + // Run the non-SIMD kernel + benchmark.nonSimdTime = timeKernel(benchmark.config.kernelNonSimd, benchmark.actualIterations); + + // Do the final sanity check + if (!benchmark.config.kernelCleanup()) { + benchmark.cleanupOk = false; + return false; + } + + return true; +} + +Benchmarks.prototype.report = function (benchmark, outputFunctions) { + + function fillRight(str, width) { + str += ""; // make sure it's a string + while (str.length < width) { + str += " "; + } + return str; + } + + function fillLeft(str, width) { + str += ""; // make sure it's a string + while (str.length < width) { + str = " " + str; + } + return str; + } + + if (!benchmark.initOk) { + outputFunctions.notifyError(fillRight(benchmark.config.kernelName + ": ", 23) + "FAILED INIT"); + return; + } + if (!benchmark.cleanupOk) { + outputFunctions.notifyError(fillRight(benchmark.config.kernelName + ": ", 23) + "FAILED CLEANUP"); + return; + } + + var ratio = benchmark.nonSimdTime / benchmark.simdTime; + ratio = ratio.toFixed(2); + outputFunctions.notifyResult( + fillRight(benchmark.config.kernelName + ": ", 23) + + "Iterations(" + fillLeft(benchmark.actualIterations, 10) + ")" + + ", SIMD(" + fillLeft(benchmark.simdTime + "ms)", 8) + + ", Non-SIMD(" + fillLeft(benchmark.nonSimdTime + "ms)", 8) + + ", Speedup(" + ratio + ")"); + outputFunctions.timeData.labels.push(benchmark.config.kernelName); + outputFunctions.timeData.datasets[0].data.push(benchmark.simdTime); + outputFunctions.timeData.datasets[1].data.push(benchmark.nonSimdTime); + outputFunctions.speedupData.labels.push(benchmark.config.kernelName); + outputFunctions.speedupData.datasets[0].data.push(ratio); +} + +Benchmarks.prototype.runAll = function (outputFunctions, useAutoIterations) { + if (typeof useAutoIterations === "undefined") { + useAutoIterations = false; + } + for (var i = 0, n = this.benchmarks.length; i < n; ++i) { + var benchmark = this.benchmarks[i]; + benchmark.useAutoIterations = useAutoIterations; + this.runOne(benchmark); + this.report(benchmark, outputFunctions); + } +} + +var benchmarks = new Benchmarks (); diff --git a/cocos2d/kazmath/simd_benchmark/index.html b/cocos2d/kazmath/simd_benchmark/index.html new file mode 100644 index 0000000000..50f077c661 --- /dev/null +++ b/cocos2d/kazmath/simd_benchmark/index.html @@ -0,0 +1,43 @@ + + + + + Kazmath SIMD benchmarks + + + +

Running benchmarks...

+
+
+

+ +
+
+

+ +
+
+
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/cocos2d/kazmath/simd_benchmark/kernel-template.js b/cocos2d/kazmath/simd_benchmark/kernel-template.js new file mode 100644 index 0000000000..d7c377585d --- /dev/null +++ b/cocos2d/kazmath/simd_benchmark/kernel-template.js @@ -0,0 +1,64 @@ +// Kernel template +// Author: Peter Jensen +(function () { + + // Kernel configuration + var kernelConfig = { + kernelName: "Test", + kernelInit: init, + kernelCleanup: cleanup, + kernelSimd: simd, + kernelNonSimd: nonSimd, + kernelIterations: 100000000 + }; + + // Hook up to the harness + benchmarks.add (new Benchmark (kernelConfig)); + + // Kernel Initializer + function init () { + // Do initial sanity check and initialize data for the kernels. + // The sanity check should verify that the simd and nonSimd results + // are the same. + // It is recommended to do minimal object creation in the kernels + // themselves. If global data needs to be initialized, here would + // be the place to do it. + // If the sanity checks fails the kernels will not be executed + // Returns: + // true: First run (unoptimized) of the kernels passed + // false: First run (unoptimized) of the kernels failed + return simd (1) === nonSimd (1); + } + + // Kernel Cleanup + function cleanup () { + // Do final sanity check and perform cleanup. + // This function is called when all the kernel iterations have been + // executed, so they should be in their final optimized version. The + // sanity check done during initialization will probably be of the + // initial unoptimized version. + // Returns: + // true: Last run (optimized) of the kernels passed + // false: last run (optimized) of the kernels failed + return simd (1) === nonSimd (1); + } + + // SIMD version of the kernel + function simd (n) { + var s = 0; + for (var i = 0; i < n; ++i) { + s += i; + } + return s; + } + + // Non SIMD version of the kernel + function nonSimd (n) { + var s = 0; + for (var i = 0; i < n; ++i) { + s += i; + } + return s; + } + +} ()); diff --git a/cocos2d/kazmath/simd_benchmark/kmMat4AreEqual.js b/cocos2d/kazmath/simd_benchmark/kmMat4AreEqual.js new file mode 100644 index 0000000000..a3dee727ac --- /dev/null +++ b/cocos2d/kazmath/simd_benchmark/kmMat4AreEqual.js @@ -0,0 +1,77 @@ +// kmMat4AreEqual + +(function () { + + // Kernel configuration + var kernelConfig = { + kernelName: "kmMat4AreEqual", + kernelInit: init, + kernelCleanup: cleanup, + kernelSimd: simd, + kernelNonSimd: nonSimd, + kernelIterations: 10000 + }; + + // Hook up to the harness + benchmarks.add(new Benchmark(kernelConfig)); + + // Benchmark data, initialization and kernel functions + var T1 = new cc.kmMat4(); + var T2 = new cc.kmMat4(); + var T1x4 = new cc.kmMat4(); + var T2x4 = new cc.kmMat4(); + var areEqual, areEqualSIMD; + + function equals(A, B) { + for (var i = 0; i < 16; ++i) { + if (A[i] != B[i]) + return false; + } + return true; + } + + function init() { + T1.mat[0] = 1.0; + T1.mat[5] = 1.0; + T1.mat[10] = 1.0; + T1.mat[15] = 1.0; + + T2.mat[0] = 1.0; + T2.mat[5] = 1.0; + T2.mat[10] = 1.0; + T2.mat[15] = 1.0; + + T1x4.mat[0] = 1.0; + T1x4.mat[5] = 1.0; + T1x4.mat[10] = 1.0; + T1x4.mat[15] = 1.0; + + T2x4.mat[0] = 1.0; + T2x4.mat[5] = 1.0; + T2x4.mat[10] = 1.0; + T2x4.mat[15] = 1.0; + + nonSimd(1); + simd(1); + + return equals(T1.mat, T1x4.mat) && equals(T2.mat, T2x4.mat) && (areEqual === areEqualSIMD); + + } + + function cleanup() { + return init(); // Sanity checking before and after are the same + } + + function nonSimd(n) { + for (var i = 0; i < n; i++) { + areEqual = T1.equals(T2); + } + } + + function simd(n) { + for (var i = 0; i < n; i++) { + areEqualSIMD = T1x4.equalsSIMD(T2x4); + } + } + +} ()); diff --git a/cocos2d/kazmath/simd_benchmark/kmMat4Assign.js b/cocos2d/kazmath/simd_benchmark/kmMat4Assign.js new file mode 100644 index 0000000000..e8e386f781 --- /dev/null +++ b/cocos2d/kazmath/simd_benchmark/kmMat4Assign.js @@ -0,0 +1,68 @@ +// kmMat4Assign + +(function () { + + // Kernel configuration + var kernelConfig = { + kernelName: "kmMat4Assign", + kernelInit: init, + kernelCleanup: cleanup, + kernelSimd: simd, + kernelNonSimd: nonSimd, + kernelIterations: 10000 + }; + + // Hook up to the harness + benchmarks.add(new Benchmark(kernelConfig)); + + // Benchmark data, initialization and kernel functions + var T1 = new cc.kmMat4(); + var T2 = new cc.kmMat4(); + var T1x4 = new cc.kmMat4(); + var T2x4 = new cc.kmMat4(); + + function equals(A, B) { + for (var i = 0; i < 16; ++i) { + if (A[i] != B[i]) + return false; + } + return true; + } + + function init() { + T1.mat[0] = 1.0; + T1.mat[5] = 1.0; + T1.mat[10] = 1.0; + T1.mat[15] = 1.0; + + T1x4.mat[0] = 1.0; + T1x4.mat[5] = 1.0; + T1x4.mat[10] = 1.0; + T1x4.mat[15] = 1.0; + + nonSimd(1); + simd(1); + + return equals(T1.mat, T1x4.mat) && equals(T2.mat, T2x4.mat); + + } + + function cleanup() { + return init(); // Sanity checking before and after are the same + } + + function nonSimd(n) { + for (var i = 0; i < n; i++) { + //cc.kmMat4Assign(T2, T1); + T2.assignFrom(T1); + } + } + + function simd(n) { + for (var i = 0; i < n; i++) { + //cc.kmMat4AssignSIMD(T2x4, T1x4); + T2x4.assignFromSIMD(T1x4); + } + } + +} ()); diff --git a/cocos2d/kazmath/simd_benchmark/kmMat4Inverse.js b/cocos2d/kazmath/simd_benchmark/kmMat4Inverse.js new file mode 100644 index 0000000000..212dff1af1 --- /dev/null +++ b/cocos2d/kazmath/simd_benchmark/kmMat4Inverse.js @@ -0,0 +1,116 @@ +// kmMat4Inverse + +(function () { + + // Kernel configuration + var kernelConfig = { + kernelName: "kmMat4Inverse", + kernelInit: init, + kernelCleanup: cleanup, + kernelSimd: simd, + kernelNonSimd: nonSimd, + kernelIterations: 10000 + }; + + // Hook up to the harness + benchmarks.add(new Benchmark(kernelConfig)); + + // Benchmark data, initialization and kernel functions + var src = new cc.kmMat4(); + var dst = new cc.kmMat4(); + var srcx4 = new cc.kmMat4(); + var dstx4 = new cc.kmMat4(); + var ident = new Float32Array( + [1,0,0,0, + 0,1,0,0, + 0,0,1,0, + 0,0,0,1]); + + function equals(A, B) { + for (var i = 0; i < 16; ++i) { + if (Math.abs (A[i] - B[i]) > 5) + return false; + } + return true; + } + + function initMatrix(matrix) { + // These values were chosen somewhat randomly, but they will at least yield a solution. + matrix [0] = 0; matrix[1] = 1; matrix[2] = 2; matrix[3] = 3; + matrix [4] = -1; matrix[5] = -2; matrix[6] = -3; matrix[7] = -4; + matrix [8] = 0; matrix[9] = 0; matrix[10] = 2; matrix[11] = 3; + matrix [12] = -1; matrix[13] = -2; matrix[14] = 0; matrix[15] = -4; + } + + function mulMatrix(dst, op1, op2) { + for (var r = 0; r < 4; ++r) { + for (var c = 0; c < 4; ++c) { + var ri = 4*r; + dst[ri + c] = op1[ri]*op2[c] + op1[ri+1]*op2[c+4] + op1[ri+2]*op2[c+8] + op1[ri+3]*op2[c+12]; + } + } + } + + function printMatrix(matrix, str) { + print('--------matrix ' + str + '----------'); + for (var r = 0; r < 4; ++r) { + var str = ""; + var ri = r*4; + for (var c = 0; c < 4; ++c) { + var value = matrix[ri + c]; + str += " " + value.toFixed(2); + } + print(str); + } + } + + function checkMatrix(src, dst) { + // when multiplied with the src matrix it should yield the identity matrix + var tmp = new Float32Array(16); + mulMatrix(tmp, src, dst); + for (var i = 0; i < 16; ++i) { + if (Math.abs (tmp[i] - ident[i]) > 0.00001) { + return false; + } + } + return true; + } + + function init() { + initMatrix(src.mat); + // printMatrix(src); + nonSimd(1); + // printMatrix(dst); + if (!checkMatrix(src.mat, dst.mat)) { + return false; + } + + initMatrix(srcx4.mat); + simd(1); + // printMatrix(dst); + if (!checkMatrix(srcx4.mat, dstx4.mat)) { + return false; + } + + return true; + } + + function cleanup() { + return init(); // Sanity checking before and after are the same + } + + function nonSimd(n) { + for (var i = 0; i < n; i++) { + //cc.kmMat4Inverse(dst, src); + dst = src.inverse(); + } + } + + function simd(n) { + for (var i = 0; i < n; i++) { + //cc.kmMat4InverseSIMD(dstx4, srcx4); + dstx4 = srcx4.inverseSIMD(); + } + } + +} ()); diff --git a/cocos2d/kazmath/simd_benchmark/kmMat4IsIdentity.js b/cocos2d/kazmath/simd_benchmark/kmMat4IsIdentity.js new file mode 100644 index 0000000000..9ab17ac744 --- /dev/null +++ b/cocos2d/kazmath/simd_benchmark/kmMat4IsIdentity.js @@ -0,0 +1,65 @@ +// kmMat4IsIdentity + +(function () { + + // Kernel configuration + var kernelConfig = { + kernelName: "kmMat4IsIdentity", + kernelInit: init, + kernelCleanup: cleanup, + kernelSimd: simd, + kernelNonSimd: nonSimd, + kernelIterations: 10000 + }; + + // Hook up to the harness + benchmarks.add(new Benchmark(kernelConfig)); + + // Benchmark data, initialization and kernel functions + var T1 = new cc.kmMat4(); + var T1x4 = new cc.kmMat4(); + var isIdentity, isIdentitySIMD; + + function equals(A, B) { + for (var i = 0; i < 16; ++i) { + if (A[i] != B[i]) + return false; + } + return true; + } + + function init() { + T1.mat[0] = 1.0; + T1.mat[5] = 1.0; + T1.mat[10] = 1.0; + T1.mat[15] = 1.0; + + T1x4.mat[0] = 1.0; + T1x4.mat[5] = 1.0; + T1x4.mat[10] = 1.0; + T1x4.mat[15] = 1.0; + + nonSimd(1); + simd(1); + + return equals(T1.mat, T1x4.mat) && (isIdentity === isIdentitySIMD); + + } + + function cleanup() { + return init(); // Sanity checking before and after are the same + } + + function nonSimd(n) { + for (var i = 0; i < n; i++) { + isIdentity = T1.isIdentity(); + } + } + + function simd(n) { + for (var i = 0; i < n; i++) { + isIdentitySIMD = T1x4.isIdentitySIMD(); + } + } + +} ()); diff --git a/cocos2d/kazmath/simd_benchmark/kmMat4LookAt.js b/cocos2d/kazmath/simd_benchmark/kmMat4LookAt.js new file mode 100644 index 0000000000..1015ad14eb --- /dev/null +++ b/cocos2d/kazmath/simd_benchmark/kmMat4LookAt.js @@ -0,0 +1,94 @@ +// kmMat4LookAt + +(function () { + + // Kernel configuration + var kernelConfig = { + kernelName: "kmMat4LookAt", + kernelInit: init, + kernelCleanup: cleanup, + kernelSimd: simd, + kernelNonSimd: nonSimd, + kernelIterations: 10000 + }; + + // Hook up to the harness + benchmarks.add(new Benchmark(kernelConfig)); + + // Benchmark data, initialization and kernel functions + var eye = new cc.kmVec3(), center = new cc.kmVec3(), up = new cc.kmVec3(); + var T1 = new cc.kmMat4(); + var eye1 = new cc.kmVec3(), center1 = new cc.kmVec3(), up1 = new cc.kmVec3(); + var T1x4 = new cc.kmMat4(); + + function printMatrix(matrix) { + print('--------matrix----------'); + for (var r = 0; r < 4; ++r) { + var str = ""; + var ri = r*4; + for (var c = 0; c < 4; ++c) { + var value = matrix[ri + c]; + str += " " + value.toFixed(2); + } + print(str); + } + } + + function equals(A, B) { + for (var i = 0; i < 16; ++i) { + if (Math.abs (A[i] - B[i]) > 0.001) { + return false; + } + } + return true; + } + + function init() { + + eye.fill(0, 1, 2); + center.fill(2, 1, 0); + up.fill(1, 1, 1); + + eye1.fill(0, 1, 2); + center1.fill(2, 1, 0); + up1.fill(1, 1, 1); + /* + eye1.data[0] = 0; + eye1.data[1] = 1; + eye1.data[2] = 2; + + center1.data[0] = 2; + center1.data[1] = 1; + center1.data[2] = 0; + + up1.data[0] = 1; + up1.data[1] = 1; + up1.data[2] = 1; + */ + nonSimd(1); + //printMatrix(T1.mat); + simd(1); + //printMatrix(T1x4.mat); + + return equals(T1.mat, T1x4.mat); + } + + function cleanup() { + return init(); // Sanity checking before and after are the same + } + + function nonSimd(n) { + for (var i = 0; i < n; i++) { + //cc.kmMat4LookAt(T1, eye, center, up); + T1.lookAt(eye, center, up); + } + } + + function simd(n) { + for (var i = 0; i < n; i++) { + //cc.kmMat4LookAtSIMD(T1x4, eye1, center1, up1); + T1x4.lookAtSIMD(eye1, center1, up1); + } + } + +} ()); diff --git a/cocos2d/kazmath/simd_benchmark/kmMat4Multiply.js b/cocos2d/kazmath/simd_benchmark/kmMat4Multiply.js new file mode 100644 index 0000000000..325b6f95bf --- /dev/null +++ b/cocos2d/kazmath/simd_benchmark/kmMat4Multiply.js @@ -0,0 +1,74 @@ +// kmMat4Multiply + +(function () { + + // Kernel configuration + var kernelConfig = { + kernelName: "kmMat4Multiply", + kernelInit: init, + kernelCleanup: cleanup, + kernelSimd: simd, + kernelNonSimd: nonSimd, + kernelIterations: 10000 + }; + + // Hook up to the harness + benchmarks.add(new Benchmark(kernelConfig)); + + // Benchmark data, initialization and kernel functions + var T1 = new cc.kmMat4(); + var T2 = new cc.kmMat4(); + var T1x4 = new cc.kmMat4(); + var T2x4 = new cc.kmMat4(); + + function equals(A, B) { + for (var i = 0; i < 16; ++i) { + if (A[i] != B[i]) + return false; + } + return true; + } + + function init() { + T1.mat[0] = 1.0; + T1.mat[5] = 1.0; + T1.mat[10] = 1.0; + T1.mat[15] = 1.0; + + T2.mat[0] = 1.0; + T2.mat[5] = 1.0; + T2.mat[10] = 1.0; + T2.mat[15] = 1.0; + + T1x4.mat[0] = 1.0; + T1x4.mat[5] = 1.0; + T1x4.mat[10] = 1.0; + T1x4.mat[15] = 1.0; + + T2x4.mat[0] = 1.0; + T2x4.mat[5] = 1.0; + T2x4.mat[10] = 1.0; + T2x4.mat[15] = 1.0; + + nonSimd(1); + simd(1); + return equals(T1.mat, T1x4.mat) && equals(T2.mat, T2x4.mat); + } + + function cleanup() { + return init(); // Sanity checking before and after are the same + } + + function nonSimd(n) { + for (var i = 0; i < n; i++) { + T1.multiply(T2); + } + } + + function simd(n) { + for (var i = 0; i < n; i++) { + T1x4.multiplySIMD(T2x4); + } + } + +} ()); diff --git a/cocos2d/kazmath/simd_benchmark/kmMat4Transpose.js b/cocos2d/kazmath/simd_benchmark/kmMat4Transpose.js new file mode 100644 index 0000000000..cd1b776bf0 --- /dev/null +++ b/cocos2d/kazmath/simd_benchmark/kmMat4Transpose.js @@ -0,0 +1,82 @@ +// kmMat4Transpose + +(function () { + + // Kernel configuration + var kernelConfig = { + kernelName: "kmMat4Transpose", + kernelInit: init, + kernelCleanup: cleanup, + kernelSimd: simd, + kernelNonSimd: nonSimd, + kernelIterations: 10000 + }; + + // Hook up to the harness + benchmarks.add(new Benchmark(kernelConfig)); + + // Benchmark data, initialization and kernel functions + var T1 = new cc.kmMat4(); + var T2 = new cc.kmMat4(); + var T1x4 = new cc.kmMat4(); + var T2x4 = new cc.kmMat4(); + + function equals(A, B) { + for (var i = 0; i < 16; ++i) { + if (A[i] != B[i]) + return false; + } + return true; + } + + function printMatrix(matrix) { + print('--------matrix----------'); + for (var r = 0; r < 4; ++r) { + var str = ""; + var ri = r*4; + for (var c = 0; c < 4; ++c) { + var value = matrix[ri + c]; + str += " " + value.toFixed(2); + } + print(str); + } + } + + function init() { + T1.mat [0] = 0; T1.mat[1] = 1; T1.mat[2] = 2; T1.mat[3] = 3; + T1.mat [4] = -1; T1.mat[5] = -2; T1.mat[6] = -3; T1.mat[7] = -4; + T1.mat [8] = 0; T1.mat[9] = 0; T1.mat[10] = 2; T1.mat[11] = 3; + T1.mat [12] = -1; T1.mat[13] = -2; T1.mat[14] = 0; T1.mat[15] = -4; + + T1x4.mat [0] = 0; T1x4.mat[1] = 1; T1x4.mat[2] = 2; T1x4.mat[3] = 3; + T1x4.mat [4] = -1; T1x4.mat[5] = -2; T1x4.mat[6] = -3; T1x4.mat[7] = -4; + T1x4.mat [8] = 0; T1x4.mat[9] = 0; T1x4.mat[10] = 2; T1x4.mat[11] = 3; + T1x4.mat [12] = -1; T1x4.mat[13] = -2; T1x4.mat[14] = 0; T1x4.mat[15] = -4; + + nonSimd(1); + //printMatrix(T2.mat); + simd(1); + //printMatrix(T2x4.mat); + return equals(T1.mat, T1x4.mat) && equals(T2.mat, T2x4.mat); + + } + + function cleanup() { + return init(); // Sanity checking before and after are the same + } + + function nonSimd(n) { + for (var i = 0; i < n; i++) { + T2 = T1.transpose(); + //T1.transpose(); + } + } + + function simd(n) { + for (var i = 0; i < n; i++) { + T2x4 = T1x4.transposeSIMD(); + //T1x4.transposeSIMD(); + } + } + +} ()); diff --git a/cocos2d/kazmath/simd_benchmark/kmVec3TransformCoord.js b/cocos2d/kazmath/simd_benchmark/kmVec3TransformCoord.js new file mode 100644 index 0000000000..541a926c9d --- /dev/null +++ b/cocos2d/kazmath/simd_benchmark/kmVec3TransformCoord.js @@ -0,0 +1,65 @@ +// kmVec3TransformCoord + +(function () { + + // Kernel configuration + var kernelConfig = { + kernelName: "kmVec3TransformCoord", + kernelInit: init, + kernelCleanup: cleanup, + kernelSimd: simd, + kernelNonSimd: nonSimd, + kernelIterations: 10000 + }; + + // Hook up to the harness + benchmarks.add(new Benchmark(kernelConfig)); + + // Benchmark data, initialization and kernel functions + var V = new cc.kmVec3(); + var T = new cc.kmMat4(); + var Out = new cc.kmVec3(); + var Vx4 = new cc.kmVec3(); + var Tx4 = new cc.kmMat4(); + var Outx4 = new cc.kmVec3(); + + function init() { + T.mat[0] = 1.0; + T.mat[5] = 1.0; + T.mat[10] = 1.0; + T.mat[15] = 1.0; + + V.fill(0.0, 1.0, 0.0); + + Tx4.mat[0] = 1.0; + Tx4.mat[5] = 1.0; + Tx4.mat[10] = 1.0; + Tx4.mat[15] = 1.0; + + Vx4.fill(0.0, 1.0, 0.0); + + nonSimd(1); + simd(1); + //console.log(V); + //console.log(Vx4); + return V.equals(Vx4); + + } + + function cleanup() { + return init(); // Sanity checking before and after are the same + } + + function nonSimd(n) { + for (var i = 0; i < n; i++) { + V.transformCoord(T); + } + } + + function simd(n) { + for (var i = 0; i < n; i++) { + Vx4.transformCoordSIMD(Tx4); + } + } + +} ()); diff --git a/cocos2d/kazmath/simd_benchmark/run.js b/cocos2d/kazmath/simd_benchmark/run.js new file mode 100644 index 0000000000..1a1b253bd4 --- /dev/null +++ b/cocos2d/kazmath/simd_benchmark/run.js @@ -0,0 +1,38 @@ +"use strict" + +var cc = {}; + +load ('base.js'); + +load ('../utility.js'); +load ('../vec3.js'); +load ('../vec4.js'); +load ('../mat4.js'); + +// load individual benchmarks +load ('kernel-template.js'); +load ('kmMat4Multiply.js'); +load ('kmMat4Assign.js'); +load ('kmMat4AreEqual.js'); +load ('kmMat4Inverse.js'); +load ('kmMat4IsIdentity.js'); +load ('kmMat4Transpose.js'); +load ('kmMat4LookAt.js'); +load ('kmVec3TransformCoord.js'); + +function printResult (str) { + print (str); +} + +function printError (str) { + print (str); +} + +function printScore (str) { + print (str); +} + +benchmarks.runAll ({notifyResult: printResult, + notifyError: printError, + notifyScore: printScore}, + true); diff --git a/cocos2d/kazmath/simd_benchmark/run_browser.js b/cocos2d/kazmath/simd_benchmark/run_browser.js new file mode 100644 index 0000000000..5d2d0cdd74 --- /dev/null +++ b/cocos2d/kazmath/simd_benchmark/run_browser.js @@ -0,0 +1,80 @@ +var echo = document.getElementById('echo'); + +function printResult(str) { + console.log(str); + echo.innerHTML += str + '
'; +} + +function printError(str) { + console.log(str); + echo.innerHTML += str + '
'; +} + +function printScore(str) { + console.log(str); + echo.innerHTML += str + '
'; +} + +var timeData = { + labels: [], + datasets: [ + { + labels: 'Non-SIMD', + fillColor: "rgba(220,220,220,0.5)", + strokeColor: "rgba(220,220,220,0.8)", + highlightFill: "rgba(220,220,220,0.75)", + highlightStroke: "rgba(220,220,220,1)", + data: [] + }, + { + labels: 'SIMD', + fillColor: "rgba(151,187,205,0.5)", + strokeColor: "rgba(151,187,205,0.8)", + highlightFill: "rgba(151,187,205,0.75)", + highlightStroke: "rgba(151,187,205,1)", + data: [] + } + ] +}; + +var speedupData ={ + labels: [], + datasets: [ + { + labels: 'SIMD', + fillColor: "rgba(151,187,205,0.5)", + strokeColor: "rgba(151,187,205,0.8)", + highlightFill: "rgba(151,187,205,0.75)", + highlightStroke: "rgba(151,187,205,1)", + data: [] + } + ] +}; + +window.onload = function() { + if (typeof(SIMD) === 'undefined') { + var head = document.getElementById('head'); + head.innerHTML = 'SIMD is not implemented in your browser, stops.'; + return; + } + console.log('Running benchmarks.'); + benchmarks.runAll({notifyResult: printResult, + notifyError: printError, + notifyScore: printScore, + timeData: timeData, + speedupData: speedupData}, true); + document.getElementById('head').innerHTML = 'Results'; + document.getElementById('time').innerHTML = 'Time'; + document.getElementById('speedup').innerHTML = 'Speedup'; + var ctx1 = document.getElementById("canvasTime").getContext("2d"); + window.Bar1 = new Chart(ctx1).Bar(timeData, { + scaleLabel: "<%=value%>ms", + responsive: true + }); + var ctx2 = document.getElementById("canvasSpeedup").getContext("2d"); + window.Bar2 = new Chart(ctx2).Bar(speedupData, { + scaleLabel: " <%=value%>", + responsive: true + }); + console.log('Benchmarks completed.'); +}; From 5f14f68e7067884b1621db303d36f59a0658d13e Mon Sep 17 00:00:00 2001 From: Ningxin Hu Date: Fri, 15 May 2015 12:51:39 +0800 Subject: [PATCH 0238/1039] Add cc.sys.doNotUseSIMD It is used to control using SIMD.js optimziation or not. --- CCBoot.js | 5 +++++ cocos2d/kazmath/mat4.js | 2 +- cocos2d/kazmath/simd_benchmark/index.html | 5 +++-- cocos2d/kazmath/vec3.js | 2 +- 4 files changed, 10 insertions(+), 4 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index 1be2d4ff3b..b4a63d66c2 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -1822,6 +1822,11 @@ cc._initSys = function (config, CONFIG_KEY) { sys.openURL = function(url){ window.open(url); } + + /** + * Don't use SIMD.js optimization + */ + sys.doNotUseSIMD = false; }; //+++++++++++++++++++++++++something about sys end+++++++++++++++++++++++++++++ diff --git a/cocos2d/kazmath/mat4.js b/cocos2d/kazmath/mat4.js index 41eb3677c4..a090fb9bc2 100644 --- a/cocos2d/kazmath/mat4.js +++ b/cocos2d/kazmath/mat4.js @@ -1421,7 +1421,7 @@ return temp.toAxisAndAngle(); }; - if(typeof(SIMD) !== 'undefined' && cc.doNotUseSIMD !== true) { + if(typeof(SIMD) !== 'undefined' && cc.sys.doNotUseSIMD !== true) { proto.inverse = proto.inverseSIMD; proto.isIdentity = proto.isIdentitySIMD; proto.transpose = proto.transposeSIMD; diff --git a/cocos2d/kazmath/simd_benchmark/index.html b/cocos2d/kazmath/simd_benchmark/index.html index 50f077c661..19135bb2d6 100644 --- a/cocos2d/kazmath/simd_benchmark/index.html +++ b/cocos2d/kazmath/simd_benchmark/index.html @@ -19,8 +19,9 @@

diff --git a/cocos2d/kazmath/vec3.js b/cocos2d/kazmath/vec3.js index 46bb0abea2..eb6264a6f6 100644 --- a/cocos2d/kazmath/vec3.js +++ b/cocos2d/kazmath/vec3.js @@ -209,7 +209,7 @@ return tyArr; }; - if(typeof(SIMD) !== 'undefined' && cc.doNotUseSIMD !== true) { + if(typeof(SIMD) !== 'undefined' && cc.sys.doNotUseSIMD !== true) { proto.transformCoord = proto.transformCoordSIMD; } })(cc); From ff3d162c4d803fcc04b2ac1b9f7629d14bf80c40 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 15 May 2015 15:11:44 +0800 Subject: [PATCH 0239/1039] Adaptation model and fix mistakes in grammar --- cocos2d/transitions/CCTransition.js | 2 +- extensions/ccui/uiwidgets/UIWebView.js | 21 ++++++++++++++++++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/cocos2d/transitions/CCTransition.js b/cocos2d/transitions/CCTransition.js index b2dd0a1f1e..204f3897a7 100644 --- a/cocos2d/transitions/CCTransition.js +++ b/cocos2d/transitions/CCTransition.js @@ -879,7 +879,7 @@ cc.TransitionShrinkGrow = cc.TransitionScene.extend(/** @lends cc.TransitionShri var scaleOut = cc.scaleTo(this._duration, 0.01); var scaleIn = cc.scaleTo(this._duration, 1.0); - this._inScene.runAction(cc.sequence(this.easeActionWithAction(scaleIn), cc.callFunc(this.finish, this)); + this._inScene.runAction(cc.sequence(this.easeActionWithAction(scaleIn), cc.callFunc(this.finish, this))); this._outScene.runAction(this.easeActionWithAction(scaleOut)); }, diff --git a/extensions/ccui/uiwidgets/UIWebView.js b/extensions/ccui/uiwidgets/UIWebView.js index f64e11908a..e6ea298a44 100644 --- a/extensions/ccui/uiwidgets/UIWebView.js +++ b/extensions/ccui/uiwidgets/UIWebView.js @@ -79,6 +79,8 @@ ccui.WebView = ccui.Widget.extend({ * go back */ goBack: function(){ + if(ccui.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; @@ -91,6 +93,8 @@ ccui.WebView = ccui.Widget.extend({ * go forward */ goForward: function(){ + if(ccui.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; @@ -195,7 +199,7 @@ ccui.WebView.EventType = { (function(){ - ccui.WebView.polyfill = { + var polyfill = ccui.WebView.polyfill = { devicePixelRatio: false, enableDiv: false }; @@ -203,6 +207,17 @@ ccui.WebView.EventType = { if(cc.sys.os === cc.sys.OS_IOS) ccui.WebView.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){ @@ -222,6 +237,10 @@ ccui.WebView.EventType = { }else{ this._div = this._iframe = document.createElement("iframe"); } + + if(polyfill.enableBG) + this._div.style["background"] = "#FFF"; + this._iframe.addEventListener("load", function(){ cc.eventManager.dispatchCustomEvent(ccui.WebView.EventType.LOADED); }); From 1fe8e9314cbf8d0653340f75646eb5a001a294c0 Mon Sep 17 00:00:00 2001 From: Ningxin Hu Date: Fri, 15 May 2015 15:39:56 +0800 Subject: [PATCH 0240/1039] Add vec3SIMD.js, mat4SIMD.js and SIMDPolyfill.js --- CCBoot.js | 5 - cocos2d/kazmath/SIMDPolyfill.js | 78 ++++++ cocos2d/kazmath/mat4.js | 424 ------------------------------- cocos2d/kazmath/mat4SIMD.js | 428 ++++++++++++++++++++++++++++++++ cocos2d/kazmath/vec3.js | 24 -- cocos2d/kazmath/vec3SIMD.js | 51 ++++ moduleConfig.json | 3 + 7 files changed, 560 insertions(+), 453 deletions(-) create mode 100644 cocos2d/kazmath/SIMDPolyfill.js create mode 100644 cocos2d/kazmath/mat4SIMD.js create mode 100644 cocos2d/kazmath/vec3SIMD.js diff --git a/CCBoot.js b/CCBoot.js index b4a63d66c2..1be2d4ff3b 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -1822,11 +1822,6 @@ cc._initSys = function (config, CONFIG_KEY) { sys.openURL = function(url){ window.open(url); } - - /** - * Don't use SIMD.js optimization - */ - sys.doNotUseSIMD = false; }; //+++++++++++++++++++++++++something about sys end+++++++++++++++++++++++++++++ diff --git a/cocos2d/kazmath/SIMDPolyfill.js b/cocos2d/kazmath/SIMDPolyfill.js new file mode 100644 index 0000000000..7c65b0a214 --- /dev/null +++ b/cocos2d/kazmath/SIMDPolyfill.js @@ -0,0 +1,78 @@ +/** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. + Copyright (c) 2008, Luke Benstead. + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +(function(cc) { + var _useSIMD = false; + + var mat4Proto = cc.math.Matrix4.prototype; + var mat4Inverse = mat4Proto.inverse; + var mat4IsIdentity = mat4Proto.isIdentity; + var mat4Transpose = mat4Proto.transpose; + var mat4Multiply = mat4Proto.multiply; + var mat4GetMat4MultiplyValue = mat4Proto.getMat4MultiplyValue; + var mat4AssignFrom = mat4Proto.assignFrom; + var mat4Equals = mat4Proto.equals; + var mat4LookAt = mat4Proto.lookAt; + + var vec3Proto = cc.math.Vec3.prototype; + var vec3TransformCoord = vec3Proto.transformCoord; + + function _isEnabledSIMD () { + return _useSIMD; + } + + function _enableSIMD (enable) { + if(typeof(SIMD) === 'undefined') + return; + + if (enable) { + mat4Proto.inverse = mat4Proto.inverseSIMD; + mat4Proto.isIdentity = mat4Proto.isIdentitySIMD; + mat4Proto.transpose = mat4Proto.transposeSIMD; + mat4Proto.multiply = mat4Proto.multiplySIMD; + mat4Proto.getMat4MultiplyValue = mat4Proto.getMat4MultiplyValueSIMD; + mat4Proto.assignFrom = mat4Proto.assignFromSIMD; + mat4Proto.equals = mat4Proto.equalsSIMD; + mat4Proto.lookAt = mat4Proto.lookAtSIMD; + vec3Proto.transformCoord = vec3Proto.transformCoordSIMD; + } else { + mat4Proto.inverse = mat4Inverse; + mat4Proto.isIdentity = mat4IsIdentity; + mat4Proto.transpose = mat4Transpose; + mat4Proto.multiply = mat4Multiply; + mat4Proto.getMat4MultiplyValue = mat4GetMat4MultiplyValue; + mat4Proto.assignFrom = mat4AssignFrom; + mat4Proto.equals = mat4Equals; + mat4Proto.lookAt = mat4LookAt; + vec3Proto.transformCoord = vec3TransformCoord; + } + _useSIMD = enable; + } + + cc.defineGetterSetter(cc.sys, "useSIMD", _isEnabledSIMD, _enableSIMD); +})(cc); \ No newline at end of file diff --git a/cocos2d/kazmath/mat4.js b/cocos2d/kazmath/mat4.js index a090fb9bc2..d211589531 100644 --- a/cocos2d/kazmath/mat4.js +++ b/cocos2d/kazmath/mat4.js @@ -188,11 +188,6 @@ return pOut; }; - cc.kmMat4InverseSIMD = function (pOut, pM) { - pOut = pM.inverseSIMD(); - return pOut; - }; - /** * Calculates the inverse of current matrix. * @returns {cc.math.Matrix4} Returns null if there is no inverse, else returns a new inverse matrix object @@ -204,133 +199,6 @@ return null; return inv; }; - - proto.inverseSIMD = function(){ - var inv = new cc.math.Matrix4(); - var src = this.mat; - var dest = inv.mat; - var src0, src1, src2, src3; - var row0, row1, row2, row3; - var tmp1; - var minor0, minor1, minor2, minor3; - var det; - - // Load the 4 rows - var src0 = SIMD.float32x4.load(src, 0); - var src1 = SIMD.float32x4.load(src, 4); - var src2 = SIMD.float32x4.load(src, 8); - var src3 = SIMD.float32x4.load(src, 12); - - // Transpose the source matrix. Sort of. Not a true transpose operation - - tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5); - row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5); - row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6); - row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7); - - tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7); - row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7); - row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6); - row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7); - - // This is a true transposition, but it will lead to an incorrect result - - //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5); - //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5); - //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6); - //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7); - - //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7); - //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7); - //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6); - //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7); - - // ---- - tmp1 = SIMD.float32x4.mul(row2, row3); - tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001 - minor0 = SIMD.float32x4.mul(row1, tmp1); - minor1 = SIMD.float32x4.mul(row0, tmp1); - tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110 - minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0); - minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1); - minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110 - - // ---- - tmp1 = SIMD.float32x4.mul(row1, row2); - tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001 - minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0); - minor3 = SIMD.float32x4.mul(row0, tmp1); - tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110 - minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1)); - minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3); - minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110 - - // ---- - tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110 - tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001 - row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110 - minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0); - minor2 = SIMD.float32x4.mul(row0, tmp1); - tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110 - minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1)); - minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2); - minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110 - - // ---- - tmp1 = SIMD.float32x4.mul(row0, row1); - tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001 - minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2); - minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3); - tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110 - minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2); - minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1)); - - // ---- - tmp1 = SIMD.float32x4.mul(row0, row3); - tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001 - minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1)); - minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2); - tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110 - minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1); - minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1)); - - // ---- - tmp1 = SIMD.float32x4.mul(row0, row2); - tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001 - minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1); - minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1)); - tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110 - minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1)); - minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3); - - // Compute determinant - det = SIMD.float32x4.mul(row0, minor0); - det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110 - det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001 - tmp1 = SIMD.float32x4.reciprocalApproximation(det); - det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1))); - det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0); - - // These shuffles aren't necessary if the faulty transposition is done - // up at the top of this function. - //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3); - //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3); - //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3); - //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3); - - // Compute final values by multiplying with 1/det - minor0 = SIMD.float32x4.mul(det, minor0); - minor1 = SIMD.float32x4.mul(det, minor1); - minor2 = SIMD.float32x4.mul(det, minor2); - minor3 = SIMD.float32x4.mul(det, minor3); - - SIMD.float32x4.store(dest, 0, minor0); - SIMD.float32x4.store(dest, 4, minor1); - SIMD.float32x4.store(dest, 8, minor2); - SIMD.float32x4.store(dest, 12, minor3); - - return inv; - }; /** * Returns true if current matrix is an identity matrix, false otherwise @@ -343,33 +211,6 @@ && mat[12] === 0 && mat[13] === 0 && mat[14] === 0 && mat[15] === 1); }; - proto.isIdentitySIMD = function () { - var inx4 = SIMD.float32x4.load(this.mat, 0); - var identityx4 = SIMD.float32x4.load(identityMatrix.mat, 0); - var ret = SIMD.float32x4.equal(inx4, identityx4); - if(ret.signMask === 0x00) - return false; - - inx4 = SIMD.float32x4.load(this.mat, 4); - identityx4 = SIMD.float32x4.load(identityMatrix.mat, 4); - ret = SIMD.float32x4.equal(inx4, identityx4); - if(ret.signMask === 0x00) - return false; - - inx4 = SIMD.float32x4.load(this.mat, 8); - identityx4 = SIMD.float32x4.load(identityMatrix.mat, 8); - ret = SIMD.float32x4.equal(inx4, identityx4); - if(ret.signMask === 0x00) - return false; - - inx4 = SIMD.float32x4.load(this.mat, 12); - identityx4 = SIMD.float32x4.load(identityMatrix.mat, 12); - ret = SIMD.float32x4.equal(inx4, identityx4); - if(ret.signMask === 0x00) - return false; - return true; - }; - /** * transpose the current matrix */ @@ -397,36 +238,6 @@ return this; }; - proto.transposeSIMD = function () { - var outArr = this.mat, inArr = this.mat; - var src0 = SIMD.float32x4.load(inArr, 0); - var src1 = SIMD.float32x4.load(inArr, 4); - var src2 = SIMD.float32x4.load(inArr, 8); - var src3 = SIMD.float32x4.load(inArr, 12); - var dst0; - var dst1; - var dst2; - var dst3; - var tmp01; - var tmp23; - - tmp01 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5); - tmp23 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5); - dst0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6); - dst1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7); - - tmp01 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7); - tmp23 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7); - dst2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6); - dst3 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7); - - SIMD.float32x4.store(outArr, 0, dst0); - SIMD.float32x4.store(outArr, 4, dst1); - SIMD.float32x4.store(outArr, 8, dst2); - SIMD.float32x4.store(outArr, 12, dst3); - return this; - }; - /** * Multiplies pM1 with pM2, stores the result in pOut, returns pOut */ @@ -462,11 +273,6 @@ return pOut; }; - cc.kmMat4MultiplySIMD = function (pOut, pM1, pM2) { - pOut = new cc.math.Matrix4(pM1); - return pOut.multiplySIMD(pM2); - }; - /** * current matrix multiplies with other matrix mat4 * @param {cc.math.Matrix4} mat4 @@ -504,55 +310,6 @@ return this; }; - proto.multiplySIMD = function(mat4) { - var a = this.mat; - var b = mat4.mat; - var out = this.mat; - - var a0 = SIMD.float32x4.load(a,0); - var a1 = SIMD.float32x4.load(a,4); - var a2 = SIMD.float32x4.load(a,8); - var a3 = SIMD.float32x4.load(a,12); - var b0 = SIMD.float32x4.load(b, 0); - SIMD.float32x4.store(out, 0, SIMD.float32x4.add( - SIMD.float32x4.mul( - SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), - SIMD.float32x4.add( - SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), - SIMD.float32x4.add( - SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), - SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3))))); - var b1 = SIMD.float32x4.load(b, 4); - SIMD.float32x4.store(out, 4, SIMD.float32x4.add( - SIMD.float32x4.mul( - SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), - SIMD.float32x4.add( - SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), - SIMD.float32x4.add( - SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), - SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3))))); - var b2 = SIMD.float32x4.load(b, 8); - SIMD.float32x4.store(out, 8, SIMD.float32x4.add( - SIMD.float32x4.mul( - SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), - SIMD.float32x4.add( - SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), - SIMD.float32x4.add( - SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), - SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3))))); - var b3 = SIMD.float32x4.load(b, 12); - SIMD.float32x4.store(out, 12, SIMD.float32x4.add( - SIMD.float32x4.mul( - SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), - SIMD.float32x4.add( - SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), - SIMD.float32x4.add( - SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), - SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3))))); - - return this; - }; - cc.getMat4MultiplyValue = function (pM1, pM2) { var m1 = pM1.mat, m2 = pM2.mat; var mat = new Float32Array(16); @@ -580,11 +337,6 @@ return mat; }; - cc.getMat4MultiplyValueSIMD = function (pM1, pM2) { - var mat = new cc.math.Matrix4(pM1); - return mat.multiplySIMD(pM2); - }; - /** * Assigns the value of pIn to pOut */ @@ -619,15 +371,6 @@ return pOut; }; - cc.kmMat4AssignSIMD = function (pOut, pIn) { - if(pOut == pIn) { - cc.log("cc.kmMat4Assign(): pOut equals pIn");//TODO: ADD SIMD? - return pOut; - } - - return pOut.assignFromSIMD(pIn); - }; - /** * Assigns the value of current matrix from mat4 * @param {cc.math.Matrix4} mat4 @@ -662,23 +405,6 @@ return this; }; - proto.assignFromSIMD = function (mat4) { - if(this == mat4) { - cc.log("cc.mat.Matrix4.assignFrom(): mat4 equals current matrix");//TODO: ADD SIMD? - return this; - } - - var outArr = this.mat; - var inArr = mat4.mat; - - SIMD.float32x4.store(outArr, 0, SIMD.float32x4.load(inArr, 0)); - SIMD.float32x4.store(outArr, 4, SIMD.float32x4.load(inArr, 4)); - SIMD.float32x4.store(outArr, 8, SIMD.float32x4.load(inArr, 8)); - SIMD.float32x4.store(outArr, 12, SIMD.float32x4.load(inArr, 12)); - - return this; - }; - /** * Returns true if current matrix equal mat4 (approximately) * @param {cc.math.Matrix4} mat4 @@ -697,40 +423,6 @@ return true; }; - proto.equalsSIMD = function (mat4) { - if(this === mat4){ - cc.log("cc.kmMat4AreEqual(): pMat1 and pMat2 are same object."); - return true; - } - var m10 = SIMD.float32x4.load(this.mat, 0); - var m20 = SIMD.float32x4.load(mat4.mat, 0); - - var epsilon = SIMD.float32x4.splat(cc.math.EPSILON); - - var ret = SIMD.float32x4.lessThanOrEqual(SIMD.float32x4.abs(SIMD.float32x4.sub(m10, m20)), epsilon); - if (ret.signMask === 0) - return false; - - var m11 = SIMD.float32x4.load(this.mat, 4); - var m21 = SIMD.float32x4.load(mat4.mat, 4); - ret = SIMD.float32x4.lessThanOrEqual(SIMD.float32x4.abs(SIMD.float32x4.sub(m11, m21)), epsilon); - if (ret.signMask === 0) - return false; - - var m12 = SIMD.float32x4.load(this.mat, 8); - var m22 = SIMD.float32x4.load(mat4.mat, 8); - ret = SIMD.float32x4.lessThanOrEqual(SIMD.float32x4.abs(SIMD.float32x4.sub(m12, m22)), epsilon); - if (ret.signMask === 0) - return false; - - var m13 = SIMD.float32x4.load(this.mat, 12); - var m23 = SIMD.float32x4.load(mat4.mat, 12); - ret = SIMD.float32x4.lessThanOrEqual(SIMD.float32x4.abs(SIMD.float32x4.sub(m13, m23)), epsilon); - if (ret.signMask === 0) - return false; - return true; - }; - /** * Builds an X-axis rotation matrix and stores it in matrix, returns matrix, if matrix is null, create a new matrix * @param {Number} radians @@ -1133,10 +825,6 @@ return pOut; }; - cc.kmMat4LookAtSIMD = function (pOut, pEye, pCenter, pUp) { - return pOut.lookAtSIMD(pEye, pCenter, pUp); - }; - var tempMatrix = new cc.math.Matrix4(); // an internal matrix proto.lookAt = function(eyeVec, centerVec, upVec) { var f = new cc.math.Vec3(centerVec), up = new cc.math.Vec3(upVec), mat = this.mat; @@ -1170,107 +858,6 @@ return this; }; - proto.lookAtSIMD = function(eyeVec, centerVec, upVec) { - var out = this.mat; - - var center = SIMD.float32x4(centerVec.x, centerVec.y, centerVec.z, 0.0); - var eye = SIMD.float32x4(eyeVec.x, eyeVec.y, eyeVec.z, 0.0); - var up = SIMD.float32x4(upVec.x, upVec.y, upVec.z, 0.0); - - // cc.kmVec3Subtract(f, pCenter, pEye); - var f = SIMD.float32x4.sub(center, eye); - // cc.kmVec3Normalize(f, f); - var tmp = SIMD.float32x4.mul(f, f); - tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3))); - f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp)); - - // cc.kmVec3Assign(up, pUp); - // cc.kmVec3Normalize(up, up); - tmp = SIMD.float32x4.mul(up, up); - tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3))); - up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp)); - - // cc.kmVec3Cross(s, f, up); - var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)), - SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3))); - // cc.kmVec3Normalize(s, s); - tmp = SIMD.float32x4.mul(s, s); - tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3))); - s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp)); - - // cc.kmVec3Cross(u, s, f); - var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)), - SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3))); - // cc.kmVec3Normalize(s, s); - tmp = SIMD.float32x4.mul(s, s); - tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3))); - s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp)); - - //cc.kmMat4Identity(pOut); - //pOut.mat[0] = s.x; - //pOut.mat[4] = s.y; - //pOut.mat[8] = s.z; - //pOut.mat[1] = u.x; - //pOut.mat[5] = u.y; - //pOut.mat[9] = u.z; - //pOut.mat[2] = -f.x; - //pOut.mat[6] = -f.y; - //pOut.mat[10] = -f.z; - var zero = SIMD.float32x4.splat(0.0); - f = SIMD.float32x4.neg(f); - var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5); - var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5); - var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6); - var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7); - - var tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7); - var tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7); - var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6); - var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0); - - // cc.kmMat4Translation(translate, -pEye.x, -pEye.y, -pEye.z); - var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0); - var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0); - var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0); - var b3 = SIMD.float32x4.neg(eye); - b3 = SIMD.float32x4.withW(b3, 1.0); - - // cc.kmMat4Multiply(pOut, pOut, translate); - SIMD.float32x4.store(out, 0, SIMD.float32x4.add( - SIMD.float32x4.mul( - SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), - SIMD.float32x4.add( - SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), - SIMD.float32x4.add( - SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), - SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3))))); - SIMD.float32x4.store(out, 4, SIMD.float32x4.add( - SIMD.float32x4.mul( - SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), - SIMD.float32x4.add( - SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), - SIMD.float32x4.add( - SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), - SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3))))); - SIMD.float32x4.store(out, 8, SIMD.float32x4.add( - SIMD.float32x4.mul( - SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), - SIMD.float32x4.add( - SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), - SIMD.float32x4.add( - SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), - SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3))))); - SIMD.float32x4.store(out, 12, SIMD.float32x4.add( - SIMD.float32x4.mul( - SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), - SIMD.float32x4.add( - SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), - SIMD.float32x4.add( - SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), - SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3))))); - return this; - }; - /** * Build a rotation matrix from an axis and an angle. Result is stored in pOut. * pOut is returned. @@ -1420,17 +1007,6 @@ var temp = cc.math.Quaternion.rotationMatrix(rotation); return temp.toAxisAndAngle(); }; - - if(typeof(SIMD) !== 'undefined' && cc.sys.doNotUseSIMD !== true) { - proto.inverse = proto.inverseSIMD; - proto.isIdentity = proto.isIdentitySIMD; - proto.transpose = proto.transposeSIMD; - proto.multiply = proto.multiplySIMD; - proto.getMat4MultiplyValue = proto.getMat4MultiplyValueSIMD; - proto.assignFrom = proto.assignFromSIMD; - proto.equals = proto.equalsSIMD; - proto.lookAt = proto.lookAtSIMD; - } })(cc); diff --git a/cocos2d/kazmath/mat4SIMD.js b/cocos2d/kazmath/mat4SIMD.js new file mode 100644 index 0000000000..f716de796b --- /dev/null +++ b/cocos2d/kazmath/mat4SIMD.js @@ -0,0 +1,428 @@ +/** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. + Copyright (c) 2008, Luke Benstead. + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +(function(cc) { + var proto = cc.math.Matrix4.prototype; + + cc.kmMat4InverseSIMD = function (pOut, pM) { + pOut = pM.inverseSIMD(); + return pOut; + }; + + proto.inverseSIMD = function(){ + var inv = new cc.math.Matrix4(); + var src = this.mat; + var dest = inv.mat; + var src0, src1, src2, src3; + var row0, row1, row2, row3; + var tmp1; + var minor0, minor1, minor2, minor3; + var det; + + // Load the 4 rows + var src0 = SIMD.float32x4.load(src, 0); + var src1 = SIMD.float32x4.load(src, 4); + var src2 = SIMD.float32x4.load(src, 8); + var src3 = SIMD.float32x4.load(src, 12); + + // Transpose the source matrix. Sort of. Not a true transpose operation + + tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5); + row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5); + row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6); + row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7); + + tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7); + row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7); + row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6); + row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7); + + // ---- + tmp1 = SIMD.float32x4.mul(row2, row3); + tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001 + minor0 = SIMD.float32x4.mul(row1, tmp1); + minor1 = SIMD.float32x4.mul(row0, tmp1); + tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110 + minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0); + minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1); + minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110 + + // ---- + tmp1 = SIMD.float32x4.mul(row1, row2); + tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001 + minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0); + minor3 = SIMD.float32x4.mul(row0, tmp1); + tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110 + minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1)); + minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3); + minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110 + + // ---- + tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110 + tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001 + row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110 + minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0); + minor2 = SIMD.float32x4.mul(row0, tmp1); + tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110 + minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1)); + minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2); + minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110 + + // ---- + tmp1 = SIMD.float32x4.mul(row0, row1); + tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001 + minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2); + minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3); + tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110 + minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2); + minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1)); + + // ---- + tmp1 = SIMD.float32x4.mul(row0, row3); + tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001 + minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1)); + minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2); + tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110 + minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1); + minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1)); + + // ---- + tmp1 = SIMD.float32x4.mul(row0, row2); + tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001 + minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1); + minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1)); + tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110 + minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1)); + minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3); + + // Compute determinant + det = SIMD.float32x4.mul(row0, minor0); + det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110 + det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001 + tmp1 = SIMD.float32x4.reciprocalApproximation(det); + det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1))); + det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0); + + // Compute final values by multiplying with 1/det + minor0 = SIMD.float32x4.mul(det, minor0); + minor1 = SIMD.float32x4.mul(det, minor1); + minor2 = SIMD.float32x4.mul(det, minor2); + minor3 = SIMD.float32x4.mul(det, minor3); + + SIMD.float32x4.store(dest, 0, minor0); + SIMD.float32x4.store(dest, 4, minor1); + SIMD.float32x4.store(dest, 8, minor2); + SIMD.float32x4.store(dest, 12, minor3); + + return inv; + }; + + var identityMatrix = new cc.math.Matrix4().identity(); + proto.isIdentitySIMD = function () { + var inx4 = SIMD.float32x4.load(this.mat, 0); + var identityx4 = SIMD.float32x4.load(identityMatrix.mat, 0); + var ret = SIMD.float32x4.equal(inx4, identityx4); + if(ret.signMask === 0x00) + return false; + + inx4 = SIMD.float32x4.load(this.mat, 4); + identityx4 = SIMD.float32x4.load(identityMatrix.mat, 4); + ret = SIMD.float32x4.equal(inx4, identityx4); + if(ret.signMask === 0x00) + return false; + + inx4 = SIMD.float32x4.load(this.mat, 8); + identityx4 = SIMD.float32x4.load(identityMatrix.mat, 8); + ret = SIMD.float32x4.equal(inx4, identityx4); + if(ret.signMask === 0x00) + return false; + + inx4 = SIMD.float32x4.load(this.mat, 12); + identityx4 = SIMD.float32x4.load(identityMatrix.mat, 12); + ret = SIMD.float32x4.equal(inx4, identityx4); + if(ret.signMask === 0x00) + return false; + return true; + }; + + proto.transposeSIMD = function () { + var outArr = this.mat, inArr = this.mat; + var src0 = SIMD.float32x4.load(inArr, 0); + var src1 = SIMD.float32x4.load(inArr, 4); + var src2 = SIMD.float32x4.load(inArr, 8); + var src3 = SIMD.float32x4.load(inArr, 12); + var dst0; + var dst1; + var dst2; + var dst3; + var tmp01; + var tmp23; + + tmp01 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5); + tmp23 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5); + dst0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6); + dst1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7); + + tmp01 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7); + tmp23 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7); + dst2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6); + dst3 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7); + + SIMD.float32x4.store(outArr, 0, dst0); + SIMD.float32x4.store(outArr, 4, dst1); + SIMD.float32x4.store(outArr, 8, dst2); + SIMD.float32x4.store(outArr, 12, dst3); + return this; + }; + + cc.kmMat4MultiplySIMD = function (pOut, pM1, pM2) { + pOut = new cc.math.Matrix4(pM1); + return pOut.multiplySIMD(pM2); + }; + + proto.multiplySIMD = function(mat4) { + var a = this.mat; + var b = mat4.mat; + var out = this.mat; + + var a0 = SIMD.float32x4.load(a,0); + var a1 = SIMD.float32x4.load(a,4); + var a2 = SIMD.float32x4.load(a,8); + var a3 = SIMD.float32x4.load(a,12); + var b0 = SIMD.float32x4.load(b, 0); + SIMD.float32x4.store(out, 0, SIMD.float32x4.add( + SIMD.float32x4.mul( + SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3))))); + var b1 = SIMD.float32x4.load(b, 4); + SIMD.float32x4.store(out, 4, SIMD.float32x4.add( + SIMD.float32x4.mul( + SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3))))); + var b2 = SIMD.float32x4.load(b, 8); + SIMD.float32x4.store(out, 8, SIMD.float32x4.add( + SIMD.float32x4.mul( + SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3))))); + var b3 = SIMD.float32x4.load(b, 12); + SIMD.float32x4.store(out, 12, SIMD.float32x4.add( + SIMD.float32x4.mul( + SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3))))); + + return this; + }; + + cc.getMat4MultiplyValueSIMD = function (pM1, pM2) { + var mat = new cc.math.Matrix4(pM1); + return mat.multiplySIMD(pM2); + }; + + cc.kmMat4AssignSIMD = function (pOut, pIn) { + if(pOut == pIn) { + cc.log("cc.kmMat4Assign(): pOut equals pIn");//TODO: ADD SIMD? + return pOut; + } + + return pOut.assignFromSIMD(pIn); + }; + + proto.assignFromSIMD = function (mat4) { + if(this == mat4) { + cc.log("cc.mat.Matrix4.assignFrom(): mat4 equals current matrix");//TODO: ADD SIMD? + return this; + } + + var outArr = this.mat; + var inArr = mat4.mat; + + SIMD.float32x4.store(outArr, 0, SIMD.float32x4.load(inArr, 0)); + SIMD.float32x4.store(outArr, 4, SIMD.float32x4.load(inArr, 4)); + SIMD.float32x4.store(outArr, 8, SIMD.float32x4.load(inArr, 8)); + SIMD.float32x4.store(outArr, 12, SIMD.float32x4.load(inArr, 12)); + + return this; + }; + + proto.equalsSIMD = function (mat4) { + if(this === mat4){ + cc.log("cc.kmMat4AreEqual(): pMat1 and pMat2 are same object."); + return true; + } + var m10 = SIMD.float32x4.load(this.mat, 0); + var m20 = SIMD.float32x4.load(mat4.mat, 0); + + var epsilon = SIMD.float32x4.splat(cc.math.EPSILON); + + var ret = SIMD.float32x4.lessThanOrEqual(SIMD.float32x4.abs(SIMD.float32x4.sub(m10, m20)), epsilon); + if (ret.signMask === 0) + return false; + + var m11 = SIMD.float32x4.load(this.mat, 4); + var m21 = SIMD.float32x4.load(mat4.mat, 4); + ret = SIMD.float32x4.lessThanOrEqual(SIMD.float32x4.abs(SIMD.float32x4.sub(m11, m21)), epsilon); + if (ret.signMask === 0) + return false; + + var m12 = SIMD.float32x4.load(this.mat, 8); + var m22 = SIMD.float32x4.load(mat4.mat, 8); + ret = SIMD.float32x4.lessThanOrEqual(SIMD.float32x4.abs(SIMD.float32x4.sub(m12, m22)), epsilon); + if (ret.signMask === 0) + return false; + + var m13 = SIMD.float32x4.load(this.mat, 12); + var m23 = SIMD.float32x4.load(mat4.mat, 12); + ret = SIMD.float32x4.lessThanOrEqual(SIMD.float32x4.abs(SIMD.float32x4.sub(m13, m23)), epsilon); + if (ret.signMask === 0) + return false; + return true; + }; + + cc.kmMat4LookAtSIMD = function (pOut, pEye, pCenter, pUp) { + return pOut.lookAtSIMD(pEye, pCenter, pUp); + }; + + proto.lookAtSIMD = function(eyeVec, centerVec, upVec) { + var out = this.mat; + + var center = SIMD.float32x4(centerVec.x, centerVec.y, centerVec.z, 0.0); + var eye = SIMD.float32x4(eyeVec.x, eyeVec.y, eyeVec.z, 0.0); + var up = SIMD.float32x4(upVec.x, upVec.y, upVec.z, 0.0); + + // cc.kmVec3Subtract(f, pCenter, pEye); + var f = SIMD.float32x4.sub(center, eye); + // cc.kmVec3Normalize(f, f); + var tmp = SIMD.float32x4.mul(f, f); + tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3))); + f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp)); + + // cc.kmVec3Assign(up, pUp); + // cc.kmVec3Normalize(up, up); + tmp = SIMD.float32x4.mul(up, up); + tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3))); + up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp)); + + // cc.kmVec3Cross(s, f, up); + var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)), + SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3))); + // cc.kmVec3Normalize(s, s); + tmp = SIMD.float32x4.mul(s, s); + tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3))); + s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp)); + + // cc.kmVec3Cross(u, s, f); + var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)), + SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3))); + // cc.kmVec3Normalize(s, s); + tmp = SIMD.float32x4.mul(s, s); + tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3))); + s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp)); + + //cc.kmMat4Identity(pOut); + //pOut.mat[0] = s.x; + //pOut.mat[4] = s.y; + //pOut.mat[8] = s.z; + //pOut.mat[1] = u.x; + //pOut.mat[5] = u.y; + //pOut.mat[9] = u.z; + //pOut.mat[2] = -f.x; + //pOut.mat[6] = -f.y; + //pOut.mat[10] = -f.z; + var zero = SIMD.float32x4.splat(0.0); + f = SIMD.float32x4.neg(f); + var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5); + var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5); + var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6); + var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7); + + var tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7); + var tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7); + var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6); + var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0); + + // cc.kmMat4Translation(translate, -pEye.x, -pEye.y, -pEye.z); + var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0); + var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0); + var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0); + var b3 = SIMD.float32x4.neg(eye); + b3 = SIMD.float32x4.withW(b3, 1.0); + + // cc.kmMat4Multiply(pOut, pOut, translate); + SIMD.float32x4.store(out, 0, SIMD.float32x4.add( + SIMD.float32x4.mul( + SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3))))); + SIMD.float32x4.store(out, 4, SIMD.float32x4.add( + SIMD.float32x4.mul( + SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3))))); + SIMD.float32x4.store(out, 8, SIMD.float32x4.add( + SIMD.float32x4.mul( + SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3))))); + SIMD.float32x4.store(out, 12, SIMD.float32x4.add( + SIMD.float32x4.mul( + SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), + SIMD.float32x4.add( + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), + SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3))))); + return this; + }; + + +})(cc); diff --git a/cocos2d/kazmath/vec3.js b/cocos2d/kazmath/vec3.js index eb6264a6f6..282b34aaae 100644 --- a/cocos2d/kazmath/vec3.js +++ b/cocos2d/kazmath/vec3.js @@ -136,26 +136,6 @@ return this; }; - proto.transformCoordSIMD = function(mat4){ - var vec = SIMD.float32x4(this.x, this.y, this.z, 0.0); - var mat0 = SIMD.float32x4.load(mat4.mat, 0); - var mat1 = SIMD.float32x4.load(mat4.mat, 4); - var mat2 = SIMD.float32x4.load(mat4.mat, 8); - var mat3 = SIMD.float32x4.load(mat4.mat, 12); - - //cc.kmVec4Transform(v, inV,pM); - var out = SIMD.float32x4.add( - SIMD.float32x4.add(SIMD.float32x4.mul(mat0, SIMD.float32x4.swizzle(vec, 0, 0, 0, 0)), - SIMD.float32x4.mul(mat1, SIMD.float32x4.swizzle(vec, 1, 1, 1, 1))), - SIMD.float32x4.add(SIMD.float32x4.mul(mat2, SIMD.float32x4.swizzle(vec, 2, 2, 2, 2)), - mat3)); - - out = SIMD.float32x4.div(out, SIMD.float32x4.swizzle(out, 3, 3, 3, 3)); - this.fill(out); - - return this; - }; - proto.scale = function(scale){ // = cc.kmVec3Scale this.x *= scale; this.y *= scale; @@ -208,10 +188,6 @@ tyArr[2] = this.z; return tyArr; }; - - if(typeof(SIMD) !== 'undefined' && cc.sys.doNotUseSIMD !== true) { - proto.transformCoord = proto.transformCoordSIMD; - } })(cc); diff --git a/cocos2d/kazmath/vec3SIMD.js b/cocos2d/kazmath/vec3SIMD.js new file mode 100644 index 0000000000..0bf4ff4b87 --- /dev/null +++ b/cocos2d/kazmath/vec3SIMD.js @@ -0,0 +1,51 @@ +/** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. + Copyright (c) 2008, Luke Benstead. + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + (function(cc) { + var proto = cc.math.Vec3.prototype; + + proto.transformCoordSIMD = function(mat4){ + var vec = SIMD.float32x4(this.x, this.y, this.z, 0.0); + var mat0 = SIMD.float32x4.load(mat4.mat, 0); + var mat1 = SIMD.float32x4.load(mat4.mat, 4); + var mat2 = SIMD.float32x4.load(mat4.mat, 8); + var mat3 = SIMD.float32x4.load(mat4.mat, 12); + + //cc.kmVec4Transform(v, inV,pM); + var out = SIMD.float32x4.add( + SIMD.float32x4.add(SIMD.float32x4.mul(mat0, SIMD.float32x4.swizzle(vec, 0, 0, 0, 0)), + SIMD.float32x4.mul(mat1, SIMD.float32x4.swizzle(vec, 1, 1, 1, 1))), + SIMD.float32x4.add(SIMD.float32x4.mul(mat2, SIMD.float32x4.swizzle(vec, 2, 2, 2, 2)), + mat3)); + + out = SIMD.float32x4.div(out, SIMD.float32x4.swizzle(out, 3, 3, 3, 3)); + this.fill(out); + + return this; + }; +})(cc); diff --git a/moduleConfig.json b/moduleConfig.json index a089e198d8..726b9105d8 100644 --- a/moduleConfig.json +++ b/moduleConfig.json @@ -144,6 +144,9 @@ "cocos2d/kazmath/plane.js", "cocos2d/kazmath/quaternion.js", "cocos2d/kazmath/aabb.js", + "cocos2d/kazmath/vec3SIMD.js", + "cocos2d/kazmath/mat4SIMD.js", + "cocos2d/kazmath/SIMDPolyfill.js", "cocos2d/kazmath/gl/mat4stack.js", "cocos2d/kazmath/gl/matrix.js" ], From 32ea37829ff3aa403628be539d350992cd5a318a Mon Sep 17 00:00:00 2001 From: Ningxin Hu Date: Fri, 15 May 2015 15:55:45 +0800 Subject: [PATCH 0241/1039] Update kazmath simd_benchmark accordingly --- cocos2d/kazmath/simd_benchmark/index.html | 6 +++--- cocos2d/kazmath/simd_benchmark/run.js | 2 ++ 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/cocos2d/kazmath/simd_benchmark/index.html b/cocos2d/kazmath/simd_benchmark/index.html index 19135bb2d6..5b115d91c9 100644 --- a/cocos2d/kazmath/simd_benchmark/index.html +++ b/cocos2d/kazmath/simd_benchmark/index.html @@ -19,14 +19,14 @@

+ + diff --git a/cocos2d/kazmath/simd_benchmark/run.js b/cocos2d/kazmath/simd_benchmark/run.js index 1a1b253bd4..8441ae1eda 100644 --- a/cocos2d/kazmath/simd_benchmark/run.js +++ b/cocos2d/kazmath/simd_benchmark/run.js @@ -8,6 +8,8 @@ load ('../utility.js'); load ('../vec3.js'); load ('../vec4.js'); load ('../mat4.js'); +load ('../vec3SIMD.js'); +load ('../mat4SIMD.js'); // load individual benchmarks load ('kernel-template.js'); From b9e38ad88f99b8aa2a2e72e850a88391d18c2ead Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 15 May 2015 16:02:39 +0800 Subject: [PATCH 0242/1039] Add notes --- extensions/ccui/uiwidgets/UIWebView.js | 30 ++++++++++++++++++-------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/extensions/ccui/uiwidgets/UIWebView.js b/extensions/ccui/uiwidgets/UIWebView.js index e6ea298a44..684c7f5fe1 100644 --- a/extensions/ccui/uiwidgets/UIWebView.js +++ b/extensions/ccui/uiwidgets/UIWebView.js @@ -52,6 +52,10 @@ ccui.WebView = ccui.Widget.extend({ stopLoading: function(){ cc.log("Web does not support loading"); }, + + /** + * Reload the WebView + */ reload: function(){ var iframe = this._renderCmd._iframe; if(iframe){ @@ -105,7 +109,7 @@ ccui.WebView = ccui.Widget.extend({ /** * In the webview execution within a period of js string - * @param str + * @param {String} str */ evaluateJS: function(str){ var iframe = this._renderCmd._iframe; @@ -128,24 +132,20 @@ ccui.WebView = ccui.Widget.extend({ /** * The binding event - * @param event string: load | loading | error Or: ccui.WebView.EventType - * @param callback + * @param {ccui.WebView.EventType} ccui.WebView.EventType + * @param {Function} callback */ addEventListener: function(event, callback){ - if(!/^ui_webview_/.test(event)) - event = "ui_webview_" + event; return cc.eventManager.addCustomListener(event, callback); }, /** * Delete events - * @param event - * @param callbackOrListener + * @param {ccui.WebView.EventType} event + * @param {Function|Listener} callbackOrListener */ removeEventListener: function(event, callbackOrListener){ var map, list; - if(!/^ui_webview_/.test(event)) - event = "ui_webview_" + event; if(typeof callbackOrListener === "function"){ map = cc.eventManager._listenersMap[event]; if(map){ @@ -175,6 +175,11 @@ ccui.WebView = ccui.Widget.extend({ return new ccui.WebView.RenderCmd(this); }, + /** + * Set the contentSize + * @param {Number} w + * @param {Number} h + */ setContentSize: function(w, h){ ccui.Widget.prototype.setContentSize.call(this, w, h); if(h === undefined){ @@ -184,6 +189,9 @@ ccui.WebView = ccui.Widget.extend({ this._renderCmd.changeSize(w, h); }, + /** + * remove node + */ cleanup: function(){ this._renderCmd.removeDom(); this.stopAllActions(); @@ -191,6 +199,10 @@ ccui.WebView = ccui.Widget.extend({ } }); +/** + * The WebView support list of events + * @type {{LOADING: string, LOADED: string, ERROR: string}} + */ ccui.WebView.EventType = { LOADING: "ui_webview_loading", LOADED: "ui_webview_load", From e3afcc11a35af5feed51418976076a92a5b35f6d Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 15 May 2015 16:12:09 +0800 Subject: [PATCH 0243/1039] Add notes and fix some small problems --- extensions/ccui/uiwidgets/UIVideoPlayer.js | 16 +++++++++------ extensions/ccui/uiwidgets/UIWebView.js | 24 ++++++++-------------- 2 files changed, 18 insertions(+), 22 deletions(-) diff --git a/extensions/ccui/uiwidgets/UIVideoPlayer.js b/extensions/ccui/uiwidgets/UIVideoPlayer.js index 3fdbcef822..f3e6cca5f3 100644 --- a/extensions/ccui/uiwidgets/UIVideoPlayer.js +++ b/extensions/ccui/uiwidgets/UIVideoPlayer.js @@ -202,6 +202,10 @@ ccui.VideoPlayer = ccui.Widget.extend({ }); +/** + * The VideoPlayer support list of events + * @type {{PLAYING: string, PAUSED: string, STOPPED: string, COMPLETED: string}} + */ ccui.VideoPlayer.EventType = { PLAYING: "ui_video_play", PAUSED: "ui_video_pause", @@ -215,7 +219,7 @@ ccui.VideoPlayer.EventType = { * @devicePixelRatio Whether you need to consider devicePixelRatio calculated position * @event To get the data using events */ - video.polyfill = { + video._polyfill = { devicePixelRatio: false, event: "canplay", canPlayType: [] @@ -224,14 +228,14 @@ ccui.VideoPlayer.EventType = { (function(){ var dom = document.createElement("video"); if(dom.canPlayType("video/ogg")) - video.polyfill.canPlayType.push(".ogg"); + video._polyfill.canPlayType.push(".ogg"); if(dom.canPlayType("video/mp4")) - video.polyfill.canPlayType.push(".mp4"); + video._polyfill.canPlayType.push(".mp4"); })(); if(cc.sys.OS_IOS === cc.sys.os){ - video.polyfill.devicePixelRatio = true; - video.polyfill.event = "progress"; + video._polyfill.devicePixelRatio = true; + video._polyfill.event = "progress"; } })(ccui.VideoPlayer); @@ -402,4 +406,4 @@ ccui.VideoPlayer.EventType = { } }; -})(ccui.VideoPlayer.polyfill); \ No newline at end of file +})(ccui.VideoPlayer._polyfill); \ No newline at end of file diff --git a/extensions/ccui/uiwidgets/UIWebView.js b/extensions/ccui/uiwidgets/UIWebView.js index 684c7f5fe1..83dd763efe 100644 --- a/extensions/ccui/uiwidgets/UIWebView.js +++ b/extensions/ccui/uiwidgets/UIWebView.js @@ -83,7 +83,7 @@ ccui.WebView = ccui.Widget.extend({ * go back */ goBack: function(){ - if(ccui.WebView.polyfill.closeHistory) + if(ccui.WebView._polyfill.closeHistory) return cc.log("The current browser does not support the GoBack"); var iframe = this._renderCmd._iframe; if(iframe){ @@ -97,7 +97,7 @@ ccui.WebView = ccui.Widget.extend({ * go forward */ goForward: function(){ - if(ccui.WebView.polyfill.closeHistory) + if(ccui.WebView._polyfill.closeHistory) return cc.log("The current browser does not support the GoForward"); var iframe = this._renderCmd._iframe; if(iframe){ @@ -116,6 +116,7 @@ ccui.WebView = ccui.Widget.extend({ if(iframe){ var win = iframe.contentWindow; try{ + cc.eventManager.dispatchCustomEvent(ccui.WebView.EventType.JS_EVALUATED); win.eval(str); }catch(err){ console.error(err); @@ -161,16 +162,6 @@ ccui.WebView = ccui.Widget.extend({ } }, - //setOnShouldStartLoading: function(callback){}, - //setOnDidFinishLoading: function(){}, - //setOnDidFailLoading: function(){}, - //setOnJSCallback: function(){}, - - //getOnShouldStartLoading: function(){}, - //getOnDidFinishLoading: function(){}, - //getOnDidFailLoading: function(){}, - //getOnJSCallback: function(){}, - _createRenderCmd: function(){ return new ccui.WebView.RenderCmd(this); }, @@ -206,18 +197,19 @@ ccui.WebView = ccui.Widget.extend({ ccui.WebView.EventType = { LOADING: "ui_webview_loading", LOADED: "ui_webview_load", - ERROR: "ui_webview_error" + ERROR: "ui_webview_error", + JS_EVALUATED: "ui_webview_js" }; (function(){ - var polyfill = ccui.WebView.polyfill = { + var polyfill = ccui.WebView._polyfill = { devicePixelRatio: false, enableDiv: false }; if(cc.sys.os === cc.sys.OS_IOS) - ccui.WebView.polyfill.enableDiv = true; + polyfill.enableDiv = true; if(cc.sys.isMobile){ if(cc.sys.browserType === cc.sys.BROWSER_TYPE_FIREFOX){ @@ -383,4 +375,4 @@ ccui.WebView.EventType = { } }; -})(ccui.WebView.polyfill); \ No newline at end of file +})(ccui.WebView._polyfill); \ No newline at end of file From 00583391556044562fb058af50382e5a964b5acb Mon Sep 17 00:00:00 2001 From: Ningxin Hu Date: Fri, 15 May 2015 16:11:17 +0800 Subject: [PATCH 0244/1039] Add kazmathSIMD module --- moduleConfig.json | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/moduleConfig.json b/moduleConfig.json index 726b9105d8..bcc74e1973 100644 --- a/moduleConfig.json +++ b/moduleConfig.json @@ -144,12 +144,16 @@ "cocos2d/kazmath/plane.js", "cocos2d/kazmath/quaternion.js", "cocos2d/kazmath/aabb.js", - "cocos2d/kazmath/vec3SIMD.js", - "cocos2d/kazmath/mat4SIMD.js", - "cocos2d/kazmath/SIMDPolyfill.js", "cocos2d/kazmath/gl/mat4stack.js", "cocos2d/kazmath/gl/matrix.js" ], + "kazmathSIMD" : [ + "kazmath", + + "cocos2d/kazmath/vec3SIMD.js", + "cocos2d/kazmath/mat4SIMD.js", + "cocos2d/kazmath/SIMDPolyfill.js" + ], "labels" : [ "core", From 1e5a35a93c28a640e79bb342758a0b97d116281c Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 15 May 2015 16:14:43 +0800 Subject: [PATCH 0245/1039] Modify event trigger order --- extensions/ccui/uiwidgets/UIWebView.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/ccui/uiwidgets/UIWebView.js b/extensions/ccui/uiwidgets/UIWebView.js index 83dd763efe..3c912b48e8 100644 --- a/extensions/ccui/uiwidgets/UIWebView.js +++ b/extensions/ccui/uiwidgets/UIWebView.js @@ -116,8 +116,8 @@ ccui.WebView = ccui.Widget.extend({ if(iframe){ var win = iframe.contentWindow; try{ - cc.eventManager.dispatchCustomEvent(ccui.WebView.EventType.JS_EVALUATED); win.eval(str); + cc.eventManager.dispatchCustomEvent(ccui.WebView.EventType.JS_EVALUATED); }catch(err){ console.error(err); } From 1bcbf0618d2a43fcbe7ad167f1b554025c4ff858 Mon Sep 17 00:00:00 2001 From: John Jardine Date: Fri, 15 May 2015 09:41:07 -0400 Subject: [PATCH 0246/1039] Polygon Points property change for consistency between frameworks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes consistency issue by changing “polygonPoints” property to “points” for storage of polygon points in CCTMXXMLParser.js. This allows CCTMXXMLParser.js to behave the same as CCTMXXMLParser.cpp in the other framework. --- cocos2d/tilemap/CCTMXXMLParser.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/tilemap/CCTMXXMLParser.js b/cocos2d/tilemap/CCTMXXMLParser.js index 63b295d0e7..7ba659e735 100644 --- a/cocos2d/tilemap/CCTMXXMLParser.js +++ b/cocos2d/tilemap/CCTMXXMLParser.js @@ -783,7 +783,7 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ if(polygonProps && polygonProps.length > 0) { var selPgPointStr = polygonProps[0].getAttribute('points'); if(selPgPointStr) - objectProp["polygonPoints"] = this._parsePointsString(selPgPointStr); + objectProp["points"] = this._parsePointsString(selPgPointStr); } //polyline From 8f435454dacd616deb92c6e9eb1f837457e85dc5 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 18 May 2015 14:21:18 +0800 Subject: [PATCH 0247/1039] Too early to remove dirtyFlag --- extensions/ccui/layouts/UILayoutCanvasRenderCmd.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js b/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js index d3861d2573..ed7f9950f9 100644 --- a/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js +++ b/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js @@ -133,7 +133,6 @@ this._clipElemType = node._stencil instanceof cc.Sprite; this._syncStatus(parentCmd); - this._dirtyFlag = 0; cc.renderer.pushRenderCommand(this._rendererSaveCmd); if (this._clipElemType) { @@ -171,6 +170,7 @@ locProtectChildren[j].visit(this); cc.renderer.pushRenderCommand(this._rendererRestoreCmd); } + this._dirtyFlag = 0; }; ccui.Layout.CanvasRenderCmd._getSharedCache = function () { From 8c72e4565963a89631f682b71206b38e6c0967c1 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 18 May 2015 18:35:03 +0800 Subject: [PATCH 0248/1039] Texture should inherit property --- cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js index dd08d36c00..37fc069f29 100644 --- a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js @@ -203,7 +203,10 @@ if (displayedColor.r === 255 && displayedColor.g === 255 && displayedColor.b === 255) { if (this._colorized) { this._colorized = false; + var rect = cc.rect(node._rect.x, node._rect.y, node._rect.width, node._rect.height); + var isRotation = node._rectRotated; node.texture = this._originalTexture; + node.setTextureRect(rect, isRotation); } return; } From d8331b5a1e61b61682a451235296ee3165726bd5 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 19 May 2015 09:51:45 +0800 Subject: [PATCH 0249/1039] Texture should inherit property --- cocos2d/core/sprites/CCSprite.js | 2 ++ cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js | 3 --- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/sprites/CCSprite.js b/cocos2d/core/sprites/CCSprite.js index b6662b3455..65a240e65b 100644 --- a/cocos2d/core/sprites/CCSprite.js +++ b/cocos2d/core/sprites/CCSprite.js @@ -966,6 +966,8 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ _clearRect: function(){ var texture = this._texture; if(texture){ + if(texture._htmlElementObj instanceof HTMLCanvasElement) + return; var textureRect = texture._contentSize; var spriteRect = this._rect; if( diff --git a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js index 37fc069f29..dd08d36c00 100644 --- a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js @@ -203,10 +203,7 @@ if (displayedColor.r === 255 && displayedColor.g === 255 && displayedColor.b === 255) { if (this._colorized) { this._colorized = false; - var rect = cc.rect(node._rect.x, node._rect.y, node._rect.width, node._rect.height); - var isRotation = node._rectRotated; node.texture = this._originalTexture; - node.setTextureRect(rect, isRotation); } return; } From 7c1dcd3301d5b332346ba00dd0f6eba9fa90b38c Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 19 May 2015 10:12:02 +0800 Subject: [PATCH 0250/1039] Revert "Texture should inherit property" This reverts commit d8331b5a1e61b61682a451235296ee3165726bd5. --- cocos2d/core/sprites/CCSprite.js | 2 -- cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js | 3 +++ 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/sprites/CCSprite.js b/cocos2d/core/sprites/CCSprite.js index 65a240e65b..b6662b3455 100644 --- a/cocos2d/core/sprites/CCSprite.js +++ b/cocos2d/core/sprites/CCSprite.js @@ -966,8 +966,6 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ _clearRect: function(){ var texture = this._texture; if(texture){ - if(texture._htmlElementObj instanceof HTMLCanvasElement) - return; var textureRect = texture._contentSize; var spriteRect = this._rect; if( diff --git a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js index dd08d36c00..37fc069f29 100644 --- a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js @@ -203,7 +203,10 @@ if (displayedColor.r === 255 && displayedColor.g === 255 && displayedColor.b === 255) { if (this._colorized) { this._colorized = false; + var rect = cc.rect(node._rect.x, node._rect.y, node._rect.width, node._rect.height); + var isRotation = node._rectRotated; node.texture = this._originalTexture; + node.setTextureRect(rect, isRotation); } return; } From f4648d29c64adc77cf6d482c13c80b8212cb1fd1 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 19 May 2015 10:17:06 +0800 Subject: [PATCH 0251/1039] Optimize performance --- cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js index 37fc069f29..35b1fa82c9 100644 --- a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js @@ -203,9 +203,9 @@ if (displayedColor.r === 255 && displayedColor.g === 255 && displayedColor.b === 255) { if (this._colorized) { this._colorized = false; - var rect = cc.rect(node._rect.x, node._rect.y, node._rect.width, node._rect.height); + var rect = cc.rect(node._rect); var isRotation = node._rectRotated; - node.texture = this._originalTexture; + node.setTexture(this._originalTexture); node.setTextureRect(rect, isRotation); } return; From 3c50924b035cbe5f71363b4da9efb15688de5deb Mon Sep 17 00:00:00 2001 From: Zachary Lester Date: Tue, 19 May 2015 01:30:57 -0700 Subject: [PATCH 0252/1039] Fix typo in AUTHORS.txt Altered sentence explaining how authors were ordered so as to fix its grammar and more clearly convey its meaning. --- AUTHORS.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AUTHORS.txt b/AUTHORS.txt index e61d18e5cb..f3ba252624 100644 --- a/AUTHORS.txt +++ b/AUTHORS.txt @@ -1,6 +1,6 @@ Cocos2d-html5 authors -(ordered by the join in time) +(Ordered by join time) Core Developers: From c1cf4c5230d2a4383763f10701867bdef385baa2 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 19 May 2015 17:11:39 +0800 Subject: [PATCH 0253/1039] PlayMusic should not increase the search path(timeline 2.x) --- extensions/cocostudio/loader/parsers/timelineParser-2.x.js | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index e5644ccada..86496e99e1 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -1131,13 +1131,10 @@ var volume = json["Volume"] || 0; cc.audioEngine.setMusicVolume(volume); //var name = json["Name"]; - var resPath = ""; - if(cc.loader.resPath) - resPath = (cc.loader.resPath + "/").replace(/\/\/$/, "/"); loadTexture(json["FileData"], resourcePath, function(path, type){ cc.loader.load(path, function(){ - cc.audioEngine.playMusic(resPath + path, loop); + cc.audioEngine.playMusic(path, loop); }); }); From 127cb997341fd426c1b3c1abc38d44bac1f147f1 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 19 May 2015 17:46:50 +0800 Subject: [PATCH 0254/1039] Resource path error --- extensions/cocostudio/loader/parsers/compatible.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/cocostudio/loader/parsers/compatible.js b/extensions/cocostudio/loader/parsers/compatible.js index caa681d4fc..3f34b13956 100644 --- a/extensions/cocostudio/loader/parsers/compatible.js +++ b/extensions/cocostudio/loader/parsers/compatible.js @@ -41,7 +41,7 @@ * @returns {*} */ widgetFromJsonFile: function(file){ - var json = cc.loader.getRes(file); + var json = cc.loader.getRes(cc.path.join(cc.loader.resPath, file)); if(json) this._fileDesignSizes[file] = cc.size(json["designWidth"]||0, json["designHeight"]||0); From 240679b074ac421c68ecddde2bfbc89e4c6a0134 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 20 May 2015 15:36:53 +0800 Subject: [PATCH 0255/1039] Premultiply texture's alpha for png by default to fix Cocos Studio render issues --- cocos2d/core/platform/CCLoaders.js | 2 +- cocos2d/core/textures/TexturesWebGL.js | 12 +++++++++--- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/cocos2d/core/platform/CCLoaders.js b/cocos2d/core/platform/CCLoaders.js index 541e3b91c5..e27536d7c3 100644 --- a/cocos2d/core/platform/CCLoaders.js +++ b/cocos2d/core/platform/CCLoaders.js @@ -54,7 +54,7 @@ cc._imgLoader = { }); } }; -cc.loader.register(["png", "jpg", "bmp","jpeg","gif", "ico"], cc._imgLoader); +cc.loader.register(["png", "jpg", "bmp","jpeg","gif", "ico", "tiff"], cc._imgLoader); cc._serverImgLoader = { load : function(realUrl, url, res, cb){ cc.loader.cache[url] = cc.loader.loadImg(res.src, function(err, img){ diff --git a/cocos2d/core/textures/TexturesWebGL.js b/cocos2d/core/textures/TexturesWebGL.js index c2dc3b3683..2b4f0260e4 100644 --- a/cocos2d/core/textures/TexturesWebGL.js +++ b/cocos2d/core/textures/TexturesWebGL.js @@ -845,17 +845,23 @@ cc._tmp.WebGLTextureCache = function () { var _p = cc.textureCache; _p.handleLoadedTexture = function (url) { - var locTexs = this._textures; + var locTexs = this._textures, tex, ext; //remove judge(webgl) if (!cc._rendererInitialized) { locTexs = this._loadedTexturesBefore; } - var tex = locTexs[url]; + tex = locTexs[url]; if (!tex) { tex = locTexs[url] = new cc.Texture2D(); tex.url = url; } - tex.handleLoadedTexture(); + ext = cc.path.extname(url); + if (ext === ".png") { + tex.handleLoadedTexture(true); + } + else { + tex.handleLoadedTexture(); + } }; /** From 42ba88358cb80e44b32fa4e264d3fc7e1bef4cd8 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 20 May 2015 15:37:00 +0800 Subject: [PATCH 0256/1039] Fix typo --- cocos2d/core/textures/TexturesWebGL.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/cocos2d/core/textures/TexturesWebGL.js b/cocos2d/core/textures/TexturesWebGL.js index 2b4f0260e4..9d9224179c 100644 --- a/cocos2d/core/textures/TexturesWebGL.js +++ b/cocos2d/core/textures/TexturesWebGL.js @@ -441,10 +441,10 @@ cc._tmp.WebGLTexture2D = function () { /** * handler of texture loaded event - * @param {Boolean} [premultipled=false] + * @param {Boolean} [premultiplied=false] */ - handleLoadedTexture: function (premultipled) { - premultipled = (premultipled === undefined)?false: premultipled; + handleLoadedTexture: function (premultiplied) { + premultiplied = (premultiplied === undefined)?false: premultiplied; var self = this; // Not sure about this ! Some texture need to be updated even after loaded if (!cc._rendererInitialized) @@ -463,7 +463,7 @@ cc._tmp.WebGLTexture2D = function () { cc.glBindTexture2D(self); gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4); - if(premultipled) + if(premultiplied) gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1); // Specify OpenGL texture image @@ -476,7 +476,7 @@ cc._tmp.WebGLTexture2D = function () { self.shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURE); cc.glBindTexture2D(null); - if(premultipled) + if(premultiplied) gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0); var pixelsWide = self._htmlElementObj.width; @@ -488,7 +488,7 @@ cc._tmp.WebGLTexture2D = function () { self.maxS = 1; self.maxT = 1; - self._hasPremultipliedAlpha = premultipled; + self._hasPremultipliedAlpha = premultiplied; self._hasMipmaps = false; //dispatch load event to listener. From 68f6224b6c984787b99a802f6c30068b5b1a0260 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 21 May 2015 15:24:41 +0800 Subject: [PATCH 0257/1039] Error loading path of resources --- extensions/cocostudio/loader/load.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/extensions/cocostudio/loader/load.js b/extensions/cocostudio/loader/load.js index 751ee53918..b30a27e675 100644 --- a/extensions/cocostudio/loader/load.js +++ b/extensions/cocostudio/loader/load.js @@ -33,6 +33,8 @@ ccs._load = (function(){ */ var load = function(file, type, path){ + file = cc.path.join(cc.loader.resPath, file); + var json = cc.loader.getRes(file); if(!json) From 6f7a2330428c5037e894f7c0a9f96e369b1820f4 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 21 May 2015 15:26:12 +0800 Subject: [PATCH 0258/1039] Error loading path of resources --- CCBoot.js | 1 - 1 file changed, 1 deletion(-) diff --git a/CCBoot.js b/CCBoot.js index 6181745665..b2335d2d38 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -784,7 +784,6 @@ cc.loader = /** @lends cc.loader# */{ this.removeEventListener('load', loadCallback, false); this.removeEventListener('error', errorCallback, false); - cc.loader.cache[url] = img; if (callback) callback(null, img); }; From 7fa429c1b0aba70d22c500546760dbbe2d93284d Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 21 May 2015 16:08:29 +0800 Subject: [PATCH 0259/1039] Repair after bake texture may wrong question and synchronous ccui.Scale9Sprite --- cocos2d/core/layers/CCLayerCanvasRenderCmd.js | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js index c80fc3f574..c22a6f7179 100644 --- a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js +++ b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js @@ -122,6 +122,7 @@ this._syncStatus(parentCmd); cc.renderer.pushRenderCommand(this); + this._cacheDirty = true; //the bakeSprite is drawing this._bakeSprite.visit(this); From 133dafbe482f45b4747389e613e5d27a31659068 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 21 May 2015 16:08:39 +0800 Subject: [PATCH 0260/1039] Repair after bake texture may wrong question and synchronous ccui.Scale9Sprite --- .../gui/control-extension/CCScale9Sprite.js | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/extensions/gui/control-extension/CCScale9Sprite.js b/extensions/gui/control-extension/CCScale9Sprite.js index 9e1fefa38a..676059269f 100644 --- a/extensions/gui/control-extension/CCScale9Sprite.js +++ b/extensions/gui/control-extension/CCScale9Sprite.js @@ -462,11 +462,11 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ if(!locLoaded){ texture.addEventListener("load", function(sender){ // the texture is rotated on Canvas render mode, so isRotated always is false. - var preferredSize = this._preferredSize, restorePreferredSize = (preferredSize.width !== 0 || preferredSize.height !== 0); - if(restorePreferredSize)preferredSize = cc.size(preferredSize.width, preferredSize.height); + var preferredSize = this._preferredSize, restorePreferredSize = preferredSize.width !== 0 && preferredSize.height !== 0; + if (restorePreferredSize) preferredSize = cc.size(preferredSize.width, preferredSize.height); var size = sender.getContentSize(); this.updateWithBatchNode(this._scale9Image, cc.rect(0,0,size.width,size.height), false, this._capInsets); - if(restorePreferredSize)this.setPreferredSize(preferredSize); + if (restorePreferredSize)this.setPreferredSize(preferredSize); this._positionsAreDirty = true; this.dispatchEvent("load"); }, this); @@ -495,10 +495,10 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ if(!locLoaded){ spriteFrame.addEventListener("load", function(sender){ // the texture is rotated on Canvas render mode, so isRotated always is false. - var preferredSize = this._preferredSize, restorePreferredSize = (preferredSize.width !== 0 || preferredSize.height !== 0); - if(restorePreferredSize)preferredSize = cc.size(preferredSize.width, preferredSize.height); + var preferredSize = this._preferredSize, restorePreferredSize = preferredSize.width !== 0 && preferredSize.height !== 0; + if (restorePreferredSize) preferredSize = cc.size(preferredSize.width, preferredSize.height); this.updateWithBatchNode(this._scale9Image, sender.getRect(), cc._renderType === cc._RENDER_TYPE_WEBGL && sender.isRotated(), this._capInsets); - if(restorePreferredSize)this.setPreferredSize(preferredSize); + if (restorePreferredSize)this.setPreferredSize(preferredSize); this._positionsAreDirty = true; this.dispatchEvent("load"); },this); @@ -897,10 +897,10 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ if(!locLoaded){ spriteFrame.addEventListener("load", function(sender){ // the texture is rotated on Canvas render mode, so isRotated always is false. - var preferredSize = this._preferredSize, restorePreferredSize = (preferredSize.width !== 0 || preferredSize.height !== 0); - if(restorePreferredSize)preferredSize = cc.size(preferredSize.width, preferredSize.height); + var preferredSize = this._preferredSize, restorePreferredSize = preferredSize.width !== 0 && preferredSize.height !== 0; + if (restorePreferredSize) preferredSize = cc.size(preferredSize.width, preferredSize.height); this.updateWithBatchNode(this._scale9Image, sender.getRect(), cc._renderType === cc._RENDER_TYPE_WEBGL && sender.isRotated(), this._capInsets); - if(restorePreferredSize)this.setPreferredSize(preferredSize); + if (restorePreferredSize)this.setPreferredSize(preferredSize); this._positionsAreDirty = true; this.dispatchEvent("load"); },this); From b3e336904751022c499822f849a65f4a31b51b29 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 21 May 2015 16:26:34 +0800 Subject: [PATCH 0261/1039] Repair after bake texture may wrong question and synchronous ccui.Scale9Sprite --- cocos2d/core/layers/CCLayerCanvasRenderCmd.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js index c22a6f7179..4d422028d7 100644 --- a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js +++ b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js @@ -47,7 +47,7 @@ this._needDraw = true; cc.renderer.childrenOrderDirty = true; //limit: 1. its children's blendfunc are invalid. - this._isBaked = this._cacheDirty = true; + this._isBaked = true; var children = this._node._children; for(var i = 0, len = children.length; i < len; i++) From bf0803f87b93c2deb65fd317778512e40e2e2156 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 21 May 2015 18:02:50 +0800 Subject: [PATCH 0262/1039] Repair after bake texture may wrong question and synchronous ccui.Scale9Sprite --- cocos2d/core/layers/CCLayerCanvasRenderCmd.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js index 4d422028d7..c22a6f7179 100644 --- a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js +++ b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js @@ -47,7 +47,7 @@ this._needDraw = true; cc.renderer.childrenOrderDirty = true; //limit: 1. its children's blendfunc are invalid. - this._isBaked = true; + this._isBaked = this._cacheDirty = true; var children = this._node._children; for(var i = 0, len = children.length; i < len; i++) From bcd1cfa3a2fc18af099d5d580074fd712119b00a Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 25 May 2015 17:50:48 +0800 Subject: [PATCH 0263/1039] Issue #2910: CCScheduler.js unscheduleAllWithMinPriority has a problem --- cocos2d/core/CCScheduler.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/CCScheduler.js b/cocos2d/core/CCScheduler.js index 688726099e..19fdde336b 100644 --- a/cocos2d/core/CCScheduler.js +++ b/cocos2d/core/CCScheduler.js @@ -727,7 +727,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ unscheduleAllWithMinPriority: function(minPriority){ // Custom Selectors var i, element, arr = this._arrayForTimers; - for(i=0; i=0; i--){ element = arr[i]; this.unscheduleAllForTarget(element.target); } From 5b0dcf8a3008fb1a7749d79cf9d18ef35e8b0cf7 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 26 May 2015 15:51:41 +0800 Subject: [PATCH 0264/1039] Repair isBaked return the undefined --- cocos2d/core/layers/CCLayer.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/layers/CCLayer.js b/cocos2d/core/layers/CCLayer.js index f80af56a0c..4e414c6397 100644 --- a/cocos2d/core/layers/CCLayer.js +++ b/cocos2d/core/layers/CCLayer.js @@ -83,7 +83,7 @@ cc.Layer = cc.Node.extend(/** @lends cc.Layer# */{ * @see cc.Layer#bake and cc.Layer#unbake */ isBaked: function(){ - return this._isBaked; + return this._renderCmd._isBaked; }, addChild: function(child, localZOrder, tag){ From 50f9533e6fe4cedaadabc2d1e46a45d18106b34e Mon Sep 17 00:00:00 2001 From: Mykyta Usikov Date: Tue, 26 May 2015 13:40:08 +0300 Subject: [PATCH 0265/1039] fixed CCProgressTimerCanvasRenderCmd to properly show colorized sprites; --- .../CCProgressTimerCanvasRenderCmd.js | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js b/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js index fbb87b8ced..551481334f 100644 --- a/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js +++ b/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js @@ -90,7 +90,7 @@ //draw sprite var image = locSprite._texture.getHtmlElementObj(); - if (locSprite._colorized) { + if (locSprite._renderCmd._colorized) { context.drawImage(image, 0, 0, locTextureCoord.width, locTextureCoord.height, locX * scaleX, locY * scaleY, locWidth * scaleX, locHeight * scaleY); @@ -226,10 +226,10 @@ spriteCmd._syncDisplayOpacity(); } -/* if(colorDirty || opacityDirty){ + if(colorDirty || opacityDirty){ spriteCmd._updateColor(); - this._updateColor(); - }*/ + //this._updateColor(); + } if (locFlag & flags.transformDirty) { //update the transform @@ -256,10 +256,10 @@ spriteCmd._updateDisplayOpacity(); } -/* if(colorDirty || opacityDirty){ + if(colorDirty || opacityDirty){ spriteCmd._updateColor(); - this._updateColor(); - }*/ + //this._updateColor(); + } if(locFlag & flags.transformDirty){ //update the transform From d6081a9fb69e3a562684b50571fc30402c74d21c Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 27 May 2015 16:48:55 +0800 Subject: [PATCH 0266/1039] Modify event trigger mechanism --- extensions/ccui/uiwidgets/UIVideoPlayer.js | 93 +++++++++++++--------- extensions/ccui/uiwidgets/UIWebView.js | 63 ++++++++------- 2 files changed, 92 insertions(+), 64 deletions(-) diff --git a/extensions/ccui/uiwidgets/UIVideoPlayer.js b/extensions/ccui/uiwidgets/UIVideoPlayer.js index f3e6cca5f3..8a1d660738 100644 --- a/extensions/ccui/uiwidgets/UIVideoPlayer.js +++ b/extensions/ccui/uiwidgets/UIVideoPlayer.js @@ -26,6 +26,7 @@ ccui.VideoPlayer = ccui.Widget.extend({ ctor: function(path){ ccui.Widget.prototype.ctor.call(this); + this._EventList = {}; if(path) this.setURL(path); }, @@ -98,7 +99,7 @@ ccui.VideoPlayer = ccui.Widget.extend({ } setTimeout(function(){ - cc.eventManager.dispatchCustomEvent(ccui.VideoPlayer.EventType.STOPPED); + self._dispatchEvent(ccui.VideoPlayer.EventType.STOPPED); }, 0); }, /** @@ -128,58 +129,78 @@ ccui.VideoPlayer = ccui.Widget.extend({ cc.log("On the web is always keep the aspect ratio"); }, isKeepAspectRatioEnabled: function(){ - return true; + return false; }, + /** + * Set whether the full screen + * May appear inconsistent in different browsers + * @param {boolean} enable + */ setFullScreenEnabled: function(enable){ var video = this._renderCmd._video; - if(video) - cc.screen.requestFullScreen(video); + if(video){ + if(enable) + cc.screen.requestFullScreen(video); + else + cc.screen.exitFullScreen(video); + } }, + + /** + * Determine whether already full screen + */ isFullScreenEnabled: function(){ cc.log("Can't know status"); }, /** - * + * The binding event * @param {String} event play | pause | stop | complete * @param {Function} callback */ - addEventListener: function(event, callback){ - if(!/^ui_video_/.test(event)) - event = "ui_video_" + event; - return cc.eventManager.addCustomListener(event, callback); + setEventListener: function(event, callback){ + var list = this._EventList[event]; + if(!list) + list = this._EventList[event] = []; + list[0] = callback; }, /** - * + * Delete events * @param {String} event play | pause | stop | complete - * @param {Function|Object} callbackOrListener + * @param {Function|Object} callback */ - removeEventListener: function(event, callbackOrListener){ - var map, list; - if(!/^ui_video_/.test(event)) - event = "ui_video_" + event; - if(typeof callbackOrListener === "function"){ - map = cc.eventManager._listenersMap[event]; - if(map){ - list = map.getFixedPriorityListeners(); - list && cc.eventManager._removeListenerInCallback(list, callbackOrListener); - } - }else{ - map = cc.eventManager._listenersMap[event]; - if(map){ - list = map.getFixedPriorityListeners(); - list && cc.eventManager._removeListenerInVector(list, callbackOrListener); - } + removeEventListener: function(event, callback){ + var list = this._EventList[event]; + if(list){ + if(callback) + for(var i=0; i Date: Wed, 27 May 2015 17:15:17 +0800 Subject: [PATCH 0267/1039] Modify event trigger mechanism --- extensions/ccui/uiwidgets/UIVideoPlayer.js | 30 +++++----------------- extensions/ccui/uiwidgets/UIWebView.js | 28 +++++--------------- 2 files changed, 13 insertions(+), 45 deletions(-) diff --git a/extensions/ccui/uiwidgets/UIVideoPlayer.js b/extensions/ccui/uiwidgets/UIVideoPlayer.js index 8a1d660738..463635d36d 100644 --- a/extensions/ccui/uiwidgets/UIVideoPlayer.js +++ b/extensions/ccui/uiwidgets/UIVideoPlayer.js @@ -160,37 +160,21 @@ ccui.VideoPlayer = ccui.Widget.extend({ * @param {Function} callback */ setEventListener: function(event, callback){ - var list = this._EventList[event]; - if(!list) - list = this._EventList[event] = []; - list[0] = callback; + this._EventList[event] = callback; }, /** * Delete events - * @param {String} event play | pause | stop | complete - * @param {Function|Object} callback + * @param {ccui.VideoPlayer.EventType} event */ - removeEventListener: function(event, callback){ - var list = this._EventList[event]; - if(list){ - if(callback) - for(var i=0; i Date: Wed, 27 May 2015 17:19:29 +0800 Subject: [PATCH 0268/1039] Consolidate the grammar --- extensions/ccui/uiwidgets/UIVideoPlayer.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/extensions/ccui/uiwidgets/UIVideoPlayer.js b/extensions/ccui/uiwidgets/UIVideoPlayer.js index 463635d36d..ff842577d7 100644 --- a/extensions/ccui/uiwidgets/UIVideoPlayer.js +++ b/extensions/ccui/uiwidgets/UIVideoPlayer.js @@ -156,7 +156,7 @@ ccui.VideoPlayer = ccui.Widget.extend({ /** * The binding event - * @param {String} event play | pause | stop | complete + * @param {ccui.VideoPlayer.EventType} event * @param {Function} callback */ setEventListener: function(event, callback){ @@ -372,10 +372,10 @@ ccui.VideoPlayer.EventType = { node._dispatchEvent(ccui.VideoPlayer.EventType.COMPLETED); }); video.addEventListener("play", function(){ - node._dispatchEvent(ccui.VideoPlayer.EventType.PLAYING) + node._dispatchEvent(ccui.VideoPlayer.EventType.PLAYING); }); video.addEventListener("pause", function(){ - node._dispatchEvent(ccui.VideoPlayer.EventType.PAUSED) + node._dispatchEvent(ccui.VideoPlayer.EventType.PAUSED); }); }; From 766b3a6cacade93e347c20e6f8a2defc104f2c20 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 28 May 2015 10:23:25 +0800 Subject: [PATCH 0269/1039] The interface should return true --- extensions/ccui/uiwidgets/UIWebView.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/extensions/ccui/uiwidgets/UIWebView.js b/extensions/ccui/uiwidgets/UIWebView.js index 52512ad480..e9ac910b60 100644 --- a/extensions/ccui/uiwidgets/UIWebView.js +++ b/extensions/ccui/uiwidgets/UIWebView.js @@ -69,6 +69,7 @@ ccui.WebView = ccui.Widget.extend({ */ canGoBack: function(){ cc.log("Web does not support query history"); + return true; }, /** @@ -76,6 +77,7 @@ ccui.WebView = ccui.Widget.extend({ */ canGoForward: function(){ cc.log("Web does not support query history"); + return true; }, /** From 52055f8776ec7990a0158feeff7c1c0dbbfe3209 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 28 May 2015 14:17:17 +0800 Subject: [PATCH 0270/1039] Studio automatically loaded rely on resources --- extensions/cocostudio/loader/load.js | 22 +++++++++++++++++++ .../cocostudio/loader/parsers/action-2.x.js | 12 ++++++++-- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/extensions/cocostudio/loader/load.js b/extensions/cocostudio/loader/load.js index 751ee53918..60b02f2fe6 100644 --- a/extensions/cocostudio/loader/load.js +++ b/extensions/cocostudio/loader/load.js @@ -221,3 +221,25 @@ ccs.csLoader = { return ccs._load(file); } }; + + +cc._jsonLoader = { + load : function(realUrl, url, res, cb){ + cc.loader.loadJson(realUrl, function(error, data){ + if(data && data["Content"] && data["Content"]["Content"]["UsedResources"]){ + var list = data["Content"]["Content"]["UsedResources"], + dirname = cc.path.dirname(realUrl); + for(var i=0; i Date: Fri, 29 May 2015 10:57:34 +0800 Subject: [PATCH 0271/1039] Update wide will to empty all of the attributes --- cocos2d/core/sprites/CCBakeSprite.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/cocos2d/core/sprites/CCBakeSprite.js b/cocos2d/core/sprites/CCBakeSprite.js index 305e84a467..85822cb4f8 100644 --- a/cocos2d/core/sprites/CCBakeSprite.js +++ b/cocos2d/core/sprites/CCBakeSprite.js @@ -63,8 +63,14 @@ cc.BakeSprite = cc.Sprite.extend(/** @lends cc.BakeSprite# */{ sizeOrWidth = sizeOrWidth.width; } var locCanvas = this._cacheCanvas; + var strokeStyle = this._cacheContext._context.strokeStyle; + var fillStyle = this._cacheContext._context.fillStyle; locCanvas.width = sizeOrWidth; locCanvas.height = height; //TODO note baidu browser reset the context after set width or height + if(strokeStyle !== this._cacheContext._context.strokeStyle) + this._cacheContext._context.strokeStyle = strokeStyle; + if(fillStyle !== this._cacheContext._context.fillStyle) + this._cacheContext._context.fillStyle = fillStyle; this.getTexture().handleLoadedTexture(); this.setTextureRect(cc.rect(0,0, sizeOrWidth, height), false); } From 738da11b7a44d949127f9c17fe61a26a6007d892 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 29 May 2015 11:33:22 +0800 Subject: [PATCH 0272/1039] Update wide will to empty all of the attributes --- cocos2d/core/sprites/CCBakeSprite.js | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/sprites/CCBakeSprite.js b/cocos2d/core/sprites/CCBakeSprite.js index 85822cb4f8..b586ea6f8f 100644 --- a/cocos2d/core/sprites/CCBakeSprite.js +++ b/cocos2d/core/sprites/CCBakeSprite.js @@ -58,13 +58,14 @@ cc.BakeSprite = cc.Sprite.extend(/** @lends cc.BakeSprite# */{ * @param {Number} [height] */ resetCanvasSize: function(sizeOrWidth, height){ + var locCanvas = this._cacheCanvas, + locContext = this._cacheContext, + strokeStyle = locContext._context.strokeStyle, + fillStyle = locContext._context.fillStyle; if(height === undefined){ height = sizeOrWidth.height; sizeOrWidth = sizeOrWidth.width; } - var locCanvas = this._cacheCanvas; - var strokeStyle = this._cacheContext._context.strokeStyle; - var fillStyle = this._cacheContext._context.fillStyle; locCanvas.width = sizeOrWidth; locCanvas.height = height; //TODO note baidu browser reset the context after set width or height if(strokeStyle !== this._cacheContext._context.strokeStyle) From e3c580a9f7e9ef71da71c426ee10813ab7405ac8 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 29 May 2015 13:33:42 +0800 Subject: [PATCH 0273/1039] Update wide will to empty all of the attributes --- cocos2d/core/sprites/CCBakeSprite.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/cocos2d/core/sprites/CCBakeSprite.js b/cocos2d/core/sprites/CCBakeSprite.js index b586ea6f8f..bcde14c2d0 100644 --- a/cocos2d/core/sprites/CCBakeSprite.js +++ b/cocos2d/core/sprites/CCBakeSprite.js @@ -68,10 +68,10 @@ cc.BakeSprite = cc.Sprite.extend(/** @lends cc.BakeSprite# */{ } locCanvas.width = sizeOrWidth; locCanvas.height = height; //TODO note baidu browser reset the context after set width or height - if(strokeStyle !== this._cacheContext._context.strokeStyle) - this._cacheContext._context.strokeStyle = strokeStyle; - if(fillStyle !== this._cacheContext._context.fillStyle) - this._cacheContext._context.fillStyle = fillStyle; + if(strokeStyle !== locContext._context.strokeStyle) + locContext._context.strokeStyle = strokeStyle; + if(fillStyle !== locContext._context.fillStyle) + locContext._context.fillStyle = fillStyle; this.getTexture().handleLoadedTexture(); this.setTextureRect(cc.rect(0,0, sizeOrWidth, height), false); } From 46da3b7da60d9daa7ef874b53b575cdc9a285270 Mon Sep 17 00:00:00 2001 From: IShm Date: Mon, 1 Jun 2015 12:26:07 +0300 Subject: [PATCH 0274/1039] added empty sprite for not found character into font --- cocos2d/labels/CCLabelBMFont.js | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/cocos2d/labels/CCLabelBMFont.js b/cocos2d/labels/CCLabelBMFont.js index 1a4a018471..e79df5a28a 100644 --- a/cocos2d/labels/CCLabelBMFont.js +++ b/cocos2d/labels/CCLabelBMFont.js @@ -327,7 +327,18 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ var fontDef = locFontDict[key]; if (!fontDef) { cc.log("cocos2d: LabelBMFont: character not found " + locStr[i]); - continue; + + fontDef = { + rect: { + x: 0, + y: 0, + width: 0, + height: 0 + }, + xOffset: 0, + yOffset: 0, + xAdvance: 0 + }; } var rect = cc.rect(fontDef.rect.x, fontDef.rect.y, fontDef.rect.width, fontDef.rect.height); @@ -439,12 +450,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ return 0; } var curTextFirstSprite = this.getChildByTag(startIndex); - var curTextLastSpriteId = startIndex + endIndex; - var curTextLastSprite = this.getChildByTag(curTextLastSpriteId); - while (!curTextLastSprite && 0 < curTextLastSpriteId) { - curTextLastSpriteId--; - curTextLastSprite = this.getChildByTag(curTextLastSpriteId); - } + var curTextLastSprite = this.getChildByTag(startIndex + endIndex); return this._getLetterPosXLeft(curTextLastSprite) - this._getLetterPosXLeft(curTextFirstSprite); }, From 795c066a19e300a5490c5f2ed58b5a26fcbb01d8 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 3 Jun 2015 12:16:32 +0800 Subject: [PATCH 0275/1039] Fixed texture does not rotate bug --- extensions/ccui/uiwidgets/UILoadingBar.js | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/extensions/ccui/uiwidgets/UILoadingBar.js b/extensions/ccui/uiwidgets/UILoadingBar.js index 0b9b90eaed..1f1d76b020 100644 --- a/extensions/ccui/uiwidgets/UILoadingBar.js +++ b/extensions/ccui/uiwidgets/UILoadingBar.js @@ -240,7 +240,9 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{ this._setPercent(percent); }, - _setPercent: function(percent){ + _setPercent: function(){ + var rect, spriteRenderer, spriteTextureRect; + if (this._totalLength <= 0) return; var res = this._percent / 100.0; @@ -248,16 +250,18 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{ if (this._scale9Enabled) this._setScale9Scale(); else { - var spriteRenderer = this._barRenderer; - var rect = spriteRenderer.getTextureRect(); - rect.width = this._barRendererTextureSize.width * res; - this._barRenderer.setTextureRect( + spriteRenderer = this._barRenderer; + spriteTextureRect = this._barRendererTextureSize; + rect = spriteRenderer.getTextureRect(); + rect.width = spriteTextureRect.width * res; + spriteRenderer.setTextureRect( cc.rect( rect.x, rect.y, - this._barRendererTextureSize.width * res, - this._barRendererTextureSize.height - ) + spriteTextureRect.width * res, + spriteTextureRect.height + ), + spriteRenderer._rectRotated ); } }, From b5b28bfe99b97b3ff2a900c2aa6d53c458b72e3a Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 3 Jun 2015 14:13:22 +0800 Subject: [PATCH 0276/1039] Fixed audioEngine.playEffect loop failures in chrome 42 --- cocos2d/audio/CCAudio.js | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index e4c2f2cce3..2cf33adfd3 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -469,6 +469,7 @@ cc.Audio = cc.Class.extend({ self._setBufferCallback = null; }; } + audio._manualLoop = this._manualLoop; } audio._AUDIO_TYPE = this._AUDIO_TYPE; return audio; From 3b5995a47b61fc7d55b379aeb2da86cdebb75364 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 3 Jun 2015 15:27:05 +0800 Subject: [PATCH 0277/1039] Armature set color --- extensions/cocostudio/loader/parsers/timelineParser-2.x.js | 1 + 1 file changed, 1 insertion(+) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 86496e99e1..3d220101f9 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -1232,6 +1232,7 @@ node.getAnimation().play(currentAnimationName, -1, isLoop); }); + node.setColor(getColor(json["CColor"])); return node; }; From cc321f0c6a02d8aeff47ba3a347799c7cdcff7d7 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 3 Jun 2015 17:56:30 +0800 Subject: [PATCH 0278/1039] The definition of variables move to the head --- extensions/ccui/uiwidgets/UILoadingBar.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/ccui/uiwidgets/UILoadingBar.js b/extensions/ccui/uiwidgets/UILoadingBar.js index 1f1d76b020..6646aa0599 100644 --- a/extensions/ccui/uiwidgets/UILoadingBar.js +++ b/extensions/ccui/uiwidgets/UILoadingBar.js @@ -241,11 +241,11 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{ }, _setPercent: function(){ - var rect, spriteRenderer, spriteTextureRect; + var res, rect, spriteRenderer, spriteTextureRect; if (this._totalLength <= 0) return; - var res = this._percent / 100.0; + res = this._percent / 100.0; if (this._scale9Enabled) this._setScale9Scale(); From 7201bc97679083bac5da206a07de7d12476e488b Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 4 Jun 2015 16:16:19 +0800 Subject: [PATCH 0279/1039] Fixed custom easing animation bug --- extensions/cocostudio/loader/parsers/action-2.x.js | 8 +++++--- extensions/cocostudio/timeline/Frame.js | 8 ++++++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/action-2.x.js b/extensions/cocostudio/loader/parsers/action-2.x.js index b0b44e3e43..900a1fe001 100644 --- a/extensions/cocostudio/loader/parsers/action-2.x.js +++ b/extensions/cocostudio/loader/parsers/action-2.x.js @@ -257,11 +257,13 @@ var type = options["Type"]; frame.setTweenType(type); var points = options["Points"]; + var result = []; if(points){ - points = points.map(function(p){ - return cc.p(p["X"], p["Y"]); + points.forEach(function(p){ + result.push(p["X"]); + result.push(p["Y"]); }); - frame.setEasingParams(points); + frame.setEasingParams(result); } }; diff --git a/extensions/cocostudio/timeline/Frame.js b/extensions/cocostudio/timeline/Frame.js index 24d924ee52..89a147c24b 100644 --- a/extensions/cocostudio/timeline/Frame.js +++ b/extensions/cocostudio/timeline/Frame.js @@ -190,6 +190,14 @@ ccs.Frame = ccs.Class.extend({ }); ccs.Frame.tweenToMap = { + "-1": function(time, easingParam){ + if (easingParam) + { + var tt = 1 - time; + return easingParam[1]*tt*tt*tt + 3*easingParam[3]*time*tt*tt + 3*easingParam[5]*time*time*tt + easingParam[7]*time*time*time; + } + return time; + }, 1: cc._easeSineInObj.easing,//Sine_EaseIn 2: cc._easeSineOutObj.easing,//Sine_EaseOut 3: cc._easeSineInOutObj.easing,//Sine_EaseInOut From 7430cab1712635259d95903161b199673ffd1df4 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 4 Jun 2015 16:58:35 +0800 Subject: [PATCH 0280/1039] fixed: resPath (ccs.load) --- extensions/cocostudio/loader/load.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/extensions/cocostudio/loader/load.js b/extensions/cocostudio/loader/load.js index 5aa8571670..60b02f2fe6 100644 --- a/extensions/cocostudio/loader/load.js +++ b/extensions/cocostudio/loader/load.js @@ -33,8 +33,6 @@ ccs._load = (function(){ */ var load = function(file, type, path){ - file = cc.path.join(cc.loader.resPath, file); - var json = cc.loader.getRes(file); if(!json) From db5b57ffd451590aa1565349c9c68298de798df7 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 5 Jun 2015 12:27:10 +0800 Subject: [PATCH 0281/1039] Activate premultiplied alpha --- cocos2d/core/platform/CCConfig.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/platform/CCConfig.js b/cocos2d/core/platform/CCConfig.js index d22450daad..951f822f4b 100644 --- a/cocos2d/core/platform/CCConfig.js +++ b/cocos2d/core/platform/CCConfig.js @@ -117,7 +117,7 @@ cc.SPRITEBATCHNODE_RENDER_SUBPIXEL = 1; * @constant * @type {Number} */ -cc.OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA = 0; +cc.OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA = 1; /** *

From f74232d94083b13ef61cd2d664d964a3f7af5339 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 8 Jun 2015 11:58:11 +0800 Subject: [PATCH 0282/1039] Fixed UIText color settings bug --- extensions/cocostudio/loader/parsers/timelineParser-2.x.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 3d220101f9..b7f7bf0a4e 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -562,8 +562,11 @@ widget.setUnifySizeEnabled(false); + var color = json["CColor"]; + json["CColor"] = null; + widget.setTextColor(getColor(color)); this.widgetAttributes(widget, json, widget.isIgnoreContentAdaptWithSize()); - + json["CColor"] = color; return widget; }; From 2d87e02b62ddcb30cf9a6dfc1e2c148f0b5ae5c0 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 8 Jun 2015 15:39:38 +0800 Subject: [PATCH 0283/1039] Fixed control LayoutComponent positioning bug --- extensions/cocostudio/loader/parsers/timelineParser-2.x.js | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index b7f7bf0a4e..8305f09c4f 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -121,6 +121,8 @@ node.setCascadeColorEnabled(true); node.setCascadeOpacityEnabled(true); + + setLayoutComponent(node, json); }; parser.parseChild = function(node, children, resourcePath){ @@ -327,6 +329,11 @@ if (color != null) widget.setColor(getColor(color)); + setLayoutComponent(widget, json); + }; + + var setLayoutComponent = function(widget, json){ + var layoutComponent = ccui.LayoutComponent.bindLayoutComponent(widget); if(!layoutComponent) return; From d06f0e2bc2639fd59bbcfc0881100b835f7ab04f Mon Sep 17 00:00:00 2001 From: jianglong0156 Date: Mon, 8 Jun 2015 18:01:05 +0800 Subject: [PATCH 0284/1039] fix return empty texture2d when add image with same url multiple times,relate issue #2928 --- cocos2d/core/textures/CCTextureCache.js | 13 +++++++++++-- cocos2d/core/textures/TexturesWebGL.js | 16 ++++++++++++++-- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/cocos2d/core/textures/CCTextureCache.js b/cocos2d/core/textures/CCTextureCache.js index 8068eb485b..b1f402ff67 100644 --- a/cocos2d/core/textures/CCTextureCache.js +++ b/cocos2d/core/textures/CCTextureCache.js @@ -342,8 +342,17 @@ if (cc._renderType === cc._RENDER_TYPE_CANVAS) { //remove judge var tex = locTexs[url] || locTexs[cc.loader._aliases[url]]; if (tex) { - cb && cb.call(target, tex); - return tex; + if(tex.isLoaded()) { + cb && cb.call(target, tex); + return tex; + } + else + { + tex.addEventListener("load", function(){ + cb && cb.call(target, tex); + }, target); + return tex; + } } tex = locTexs[url] = new cc.Texture2D(); diff --git a/cocos2d/core/textures/TexturesWebGL.js b/cocos2d/core/textures/TexturesWebGL.js index 9d9224179c..b289008755 100644 --- a/cocos2d/core/textures/TexturesWebGL.js +++ b/cocos2d/core/textures/TexturesWebGL.js @@ -888,8 +888,20 @@ cc._tmp.WebGLTextureCache = function () { } var tex = locTexs[url] || locTexs[cc.loader._aliases[url]]; if (tex) { - cb && cb.call(target, tex); - return tex; + if(tex.isLoaded()) { + cb && cb.call(target, tex); + return tex; + } + else + { + tex.addEventListener("load", function(){ + cb && cb.call(target, tex); + }, target); + return tex; + } + } else { + tex = locTexs[url] = new cc.Texture2D(); + tex.url = url; } tex = locTexs[url] = new cc.Texture2D(); From c411435047ff48733b38b98590722557555a1add Mon Sep 17 00:00:00 2001 From: jianglong0156 Date: Mon, 8 Jun 2015 18:14:48 +0800 Subject: [PATCH 0285/1039] fix the error code --- cocos2d/core/textures/TexturesWebGL.js | 3 --- 1 file changed, 3 deletions(-) diff --git a/cocos2d/core/textures/TexturesWebGL.js b/cocos2d/core/textures/TexturesWebGL.js index b289008755..5826bfef7b 100644 --- a/cocos2d/core/textures/TexturesWebGL.js +++ b/cocos2d/core/textures/TexturesWebGL.js @@ -899,9 +899,6 @@ cc._tmp.WebGLTextureCache = function () { }, target); return tex; } - } else { - tex = locTexs[url] = new cc.Texture2D(); - tex.url = url; } tex = locTexs[url] = new cc.Texture2D(); From 8d5bcee5851de833ed507cfcdd7c23c3be47ec42 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 9 Jun 2015 14:03:11 +0800 Subject: [PATCH 0286/1039] Set the background image should disable background color --- extensions/ccui/layouts/UILayout.js | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/extensions/ccui/layouts/UILayout.js b/extensions/ccui/layouts/UILayout.js index 99b242c2ae..db18220930 100644 --- a/extensions/ccui/layouts/UILayout.js +++ b/extensions/ccui/layouts/UILayout.js @@ -41,6 +41,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ _backGroundImageFileName: null, _backGroundImageCapInsets: null, _colorType: null, + _colorTypeBackup: null, _bgImageTexType: ccui.Widget.LOCAL_TEXTURE, _colorRender: null, _gradientRender: null, @@ -531,6 +532,8 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ this._backGroundImageTextureSize = locBackgroundImage.getContentSize(); locBackgroundImage.setPosition(this._contentSize.width * 0.5, this._contentSize.height * 0.5); this._updateBackGroundImageColor(); + this._colorTypeBackup = this._colorType; + this.setBackGroundColorType(0); }, /** @@ -602,6 +605,11 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ this._backGroundImageFileName = ""; this._backGroundImageTextureSize.width = 0; this._backGroundImageTextureSize.height = 0; + if(this._colorTypeBackup !== null){ + var type = this._colorTypeBackup; + this._colorTypeBackup = null; + this.setBackGroundColorType(type); + } }, /** @@ -609,6 +617,10 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * @param {ccui.Layout.BG_COLOR_NONE|ccui.Layout.BG_COLOR_SOLID|ccui.Layout.BG_COLOR_GRADIENT} type */ setBackGroundColorType: function (type) { + if(this._colorTypeBackup !== null){ + this._colorTypeBackup = type; + return; + } if (this._colorType === type) return; switch (this._colorType) { From 55a84ec5234ef59c49d0499444b5b553949eb777 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 10 Jun 2015 11:43:25 +0800 Subject: [PATCH 0287/1039] Fixed #2931: Fix draw node, Layer's blend function issue --- cocos2d/core/layers/CCLayer.js | 2 +- cocos2d/core/platform/CCMacro.js | 2 +- cocos2d/core/sprites/CCSprite.js | 2 +- cocos2d/core/textures/TexturesWebGL.js | 2 +- cocos2d/shape-nodes/CCDrawNode.js | 4 ++-- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/cocos2d/core/layers/CCLayer.js b/cocos2d/core/layers/CCLayer.js index 4e414c6397..42a6cf70e1 100644 --- a/cocos2d/core/layers/CCLayer.js +++ b/cocos2d/core/layers/CCLayer.js @@ -191,7 +191,7 @@ cc.LayerColor = cc.Layer.extend(/** @lends cc.LayerColor# */{ */ ctor: function(color, width, height){ cc.Layer.prototype.ctor.call(this); - this._blendFunc = new cc.BlendFunc(cc.BLEND_SRC, cc.BLEND_DST); + this._blendFunc = new cc.BlendFunc(cc.SRC_ALPHA, cc.ONE_MINUS_SRC_ALPHA); cc.LayerColor.prototype.init.call(this, color, width, height); }, diff --git a/cocos2d/core/platform/CCMacro.js b/cocos2d/core/platform/CCMacro.js index cabb8f2c30..e1c852497a 100644 --- a/cocos2d/core/platform/CCMacro.js +++ b/cocos2d/core/platform/CCMacro.js @@ -171,7 +171,7 @@ cc.REPEAT_FOREVER = Number.MAX_VALUE - 1; * @constant * @type Number */ -cc.BLEND_SRC = cc.OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA ? 1 : 0x0302; +cc.BLEND_SRC = (cc._renderType === cc._RENDER_TYPE_WEBGL && cc.OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA) ? cc.ONE : cc.SRC_ALPHA; /** * default gl blend dst function. Compatible with premultiplied alpha images. diff --git a/cocos2d/core/sprites/CCSprite.js b/cocos2d/core/sprites/CCSprite.js index b6662b3455..9d7acb18ff 100644 --- a/cocos2d/core/sprites/CCSprite.js +++ b/cocos2d/core/sprites/CCSprite.js @@ -738,7 +738,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ this._renderCmd._checkTextureBoundary(texture, rect, rotated); - _t.texture = texture; + _t.setTexture(texture); _t.setTextureRect(rect, rotated); // by default use "Self Render". diff --git a/cocos2d/core/textures/TexturesWebGL.js b/cocos2d/core/textures/TexturesWebGL.js index 9d9224179c..663a83966f 100644 --- a/cocos2d/core/textures/TexturesWebGL.js +++ b/cocos2d/core/textures/TexturesWebGL.js @@ -444,7 +444,7 @@ cc._tmp.WebGLTexture2D = function () { * @param {Boolean} [premultiplied=false] */ handleLoadedTexture: function (premultiplied) { - premultiplied = (premultiplied === undefined)?false: premultiplied; + premultiplied = (premultiplied === undefined) ? false : premultiplied; var self = this; // Not sure about this ! Some texture need to be updated even after loaded if (!cc._rendererInitialized) diff --git a/cocos2d/shape-nodes/CCDrawNode.js b/cocos2d/shape-nodes/CCDrawNode.js index 1d222cb9e7..1b63d3426d 100644 --- a/cocos2d/shape-nodes/CCDrawNode.js +++ b/cocos2d/shape-nodes/CCDrawNode.js @@ -105,7 +105,7 @@ cc.DrawNodeCanvas = cc.Node.extend(/** @lends cc.DrawNode# */{ var locCmd = this._renderCmd; locCmd._buffer = this._buffer = []; locCmd._drawColor = this._drawColor = cc.color(255, 255, 255, 255); - locCmd._blendFunc = this._blendFunc = new cc.BlendFunc(cc.BLEND_SRC, cc.BLEND_DST); + locCmd._blendFunc = this._blendFunc = new cc.BlendFunc(cc.SRC_ALPHA, cc.ONE_MINUS_SRC_ALPHA); this.init(); }, @@ -516,7 +516,7 @@ cc.DrawNodeWebGL = cc.Node.extend({ ctor:function () { cc.Node.prototype.ctor.call(this); this._buffer = []; - this._blendFunc = new cc.BlendFunc(cc.BLEND_SRC, cc.BLEND_DST); + this._blendFunc = new cc.BlendFunc(cc.SRC_ALPHA, cc.ONE_MINUS_SRC_ALPHA); this._drawColor = cc.color(255,255,255,255); this.init(); From 3b16bd8303a9c18ded8aba76effe1ac98e5bbdca Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 10 Jun 2015 12:01:18 +0800 Subject: [PATCH 0288/1039] Fix constant undefined issue --- cocos2d/core/platform/CCMacro.js | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/cocos2d/core/platform/CCMacro.js b/cocos2d/core/platform/CCMacro.js index e1c852497a..ae2d815e20 100644 --- a/cocos2d/core/platform/CCMacro.js +++ b/cocos2d/core/platform/CCMacro.js @@ -166,20 +166,6 @@ cc.radiansToDegress = function (angle) { */ cc.REPEAT_FOREVER = Number.MAX_VALUE - 1; -/** - * default gl blend src function. Compatible with premultiplied alpha images. - * @constant - * @type Number - */ -cc.BLEND_SRC = (cc._renderType === cc._RENDER_TYPE_WEBGL && cc.OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA) ? cc.ONE : cc.SRC_ALPHA; - -/** - * default gl blend dst function. Compatible with premultiplied alpha images. - * @constant - * @type Number - */ -cc.BLEND_DST = 0x0303; - /** * Helpful macro that setups the GL server state, the correct GL program and sets the Model View Projection matrix * @param {cc.Node} node setup node @@ -455,6 +441,20 @@ cc.CLAMP_TO_EDGE = 0x812f; */ cc.MIRRORED_REPEAT = 0x8370; +/** + * default gl blend src function. Compatible with premultiplied alpha images. + * @constant + * @type Number + */ +cc.BLEND_SRC = (cc._renderType === cc._RENDER_TYPE_WEBGL && cc.OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA) ? cc.ONE : cc.SRC_ALPHA; + +/** + * default gl blend dst function. Compatible with premultiplied alpha images. + * @constant + * @type Number + */ +cc.BLEND_DST = 0x0303; + /** * Check webgl error.Error will be shown in console if exists. * @function From 412837f88815890731e7efd6cc7e726c4bd1cab7 Mon Sep 17 00:00:00 2001 From: jianglong0156 Date: Wed, 10 Jun 2015 15:43:46 +0800 Subject: [PATCH 0289/1039] don't need use full path, the cache is relative path --- extensions/cocostudio/loader/load.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/extensions/cocostudio/loader/load.js b/extensions/cocostudio/loader/load.js index 5aa8571670..60b02f2fe6 100644 --- a/extensions/cocostudio/loader/load.js +++ b/extensions/cocostudio/loader/load.js @@ -33,8 +33,6 @@ ccs._load = (function(){ */ var load = function(file, type, path){ - file = cc.path.join(cc.loader.resPath, file); - var json = cc.loader.getRes(file); if(!json) From 6871db4de3ba49da9d6109636cc2b2810e8a4e8c Mon Sep 17 00:00:00 2001 From: Kevin Kirsche Date: Wed, 10 Jun 2015 18:05:28 -0400 Subject: [PATCH 0290/1039] Remove moot `version` property from bower.json Per bower/bower.json-spec@a325da3 --- bower.json | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/bower.json b/bower.json index 5493b6e512..e97d56bb83 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,5 @@ { "name": "cocos2d-html5", - "version": "3.4", "homepage": "http://www.cocos2d-x.org", "authors": [ "AUTHORS.txt" @@ -34,4 +33,4 @@ "test", "tests" ] -} \ No newline at end of file +} From b29721a39a33efffcf0d2ee89ea7bedf783390ae Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 11 Jun 2015 11:02:12 +0800 Subject: [PATCH 0291/1039] Plist file parsing (action-2.x.js) --- .../cocostudio/loader/parsers/action-2.x.js | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/action-2.x.js b/extensions/cocostudio/loader/parsers/action-2.x.js index 900a1fe001..2f19946113 100644 --- a/extensions/cocostudio/loader/parsers/action-2.x.js +++ b/extensions/cocostudio/loader/parsers/action-2.x.js @@ -194,11 +194,20 @@ { name: "FileData", handle: function(options, resourcePath){ - var frame = new ccs.TextureFrame(); - var texture = options["TextureFile"]; + var frame, texture, plist, path, spriteFrame; + frame = new ccs.TextureFrame(); + texture = options["TextureFile"]; if(texture != null) { - var path = texture["Path"]; - var spriteFrame = cc.spriteFrameCache.getSpriteFrame(path); + plist = texture["Plist"]; + path = texture["Path"]; + spriteFrame = cc.spriteFrameCache.getSpriteFrame(path); + if(!spriteFrame && plist){ + if(cc.loader.getRes(resourcePath + plist)){ + cc.spriteFrameCache.addSpriteFrames(resourcePath + plist); + }else{ + cc.log("%s need to be preloaded", resourcePath + plist); + } + } if(spriteFrame == null){ path = resourcePath + path; } From 19ebf245baddd6b99875205e1f664295785a3308 Mon Sep 17 00:00:00 2001 From: jianglong0156 Date: Thu, 11 Jun 2015 11:09:44 +0800 Subject: [PATCH 0292/1039] load remote url don't need add respath, add url match method --- CCBoot.js | 39 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index b2335d2d38..f90ffc16da 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -837,8 +837,13 @@ cc.loader = /** @lends cc.loader# */{ cc.error("loader for [" + type + "] not exists!"); return cb(); } - var basePath = loader.getBasePath ? loader.getBasePath() : self.resPath; - var realUrl = self.getUrl(basePath, url); + var realUrl = url; + if (!url.match(cc.urlRegExp)) + { + var basePath = loader.getBasePath ? loader.getBasePath() : self.resPath; + realUrl = self.getUrl(basePath, url); + } + if(cc.game.config["noCache"] && typeof realUrl === "string"){ if(self._noCacheRex.test(realUrl)) realUrl += "&_t=" + (new Date() - 0); @@ -2351,3 +2356,33 @@ Function.prototype.bind = Function.prototype.bind || function (oThis) { return fBound; }; + +cc.urlRegExp = new RegExp( + "^" + + // protocol identifier + "(?:(?:https?|ftp)://)" + + // user:pass authentication + "(?:\\S+(?::\\S*)?@)?" + + "(?:" + + // IP address dotted notation octets + // excludes loopback network 0.0.0.0 + // excludes reserved space >= 224.0.0.0 + // excludes network & broacast addresses + // (first & last IP address of each class) + "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" + + "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" + + "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" + + "|" + + // host name + "(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" + + // domain name + "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*" + + // TLD identifier + "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" + + ")" + + // port number + "(?::\\d{2,5})?" + + // resource path + "(?:/\\S*)?" + + "$", "i" +); From cce2328e1b1d3c0c52cf32cedbbcbccf6cd9c6e3 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 11 Jun 2015 14:23:20 +0800 Subject: [PATCH 0293/1039] fix bug: fix actiontimeline can not step to last frame when loop play --- .../cocostudio/timeline/ActionTimeline.js | 30 +++++++++++++++---- 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/extensions/cocostudio/timeline/ActionTimeline.js b/extensions/cocostudio/timeline/ActionTimeline.js index d458bb958b..dedc489b48 100644 --- a/extensions/cocostudio/timeline/ActionTimeline.js +++ b/extensions/cocostudio/timeline/ActionTimeline.js @@ -121,6 +121,7 @@ ccs.ActionTimeline = cc.Action.extend({ _loop: null, _frameEventListener: null, _animationInfos: null, + _lastFrameListener: null, ctor: function(){ cc.Action.prototype.ctor.call(this); @@ -399,15 +400,24 @@ ccs.ActionTimeline = cc.Action.extend({ } this._time += delta * this._timeSpeed; - this._currentFrame = this._time / this._frameInternal | 0; + var endoffset = this._time - this._endFrame * this._frameInternal; - this._stepToFrame(this._currentFrame); - - if(this._time > this._endFrame * this._frameInternal){ + if(endoffset < this._frameInternal){ + this._currentFrame = this._time / this._frameInternal; + this._stepToFrame(this._currentFrame); + if(endoffset >= 0 && this._lastFrameListener) + this._lastFrameListener(); + }else{ this._playing = this._loop; - if(!this._playing) + if(!this._playing){ this._time = this._endFrame * this._frameInternal; - else + if (this._currentFrame != this._endFrame){ + this._currentFrame = this._endFrame; + this._stepToFrame(this._currentFrame); + if(this._lastFrameListener) + this._lastFrameListener(); + } + }else this.gotoFrameAndPlay(this._startFrame, this._endFrame, this._loop); } @@ -492,6 +502,14 @@ ccs.ActionTimeline = cc.Action.extend({ getAnimationInfo: function(name){ return this._animationInfos[name]; + }, + + setLastFrameCallFunc: function(listener){ + this._lastFrameListener = listener; + }, + + clearLastFrameCallFunc: function(){ + this._lastFrameListener = null; } }); From 9fb5cccc60dbceb97aec534db3fc31f103485ee7 Mon Sep 17 00:00:00 2001 From: jianglong0156 Date: Thu, 11 Jun 2015 17:35:14 +0800 Subject: [PATCH 0294/1039] rename jsb.urlRegExp to cc._urlRegExp --- CCBoot.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index f90ffc16da..eaab8d21e9 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -838,7 +838,7 @@ cc.loader = /** @lends cc.loader# */{ return cb(); } var realUrl = url; - if (!url.match(cc.urlRegExp)) + if (!url.match(cc._urlRegExp)) { var basePath = loader.getBasePath ? loader.getBasePath() : self.resPath; realUrl = self.getUrl(basePath, url); @@ -2357,7 +2357,7 @@ Function.prototype.bind = Function.prototype.bind || function (oThis) { return fBound; }; -cc.urlRegExp = new RegExp( +cc._urlRegExp = new RegExp( "^" + // protocol identifier "(?:(?:https?|ftp)://)" + From 531d5aadf865b392dc00528ab2a35f076bd4db81 Mon Sep 17 00:00:00 2001 From: jianglong0156 Date: Fri, 12 Jun 2015 10:25:00 +0800 Subject: [PATCH 0295/1039] fix the prompt can not use in wechat --- cocos2d/text-input/CCIMEDispatcher.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cocos2d/text-input/CCIMEDispatcher.js b/cocos2d/text-input/CCIMEDispatcher.js index 4b713086e5..05b86215b7 100644 --- a/cocos2d/text-input/CCIMEDispatcher.js +++ b/cocos2d/text-input/CCIMEDispatcher.js @@ -389,7 +389,8 @@ cc.IMEDispatcher = cc.Class.extend(/** @lends cc.imeDispatcher# */{ this._currentInputString = delegate.string || ""; var tipMessage = delegate.getTipMessage ? delegate.getTipMessage() : "please enter your word:"; - var userInput = prompt(tipMessage, this._currentInputString); + // wechat cover the prompt funciton .So need use the Window.prototype.prompt + var userInput = Window.prototype.prompt.call(window, tipMessage, this._currentInputString); if(userInput != null) this._processDomInputString(userInput); this.dispatchInsertText("\n", 1); From 71c5db165e2fb84ac0203889b23286904296ef09 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 12 Jun 2015 11:51:38 +0800 Subject: [PATCH 0296/1039] Fix Uint8Array initialize issue --- cocos2d/core/utils/BinaryLoader.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/utils/BinaryLoader.js b/cocos2d/core/utils/BinaryLoader.js index 013c3dee6e..f0e692dc3b 100644 --- a/cocos2d/core/utils/BinaryLoader.js +++ b/cocos2d/core/utils/BinaryLoader.js @@ -105,7 +105,7 @@ cc.loader.loadBinarySync = function (url) { }; //Compatibility with IE9 -var Uint8Array = Uint8Array || Array; +window.Uint8Array = window.Uint8Array || window.Array; if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) { var IEBinaryToArray_ByteStr_Script = From 77ba0a3c847a967531ebff68cb0bbe31678165e6 Mon Sep 17 00:00:00 2001 From: Igor Shmulyan Date: Fri, 12 Jun 2015 10:49:09 +0300 Subject: [PATCH 0297/1039] restoring of sprite's color was fixed for browsers that not supported canvas new blend modes --- .../core/sprites/CCSpriteCanvasRenderCmd.js | 24 ++++++++++--------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js index 35b1fa82c9..2361afdfa3 100644 --- a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js @@ -168,10 +168,7 @@ var node = this._node, displayedColor = this._displayedColor; if (displayedColor.r === 255 && displayedColor.g === 255 && displayedColor.b === 255){ - if(this._colorized){ - this._colorized = false; - node.texture = this._originalTexture; - } + this._setOriginalTexture(); return; } @@ -201,13 +198,7 @@ proto._updateColor = function () { var node = this._node, displayedColor = this._displayedColor; if (displayedColor.r === 255 && displayedColor.g === 255 && displayedColor.b === 255) { - if (this._colorized) { - this._colorized = false; - var rect = cc.rect(node._rect); - var isRotation = node._rectRotated; - node.setTexture(this._originalTexture); - node.setTextureRect(rect, isRotation); - } + this._setOriginalTexture(); return; } @@ -231,6 +222,17 @@ } }; } + + proto._setOriginalTexture = function () { + if (this._colorized) { + this._colorized = false; + var node = this._node; + var rect = cc.rect(node._rect); + var isRotation = node._rectRotated; + node.setTexture(this._originalTexture); + node.setTextureRect(rect, isRotation); + } + }; proto.getQuad = function () { //throw an error. it doesn't support this function. From 011bf0dbd1747c85e2d79909ba816e767ae08e5a Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 12 Jun 2015 17:47:16 +0800 Subject: [PATCH 0298/1039] Issue #2835: Fixed cc.TextFieldTTF Delegate memory leaks due --- cocos2d/text-input/CCTextFieldTTF.js | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/cocos2d/text-input/CCTextFieldTTF.js b/cocos2d/text-input/CCTextFieldTTF.js index b5c9fb1283..3f1a686deb 100644 --- a/cocos2d/text-input/CCTextFieldTTF.js +++ b/cocos2d/text-input/CCTextFieldTTF.js @@ -126,7 +126,6 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ ctor:function (placeholder, dimensions, alignment, fontName, fontSize) { this.colorSpaceHolder = cc.color(127, 127, 127); this._colorText = cc.color(255,255,255, 255); - cc.imeDispatcher.addDelegate(this); cc.LabelTTF.prototype.ctor.call(this); if(fontSize !== undefined){ @@ -140,6 +139,16 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ } }, + onEnter: function(){ + cc.LabelTTF.prototype.onEnter.call(this); + cc.imeDispatcher.addDelegate(this); + }, + + onExit: function(){ + cc.LabelTTF.prototype.onExit.call(this); + cc.imeDispatcher.removeDelegate(this); + }, + /** * Gets the delegate. * @return {cc.Node} From 3afb9e609f75fc2a171ec4e210e6d02927758914 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Sat, 13 Jun 2015 13:43:52 +0800 Subject: [PATCH 0299/1039] Merge -x #8853 --- extensions/cocostudio/timeline/Frame.js | 3 ++ extensions/cocostudio/timeline/Timeline.js | 38 ++++++++++++++++++---- 2 files changed, 34 insertions(+), 7 deletions(-) diff --git a/extensions/cocostudio/timeline/Frame.js b/extensions/cocostudio/timeline/Frame.js index 89a147c24b..6ce6790ce1 100644 --- a/extensions/cocostudio/timeline/Frame.js +++ b/extensions/cocostudio/timeline/Frame.js @@ -35,12 +35,14 @@ ccs.Frame = ccs.Class.extend({ _node: null, _tweenType: null, _easingParam: null, + _enterWhenPassed: null, ctor: function(){ this._frameIndex = 0; this._tween = true; this._timeline = null; this._node = null; + this._enterWhenPassed = false; this._easingParam = []; }, @@ -1284,6 +1286,7 @@ ccs.EventFrame = ccs.Frame.extend({ ctor: function(){ ccs.Frame.prototype.ctor.call(this); this._event = ""; + this._enterWhenPassed = true; }, /** diff --git a/extensions/cocostudio/timeline/Timeline.js b/extensions/cocostudio/timeline/Timeline.js index 273ef72a11..7f4745a6c7 100644 --- a/extensions/cocostudio/timeline/Timeline.js +++ b/extensions/cocostudio/timeline/Timeline.js @@ -206,6 +206,13 @@ ccs.Timeline = ccs.Class.extend({ if(this._currentKeyFrameIndex >= this._frames[0].getFrameIndex()) needEnterFrame = true; + this._fromIndex = 0; + + if(length > 1) + this._toIndex = 1; + else + this._toIndex = 0; + from = to = this._frames[0]; this._currentKeyFrameIndex = 0; this._betweenDuration = this._frames[0].getFrameIndex(); @@ -213,6 +220,9 @@ ccs.Timeline = ccs.Class.extend({ } else if(frameIndex >= this._frames[length - 1].getFrameIndex()) { + this._fromIndex = length - 1; + this._toIndex = 0; + from = to = this._frames[length - 1]; this._currentKeyFrameIndex = this._frames[length - 1].getFrameIndex(); this._betweenDuration = 0; @@ -236,6 +246,16 @@ ccs.Timeline = ccs.Class.extend({ low = mid + 1; } + this._fromIndex = target; + + if(length > 1) + this._toIndex = (target + 1) | 0; + else + this._toIndex = (target) | 0; + + from = this._frames[this._fromIndex]; + to = this._frames[this._toIndex]; + from = this._frames[target]; to = this._frames[target+1]; @@ -254,6 +274,8 @@ ccs.Timeline = ccs.Class.extend({ }, _updateCurrentKeyFrame: function(frameIndex){ + if(frameIndex > 60) + var a = 0; //! If play to current frame's front or back, then find current frame again if (frameIndex < this._currentKeyFrameIndex || frameIndex >= this._currentKeyFrameIndex + this._betweenDuration) { @@ -273,10 +295,10 @@ ccs.Timeline = ccs.Class.extend({ } else if(frameIndex >= this._frames[length - 1].getFrameIndex()) { - from = to = this._frames[length - 1]; - this._currentKeyFrameIndex = this._frames[length - 1].getFrameIndex(); - this._betweenDuration = 0; - break; + var lastFrameIndex = this._frames[length - 1].getFrameIndex(); + if(this._currentKeyFrameIndex >= lastFrameIndex) + return; + frameIndex = lastFrameIndex; } do{ @@ -293,10 +315,12 @@ ccs.Timeline = ccs.Class.extend({ to = this._frames[this._toIndex]; if (frameIndex === from.getFrameIndex()) - { break; - } - }while (frameIndex < from.getFrameIndex() || frameIndex >= to.getFrameIndex()); + if(frameIndex > from.getFrameIndex() && frameIndex < to.getFrameIndex()) + break; + if(from.isEnterWhenPassed()) + from.onEnter(to); + }while (true); this._betweenDuration = to.getFrameIndex() - from.getFrameIndex(); From bb01ba81e9d0b648d30a2cabbd095c84e9f7a566 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 15 Jun 2015 15:22:29 +0800 Subject: [PATCH 0300/1039] Fixed sorted result is wrong(_sortEventListenersOfSceneGraphPriorityDes) --- cocos2d/core/event-manager/CCEventManager.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/event-manager/CCEventManager.js b/cocos2d/core/event-manager/CCEventManager.js index d01b3527aa..0d02a9a661 100644 --- a/cocos2d/core/event-manager/CCEventManager.js +++ b/cocos2d/core/event-manager/CCEventManager.js @@ -313,8 +313,10 @@ cc.eventManager = /** @lends cc.eventManager# */{ _sortEventListenersOfSceneGraphPriorityDes : function(l1, l2){ var locNodePriorityMap = cc.eventManager._nodePriorityMap, node1 = l1._getSceneGraphPriority(), node2 = l2._getSceneGraphPriority(); - if(!l1 || !l2 || !node1 || !node2 || !locNodePriorityMap[node1.__instanceId] || !locNodePriorityMap[node2.__instanceId]) + if( !l2 || !node2 || !locNodePriorityMap[node2.__instanceId] ) return -1; + else if( !l1 || !node1 || !locNodePriorityMap[node1.__instanceId] ) + return 1; return locNodePriorityMap[l2._getSceneGraphPriority().__instanceId] - locNodePriorityMap[l1._getSceneGraphPriority().__instanceId]; }, From 367ba065b9883ec73bec70aebea55e58685d9f7f Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 16 Jun 2015 16:46:40 +0800 Subject: [PATCH 0301/1039] Fixed a bug that Change the url failure(VideoPlayer) --- extensions/ccui/uiwidgets/UIVideoPlayer.js | 93 ++++++++++++++-------- 1 file changed, 59 insertions(+), 34 deletions(-) diff --git a/extensions/ccui/uiwidgets/UIVideoPlayer.js b/extensions/ccui/uiwidgets/UIVideoPlayer.js index ff842577d7..597d9ca23b 100644 --- a/extensions/ccui/uiwidgets/UIVideoPlayer.js +++ b/extensions/ccui/uiwidgets/UIVideoPlayer.js @@ -50,14 +50,7 @@ ccui.VideoPlayer = ccui.Widget.extend({ * @returns {String} */ getURL: function() { - var video = this._renderCmd._video; - if (video) { - var source = video.getElementsByTagName("source"); - if (source && source[0]) - return source[0].src; - } - - return ""; + return this._renderCmd._url; }, /** @@ -65,8 +58,10 @@ ccui.VideoPlayer = ccui.Widget.extend({ */ play: function(){ var video = this._renderCmd._video; - if(video) + if(video){ + this._renderCmd._played = true; video.play(); + } }, /** @@ -248,12 +243,8 @@ ccui.VideoPlayer.EventType = { (function(polyfill){ ccui.VideoPlayer.RenderCmd = function(node){ cc.Node.CanvasRenderCmd.call(this, node); - this._video = document.createElement("video"); - //this._video.controls = "controls"; - this._video.preload = "metadata"; - this._video.style["visibility"] = "hidden"; - this._loaded = false; this._listener = null; + this._url = ""; this.initStyle(); }; @@ -332,36 +323,67 @@ ccui.VideoPlayer.EventType = { }; proto.updateURL = function(path){ - var video = this._video; - var source = document.createElement("source"); - source.src = path; - video.appendChild(source); - var extname = cc.path.extname(path); - for(var i=0; i Date: Tue, 16 Jun 2015 18:24:02 +0800 Subject: [PATCH 0302/1039] Change the path(UIVideoPlayerTest.js) --- extensions/ccui/uiwidgets/UIVideoPlayer.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/ccui/uiwidgets/UIVideoPlayer.js b/extensions/ccui/uiwidgets/UIVideoPlayer.js index 597d9ca23b..11bb68fce3 100644 --- a/extensions/ccui/uiwidgets/UIVideoPlayer.js +++ b/extensions/ccui/uiwidgets/UIVideoPlayer.js @@ -364,7 +364,7 @@ ccui.VideoPlayer.EventType = { }; video.addEventListener(polyfill.event, cb); - video.controls = "controls"; + //video.controls = "controls"; video.preload = "metadata"; video.style["visibility"] = "hidden"; this._loaded = false; From c0641b40e6981ffcd7deba28122e6ae0eb9596b6 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 17 Jun 2015 11:34:27 +0800 Subject: [PATCH 0303/1039] Preventing operation of the remote address error --- extensions/ccui/uiwidgets/UIWebView.js | 36 ++++++++++++++++---------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/extensions/ccui/uiwidgets/UIWebView.js b/extensions/ccui/uiwidgets/UIWebView.js index e9ac910b60..b4afc7af4e 100644 --- a/extensions/ccui/uiwidgets/UIWebView.js +++ b/extensions/ccui/uiwidgets/UIWebView.js @@ -84,13 +84,17 @@ ccui.WebView = ccui.Widget.extend({ * go back */ goBack: function(){ - if(ccui.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(); + try{ + if(ccui.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(); + } + }catch(err){ + cc.log(err); } }, @@ -98,13 +102,17 @@ ccui.WebView = ccui.Widget.extend({ * go forward */ goForward: function(){ - if(ccui.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(); + try{ + if(ccui.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(); + } + }catch(err){ + cc.log(err); } }, From d8a7b863917772fbb3bb612cb37c36b074e7e6f4 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 17 Jun 2015 11:48:52 +0800 Subject: [PATCH 0304/1039] Fixed widgetFromJsonFile bug(#20035) --- extensions/cocostudio/loader/parsers/compatible.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/cocostudio/loader/parsers/compatible.js b/extensions/cocostudio/loader/parsers/compatible.js index 3f34b13956..caa681d4fc 100644 --- a/extensions/cocostudio/loader/parsers/compatible.js +++ b/extensions/cocostudio/loader/parsers/compatible.js @@ -41,7 +41,7 @@ * @returns {*} */ widgetFromJsonFile: function(file){ - var json = cc.loader.getRes(cc.path.join(cc.loader.resPath, file)); + var json = cc.loader.getRes(file); if(json) this._fileDesignSizes[file] = cc.size(json["designWidth"]||0, json["designHeight"]||0); From 900744fd49669196eb4ae3e6fa125d4b0855d636 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 17 Jun 2015 13:52:54 +0800 Subject: [PATCH 0305/1039] Prevent reference method does not exist --- cocos2d/core/utils/BinaryLoader.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/utils/BinaryLoader.js b/cocos2d/core/utils/BinaryLoader.js index f0e692dc3b..e199733458 100644 --- a/cocos2d/core/utils/BinaryLoader.js +++ b/cocos2d/core/utils/BinaryLoader.js @@ -107,7 +107,7 @@ cc.loader.loadBinarySync = function (url) { //Compatibility with IE9 window.Uint8Array = window.Uint8Array || window.Array; -if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) { +if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent) && window.IEBinaryToArray_ByteStr && window.IEBinaryToArray_ByteStr_Last) { var IEBinaryToArray_ByteStr_Script = "\r\n" + //"