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
diff --git a/AUTHORS.txt b/AUTHORS.txt
index 208e7edf3e..5a20dc7535 100644
--- a/AUTHORS.txt
+++ b/AUTHORS.txt
@@ -1,22 +1,20 @@
Cocos2d-html5 authors
-(ordered by the join in time)
+(Ordered by join time)
Core Developers:
Shun Lin (Sean Lin)
- Hao Wu (WuHao)
-
- Dingping Lv (David Lv)
-
Ricardo Quesada
- Huabin LING (pandamicro)
+ Huabin LING (@pandamicro)
+
+ Sijie Wang (@VisualSJ)
- Sijie Wang
+ Long Jiang (@jianglong0156)
- Jialong Zhai
+ Menghe Zhang (@ZhangMenghe)
Contributors:
Name GithubID Main contribution
@@ -86,8 +84,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
@@ -164,17 +163,22 @@ erykwalder @erykwalder Function.prototype.bind bug fix
ZippoLag @ZippoLag cc.Application.getCurrentLanguage bug fix
typo fix
+ Fixed `cc.TMXObjectGroup#objectNamed` not returning the result bug
Asano @LaercioAsano cc.Node bug fix
Bruno Assarisse @bassarisse cc.LabelBMFont bug fix
-musikov @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 bug fix
- cc.Scale9Sprite bug fix
+ cc.ProgressTimer bugs fix
+ cc.Scale9Sprite bugs fix
+ cc.RenderTexture bug fix
+ cc.ParticleSystem bug fix
+ Made CCProgressTimerCanvasRenderCmd to properly show colorized sprites
+ cc.ScrollView and cc.TableView: added check for parent visibility in onTouchBegan method
Han XiaoLong @kpkhxlgy0 cc.ParticleSytem bug fix
@@ -185,6 +189,8 @@ Xiaodong Liu @tianxing113 cc.Spawn.create bug fix
Park Hyun Chen @sincntx Touch anywhere of screen to finish input when using cc.EditBox
ccui.TextBMFont bug fix
+ cc.game bug fix
+ Fixed an issue of cc.ArmatureAnimation's setMovementEventCallFunc
Ninja Lau @mutoo A typo bug in UILayout fix
One-loop CCArmatureAnimation can't finish when setSpeedScale is less than 1.0 bug fix
@@ -216,9 +222,64 @@ nopakos @nopakos cc.Texture2D bug fix
Robert Rouhani @Robmaister cc.TMXMapInfo bug fix
cc.TMXLayer 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
+
+Hermanto @man2 cc.loader bug fix
+
+Long Jiang @jianglong0156 cc.LabelBMFont bug fix
+ KeyCode bug fix
+ ccui.ListView bug fix
+
+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
+ ccui.PageView bug fix
+ Fixed crash when character not found into BMP font
+ Fixed restoring of sprite's color issue
+
+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
+
+RackovychV @RackovychV Fixed a bug of `cc.Scheduler`'s `pauseAllTargetsWithMinPriority`
+
+giuseppelt @giuseppelt Fixed TransitionSlideX callback sequence issue
+
+YShumov @pixmaster Fixed issue in music end event
+
+SPACELAN @spacelan Fixed `inverse` function bug of `cc.math.Matrix4`
+
+patriciog @patriciog Allowed timeline animations with only one frame
+
+Ningxin Hu @huningxin SIMD.js optimization for kazmath functions
+
+Zachary Lester @ZLester Fix typo in AUTHORS.txt
+
+Juan Carlos @Ruluk Fixed a bug where not resetting cc.Audio._ignoreEnded when replaying a sound caused it to stay in a "playing" state
+
+Maxim Litvinov @metalim Throw new Error object instead of error message string
+
Retired Core Developers:
Shengxiang Chen (Nero Chan)
Xingsen Ma
+ Jialong Zhai (@JoshuaAstray)
+ Hao Wu (WuHao)
+ Dingping Lv (David Lv)
Cocos2d-x and cocos2d-html5 can not grow so fast without the active community.
diff --git a/CCBoot.js b/CCBoot.js
index ad2fe3c4c2..22c50494b6 100644
--- a/CCBoot.js
+++ b/CCBoot.js
@@ -1,6 +1,6 @@
/****************************************************************************
Copyright (c) 2011-2012 cocos2d-x.org
- Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2013-2015 Chukong Technologies Inc.
http://www.cocos2d-x.org
@@ -32,9 +32,7 @@ var cc = cc || {};
cc._tmp = cc._tmp || {};
cc._LogInfos = {};
-/** @expose */
-window._p;
-_p = window;
+var _p = window;
/** @expose */
_p.gl;
/** @expose */
@@ -45,8 +43,10 @@ _p.DeviceOrientationEvent;
_p.DeviceMotionEvent;
/** @expose */
_p.AudioContext;
-/** @expose */
-_p.webkitAudioContext;
+if (!_p.AudioContext) {
+ /** @expose */
+ _p.webkitAudioContext;
+}
/** @expose */
_p.mozAudioContext;
_p = Object.prototype;
@@ -54,18 +54,35 @@ _p = Object.prototype;
_p._super;
/** @expose */
_p.ctor;
-delete window._p;
+_p = null;
-cc.newElement = function (x) {
- return document.createElement(x);
-};
+/**
+ * drawing primitive of game engine
+ * @type {cc.DrawingPrimitive}
+ */
+cc._drawingUtil = null;
-cc._addEventListener = function (element, type, listener, useCapture) {
- element.addEventListener(type, listener, useCapture);
-};
+/**
+ * main Canvas 2D/3D Context of game engine
+ * @type {CanvasRenderingContext2D|WebGLRenderingContext}
+ */
+cc._renderContext = null;
+cc._supportRender = false;
+
+/**
+ * Main canvas of game engine
+ * @type {HTMLCanvasElement}
+ */
+cc._canvas = null;
+
+/**
+ * The element contains the game canvas
+ * @type {HTMLDivElement}
+ */
+cc.container = null;
+cc._gameDiv = null;
-//is nodejs ? Used to support node-webkit.
-cc._isNodeJs = typeof require !== 'undefined' && require("fs");
+window.ENABLE_IMAEG_POOL = true;
/**
* Iterate over an object or an array, executing a function for each matched element.
@@ -95,11 +112,11 @@ cc.each = function (obj, iterator, context) {
* @param {object} *sources
* @returns {object}
*/
-cc.extend = function(target) {
+cc.extend = function (target) {
var sources = arguments.length >= 2 ? Array.prototype.slice.call(arguments, 1) : [];
- cc.each(sources, function(src) {
- for(var key in src) {
+ cc.each(sources, function (src) {
+ for (var key in src) {
if (src.hasOwnProperty(key)) {
target[key] = src[key];
}
@@ -108,13 +125,33 @@ cc.extend = function(target) {
return target;
};
+/**
+ * Another way to subclass: Using Google Closure.
+ * The following code was copied + pasted from goog.base / goog.inherits
+ * @function
+ * @param {Function} childCtor
+ * @param {Function} parentCtor
+ */
+cc.inherits = function (childCtor, parentCtor) {
+ function tempCtor() {}
+ tempCtor.prototype = parentCtor.prototype;
+ childCtor.superClass_ = parentCtor.prototype;
+ childCtor.prototype = new tempCtor();
+ childCtor.prototype.constructor = childCtor;
+
+ // Copy "static" method, but doesn't generate subclasses.
+ // for( var i in parentCtor ) {
+ // childCtor[ i ] = parentCtor[ i ];
+ // }
+};
+
/**
* Check the obj whether is function or not
* @param {*} obj
* @returns {boolean}
*/
-cc.isFunction = function(obj) {
- return typeof obj == 'function';
+cc.isFunction = function (obj) {
+ return typeof obj === 'function';
};
/**
@@ -122,8 +159,8 @@ cc.isFunction = function(obj) {
* @param {*} obj
* @returns {boolean}
*/
-cc.isNumber = function(obj) {
- return typeof obj == 'number' || Object.prototype.toString.call(obj) == '[object Number]';
+cc.isNumber = function (obj) {
+ return typeof obj === 'number' || Object.prototype.toString.call(obj) === '[object Number]';
};
/**
@@ -131,8 +168,8 @@ cc.isNumber = function(obj) {
* @param {*} obj
* @returns {boolean}
*/
-cc.isString = function(obj) {
- return typeof obj == 'string' || Object.prototype.toString.call(obj) == '[object String]';
+cc.isString = function (obj) {
+ return typeof obj === 'string' || Object.prototype.toString.call(obj) === '[object String]';
};
/**
@@ -140,8 +177,9 @@ cc.isString = function(obj) {
* @param {*} obj
* @returns {boolean}
*/
-cc.isArray = function(obj) {
- return Object.prototype.toString.call(obj) == '[object Array]';
+cc.isArray = function (obj) {
+ return Array.isArray(obj) ||
+ (typeof obj === 'object' && Object.prototype.toString.call(obj) === '[object Array]');
};
/**
@@ -149,8 +187,8 @@ cc.isArray = function(obj) {
* @param {*} obj
* @returns {boolean}
*/
-cc.isUndefined = function(obj) {
- return typeof obj == 'undefined';
+cc.isUndefined = function (obj) {
+ return typeof obj === 'undefined';
};
/**
@@ -158,10 +196,8 @@ cc.isUndefined = function(obj) {
* @param {*} obj
* @returns {boolean}
*/
-cc.isObject = function(obj) {
- var type = typeof obj;
-
- return type == 'function' || (obj && type == 'object');
+cc.isObject = function (obj) {
+ return typeof obj === "object" && Object.prototype.toString.call(obj) === '[object Object]';
};
/**
@@ -175,12 +211,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+++++++++++++++++++++++++++++++
@@ -193,8 +229,9 @@ cc.isCrossOrigin = function (url) {
* @param {object} target
* @constructor
*/
-cc.AsyncPool = function(srcObj, limit, iterator, onEnd, target){
+cc.AsyncPool = function (srcObj, limit, iterator, onEnd, target) {
var self = this;
+ self._finished = false;
self._srcObj = srcObj;
self._limit = limit;
self._pool = [];
@@ -203,10 +240,10 @@ cc.AsyncPool = function(srcObj, limit, iterator, onEnd, target){
self._onEnd = onEnd;
self._onEndTarget = target;
self._results = srcObj instanceof Array ? [] : {};
- self._isErr = false;
+ self._errors = srcObj instanceof Array ? [] : {};
- cc.each(srcObj, function(value, index){
- self._pool.push({index : index, value : value});
+ cc.each(srcObj, function (value, index) {
+ self._pool.push({index: index, value: value});
});
self.size = self._pool.length;
@@ -215,59 +252,70 @@ cc.AsyncPool = function(srcObj, limit, iterator, onEnd, target){
self._limit = self._limit || self.size;
- self.onIterator = function(iterator, target){
+ self.onIterator = function (iterator, target) {
self._iterator = iterator;
self._iteratorTarget = target;
};
- self.onEnd = function(endCb, endCbTarget){
+ self.onEnd = function (endCb, endCbTarget) {
self._onEnd = endCb;
self._onEndTarget = endCbTarget;
};
- self._handleItem = function(){
+ self._handleItem = function () {
var self = this;
- if(self._pool.length == 0)
- return; //return directly if the array's length = 0
- if(self._workingSize >= self._limit)
- return; //return directly if the working size great equal limit number
+ if (self._pool.length === 0 || self._workingSize >= self._limit)
+ return; //return directly if the array's length = 0 or the working size great equal limit number
+
var item = self._pool.shift();
var value = item.value, index = item.index;
self._workingSize++;
- self._iterator.call(self._iteratorTarget, value, index, function(err){
- if(self._isErr)
- return;
+ self._iterator.call(self._iteratorTarget, value, index,
+ function (err, result) {
+ if (self._finished) {
+ return;
+ }
- self.finishedSize++;
- self._workingSize--;
- if(err) {
- self._isErr = true;
- if(self._onEnd)
- self._onEnd.call(self._onEndTarget, err);
- return;
- }
+ if (err) {
+ self._errors[this.index] = err;
+ }
+ else {
+ self._results[this.index] = result;
+ }
- var arr = Array.prototype.slice.call(arguments, 1);
- self._results[this.index] = arr[0];
- if(self.finishedSize == self.size) {
- if(self._onEnd)
- self._onEnd.call(self._onEndTarget, null, self._results);
- return;
- }
- self._handleItem();
- }.bind(item), self);
+ self.finishedSize++;
+ self._workingSize--;
+ if (self.finishedSize === self.size) {
+ var errors = self._errors.length === 0 ? null : self._errors;
+ self.onEnd(errors, self._results);
+ return;
+ }
+ self._handleItem();
+ }.bind(item),
+ self);
};
- self.flow = function(){
+ self.flow = function () {
var self = this;
- if(self._pool.length == 0) {
- if(self._onEnd)
+ if (self._pool.length === 0) {
+ if (self._onEnd)
self._onEnd.call(self._onEndTarget, null, []);
- return;
+ return;
}
- for(var i = 0; i < self._limit; i++)
+ for (var i = 0; i < self._limit; i++)
self._handleItem();
- }
+ };
+
+ self.onEnd = function(errors, results) {
+ self._finished = true;
+ if (self._onEnd) {
+ var selector = self._onEnd;
+ var target = self._onEndTarget;
+ self._onEnd = null;
+ self._onEndTarget = null;
+ selector.call(target, errors, results);
+ }
+ };
};
/**
@@ -281,8 +329,8 @@ cc.async = /** @lends cc.async# */{
* @param {Object} [target]
* @return {cc.AsyncPool}
*/
- series : function(tasks, cb, target){
- var asyncPool = new cc.AsyncPool(tasks, 1, function(func, index, cb1){
+ series: function (tasks, cb, target) {
+ var asyncPool = new cc.AsyncPool(tasks, 1, function (func, index, cb1) {
func.call(target, cb1);
}, cb, target);
asyncPool.flow();
@@ -296,8 +344,8 @@ cc.async = /** @lends cc.async# */{
* @param {Object} [target]
* @return {cc.AsyncPool}
*/
- parallel : function(tasks, cb, target){
- var asyncPool = new cc.AsyncPool(tasks, 0, function(func, index, cb1){
+ parallel: function (tasks, cb, target) {
+ var asyncPool = new cc.AsyncPool(tasks, 0, function (func, index, cb1) {
func.call(target, cb1);
}, cb, target);
asyncPool.flow();
@@ -311,14 +359,14 @@ cc.async = /** @lends cc.async# */{
* @param {Object} [target]
* @return {cc.AsyncPool}
*/
- waterfall : function(tasks, cb, target){
+ waterfall: function (tasks, cb, target) {
var args = [];
var lastResults = [null];//the array to store the last results
var asyncPool = new cc.AsyncPool(tasks, 1,
function (func, index, cb1) {
args.push(function (err) {
args = Array.prototype.slice.call(arguments, 1);
- if(tasks.length - 1 == index) lastResults = lastResults.concat(args);//while the last task
+ if (tasks.length - 1 === index) lastResults = lastResults.concat(args);//while the last task
cb1.apply(null, arguments);
});
func.apply(target, args);
@@ -337,18 +385,18 @@ cc.async = /** @lends cc.async# */{
* Do tasks by iterator.
* @param {Array|Object} tasks
* @param {function|Object} iterator
- * @param {function} cb callback
+ * @param {function} [callback]
* @param {Object} [target]
* @return {cc.AsyncPool}
*/
- map : function(tasks, iterator, cb, target){
+ map: function (tasks, iterator, callback, target) {
var locIterator = iterator;
- if(typeof(iterator) == "object"){
- cb = iterator.cb;
+ if (typeof(iterator) === "object") {
+ callback = iterator.cb;
target = iterator.iteratorTarget;
locIterator = iterator.iterator;
}
- var asyncPool = new cc.AsyncPool(tasks, 0, locIterator, cb, target);
+ var asyncPool = new cc.AsyncPool(tasks, 0, locIterator, callback, target);
asyncPool.flow();
return asyncPool;
},
@@ -361,7 +409,7 @@ cc.async = /** @lends cc.async# */{
* @param {function} cb callback
* @param {Object} [target]
*/
- mapLimit : function(tasks, limit, iterator, cb, target){
+ mapLimit: function (tasks, limit, iterator, cb, target) {
var asyncPool = new cc.AsyncPool(tasks, limit, iterator, cb, target);
asyncPool.flow();
return asyncPool;
@@ -374,6 +422,8 @@ cc.async = /** @lends cc.async# */{
* @class
*/
cc.path = /** @lends cc.path# */{
+ normalizeRE: /[^\.\/]+\/\.\.\//,
+
/**
* Join strings to be a path.
* @example
@@ -388,7 +438,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;
},
@@ -413,11 +463,11 @@ cc.path = /** @lends cc.path# */{
* @param {string} fileName
* @returns {string}
*/
- mainFileName: function(fileName){
- if(fileName){
- var idx = fileName.lastIndexOf(".");
- if(idx !== -1)
- return fileName.substring(0,idx);
+ mainFileName: function (fileName) {
+ if (fileName) {
+ var idx = fileName.lastIndexOf(".");
+ if (idx !== -1)
+ return fileName.substring(0, idx);
}
return fileName;
},
@@ -441,7 +491,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 +549,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) : "";
@@ -510,507 +560,722 @@ cc.path = /** @lends cc.path# */{
index = pathStr.lastIndexOf("/");
index = index <= 0 ? 0 : index + 1;
return pathStr.substring(0, index) + basename + ext + tempStr;
+ },
+ //todo make public after verification
+ _normalize: function (url) {
+ var oldUrl = url = String(url);
+
+ //removing all ../
+ do {
+ oldUrl = url;
+ url = url.replace(this.normalizeRE, "");
+ } while (oldUrl.length !== url.length);
+ return url;
}
};
//+++++++++++++++++++++++++something about path end++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++something about loader start+++++++++++++++++++++++++++
/**
- * Loader for resource loading process. It's a singleton object.
+ * Resource loading management. Created by in CCBoot.js as a singleton
+ * cc.loader.
+ * @name cc.Loader
* @class
+ * @memberof cc
+ * @see cc.loader
*/
-cc.loader = /** @lends cc.loader# */{
- _jsCache: {},//cache for js
- _register: {},//register of loaders
- _langPathCache: {},//cache for lang path
- _aliases: {},//aliases for res url
- resPath: "",//root path of resource
- audioPath: "",//root path of audio
- cache: {},//cache for data loaded
-
- /**
- * Get XMLHttpRequest.
- * @returns {XMLHttpRequest}
- */
- getXMLHttpRequest: function () {
- return window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP");
+var imagePool = {
+ _pool: new Array(10),
+ _MAX: 10,
+ _smallImg: "data:image/gif;base64,R0lGODlhAQABAAAAACwAAAAAAQABAAA=",
+
+ count: 0,
+ get: function () {
+ if (this.count > 0) {
+ this.count--;
+ var result = this._pool[this.count];
+ this._pool[this.count] = null;
+ return result;
+ }
+ else {
+ return new Image();
+ }
},
+ put: function (img) {
+ var pool = this._pool;
+ if (img instanceof HTMLImageElement && this.count < this._MAX) {
+ img.src = this._smallImg;
+ pool[this.count] = img;
+ this.count++;
+ }
+ }
+};
+
+/**
+ * Singleton instance of cc.Loader.
+ * @name cc.loader
+ * @member {cc.Loader}
+ * @memberof cc
+ */
+cc.loader = (function () {
+ var _jsCache = {}, //cache for js
+ _register = {}, //register of loaders
+ _langPathCache = {}, //cache for lang path
+ _aliases = {}, //aliases for res url
+ _queue = {}, // Callback queue for resources already loading
+ _urlRegExp = new RegExp("^(?:https?|ftp)://\\S*$", "i");
+
+ return /** @lends cc.Loader# */{
+ /**
+ * Root path of resources.
+ * @type {String}
+ */
+ resPath: "",
+
+ /**
+ * Root path of audio resources
+ * @type {String}
+ */
+ audioPath: "",
+
+ /**
+ * Cache for data loaded.
+ * @type {Object}
+ */
+ cache: {},
+
+ /**
+ * Get XMLHttpRequest.
+ * @returns {XMLHttpRequest}
+ */
+ getXMLHttpRequest: function () {
+ var xhr = window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP");
+ xhr.timeout = 10000;
+ if (xhr.ontimeout === undefined) {
+ xhr._timeoutId = -1;
+ }
+ return xhr;
+ },
- //@MODE_BEGIN DEV
+ //@MODE_BEGIN DEV
- _getArgs4Js: function (args) {
- var a0 = args[0], a1 = args[1], a2 = args[2], results = ["", null, null];
+ _getArgs4Js: function (args) {
+ var a0 = args[0], a1 = args[1], a2 = args[2], results = ["", null, null];
- if (args.length === 1) {
- results[1] = a0 instanceof Array ? a0 : [a0];
- } else if (args.length === 2) {
- if (typeof a1 == "function") {
+ if (args.length === 1) {
results[1] = a0 instanceof Array ? a0 : [a0];
- results[2] = a1;
- } else {
+ } else if (args.length === 2) {
+ if (typeof a1 === "function") {
+ results[1] = a0 instanceof Array ? a0 : [a0];
+ results[2] = a1;
+ } else {
+ results[0] = a0 || "";
+ results[1] = a1 instanceof Array ? a1 : [a1];
+ }
+ } else if (args.length === 3) {
results[0] = a0 || "";
results[1] = a1 instanceof Array ? a1 : [a1];
- }
- } else if (args.length === 3) {
- results[0] = a0 || "";
- results[1] = a1 instanceof Array ? a1 : [a1];
- results[2] = a2;
- } else throw "arguments error to load js!";
- return results;
- },
-
- /**
- * Load js files.
- * If the third parameter doesn't exist, then the baseDir turns to be "".
- *
- * @param {string} [baseDir] The pre path for jsList or the list of js path.
- * @param {array} jsList List of js path.
- * @param {function} [cb] Callback function
- * @returns {*}
- */
- loadJs: function (baseDir, jsList, cb) {
- var self = this, localJsCache = self._jsCache,
- args = self._getArgs4Js(arguments);
-
- var preDir = args[0], list = args[1], callback = args[2];
- if (navigator.userAgent.indexOf("Trident/5") > -1) {
- self._loadJs4Dependency(preDir, list, 0, callback);
- } else {
- cc.async.map(list, function (item, index, cb1) {
- var jsPath = cc.path.join(preDir, item);
- if (localJsCache[jsPath]) return cb1(null);
- self._createScript(jsPath, false, cb1);
- }, callback);
- }
- },
- /**
- * Load js width loading image.
- *
- * @param {string} [baseDir]
- * @param {array} jsList
- * @param {function} [cb]
- */
- loadJsWithImg: function (baseDir, jsList, cb) {
- var self = this, jsLoadingImg = self._loadJsImg(),
- args = self._getArgs4Js(arguments);
- this.loadJs(args[0], args[1], function (err) {
- if (err) throw err;
- jsLoadingImg.parentNode.removeChild(jsLoadingImg);//remove loading gif
- if (args[2]) args[2]();
- });
- },
- _createScript: function (jsPath, isAsync, cb) {
- var d = document, self = this, s = cc.newElement('script');
- s.async = isAsync;
- s.src = jsPath;
- self._jsCache[jsPath] = true;
- cc._addEventListener(s, 'load', function () {
- s.parentNode.removeChild(s);
- this.removeEventListener('load', arguments.callee, false);
- cb();
- }, false);
- cc._addEventListener(s, 'error', function () {
- s.parentNode.removeChild(s);
- cb("Load " + jsPath + " failed!");
- }, false);
- d.body.appendChild(s);
- },
- _loadJs4Dependency: function (baseDir, jsList, index, cb) {
- if (index >= jsList.length) {
- if (cb) cb();
- return;
- }
- var self = this;
- self._createScript(cc.path.join(baseDir, jsList[index]), false, function (err) {
- if (err) return cb(err);
- self._loadJs4Dependency(baseDir, jsList, index + 1, cb);
- });
- },
- _loadJsImg: function () {
- var d = document, jsLoadingImg = d.getElementById("cocos2d_loadJsImg");
- if (!jsLoadingImg) {
- jsLoadingImg = cc.newElement('img');
-
- if (cc._loadingImage)
- jsLoadingImg.src = cc._loadingImage;
-
- var canvasNode = d.getElementById(cc.game.config["id"]);
- canvasNode.style.backgroundColor = "black";
- canvasNode.parentNode.appendChild(jsLoadingImg);
-
- var canvasStyle = getComputedStyle ? getComputedStyle(canvasNode) : canvasNode.currentStyle;
- if (!canvasStyle)
- canvasStyle = {width: canvasNode.width, height: canvasNode.height};
- jsLoadingImg.style.left = canvasNode.offsetLeft + (parseFloat(canvasStyle.width) - jsLoadingImg.width) / 2 + "px";
- jsLoadingImg.style.top = canvasNode.offsetTop + (parseFloat(canvasStyle.height) - jsLoadingImg.height) / 2 + "px";
- jsLoadingImg.style.position = "absolute";
- }
- return jsLoadingImg;
- },
- //@MODE_END DEV
-
- /**
- * Load a single resource as txt.
- * @param {string} url
- * @param {function} [cb] arguments are : err, txt
- */
- loadTxt: function (url, cb) {
- if (!cc._isNodeJs) {
- var xhr = this.getXMLHttpRequest(),
- errInfo = "load " + url + " failed!";
- xhr.open("GET", url, true);
- if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) {
- // 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);
- };
+ results[2] = a2;
+ } else throw new Error("arguments error to load js!");
+ return results;
+ },
+
+ isLoading: function (url) {
+ return (_queue[url] !== undefined);
+ },
+
+ /**
+ * Load js files.
+ * If the third parameter doesn't exist, then the baseDir turns to be "".
+ *
+ * @param {string} [baseDir] The pre path for jsList or the list of js path.
+ * @param {array} jsList List of js path.
+ * @param {function} [cb] Callback function
+ * @returns {*}
+ */
+ loadJs: function (baseDir, jsList, cb) {
+ var self = this,
+ args = self._getArgs4Js(arguments);
+
+ var preDir = args[0], list = args[1], callback = args[2];
+ if (navigator.userAgent.indexOf("Trident/5") > -1) {
+ self._loadJs4Dependency(preDir, list, 0, callback);
} 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);
- };
+ cc.async.map(list, function (item, index, cb1) {
+ var jsPath = cc.path.join(preDir, item);
+ if (_jsCache[jsPath]) return cb1(null);
+ self._createScript(jsPath, false, cb1);
+ }, callback);
}
- xhr.send(null);
- } else {
- var fs = require("fs");
- fs.readFile(url, function (err, data) {
- err ? cb(err) : cb(null, data.toString());
+ },
+ /**
+ * Load js width loading image.
+ *
+ * @param {string} [baseDir]
+ * @param {array} jsList
+ * @param {function} [cb]
+ */
+ loadJsWithImg: function (baseDir, jsList, cb) {
+ var self = this, jsLoadingImg = self._loadJsImg(),
+ args = self._getArgs4Js(arguments);
+ this.loadJs(args[0], args[1], function (err) {
+ if (err) throw new Error(err);
+ jsLoadingImg.parentNode.removeChild(jsLoadingImg);//remove loading gif
+ if (args[2]) args[2]();
});
- }
- },
- _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");
+ },
+ _createScript: function (jsPath, isAsync, cb) {
+ var d = document, self = this, s = document.createElement('script');
+ s.async = isAsync;
+ _jsCache[jsPath] = true;
+ if (cc.game.config["noCache"] && typeof jsPath === "string") {
+ if (self._noCacheRex.test(jsPath))
+ s.src = jsPath + "&_t=" + (new Date() - 0);
+ else
+ s.src = jsPath + "?_t=" + (new Date() - 0);
} else {
- if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=utf-8");
+ s.src = jsPath;
}
- xhr.send(null);
- if (!xhr.readyState == 4 || xhr.status != 200) {
- return null;
+ s.addEventListener('load', function () {
+ s.parentNode.removeChild(s);
+ this.removeEventListener('load', arguments.callee, false);
+ cb();
+ }, false);
+ s.addEventListener('error', function () {
+ s.parentNode.removeChild(s);
+ cb("Load " + jsPath + " failed!");
+ }, false);
+ d.body.appendChild(s);
+ },
+ _loadJs4Dependency: function (baseDir, jsList, index, cb) {
+ if (index >= jsList.length) {
+ if (cb) cb();
+ return;
}
- return xhr.responseText;
- } else {
- var fs = require("fs");
- return fs.readFileSync(url).toString();
- }
- },
-
- loadCsb: function(url, cb){
- var xhr = new XMLHttpRequest();
- xhr.open("GET", url, true);
- xhr.responseType = "arraybuffer";
-
- xhr.onload = function () {
- var arrayBuffer = xhr.response; // Note: not oReq.responseText
- if (arrayBuffer) {
- window.msg = arrayBuffer;
+ var self = this;
+ self._createScript(cc.path.join(baseDir, jsList[index]), false, function (err) {
+ if (err) return cb(err);
+ self._loadJs4Dependency(baseDir, jsList, index + 1, cb);
+ });
+ },
+ _loadJsImg: function () {
+ var d = document, jsLoadingImg = d.getElementById("cocos2d_loadJsImg");
+ if (!jsLoadingImg) {
+ jsLoadingImg = document.createElement('img');
+
+ if (cc._loadingImage)
+ jsLoadingImg.src = cc._loadingImage;
+
+ var canvasNode = d.getElementById(cc.game.config["id"]);
+ canvasNode.style.backgroundColor = "transparent";
+ canvasNode.parentNode.appendChild(jsLoadingImg);
+
+ var canvasStyle = getComputedStyle ? getComputedStyle(canvasNode) : canvasNode.currentStyle;
+ if (!canvasStyle)
+ canvasStyle = {width: canvasNode.width, height: canvasNode.height};
+ jsLoadingImg.style.left = canvasNode.offsetLeft + (parseFloat(canvasStyle.width) - jsLoadingImg.width) / 2 + "px";
+ jsLoadingImg.style.top = canvasNode.offsetTop + (parseFloat(canvasStyle.height) - jsLoadingImg.height) / 2 + "px";
+ jsLoadingImg.style.position = "absolute";
}
- if(xhr.readyState == 4)
- xhr.status == 200 ? cb(null, xhr.response) : cb("load " + url + " failed!");
- };
+ return jsLoadingImg;
+ },
+ //@MODE_END DEV
+
+ /**
+ * Load a single resource as txt.
+ * @param {string} url
+ * @param {function} [cb] arguments are : err, txt
+ */
+ loadTxt: function (url, cb) {
+ if (!cc._isNodeJs) {
+ var xhr = this.getXMLHttpRequest(),
+ errInfo = "load " + url + " failed!";
+ xhr.open("GET", url, true);
+ if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) {
+ // IE-specific logic here
+ xhr.setRequestHeader("Accept-Charset", "utf-8");
+ xhr.onreadystatechange = function () {
+ if (xhr.readyState === 4)
+ (xhr.status === 200||xhr.status === 0) ? cb(null, xhr.responseText) : cb({status:xhr.status, errorMessage:errInfo}, null);
+ };
+ } else {
+ if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=utf-8");
+ var loadCallback = function () {
+ xhr.removeEventListener('load', loadCallback);
+ xhr.removeEventListener('error', errorCallback);
+ if (xhr._timeoutId >= 0) {
+ clearTimeout(xhr._timeoutId);
+ }
+ else {
+ xhr.removeEventListener('timeout', timeoutCallback);
+ }
+ if (xhr.readyState === 4) {
+ (xhr.status === 200||xhr.status === 0) ? cb(null, xhr.responseText) : cb({status:xhr.status, errorMessage:errInfo}, null);
+ }
+ };
+ var errorCallback = function () {
+ xhr.removeEventListener('load', loadCallback);
+ xhr.removeEventListener('error', errorCallback);
+ if (xhr._timeoutId >= 0) {
+ clearTimeout(xhr._timeoutId);
+ }
+ else {
+ xhr.removeEventListener('timeout', timeoutCallback);
+ }
+ cb({status: xhr.status, errorMessage: errInfo}, null);
+ };
+ var timeoutCallback = function () {
+ xhr.removeEventListener('load', loadCallback);
+ xhr.removeEventListener('error', errorCallback);
+ if (xhr._timeoutId >= 0) {
+ clearTimeout(xhr._timeoutId);
+ }
+ else {
+ xhr.removeEventListener('timeout', timeoutCallback);
+ }
+ cb({status: xhr.status, errorMessage: "Request timeout: " + errInfo}, null);
+ };
+ xhr.addEventListener('load', loadCallback);
+ xhr.addEventListener('error', errorCallback);
+ if (xhr.ontimeout === undefined) {
+ xhr._timeoutId = setTimeout(function () {
+ timeoutCallback();
+ }, xhr.timeout);
+ }
+ else {
+ xhr.addEventListener('timeout', timeoutCallback);
+ }
+ }
+ xhr.send(null);
+ } else {
+ var fs = require("fs");
+ fs.readFile(url, function (err, data) {
+ err ? cb(err) : cb(null, data.toString());
+ });
+ }
+ },
- xhr.send(null);
- },
+ loadCsb: function(url, cb){
+ var xhr = cc.loader.getXMLHttpRequest(),
+ errInfo = "load " + url + " failed!";
+ xhr.open("GET", url, true);
+ xhr.responseType = "arraybuffer";
- /**
- * Load a single resource as json.
- * @param {string} url
- * @param {function} [cb] arguments are : err, json
- */
- loadJson: function (url, cb) {
- this.loadTxt(url, function (err, txt) {
- if (err) {
- cb(err);
+ var loadCallback = function () {
+ xhr.removeEventListener('load', loadCallback);
+ xhr.removeEventListener('error', errorCallback);
+ if (xhr._timeoutId >= 0) {
+ clearTimeout(xhr._timeoutId);
+ }
+ else {
+ xhr.removeEventListener('timeout', timeoutCallback);
+ }
+ var arrayBuffer = xhr.response; // Note: not oReq.responseText
+ if (arrayBuffer) {
+ window.msg = arrayBuffer;
+ }
+ if (xhr.readyState === 4) {
+ (xhr.status === 200||xhr.status === 0) ? cb(null, xhr.response) : cb({status:xhr.status, errorMessage:errInfo}, null);
+ }
+ };
+ var errorCallback = function(){
+ xhr.removeEventListener('load', loadCallback);
+ xhr.removeEventListener('error', errorCallback);
+ if (xhr._timeoutId >= 0) {
+ clearTimeout(xhr._timeoutId);
+ }
+ else {
+ xhr.removeEventListener('timeout', timeoutCallback);
+ }
+ cb({status:xhr.status, errorMessage:errInfo}, null);
+ };
+ var timeoutCallback = function () {
+ xhr.removeEventListener('load', loadCallback);
+ xhr.removeEventListener('error', errorCallback);
+ if (xhr._timeoutId >= 0) {
+ clearTimeout(xhr._timeoutId);
+ }
+ else {
+ xhr.removeEventListener('timeout', timeoutCallback);
+ }
+ cb({status: xhr.status, errorMessage: "Request timeout: " + errInfo}, null);
+ };
+ xhr.addEventListener('load', loadCallback);
+ xhr.addEventListener('error', errorCallback);
+ if (xhr.ontimeout === undefined) {
+ xhr._timeoutId = setTimeout(function () {
+ timeoutCallback();
+ }, xhr.timeout);
}
else {
- try {
- var result = JSON.parse(txt);
+ xhr.addEventListener('timeout', timeoutCallback);
+ }
+ xhr.send(null);
+ },
+
+ /**
+ * Load a single resource as json.
+ * @param {string} url
+ * @param {function} [cb] arguments are : err, json
+ */
+ loadJson: function (url, cb) {
+ this.loadTxt(url, function (err, txt) {
+ if (err) {
+ cb(err);
}
- catch (e) {
- throw "parse json [" + url + "] failed : " + e;
- return;
+ else {
+ try {
+ var result = JSON.parse(txt);
+ }
+ catch (e) {
+ throw new Error("parse json [" + url + "] failed : " + e);
+ return;
+ }
+ cb(null, result);
}
- cb(null, result);
+ });
+ },
+
+ _checkIsImageURL: function (url) {
+ var ext = /(\.png)|(\.jpg)|(\.bmp)|(\.jpeg)|(\.gif)/.exec(url);
+ return (ext != null);
+ },
+ /**
+ * Load a single image.
+ * @param {!string} url
+ * @param {object} [option]
+ * @param {function} callback
+ * @returns {Image}
+ */
+ loadImg: function (url, option, callback, img) {
+ var opt = {
+ isCrossOrigin: true
+ };
+ if (callback !== undefined)
+ opt.isCrossOrigin = option.isCrossOrigin === undefined ? opt.isCrossOrigin : option.isCrossOrigin;
+ else if (option !== undefined)
+ callback = option;
+
+ var texture = this.getRes(url);
+ if (texture) {
+ callback && callback(null, texture);
+ return null;
}
- });
- },
-
- _checkIsImageURL: function (url) {
- var ext = /(\.png)|(\.jpg)|(\.bmp)|(\.jpeg)|(\.gif)/.exec(url);
- return (ext != null);
- },
- /**
- * Load a single image.
- * @param {!string} url
- * @param {object} [option]
- * @param {function} cb
- * @returns {Image}
- */
- loadImg: function (url, option, cb) {
- var opt = {
- isCrossOrigin: true
- };
- if (cb !== undefined)
- opt.isCrossOrigin = option.isCrossOrigin == null ? opt.isCrossOrigin : option.isCrossOrigin;
- else if (option !== undefined)
- cb = option;
-
- var img = this.getRes(url);
- if (img) {
- cb && cb(null, img);
- return img;
- }
- img = new Image();
- if (opt.isCrossOrigin && location.origin != "file://")
- img.crossOrigin = "Anonymous";
-
- var lcb = function () {
- this.removeEventListener('load', lcb, false);
- this.removeEventListener('error', ecb, false);
-
- cc.loader.cache[url] = img;
- if (cb)
- cb(null, img);
- };
+ var queue = _queue[url];
+ if (queue) {
+ queue.callbacks.push(callback);
+ return queue.img;
+ }
- var ecb = function () {
- this.removeEventListener('error', ecb, false);
+ img = img || imagePool.get();
+ if (opt.isCrossOrigin && location.origin !== "file://")
+ img.crossOrigin = "Anonymous";
+ else
+ img.crossOrigin = null;
+
+ var loadCallback = function () {
+ this.removeEventListener('load', loadCallback, false);
+ this.removeEventListener('error', errorCallback, false);
+
+ var queue = _queue[url];
+ if (queue) {
+ var callbacks = queue.callbacks;
+ for (var i = 0; i < callbacks.length; ++i) {
+ var cb = callbacks[i];
+ if (cb) {
+ cb(null, img);
+ }
+ }
+ queue.img = null;
+ delete _queue[url];
+ }
- if(img.crossOrigin && img.crossOrigin.toLowerCase() == "anonymous"){
- opt.isCrossOrigin = false;
- cc.loader.loadImg(url, opt, cb);
- }else{
- typeof cb == "function" && cb("load image failed");
- }
- };
+ if (window.ENABLE_IMAEG_POOL && cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
+ imagePool.put(img);
+ }
+ };
+
+ var self = this;
+ var errorCallback = function () {
+ this.removeEventListener('load', loadCallback, false);
+ this.removeEventListener('error', errorCallback, false);
+
+ if (window.location.protocol !== 'https:' && img.crossOrigin && img.crossOrigin.toLowerCase() === "anonymous") {
+ opt.isCrossOrigin = false;
+ self.release(url);
+ cc.loader.loadImg(url, opt, callback, img);
+ } else {
+ var queue = _queue[url];
+ if (queue) {
+ var callbacks = queue.callbacks;
+ for (var i = 0; i < callbacks.length; ++i) {
+ var cb = callbacks[i];
+ if (cb) {
+ cb("load image failed");
+ }
+ }
+ queue.img = null;
+ delete _queue[url];
+ }
- cc._addEventListener(img, "load", lcb);
- cc._addEventListener(img, "error", ecb);
- img.src = url;
- return img;
- },
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
+ imagePool.put(img);
+ }
+ }
+ };
- /**
- * Iterator function to load res
- * @param {object} item
- * @param {number} index
- * @param {function} [cb]
- * @returns {*}
- * @private
- */
- _loadResIterator: function (item, index, cb) {
- var self = this, url = null;
- var type = item.type;
- if (type) {
- type = "." + type.toLowerCase();
- url = item.src ? item.src : item.name + type;
- } else {
- url = item;
- type = cc.path.extname(url);
- }
+ _queue[url] = {
+ img: img,
+ callbacks: callback ? [callback] : []
+ };
- var obj = self.getRes(url);
- if (obj)
- return cb(null, obj);
- var loader = null;
- if (type) {
- loader = self._register[type.toLowerCase()];
- }
- if (!loader) {
- cc.error("loader for [" + type + "] not exists!");
- return cb();
- }
- var basePath = loader.getBasePath ? loader.getBasePath() : self.resPath;
- var realUrl = self.getUrl(basePath, url);
- loader.load(realUrl, url, item, function (err, data) {
- if (err) {
- cc.log(err);
- self.cache[url] = null;
- delete self.cache[url];
- cb();
+ img.addEventListener("load", loadCallback);
+ img.addEventListener("error", errorCallback);
+ img.src = url;
+ return img;
+ },
+
+ /**
+ * Iterator function to load res
+ * @param {object} item
+ * @param {number} index
+ * @param {function} [cb]
+ * @returns {*}
+ * @private
+ */
+ _loadResIterator: function (item, index, cb) {
+ var self = this, url = null;
+ var type = item.type;
+ if (type) {
+ type = "." + type.toLowerCase();
+ url = item.src ? item.src : item.name + type;
} else {
- self.cache[url] = data;
- cb(null, data);
+ url = item;
+ type = cc.path.extname(url);
}
- });
- },
- /**
- * Get url with basePath.
- * @param {string} basePath
- * @param {string} [url]
- * @returns {*}
- */
- getUrl: function (basePath, url) {
- var self = this, langPathCache = self._langPathCache, path = cc.path;
- if (basePath !== undefined && url === undefined) {
- url = basePath;
- var type = path.extname(url);
- type = type ? type.toLowerCase() : "";
- var loader = self._register[type];
- if (!loader)
- basePath = self.resPath;
- else
- basePath = loader.getBasePath ? loader.getBasePath() : self.resPath;
- }
- url = cc.path.join(basePath || "", url);
- if (url.match(/[\/(\\\\)]lang[\/(\\\\)]/i)) {
- if (langPathCache[url])
- return langPathCache[url];
- var extname = path.extname(url) || "";
- url = langPathCache[url] = url.substring(0, url.length - extname.length) + "_" + cc.sys.language + extname;
- }
- return url;
- },
+ var obj = self.getRes(url);
+ if (obj)
+ return cb(null, obj);
+ var loader = null;
+ if (type) {
+ loader = _register[type.toLowerCase()];
+ }
+ if (!loader) {
+ cc.error("loader for [" + type + "] doesn't exist!");
+ return cb();
+ }
+ var realUrl = url;
+ if (!_urlRegExp.test(url)) {
+ var basePath = loader.getBasePath ? loader.getBasePath() : self.resPath;
+ realUrl = self.getUrl(basePath, url);
+ }
- /**
- * Load resources then call the callback.
- * @param {string} resources
- * @param {function} [option] callback or trigger
- * @param {function|Object} [cb]
- * @return {cc.AsyncPool}
- */
- load : function(resources, option, cb){
- var self = this;
- var len = arguments.length;
- if(len == 0)
- throw "arguments error!";
-
- if(len == 3){
- if(typeof option == "function"){
- if(typeof cb == "function")
- option = {trigger : option, cb : cb };
+ if (cc.game.config["noCache"] && typeof realUrl === "string") {
+ if (self._noCacheRex.test(realUrl))
+ realUrl += "&_t=" + (new Date() - 0);
else
- option = { cb : option, cbTarget : cb};
+ realUrl += "?_t=" + (new Date() - 0);
}
- }else if(len == 2){
- if(typeof option == "function")
- option = {cb : option};
- }else if(len == 1){
- option = {};
- }
-
- if(!(resources instanceof Array))
- resources = [resources];
- var asyncPool = new cc.AsyncPool(resources, 0, function(value, index, cb1, aPool){
- self._loadResIterator(value, index, function(err){
- if(err)
- return cb1(err);
- var arr = Array.prototype.slice.call(arguments, 1);
- if(option.trigger)
- option.trigger.call(option.triggerTarget, arr[0], aPool.size, aPool.finishedSize); //call trigger
- cb1(null, arr[0]);
- });
- }, option.cb, option.cbTarget);
- asyncPool.flow();
- return asyncPool;
- },
-
- _handleAliases: function (fileNames, cb) {
- var self = this, aliases = self._aliases;
- var resList = [];
- for (var key in fileNames) {
- var value = fileNames[key];
- aliases[key] = value;
- resList.push(value);
- }
- this.load(resList, cb);
- },
-
- /**
- *
- * Loads alias map from the contents of a filename.
- *
- * @note The plist file name should follow the format below:
- *
- *
- *
- *
- * filenames
- *
- * sounds/click.wav
- * sounds/click.caf
- * sounds/endgame.wav
- * sounds/endgame.caf
- * sounds/gem-0.wav
- * sounds/gem-0.caf
- *
- * metadata
- *
- * version
- * 1
- *
- *
- *
- *
- * @param {String} url The plist file name.
- * @param {Function} [cb] callback
- */
- loadAliases: function (url, cb) {
- var self = this, dict = self.getRes(url);
- if (!dict) {
- self.load(url, function (err, results) {
- self._handleAliases(results[0]["filenames"], cb);
+ loader.load(realUrl, url, item, function (err, data) {
+ if (err) {
+ cc.log(err);
+ self.cache[url] = null;
+ delete self.cache[url];
+ cb({status: 520, errorMessage: err}, null);
+ } else {
+ self.cache[url] = data;
+ cb(null, data);
+ }
});
- } else
- self._handleAliases(dict["filenames"], cb);
- },
+ },
+ _noCacheRex: /\?/,
+
+ /**
+ * Get url with basePath.
+ * @param {string} basePath
+ * @param {string} [url]
+ * @returns {*}
+ */
+ getUrl: function (basePath, url) {
+ var self = this, path = cc.path;
+ if (basePath !== undefined && url === undefined) {
+ url = basePath;
+ var type = path.extname(url);
+ type = type ? type.toLowerCase() : "";
+ var loader = _register[type];
+ if (!loader)
+ basePath = self.resPath;
+ else
+ basePath = loader.getBasePath ? loader.getBasePath() : self.resPath;
+ }
+ url = cc.path.join(basePath || "", url);
+ if (url.match(/[\/(\\\\)]lang[\/(\\\\)]/i)) {
+ if (_langPathCache[url])
+ return _langPathCache[url];
+ var extname = path.extname(url) || "";
+ url = _langPathCache[url] = url.substring(0, url.length - extname.length) + "_" + cc.sys.language + extname;
+ }
+ return url;
+ },
+
+ /**
+ * Load resources then call the callback.
+ * @param {string} resources
+ * @param {function} [option] callback or trigger
+ * @param {function|Object} [loadCallback]
+ * @return {cc.AsyncPool}
+ */
+ load: function (resources, option, loadCallback) {
+ var self = this;
+ var len = arguments.length;
+ if (len === 0)
+ throw new Error("arguments error!");
+
+ 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")
+ option = {cb: option};
+ } else if (len === 1) {
+ option = {};
+ }
- /**
- * Register a resource loader into loader.
- * @param {string} extNames
- * @param {function} loader
- */
- register: function (extNames, loader) {
- if (!extNames || !loader) return;
- var self = this;
- 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;
+ if (!(resources instanceof Array))
+ resources = [resources];
+ var asyncPool = new cc.AsyncPool(
+ resources, cc.CONCURRENCY_HTTP_REQUEST_COUNT,
+ function (value, index, AsyncPoolCallback, aPool) {
+ self._loadResIterator(value, index, function (err) {
+ var arr = Array.prototype.slice.call(arguments, 1);
+ if (option.trigger)
+ option.trigger.call(option.triggerTarget, arr[0], aPool.size, aPool.finishedSize); //call trigger
+ AsyncPoolCallback(err, arr[0]);
+ });
+ },
+ option.cb, option.cbTarget);
+ asyncPool.flow();
+ return asyncPool;
+ },
+
+ _handleAliases: function (fileNames, cb) {
+ var self = this;
+ var resList = [];
+ for (var key in fileNames) {
+ var value = fileNames[key];
+ _aliases[key] = value;
+ resList.push(value);
+ }
+ this.load(resList, cb);
+ },
+
+ /**
+ *
+ * Loads alias map from the contents of a filename.
+ *
+ * @note The plist file name should follow the format below:
+ *
+ *
+ *
+ *
+ * filenames
+ *
+ * sounds/click.wav
+ * sounds/click.caf
+ * sounds/endgame.wav
+ * sounds/endgame.caf
+ * sounds/gem-0.wav
+ * sounds/gem-0.caf
+ *
+ * metadata
+ *
+ * version
+ * 1
+ *
+ *
+ *
+ *
+ * @param {String} url The plist file name.
+ * @param {Function} [callback]
+ */
+ loadAliases: function (url, callback) {
+ var self = this, dict = self.getRes(url);
+ if (!dict) {
+ self.load(url, function (err, results) {
+ self._handleAliases(results[0]["filenames"], callback);
+ });
+ } else
+ self._handleAliases(dict["filenames"], callback);
+ },
+
+ /**
+ * Register a resource loader into loader.
+ * @param {string} extNames
+ * @param {function} loader
+ */
+ register: function (extNames, loader) {
+ if (!extNames || !loader) return;
+ var self = this;
+ if (typeof extNames === "string")
+ return _register[extNames.trim().toLowerCase()] = loader;
+ for (var i = 0, li = extNames.length; i < li; i++) {
+ _register["." + extNames[i].trim().toLowerCase()] = loader;
+ }
+ },
+
+ /**
+ * Get resource data by url.
+ * @param url
+ * @returns {*}
+ */
+ getRes: function (url) {
+ return this.cache[url] || this.cache[_aliases[url]];
+ },
+
+ /**
+ * Get aliase by url.
+ * @param url
+ * @returns {*}
+ */
+ _getAliase: function (url) {
+ return _aliases[url];
+ },
+
+ /**
+ * Release the cache of resource by url.
+ * @param url
+ */
+ release: function (url) {
+ var cache = this.cache;
+ var queue = _queue[url];
+ if (queue) {
+ queue.img = null;
+ delete _queue[url];
+ }
+ delete cache[url];
+ delete cache[_aliases[url]];
+ delete _aliases[url];
+ },
+
+ /**
+ * Resource cache of all resources.
+ */
+ releaseAll: function () {
+ var locCache = this.cache;
+ for (var key in locCache)
+ delete locCache[key];
+ for (var key in _aliases)
+ delete _aliases[key];
}
- },
-
- /**
- * Get resource data by url.
- * @param url
- * @returns {*}
- */
- getRes: function (url) {
- return this.cache[url] || this.cache[this._aliases[url]];
- },
-
- /**
- * Release the cache of resource by url.
- * @param url
- */
- release: function (url) {
- var cache = this.cache, aliases = this._aliases;
- delete cache[url];
- delete cache[aliases[url]];
- delete aliases[url];
- },
-
- /**
- * Resource cache of all resources.
- */
- releaseAll: function () {
- var locCache = this.cache, aliases = this._aliases;
- for (var key in locCache)
- delete locCache[key];
- for (var key in aliases)
- delete aliases[key];
- }
-};
+ };
+})();
//+++++++++++++++++++++++++something about loader end+++++++++++++++++++++++++++++
/**
@@ -1020,143 +1285,65 @@ cc.loader = /** @lends cc.loader# */{
* cc.formatStr(a, b, c);
* @returns {String}
*/
-cc.formatStr = function(){
+cc.formatStr = function () {
var args = arguments;
var l = args.length;
- if(l < 1)
+ if (l < 1)
return "";
var str = args[0];
var needToFormat = true;
- if(typeof str == "object"){
+ if (typeof str === "object") {
needToFormat = false;
}
- for(var i = 1; i < l; ++i){
+ for (var i = 1; i < l; ++i) {
var arg = args[i];
- if(needToFormat){
- while(true){
+ if (needToFormat) {
+ while (true) {
var result = null;
- if(typeof arg == "number"){
+ if (typeof arg === "number") {
result = str.match(/(%d)|(%s)/);
- if(result){
+ if (result) {
str = str.replace(/(%d)|(%s)/, arg);
break;
}
}
result = str.match(/%s/);
- if(result)
+ if (result)
str = str.replace(/%s/, arg);
else
str += " " + arg;
break;
}
- }else
+ } else
str += " " + arg;
}
return str;
};
-//+++++++++++++++++++++++++something about window events begin+++++++++++++++++++++++++++
+//+++++++++++++++++++++++++Engine initialization function begin+++++++++++++++++++++++++++
(function () {
- var win = window, hidden, visibilityChange, _undef = "undefined";
- if (!cc.isUndefined(document.hidden)) {
- hidden = "hidden";
- visibilityChange = "visibilitychange";
- } else if (!cc.isUndefined(document.mozHidden)) {
- hidden = "mozHidden";
- visibilityChange = "mozvisibilitychange";
- } else if (!cc.isUndefined(document.msHidden)) {
- hidden = "msHidden";
- visibilityChange = "msvisibilitychange";
- } else if (!cc.isUndefined(document.webkitHidden)) {
- hidden = "webkitHidden";
- visibilityChange = "webkitvisibilitychange";
- }
- var onHidden = function () {
- if (cc.eventManager && cc.game._eventHide)
- cc.eventManager.dispatchEvent(cc.game._eventHide);
- };
- var onShow = function () {
- if (cc.eventManager && cc.game._eventShow)
- cc.eventManager.dispatchEvent(cc.game._eventShow);
-
- if(cc.game._intervalId){
- window.cancelAnimationFrame(cc.game._intervalId);
+var _tmpCanvas1 = document.createElement("canvas"),
+ _tmpCanvas2 = document.createElement("canvas");
- cc.game._runMainLoop();
+cc.create3DContext = function (canvas, opt_attribs) {
+ var names = ["webgl", "experimental-webgl", "webkit-3d", "moz-webgl"];
+ var context = null;
+ for (var ii = 0; ii < names.length; ++ii) {
+ try {
+ context = canvas.getContext(names[ii], opt_attribs);
+ } catch (e) {
+ }
+ if (context) {
+ break;
}
- };
-
- if (hidden) {
- cc._addEventListener(document, visibilityChange, function () {
- if (document[hidden]) onHidden();
- else onShow();
- }, false);
- } else {
- cc._addEventListener(win, "blur", onHidden, false);
- cc._addEventListener(win, "focus", onShow, false);
- }
-
- if(navigator.userAgent.indexOf("MicroMessenger") > -1){
- win.onfocus = function(){ onShow() };
}
+ return context;
+};
- if ("onpageshow" in window && "onpagehide" in window) {
- cc._addEventListener(win, "pagehide", onHidden, false);
- cc._addEventListener(win, "pageshow", onShow, false);
- }
- win = null;
- visibilityChange = null;
-})();
-//+++++++++++++++++++++++++something about window events end+++++++++++++++++++++++++++++
-
-//+++++++++++++++++++++++++something about log start++++++++++++++++++++++++++++
-
-//to make sure the cc.log, cc.warn, cc.error and cc.assert would not throw error before init by debugger mode.
-
-cc.log = cc.warn = cc.error = cc.assert = function () {
-};
-
-//+++++++++++++++++++++++++something about log end+++++++++++++++++++++++++++++
-
-/**
- * create a webgl context
- * @param {HTMLCanvasElement} canvas
- * @param {Object} opt_attribs
- * @return {WebGLRenderingContext}
- */
-cc.create3DContext = function (canvas, opt_attribs) {
- var names = ["webgl", "experimental-webgl", "webkit-3d", "moz-webgl"];
- var context = null;
- for (var ii = 0; ii < names.length; ++ii) {
- try {
- context = canvas.getContext(names[ii], opt_attribs);
- } catch (e) {
- }
- if (context) {
- break;
- }
- }
- return context;
-};
-//+++++++++++++++++++++++++something about sys begin+++++++++++++++++++++++++++++
-cc._initSys = function (config, CONFIG_KEY) {
- /**
- * Canvas of render type
- * @constant
- * @type {Number}
- */
- cc._RENDER_TYPE_CANVAS = 0;
-
- /**
- * WebGL of render type
- * @constant
- * @type {Number}
- */
- cc._RENDER_TYPE_WEBGL = 1;
-
+var _initSys = function () {
/**
* System variables
* @namespace
@@ -1301,12 +1488,14 @@ cc._initSys = function (config, CONFIG_KEY) {
sys.LANGUAGE_POLISH = "pl";
/**
+ * Unknown language code
* @memberof cc.sys
- * @name OS_WINDOWS
+ * @name LANGUAGE_UNKNOWN
* @constant
- * @type {string}
+ * @type {Number}
*/
- sys.OS_WINDOWS = "Windows";
+ sys.LANGUAGE_UNKNOWN = "unkonwn";
+
/**
* @memberof cc.sys
* @name OS_IOS
@@ -1316,18 +1505,25 @@ cc._initSys = function (config, CONFIG_KEY) {
sys.OS_IOS = "iOS";
/**
* @memberof cc.sys
- * @name OS_OSX
+ * @name OS_ANDROID
* @constant
* @type {string}
*/
- sys.OS_OSX = "OS X";
+ sys.OS_ANDROID = "Android";
/**
* @memberof cc.sys
- * @name OS_UNIX
+ * @name OS_WINDOWS
* @constant
* @type {string}
*/
- sys.OS_UNIX = "UNIX";
+ sys.OS_WINDOWS = "Windows";
+ /**
+ * @memberof cc.sys
+ * @name OS_MARMALADE
+ * @constant
+ * @type {string}
+ */
+ sys.OS_MARMALADE = "Marmalade";
/**
* @memberof cc.sys
* @name OS_LINUX
@@ -1337,11 +1533,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
@@ -1352,12 +1576,20 @@ cc._initSys = function (config, CONFIG_KEY) {
/**
* @memberof cc.sys
- * @name WINDOWS
+ * @name UNKNOWN
+ * @constant
+ * @default
+ * @type {Number}
+ */
+ sys.UNKNOWN = -1;
+ /**
+ * @memberof cc.sys
+ * @name WIN32
* @constant
* @default
* @type {Number}
*/
- sys.WINDOWS = 0;
+ sys.WIN32 = 0;
/**
* @memberof cc.sys
* @name LINUX
@@ -1384,7 +1616,7 @@ cc._initSys = function (config, CONFIG_KEY) {
sys.ANDROID = 3;
/**
* @memberof cc.sys
- * @name IPHONE
+ * @name IOS
* @constant
* @default
* @type {Number}
@@ -1392,7 +1624,7 @@ cc._initSys = function (config, CONFIG_KEY) {
sys.IPHONE = 4;
/**
* @memberof cc.sys
- * @name IPAD
+ * @name IOS
* @constant
* @default
* @type {Number}
@@ -1466,6 +1698,7 @@ cc._initSys = function (config, CONFIG_KEY) {
sys.BROWSER_TYPE_WECHAT = "wechat";
sys.BROWSER_TYPE_ANDROID = "androidbrowser";
sys.BROWSER_TYPE_IE = "ie";
+ sys.BROWSER_TYPE_QQ_APP = "qq"; // QQ App
sys.BROWSER_TYPE_QQ = "qqbrowser";
sys.BROWSER_TYPE_MOBILE_QQ = "mqqbrowser";
sys.BROWSER_TYPE_UC = "ucbrowser";
@@ -1479,6 +1712,9 @@ cc._initSys = function (config, CONFIG_KEY) {
sys.BROWSER_TYPE_FIREFOX = "firefox";
sys.BROWSER_TYPE_SAFARI = "safari";
sys.BROWSER_TYPE_CHROME = "chrome";
+ sys.BROWSER_TYPE_LIEBAO = "liebao";
+ sys.BROWSER_TYPE_QZONE = "qzone";
+ sys.BROWSER_TYPE_SOUGOU = "sogou";
sys.BROWSER_TYPE_UNKNOWN = "unknown";
/**
@@ -1489,13 +1725,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();
@@ -1505,7 +1734,7 @@ cc._initSys = function (config, CONFIG_KEY) {
* @name isMobile
* @type {Boolean}
*/
- sys.isMobile = ua.indexOf('mobile') != -1 || ua.indexOf('android') != -1;
+ sys.isMobile = /mobile|android|iphone|ipad/.test(ua);
/**
* Indicate the running platform
@@ -1527,36 +1756,33 @@ cc._initSys = function (config, CONFIG_KEY) {
*/
sys.language = currLanguage;
- var browserType = sys.BROWSER_TYPE_UNKNOWN;
- var browserTypes = ua.match(/micromessenger|qqbrowser|ucbrowser|360 aphone|360browser|baiduboxapp|baidubrowser|maxthon|trident|oupeng|opera|miuibrowser|firefox/i)
- || ua.match(/chrome|safari/i);
- if (browserTypes && browserTypes.length > 0) {
- browserType = browserTypes[0].toLowerCase();
- 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;
+ // Get the os of system
+ var isAndroid = false, iOS = false, osVersion = '', osMainVersion = 0;
+ var uaResult = /android (\d+(?:\.\d+)+)/i.exec(ua) || /android (\d+(?:\.\d+)+)/i.exec(nav.platform);
+ if (uaResult) {
+ isAndroid = true;
+ osVersion = uaResult[1] || '';
+ osMainVersion = parseInt(osVersion) || 0;
+ }
+ uaResult = /(iPad|iPhone|iPod).*OS ((\d+_?){2,3})/i.exec(ua);
+ if (uaResult) {
+ iOS = true;
+ osVersion = uaResult[2] || '';
+ osMainVersion = parseInt(osVersion) || 0;
+ }
+ else if (/(iPhone|iPad|iPod)/.exec(nav.platform)) {
+ iOS = true;
+ osVersion = '';
+ osMainVersion = 0;
}
- /**
- * Indicate the running browser type
- * @memberof cc.sys
- * @name browserType
- * @type {String}
- */
- sys.browserType = browserType;
- // Get the os of system
- 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) 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
@@ -1565,68 +1791,116 @@ cc._initSys = function (config, CONFIG_KEY) {
* @type {String}
*/
sys.os = osName;
+ /**
+ * Indicate the running os version string
+ * @memberof cc.sys
+ * @name osVersion
+ * @type {String}
+ */
+ sys.osVersion = osVersion;
+ /**
+ * Indicate the running os main version number
+ * @memberof cc.sys
+ * @name osMainVersion
+ * @type {Number}
+ */
+ sys.osMainVersion = osMainVersion;
- sys._supportMultipleAudio = multipleAudioWhiteList.indexOf(sys.browserType) > -1;
+ /**
+ * Indicate the running browser type
+ * @memberof cc.sys
+ * @name browserType
+ * @type {String}
+ */
+ sys.browserType = sys.BROWSER_TYPE_UNKNOWN;
+ /* Determine the browser type */
+ (function(){
+ var typeReg1 = /micromessenger|mqqbrowser|sogou|qzone|liebao|ucbrowser|360 aphone|360browser|baiduboxapp|baidubrowser|maxthon|mxbrowser|trident|miuibrowser/i;
+ var typeReg2 = /qqbrowser|qq|chrome|safari|firefox|opr|oupeng|opera/i;
+ var browserTypes = typeReg1.exec(ua);
+ if(!browserTypes) browserTypes = typeReg2.exec(ua);
+ var browserType = browserTypes ? browserTypes[0] : sys.BROWSER_TYPE_UNKNOWN;
+ if (browserType === 'micromessenger')
+ browserType = sys.BROWSER_TYPE_WECHAT;
+ else if (browserType === "safari" && isAndroid)
+ 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 === "mxbrowser")
+ browserType = sys.BROWSER_TYPE_MAXTHON;
+ else if (browserType === "opr")
+ browserType = sys.BROWSER_TYPE_OPERA;
+ sys.browserType = browserType;
+ })();
- //++++++++++++++++++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 = !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;
- }
+ /**
+ * Indicate the running browser version
+ * @memberof cc.sys
+ * @name browserVersion
+ * @type {String}
+ */
+ sys.browserVersion = "";
+ /* Determine the browser version number */
+ (function(){
+ var versionReg1 = /(mqqbrowser|micromessenger|sogou|qzone|liebao|maxthon|mxbrowser|baidu)(mobile)?(browser)?\/?([\d.]+)/i;
+ var versionReg2 = /(msie |rv:|firefox|chrome|ucbrowser|qq|oupeng|opera|opr|safari|miui)(mobile)?(browser)?\/?([\d.]+)/i;
+ var tmp = ua.match(versionReg1);
+ if(!tmp) tmp = ua.match(versionReg2);
+ sys.browserVersion = tmp ? tmp[4] : "";
+ })();
+
+ var w = window.innerWidth || document.documentElement.clientWidth;
+ var h = window.innerHeight || document.documentElement.clientHeight;
+ var ratio = window.devicePixelRatio || 1;
- sys._canUseCanvasNewBlendModes = function(){
- var canvas = document.createElement('canvas');
+ /**
+ * Indicate the real pixel resolution of the whole game window
+ * @memberof cc.sys
+ * @name windowPixelResolution
+ * @type {Size}
+ */
+ sys.windowPixelResolution = {
+ width: ratio * w,
+ height: ratio * h
+ };
+
+ sys._checkWebGLRenderMode = function () {
+ if (cc._renderType !== cc.game.RENDER_TYPE_WEBGL)
+ throw new Error("This feature supports WebGL render mode only.");
+ };
+
+ //Whether or not the Canvas BlendModes are supported.
+ sys._supportCanvasNewBlendModes = (function(){
+ var canvas = _tmpCanvas1;
canvas.width = 1;
canvas.height = 1;
var context = canvas.getContext('2d');
context.fillStyle = '#000';
- context.fillRect(0,0,1,1);
+ context.fillRect(0, 0, 1, 1);
context.globalCompositeOperation = 'multiply';
- var canvas2 = document.createElement('canvas');
+ var canvas2 = _tmpCanvas2;
canvas2.width = 1;
canvas2.height = 1;
var context2 = canvas2.getContext('2d');
context2.fillStyle = '#fff';
- context2.fillRect(0,0,1,1);
-
+ context2.fillRect(0, 0, 1, 1);
context.drawImage(canvas2, 0, 0, 1, 1);
- return context.getImageData(0,0,1,1).data[0] === 0;
- };
+ return context.getImageData(0, 0, 1, 1).data[0] === 0;
+ })();
- //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++++++++++++++++++++++++++++++
+ // Adjust mobile css settings
+ if (cc.sys.isMobile) {
+ var fontStyle = document.createElement("style");
+ fontStyle.type = "text/css";
+ document.body.appendChild(fontStyle);
- // check if browser supports Web Audio
- // check Web Audio's context
- try {
- sys._supportWebAudio = !!(win.AudioContext || win.webkitAudioContext || win.mozAudioContext);
- } catch (e) {
- sys._supportWebAudio = false;
+ fontStyle.textContent = "body,canvas,div{ -moz-user-select: none;-webkit-user-select: none;-ms-user-select: none;-khtml-user-select: none;"
+ + "-webkit-tap-highlight-color:rgba(0,0,0,0);}";
}
/**
@@ -1641,17 +1915,85 @@ cc._initSys = function (config, CONFIG_KEY) {
localStorage.removeItem("storage");
localStorage = null;
} catch (e) {
- if (e.name === "SECURITY_ERR" || e.name === "QuotaExceededError") {
+ var warn = function () {
cc.warn("Warning: localStorage isn't enabled. Please confirm browser cookie or privacy option");
- }
- sys.localStorage = function () {
+ };
+ sys.localStorage = {
+ getItem : warn,
+ setItem : warn,
+ removeItem : warn,
+ clear : warn
};
}
- var capabilities = sys.capabilities = {"canvas": true};
- if (cc._renderType == cc._RENDER_TYPE_WEBGL)
- capabilities["opengl"] = true;
- if (docEle['ontouchstart'] !== undefined || nav.msPointerEnabled)
+ var _supportCanvas = !!_tmpCanvas1.getContext("2d");
+ var _supportWebGL = false;
+ if (win.WebGLRenderingContext) {
+ var tmpCanvas = document.createElement("CANVAS");
+ try{
+ var context = cc.create3DContext(tmpCanvas);
+ if (context) {
+ _supportWebGL = true;
+ }
+
+ if (_supportWebGL && sys.os === sys.OS_IOS && sys.osMainVersion === 9) {
+ // Not activating WebGL in iOS 9 UIWebView because it may crash when entering background
+ if (!window.indexedDB) {
+ _supportWebGL = false;
+ }
+ }
+
+ if (_supportWebGL && sys.os === sys.OS_ANDROID) {
+ var browserVer = parseFloat(sys.browserVersion);
+ switch (sys.browserType) {
+ case sys.BROWSER_TYPE_MOBILE_QQ:
+ case sys.BROWSER_TYPE_BAIDU:
+ case sys.BROWSER_TYPE_BAIDU_APP:
+ // QQ & Baidu Brwoser 6.2+ (using blink kernel)
+ if (browserVer >= 6.2) {
+ _supportWebGL = true;
+ }
+ else {
+ _supportWebGL = false;
+ }
+ break;
+ case sys.BROWSER_TYPE_CHROME:
+ // Chrome on android supports WebGL from v.30
+ if(browserVer >= 30.0) {
+ _supportWebGL = true;
+ } else {
+ _supportWebGL = false;
+ }
+ break;
+ case sys.BROWSER_TYPE_ANDROID:
+ // Android 5+ default browser
+ if (sys.osMainVersion && sys.osMainVersion >= 5) {
+ _supportWebGL = true;
+ }
+ break;
+ case sys.BROWSER_TYPE_UNKNOWN:
+ case sys.BROWSER_TYPE_360:
+ case sys.BROWSER_TYPE_MIUI:
+ case sys.BROWSER_TYPE_UC:
+ _supportWebGL = false;
+ }
+ }
+ }
+ catch (e) {}
+ tmpCanvas = null;
+ }
+
+ /**
+ * The capabilities of the current platform
+ * @memberof cc.sys
+ * @name capabilities
+ * @type {Object}
+ */
+ var capabilities = sys.capabilities = {
+ "canvas": _supportCanvas,
+ "opengl": _supportWebGL
+ };
+ if (docEle['ontouchstart'] !== undefined || doc['ontouchstart'] !== undefined || nav.msPointerEnabled)
capabilities["touches"] = true;
if (docEle['onmouseup'] !== undefined)
capabilities["mouse"] = true;
@@ -1701,6 +2043,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
@@ -1713,305 +2070,324 @@ cc._initSys = function (config, CONFIG_KEY) {
str += "isMobile : " + self.isMobile + "\r\n";
str += "language : " + self.language + "\r\n";
str += "browserType : " + self.browserType + "\r\n";
+ str += "browserVersion : " + self.browserVersion + "\r\n";
str += "capabilities : " + JSON.stringify(self.capabilities) + "\r\n";
str += "os : " + self.os + "\r\n";
+ str += "osVersion : " + self.osVersion + "\r\n";
str += "platform : " + self.platform + "\r\n";
+ str += "Using " + (cc._renderType === cc.game.RENDER_TYPE_WEBGL ? "WEBGL" : "CANVAS") + " renderer." + "\r\n";
cc.log(str);
- }
-};
-
-//+++++++++++++++++++++++++something about sys end+++++++++++++++++++++++++++++
-
-//+++++++++++++++++++++++++something about CCGame begin+++++++++++++++++++++++++++
-
-/**
- * Device oriented vertically, home button on the bottom
- * @constant
- * @type {Number}
- */
-cc.ORIENTATION_PORTRAIT = 0;
-
-/**
- * Device oriented vertically, home button on the top
- * @constant
- * @type {Number}
- */
-cc.ORIENTATION_PORTRAIT_UPSIDE_DOWN = 1;
+ };
-/**
- * Device oriented horizontally, home button on the right
- * @constant
- * @type {Number}
- */
-cc.ORIENTATION_LANDSCAPE_LEFT = 2;
+ /**
+ * Open a url in browser
+ * @memberof cc.sys
+ * @name openURL
+ * @param {String} url
+ */
+ sys.openURL = function(url){
+ window.open(url);
+ };
-/**
- * Device oriented horizontally, home button on the left
- * @constant
- * @type {Number}
- */
-cc.ORIENTATION_LANDSCAPE_RIGHT = 3;
+ /**
+ * Get the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.
+ * @memberof cc.sys
+ * @name now
+ * @return {Number}
+ */
+ sys.now = function () {
+ if (Date.now) {
+ return Date.now();
+ }
+ else {
+ return +(new Date);
+ }
+ };
+};
+_initSys();
-/**
- * drawing primitive of game engine
- * @type {cc.DrawingPrimitive}
- */
-cc._drawingUtil = null;
+_tmpCanvas1 = null;
+_tmpCanvas2 = null;
-/**
- * main Canvas 2D/3D Context of game engine
- * @type {CanvasRenderingContext2D|WebGLRenderingContext}
- */
-cc._renderContext = null;
+//to make sure the cc.log, cc.warn, cc.error and cc.assert would not throw error before init by debugger mode.
+cc.log = cc.warn = cc.error = cc.assert = function () {
+};
-/**
- * main Canvas of game engine
- * @type {HTMLCanvasElement}
- */
-cc._canvas = null;
+var _config = null,
+ //cache for js and module that has added into jsList to be loaded.
+ _jsAddedCache = {},
+ _engineInitCalled = false,
+ _engineLoadedCallback = null;
-/**
- * This Div element contain all game canvas
- * @type {HTMLDivElement}
- */
-cc._gameDiv = null;
+cc._engineLoaded = false;
-cc._rendererInitialized = false;
-/**
- *
- * setup game main canvas,renderContext,gameDiv and drawingUtil with argument
- *
- * can receive follow type of arguemnt:
- * - empty: create a canvas append to document's body, and setup other option
- * - string: search the element by document.getElementById(),
- * if this element is HTMLCanvasElement, set this element as main canvas of engine, and set it's ParentNode as cc._gameDiv.
- * if this element is HTMLDivElement, set it's ParentNode to cc._gameDiv, and create a canvas as main canvas of engine.
- *
- * @function
- * @example
- * //setup with null
- * cc._setup();
- *
- * // setup with HTMLCanvasElement, gameCanvas is Canvas element
- * // declare like this:
- * cc._setup("gameCanvas");
- *
- * //setup with HTMLDivElement, gameDiv is Div element
- * // declare like this:
- * cc._setup("Cocos2dGameContainer");
- */
-cc._setupCalled = false;
-cc._setup = function (el, width, height) {
- // Avoid setup to be called twice.
- if (cc._setupCalled) return;
- else cc._setupCalled = true;
- var win = window;
- var lastTime = new Date();
- var frameTime = 1000 / cc.game.config[cc.game.CONFIG_KEY.frameRate];
-
- var stTime = function(callback){
- var currTime = new Date().getTime();
- var timeToCall = Math.max(0, frameTime - (currTime - lastTime));
- var id = window.setTimeout(function() { callback(); },
- timeToCall);
- lastTime = currTime + timeToCall;
- return id;
- };
+function _determineRenderType(config) {
+ var CONFIG_KEY = cc.game.CONFIG_KEY,
+ userRenderMode = parseInt(config[CONFIG_KEY.renderMode]) || 0;
- var ctTime = function(id){
- clearTimeout(id);
- };
+ // Adjust RenderType
+ if (isNaN(userRenderMode) || userRenderMode > 2 || userRenderMode < 0)
+ config[CONFIG_KEY.renderMode] = 0;
- if(cc.sys.os === cc.sys.OS_IOS && cc.sys.browserType === cc.sys.BROWSER_TYPE_WECHAT){
- win.requestAnimFrame = stTime;
- win.cancelAnimationFrame = ctTime;
- }else if(cc.game.config[cc.game.CONFIG_KEY.frameRate] != 60){
- win.requestAnimFrame = stTime;
- win.cancelAnimationFrame = ctTime;
- }else{
- win.requestAnimFrame = win.requestAnimationFrame ||
- win.webkitRequestAnimationFrame ||
- win.mozRequestAnimationFrame ||
- win.oRequestAnimationFrame ||
- win.msRequestAnimationFrame ||
- stTime;
- win.cancelAnimationFrame = window.cancelAnimationFrame ||
- window.cancelRequestAnimationFrame ||
- window.msCancelRequestAnimationFrame ||
- window.mozCancelRequestAnimationFrame ||
- window.oCancelRequestAnimationFrame ||
- window.webkitCancelRequestAnimationFrame ||
- window.msCancelAnimationFrame ||
- window.mozCancelAnimationFrame ||
- window.webkitCancelAnimationFrame ||
- window.oCancelAnimationFrame ||
- ctTime;
- }
+ // Determine RenderType
+ cc._renderType = cc.game.RENDER_TYPE_CANVAS;
+ cc._supportRender = false;
- var element = cc.$(el) || cc.$('#' + el);
- var localCanvas, localContainer, localConStyle;
- if (element.tagName == "CANVAS") {
- width = width || element.width;
- height = height || element.height;
-
- //it is already a canvas, we wrap it around with a div
- localContainer = cc.container = cc.newElement("DIV");
- localCanvas = cc._canvas = element;
- localCanvas.parentNode.insertBefore(localContainer, localCanvas);
- localCanvas.appendTo(localContainer);
- localContainer.setAttribute('id', 'Cocos2dGameContainer');
- } else {//we must make a new canvas and place into this element
- if (element.tagName != "DIV") {
- cc.log("Warning: target element is not a DIV or CANVAS");
+ if (userRenderMode === 0) {
+ if (cc.sys.capabilities["opengl"]) {
+ cc._renderType = cc.game.RENDER_TYPE_WEBGL;
+ cc._supportRender = true;
+ }
+ else if (cc.sys.capabilities["canvas"]) {
+ cc._renderType = cc.game.RENDER_TYPE_CANVAS;
+ cc._supportRender = true;
}
- width = width || element.clientWidth;
- height = height || element.clientHeight;
- localContainer = cc.container = element;
- localCanvas = cc._canvas = cc.$(cc.newElement("CANVAS"));
- element.appendChild(localCanvas);
}
+ else if (userRenderMode === 1 && cc.sys.capabilities["canvas"]) {
+ cc._renderType = cc.game.RENDER_TYPE_CANVAS;
+ cc._supportRender = true;
+ }
+ else if (userRenderMode === 2 && cc.sys.capabilities["opengl"]) {
+ cc._renderType = cc.game.RENDER_TYPE_WEBGL;
+ cc._supportRender = true;
+ }
+}
+
+function _getJsListOfModule(moduleMap, moduleName, dir) {
+ if (_jsAddedCache[moduleName]) return null;
+ dir = dir || "";
+ var jsList = [];
+ var tempList = moduleMap[moduleName];
+ if (!tempList) throw new Error("can not find module [" + moduleName + "]");
+ var ccPath = cc.path;
+ for (var i = 0, li = tempList.length; i < li; i++) {
+ var item = tempList[i];
+ if (_jsAddedCache[item]) continue;
+ var extname = ccPath.extname(item);
+ if (!extname) {
+ var arr = _getJsListOfModule(moduleMap, item, dir);
+ if (arr) jsList = jsList.concat(arr);
+ } else if (extname.toLowerCase() === ".js") jsList.push(ccPath.join(dir, item));
+ _jsAddedCache[item] = 1;
+ }
+ return jsList;
+}
+
+function _afterEngineLoaded(config) {
+ if (cc._initDebugSetting)
+ cc._initDebugSetting(config[cc.game.CONFIG_KEY.debugMode]);
+ cc._engineLoaded = true;
+ console.log(cc.ENGINE_VERSION);
+ if (_engineLoadedCallback) _engineLoadedCallback();
+}
+
+function _load(config) {
+ var self = this;
+ var CONFIG_KEY = cc.game.CONFIG_KEY, engineDir = config[CONFIG_KEY.engineDir], loader = cc.loader;
- localCanvas.addClass("gameCanvas");
- localCanvas.setAttribute("width", width || 480);
- localCanvas.setAttribute("height", height || 320);
- localCanvas.setAttribute("tabindex", 99);
- localCanvas.style.outline = "none";
- localConStyle = localContainer.style;
- localConStyle.width = (width || 480) + "px";
- localConStyle.height = (height || 320) + "px";
- localConStyle.margin = "0 auto";
-
- localConStyle.position = 'relative';
- localConStyle.overflow = 'hidden';
- localContainer.top = '100%';
-
- if (cc._renderType == cc._RENDER_TYPE_WEBGL)
- cc._renderContext = cc.webglContext = cc.create3DContext(localCanvas, {
- 'stencil': true,
- 'preserveDrawingBuffer': true,
- 'antialias': !cc.sys.isMobile,
- 'alpha': false});
- if (cc._renderContext) {
- win.gl = cc._renderContext; // global variable declared in CCMacro.js
- cc._drawingUtil = new cc.DrawingPrimitiveWebGL(cc._renderContext);
- cc._rendererInitialized = true;
- cc.textureCache._initializingRenderer();
- cc.shaderCache._init();
+ if (cc.Class) {
+ // Single file loaded
+ _afterEngineLoaded(config);
} else {
- cc._renderContext = localCanvas.getContext("2d");
- cc._mainRenderContextBackup = cc._renderContext;
- cc._renderContext.translate(0, localCanvas.height);
- cc._drawingUtil = cc.DrawingPrimitiveCanvas ? new cc.DrawingPrimitiveCanvas(cc._renderContext) : null;
+ // Load cocos modules
+ var ccModulesPath = cc.path.join(engineDir, "moduleConfig.json");
+ loader.loadJson(ccModulesPath, function (err, modulesJson) {
+ if (err) throw new Error(err);
+ var modules = config["modules"] || [];
+ var moduleMap = modulesJson["module"];
+ var jsList = [];
+ if (cc.sys.capabilities["opengl"] && modules.indexOf("base4webgl") < 0) modules.splice(0, 0, "base4webgl");
+ else if (modules.indexOf("core") < 0) modules.splice(0, 0, "core");
+ for (var i = 0, li = modules.length; i < li; i++) {
+ var arr = _getJsListOfModule(moduleMap, modules[i], engineDir);
+ if (arr) jsList = jsList.concat(arr);
+ }
+ cc.loader.loadJsWithImg(jsList, function (err) {
+ if (err) throw err;
+ _afterEngineLoaded(config);
+ });
+ });
}
-
- cc._gameDiv = localContainer;
- cc.log(cc.ENGINE_VERSION);
- cc._setContextMenuEnable(false);
-
- if (cc.sys.isMobile) {
- var fontStyle = cc.newElement("style");
- fontStyle.type = "text/css";
- document.body.appendChild(fontStyle);
-
- fontStyle.textContent = "body,canvas,div{ -moz-user-select: none;-webkit-user-select: none;-ms-user-select: none;-khtml-user-select: none;"
- + "-webkit-tap-highlight-color:rgba(0,0,0,0);}";
+}
+
+function _windowLoaded() {
+ this.removeEventListener('load', _windowLoaded, false);
+ _load(cc.game.config);
+}
+
+cc.initEngine = function (config, cb) {
+ if (_engineInitCalled) {
+ var previousCallback = _engineLoadedCallback;
+ _engineLoadedCallback = function () {
+ previousCallback && previousCallback();
+ cb && cb();
+ }
+ return;
}
- // Init singletons
+ _engineLoadedCallback = cb;
- /**
- * @type {cc.EGLView}
- * @name cc.view
- * cc.view is the shared view object.
- */
- cc.view = cc.EGLView._getInstance();
- // register system events
- cc.inputManager.registerSystemEvent(cc._canvas);
-
- /**
- * @type {cc.Director}
- * @name cc.director
- */
- cc.director = cc.Director._getInstance();
- if (cc.director.setOpenGLView)
- cc.director.setOpenGLView(cc.view);
- /**
- * @type {cc.Size}
- * @name cc.winSize
- * cc.winSize is the alias object for the size of the current game window.
- */
- cc.winSize = cc.director.getWinSize();
+ // Config uninitialized and given, initialize with it
+ if (!cc.game.config && config) {
+ cc.game.config = config;
+ }
+ // No config given and no config set before, load it
+ else if (!cc.game.config) {
+ cc.game._loadConfig();
+ }
+ config = cc.game.config;
- // Parsers
- cc.saxParser = new cc.SAXParser();
- /**
- * @type {cc.PlistParser}
- * @name cc.plistParser
- * A Plist Parser
- */
- cc.plistParser = new cc.PlistParser();
-};
+ _determineRenderType(config);
-cc._checkWebGLRenderMode = function () {
- if (cc._renderType !== cc._RENDER_TYPE_WEBGL)
- throw "This feature supports WebGL render mode only.";
+ document.body ? _load(config) : cc._addEventListener(window, 'load', _windowLoaded, false);
+ _engineInitCalled = true;
};
-cc._isContextMenuEnable = false;
-/**
- * enable/disable contextMenu for Canvas
- * @param {Boolean} enabled
- */
-cc._setContextMenuEnable = function (enabled) {
- cc._isContextMenuEnable = enabled;
- cc._canvas.oncontextmenu = function () {
- if (!cc._isContextMenuEnable) return false;
- };
-};
+})();
+//+++++++++++++++++++++++++Engine initialization function end+++++++++++++++++++++++++++++
+//+++++++++++++++++++++++++something about CCGame begin+++++++++++++++++++++++++++
/**
* An object to boot the game.
* @class
* @name cc.game
+ *
*/
cc.game = /** @lends cc.game# */{
+ /**
+ * Debug mode: No debugging. {@static}
+ * @const {Number}
+ * @static
+ */
DEBUG_MODE_NONE: 0,
+ /**
+ * Debug mode: Info, warning, error to console.
+ * @const {Number}
+ * @static
+ */
DEBUG_MODE_INFO: 1,
+ /**
+ * Debug mode: Warning, error to console.
+ * @const {Number}
+ * @static
+ */
DEBUG_MODE_WARN: 2,
+ /**
+ * Debug mode: Error to console.
+ * @const {Number}
+ * @static
+ */
DEBUG_MODE_ERROR: 3,
+ /**
+ * Debug mode: Info, warning, error to web page.
+ * @const {Number}
+ * @static
+ */
DEBUG_MODE_INFO_FOR_WEB_PAGE: 4,
+ /**
+ * Debug mode: Warning, error to web page.
+ * @const {Number}
+ * @static
+ */
DEBUG_MODE_WARN_FOR_WEB_PAGE: 5,
+ /**
+ * Debug mode: Error to web page.
+ * @const {Number}
+ * @static
+ */
DEBUG_MODE_ERROR_FOR_WEB_PAGE: 6,
+ /**
+ * Event that is fired when the game is hidden.
+ * @constant {String}
+ */
EVENT_HIDE: "game_on_hide",
+ /**
+ * Event that is fired when the game is shown.
+ * @constant {String}
+ */
EVENT_SHOW: "game_on_show",
+ /**
+ * Event that is fired when the game is resized.
+ * @constant {String}
+ */
+ EVENT_RESIZE: "game_on_resize",
+ /**
+ * Event that is fired when the renderer is done being initialized.
+ * @constant {String}
+ */
+ EVENT_RENDERER_INITED: "renderer_inited",
+
+ /** @constant {Number} */
+ RENDER_TYPE_CANVAS: 0,
+ /** @constant {Number} */
+ RENDER_TYPE_WEBGL: 1,
+ /** @constant {Number} */
+ RENDER_TYPE_OPENGL: 2,
+
_eventHide: null,
_eventShow: null,
- _onBeforeStartArr: [],
/**
- * Key of config
+ * Keys found in project.json.
+ *
* @constant
* @type {Object}
+ *
+ * @prop {String} engineDir - In debug mode, if you use the whole engine to develop your game, you should specify its relative path with "engineDir".
+ * @prop {String} modules - Defines which modules you will need in your game, it's useful only on web
+ * @prop {String} debugMode - Debug mode, see DEBUG_MODE_XXX constant definitions.
+ * @prop {String} exposeClassName - Expose class name to chrome debug tools
+ * @prop {String} showFPS - Left bottom corner fps information will show when "showFPS" equals true, otherwise it will be hide.
+ * @prop {String} frameRate - Sets the wanted frame rate for your game, but the real fps depends on your game implementation and the running environment.
+ * @prop {String} id - Sets the id of your canvas element on the web page, it's useful only on web.
+ * @prop {String} renderMode - Sets the renderer type, only useful on web, 0: Automatic, 1: Canvas, 2: WebGL
+ * @prop {String} jsList - Sets the list of js files in your game.
*/
CONFIG_KEY: {
+ width: "width",
+ height: "height",
engineDir: "engineDir",
- dependencies: "dependencies",
+ modules: "modules",
debugMode: "debugMode",
+ exposeClassName: "exposeClassName",
showFPS: "showFPS",
frameRate: "frameRate",
id: "id",
renderMode: "renderMode",
- jsList: "jsList",
- classReleaseMode: "classReleaseMode"
+ jsList: "jsList"
},
+ // states
+ _paused: true,//whether the game is paused
+ _configLoaded: false,//whether config loaded
_prepareCalled: false,//whether the prepare function has been called
_prepared: false,//whether the engine has prepared
- _paused: true,//whether the game is paused
+ _rendererInitialized: false,
+
+ _renderContext: null,
_intervalId: null,//interval target of main
+ _lastTime: null,
+ _frameTime: null,
+
+ /**
+ * The outer frame of the game canvas, parent of cc.container
+ * @type {Object}
+ */
+ frame: null,
+ /**
+ * The container of game canvas, equals to cc.container
+ * @type {Object}
+ */
+ container: null,
+ /**
+ * The canvas of the game, equals to cc._canvas
+ * @type {Object}
+ */
+ canvas: null,
+
/**
* Config of game
* @type {Object}
@@ -2020,16 +2396,19 @@ cc.game = /** @lends cc.game# */{
/**
* Callback when the scripts of engine have been load.
- * @type {Function}
+ * @type {Function|null}
*/
onStart: null,
/**
* Callback when game exits.
- * @type {Function}
+ * @type {Function|null}
*/
onStop: null,
+//@Public Methods
+
+// @Game play control
/**
* Set frameRate of game.
* @param frameRate
@@ -2039,27 +2418,54 @@ cc.game = /** @lends cc.game# */{
config[CONFIG_KEY.frameRate] = frameRate;
if (self._intervalId)
window.cancelAnimationFrame(self._intervalId);
+ self._intervalId = 0;
self._paused = true;
+ self._setAnimFrame();
self._runMainLoop();
},
- //Run game.
- _runMainLoop: function () {
- var self = this, callback, config = self.config, CONFIG_KEY = self.CONFIG_KEY,
- director = cc.director;
- director.setDisplayStats(config[CONFIG_KEY.showFPS]);
+ /**
+ * Run the game frame by frame.
+ */
+ step: function () {
+ cc.director.mainLoop();
+ },
- callback = function () {
- if (!self._paused) {
- director.mainLoop();
- if(self._intervalId)
- window.cancelAnimationFrame(self._intervalId);
- self._intervalId = window.requestAnimFrame(callback);
- }
- };
+ /**
+ * Pause the game.
+ */
+ pause: function () {
+ if (this._paused) return;
+ this._paused = true;
+ // Pause audio engine
+ if (cc.audioEngine) {
+ cc.audioEngine._pausePlaying();
+ }
+ // Pause main loop
+ if (this._intervalId)
+ window.cancelAnimationFrame(this._intervalId);
+ this._intervalId = 0;
+ },
- window.requestAnimFrame(callback);
- self._paused = false;
+ /**
+ * Resume the game from pause.
+ */
+ resume: function () {
+ if (!this._paused) return;
+ this._paused = false;
+ // Resume audio engine
+ if (cc.audioEngine) {
+ cc.audioEngine._resumePlaying();
+ }
+ // Resume main loop
+ this._runMainLoop();
+ },
+
+ /**
+ * Check whether the game is paused.
+ */
+ isPaused: function () {
+ return this._paused;
},
/**
@@ -2074,153 +2480,399 @@ cc.game = /** @lends cc.game# */{
},
/**
- * Run game.
+ * End game, it will close the game window
*/
- run: function (id) {
- var self = this;
- var _run = function () {
- if (id) {
- self.config[self.CONFIG_KEY.id] = id;
- }
- if (!self._prepareCalled) {
- self.prepare(function () {
+ end: function () {
+ close();
+ },
+
+// @Game loading
+ /**
+ * Prepare game.
+ * @param cb
+ */
+ prepare: function (cb) {
+ var self = this,
+ config = self.config,
+ CONFIG_KEY = self.CONFIG_KEY;
+
+ // Config loaded
+ if (!this._configLoaded) {
+ this._loadConfig(function () {
+ self.prepare(cb);
+ });
+ return;
+ }
+
+ // Already prepared
+ if (this._prepared) {
+ if (cb) cb();
+ return;
+ }
+ // Prepare called, but not done yet
+ if (this._prepareCalled) {
+ return;
+ }
+ // Prepare never called and engine ready
+ if (cc._engineLoaded) {
+ this._prepareCalled = true;
+
+ this._initRenderer(config[CONFIG_KEY.width], config[CONFIG_KEY.height]);
+
+ /**
+ * cc.view is the shared view object.
+ * @type {cc.EGLView}
+ * @name cc.view
+ * @memberof cc
+ */
+ cc.view = cc.EGLView._getInstance();
+
+ /**
+ * @type {cc.Director}
+ * @name cc.director
+ * @memberof cc
+ */
+ cc.director = cc.Director._getInstance();
+ if (cc.director.setOpenGLView)
+ cc.director.setOpenGLView(cc.view);
+ /**
+ * cc.winSize is the alias object for the size of the current game window.
+ * @type {cc.Size}
+ * @name cc.winSize
+ * @memberof cc
+ */
+ cc.winSize = cc.director.getWinSize();
+
+ this._initEvents();
+
+ this._setAnimFrame();
+ this._runMainLoop();
+
+ // Load game scripts
+ var jsList = config[CONFIG_KEY.jsList];
+ if (jsList) {
+ cc.loader.loadJsWithImg(jsList, function (err) {
+ if (err) throw new Error(err);
self._prepared = true;
+ if (cb) cb();
});
}
- if (cc._supportRender) {
- self._checkPrepare = setInterval(function () {
- if (self._prepared) {
- cc._setup(self.config[self.CONFIG_KEY.id]);
- self._runMainLoop();
- self._eventHide = self._eventHide || new cc.EventCustom(self.EVENT_HIDE);
- self._eventHide.setUserData(self);
- self._eventShow = self._eventShow || new cc.EventCustom(self.EVENT_SHOW);
- self._eventShow.setUserData(self);
- self.onStart();
- clearInterval(self._checkPrepare);
- }
- }, 10);
+ else {
+ if (cb) cb();
}
- };
- document.body ?
- _run() :
- cc._addEventListener(window, 'load', function () {
- this.removeEventListener('load', arguments.callee, false);
- _run();
- }, false);
+
+ return;
+ }
+
+ // Engine not loaded yet
+ cc.initEngine(this.config, function () {
+ self.prepare(cb);
+ });
},
- _initConfig: function () {
- var self = this, CONFIG_KEY = self.CONFIG_KEY;
- var _init = function (cfg) {
- cfg[CONFIG_KEY.engineDir] = cfg[CONFIG_KEY.engineDir] || "frameworks/cocos2d-html5";
- if(cfg[CONFIG_KEY.debugMode] == null)
- cfg[CONFIG_KEY.debugMode] = 0;
- cfg[CONFIG_KEY.frameRate] = cfg[CONFIG_KEY.frameRate] || 60;
- if(cfg[CONFIG_KEY.renderMode] == null)
- cfg[CONFIG_KEY.renderMode] = 1;
- return cfg;
- };
- if (document["ccConfig"]) {
- self.config = _init(document["ccConfig"]);
- } else {
- try {
- var cocos_script = document.getElementsByTagName('script');
- for(var i=0;i -1) {
+ win.onfocus = function(){ onShow() };
+ }
+
+ if ("onpageshow" in window && "onpagehide" in window) {
+ win.addEventListener("pagehide", onHidden, false);
+ win.addEventListener("pageshow", onShow, false);
+ }
+
+ cc.eventManager.addCustomListener(cc.game.EVENT_HIDE, function () {
+ cc.game.pause();
+ });
+ cc.eventManager.addCustomListener(cc.game.EVENT_SHOW, function () {
+ cc.game.resume();
+ });
}
};
-cc.game._initConfig();
//+++++++++++++++++++++++++something about CCGame end+++++++++++++++++++++++++++++
Function.prototype.bind = Function.prototype.bind || function (oThis) {
diff --git a/CCDebugger.js b/CCDebugger.js
index c14408afca..7acfc1cb0d 100644
--- a/CCDebugger.js
+++ b/CCDebugger.js
@@ -68,7 +68,8 @@ cc._LogInfos = {
Node_resumeSchedulerAndActions: "resumeSchedulerAndActions is deprecated, please use resume instead.",
Node_pauseSchedulerAndActions: "pauseSchedulerAndActions is deprecated, please use pause instead.",
Node__arrayMakeObjectsPerformSelector: "Unknown callback function",
- Node_reorderChild: "child must be non-null",
+ Node_reorderChild: "cc.Node.reorderChild(): child must be non-null",
+ Node_reorderChild_2: "cc.Node.reorderChild(): this child is not in children list",
Node_runAction: "cc.Node.runAction(): action must be non-null",
Node_schedule: "callback function must be non-null",
Node_schedule_2: "interval must be positive",
@@ -119,7 +120,6 @@ cc._LogInfos = {
animationCache__parseVersion2_2: "cocos2d: cc.AnimationCache: Animation '%s' refers to frame '%s' which is not currently in the cc.SpriteFrameCache. This frame will not be added to the animation.",
animationCache_addAnimations_2: "cc.AnimationCache.addAnimations(): Invalid texture file name",
- Sprite_reorderChild: "cc.Sprite.reorderChild(): this child is not in children list",
Sprite_ignoreAnchorPointForPosition: "cc.Sprite.ignoreAnchorPointForPosition(): it is invalid in cc.Sprite when using SpriteBatchNode",
Sprite_setDisplayFrameWithAnimationName: "cc.Sprite.setDisplayFrameWithAnimationName(): Frame not found",
Sprite_setDisplayFrameWithAnimationName_2: "cc.Sprite.setDisplayFrameWithAnimationName(): Invalid frame index",
@@ -130,7 +130,6 @@ cc._LogInfos = {
Sprite_initWithSpriteFrameName1: " is null, please check.",
Sprite_initWithFile: "cc.Sprite.initWithFile(): filename should be non-null",
Sprite_setDisplayFrameWithAnimationName_3: "cc.Sprite.setDisplayFrameWithAnimationName(): animationName must be non-null",
- Sprite_reorderChild_2: "cc.Sprite.reorderChild(): child should be non-null",
Sprite_addChild: "cc.Sprite.addChild(): cc.Sprite only supports cc.Sprites as children when using cc.SpriteBatchNode",
Sprite_addChild_2: "cc.Sprite.addChild(): cc.Sprite only supports a sprite using same texture as children when using cc.SpriteBatchNode",
Sprite_addChild_3: "cc.Sprite.addChild(): child should be non-null",
@@ -282,7 +281,7 @@ cc._formatString = function (arg) {
*/
cc._initDebugSetting = function (mode) {
var ccGame = cc.game;
- if(mode == ccGame.DEBUG_MODE_NONE)
+ if(mode === ccGame.DEBUG_MODE_NONE)
return;
var locLog;
@@ -299,12 +298,12 @@ cc._initDebugSetting = function (mode) {
locLog("Assert: " + msg);
}
};
- if(mode != ccGame.DEBUG_MODE_ERROR_FOR_WEB_PAGE){
+ if(mode !== ccGame.DEBUG_MODE_ERROR_FOR_WEB_PAGE){
cc.warn = function(){
locLog("WARN : " + cc.formatStr.apply(cc, arguments));
};
}
- if(mode == ccGame.DEBUG_MODE_INFO_FOR_WEB_PAGE){
+ if(mode === ccGame.DEBUG_MODE_INFO_FOR_WEB_PAGE){
cc.log = function(){
locLog(cc.formatStr.apply(cc, arguments));
};
@@ -312,25 +311,23 @@ cc._initDebugSetting = function (mode) {
} else if(console && console.log.apply){//console is null when user doesn't open dev tool on IE9
//log to console
- cc.error = function(){
- return console.error.apply(console, arguments);
- };
- cc.assert = function (cond, msg) {
- if (!cond && msg) {
- for (var i = 2; i < arguments.length; i++)
- msg = msg.replace(/(%s)|(%d)/, cc._formatString(arguments[i]));
- throw msg;
- }
- };
- if(mode != ccGame.DEBUG_MODE_ERROR)
- cc.warn = function(){
- return console.warn.apply(console, arguments);
- };
- if(mode == ccGame.DEBUG_MODE_INFO)
- cc.log = function(){
- return console.log.apply(console, arguments);
+ cc.error = Function.prototype.bind.call(console.error, console);
+ //If console.assert is not support user throw Error msg on wrong condition
+ if (console.assert) {
+ cc.assert = Function.prototype.bind.call(console.assert, console);
+ } else {
+ cc.assert = function (cond, msg) {
+ if (!cond && msg) {
+ for (var i = 2; i < arguments.length; i++)
+ msg = msg.replace(/(%s)|(%d)/, cc._formatString(arguments[i]));
+ throw new Error(msg);
+ }
};
+ }
+ if (mode !== ccGame.DEBUG_MODE_ERROR)
+ cc.warn = Function.prototype.bind.call(console.warn, console);
+ if (mode === ccGame.DEBUG_MODE_INFO)
+ cc.log = Function.prototype.bind.call(console.log, console);
}
};
-cc._initDebugSetting(cc.game.config[cc.game.CONFIG_KEY.debugMode]);
-//+++++++++++++++++++++++++something about log end+++++++++++++++++++++++++++++
\ No newline at end of file
+//+++++++++++++++++++++++++something about log end+++++++++++++++++++++++++++++
diff --git a/CHANGELOG.txt b/CHANGELOG.txt
index 2f5809f9dc..9cfe4159f7 100644
--- a/CHANGELOG.txt
+++ b/CHANGELOG.txt
@@ -1,5 +1,374 @@
ChangeLog:
+Cocos2d-x v3.8 @ September.6 2015
+
+ [NEW] spine: Supported Spine runtime 2.3 (Both native and web engine)
+ [NEW] Animate: Added Animate's getCurrentFrameIndex function
+ [NEW] network: Upgrade SocketIO support to v1.x
+
+ [REFINE] web: Avoid re-bake the content when the parent node's position get changed
+ [REFINE] web: Added GameNodeObjectData and GameLayerObjectData in JSON parser
+ [REFINE] web: Updated skeleton animation to the latest version
+ [REFINE] web: Optimized resources automatic loading in JSON parser
+ [REFINE] web: Avoid cc.loader resource loading being terminated while encounter errors
+ [REFINE] web: Throw new Error object instead of error message string
+ [REFINE] web: Move setDepthTest to renderer
+ [REFINE] web: Added BlendFuncFrame parser
+ [REFINE] web: Permitted webp image loading on Chrome
+ [REFINE] web: Suspended the video player when the browser is minimized
+
+ [FIX] web: Fixed a bug that VideoPlayer remove event throw error
+ [FIX] web: Fixed Armature position error in studio JSON parser
+ [FIX] web: Fixed default clearColor error in director
+ [FIX] web: Fixed rotation value parsing error in the timeline parser
+ [FIX] web: Fixed a bug that nested animation may be affected by outer animation
+ [FIX] web: Made LabelAtlas ignoring invalid characters and updating correctly the content size
+ [FIX] web: Fixed a bug that VideoPlayer remove event throw error
+ [FIX] web: Fixed a bug that cc.director.setNotificationNode(null) doesn't take effect
+ [FIX] web: Fixed texture rect update issue while changing sprite frame
+ [FIX] web: Fixed effect issue in ActionGrid and NodeGrid
+ [FIX] web: Fixed logic issue in Menu's _onTouchCancelled function
+ [FIX] web: Fixed MenuItem crash when normal image is null
+ [FIX] web: Fixed incomplete fadeout effects
+ [FIX] web: Fixed issue that return value of cc.screen.fullScreen is not boolean
+ [FIX] web: Fixed a bug that SkeletonNode is not drawing children
+
+ [TEST] web: Rewrote testcase for stencil depth mask in RenderTextureTest
+ [TEST] web: Improved renderTexture stencilDepth test
+ [TEST] web: Fixed abnormal effects in effectsTest
+ [TEST] web: Fixed invisiable testcase of effects
+
+Cocos2d-x v3.7.1 @ August.12 2015
+ [HIGHLIGHT] studio: Added new skeleton animation support and JSON parser for cocos v2.3.2 beta
+
+ [NEW] Node: Added getNodeToParentTransform with selected ancestor
+ [NEW] web: Added cc.director.setClearColor and support transparent background
+ [NEW] web: Added Animate's getCurrentFrameIndex function
+
+ [REFINE] studio: Optimized JSON parser's performance by removing audio play
+ [REFINE] studio: Optimized editor related extension data to a component instead of hosting in _userObject
+ [REFINE] web: Improved color/opacity manipulations in MenuItems
+
+ [FIX] studio: Fixed ccs.Skin construction issue in JSON parser
+ [FIX] web: Fixed an issue that loading process won't trigger callback problem
+ [FIX] web: Fixed a bug where not resetting cc.Audio._ignoreEnded when replaying a sound caused it to stay in a "playing" state
+ [FIX] web: cc.ScrollView and cc.TableView: added check for parent visibility in onTouchBegan method
+ [FIX] web: Fixed TurnPageDown effect
+ [FIX] web: Fixed Cocos Studio parser issue that all elements are missing while the timeline action contains rotation
+
+Cocos2d-x v3.7 Final @ July 20 2015
+ [REFINE] web: Add compatible Uint16Array definition
+
+ [FIX] web: Fixed url check regular expression not supporting localhost issue
+ [FIX] web: Fixed issue that sprite doesn't update texture rect correctly
+
+Cocos2d-x v3.7 RC1 @ July 14 2015
+ [REFINE] Improved localStorage warning when disabled
+
+ [FIX] Fixed a bug that SingleNode's color isn't set
+ [FIX] studio: Fixed a bug of JSON parser that texture address is wrong
+ [FIX] Fixed MenuItems' color/opacity setter issue with child nodes
+ [FIX] Fixed page view's layout issue for JSON parser
+ [FIX] Add ttc loader and prevent the pure digital fonts is invalid
+ [FIX] Fixed Float32Array initialization
+ [FIX] Fixed a bug that layout background is missing
+ [FIX] Fixed a bug that ObjectExtensionData miss setCustomProperty and getCustomProperty function
+
+Cocos2d-x v3.7 RC0 @ July 1 2015
+
+* The json loader of Cocos Studio will automatically load dependencies resources
+* SIMD.js optimization for kazmath functions (from Intel)
+* Deleted the redundant variables defined and log informations in ccui.RichText
+* Allowed timeline animations with only one frame
+* Improved property declaration of cc.Texture2D
+
+* Bug fixes:
+ 1. Fixed positionType error of particle system in timeline parser
+ 2. Fixed setAnimationName issue while the property is undefined in timeline parser
+ 3. Fixed `cc.TMXObjectGroup#objectNamed` not returning the result bug
+ 4. Fixed TransitionSlideX callback sequence issue
+ 5. Fixed issue in music end event
+ 6. Fixed bug that LayerColor's color will disappear when update transform after being baked
+ 7. Fixed `inverse` function bug of `cc.math.Matrix4`
+ 8. Fixed the webaudio's invalid loop attribute bug for chrome 42
+ 9. Fixed crash when character not found into BMP font
+ 10. Fixed spine's js parser issue by avoid NaN duration
+ 11. Fixed LabelTTF multiline detection
+ 12. Fixed issue in ccui.Widget#getScale
+ 13. Fixed texture is not updated in some cases
+ 14. PlayMusic should not use the search path (timeline 2.x)
+ 15. Fixed bug of loading path of resources
+ 16. Premultiply texture's alpha for png by default to fix Cocos Studio render issues
+ 17. Fixed cache update issue of Layout after bake
+ 18. Fixed isBaked returning undefined issue
+ 19. Made CCProgressTimerCanvasRenderCmd to properly show colorized sprites
+ 20. Fixed attributes being reset issue while baked cache canvas' size changed
+ 21. Fixed texture does not rotate bug of ccui.LoadingBar
+ 22. Fixed color not being set issue in timeline parser
+ 23. Fixed custom easing animation bug
+ 24. Fixed return empty texture2d bug when adding image with same url multiple times
+ 25. Fixed actiontimeline can not step to last frame issue when loop play
+ 26. Fixed the prompt can not be used in iOS wechat 6.2
+ 27. Fixed restoring of sprite's color issue
+ 28. Fixed Uint8Array initialize issue
+ 29. Fixed cc.TextFieldTTF Delegate memory leaks
+ 30. Fixed sorted result is wrong in cc.eventManager (_sortEventListenersOfSceneGraphPriorityDes)
+ 31. Fixed BinaryLoader issue on IE11
+ 32. Fixed the sprite's texture bug when frequently change the color
+ 33. Fixed an issue that action will result in automatic termination
+ 34. Fixed ScrollView initWithViewSize issue
+
+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.
+* 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.
+* 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 movement 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.
+* 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.
+* Added an option "noCache" for debugging on browsers.
+* Set the default value of `cc.ParticleSystem`'s draw mode to texture mode.
+* Added message to `ccs.load` when loading armature json file.
+* Improved particle system test case.
+
+* Bug fixes:
+ 1. Fixed a bug of `cc.Sprite` that its `setSpriteFrame` doesn't work when sprite frame's `rotated` property is true.
+ 2. Fixed a bug of `cc.ClippingNode` when its stencil is `cc.Node` object in canvas mode.
+ 3. Fixed a ccui bug that the position of widgets is incorrect after loaded v2.x json file with `ccs.load`.
+ 4. Fixed a bug of `cc.PhysicsSprite` that `setIgnoreBodyRotation` function doesn't work.
+ 5. Fixed a bug of `ccui.Button` that setting pressed texture doesn't work when scale9 enabled.
+ 6. Fixed a bug of `ccui.ScrollView` that its `dir` property is null when passing `DIR_NONE` as `direction` in `_endRecordSlidAction` function.
+
+Cocos2d-JS v3.3 RC0 @ Feb.1, 2015
+
+* Added web exclusive functions: `_getFontStyle`, `_setFontStyle`, `_getFontWeight` and `_setFontWeight` APIs to `cc.LabelTTF`.
+* Observed orientation change event on mobile for resolution policy adaptation.
+
+* Bug fixes:
+ 1. Fixed Cocos Studio JSON parser's issues for parsing nested animation.
+ 2. Fixed Cocos Studio JSON parser's parameters parsing issues.
+ 3. Fixed Cocos Studio JSON parser's issue for parsing layer.
+ 4. Fixed Cocos Studio JSON action parser's issues.
+ 5. Fixed Cocos Studio JSON parser's issue for parsing Scale9Sprite.
+ 6. Fixed Cocos Studio JSON parser's issues caused by parsing process order.
+ 7. Fixed Cocos Studio JSON parser's issue for parsing loading bar's direction.
+ 8. Fixed UI layout system issues.
+ 9. Fixed `cc.EditBox`'s position issue under certain resolution policies.
+ 10. Fixed `ccui.ListView`'s issue for setting direction.
+ 11. Fixed an issue of `cc.Tween` that its `_currentPercent` is incorrect in `updateHandler` function.
+ 12. Fixed an issue of `ccui.Button` that its state is incorrect in `_onPressStateChangedToNormal`.
+ 13. Fixed an issue of `cc.ArmatureAnimation`'s `setMovementEventCallFunc`.
+ 14. Fixed an issue of `cc.Sequence` action when it's repeated.
+ 15. Fixed `_anchorPointInPoints` usage issue.
+ 16. Fixed an issue of `cc.GLProgram` that it doesn't work on some devices which didn't support highp float precision.
+ 17. Fixed an issue of fade actions that they don't work when duration is 0.
+ 18. Fixed `onended` callback issue of audio engine on iOS.
+ 19. Fixed Cocos Builder's parser issue for auto playing animations.
+ 20. Added a message to `ccs.Armature` that it doesn't support adding widget as its child.
+ 21. Improved test cases for stability.
+
+Cocos2d-JS v3.3 Beta @ Jan.24, 2015
+
+* Added Cocos Studio v2.x parser and refactored 1.x parser.
+* Upgraded new flow layout UI system in web engine.
+* Refactored `load` events of texture2d, sprite and so on to be more intuitive.
+* Added JavaScript file loader.
+* Allowed set texture to null in `cc.Sprite`.
+* Added full test cases for Cocos Studio v2.x parser and the new flow layout UI system.
+* Upgraded MoonWarriors sample's UI and graphic design.
+
+* Bug fixes:
+ 1. Fixed a bug of Cocos2d UI, their focus event has been supported.
+ 2. Fixed a buf of `ccui.Widget` that its percent position doesn't work.
+ 3. Fixed a bug of `ccs.Armature` that its position doesn't update in visit on WebGL render mode.
+ 4. Fixed a bug of `cc.Sprite` that its `setTextureRect` function doesn't work when `setColor` invoked.
+ 5. Fixed a bug of `cc.PhysicsSprite` that its position is incorrect.
+ 6. Fixed a bug of `ccs.Bone` that its `setOpacity` and `setColor` doesn't work.
+ 7. Fixed a bug of `cc.LabelBMFont` that its word wrap doesn't work.
+ 8. Fixed a bug of `cc.sys` that it gets the incorrect OS type when system is Linux.
+ 9. Fixed a bug of `cc.audioEngine` that its loading path is incorrect.
+ 10. Fixed a bug of `ccui.Widget` that it can't touch when it's reused.
+ 11. Fixed a bug of UI system that the `setNormalizedPosition` doesn't work.
+ 12. Fixed a bug of `cc.ActionInterval` that its `_times` conflict with `cc.Blink`.
+ 13. Fixed release texture issue in canvas mode.
+ 14. Fixed a bug of `ccs.actionManager` that its `getActionByName` doesn't work.
+ 15. Fixed a bug of `cc.Sprite` that it can't draw without texture on WebGL mode.
+ 16. Fixed a bug of `cc.audioEngine` that it doesn't work on baidu browser.
+ 17. Fixed a bug of `cc.EditBox` that its position is incorrect on Canvas Mode and its string value is wrong when PlaceHolder is showing.
+ 18. Fixed a bug of `cc.loader` that its `loadImg` function doesn't work when image is accessed cross origin.
+ 19. Fixed a bug of `ccui.TextField` that its `contentSize` is incorrect in text field event.
+
+Cocos2d-JS v3.2 @ Dec.29, 2014
+
+* Replaced `transform` function with `setTransform` function under canvas render mode for better performance.
+* Added a timer in `cc.audioEngine` to check audio element loading event, prevent the loading process being stucked when load audio file failed.
+* Added some new browser types to `cc.sys`.
+* Added some audio resource loading codes to ensure compatibility with Wechat browser.
+* Added check for WebAudio support to ensure compatibility.
+
+* Bug fixes:
+ 1. Fixed an issue that `cc.InputManager` doesn't trigger touch event on chrome mobile emulator.
+ 2. Fixed an issue that `cc.game.setFrameRate` doesn't work.
+ 3. Fixed an issue that `cc.view` can't remove resize event listener.
+ 4. Fixed an issue that `cc.EventManager` didn't set register flag to false when a listener is removed.
+ 5. Fixed an issue that `cc.audioEngine` doesn't play some audios on some iOS devices.
+ 6. Fixed an issue of ccui controls that their `setColor` doesn't work when cascade color is enabled.
+ 7. Fixed an issue that `ccs.Armature`'s `setColor` doesn't work in canvas render mode.
+ 8. Fixed an issue that `ccs.Armature` crashes when adding a child to it.
+ 9. Fixed an issue that `cc.SpriteBatchNode`'s status is incorrect in WebGL render mode.
+ 10. Fixed an issue of `cc.Layer` that its position is incorrect under bake mode.
+ 11. Fixed an issue of `ccui.RichText` that its `setContentSize` doesn't work.
+ 12. Fixed an issue of `cc.LabelTTF` that its `setColor` doesn't work when cascade color is enabled.
+ 13. Fixed an issue of spine that its skeletons position is incorrect when scaleX equals to -1 and scaleY equals to 1.
+ 14. Fixed `sp.Skeleton`'s API inconsistence by renaming `boundingBox` to `getBoundingBox`.
+ 15. Removed all usages of deprecated create functions in the test cases.
+
+Cocos2d-JS v3.2 RC0 @ Dec.11, 2014
+
+* Refactoration of web engine by separating the render logic, the arthictecture level refactoration is now completed and brounght great performance improvement.
+* Refactoration of web engine's resolution adaptation and audio engine with polyfilled adaptation logics for different devices and browsers. This ensures better compatibility and better extensibility for future needs.
+* Added `setRotation` method to `ccui.ImageView`.
+* Added a function that fill sprite with repeated texture in Canvas mode.
+* Added `setLineHeight` method to `cc.LabelTTF`.
+* Added `dumpAudioInfo` to `cc.audioEngine` for debugging purpose on mobile browser.
+* Removed Cocos Studio's Protobuffer support from the framework.
+* Added an outline shader sample.
+
+* Bug fixes:
+ 1. Fixed an issue of `cc.Sprite` that its rendering is incorrect without texture.
+ 2. Fixed an issue of `cc.ClippingNode` that its stencil drawing is incorrect on Canvas Mode.
+ 3. Fixed an issue of `TextFieldReader` that it will throw an error when 'areaWidth' and 'areaHeight' equal to zero.
+ 4. Fixed an issue of `ccui.CheckBox` that its getSelectedState doesn't return its state.
+ 5. Fixed an issue of `cc.LabelTTF` that it doesn't update the string when its string become to empty string.
+ 6. Fixed an issue of `cc.ParticleSystem` that it can't change its texture mode and shape type in Canvas mode.
+ 7. Fixed an issue of `cc.Layer`'s bake function that its position is incorrect when cc.view's scale isn't 1.
+ 8. Fixed an issue of `ccs.ArmatureAnimation`'s `setMovementEventCallFunc` and `setFrameEventCallFunc`.
+ 9. Fixed an issue of `console.log` that it isn't a function on IE9.
+ 10. Fixed an issue of `CSLoader` that it will add duplicate resources to sprite frame cache.
+ 11. Fixed an issue of `cc.ProgressTimer` that its setColor is not taking effect.
+ 12. Fixed an issue of `cc.loader` that it will throw an error when loading a remote texture.
+ 13. Upgrade html5 version chipmunk to the latest release.
+
Cocos2d-JS-v3.1 @ Oct.22, 2014
* Released Facebook Integration for Cocos2d-JS v1.0, all APIs have been significantly polished and stabilized. Improved test cases for Facebook with more features demonstrated.
diff --git a/README.mdown b/README.mdown
index 5e3bc6adcd..3b13c27fac 100644
--- a/README.mdown
+++ b/README.mdown
@@ -1,32 +1,26 @@
Cocos2d-html5
==================
-[Cocos2d-html5][1] is a cross-platform 2D game engine written in Javascript, based on [Cocos2d-X][2] and licensed under MIT.
+[Cocos2d-html5][1] is a cross-platform 2D game engine written in JavaScript, based on [Cocos2d-X][2] and licensed under MIT.
It incorporates the same high level api as “Cocos2d JS-binding engine†and compatible with Cocos2d-X.
-It currently supports canvas and will support WebGL in the future.
+It currently supports canvas and WebGL renderer.
+
+-------------
+
+#### Cocos2d-html5 has evolved to [Cocos Creator][11], new generation of Cocos game engine with a full featured editor and content creation friendly workflow. It supports all major platforms allowing games to be quickly released for the web, iOS, Android, Windows, Mac, and various mini-game platforms. A pure JavaScript-developed engine runtime is available on the web and mini-game platforms for better performance and smaller packages. On other native platforms, C++ is used to implement the underlying framework, providing greater operational efficiency. The latest repository is maintained in here [Engine of Cocos Creator][9].
+
+-------------
Cross Platform
-------------
* Popular browsers: Chrome 14+, Safari 5.0+, IE9+, Firefox 3.5+.
- * Mobile platforms: coming soon.
+ * Mobile platforms: Mobile browsers,Facebook Instant Games and Mini Games.
* Native App: Same piece of code can run on "Cocos2d JS-Binding Engine" without or with little modification.
Documentation
------------------
* Website: [www.cocos2d-x.org][3]
- * API References: [http://www.cocos2d-x.org/wiki/Reference] [4]
-
-Running the tests
-------------------
-
-```shell
-$ git clone git://github.com/cocos2d/cocos2d-html5.git
-$ cd cocos2d-html5
-$ git submodule update --init
-$ python -m SimpleHTTPServer
-```
-... and then open a browser and go to `http://localhost:8000/tests`
-
+ * Cocos Creator download: [Cocos Creator][10]
Contact us
------------------
@@ -41,3 +35,7 @@ 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"
+[9]: https://github.com/cocos-creator/engine
+[10]: http://cocos2d-x.org/download
+[11]: https://www.cocos.com/en/products#CocosCreator "https://www.cocos.com"
diff --git a/bower.json b/bower.json
new file mode 100644
index 0000000000..e97d56bb83
--- /dev/null
+++ b/bower.json
@@ -0,0 +1,36 @@
+{
+ "name": "cocos2d-html5",
+ "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 WebGL renderering.",
+ "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"
+ ]
+}
diff --git a/cocos2d/actions/CCAction.js b/cocos2d/actions/CCAction.js
index 3797077f71..e5487824aa 100644
--- a/cocos2d/actions/CCAction.js
+++ b/cocos2d/actions/CCAction.js
@@ -43,16 +43,16 @@ cc.ACTION_TAG_INVALID = -1;
*/
cc.Action = cc.Class.extend(/** @lends cc.Action# */{
//***********variables*************
- originalTarget:null,
- target:null,
- tag:cc.ACTION_TAG_INVALID,
+ originalTarget: null,
+ target: null,
+ tag: cc.ACTION_TAG_INVALID,
//**************Public Functions***********
/**
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
*/
- ctor:function () {
+ ctor: function () {
this.originalTarget = null;
this.target = null;
this.tag = cc.ACTION_TAG_INVALID;
@@ -65,7 +65,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{
*
* @return {cc.Action}
*/
- copy:function () {
+ copy: function () {
cc.log("copy is deprecated. Please use clone instead.");
return this.clone();
},
@@ -76,7 +76,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{
*
* @return {cc.Action}
*/
- clone:function () {
+ clone: function () {
var action = new cc.Action();
action.originalTarget = null;
action.target = null;
@@ -89,7 +89,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{
*
* @return {Boolean}
*/
- isDone:function () {
+ isDone: function () {
return true;
},
@@ -98,7 +98,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{
*
* @param {cc.Node} target
*/
- startWithTarget:function (target) {
+ startWithTarget: function (target) {
this.originalTarget = target;
this.target = target;
},
@@ -107,7 +107,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{
* called after the action has finished. It will set the 'target' to nil.
* IMPORTANT: You should never call "action stop" manually. Instead, use: "target.stopAction(action);"
*/
- stop:function () {
+ stop: function () {
this.target = null;
},
@@ -117,7 +117,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{
*
* @param {Number} dt
*/
- step:function (dt) {
+ step: function (dt) {
cc.log("[Action step]. override me");
},
@@ -126,7 +126,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{
*
* @param {Number} dt
*/
- update:function (dt) {
+ update: function (dt) {
cc.log("[Action update]. override me");
},
@@ -135,7 +135,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{
*
* @return {cc.Node}
*/
- getTarget:function () {
+ getTarget: function () {
return this.target;
},
@@ -144,7 +144,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{
*
* @param {cc.Node} target
*/
- setTarget:function (target) {
+ setTarget: function (target) {
this.target = target;
},
@@ -153,7 +153,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{
*
* @return {cc.Node}
*/
- getOriginalTarget:function () {
+ getOriginalTarget: function () {
return this.originalTarget;
},
@@ -164,7 +164,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{
* The target is 'assigned', it is not 'retained'.
* @param {cc.Node} originalTarget
*/
- setOriginalTarget:function (originalTarget) {
+ setOriginalTarget: function (originalTarget) {
this.originalTarget = originalTarget;
},
@@ -172,7 +172,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{
* get tag number.
* @return {Number}
*/
- getTag:function () {
+ getTag: function () {
return this.tag;
},
@@ -180,24 +180,24 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{
* set tag number.
* @param {Number} tag
*/
- setTag:function (tag) {
+ setTag: function (tag) {
this.tag = tag;
},
/**
- * Currently JavaScript Bindigns (JSB), in some cases, needs to use retain and release. This is a bug in JSB,
+ * Currently JavaScript Bindings (JSB), in some cases, needs to use retain and release. This is a bug in JSB,
* and the ugly workaround is to use retain/release. So, these 2 methods were added to be compatible with JSB.
* This is a hack, and should be removed once JSB fixes the retain/release bug.
*/
- retain:function () {
+ retain: function () {
},
/**
- * Currently JavaScript Bindigns (JSB), in some cases, needs to use retain and release. This is a bug in JSB,
+ * Currently JavaScript Bindings (JSB), in some cases, needs to use retain and release. This is a bug in JSB,
* and the ugly workaround is to use retain/release. So, these 2 methods were added to be compatible with JSB.
* This is a hack, and should be removed once JSB fixes the retain/release bug.
*/
- release:function () {
+ release: function () {
}
});
@@ -238,13 +238,13 @@ cc.Action.create = cc.action;
* @extends cc.Action
*/
cc.FiniteTimeAction = cc.Action.extend(/** @lends cc.FiniteTimeAction# */{
- //! duration in seconds
- _duration:0,
+ // duration in seconds
+ _duration: 0,
/**
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
*/
- ctor:function () {
+ ctor: function () {
cc.Action.prototype.ctor.call(this);
this._duration = 0;
},
@@ -254,8 +254,8 @@ cc.FiniteTimeAction = cc.Action.extend(/** @lends cc.FiniteTimeAction# */{
*
* @return {Number}
*/
- getDuration:function () {
- return this._duration * (this._times || 1);
+ getDuration: function () {
+ return this._duration * (this._timesForRepeat || 1);
},
/**
@@ -263,7 +263,7 @@ cc.FiniteTimeAction = cc.Action.extend(/** @lends cc.FiniteTimeAction# */{
*
* @param {Number} duration
*/
- setDuration:function (duration) {
+ setDuration: function (duration) {
this._duration = duration;
},
@@ -274,9 +274,9 @@ cc.FiniteTimeAction = cc.Action.extend(/** @lends cc.FiniteTimeAction# */{
* - The reversed action will be x of 100 move to 0.
* - Will be rewritten
*
- * @return {Null}
+ * @return {?cc.Action}
*/
- reverse:function () {
+ reverse: function () {
cc.log("cocos2d: FiniteTimeAction#reverse: Implement me");
return null;
},
@@ -287,7 +287,7 @@ cc.FiniteTimeAction = cc.Action.extend(/** @lends cc.FiniteTimeAction# */{
*
* @return {cc.FiniteTimeAction}
*/
- clone:function () {
+ clone: function () {
return new cc.FiniteTimeAction();
}
});
@@ -304,20 +304,20 @@ cc.FiniteTimeAction = cc.Action.extend(/** @lends cc.FiniteTimeAction# */{
* @param {Number} speed
*/
cc.Speed = cc.Action.extend(/** @lends cc.Speed# */{
- _speed:0.0,
- _innerAction:null,
+ _speed: 0.0,
+ _innerAction: null,
- /**
+ /**
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * @param {cc.ActionInterval} action
- * @param {Number} speed
- */
- ctor:function (action, speed) {
+ * @param {cc.ActionInterval} action
+ * @param {Number} speed
+ */
+ ctor: function (action, speed) {
cc.Action.prototype.ctor.call(this);
this._speed = 0;
this._innerAction = null;
- action && this.initWithAction(action, speed);
+ action && this.initWithAction(action, speed);
},
/**
@@ -326,7 +326,7 @@ cc.Speed = cc.Action.extend(/** @lends cc.Speed# */{
*
* @return {Number}
*/
- getSpeed:function () {
+ getSpeed: function () {
return this._speed;
},
@@ -335,7 +335,7 @@ cc.Speed = cc.Action.extend(/** @lends cc.Speed# */{
*
* @param {Number} speed
*/
- setSpeed:function (speed) {
+ setSpeed: function (speed) {
this._speed = speed;
},
@@ -346,9 +346,9 @@ cc.Speed = cc.Action.extend(/** @lends cc.Speed# */{
* @param {Number} speed
* @return {Boolean}
*/
- initWithAction:function (action, speed) {
- if(!action)
- throw "cc.Speed.initWithAction(): action must be non nil";
+ initWithAction: function (action, speed) {
+ if (!action)
+ throw new Error("cc.Speed.initWithAction(): action must be non nil");
this._innerAction = action;
this._speed = speed;
@@ -361,7 +361,7 @@ cc.Speed = cc.Action.extend(/** @lends cc.Speed# */{
*
* @returns {cc.Speed}
*/
- clone:function () {
+ clone: function () {
var action = new cc.Speed();
action.initWithAction(this._innerAction.clone(), this._speed);
return action;
@@ -372,7 +372,7 @@ cc.Speed = cc.Action.extend(/** @lends cc.Speed# */{
*
* @param {cc.Node} target
*/
- startWithTarget:function (target) {
+ startWithTarget: function (target) {
cc.Action.prototype.startWithTarget.call(this, target);
this._innerAction.startWithTarget(target);
},
@@ -380,7 +380,7 @@ cc.Speed = cc.Action.extend(/** @lends cc.Speed# */{
/**
* Stop the action.
*/
- stop:function () {
+ stop: function () {
this._innerAction.stop();
cc.Action.prototype.stop.call(this);
},
@@ -391,7 +391,7 @@ cc.Speed = cc.Action.extend(/** @lends cc.Speed# */{
*
* @param {Number} dt
*/
- step:function (dt) {
+ step: function (dt) {
this._innerAction.step(dt * this._speed);
},
@@ -400,7 +400,7 @@ cc.Speed = cc.Action.extend(/** @lends cc.Speed# */{
*
* @return {Boolean}
*/
- isDone:function () {
+ isDone: function () {
return this._innerAction.isDone();
},
@@ -413,7 +413,7 @@ cc.Speed = cc.Action.extend(/** @lends cc.Speed# */{
*
* @return {cc.Speed}
*/
- reverse:function () {
+ reverse: function () {
return new cc.Speed(this._innerAction.reverse(), this._speed);
},
@@ -421,8 +421,8 @@ cc.Speed = cc.Action.extend(/** @lends cc.Speed# */{
* Set inner Action.
* @param {cc.ActionInterval} action
*/
- setInnerAction:function (action) {
- if (this._innerAction != action) {
+ setInnerAction: function (action) {
+ if (this._innerAction !== action) {
this._innerAction = action;
}
},
@@ -432,7 +432,7 @@ cc.Speed = cc.Action.extend(/** @lends cc.Speed# */{
*
* @return {cc.ActionInterval}
*/
- getInnerAction:function () {
+ getInnerAction: function () {
return this._innerAction;
}
});
@@ -492,29 +492,29 @@ cc.Speed.create = cc.speed;
*/
cc.Follow = cc.Action.extend(/** @lends cc.Follow# */{
// node to follow
- _followedNode:null,
+ _followedNode: null,
// whether camera should be limited to certain area
- _boundarySet:false,
+ _boundarySet: false,
// if screen size is bigger than the boundary - update not needed
- _boundaryFullyCovered:false,
+ _boundaryFullyCovered: false,
// fast access to the screen dimensions
- _halfScreenSize:null,
- _fullScreenSize:null,
- _worldRect:null,
+ _halfScreenSize: null,
+ _fullScreenSize: null,
+ _worldRect: null,
- leftBoundary:0.0,
- rightBoundary:0.0,
- topBoundary:0.0,
- bottomBoundary:0.0,
+ leftBoundary: 0.0,
+ rightBoundary: 0.0,
+ topBoundary: 0.0,
+ bottomBoundary: 0.0,
- /**
+ /**
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * creates the action with a set boundary.
- * creates the action with no boundary set.
+ * creates the action with a set boundary.
+ * creates the action with no boundary set.
* @param {cc.Node} followedNode
* @param {cc.Rect} rect
- */
- ctor:function (followedNode, rect) {
+ */
+ ctor: function (followedNode, rect) {
cc.Action.prototype.ctor.call(this);
this._followedNode = null;
this._boundarySet = false;
@@ -529,9 +529,9 @@ cc.Follow = cc.Action.extend(/** @lends cc.Follow# */{
this.bottomBoundary = 0.0;
this._worldRect = cc.rect(0, 0, 0, 0);
- if(followedNode)
- rect ? this.initWithTarget(followedNode, rect)
- : this.initWithTarget(followedNode);
+ if (followedNode)
+ rect ? this.initWithTarget(followedNode, rect)
+ : this.initWithTarget(followedNode);
},
/**
@@ -540,7 +540,7 @@ cc.Follow = cc.Action.extend(/** @lends cc.Follow# */{
*
* @return {cc.Follow}
*/
- clone:function () {
+ clone: function () {
var action = new cc.Follow();
var locRect = this._worldRect;
var rect = new cc.Rect(locRect.x, locRect.y, locRect.width, locRect.height);
@@ -553,7 +553,7 @@ cc.Follow = cc.Action.extend(/** @lends cc.Follow# */{
*
* @return {Boolean}
*/
- isBoundarySet:function () {
+ isBoundarySet: function () {
return this._boundarySet;
},
@@ -562,7 +562,7 @@ cc.Follow = cc.Action.extend(/** @lends cc.Follow# */{
*
* @param {Boolean} value
*/
- setBoudarySet:function (value) {
+ setBoudarySet: function (value) {
this._boundarySet = value;
},
@@ -573,9 +573,9 @@ cc.Follow = cc.Action.extend(/** @lends cc.Follow# */{
* @param {cc.Rect} [rect=]
* @return {Boolean}
*/
- initWithTarget:function (followedNode, rect) {
- if(!followedNode)
- throw "cc.Follow.initWithAction(): followedNode must be non nil";
+ initWithTarget: function (followedNode, rect) {
+ if (!followedNode)
+ throw new Error("cc.Follow.initWithAction(): followedNode must be non nil");
var _this = this;
rect = rect || cc.rect(0, 0, 0, 0);
@@ -607,7 +607,7 @@ cc.Follow = cc.Action.extend(/** @lends cc.Follow# */{
_this.topBoundary = _this.bottomBoundary = (_this.topBoundary + _this.bottomBoundary) / 2;
}
- if ((_this.topBoundary == _this.bottomBoundary) && (_this.leftBoundary == _this.rightBoundary))
+ if ((_this.topBoundary === _this.bottomBoundary) && (_this.leftBoundary === _this.rightBoundary))
_this._boundaryFullyCovered = true;
}
return true;
@@ -619,7 +619,7 @@ cc.Follow = cc.Action.extend(/** @lends cc.Follow# */{
*
* @param {Number} dt
*/
- step:function (dt) {
+ step: function (dt) {
var tempPosX = this._followedNode.x;
var tempPosY = this._followedNode.y;
tempPosX = this._halfScreenSize.x - tempPosX;
@@ -633,7 +633,7 @@ cc.Follow = cc.Action.extend(/** @lends cc.Follow# */{
if (this._boundaryFullyCovered)
return;
- this.target.setPosition(cc.clampf(tempPosX, this.leftBoundary, this.rightBoundary), cc.clampf(tempPosY, this.bottomBoundary, this.topBoundary));
+ this.target.setPosition(cc.clampf(tempPosX, this.leftBoundary, this.rightBoundary), cc.clampf(tempPosY, this.bottomBoundary, this.topBoundary));
} else {
this.target.setPosition(tempPosX, tempPosY);
}
@@ -644,14 +644,14 @@ cc.Follow = cc.Action.extend(/** @lends cc.Follow# */{
*
* @return {Boolean}
*/
- isDone:function () {
+ isDone: function () {
return ( !this._followedNode.running );
},
/**
* Stop the action.
*/
- stop:function () {
+ stop: function () {
this.target = null;
cc.Action.prototype.stop.call(this);
}
diff --git a/cocos2d/actions/CCActionCamera.js b/cocos2d/actions/CCActionCamera.js
deleted file mode 100644
index 0ff5786b71..0000000000
--- a/cocos2d/actions/CCActionCamera.js
+++ /dev/null
@@ -1,293 +0,0 @@
-/****************************************************************************
- Copyright (c) 2008-2010 Ricardo Quesada
- Copyright (c) 2011-2012 cocos2d-x.org
- Copyright (c) 2013-2014 Chukong Technologies Inc.
-
- http://www.cocos2d-x.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be included in
- all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
-
-/**
- * Base class for cc.Camera actions
- * @class
- * @extends cc.ActionInterval
- */
-cc.ActionCamera = cc.ActionInterval.extend(/** @lends cc.ActionCamera# */{
- _centerXOrig:0,
- _centerYOrig:0,
- _centerZOrig:0,
- _eyeXOrig:0,
- _eyeYOrig:0,
- _eyeZOrig:0,
- _upXOrig:0,
- _upYOrig:0,
- _upZOrig:0,
-
- /**
- * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- */
- ctor:function(){
- var _t = this;
- cc.ActionInterval.prototype.ctor.call(_t);
-
- _t._centerXOrig=0;
- _t._centerYOrig=0;
- _t._centerZOrig=0;
- _t._eyeXOrig=0;
- _t._eyeYOrig=0;
- _t._eyeZOrig=0;
- _t._upXOrig=0;
- _t._upYOrig=0;
- _t._upZOrig=0;
- },
-
- /**
- * called before the action start. It will also set the target.
- *
- * @param {cc.Node} target
- */
- startWithTarget:function (target) {
- var _t = this;
- cc.ActionInterval.prototype.startWithTarget.call(_t, target);
-
- var camera = target.getCamera();
- var centerXYZ = camera.getCenter();
- _t._centerXOrig = centerXYZ.x;
- _t._centerYOrig = centerXYZ.y;
- _t._centerZOrig = centerXYZ.z;
-
- var eyeXYZ = camera.getEye();
- _t._eyeXOrig = eyeXYZ.x;
- _t._eyeYOrig = eyeXYZ.y;
- _t._eyeZOrig = eyeXYZ.z;
-
- var upXYZ = camera.getUp();
- _t._upXOrig = upXYZ.x;
- _t._upYOrig = upXYZ.y;
- _t._upZOrig = upXYZ.z;
- },
-
- /**
- * to copy object with deep copy.
- * returns a new clone of the action
- *
- * @returns {cc.ActionCamera}
- */
- clone:function(){
- return new cc.ActionCamera();
- },
-
- /**
- * returns a reversed action.
- * For example:
- * - The action will be x coordinates of 0 move to 100.
- * - The reversed action will be x of 100 move to 0.
- * - Will be rewritten
- *
- */
- reverse:function () {
- return new cc.ReverseTime(this);
- }
-});
-
-/**
- * Orbits the camera around the center of the screen using spherical coordinates.
- *
- * @param {Number} t time
- * @param {Number} radius
- * @param {Number} deltaRadius
- * @param {Number} angleZ
- * @param {Number} deltaAngleZ
- * @param {Number} angleX
- * @param {Number} deltaAngleX
- *
- * @class
- * @extends cc.ActionCamera
- */
-cc.OrbitCamera = cc.ActionCamera.extend(/** @lends cc.OrbitCamera# */{
- _radius: 0.0,
- _deltaRadius: 0.0,
- _angleZ: 0.0,
- _deltaAngleZ: 0.0,
- _angleX: 0.0,
- _deltaAngleX: 0.0,
- _radZ: 0.0,
- _radDeltaZ: 0.0,
- _radX: 0.0,
- _radDeltaX: 0.0,
-
- /**
- * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * creates a cc.OrbitCamera action with radius, delta-radius, z, deltaZ, x, deltaX.
- * @param {Number} t time
- * @param {Number} radius
- * @param {Number} deltaRadius
- * @param {Number} angleZ
- * @param {Number} deltaAngleZ
- * @param {Number} angleX
- * @param {Number} deltaAngleX
- */
- ctor:function(t, radius, deltaRadius, angleZ, deltaAngleZ, angleX, deltaAngleX){
- cc.ActionCamera.prototype.ctor.call(this);
-
- deltaAngleX !== undefined && this.initWithDuration(t, radius, deltaRadius, angleZ, deltaAngleZ, angleX, deltaAngleX);
- },
-
- /**
- * initializes a cc.OrbitCamera action with radius, delta-radius, z, deltaZ, x, deltaX
- * @param {Number} t time
- * @param {Number} radius
- * @param {Number} deltaRadius
- * @param {Number} angleZ
- * @param {Number} deltaAngleZ
- * @param {Number} angleX
- * @param {Number} deltaAngleX
- * @return {Boolean}
- */
- initWithDuration:function (t, radius, deltaRadius, angleZ, deltaAngleZ, angleX, deltaAngleX) {
- if (cc.ActionInterval.prototype.initWithDuration.call(this, t)) {
- var _t = this;
- _t._radius = radius;
- _t._deltaRadius = deltaRadius;
- _t._angleZ = angleZ;
- _t._deltaAngleZ = deltaAngleZ;
- _t._angleX = angleX;
- _t._deltaAngleX = deltaAngleX;
-
- _t._radDeltaZ = cc.degreesToRadians(deltaAngleZ);
- _t._radDeltaX = cc.degreesToRadians(deltaAngleX);
- return true;
- }
- return false;
- },
-
- /**
- * positions the camera according to spherical coordinates
- * @return {Object}
- */
- sphericalRadius:function () {
- var newRadius, zenith, azimuth;
- var camera = this.target.getCamera();
- var eyeXYZ = camera.getEye();
- var centerXYZ = camera.getCenter();
-
- var x = eyeXYZ.x - centerXYZ.x, y = eyeXYZ.y - centerXYZ.y, z = eyeXYZ.z - centerXYZ.z;
-
- var r = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2));
- var s = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
- if (s === 0.0)
- s = cc.FLT_EPSILON;
- if (r === 0.0)
- r = cc.FLT_EPSILON;
-
- zenith = Math.acos(z / r);
- if (x < 0)
- azimuth = Math.PI - Math.asin(y / s);
- else
- azimuth = Math.asin(y / s);
- newRadius = r / cc.Camera.getZEye();
- return {newRadius:newRadius, zenith:zenith, azimuth:azimuth};
- },
-
- /**
- * called before the action start. It will also set the target.
- *
- * @param {cc.Node} target
- */
- startWithTarget:function (target) {
- var _t = this;
- cc.ActionInterval.prototype.startWithTarget.call(_t, target);
- var retValue = _t.sphericalRadius();
- if (isNaN(_t._radius))
- _t._radius = retValue.newRadius;
-
- if (isNaN(_t._angleZ))
- _t._angleZ = cc.radiansToDegrees(retValue.zenith);
-
- if (isNaN(_t._angleX))
- _t._angleX = cc.radiansToDegrees(retValue.azimuth);
-
- _t._radZ = cc.degreesToRadians(_t._angleZ);
- _t._radX = cc.degreesToRadians(_t._angleX);
- },
-
- /**
- * to copy object with deep copy.
- * returns a new clone of the action
- *
- * @returns {cc.ActionCamera}
- */
- clone:function(){
- var a = new cc.OrbitCamera(), _t = this;
- a.initWithDuration(_t._duration, _t._radius, _t._deltaRadius, _t._angleZ, _t._deltaAngleZ, _t._angleX, _t._deltaAngleX);
- return a;
- },
-
- /**
- * Called once per frame. Time is the number of seconds of a frame interval.
- *
- * @param {Number} dt
- */
- update:function (dt) {
- dt = this._computeEaseTime(dt);
- var r = (this._radius + this._deltaRadius * dt) * cc.Camera.getZEye();
- var za = this._radZ + this._radDeltaZ * dt;
- var xa = this._radX + this._radDeltaX * dt;
-
- var i = Math.sin(za) * Math.cos(xa) * r + this._centerXOrig;
- var j = Math.sin(za) * Math.sin(xa) * r + this._centerYOrig;
- var k = Math.cos(za) * r + this._centerZOrig;
-
- this.target.getCamera().setEye(i, j, k);
- this.target.setNodeDirty();
- }
-});
-
-/**
- * creates a cc.OrbitCamera action with radius, delta-radius, z, deltaZ, x, deltaX
- * @function
- * @param {Number} t time
- * @param {Number} radius
- * @param {Number} deltaRadius
- * @param {Number} angleZ
- * @param {Number} deltaAngleZ
- * @param {Number} angleX
- * @param {Number} deltaAngleX
- * @return {cc.OrbitCamera}
- */
-cc.orbitCamera = function (t, radius, deltaRadius, angleZ, deltaAngleZ, angleX, deltaAngleX) {
- return new cc.OrbitCamera(t, radius, deltaRadius, angleZ, deltaAngleZ, angleX, deltaAngleX);
-};
-
-/**
- * Please use cc.orbitCamera instead
- * creates a cc.OrbitCamera action with radius, delta-radius, z, deltaZ, x, deltaX
- * @param {Number} t time
- * @param {Number} radius
- * @param {Number} deltaRadius
- * @param {Number} angleZ
- * @param {Number} deltaAngleZ
- * @param {Number} angleX
- * @param {Number} deltaAngleX
- * @return {cc.OrbitCamera}
- * @static
- * @deprecated since v3.0 please use cc.orbitCamera() instead.
- */
-cc.OrbitCamera.create = cc.orbitCamera;
diff --git a/cocos2d/actions/CCActionCatmullRom.js b/cocos2d/actions/CCActionCatmullRom.js
index 285f2b6f6b..a17dca4ccc 100644
--- a/cocos2d/actions/CCActionCatmullRom.js
+++ b/cocos2d/actions/CCActionCatmullRom.js
@@ -44,9 +44,10 @@
* @param {cc.Point} p3
* @param {Number} tension
* @param {Number} t
+ * @param {cc.Point} [out]
* @return {cc.Point}
*/
-cc.cardinalSplineAt = function (p0, p1, p2, p3, tension, t) {
+cc.cardinalSplineAt = function (p0, p1, p2, p3, tension, t, out) {
var t2 = t * t;
var t3 = t2 * t;
@@ -62,7 +63,13 @@ cc.cardinalSplineAt = function (p0, p1, p2, p3, tension, t) {
var x = (p0.x * b1 + p1.x * b2 + p2.x * b3 + p3.x * b4);
var y = (p0.y * b1 + p1.y * b2 + p2.y * b3 + p3.y * b4);
- return cc.p(x, y);
+ if (out !== undefined) {
+ out.x = x;
+ out.y = y;
+ }
+ else {
+ return cc.p(x, y);
+ }
};
/**
@@ -174,8 +181,8 @@ cc.CardinalSplineTo = cc.ActionInterval.extend(/** @lends cc.CardinalSplineTo# *
* @return {Boolean}
*/
initWithDuration:function (duration, points, tension) {
- if(!points || points.length == 0)
- throw "Invalid configuration. It must at least have one control point";
+ if(!points || points.length === 0)
+ throw new Error("Invalid configuration. It must at least have one control point");
if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
this.setPoints(points);
@@ -222,7 +229,7 @@ cc.CardinalSplineTo = cc.ActionInterval.extend(/** @lends cc.CardinalSplineTo# *
// p..p..p..p..p..p..p
// 1..2..3..4..5..6..7
// want p to be 1, 2, 3, 4, 5, 6
- if (dt == 1) {
+ if (dt === 1) {
p = ps.length - 1;
lt = 1;
} else {
@@ -242,7 +249,7 @@ cc.CardinalSplineTo = cc.ActionInterval.extend(/** @lends cc.CardinalSplineTo# *
var tempX, tempY;
tempX = this.target.getPositionX() - this._previousPosition.x;
tempY = this.target.getPositionY() - this._previousPosition.y;
- if (tempX != 0 || tempY != 0) {
+ if (tempX !== 0 || tempY !== 0) {
var locAccDiff = this._accumulatedDiff;
tempX = locAccDiff.x + tempX;
tempY = locAccDiff.y + tempY;
diff --git a/cocos2d/actions/CCActionEase.js b/cocos2d/actions/CCActionEase.js
index b117f91d2b..f6ddef0ce0 100644
--- a/cocos2d/actions/CCActionEase.js
+++ b/cocos2d/actions/CCActionEase.js
@@ -56,7 +56,7 @@ cc.ActionEase = cc.ActionInterval.extend(/** @lends cc.ActionEase# */{
*/
initWithAction:function (action) {
if(!action)
- throw "cc.ActionEase.initWithAction(): action must be non nil";
+ throw new Error("cc.ActionEase.initWithAction(): action must be non nil");
if (this.initWithDuration(action.getDuration())) {
this._inner = action;
@@ -651,7 +651,7 @@ cc.EaseExponentialOut = cc.ActionEase.extend(/** @lends cc.EaseExponentialOut# *
* @param {Number} dt
*/
update:function (dt) {
- this._inner.update(dt == 1 ? 1 : (-(Math.pow(2, -10 * dt)) + 1));
+ this._inner.update(dt === 1 ? 1 : (-(Math.pow(2, -10 * dt)) + 1));
},
/**
@@ -696,7 +696,7 @@ cc.EaseExponentialOut.create = function (action) {
cc._easeExponentialOutObj = {
easing: function(dt){
- return dt == 1 ? 1 : (-(Math.pow(2, -10 * dt)) + 1);
+ return dt === 1 ? 1 : (-(Math.pow(2, -10 * dt)) + 1);
},
reverse: function(){
return cc._easeExponentialInObj;
@@ -740,7 +740,7 @@ cc.EaseExponentialInOut = cc.ActionEase.extend(/** @lends cc.EaseExponentialInOu
* @param {Number} dt
*/
update:function (dt) {
- if( dt != 1 && dt !== 0) {
+ if( dt !== 1 && dt !== 0) {
dt *= 2;
if (dt < 1)
dt = 0.5 * Math.pow(2, 10 * (dt - 1));
@@ -976,7 +976,7 @@ cc.EaseSineOut.create = function (action) {
cc._easeSineOutObj = {
easing: function(dt){
- return (dt===0 || dt==1) ? dt : Math.sin(dt * Math.PI / 2);
+ return (dt===0 || dt===1) ? dt : Math.sin(dt * Math.PI / 2);
},
reverse: function(){
return cc._easeSineInObj;
@@ -1140,7 +1140,7 @@ cc.EaseElastic = cc.ActionEase.extend(/** @lends cc.EaseElastic# */{
/**
* Create a action. Opposite with the original motion trajectory.
* Will be overwrite.
- * @return {null}
+ * @return {?cc.Action}
*/
reverse:function () {
cc.log("cc.EaseElastic.reverse(): it should be overridden in subclass.");
@@ -1313,7 +1313,7 @@ cc.EaseElasticOut = cc.EaseElastic.extend(/** @lends cc.EaseElasticOut# */{
*/
update:function (dt) {
var newT = 0;
- if (dt === 0 || dt == 1) {
+ if (dt === 0 || dt === 1) {
newT = dt;
} else {
var s = this._period / 4;
@@ -1423,7 +1423,7 @@ cc.EaseElasticInOut = cc.EaseElastic.extend(/** @lends cc.EaseElasticInOut# */{
update:function (dt) {
var newT = 0;
var locPeriod = this._period;
- if (dt === 0 || dt == 1) {
+ if (dt === 0 || dt === 1) {
newT = dt;
} else {
dt = dt * 2;
@@ -1770,7 +1770,7 @@ cc.easeBounceOut = function(){
/**
* cc.EaseBounceInOut action.
- * Eased bounce effect at the begining and ending.
+ * Eased bounce effect at the beginning and ending.
* @warning This action doesn't use a bijective function. Actions like Sequence might have an unexpected result when used with this action.
* @class
* @extends cc.EaseBounce
@@ -1823,7 +1823,7 @@ cc.EaseBounceInOut = cc.EaseBounce.extend(/** @lends cc.EaseBounceInOut# */{
/**
* Creates the action.
- * Eased bounce effect at the begining and ending.
+ * Eased bounce effect at the beginning and ending.
* @static
* @deprecated since v3.0 Please use action.easing(cc.easeBounceInOut())
* @param {cc.ActionInterval} action
@@ -1857,7 +1857,7 @@ cc._easeBounceInOutObj = {
/**
* Creates the action easing object.
- * Eased bounce effect at the begining and ending.
+ * Eased bounce effect at the beginning and ending.
* @function
* @return {Object}
* @example
@@ -1891,7 +1891,7 @@ cc.EaseBackIn = cc.ActionEase.extend(/** @lends cc.EaseBackIn# */{
*/
update:function (dt) {
var overshoot = 1.70158;
- dt = dt===0 || dt==1 ? dt : dt * dt * ((overshoot + 1) * dt - overshoot);
+ dt = dt===0 || dt===1 ? dt : dt * dt * ((overshoot + 1) * dt - overshoot);
this._inner.update(dt);
},
@@ -2050,7 +2050,7 @@ cc.easeBackOut = function(){
/**
* cc.EaseBackInOut action.
- * Begining of cc.EaseBackIn. Ending of cc.EaseBackOut.
+ * Beginning of cc.EaseBackIn. Ending of cc.EaseBackOut.
* @warning This action doesn't use a bijective function. Actions like Sequence might have an unexpected result when used with this action.
* @class
* @extends cc.ActionEase
@@ -2104,7 +2104,7 @@ cc.EaseBackInOut = cc.ActionEase.extend(/** @lends cc.EaseBackInOut# */{
/**
* Creates the action.
- * Begining of cc.EaseBackIn. Ending of cc.EaseBackOut.
+ * Beginning of cc.EaseBackIn. Ending of cc.EaseBackOut.
* @static
* @param {cc.ActionInterval} action
* @return {cc.EaseBackInOut}
@@ -2139,7 +2139,7 @@ cc._easeBackInOutObj = {
/**
* Creates the action easing object.
- * Begining of cc.EaseBackIn. Ending of cc.EaseBackOut.
+ * Beginning of cc.EaseBackIn. Ending of cc.EaseBackOut.
* @function
* @return {Object}
* @example
@@ -3678,4 +3678,3 @@ cc._easeCubicActionInOut = {
cc.easeCubicActionInOut = function(){
return cc._easeCubicActionInOut;
};
-
diff --git a/cocos2d/actions/CCActionInstant.js b/cocos2d/actions/CCActionInstant.js
index 84e2252fb5..f1e73f91ac 100644
--- a/cocos2d/actions/CCActionInstant.js
+++ b/cocos2d/actions/CCActionInstant.js
@@ -630,11 +630,10 @@ cc.Place.create = cc.place;
*/
cc.CallFunc = cc.ActionInstant.extend(/** @lends cc.CallFunc# */{
_selectorTarget:null,
- _callFunc:null,
_function:null,
_data:null,
- /**
+ /**
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
* Creates a CallFunc action with the callback.
* @param {function} selector
@@ -644,11 +643,7 @@ cc.CallFunc = cc.ActionInstant.extend(/** @lends cc.CallFunc# */{
ctor:function(selector, selectorTarget, data){
cc.FiniteTimeAction.prototype.ctor.call(this);
- if(selector !== undefined){
- if(selectorTarget === undefined)
- this.initWithFunction(selector);
- else this.initWithFunction(selector, selectorTarget, data);
- }
+ this.initWithFunction(selector, selectorTarget, data);
},
/**
@@ -659,13 +654,15 @@ cc.CallFunc = cc.ActionInstant.extend(/** @lends cc.CallFunc# */{
* @return {Boolean}
*/
initWithFunction:function (selector, selectorTarget, data) {
- if (selectorTarget) {
- this._data = data;
- this._callFunc = selector;
+ if (selector) {
+ this._function = selector;
+ }
+ if (selectorTarget) {
this._selectorTarget = selectorTarget;
- }
- else if (selector)
- this._function = selector;
+ }
+ if (data !== undefined) {
+ this._data = data;
+ }
return true;
},
@@ -673,10 +670,9 @@ cc.CallFunc = cc.ActionInstant.extend(/** @lends cc.CallFunc# */{
* execute the function.
*/
execute:function () {
- if (this._callFunc != null) //CallFunc, N, ND
- this._callFunc.call(this._selectorTarget, this.target, this._data);
- else if(this._function)
- this._function.call(null, this.target);
+ if (this._function) {
+ this._function.call(this._selectorTarget, this.target, this._data);
+ }
},
/**
@@ -701,7 +697,7 @@ cc.CallFunc = cc.ActionInstant.extend(/** @lends cc.CallFunc# */{
* @param {object} sel
*/
setTargetCallback:function (sel) {
- if (sel != this._selectorTarget) {
+ if (sel !== this._selectorTarget) {
if (this._selectorTarget)
this._selectorTarget = null;
this._selectorTarget = sel;
@@ -715,12 +711,8 @@ cc.CallFunc = cc.ActionInstant.extend(/** @lends cc.CallFunc# */{
* @return {cc.CallFunc}
*/
clone:function(){
- var action = new cc.CallFunc();
- if(this._selectorTarget){
- action.initWithFunction(this._callFunc, this._selectorTarget, this._data)
- }else if(this._function){
- action.initWithFunction(this._function);
- }
+ var action = new cc.CallFunc();
+ action.initWithFunction(this._function, this._selectorTarget, this._data);
return action;
}
});
diff --git a/cocos2d/actions/CCActionInterval.js b/cocos2d/actions/CCActionInterval.js
index c7e8ed2a19..905d72b0a2 100644
--- a/cocos2d/actions/CCActionInterval.js
+++ b/cocos2d/actions/CCActionInterval.js
@@ -44,35 +44,35 @@
* var actionInterval = new cc.ActionInterval(3);
*/
cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{
- _elapsed:0,
- _firstTick:false,
+ _elapsed: 0,
+ _firstTick: false,
_easeList: null,
- _times:1,
+ _timesForRepeat: 1,
_repeatForever: false,
_repeatMethod: false,//Compatible with repeat class, Discard after can be deleted
_speed: 1,
_speedMethod: false,//Compatible with speed class, Discard after can be deleted
- /**
+ /**
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * @param {Number} d duration in seconds
- */
- ctor:function (d) {
+ * @param {Number} d duration in seconds
+ */
+ ctor: function (d) {
this._speed = 1;
- this._times = 1;
+ this._timesForRepeat = 1;
this._repeatForever = false;
this.MAX_VALUE = 2;
this._repeatMethod = false;//Compatible with repeat class, Discard after can be deleted
this._speedMethod = false;//Compatible with repeat class, Discard after can be deleted
cc.FiniteTimeAction.prototype.ctor.call(this);
- d !== undefined && this.initWithDuration(d);
+ d !== undefined && this.initWithDuration(d);
},
/**
* How many seconds had elapsed since the actions started to run.
* @return {Number}
*/
- getElapsed:function () {
+ getElapsed: function () {
return this._elapsed;
},
@@ -81,7 +81,7 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{
* @param {Number} d duration in seconds
* @return {Boolean}
*/
- initWithDuration:function (d) {
+ initWithDuration: function (d) {
this._duration = (d === 0) ? cc.FLT_EPSILON : d;
// prevent division by 0
// This comparison could be in step:, but it might decrease the performance
@@ -95,7 +95,7 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{
* Returns true if the action has finished.
* @return {Boolean}
*/
- isDone:function () {
+ isDone: function () {
return (this._elapsed >= this._duration);
},
@@ -104,19 +104,19 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{
* @param {cc.Action} action
* @private
*/
- _cloneDecoration: function(action){
+ _cloneDecoration: function (action) {
action._repeatForever = this._repeatForever;
action._speed = this._speed;
- action._times = this._times;
+ action._timesForRepeat = this._timesForRepeat;
action._easeList = this._easeList;
action._speedMethod = this._speedMethod;
action._repeatMethod = this._repeatMethod;
},
- _reverseEaseList: function(action){
- if(this._easeList){
+ _reverseEaseList: function (action) {
+ if (this._easeList) {
action._easeList = [];
- for(var i=0; i 0 ? t : 0);
//Compatible with repeat class, Discard after can be deleted (this._repeatMethod)
- if(this._repeatMethod && this._times > 1 && this.isDone()){
- if(!this._repeatForever){
- this._times--;
+ if (this._repeatMethod && this._timesForRepeat > 1 && this.isDone()) {
+ if (!this._repeatForever) {
+ this._timesForRepeat--;
}
//var diff = locInnerAction.getElapsed() - locInnerAction._duration;
this.startWithTarget(this.target);
@@ -198,7 +198,7 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{
* Start this action with target.
* @param {cc.Node} target
*/
- startWithTarget:function (target) {
+ startWithTarget: function (target) {
cc.Action.prototype.startWithTarget.call(this, target);
this._elapsed = 0;
this._firstTick = true;
@@ -208,9 +208,9 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{
* returns a reversed action.
* Will be overwrite.
*
- * @return {null}
+ * @return {?cc.Action}
*/
- reverse:function () {
+ reverse: function () {
cc.log("cc.IntervalAction: reverse not implemented.");
return null;
},
@@ -220,7 +220,7 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{
* @warning It should be overridden in subclass.
* @param {Number} amp
*/
- setAmplitudeRate:function (amp) {
+ setAmplitudeRate: function (amp) {
// Abstract class needs implementation
cc.log("cc.ActionInterval.setAmplitudeRate(): it should be overridden in subclass.");
},
@@ -230,7 +230,7 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{
* @warning It should be overridden in subclass.
* @return {Number} 0
*/
- getAmplitudeRate:function () {
+ getAmplitudeRate: function () {
// Abstract class needs implementation
cc.log("cc.ActionInterval.getAmplitudeRate(): it should be overridden in subclass.");
return 0;
@@ -244,8 +244,8 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{
* @param speed
* @returns {cc.Action}
*/
- speed: function(speed){
- if(speed <= 0){
+ speed: function (speed) {
+ if (speed <= 0) {
cc.log("The speed parameter error");
return this;
}
@@ -259,7 +259,7 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{
* Get this action speed.
* @return {Number}
*/
- getSpeed: function(){
+ getSpeed: function () {
return this._speed;
},
@@ -268,7 +268,7 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{
* @param {Number} speed
* @returns {cc.ActionInterval}
*/
- setSpeed: function(speed){
+ setSpeed: function (speed) {
this._speed = speed;
return this;
},
@@ -279,14 +279,14 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{
* @param times
* @returns {cc.ActionInterval}
*/
- repeat: function(times){
+ repeat: function (times) {
times = Math.round(times);
- if(isNaN(times) || times < 1){
+ if (isNaN(times) || times < 1) {
cc.log("The repeat parameter error");
return this;
}
this._repeatMethod = true;//Compatible with repeat class, Discard after can be deleted
- this._times *= times;
+ this._timesForRepeat *= times;
return this;
},
@@ -295,9 +295,9 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{
* To repeat the an action for a limited number of times use the Repeat action.
* @returns {cc.ActionInterval}
*/
- repeatForever: function(){
+ repeatForever: function () {
this._repeatMethod = true;//Compatible with repeat class, Discard after can be deleted
- this._times = this.MAX_VALUE;
+ this._timesForRepeat = this.MAX_VALUE;
this._repeatForever = true;
return this;
}
@@ -339,23 +339,23 @@ cc.ActionInterval.create = cc.actionInterval;
* var seq = new cc.Sequence(actArray);
*/
cc.Sequence = cc.ActionInterval.extend(/** @lends cc.Sequence# */{
- _actions:null,
- _split:null,
- _last:0,
+ _actions: null,
+ _split: null,
+ _last: 0,
- /**
+ /**
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
* Create an array of sequenceable actions.
- * @param {Array|cc.FiniteTimeAction} tempArray
- */
- ctor:function (tempArray) {
+ * @param {Array|cc.FiniteTimeAction} tempArray
+ */
+ ctor: function (tempArray) {
cc.ActionInterval.prototype.ctor.call(this);
this._actions = [];
- var paramArray = (tempArray instanceof Array) ? tempArray : arguments;
- var last = paramArray.length - 1;
- if ((last >= 0) && (paramArray[last] == null))
- cc.log("parameters should not be ending with null in Javascript");
+ var paramArray = (tempArray instanceof Array) ? tempArray : arguments;
+ var last = paramArray.length - 1;
+ if ((last >= 0) && (paramArray[last] == null))
+ cc.log("parameters should not be ending with null in Javascript");
if (last >= 0) {
var prev = paramArray[0], action1;
@@ -375,9 +375,9 @@ cc.Sequence = cc.ActionInterval.extend(/** @lends cc.Sequence# */{
* @param {cc.FiniteTimeAction} actionTwo
* @return {Boolean}
*/
- initWithTwoActions:function (actionOne, actionTwo) {
- if(!actionOne || !actionTwo)
- throw "cc.Sequence.initWithTwoActions(): arguments must all be non nil";
+ initWithTwoActions: function (actionOne, actionTwo) {
+ if (!actionOne || !actionTwo)
+ throw new Error("cc.Sequence.initWithTwoActions(): arguments must all be non nil");
var d = actionOne._duration + actionTwo._duration;
this.initWithDuration(d);
@@ -391,7 +391,7 @@ cc.Sequence = cc.ActionInterval.extend(/** @lends cc.Sequence# */{
* returns a new clone of the action
* @returns {cc.Sequence}
*/
- clone:function () {
+ clone: function () {
var action = new cc.Sequence();
this._cloneDecoration(action);
action.initWithTwoActions(this._actions[0].clone(), this._actions[1].clone());
@@ -402,7 +402,7 @@ cc.Sequence = cc.ActionInterval.extend(/** @lends cc.Sequence# */{
* Start the action with target.
* @param {cc.Node} target
*/
- startWithTarget:function (target) {
+ startWithTarget: function (target) {
cc.ActionInterval.prototype.startWithTarget.call(this, target);
this._split = this._actions[0]._duration / this._duration;
this._last = -1;
@@ -411,7 +411,7 @@ cc.Sequence = cc.ActionInterval.extend(/** @lends cc.Sequence# */{
/**
* stop the action.
*/
- stop:function () {
+ stop: function () {
// Issue #1305
if (this._last !== -1)
this._actions[this._last].stop();
@@ -422,7 +422,7 @@ cc.Sequence = cc.ActionInterval.extend(/** @lends cc.Sequence# */{
* Called once per frame. Time is the number of seconds of a frame interval.
* @param {Number} dt
*/
- update:function (dt) {
+ update: function (dt) {
var new_t, found = 0;
var locSplit = this._split, locActions = this._actions, locLast = this._last, actionFound;
@@ -466,7 +466,7 @@ cc.Sequence = cc.ActionInterval.extend(/** @lends cc.Sequence# */{
if (locLast !== found)
actionFound.startWithTarget(this.target);
- new_t = new_t * actionFound._times;
+ new_t = new_t * actionFound._timesForRepeat;
actionFound.update(new_t > 1 ? new_t % 1 : new_t);
this._last = found;
},
@@ -475,7 +475,7 @@ cc.Sequence = cc.ActionInterval.extend(/** @lends cc.Sequence# */{
* Returns a reversed action.
* @return {cc.Sequence}
*/
- reverse:function () {
+ reverse: function () {
var action = cc.Sequence._actionOneTwo(this._actions[1].reverse(), this._actions[0].reverse());
this._cloneDecoration(action);
this._reverseEaseList(action);
@@ -501,12 +501,25 @@ cc.sequence = function (/*Multiple Arguments*/tempArray) {
if ((paramArray.length > 0) && (paramArray[paramArray.length - 1] == null))
cc.log("parameters should not be ending with null in Javascript");
- var prev = paramArray[0];
- for (var i = 1; i < paramArray.length; i++) {
- if (paramArray[i])
- prev = cc.Sequence._actionOneTwo(prev, paramArray[i]);
+ var result, current, i, repeat;
+ while (paramArray && paramArray.length > 0) {
+ current = Array.prototype.shift.call(paramArray);
+ repeat = current._timesForRepeat || 1;
+ current._repeatMethod = false;
+ current._timesForRepeat = 1;
+
+ i = 0;
+ if (!result) {
+ result = current;
+ i = 1;
+ }
+
+ for (i; i < repeat; i++) {
+ result = cc.Sequence._actionOneTwo(result, current);
+ }
}
- return prev;
+
+ return result;
};
/**
@@ -542,22 +555,22 @@ cc.Sequence._actionOneTwo = function (actionOne, actionTwo) {
* var rep = new cc.Repeat(cc.sequence(jump2, jump1), 5);
*/
cc.Repeat = cc.ActionInterval.extend(/** @lends cc.Repeat# */{
- _times:0,
- _total:0,
- _nextDt:0,
- _actionInstant:false,
- _innerAction:null, //CCFiniteTimeAction
+ _times: 0,
+ _total: 0,
+ _nextDt: 0,
+ _actionInstant: false,
+ _innerAction: null, //CCFiniteTimeAction
- /**
+ /**
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * Creates a Repeat action. Times is an unsigned integer between 1 and pow(2,30).
- * @param {cc.FiniteTimeAction} action
- * @param {Number} times
- */
+ * Creates a Repeat action. Times is an unsigned integer between 1 and pow(2,30).
+ * @param {cc.FiniteTimeAction} action
+ * @param {Number} times
+ */
ctor: function (action, times) {
cc.ActionInterval.prototype.ctor.call(this);
- times !== undefined && this.initWithAction(action, times);
+ times !== undefined && this.initWithAction(action, times);
},
/**
@@ -565,13 +578,13 @@ cc.Repeat = cc.ActionInterval.extend(/** @lends cc.Repeat# */{
* @param {Number} times
* @return {Boolean}
*/
- initWithAction:function (action, times) {
+ initWithAction: function (action, times) {
var duration = action._duration * times;
if (this.initWithDuration(duration)) {
this._times = times;
this._innerAction = action;
- if (action instanceof cc.ActionInstant){
+ if (action instanceof cc.ActionInstant) {
this._actionInstant = true;
this._times -= 1;
}
@@ -585,7 +598,7 @@ cc.Repeat = cc.ActionInterval.extend(/** @lends cc.Repeat# */{
* returns a new clone of the action
* @returns {cc.Repeat}
*/
- clone:function () {
+ clone: function () {
var action = new cc.Repeat();
this._cloneDecoration(action);
action.initWithAction(this._innerAction.clone(), this._times);
@@ -596,7 +609,7 @@ cc.Repeat = cc.ActionInterval.extend(/** @lends cc.Repeat# */{
* Start the action with target.
* @param {cc.Node} target
*/
- startWithTarget:function (target) {
+ startWithTarget: function (target) {
this._total = 0;
this._nextDt = this._innerAction._duration / this._duration;
cc.ActionInterval.prototype.startWithTarget.call(this, target);
@@ -606,7 +619,7 @@ cc.Repeat = cc.ActionInterval.extend(/** @lends cc.Repeat# */{
/**
* stop the action
*/
- stop:function () {
+ stop: function () {
this._innerAction.stop();
cc.Action.prototype.stop.call(this);
},
@@ -615,7 +628,7 @@ cc.Repeat = cc.ActionInterval.extend(/** @lends cc.Repeat# */{
* Called once per frame. Time is the number of seconds of a frame interval.
* @param {Number} dt
*/
- update:function (dt) {
+ update: function (dt) {
dt = this._computeEaseTime(dt);
var locInnerAction = this._innerAction;
var locDuration = this._duration;
@@ -655,15 +668,15 @@ cc.Repeat = cc.ActionInterval.extend(/** @lends cc.Repeat# */{
* Return true if the action has finished.
* @return {Boolean}
*/
- isDone:function () {
- return this._total == this._times;
+ isDone: function () {
+ return this._total === this._times;
},
/**
* returns a reversed action.
* @return {cc.Repeat}
*/
- reverse:function () {
+ reverse: function () {
var action = new cc.Repeat(this._innerAction.reverse(), this._times);
this._cloneDecoration(action);
this._reverseEaseList(action);
@@ -674,8 +687,8 @@ cc.Repeat = cc.ActionInterval.extend(/** @lends cc.Repeat# */{
* Set inner Action.
* @param {cc.FiniteTimeAction} action
*/
- setInnerAction:function (action) {
- if (this._innerAction != action) {
+ setInnerAction: function (action) {
+ if (this._innerAction !== action) {
this._innerAction = action;
}
},
@@ -684,7 +697,7 @@ cc.Repeat = cc.ActionInterval.extend(/** @lends cc.Repeat# */{
* Get inner Action.
* @return {cc.FiniteTimeAction}
*/
- getInnerAction:function () {
+ getInnerAction: function () {
return this._innerAction;
}
});
@@ -725,27 +738,27 @@ cc.Repeat.create = cc.repeat;
* var rep = new cc.RepeatForever(cc.sequence(jump2, jump1), 5);
*/
cc.RepeatForever = cc.ActionInterval.extend(/** @lends cc.RepeatForever# */{
- _innerAction:null, //CCActionInterval
+ _innerAction: null, //CCActionInterval
- /**
+ /**
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * Create a acton which repeat forever.
- * @param {cc.FiniteTimeAction} action
- */
- ctor:function (action) {
+ * Create a acton which repeat forever.
+ * @param {cc.FiniteTimeAction} action
+ */
+ ctor: function (action) {
cc.ActionInterval.prototype.ctor.call(this);
this._innerAction = null;
- action && this.initWithAction(action);
+ action && this.initWithAction(action);
},
/**
* @param {cc.ActionInterval} action
* @return {Boolean}
*/
- initWithAction:function (action) {
- if(!action)
- throw "cc.RepeatForever.initWithAction(): action must be non null";
+ initWithAction: function (action) {
+ if (!action)
+ throw new Error("cc.RepeatForever.initWithAction(): action must be non null");
this._innerAction = action;
return true;
@@ -755,7 +768,7 @@ cc.RepeatForever = cc.ActionInterval.extend(/** @lends cc.RepeatForever# */{
* returns a new clone of the action
* @returns {cc.RepeatForever}
*/
- clone:function () {
+ clone: function () {
var action = new cc.RepeatForever();
this._cloneDecoration(action);
action.initWithAction(this._innerAction.clone());
@@ -766,7 +779,7 @@ cc.RepeatForever = cc.ActionInterval.extend(/** @lends cc.RepeatForever# */{
* Start the action with target.
* @param {cc.Node} target
*/
- startWithTarget:function (target) {
+ startWithTarget: function (target) {
cc.ActionInterval.prototype.startWithTarget.call(this, target);
this._innerAction.startWithTarget(target);
},
@@ -776,7 +789,7 @@ cc.RepeatForever = cc.ActionInterval.extend(/** @lends cc.RepeatForever# */{
* DON'T override unless you know what you are doing.
* @param dt delta time in seconds
*/
- step:function (dt) {
+ step: function (dt) {
var locInnerAction = this._innerAction;
locInnerAction.step(dt);
if (locInnerAction.isDone()) {
@@ -793,7 +806,7 @@ cc.RepeatForever = cc.ActionInterval.extend(/** @lends cc.RepeatForever# */{
* Return true if the action has finished.
* @return {Boolean}
*/
- isDone:function () {
+ isDone: function () {
return false;
},
@@ -801,7 +814,7 @@ cc.RepeatForever = cc.ActionInterval.extend(/** @lends cc.RepeatForever# */{
* Returns a reversed action.
* @return {cc.RepeatForever}
*/
- reverse:function () {
+ reverse: function () {
var action = new cc.RepeatForever(this._innerAction.reverse());
this._cloneDecoration(action);
this._reverseEaseList(action);
@@ -812,8 +825,8 @@ cc.RepeatForever = cc.ActionInterval.extend(/** @lends cc.RepeatForever# */{
* Set inner action.
* @param {cc.ActionInterval} action
*/
- setInnerAction:function (action) {
- if (this._innerAction != action) {
+ setInnerAction: function (action) {
+ if (this._innerAction !== action) {
this._innerAction = action;
}
},
@@ -822,7 +835,7 @@ cc.RepeatForever = cc.ActionInterval.extend(/** @lends cc.RepeatForever# */{
* Get inner action.
* @return {cc.ActionInterval}
*/
- getInnerAction:function () {
+ getInnerAction: function () {
return this._innerAction;
}
});
@@ -859,26 +872,35 @@ cc.RepeatForever.create = cc.repeatForever;
* @extends cc.ActionInterval
*/
cc.Spawn = cc.ActionInterval.extend(/** @lends cc.Spawn# */{
- _one:null,
- _two:null,
+ _one: null,
+ _two: null,
- /**
+ /**
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * @param {Array|cc.FiniteTimeAction} tempArray
- */
- ctor:function (tempArray) {
+ * @param {Array|cc.FiniteTimeAction} tempArray
+ */
+ ctor: function (tempArray) {
cc.ActionInterval.prototype.ctor.call(this);
this._one = null;
this._two = null;
- var paramArray = (tempArray instanceof Array) ? tempArray : arguments;
- var last = paramArray.length - 1;
- if ((last >= 0) && (paramArray[last] == null))
- cc.log("parameters should not be ending with null in Javascript");
+ var i, paramArray, last;
+ if (tempArray instanceof Array) {
+ paramArray = tempArray;
+ }
+ else {
+ paramArray = new Array(arguments.length);
+ for (i = 0; i < arguments.length; ++i) {
+ paramArray[i] = arguments[i];
+ }
+ }
+ last = paramArray.length - 1;
+ if ((last >= 0) && (paramArray[last] == null))
+ cc.log("parameters should not be ending with null in Javascript");
if (last >= 0) {
var prev = paramArray[0], action1;
- for (var i = 1; i < last; i++) {
+ for (i = 1; i < last; i++) {
if (paramArray[i]) {
action1 = prev;
prev = cc.Spawn._actionOneTwo(action1, paramArray[i]);
@@ -893,9 +915,9 @@ cc.Spawn = cc.ActionInterval.extend(/** @lends cc.Spawn# */{
* @param {cc.FiniteTimeAction} action2
* @return {Boolean}
*/
- initWithTwoActions:function (action1, action2) {
- if(!action1 || !action2)
- throw "cc.Spawn.initWithTwoActions(): arguments must all be non null" ;
+ initWithTwoActions: function (action1, action2) {
+ if (!action1 || !action2)
+ throw new Error("cc.Spawn.initWithTwoActions(): arguments must all be non null");
var ret = false;
@@ -921,7 +943,7 @@ cc.Spawn = cc.ActionInterval.extend(/** @lends cc.Spawn# */{
* returns a new clone of the action
* @returns {cc.Spawn}
*/
- clone:function () {
+ clone: function () {
var action = new cc.Spawn();
this._cloneDecoration(action);
action.initWithTwoActions(this._one.clone(), this._two.clone());
@@ -932,7 +954,7 @@ cc.Spawn = cc.ActionInterval.extend(/** @lends cc.Spawn# */{
* Start the action with target.
* @param {cc.Node} target
*/
- startWithTarget:function (target) {
+ startWithTarget: function (target) {
cc.ActionInterval.prototype.startWithTarget.call(this, target);
this._one.startWithTarget(target);
this._two.startWithTarget(target);
@@ -941,7 +963,7 @@ cc.Spawn = cc.ActionInterval.extend(/** @lends cc.Spawn# */{
/**
* Stop the action
*/
- stop:function () {
+ stop: function () {
this._one.stop();
this._two.stop();
cc.Action.prototype.stop.call(this);
@@ -951,7 +973,7 @@ cc.Spawn = cc.ActionInterval.extend(/** @lends cc.Spawn# */{
* Called once per frame. Time is the number of seconds of a frame interval.
* @param {Number} dt
*/
- update:function (dt) {
+ update: function (dt) {
dt = this._computeEaseTime(dt);
if (this._one)
this._one.update(dt);
@@ -963,7 +985,7 @@ cc.Spawn = cc.ActionInterval.extend(/** @lends cc.Spawn# */{
* Returns a reversed action.
* @return {cc.Spawn}
*/
- reverse:function () {
+ reverse: function () {
var action = cc.Spawn._actionOneTwo(this._one.reverse(), this._two.reverse());
this._cloneDecoration(action);
this._reverseEaseList(action);
@@ -975,7 +997,7 @@ cc.Spawn = cc.ActionInterval.extend(/** @lends cc.Spawn# */{
* Create a spawn action which runs several actions in parallel.
* @function
* @param {Array|cc.FiniteTimeAction}tempArray
- * @return {cc.FiniteTimeAction}
+ * @return {cc.Spawn}
* @example
* // example
* var action = cc.spawn(cc.jumpBy(2, cc.p(300, 0), 50, 4), cc.rotateBy(2, 720));
@@ -1000,7 +1022,7 @@ cc.spawn = function (/*Multiple Arguments*/tempArray) {
* @static
* @deprecated since v3.0 Please use cc.spawn instead.
* @param {Array|cc.FiniteTimeAction}tempArray
- * @return {cc.FiniteTimeAction}
+ * @return {cc.Spawn}
*/
cc.Spawn.create = cc.spawn;
@@ -1030,25 +1052,25 @@ cc.Spawn._actionOneTwo = function (action1, action2) {
* var rotateTo = new cc.RotateTo(2, 61.0);
*/
cc.RotateTo = cc.ActionInterval.extend(/** @lends cc.RotateTo# */{
- _dstAngleX:0,
- _startAngleX:0,
- _diffAngleX:0,
+ _dstAngleX: 0,
+ _startAngleX: 0,
+ _diffAngleX: 0,
- _dstAngleY:0,
- _startAngleY:0,
- _diffAngleY:0,
+ _dstAngleY: 0,
+ _startAngleY: 0,
+ _diffAngleY: 0,
- /**
+ /**
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * Creates a RotateTo action with x and y rotation angles.
- * @param {Number} duration duration in seconds
- * @param {Number} deltaAngleX deltaAngleX in degrees.
- * @param {Number} [deltaAngleY] deltaAngleY in degrees.
- */
- ctor:function (duration, deltaAngleX, deltaAngleY) {
+ * Creates a RotateTo action with x and y rotation angles.
+ * @param {Number} duration duration in seconds
+ * @param {Number} deltaAngleX deltaAngleX in degrees.
+ * @param {Number} [deltaAngleY] deltaAngleY in degrees.
+ */
+ ctor: function (duration, deltaAngleX, deltaAngleY) {
cc.ActionInterval.prototype.ctor.call(this);
- deltaAngleX !== undefined && this.initWithDuration(duration, deltaAngleX, deltaAngleY);
+ deltaAngleX !== undefined && this.initWithDuration(duration, deltaAngleX, deltaAngleY);
},
/**
@@ -1058,10 +1080,10 @@ cc.RotateTo = cc.ActionInterval.extend(/** @lends cc.RotateTo# */{
* @param {Number} deltaAngleY
* @return {Boolean}
*/
- initWithDuration:function (duration, deltaAngleX, deltaAngleY) {
+ initWithDuration: function (duration, deltaAngleX, deltaAngleY) {
if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
this._dstAngleX = deltaAngleX || 0;
- this._dstAngleY = deltaAngleY || this._dstAngleX;
+ this._dstAngleY = deltaAngleY !== undefined ? deltaAngleY : this._dstAngleX;
return true;
}
return false;
@@ -1071,7 +1093,7 @@ cc.RotateTo = cc.ActionInterval.extend(/** @lends cc.RotateTo# */{
* returns a new clone of the action
* @returns {cc.RotateTo}
*/
- clone:function () {
+ clone: function () {
var action = new cc.RotateTo();
this._cloneDecoration(action);
action.initWithDuration(this._duration, this._dstAngleX, this._dstAngleY);
@@ -1082,7 +1104,7 @@ cc.RotateTo = cc.ActionInterval.extend(/** @lends cc.RotateTo# */{
* Start the action with target.
* @param {cc.Node} target
*/
- startWithTarget:function (target) {
+ startWithTarget: function (target) {
cc.ActionInterval.prototype.startWithTarget.call(this, target);
// Calculate X
@@ -1108,8 +1130,9 @@ cc.RotateTo = cc.ActionInterval.extend(/** @lends cc.RotateTo# */{
/**
* RotateTo reverse not implemented.
* Will be overridden.
+ * @returns {cc.Action}
*/
- reverse:function () {
+ reverse: function () {
cc.log("cc.RotateTo.reverse(): it should be overridden in subclass.");
},
@@ -1117,7 +1140,7 @@ cc.RotateTo = cc.ActionInterval.extend(/** @lends cc.RotateTo# */{
* Called once per frame. Time is the number of seconds of a frame interval.
* @param {Number} dt
*/
- update:function (dt) {
+ update: function (dt) {
dt = this._computeEaseTime(dt);
if (this.target) {
this.target.rotationX = this._startAngleX + this._diffAngleX * dt;
@@ -1168,21 +1191,21 @@ cc.RotateTo.create = cc.rotateTo;
* var actionBy = new cc.RotateBy(2, 360);
*/
cc.RotateBy = cc.ActionInterval.extend(/** @lends cc.RotateBy# */{
- _angleX:0,
- _startAngleX:0,
- _angleY:0,
- _startAngleY:0,
+ _angleX: 0,
+ _startAngleX: 0,
+ _angleY: 0,
+ _startAngleY: 0,
- /**
+ /**
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * @param {Number} duration duration in seconds
- * @param {Number} deltaAngleX deltaAngleX in degrees
- * @param {Number} [deltaAngleY] deltaAngleY in degrees
- */
+ * @param {Number} duration duration in seconds
+ * @param {Number} deltaAngleX deltaAngleX in degrees
+ * @param {Number} [deltaAngleY] deltaAngleY in degrees
+ */
ctor: function (duration, deltaAngleX, deltaAngleY) {
cc.ActionInterval.prototype.ctor.call(this);
- deltaAngleX !== undefined && this.initWithDuration(duration, deltaAngleX, deltaAngleY);
+ deltaAngleX !== undefined && this.initWithDuration(duration, deltaAngleX, deltaAngleY);
},
/**
@@ -1192,7 +1215,7 @@ cc.RotateBy = cc.ActionInterval.extend(/** @lends cc.RotateBy# */{
* @param {Number} [deltaAngleY=] deltaAngleY in degrees
* @return {Boolean}
*/
- initWithDuration:function (duration, deltaAngleX, deltaAngleY) {
+ initWithDuration: function (duration, deltaAngleX, deltaAngleY) {
if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
this._angleX = deltaAngleX || 0;
this._angleY = deltaAngleY || this._angleX;
@@ -1205,7 +1228,7 @@ cc.RotateBy = cc.ActionInterval.extend(/** @lends cc.RotateBy# */{
* returns a new clone of the action
* @returns {cc.RotateBy}
*/
- clone:function () {
+ clone: function () {
var action = new cc.RotateBy();
this._cloneDecoration(action);
action.initWithDuration(this._duration, this._angleX, this._angleY);
@@ -1216,7 +1239,7 @@ cc.RotateBy = cc.ActionInterval.extend(/** @lends cc.RotateBy# */{
* Start the action with target.
* @param {cc.Node} target
*/
- startWithTarget:function (target) {
+ startWithTarget: function (target) {
cc.ActionInterval.prototype.startWithTarget.call(this, target);
this._startAngleX = target.rotationX;
this._startAngleY = target.rotationY;
@@ -1226,7 +1249,7 @@ cc.RotateBy = cc.ActionInterval.extend(/** @lends cc.RotateBy# */{
* Called once per frame. Time is the number of seconds of a frame interval.
* @param {Number} dt
*/
- update:function (dt) {
+ update: function (dt) {
dt = this._computeEaseTime(dt);
if (this.target) {
this.target.rotationX = this._startAngleX + this._angleX * dt;
@@ -1238,7 +1261,7 @@ cc.RotateBy = cc.ActionInterval.extend(/** @lends cc.RotateBy# */{
* Returns a reversed action.
* @return {cc.RotateBy}
*/
- reverse:function () {
+ reverse: function () {
var action = new cc.RotateBy(this._duration, -this._angleX, -this._angleY);
this._cloneDecoration(action);
this._reverseEaseList(action);
@@ -1288,27 +1311,27 @@ cc.RotateBy.create = cc.rotateBy;
* @param {cc.Point|Number} deltaPos
* @param {Number} [deltaY]
* @example
- * var actionTo = cc.moveBy(2, cc.p(windowSize.width - 40, windowSize.height - 40));
+ * var actionBy = cc.moveBy(2, cc.p(windowSize.width - 40, windowSize.height - 40));
*/
cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{
- _positionDelta:null,
- _startPosition:null,
- _previousPosition:null,
+ _positionDelta: null,
+ _startPosition: null,
+ _previousPosition: null,
- /**
+ /**
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * @param {Number} duration duration in seconds
- * @param {cc.Point|Number} deltaPos
- * @param {Number} [deltaY]
- */
- ctor:function (duration, deltaPos, deltaY) {
+ * @param {Number} duration duration in seconds
+ * @param {cc.Point|Number} deltaPos
+ * @param {Number} [deltaY]
+ */
+ ctor: function (duration, deltaPos, deltaY) {
cc.ActionInterval.prototype.ctor.call(this);
this._positionDelta = cc.p(0, 0);
this._startPosition = cc.p(0, 0);
this._previousPosition = cc.p(0, 0);
- deltaPos !== undefined && this.initWithDuration(duration, deltaPos, deltaY);
+ deltaPos !== undefined && this.initWithDuration(duration, deltaPos, deltaY);
},
/**
@@ -1318,12 +1341,12 @@ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{
* @param {Number} [y]
* @return {Boolean}
*/
- initWithDuration:function (duration, position, y) {
+ initWithDuration: function (duration, position, y) {
if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
- if(position.x !== undefined) {
- y = position.y;
- position = position.x;
- }
+ if (position.x !== undefined) {
+ y = position.y;
+ position = position.x;
+ }
this._positionDelta.x = position;
this._positionDelta.y = y;
@@ -1336,7 +1359,7 @@ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{
* returns a new clone of the action
* @returns {cc.MoveBy}
*/
- clone:function () {
+ clone: function () {
var action = new cc.MoveBy();
this._cloneDecoration(action);
action.initWithDuration(this._duration, this._positionDelta);
@@ -1347,7 +1370,7 @@ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{
* Start the action with target.
* @param {cc.Node} target
*/
- startWithTarget:function (target) {
+ startWithTarget: function (target) {
cc.ActionInterval.prototype.startWithTarget.call(this, target);
var locPosX = target.getPositionX();
var locPosY = target.getPositionY();
@@ -1361,7 +1384,7 @@ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{
* Called once per frame. Time is the number of seconds of a frame interval.
* @param {Number} dt
*/
- update:function (dt) {
+ update: function (dt) {
dt = this._computeEaseTime(dt);
if (this.target) {
var x = this._positionDelta.x * dt;
@@ -1376,9 +1399,9 @@ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{
locStartPosition.y = locStartPosition.y + targetY - locPreviousPosition.y;
x = x + locStartPosition.x;
y = y + locStartPosition.y;
- locPreviousPosition.x = x;
- locPreviousPosition.y = y;
- this.target.setPosition(x, y);
+ locPreviousPosition.x = x;
+ locPreviousPosition.y = y;
+ this.target.setPosition(x, y);
} else {
this.target.setPosition(locStartPosition.x + x, locStartPosition.y + y);
}
@@ -1389,7 +1412,7 @@ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{
* MoveTo reverse is not implemented
* @return {cc.MoveBy}
*/
- reverse:function () {
+ reverse: function () {
var action = new cc.MoveBy(this._duration, cc.p(-this._positionDelta.x, -this._positionDelta.y));
this._cloneDecoration(action);
this._reverseEaseList(action);
@@ -1407,7 +1430,7 @@ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{
* @return {cc.MoveBy}
* @example
* // example
- * var actionTo = cc.moveBy(2, cc.p(windowSize.width - 40, windowSize.height - 40));
+ * var actionBy = cc.moveBy(2, cc.p(windowSize.width - 40, windowSize.height - 40));
*/
cc.moveBy = function (duration, deltaPos, deltaY) {
return new cc.MoveBy(duration, deltaPos, deltaY);
@@ -1435,22 +1458,22 @@ cc.MoveBy.create = cc.moveBy;
* @param {cc.Point|Number} position
* @param {Number} y
* @example
- * var actionBy = new cc.MoveTo(2, cc.p(80, 80));
+ * var actionTo = new cc.MoveTo(2, cc.p(80, 80));
*/
cc.MoveTo = cc.MoveBy.extend(/** @lends cc.MoveTo# */{
- _endPosition:null,
+ _endPosition: null,
- /**
+ /**
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * @param {Number} duration duration in seconds
- * @param {cc.Point|Number} position
- * @param {Number} y
- */
- ctor:function (duration, position, y) {
+ * @param {Number} duration duration in seconds
+ * @param {cc.Point|Number} position
+ * @param {Number} y
+ */
+ ctor: function (duration, position, y) {
cc.MoveBy.prototype.ctor.call(this);
this._endPosition = cc.p(0, 0);
- position !== undefined && this.initWithDuration(duration, position, y);
+ position !== undefined && this.initWithDuration(duration, position, y);
},
/**
@@ -1460,12 +1483,12 @@ cc.MoveTo = cc.MoveBy.extend(/** @lends cc.MoveTo# */{
* @param {Number} y
* @return {Boolean}
*/
- initWithDuration:function (duration, position, y) {
+ initWithDuration: function (duration, position, y) {
if (cc.MoveBy.prototype.initWithDuration.call(this, duration, position, y)) {
- if(position.x !== undefined) {
- y = position.y;
- position = position.x;
- }
+ if (position.x !== undefined) {
+ y = position.y;
+ position = position.x;
+ }
this._endPosition.x = position;
this._endPosition.y = y;
@@ -1478,7 +1501,7 @@ cc.MoveTo = cc.MoveBy.extend(/** @lends cc.MoveTo# */{
* returns a new clone of the action
* @returns {cc.MoveTo}
*/
- clone:function () {
+ clone: function () {
var action = new cc.MoveTo();
this._cloneDecoration(action);
action.initWithDuration(this._duration, this._endPosition);
@@ -1489,7 +1512,7 @@ cc.MoveTo = cc.MoveBy.extend(/** @lends cc.MoveTo# */{
* Start the action with target.
* @param {cc.Node} target
*/
- startWithTarget:function (target) {
+ startWithTarget: function (target) {
cc.MoveBy.prototype.startWithTarget.call(this, target);
this._positionDelta.x = this._endPosition.x - target.getPositionX();
this._positionDelta.y = this._endPosition.y - target.getPositionY();
@@ -1501,12 +1524,12 @@ cc.MoveTo = cc.MoveBy.extend(/** @lends cc.MoveTo# */{
* Moving to the specified coordinates.
* @function
* @param {Number} duration duration in seconds
- * @param {cc.Point} position
+ * @param {cc.Point|Number} position
* @param {Number} y
- * @return {cc.MoveBy}
+ * @return {cc.MoveTo}
* @example
* // example
- * var actionBy = cc.moveTo(2, cc.p(80, 80));
+ * var actionTo = cc.moveTo(2, cc.p(80, 80));
*/
cc.moveTo = function (duration, position, y) {
return new cc.MoveTo(duration, position, y);
@@ -1517,9 +1540,9 @@ cc.moveTo = function (duration, position, y) {
* @static
* @deprecated since v3.0 Please use cc.moveTo instead.
* @param {Number} duration duration in seconds
- * @param {cc.Point} position
+ * @param {cc.Point|Number} position
* @param {Number} y
- * @return {cc.MoveBy}
+ * @return {cc.MoveTo}
*/
cc.MoveTo.create = cc.moveTo;
@@ -1534,25 +1557,25 @@ cc.MoveTo.create = cc.moveTo;
* var actionTo = new cc.SkewTo(2, 37.2, -37.2);
*/
cc.SkewTo = cc.ActionInterval.extend(/** @lends cc.SkewTo# */{
- _skewX:0,
- _skewY:0,
- _startSkewX:0,
- _startSkewY:0,
- _endSkewX:0,
- _endSkewY:0,
- _deltaX:0,
- _deltaY:0,
-
- /**
+ _skewX: 0,
+ _skewY: 0,
+ _startSkewX: 0,
+ _startSkewY: 0,
+ _endSkewX: 0,
+ _endSkewY: 0,
+ _deltaX: 0,
+ _deltaY: 0,
+
+ /**
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * @param {Number} t time in seconds
- * @param {Number} sx
- * @param {Number} sy
- */
+ * @param {Number} t time in seconds
+ * @param {Number} sx
+ * @param {Number} sy
+ */
ctor: function (t, sx, sy) {
cc.ActionInterval.prototype.ctor.call(this);
- sy !== undefined && this.initWithDuration(t, sx, sy);
+ sy !== undefined && this.initWithDuration(t, sx, sy);
},
/**
@@ -1562,7 +1585,7 @@ cc.SkewTo = cc.ActionInterval.extend(/** @lends cc.SkewTo# */{
* @param {Number} sy
* @return {Boolean}
*/
- initWithDuration:function (t, sx, sy) {
+ initWithDuration: function (t, sx, sy) {
var ret = false;
if (cc.ActionInterval.prototype.initWithDuration.call(this, t)) {
this._endSkewX = sx;
@@ -1576,7 +1599,7 @@ cc.SkewTo = cc.ActionInterval.extend(/** @lends cc.SkewTo# */{
* returns a new clone of the action
* @returns {cc.SkewTo}
*/
- clone:function () {
+ clone: function () {
var action = new cc.SkewTo();
this._cloneDecoration(action);
action.initWithDuration(this._duration, this._endSkewX, this._endSkewY);
@@ -1587,7 +1610,7 @@ cc.SkewTo = cc.ActionInterval.extend(/** @lends cc.SkewTo# */{
* Start the action with target.
* @param {cc.Node} target
*/
- startWithTarget:function (target) {
+ startWithTarget: function (target) {
cc.ActionInterval.prototype.startWithTarget.call(this, target);
this._startSkewX = target.skewX % 180;
@@ -1609,7 +1632,7 @@ cc.SkewTo = cc.ActionInterval.extend(/** @lends cc.SkewTo# */{
* Called once per frame. Time is the number of seconds of a frame interval.
* @param {Number} dt
*/
- update:function (dt) {
+ update: function (dt) {
dt = this._computeEaseTime(dt);
this.target.skewX = this._startSkewX + this._deltaX * dt;
this.target.skewY = this._startSkewY + this._deltaY * dt;
@@ -1655,16 +1678,16 @@ cc.SkewTo.create = cc.skewTo;
*/
cc.SkewBy = cc.SkewTo.extend(/** @lends cc.SkewBy# */{
- /**
+ /**
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * @param {Number} t time in seconds
- * @param {Number} sx skew in degrees for X axis
- * @param {Number} sy skew in degrees for Y axis
- */
- ctor: function(t, sx, sy) {
- cc.SkewTo.prototype.ctor.call(this);
- sy !== undefined && this.initWithDuration(t, sx, sy);
- },
+ * @param {Number} t time in seconds
+ * @param {Number} sx skew in degrees for X axis
+ * @param {Number} sy skew in degrees for Y axis
+ */
+ ctor: function (t, sx, sy) {
+ cc.SkewTo.prototype.ctor.call(this);
+ sy !== undefined && this.initWithDuration(t, sx, sy);
+ },
/**
* Initializes the action.
@@ -1673,7 +1696,7 @@ cc.SkewBy = cc.SkewTo.extend(/** @lends cc.SkewBy# */{
* @param {Number} deltaSkewY skew in degrees for Y axis
* @return {Boolean}
*/
- initWithDuration:function (t, deltaSkewX, deltaSkewY) {
+ initWithDuration: function (t, deltaSkewX, deltaSkewY) {
var ret = false;
if (cc.SkewTo.prototype.initWithDuration.call(this, t, deltaSkewX, deltaSkewY)) {
this._skewX = deltaSkewX;
@@ -1687,7 +1710,7 @@ cc.SkewBy = cc.SkewTo.extend(/** @lends cc.SkewBy# */{
* returns a new clone of the action
* @returns {cc.SkewBy}
*/
- clone:function () {
+ clone: function () {
var action = new cc.SkewBy();
this._cloneDecoration(action);
action.initWithDuration(this._duration, this._skewX, this._skewY);
@@ -1698,7 +1721,7 @@ cc.SkewBy = cc.SkewTo.extend(/** @lends cc.SkewBy# */{
* Start the action width target.
* @param {cc.Node} target
*/
- startWithTarget:function (target) {
+ startWithTarget: function (target) {
cc.SkewTo.prototype.startWithTarget.call(this, target);
this._deltaX = this._skewX;
this._deltaY = this._skewY;
@@ -1710,7 +1733,7 @@ cc.SkewBy = cc.SkewTo.extend(/** @lends cc.SkewBy# */{
* Returns a reversed action.
* @return {cc.SkewBy}
*/
- reverse:function () {
+ reverse: function () {
var action = new cc.SkewBy(this._duration, -this._skewX, -this._skewY);
this._cloneDecoration(action);
this._reverseEaseList(action);
@@ -1762,27 +1785,27 @@ cc.SkewBy.create = cc.skewBy;
* var actionBy = new cc.JumpBy(2, 300, 0, 50, 4);
*/
cc.JumpBy = cc.ActionInterval.extend(/** @lends cc.JumpBy# */{
- _startPosition:null,
- _delta:null,
- _height:0,
- _jumps:0,
- _previousPosition:null,
+ _startPosition: null,
+ _delta: null,
+ _height: 0,
+ _jumps: 0,
+ _previousPosition: null,
- /**
+ /**
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * @param {Number} duration
- * @param {cc.Point|Number} position
- * @param {Number} [y]
- * @param {Number} height
- * @param {Number} jumps
- */
- ctor:function (duration, position, y, height, jumps) {
+ * @param {Number} duration
+ * @param {cc.Point|Number} position
+ * @param {Number} [y]
+ * @param {Number} height
+ * @param {Number} jumps
+ */
+ ctor: function (duration, position, y, height, jumps) {
cc.ActionInterval.prototype.ctor.call(this);
this._startPosition = cc.p(0, 0);
this._previousPosition = cc.p(0, 0);
this._delta = cc.p(0, 0);
- height !== undefined && this.initWithDuration(duration, position, y, height, jumps);
+ height !== undefined && this.initWithDuration(duration, position, y, height, jumps);
},
/**
* Initializes the action.
@@ -1796,14 +1819,14 @@ cc.JumpBy = cc.ActionInterval.extend(/** @lends cc.JumpBy# */{
* actionBy.initWithDuration(2, cc.p(300, 0), 50, 4);
* actionBy.initWithDuration(2, 300, 0, 50, 4);
*/
- initWithDuration:function (duration, position, y, height, jumps) {
+ initWithDuration: function (duration, position, y, height, jumps) {
if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
- if (jumps === undefined) {
- jumps = height;
- height = y;
- y = position.y;
- position = position.x;
- }
+ if (jumps === undefined) {
+ jumps = height;
+ height = y;
+ y = position.y;
+ position = position.x;
+ }
this._delta.x = position;
this._delta.y = y;
this._height = height;
@@ -1817,7 +1840,7 @@ cc.JumpBy = cc.ActionInterval.extend(/** @lends cc.JumpBy# */{
* returns a new clone of the action
* @returns {cc.JumpBy}
*/
- clone:function () {
+ clone: function () {
var action = new cc.JumpBy();
this._cloneDecoration(action);
action.initWithDuration(this._duration, this._delta, this._height, this._jumps);
@@ -1828,7 +1851,7 @@ cc.JumpBy = cc.ActionInterval.extend(/** @lends cc.JumpBy# */{
* Start the action with target.
* @param {cc.Node} target
*/
- startWithTarget:function (target) {
+ startWithTarget: function (target) {
cc.ActionInterval.prototype.startWithTarget.call(this, target);
var locPosX = target.getPositionX();
var locPosY = target.getPositionY();
@@ -1842,7 +1865,7 @@ cc.JumpBy = cc.ActionInterval.extend(/** @lends cc.JumpBy# */{
* Called once per frame. Time is the number of seconds of a frame interval.
* @param {Number} dt
*/
- update:function (dt) {
+ update: function (dt) {
dt = this._computeEaseTime(dt);
if (this.target) {
var frac = dt * this._jumps % 1.0;
@@ -1860,9 +1883,9 @@ cc.JumpBy = cc.ActionInterval.extend(/** @lends cc.JumpBy# */{
locStartPosition.y = locStartPosition.y + targetY - locPreviousPosition.y;
x = x + locStartPosition.x;
y = y + locStartPosition.y;
- locPreviousPosition.x = x;
- locPreviousPosition.y = y;
- this.target.setPosition(x, y);
+ locPreviousPosition.x = x;
+ locPreviousPosition.y = y;
+ this.target.setPosition(x, y);
} else {
this.target.setPosition(locStartPosition.x + x, locStartPosition.y + y);
}
@@ -1873,7 +1896,7 @@ cc.JumpBy = cc.ActionInterval.extend(/** @lends cc.JumpBy# */{
* Returns a reversed action.
* @return {cc.JumpBy}
*/
- reverse:function () {
+ reverse: function () {
var action = new cc.JumpBy(this._duration, cc.p(-this._delta.x, -this._delta.y), this._height, this._jumps);
this._cloneDecoration(action);
this._reverseEaseList(action);
@@ -1929,7 +1952,7 @@ cc.JumpBy.create = cc.jumpBy;
* var actionTo = new cc.JumpTo(2, 300, 0, 50, 4);
*/
cc.JumpTo = cc.JumpBy.extend(/** @lends cc.JumpTo# */{
- _endPosition:null,
+ _endPosition: null,
/**
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
@@ -1939,7 +1962,7 @@ cc.JumpTo = cc.JumpBy.extend(/** @lends cc.JumpTo# */{
* @param {Number} height
* @param {Number} jumps
*/
- ctor:function (duration, position, y, height, jumps) {
+ ctor: function (duration, position, y, height, jumps) {
cc.JumpBy.prototype.ctor.call(this);
this._endPosition = cc.p(0, 0);
@@ -1957,7 +1980,7 @@ cc.JumpTo = cc.JumpBy.extend(/** @lends cc.JumpTo# */{
* actionTo.initWithDuration(2, cc.p(300, 0), 50, 4);
* actionTo.initWithDuration(2, 300, 0, 50, 4);
*/
- initWithDuration:function (duration, position, y, height, jumps) {
+ initWithDuration: function (duration, position, y, height, jumps) {
if (cc.JumpBy.prototype.initWithDuration.call(this, duration, position, y, height, jumps)) {
if (jumps === undefined) {
y = position.y;
@@ -1973,7 +1996,7 @@ cc.JumpTo = cc.JumpBy.extend(/** @lends cc.JumpTo# */{
* Start the action with target.
* @param {cc.Node} target
*/
- startWithTarget:function (target) {
+ startWithTarget: function (target) {
cc.JumpBy.prototype.startWithTarget.call(this, target);
this._delta.x = this._endPosition.x - this._startPosition.x;
this._delta.y = this._endPosition.y - this._startPosition.y;
@@ -1983,7 +2006,7 @@ cc.JumpTo = cc.JumpBy.extend(/** @lends cc.JumpTo# */{
* returns a new clone of the action
* @returns {cc.JumpTo}
*/
- clone:function () {
+ clone: function () {
var action = new cc.JumpTo();
this._cloneDecoration(action);
action.initWithDuration(this._duration, this._endPosition, this._height, this._jumps);
@@ -2035,9 +2058,9 @@ cc.JumpTo.create = cc.jumpTo;
*/
cc.bezierAt = function (a, b, c, d, t) {
return (Math.pow(1 - t, 3) * a +
- 3 * t * (Math.pow(1 - t, 2)) * b +
- 3 * Math.pow(t, 2) * (1 - t) * c +
- Math.pow(t, 3) * d );
+ 3 * t * (Math.pow(1 - t, 2)) * b +
+ 3 * Math.pow(t, 2) * (1 - t) * c +
+ Math.pow(t, 3) * d );
};
/** An action that moves the target with a cubic Bezier curve by a certain distance.
@@ -2051,22 +2074,22 @@ cc.bezierAt = function (a, b, c, d, t) {
* var bezierForward = new cc.BezierBy(3, bezier);
*/
cc.BezierBy = cc.ActionInterval.extend(/** @lends cc.BezierBy# */{
- _config:null,
- _startPosition:null,
- _previousPosition:null,
+ _config: null,
+ _startPosition: null,
+ _previousPosition: null,
- /**
+ /**
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * @param {Number} t time in seconds
- * @param {Array} c Array of points
- */
- ctor:function (t, c) {
+ * @param {Number} t time in seconds
+ * @param {Array} c Array of points
+ */
+ ctor: function (t, c) {
cc.ActionInterval.prototype.ctor.call(this);
this._config = [];
this._startPosition = cc.p(0, 0);
this._previousPosition = cc.p(0, 0);
- c && this.initWithDuration(t, c);
+ c && this.initWithDuration(t, c);
},
/**
@@ -2075,7 +2098,7 @@ cc.BezierBy = cc.ActionInterval.extend(/** @lends cc.BezierBy# */{
* @param {Array} c Array of points
* @return {Boolean}
*/
- initWithDuration:function (t, c) {
+ initWithDuration: function (t, c) {
if (cc.ActionInterval.prototype.initWithDuration.call(this, t)) {
this._config = c;
return true;
@@ -2087,7 +2110,7 @@ cc.BezierBy = cc.ActionInterval.extend(/** @lends cc.BezierBy# */{
* returns a new clone of the action
* @returns {cc.BezierBy}
*/
- clone:function () {
+ clone: function () {
var action = new cc.BezierBy();
this._cloneDecoration(action);
var newConfigs = [];
@@ -2103,7 +2126,7 @@ cc.BezierBy = cc.ActionInterval.extend(/** @lends cc.BezierBy# */{
* Start the action with target.
* @param {cc.Node} target
*/
- startWithTarget:function (target) {
+ startWithTarget: function (target) {
cc.ActionInterval.prototype.startWithTarget.call(this, target);
var locPosX = target.getPositionX();
var locPosY = target.getPositionY();
@@ -2117,7 +2140,7 @@ cc.BezierBy = cc.ActionInterval.extend(/** @lends cc.BezierBy# */{
* Called once per frame. Time is the number of seconds of a frame interval.
* @param {Number} dt
*/
- update:function (dt) {
+ update: function (dt) {
dt = this._computeEaseTime(dt);
if (this.target) {
var locConfig = this._config;
@@ -2144,9 +2167,9 @@ cc.BezierBy = cc.ActionInterval.extend(/** @lends cc.BezierBy# */{
locStartPosition.y = locStartPosition.y + targetY - locPreviousPosition.y;
x = x + locStartPosition.x;
y = y + locStartPosition.y;
- locPreviousPosition.x = x;
- locPreviousPosition.y = y;
- this.target.setPosition(x, y);
+ locPreviousPosition.x = x;
+ locPreviousPosition.y = y;
+ this.target.setPosition(x, y);
} else {
this.target.setPosition(locStartPosition.x + x, locStartPosition.y + y);
}
@@ -2157,12 +2180,12 @@ cc.BezierBy = cc.ActionInterval.extend(/** @lends cc.BezierBy# */{
* Returns a reversed action.
* @return {cc.BezierBy}
*/
- reverse:function () {
+ reverse: function () {
var locConfig = this._config;
var r = [
cc.pAdd(locConfig[1], cc.pNeg(locConfig[2])),
cc.pAdd(locConfig[0], cc.pNeg(locConfig[2])),
- cc.pNeg(locConfig[2]) ];
+ cc.pNeg(locConfig[2])];
var action = new cc.BezierBy(this._duration, r);
this._cloneDecoration(action);
this._reverseEaseList(action);
@@ -2208,18 +2231,18 @@ cc.BezierBy.create = cc.bezierBy;
* var bezierTo = new cc.BezierTo(2, bezier);
*/
cc.BezierTo = cc.BezierBy.extend(/** @lends cc.BezierTo# */{
- _toConfig:null,
+ _toConfig: null,
- /**
+ /**
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * @param {Number} t
- * @param {Array} c array of points
- * var bezierTo = new cc.BezierTo(2, bezier);
- */
- ctor:function (t, c) {
+ * @param {Number} t
+ * @param {Array} c array of points
+ * var bezierTo = new cc.BezierTo(2, bezier);
+ */
+ ctor: function (t, c) {
cc.BezierBy.prototype.ctor.call(this);
this._toConfig = [];
- c && this.initWithDuration(t, c);
+ c && this.initWithDuration(t, c);
},
/**
@@ -2228,7 +2251,7 @@ cc.BezierTo = cc.BezierBy.extend(/** @lends cc.BezierTo# */{
* @param {Array} c Array of points
* @return {Boolean}
*/
- initWithDuration:function (t, c) {
+ initWithDuration: function (t, c) {
if (cc.ActionInterval.prototype.initWithDuration.call(this, t)) {
this._toConfig = c;
return true;
@@ -2240,7 +2263,7 @@ cc.BezierTo = cc.BezierBy.extend(/** @lends cc.BezierTo# */{
* returns a new clone of the action
* @returns {cc.BezierTo}
*/
- clone:function () {
+ clone: function () {
var action = new cc.BezierTo();
this._cloneDecoration(action);
action.initWithDuration(this._duration, this._toConfig);
@@ -2251,7 +2274,7 @@ cc.BezierTo = cc.BezierBy.extend(/** @lends cc.BezierTo# */{
* Start the action with target.
* @param {cc.Node} target
*/
- startWithTarget:function (target) {
+ startWithTarget: function (target) {
cc.BezierBy.prototype.startWithTarget.call(this, target);
var locStartPos = this._startPosition;
var locToConfig = this._toConfig;
@@ -2302,24 +2325,24 @@ cc.BezierTo.create = cc.bezierTo;
* var actionTo = new cc.ScaleTo(2, 0.5, 2);
*/
cc.ScaleTo = cc.ActionInterval.extend(/** @lends cc.ScaleTo# */{
- _scaleX:1,
- _scaleY:1,
- _startScaleX:1,
- _startScaleY:1,
- _endScaleX:0,
- _endScaleY:0,
- _deltaX:0,
- _deltaY:0,
-
- /**
+ _scaleX: 1,
+ _scaleY: 1,
+ _startScaleX: 1,
+ _startScaleY: 1,
+ _endScaleX: 0,
+ _endScaleY: 0,
+ _deltaX: 0,
+ _deltaY: 0,
+
+ /**
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * @param {Number} duration
- * @param {Number} sx scale parameter in X
- * @param {Number} [sy] scale parameter in Y, if Null equal to sx
- */
- ctor:function (duration, sx, sy) {
+ * @param {Number} duration
+ * @param {Number} sx scale parameter in X
+ * @param {Number} [sy] scale parameter in Y, if Null equal to sx
+ */
+ ctor: function (duration, sx, sy) {
cc.ActionInterval.prototype.ctor.call(this);
- sx !== undefined && this.initWithDuration(duration, sx, sy);
+ sx !== undefined && this.initWithDuration(duration, sx, sy);
},
/**
@@ -2329,7 +2352,7 @@ cc.ScaleTo = cc.ActionInterval.extend(/** @lends cc.ScaleTo# */{
* @param {Number} [sy=]
* @return {Boolean}
*/
- initWithDuration:function (duration, sx, sy) { //function overload here
+ initWithDuration: function (duration, sx, sy) { //function overload here
if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
this._endScaleX = sx;
this._endScaleY = (sy != null) ? sy : sx;
@@ -2342,7 +2365,7 @@ cc.ScaleTo = cc.ActionInterval.extend(/** @lends cc.ScaleTo# */{
* returns a new clone of the action
* @returns {cc.ScaleTo}
*/
- clone:function () {
+ clone: function () {
var action = new cc.ScaleTo();
this._cloneDecoration(action);
action.initWithDuration(this._duration, this._endScaleX, this._endScaleY);
@@ -2353,7 +2376,7 @@ cc.ScaleTo = cc.ActionInterval.extend(/** @lends cc.ScaleTo# */{
* Start the action with target.
* @param {cc.Node} target
*/
- startWithTarget:function (target) {
+ startWithTarget: function (target) {
cc.ActionInterval.prototype.startWithTarget.call(this, target);
this._startScaleX = target.scaleX;
this._startScaleY = target.scaleY;
@@ -2365,11 +2388,11 @@ cc.ScaleTo = cc.ActionInterval.extend(/** @lends cc.ScaleTo# */{
* Called once per frame. Time is the number of seconds of a frame interval.
* @param {Number} dt
*/
- update:function (dt) {
+ update: function (dt) {
dt = this._computeEaseTime(dt);
if (this.target) {
this.target.scaleX = this._startScaleX + this._deltaX * dt;
- this.target.scaleY = this._startScaleY + this._deltaY * dt;
+ this.target.scaleY = this._startScaleY + this._deltaY * dt;
}
}
});
@@ -2414,7 +2437,7 @@ cc.ScaleBy = cc.ScaleTo.extend(/** @lends cc.ScaleBy# */{
* Start the action with target.
* @param {cc.Node} target
*/
- startWithTarget:function (target) {
+ startWithTarget: function (target) {
cc.ScaleTo.prototype.startWithTarget.call(this, target);
this._deltaX = this._startScaleX * this._endScaleX - this._startScaleX;
this._deltaY = this._startScaleY * this._endScaleY - this._startScaleY;
@@ -2424,7 +2447,7 @@ cc.ScaleBy = cc.ScaleTo.extend(/** @lends cc.ScaleBy# */{
* Returns a reversed action.
* @return {cc.ScaleBy}
*/
- reverse:function () {
+ reverse: function () {
var action = new cc.ScaleBy(this._duration, 1 / this._endScaleX, 1 / this._endScaleY);
this._cloneDecoration(action);
this._reverseEaseList(action);
@@ -2435,7 +2458,7 @@ cc.ScaleBy = cc.ScaleTo.extend(/** @lends cc.ScaleBy# */{
* returns a new clone of the action
* @returns {cc.ScaleBy}
*/
- clone:function () {
+ clone: function () {
var action = new cc.ScaleBy();
this._cloneDecoration(action);
action.initWithDuration(this._duration, this._endScaleX, this._endScaleY);
@@ -2482,17 +2505,17 @@ cc.ScaleBy.create = cc.scaleBy;
* var action = new cc.Blink(2, 10);
*/
cc.Blink = cc.ActionInterval.extend(/** @lends cc.Blink# */{
- _times:0,
- _originalState:false,
+ _times: 0,
+ _originalState: false,
- /**
+ /**
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
* @param {Number} duration duration in seconds
- * @param {Number} blinks blinks in times
- */
- ctor:function (duration, blinks) {
+ * @param {Number} blinks blinks in times
+ */
+ ctor: function (duration, blinks) {
cc.ActionInterval.prototype.ctor.call(this);
- blinks !== undefined && this.initWithDuration(duration, blinks);
+ blinks !== undefined && this.initWithDuration(duration, blinks);
},
/**
@@ -2501,7 +2524,7 @@ cc.Blink = cc.ActionInterval.extend(/** @lends cc.Blink# */{
* @param {Number} blinks blinks in times
* @return {Boolean}
*/
- initWithDuration:function (duration, blinks) {
+ initWithDuration: function (duration, blinks) {
if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
this._times = blinks;
return true;
@@ -2513,7 +2536,7 @@ cc.Blink = cc.ActionInterval.extend(/** @lends cc.Blink# */{
* returns a new clone of the action
* @returns {cc.Blink}
*/
- clone:function () {
+ clone: function () {
var action = new cc.Blink();
this._cloneDecoration(action);
action.initWithDuration(this._duration, this._times);
@@ -2524,7 +2547,7 @@ cc.Blink = cc.ActionInterval.extend(/** @lends cc.Blink# */{
* Called once per frame. Time is the number of seconds of a frame interval.
* @param {Number} dt time in seconds
*/
- update:function (dt) {
+ update: function (dt) {
dt = this._computeEaseTime(dt);
if (this.target && !this.isDone()) {
var slice = 1.0 / this._times;
@@ -2537,7 +2560,7 @@ cc.Blink = cc.ActionInterval.extend(/** @lends cc.Blink# */{
* Start the action with target.
* @param {cc.Node} target
*/
- startWithTarget:function (target) {
+ startWithTarget: function (target) {
cc.ActionInterval.prototype.startWithTarget.call(this, target);
this._originalState = target.visible;
},
@@ -2545,7 +2568,7 @@ cc.Blink = cc.ActionInterval.extend(/** @lends cc.Blink# */{
/**
* stop the action
*/
- stop:function () {
+ stop: function () {
this.target.visible = this._originalState;
cc.ActionInterval.prototype.stop.call(this);
},
@@ -2554,7 +2577,7 @@ cc.Blink = cc.ActionInterval.extend(/** @lends cc.Blink# */{
* Returns a reversed action.
* @return {cc.Blink}
*/
- reverse:function () {
+ reverse: function () {
var action = new cc.Blink(this._duration, this._times);
this._cloneDecoration(action);
this._reverseEaseList(action);
@@ -2595,17 +2618,17 @@ cc.Blink.create = cc.blink;
* var action = new cc.FadeTo(1.0, 0);
*/
cc.FadeTo = cc.ActionInterval.extend(/** @lends cc.FadeTo# */{
- _toOpacity:0,
- _fromOpacity:0,
+ _toOpacity: 0,
+ _fromOpacity: 0,
- /**
+ /**
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * @param {Number} duration
- * @param {Number} opacity 0-255, 0 is transparent
- */
- ctor:function (duration, opacity) {
+ * @param {Number} duration
+ * @param {Number} opacity 0-255, 0 is transparent
+ */
+ ctor: function (duration, opacity) {
cc.ActionInterval.prototype.ctor.call(this);
- opacity !== undefined && this.initWithDuration(duration, opacity);
+ opacity !== undefined && this.initWithDuration(duration, opacity);
},
/**
@@ -2614,7 +2637,7 @@ cc.FadeTo = cc.ActionInterval.extend(/** @lends cc.FadeTo# */{
* @param {Number} opacity
* @return {Boolean}
*/
- initWithDuration:function (duration, opacity) {
+ initWithDuration: function (duration, opacity) {
if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
this._toOpacity = opacity;
return true;
@@ -2626,7 +2649,7 @@ cc.FadeTo = cc.ActionInterval.extend(/** @lends cc.FadeTo# */{
* returns a new clone of the action
* @returns {cc.FadeTo}
*/
- clone:function () {
+ clone: function () {
var action = new cc.FadeTo();
this._cloneDecoration(action);
action.initWithDuration(this._duration, this._toOpacity);
@@ -2637,18 +2660,17 @@ cc.FadeTo = cc.ActionInterval.extend(/** @lends cc.FadeTo# */{
* Called once per frame. Time is the number of seconds of a frame interval.
* @param {Number} time time in seconds
*/
- update:function (time) {
+ update: function (time) {
time = this._computeEaseTime(time);
var fromOpacity = this._fromOpacity !== undefined ? this._fromOpacity : 255;
this.target.opacity = fromOpacity + (this._toOpacity - fromOpacity) * time;
-
},
/**
* Start this action with target.
* @param {cc.Node} target
*/
- startWithTarget:function (target) {
+ startWithTarget: function (target) {
cc.ActionInterval.prototype.startWithTarget.call(this, target);
this._fromOpacity = target.opacity;
}
@@ -2691,16 +2713,18 @@ cc.FadeIn = cc.FadeTo.extend(/** @lends cc.FadeIn# */{
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
* @param {Number} duration duration in seconds
*/
- ctor:function (duration) {
+ ctor: function (duration) {
cc.FadeTo.prototype.ctor.call(this);
- duration && this.initWithDuration(duration, 255);
+ if (duration == null)
+ duration = 0;
+ this.initWithDuration(duration, 255);
},
/**
* Returns a reversed action.
* @return {cc.FadeOut}
*/
- reverse:function () {
+ reverse: function () {
var action = new cc.FadeOut();
action.initWithDuration(this._duration, 0);
this._cloneDecoration(action);
@@ -2712,7 +2736,7 @@ cc.FadeIn = cc.FadeTo.extend(/** @lends cc.FadeIn# */{
* returns a new clone of the action
* @returns {cc.FadeIn}
*/
- clone:function () {
+ clone: function () {
var action = new cc.FadeIn();
this._cloneDecoration(action);
action.initWithDuration(this._duration, this._toOpacity);
@@ -2723,8 +2747,8 @@ cc.FadeIn = cc.FadeTo.extend(/** @lends cc.FadeIn# */{
* Start the action with target.
* @param {cc.Node} target
*/
- startWithTarget:function (target) {
- if(this._reverseAction)
+ startWithTarget: function (target) {
+ if (this._reverseAction)
this._toOpacity = this._reverseAction._fromOpacity;
cc.FadeTo.prototype.startWithTarget.call(this, target);
}
@@ -2765,16 +2789,18 @@ cc.FadeOut = cc.FadeTo.extend(/** @lends cc.FadeOut# */{
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
* @param {Number} duration duration in seconds
*/
- ctor:function (duration) {
+ ctor: function (duration) {
cc.FadeTo.prototype.ctor.call(this);
- duration && this.initWithDuration(duration, 0);
+ if (duration == null)
+ duration = 0;
+ this.initWithDuration(duration, 0);
},
/**
* Returns a reversed action.
* @return {cc.FadeIn}
*/
- reverse:function () {
+ reverse: function () {
var action = new cc.FadeIn();
action._reverseAction = this;
action.initWithDuration(this._duration, 255);
@@ -2787,7 +2813,7 @@ cc.FadeOut = cc.FadeTo.extend(/** @lends cc.FadeOut# */{
* returns a new clone of the action
* @returns {cc.FadeOut}
*/
- clone:function () {
+ clone: function () {
var action = new cc.FadeOut();
this._cloneDecoration(action);
action.initWithDuration(this._duration, this._toOpacity);
@@ -2829,22 +2855,22 @@ cc.FadeOut.create = cc.fadeOut;
* var action = new cc.TintTo(2, 255, 0, 255);
*/
cc.TintTo = cc.ActionInterval.extend(/** @lends cc.TintTo# */{
- _to:null,
- _from:null,
+ _to: null,
+ _from: null,
- /**
+ /**
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * @param {Number} duration
- * @param {Number} red 0-255
- * @param {Number} green 0-255
- * @param {Number} blue 0-255
- */
- ctor:function (duration, red, green, blue) {
+ * @param {Number} duration
+ * @param {Number} red 0-255
+ * @param {Number} green 0-255
+ * @param {Number} blue 0-255
+ */
+ ctor: function (duration, red, green, blue) {
cc.ActionInterval.prototype.ctor.call(this);
this._to = cc.color(0, 0, 0);
this._from = cc.color(0, 0, 0);
- blue !== undefined && this.initWithDuration(duration, red, green, blue);
+ blue !== undefined && this.initWithDuration(duration, red, green, blue);
},
/**
@@ -2855,7 +2881,7 @@ cc.TintTo = cc.ActionInterval.extend(/** @lends cc.TintTo# */{
* @param {Number} blue 0-255
* @return {Boolean}
*/
- initWithDuration:function (duration, red, green, blue) {
+ initWithDuration: function (duration, red, green, blue) {
if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
this._to = cc.color(red, green, blue);
return true;
@@ -2867,7 +2893,7 @@ cc.TintTo = cc.ActionInterval.extend(/** @lends cc.TintTo# */{
* returns a new clone of the action
* @returns {cc.TintTo}
*/
- clone:function () {
+ clone: function () {
var action = new cc.TintTo();
this._cloneDecoration(action);
var locTo = this._to;
@@ -2879,7 +2905,7 @@ cc.TintTo = cc.ActionInterval.extend(/** @lends cc.TintTo# */{
* Start the action with target.
* @param {cc.Node} target
*/
- startWithTarget:function (target) {
+ startWithTarget: function (target) {
cc.ActionInterval.prototype.startWithTarget.call(this, target);
this._from = this.target.color;
@@ -2889,13 +2915,16 @@ cc.TintTo = cc.ActionInterval.extend(/** @lends cc.TintTo# */{
* Called once per frame. Time is the number of seconds of a frame interval.
* @param {Number} dt time in seconds
*/
- update:function (dt) {
+ update: function (dt) {
dt = this._computeEaseTime(dt);
var locFrom = this._from, locTo = this._to;
if (locFrom) {
- this.target.color = cc.color(locFrom.r + (locTo.r - locFrom.r) * dt,
- locFrom.g + (locTo.g - locFrom.g) * dt,
- locFrom.b + (locTo.b - locFrom.b) * dt);
+ this.target.setColor(
+ cc.color(
+ locFrom.r + (locTo.r - locFrom.r) * dt,
+ locFrom.g + (locTo.g - locFrom.g) * dt,
+ locFrom.b + (locTo.b - locFrom.b) * dt)
+ );
}
}
});
@@ -2941,24 +2970,24 @@ cc.TintTo.create = cc.tintTo;
* var action = new cc.TintBy(2, -127, -255, -127);
*/
cc.TintBy = cc.ActionInterval.extend(/** @lends cc.TintBy# */{
- _deltaR:0,
- _deltaG:0,
- _deltaB:0,
+ _deltaR: 0,
+ _deltaG: 0,
+ _deltaB: 0,
- _fromR:0,
- _fromG:0,
- _fromB:0,
+ _fromR: 0,
+ _fromG: 0,
+ _fromB: 0,
- /**
+ /**
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * @param {Number} duration duration in seconds
- * @param {Number} deltaRed
- * @param {Number} deltaGreen
- * @param {Number} deltaBlue
- */
- ctor:function (duration, deltaRed, deltaGreen, deltaBlue) {
+ * @param {Number} duration duration in seconds
+ * @param {Number} deltaRed
+ * @param {Number} deltaGreen
+ * @param {Number} deltaBlue
+ */
+ ctor: function (duration, deltaRed, deltaGreen, deltaBlue) {
cc.ActionInterval.prototype.ctor.call(this);
- deltaBlue !== undefined && this.initWithDuration(duration, deltaRed, deltaGreen, deltaBlue);
+ deltaBlue !== undefined && this.initWithDuration(duration, deltaRed, deltaGreen, deltaBlue);
},
/**
@@ -2969,7 +2998,7 @@ cc.TintBy = cc.ActionInterval.extend(/** @lends cc.TintBy# */{
* @param {Number} deltaBlue 0-255
* @return {Boolean}
*/
- initWithDuration:function (duration, deltaRed, deltaGreen, deltaBlue) {
+ initWithDuration: function (duration, deltaRed, deltaGreen, deltaBlue) {
if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
this._deltaR = deltaRed;
this._deltaG = deltaGreen;
@@ -2983,7 +3012,7 @@ cc.TintBy = cc.ActionInterval.extend(/** @lends cc.TintBy# */{
* returns a new clone of the action
* @returns {cc.TintBy}
*/
- clone:function () {
+ clone: function () {
var action = new cc.TintBy();
this._cloneDecoration(action);
action.initWithDuration(this._duration, this._deltaR, this._deltaG, this._deltaB);
@@ -2994,7 +3023,7 @@ cc.TintBy = cc.ActionInterval.extend(/** @lends cc.TintBy# */{
* Start the action with target.
* @param {cc.Node} target
*/
- startWithTarget:function (target) {
+ startWithTarget: function (target) {
cc.ActionInterval.prototype.startWithTarget.call(this, target);
var color = target.color;
@@ -3008,12 +3037,12 @@ cc.TintBy = cc.ActionInterval.extend(/** @lends cc.TintBy# */{
* Called once per frame. Time is the number of seconds of a frame interval.
* @param {Number} dt time in seconds
*/
- update:function (dt) {
+ update: function (dt) {
dt = this._computeEaseTime(dt);
this.target.color = cc.color(this._fromR + this._deltaR * dt,
- this._fromG + this._deltaG * dt,
- this._fromB + this._deltaB * dt);
+ this._fromG + this._deltaG * dt,
+ this._fromB + this._deltaB * dt);
},
@@ -3021,7 +3050,7 @@ cc.TintBy = cc.ActionInterval.extend(/** @lends cc.TintBy# */{
* Returns a reversed action.
* @return {cc.TintBy}
*/
- reverse:function () {
+ reverse: function () {
var action = new cc.TintBy(this._duration, -this._deltaR, -this._deltaG, -this._deltaB);
this._cloneDecoration(action);
this._reverseEaseList(action);
@@ -3069,13 +3098,14 @@ cc.DelayTime = cc.ActionInterval.extend(/** @lends cc.DelayTime# */{
* Will be overwrite.
* @param {Number} dt time in seconds
*/
- update:function (dt) {},
+ update: function (dt) {
+ },
/**
* Returns a reversed action.
* @return {cc.DelayTime}
*/
- reverse:function () {
+ reverse: function () {
var action = new cc.DelayTime(this._duration);
this._cloneDecoration(action);
this._reverseEaseList(action);
@@ -3086,7 +3116,7 @@ cc.DelayTime = cc.ActionInterval.extend(/** @lends cc.DelayTime# */{
* returns a new clone of the action
* @returns {cc.DelayTime}
*/
- clone:function () {
+ clone: function () {
var action = new cc.DelayTime();
this._cloneDecoration(action);
action.initWithDuration(this._duration);
@@ -3130,28 +3160,28 @@ cc.DelayTime.create = cc.delayTime;
* var reverse = new cc.ReverseTime(this);
*/
cc.ReverseTime = cc.ActionInterval.extend(/** @lends cc.ReverseTime# */{
- _other:null,
+ _other: null,
- /**
+ /**
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * @param {cc.FiniteTimeAction} action
- */
- ctor:function (action) {
+ * @param {cc.FiniteTimeAction} action
+ */
+ ctor: function (action) {
cc.ActionInterval.prototype.ctor.call(this);
this._other = null;
- action && this.initWithAction(action);
+ action && this.initWithAction(action);
},
/**
* @param {cc.FiniteTimeAction} action
* @return {Boolean}
*/
- initWithAction:function (action) {
- if(!action)
- throw "cc.ReverseTime.initWithAction(): action must be non null";
- if(action == this._other)
- throw "cc.ReverseTime.initWithAction(): the action was already passed in.";
+ initWithAction: function (action) {
+ if (!action)
+ throw new Error("cc.ReverseTime.initWithAction(): action must be non null");
+ if (action === this._other)
+ throw new Error("cc.ReverseTime.initWithAction(): the action was already passed in.");
if (cc.ActionInterval.prototype.initWithDuration.call(this, action._duration)) {
// Don't leak if action is reused
@@ -3165,7 +3195,7 @@ cc.ReverseTime = cc.ActionInterval.extend(/** @lends cc.ReverseTime# */{
* returns a new clone of the action
* @returns {cc.ReverseTime}
*/
- clone:function () {
+ clone: function () {
var action = new cc.ReverseTime();
this._cloneDecoration(action);
action.initWithAction(this._other.clone());
@@ -3176,7 +3206,7 @@ cc.ReverseTime = cc.ActionInterval.extend(/** @lends cc.ReverseTime# */{
* Start the action with target.
* @param {cc.Node} target
*/
- startWithTarget:function (target) {
+ startWithTarget: function (target) {
cc.ActionInterval.prototype.startWithTarget.call(this, target);
this._other.startWithTarget(target);
},
@@ -3185,7 +3215,7 @@ cc.ReverseTime = cc.ActionInterval.extend(/** @lends cc.ReverseTime# */{
* Called once per frame. Time is the number of seconds of a frame interval.
* @param {Number} dt time in seconds
*/
- update:function (dt) {
+ update: function (dt) {
dt = this._computeEaseTime(dt);
if (this._other)
this._other.update(1 - dt);
@@ -3195,14 +3225,14 @@ cc.ReverseTime = cc.ActionInterval.extend(/** @lends cc.ReverseTime# */{
* Returns a reversed action.
* @return {cc.ActionInterval}
*/
- reverse:function () {
+ reverse: function () {
return this._other.clone();
},
/**
* Stop the action
*/
- stop:function () {
+ stop: function () {
this._other.stop();
cc.Action.prototype.stop.call(this);
}
@@ -3240,45 +3270,54 @@ cc.ReverseTime.create = cc.reverseTime;
* var anim = new cc.Animate(dance_grey);
*/
cc.Animate = cc.ActionInterval.extend(/** @lends cc.Animate# */{
- _animation:null,
- _nextFrame:0,
- _origFrame:null,
- _executedLoops:0,
- _splitTimes:null,
+ _animation: null,
+ _nextFrame: 0,
+ _origFrame: null,
+ _executedLoops: 0,
+ _splitTimes: null,
+ _currFrameIndex: 0,
- /**
+ /**
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * create the animate with animation.
- * @param {cc.Animation} animation
- */
- ctor:function (animation) {
+ * create the animate with animation.
+ * @param {cc.Animation} animation
+ */
+ ctor: function (animation) {
cc.ActionInterval.prototype.ctor.call(this);
this._splitTimes = [];
- animation && this.initWithAnimation(animation);
+ animation && this.initWithAnimation(animation);
},
/**
* @return {cc.Animation}
*/
- getAnimation:function () {
+ getAnimation: function () {
return this._animation;
},
/**
* @param {cc.Animation} animation
*/
- setAnimation:function (animation) {
+ setAnimation: function (animation) {
this._animation = animation;
},
+ /**
+ * Gets the index of sprite frame currently displayed.
+ * @return {Number}
+ */
+ getCurrentFrameIndex: function () {
+ return this._currFrameIndex;
+ },
+
/**
* @param {cc.Animation} animation
* @return {Boolean}
*/
- initWithAnimation:function (animation) {
- if(!animation)
- throw "cc.Animate.initWithAnimation(): animation must be non-NULL";
+ initWithAnimation: function (animation) {
+ if (!animation)
+ throw new Error("cc.Animate.initWithAnimation(): animation must be non-NULL");
var singleDuration = animation.getDuration();
if (this.initWithDuration(singleDuration * animation.getLoops())) {
this._nextFrame = 0;
@@ -3310,7 +3349,7 @@ cc.Animate = cc.ActionInterval.extend(/** @lends cc.Animate# */{
* returns a new clone of the action
* @returns {cc.Animate}
*/
- clone:function () {
+ clone: function () {
var action = new cc.Animate();
this._cloneDecoration(action);
action.initWithAnimation(this._animation.clone());
@@ -3321,10 +3360,10 @@ cc.Animate = cc.ActionInterval.extend(/** @lends cc.Animate# */{
* Start the action with target.
* @param {cc.Sprite} target
*/
- startWithTarget:function (target) {
+ startWithTarget: function (target) {
cc.ActionInterval.prototype.startWithTarget.call(this, target);
if (this._animation.getRestoreOriginalFrame())
- this._origFrame = target.displayFrame();
+ this._origFrame = target.getSpriteFrame();
this._nextFrame = 0;
this._executedLoops = 0;
},
@@ -3333,7 +3372,7 @@ cc.Animate = cc.ActionInterval.extend(/** @lends cc.Animate# */{
* Called once per frame. Time is the number of seconds of a frame interval.
* @param {Number} dt
*/
- update:function (dt) {
+ update: function (dt) {
dt = this._computeEaseTime(dt);
// if t==1, ignore. Animation should finish with t==1
if (dt < 1.0) {
@@ -3354,7 +3393,8 @@ cc.Animate = cc.ActionInterval.extend(/** @lends cc.Animate# */{
var numberOfFrames = frames.length, locSplitTimes = this._splitTimes;
for (var i = this._nextFrame; i < numberOfFrames; i++) {
if (locSplitTimes[i] <= dt) {
- this.target.setSpriteFrame(frames[i].getSpriteFrame());
+ _currFrameIndex = i;
+ this.target.setSpriteFrame(frames[_currFrameIndex].getSpriteFrame());
this._nextFrame = i + 1;
} else {
// Issue 1438. Could be more than one frame per tick, due to low frame rate or frame delta < 1/FPS
@@ -3367,7 +3407,7 @@ cc.Animate = cc.ActionInterval.extend(/** @lends cc.Animate# */{
* Returns a reversed action.
* @return {cc.Animate}
*/
- reverse:function () {
+ reverse: function () {
var locAnimation = this._animation;
var oldArray = locAnimation.getFrames();
var newArray = [];
@@ -3392,7 +3432,7 @@ cc.Animate = cc.ActionInterval.extend(/** @lends cc.Animate# */{
/**
* stop the action
*/
- stop:function () {
+ stop: function () {
if (this._animation.getRestoreOriginalFrame() && this.target)
this.target.setSpriteFrame(this._origFrame);
cc.Action.prototype.stop.call(this);
@@ -3433,18 +3473,18 @@ cc.Animate.create = cc.animate;
* @param {cc.FiniteTimeAction} action
*/
cc.TargetedAction = cc.ActionInterval.extend(/** @lends cc.TargetedAction# */{
- _action:null,
- _forcedTarget:null,
+ _action: null,
+ _forcedTarget: null,
- /**
+ /**
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * Create an action with the specified action and forced target.
- * @param {cc.Node} target
- * @param {cc.FiniteTimeAction} action
- */
+ * Create an action with the specified action and forced target.
+ * @param {cc.Node} target
+ * @param {cc.FiniteTimeAction} action
+ */
ctor: function (target, action) {
cc.ActionInterval.prototype.ctor.call(this);
- action && this.initWithTarget(target, action);
+ action && this.initWithTarget(target, action);
},
/**
@@ -3453,7 +3493,7 @@ cc.TargetedAction = cc.ActionInterval.extend(/** @lends cc.TargetedAction# */{
* @param {cc.FiniteTimeAction} action
* @return {Boolean}
*/
- initWithTarget:function (target, action) {
+ initWithTarget: function (target, action) {
if (this.initWithDuration(action._duration)) {
this._forcedTarget = target;
this._action = action;
@@ -3466,7 +3506,7 @@ cc.TargetedAction = cc.ActionInterval.extend(/** @lends cc.TargetedAction# */{
* returns a new clone of the action
* @returns {cc.TargetedAction}
*/
- clone:function () {
+ clone: function () {
var action = new cc.TargetedAction();
this._cloneDecoration(action);
action.initWithTarget(this._forcedTarget, this._action.clone());
@@ -3477,7 +3517,7 @@ cc.TargetedAction = cc.ActionInterval.extend(/** @lends cc.TargetedAction# */{
* Start the action with target.
* @param {cc.Node} target
*/
- startWithTarget:function (target) {
+ startWithTarget: function (target) {
cc.ActionInterval.prototype.startWithTarget.call(this, target);
this._action.startWithTarget(this._forcedTarget);
},
@@ -3485,7 +3525,7 @@ cc.TargetedAction = cc.ActionInterval.extend(/** @lends cc.TargetedAction# */{
/**
* stop the action
*/
- stop:function () {
+ stop: function () {
this._action.stop();
},
@@ -3493,7 +3533,7 @@ cc.TargetedAction = cc.ActionInterval.extend(/** @lends cc.TargetedAction# */{
* Called once per frame. Time is the number of seconds of a frame interval.
* @param {Number} dt
*/
- update:function (dt) {
+ update: function (dt) {
dt = this._computeEaseTime(dt);
this._action.update(dt);
},
@@ -3502,7 +3542,7 @@ cc.TargetedAction = cc.ActionInterval.extend(/** @lends cc.TargetedAction# */{
* return the target that the action will be forced to run with
* @return {cc.Node}
*/
- getForcedTarget:function () {
+ getForcedTarget: function () {
return this._forcedTarget;
},
@@ -3510,8 +3550,8 @@ cc.TargetedAction = cc.ActionInterval.extend(/** @lends cc.TargetedAction# */{
* set the target that the action will be forced to run with
* @param {cc.Node} forcedTarget
*/
- setForcedTarget:function (forcedTarget) {
- if (this._forcedTarget != forcedTarget)
+ setForcedTarget: function (forcedTarget) {
+ if (this._forcedTarget !== forcedTarget)
this._forcedTarget = forcedTarget;
}
});
diff --git a/cocos2d/actions/CCActionTween.js b/cocos2d/actions/CCActionTween.js
index 12490a4146..daa6c368d1 100644
--- a/cocos2d/actions/CCActionTween.js
+++ b/cocos2d/actions/CCActionTween.js
@@ -36,7 +36,8 @@ cc.ActionTweenDelegate = cc.Class.extend(/** @lends cc.ActionTweenDelegate */{
* @param value
* @param key
*/
- updateTweenAction:function(value, key){}
+ updateTweenAction: function (value, key) {
+ }
});
/**
@@ -60,24 +61,24 @@ cc.ActionTweenDelegate = cc.Class.extend(/** @lends cc.ActionTweenDelegate */{
* @param {Number} to
*/
cc.ActionTween = cc.ActionInterval.extend(/** @lends cc.ActionTween */{
- key:"",
- from:0,
- to:0,
- delta:0,
+ key: "",
+ from: 0,
+ to: 0,
+ delta: 0,
- /**
+ /**
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * Creates an initializes the action with the property name (key), and the from and to parameters.
- * @param {Number} duration
- * @param {String} key
- * @param {Number} from
- * @param {Number} to
- */
- ctor:function(duration, key, from, to){
+ * Creates an initializes the action with the property name (key), and the from and to parameters.
+ * @param {Number} duration
+ * @param {String} key
+ * @param {Number} from
+ * @param {Number} to
+ */
+ ctor: function (duration, key, from, to) {
cc.ActionInterval.prototype.ctor.call(this);
this.key = "";
- to !== undefined && this.initWithDuration(duration, key, from, to);
+ to !== undefined && this.initWithDuration(duration, key, from, to);
},
/**
@@ -88,7 +89,7 @@ cc.ActionTween = cc.ActionInterval.extend(/** @lends cc.ActionTween */{
* @param {Number} to
* @return {Boolean}
*/
- initWithDuration:function (duration, key, from, to) {
+ initWithDuration: function (duration, key, from, to) {
if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
this.key = key;
this.to = to;
@@ -102,9 +103,9 @@ cc.ActionTween = cc.ActionInterval.extend(/** @lends cc.ActionTween */{
* Start this tween with target.
* @param {cc.ActionTweenDelegate} target
*/
- startWithTarget:function (target) {
- if(!target || !target.updateTweenAction)
- throw "cc.ActionTween.startWithTarget(): target must be non-null, and target must implement updateTweenAction function";
+ startWithTarget: function (target) {
+ if (!target || !target.updateTweenAction)
+ throw new Error("cc.ActionTween.startWithTarget(): target must be non-null, and target must implement updateTweenAction function");
cc.ActionInterval.prototype.startWithTarget.call(this, target);
this.delta = this.to - this.from;
},
@@ -114,7 +115,7 @@ cc.ActionTween = cc.ActionInterval.extend(/** @lends cc.ActionTween */{
*
* @param {Number} dt
*/
- update:function (dt) {
+ update: function (dt) {
this.target.updateTweenAction(this.to - this.delta * (1 - dt), this.key);
},
@@ -122,7 +123,7 @@ cc.ActionTween = cc.ActionInterval.extend(/** @lends cc.ActionTween */{
* returns a reversed action.
* @return {cc.ActionTween}
*/
- reverse:function () {
+ reverse: function () {
return new cc.ActionTween(this.duration, this.key, this.to, this.from);
},
@@ -132,7 +133,7 @@ cc.ActionTween = cc.ActionInterval.extend(/** @lends cc.ActionTween */{
*
* @return {cc.ActionTween}
*/
- clone:function(){
+ clone: function () {
var action = new cc.ActionTween();
action.initWithDuration(this._duration, this.key, this.from, this.to);
return action;
@@ -163,4 +164,4 @@ cc.actionTween = function (duration, key, from, to) {
* @param {Number} to
* @return {cc.ActionTween}
*/
-cc.ActionTween.create = cc.actionTween;
\ No newline at end of file
+cc.ActionTween.create = cc.actionTween;
diff --git a/cocos2d/actions3d/CCActionGrid.js b/cocos2d/actions3d/CCActionGrid.js
index b29947eb42..61b90a1454 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.
@@ -40,18 +41,22 @@ cc.GridAction = cc.ActionInterval.extend(/** @lends cc.GridAction# */{
* @param {cc.Size} gridSize
*/
ctor:function(duration, gridSize){
- cc._checkWebGLRenderMode();
+ cc.sys._checkWebGLRenderMode();
cc.ActionInterval.prototype.ctor.call(this);
this._gridSize = cc.size(0,0);
- gridSize && this.initWithDuration(duration, gridSize);
+ gridSize && this.initWithDuration(duration, gridSize);
+ },
+
+ _cacheTargetAsGridNode:function (target) {
+ this._gridNodeTarget = target;
},
/**
* to copy object with deep copy.
* returns a clone of action.
*
- * @return {cc.Action}
+ * @return {cc.ActionInterval}
*/
clone:function(){
var action = new cc.GridAction();
@@ -68,18 +73,20 @@ cc.GridAction = cc.ActionInterval.extend(/** @lends cc.GridAction# */{
startWithTarget:function (target) {
cc.ActionInterval.prototype.startWithTarget.call(this, target);
cc.renderer.childrenOrderDirty = true;
+ this._cacheTargetAsGridNode(target);
+
var newGrid = this.getGrid();
- var t = this.target;
- var targetGrid = t.grid;
+
+ var targetGrid = this._gridNodeTarget.getGrid();
if (targetGrid && targetGrid.getReuseGrid() > 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())
targetGrid.setActive(false);
- t.grid = newGrid;
- t.grid.setActive(true);
+ this._gridNodeTarget.setGrid(newGrid);
+ this._gridNodeTarget.getGrid().setActive(true);
}
},
@@ -151,24 +158,52 @@ cc.Grid3DAction = cc.GridAction.extend(/** @lends cc.Grid3DAction# */{
* @return {cc.Grid3D}
*/
getGrid:function () {
- return new cc.Grid3D(this._gridSize);
+ return new cc.Grid3D(this._gridSize, undefined, undefined, this._gridNodeTarget.getGridRect());
},
/**
- * returns the vertex than belongs to certain position in the grid
+ * get rect of the grid
+ * @return {cc.Rect} rect
+ */
+ getGridRect:function () {
+ return this._gridNodeTarget.getGridRect();
+ },
+
+ /**
+ * 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 that 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 +246,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);
},
@@ -242,7 +297,7 @@ cc.TiledGrid3DAction = cc.GridAction.extend(/** @lends cc.TiledGrid3DAction# */{
* @return {cc.TiledGrid3D}
*/
getGrid:function () {
- return new cc.TiledGrid3D(this._gridSize);
+ return new cc.TiledGrid3D(this._gridSize, undefined, undefined, this._gridNodeTarget.getGridRect());
}
});
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/CCActionPageTurn3D.js b/cocos2d/actions3d/CCActionPageTurn3D.js
index 367531662c..ae7313b2dd 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, undefined, undefined, this._gridNodeTarget.getGridRect());
+ 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
@@ -45,8 +57,9 @@ cc.PageTurn3D = cc.Grid3DAction.extend(/** @lends cc.PageTurn3D# */{
var deltaAy = (tt * tt * 500);
var ay = -100 - deltaAy;
- var deltaTheta = -Math.PI / 2 * Math.sqrt(time);
- var theta = /*0.01f */ +Math.PI / 2 + deltaTheta;
+ var deltaTheta = Math.sqrt(time);
+ var theta = deltaTheta>0.5?Math.PI/2 *deltaTheta : Math.PI/2*(1-deltaTheta);
+ var rotateByYAxis = (2-time)*Math.PI;
var sinTheta = Math.sin(theta);
var cosTheta = Math.cos(theta);
@@ -58,8 +71,9 @@ 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);
+ p.x -= this.getGridRect().x;
var R = Math.sqrt((p.x * p.x) + ((p.y - ay) * (p.y - ay)));
var r = R * sinTheta;
var alpha = Math.asin(p.x / R);
@@ -77,14 +91,17 @@ cc.PageTurn3D = cc.Grid3DAction.extend(/** @lends cc.PageTurn3D# */{
// We scale z here to avoid the animation being
// too much bigger than the screen due to perspectve transform
- p.z = (r * ( 1 - cosBeta ) * cosTheta) / 7;// "100" didn't work for
-
+ p.z = (r * ( 1 - cosBeta ) * cosTheta);// "100" didn't work for
+ p.x = p.z * Math.sin(rotateByYAxis) + p.x * Math.cos(rotateByYAxis);
+ p.z = p.z * Math.cos(rotateByYAxis) - p.x * Math.cos(rotateByYAxis);
+ p.z/= 7;
// Stop z coord from dropping beneath underlying page in a transition
// issue #751
if (p.z < 0.5)
p.z = 0.5;
// Set new coords
+ p.x+= this.getGridRect().x;
this.setVertex(locVer, p);
}
}
diff --git a/cocos2d/actions3d/CCActionTiledGrid.js b/cocos2d/actions3d/CCActionTiledGrid.js
index ff9b42e6be..67dffc5aa4 100644
--- a/cocos2d/actions3d/CCActionTiledGrid.js
+++ b/cocos2d/actions3d/CCActionTiledGrid.js
@@ -451,15 +451,16 @@ cc.ShuffleTiles.create = cc.shuffleTiles;
cc.FadeOutTRTiles = cc.TiledGrid3DAction.extend(/** @lends cc.FadeOutTRTiles# */{
/**
* Test function
- * @param {cc.Size} pos
+ * @param {cc.Point} pos
* @param {Number} time
*/
testFunc:function (pos, time) {
var locX = this._gridSize.width * time;
var locY = this._gridSize.height * time;
- if ((locX + locY) == 0.0)
+ if (locX === this._gridSize.width && locY === this._gridSize.height) return 0.0;
+ if ((locX + locY) === 0.0)
return 1.0;
- return Math.pow((pos.width + pos.height) / (locX + locY), 6);
+ return Math.pow((pos.x + pos.y) / (locX + locY), 6);
},
/**
@@ -508,15 +509,13 @@ cc.FadeOutTRTiles = cc.TiledGrid3DAction.extend(/** @lends cc.FadeOutTRTiles# */
*/
update:function (dt) {
var locGridSize = this._gridSize;
- var locPos = cc.p(0, 0), locSize = cc.size(0, 0), distance;
+ var locPos = cc.p(0, 0), distance;
for (var i = 0; i < locGridSize.width; ++i) {
for (var j = 0; j < locGridSize.height; ++j) {
locPos.x = i;
locPos.y = j;
- locSize.width = i;
- locSize.height = j;
- distance = this.testFunc(locSize, dt);
- if (distance == 0)
+ distance = this.testFunc(locPos, dt);
+ if (distance === 0)
this.turnOffTile(locPos);
else if (distance < 1)
this.transformTile(locPos, distance);
@@ -560,16 +559,18 @@ cc.FadeOutTRTiles.create = cc.fadeOutTRTiles;
cc.FadeOutBLTiles = cc.FadeOutTRTiles.extend(/** @lends cc.FadeOutBLTiles# */{
/**
* Test function
- * @param {cc.Size} pos
+ * @param {cc.Point} pos
* @param {Number} time
*/
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 ((locX + locY) === 0)
+ return 0.0;
+ if ((pos.x + pos.y) === 0)
return 1.0;
- return Math.pow((locX + locY) / (pos.width + pos.height), 6);
+ return Math.pow((locX + locY) / (pos.x + pos.y), 6);
}
});
@@ -604,11 +605,16 @@ cc.FadeOutBLTiles.create = cc.fadeOutBLTiles;
* @extends cc.FadeOutTRTiles
*/
cc.FadeOutUpTiles = cc.FadeOutTRTiles.extend(/** @lends cc.FadeOutUpTiles# */{
+ /**
+ * Test function
+ * @param {cc.Point} pos
+ * @param {Number} time
+ */
testFunc:function (pos, time) {
var locY = this._gridSize.height * time;
- if (locY == 0.0)
- return 1.0;
- return Math.pow(pos.height / locY, 6);
+ if( locY === this._gridSize.height) return 0.0;
+ if (locY === 0.0) return 1.0;
+ return Math.pow(pos.y / locY, 6);
},
transformTile:function (pos, distance) {
@@ -655,11 +661,16 @@ cc.FadeOutUpTiles.create = cc.fadeOutUpTiles;
* @extends cc.FadeOutUpTiles
*/
cc.FadeOutDownTiles = cc.FadeOutUpTiles.extend(/** @lends cc.FadeOutDownTiles# */{
+ /**
+ * Test function
+ * @param {cc.Point} pos
+ * @param {Number} time
+ */
testFunc:function (pos, time) {
var locY = this._gridSize.height * (1.0 - time);
- if (pos.height == 0)
- return 1.0;
- return Math.pow(locY / pos.height, 6);
+ if( locY === 0.0 ) return 0.0;
+ if (pos.y === 0) return 1.0;
+ return Math.pow(locY / pos.y, 6);
}
});
@@ -1057,7 +1068,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 +1161,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 +1252,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 a0bf2f8a71..7762bf4d02 100644
--- a/cocos2d/audio/CCAudio.js
+++ b/cocos2d/audio/CCAudio.js
@@ -27,101 +27,53 @@
/**
* Audio support in the browser
*
- * multichannel : Multiple audio while playing - If it doesn't, you can only play background music
- * webAudio : Support for WebAudio - Support W3C WebAudio standards, all of the audio can be played
- * auto : Supports auto-play audio - if Don‘t support it, On a touch detecting background music canvas, and then replay
+ * MULTI_CHANNEL : Multiple audio while playing - If it doesn't, you can only play background music
+ * WEB_AUDIO : Support for WebAudio - Support W3C WebAudio standards, all of the audio can be played
+ * AUTOPLAY : Supports auto-play audio - if Don‘t support it, On a touch detecting background music canvas, and then replay
+ * REPLAY_AFTER_TOUCH : The first music will fail, must be replay after touchstart
+ * USE_EMPTIED_EVENT : Whether to use the emptied event to replace load callback
+ * DELAY_CREATE_CTX : delay created the context object - only webAudio
+ * NEED_MANUAL_LOOP : loop attribute failure, need to perform loop manually
*
* May be modifications for a few browser version
*/
-(function(){
+(function () {
var DEBUG = false;
var sys = cc.sys;
+ var version = sys.browserVersion;
- var supportTable = {
- "common" : {multichannel: true , webAudio: cc.sys._supportWebAudio , auto: true }
- };
+ // check if browser supports Web Audio
+ // check Web Audio's context
+ var supportWebAudio = !!(window.AudioContext || window.webkitAudioContext || window.mozAudioContext);
- // 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_BAIDU] = {multichannel: false, webAudio: false, auto: true };
- supportTable[sys.BROWSER_TYPE_UC] = {multichannel: true , webAudio: false, auto: true };
- supportTable[sys.BROWSER_TYPE_QQ] = {multichannel: false, webAudio: false, auto: true };
- supportTable[sys.BROWSER_TYPE_OUPENG] = {multichannel: false, webAudio: false, auto: false};
- supportTable[sys.BROWSER_TYPE_WECHAT] = {multichannel: false, webAudio: false, auto: false};
- supportTable[sys.BROWSER_TYPE_360] = {multichannel: false, webAudio: false, auto: true };
- supportTable[sys.BROWSER_TYPE_MIUI] = {multichannel: false, webAudio: false, auto: true };
-
- // APPLE //
- supportTable[sys.BROWSER_TYPE_SAFARI] = {multichannel: true , webAudio: true , auto: false};
-
- /* Determine the browser version number */
- var version, tmp;
- try{
- var ua = navigator.userAgent.toLowerCase();
- switch(sys.browserType){
- case sys.BROWSER_TYPE_IE:
- tmp = ua.match(/(msie |rv:)([\d.]+)/);
- break;
- case sys.BROWSER_TYPE_FIREFOX:
- tmp = ua.match(/(firefox\/|rv:)([\d.]+)/);
- break;
- case sys.BROWSER_TYPE_CHROME:
- tmp = ua.match(/chrome\/([\d.]+)/);
- break;
- case sys.BROWSER_TYPE_BAIDU:
- tmp = ua.match(/baidubrowser\/([\d.]+)/);
- break;
- case sys.BROWSER_TYPE_UC:
- tmp = ua.match(/ucbrowser\/([\d.]+)/);
- break;
- case sys.BROWSER_TYPE_QQ:
- tmp = ua.match(/qqbrowser\/([\d.]+)/);
- break;
- case sys.BROWSER_TYPE_OUPENG:
- tmp = ua.match(/oupeng\/([\d.]+)/);
- break;
- case sys.BROWSER_TYPE_WECHAT:
- tmp = ua.match(/micromessenger\/([\d.]+)/);
- break;
- case sys.BROWSER_TYPE_SAFARI:
- tmp = ua.match(/safari\/([\d.]+)/);
- break;
- }
- version = tmp ? tmp[1] : "";
- }catch(e){
- console.log(e);
+ var support = {ONLY_ONE: false, WEB_AUDIO: supportWebAudio, DELAY_CREATE_CTX: false, ONE_SOURCE: false};
+
+ if (sys.browserType === sys.BROWSER_TYPE_FIREFOX) {
+ support.DELAY_CREATE_CTX = true;
+ support.USE_LOADER_EVENT = 'canplay';
}
- ///////////////////////////
- // 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};
- }
- }
+ if (sys.os === sys.OS_IOS) {
+ support.USE_LOADER_EVENT = 'loadedmetadata';
}
- if(cc.sys.isMobile){
- cc.__audioSupport = supportTable[cc.sys.browserType] || supportTable["common"];
- }else{
- //Desktop support all
- cc.__audioSupport = supportTable["common"];
+ if (sys.os === sys.OS_ANDROID) {
+ if (sys.browserType === sys.BROWSER_TYPE_UC) {
+ support.ONE_SOURCE = true;
+ }
}
- if(DEBUG){
- setTimeout(function(){
+ window.__audioSupport = support;
+
+ if (DEBUG) {
+ setTimeout(function () {
cc.log("browse type: " + sys.browserType);
cc.log("browse version: " + version);
- cc.log("multichannel: " + cc.__audioSupport.multichannel);
- cc.log("webAudio: " + cc.__audioSupport.webAudio);
- cc.log("auto: " + cc.__audioSupport.auto);
+ cc.log("MULTI_CHANNEL: " + window.__audioSupport.MULTI_CHANNEL);
+ cc.log("WEB_AUDIO: " + window.__audioSupport.WEB_AUDIO);
+ cc.log("AUTOPLAY: " + window.__audioSupport.AUTOPLAY);
}, 0);
}
@@ -131,292 +83,259 @@
* Encapsulate DOM and webAudio
*/
cc.Audio = cc.Class.extend({
- //TODO Maybe loader shift in will be better
- volume: 1,
- loop: false,
+ interruptPlay: false,
src: null,
- _touch: false,
-
- _playing: false,
- _AUDIO_TYPE: "AUDIO",
- _pause: false,
-
- //Web Audio
- _buffer: null,
- _currentSource: null,
- _startTime: null,
- _currentTime: null,
- _context: null,
- _volume: null,
-
- //DOM Audio
_element: null,
+ _AUDIO_TYPE: "AUDIO",
- ctor: function(context, volume, url){
- context && (this._context = context);
- volume && (this._volume = volume);
- if(context && volume){
- this._AUDIO_TYPE = "WEBAUDIO";
- }
+ ctor: function (url) {
this.src = url;
},
- _setBufferCallback: null,
- setBuffer: function(buffer){
+ setBuffer: function (buffer) {
this._AUDIO_TYPE = "WEBAUDIO";
- this._buffer = buffer;
- if(this._playing)
- this.play();
-
- this._volume["gain"].value = this.volume;
- this._setBufferCallback && this._setBufferCallback(buffer);
+ this._element = new cc.Audio.WebAudio(buffer);
},
- _setElementCallback: null,
- setElement: function(element){
+ setElement: function (element) {
this._AUDIO_TYPE = "AUDIO";
this._element = element;
- if(this._playing)
- this.play();
- element.volume = this.volume;
- element.loop = this.loop;
- this._setElementCallback && this._setElementCallback(element);
+ // Prevent partial browser from playing after the end does not reset the paused tag
+ // Will cause the player to judge the status of the error
+ element.addEventListener('ended', function () {
+ if (!element.loop) {
+ element.paused = true;
+ }
+ });
},
- play: function(offset, loop){
- this._playing = true;
- this.loop = loop === undefined ? this.loop : (loop || false);
- if(this._AUDIO_TYPE === "AUDIO"){
- this._playOfAudio(offset);
- }else{
- this._playOfWebAudio(offset);
+ play: function (offset, loop) {
+ if (!this._element) {
+ this.interruptPlay = false;
+ return;
}
- },
-
- getPlaying: function(){
- if(!this._playing){
- return this._playing;
+ this._element.loop = loop;
+ this._element.play();
+ if (this._AUDIO_TYPE === 'AUDIO' && this._element.paused) {
+ this.stop();
+ cc.Audio.touchPlayList.push({ loop: loop, offset: offset, audio: this._element });
}
- if(this._AUDIO_TYPE === "AUDIO"){
- var audio = this._element;
- if(!audio || this._pause){
- this._playing = false;
- return false;
- }else if(audio.ended){
- this._playing = false;
- return false;
- }else
- return true;
- }else{
- var sourceNode = this._currentSource;
- if(!this._playing && !sourceNode)
- return true;
- if(sourceNode["playbackState"] == null)
- return this._playing;
- else
- return sourceNode["playbackState"] == 3;
+
+ if (cc.Audio.bindTouch === false) {
+ cc.Audio.bindTouch = true;
+ // Listen to the touchstart body event and play the audio when necessary.
+ cc.game.canvas.addEventListener('touchstart', cc.Audio.touchStart);
}
},
- _playOfWebAudio: function(offset){
- var cs = this._currentSource;
- if(!this._buffer){
+ getPlaying: function () {
+ if (!this._element) return true;
+ return !this._element.paused;
+ },
+
+ stop: function () {
+ if (!this._element) {
+ this.interruptPlay = true;
return;
}
- if(!this._pause && cs){
- if(this._currentTime + this._context.currentTime - this._startTime < this._currentSource.buffer.duration)
- return;
- else
- this._stopOfWebAudio();
+ this._element.pause();
+ try {
+ this._element.currentTime = 0;
+ } catch (err) {
}
- var audio = this._context["createBufferSource"]();
- audio.buffer = this._buffer;
- audio["connect"](this._volume);
- audio.loop = this.loop;
- this._startTime = this._context.currentTime;
- this._currentTime = 0;
-
- /*
- * Safari on iOS 6 only supports noteOn(), noteGrainOn(), and noteOff() now.(iOS 6.1.3)
- * The latest version of chrome has supported start() and stop()
- * start() & stop() are specified in the latest specification (written on 04/26/2013)
- * Reference: https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
- * noteOn(), noteGrainOn(), and noteOff() are specified in Draft 13 version (03/13/2012)
- * Reference: http://www.w3.org/2011/audio/drafts/2WD/Overview.html
- */
- if(audio.start){
- audio.start(0, offset || 0);
- }else if(audio["noteGrainOn"]){
- var duration = audio.buffer.duration;
- if (this.loop) {
- /*
- * On Safari on iOS 6, if loop == true, the passed in @param duration will be the duration from now on.
- * In other words, the sound will keep playing the rest of the music all the time.
- * On latest chrome desktop version, the passed in duration will only be the duration in this cycle.
- * Now that latest chrome would have start() method, it is prepared for iOS here.
- */
- audio["noteGrainOn"](0, offset, duration);
- } else {
- audio["noteGrainOn"](0, offset, duration - offset);
- }
- }else {
- // if only noteOn() is supported, resuming sound will NOT work
- audio["noteOn"](0);
- }
- this._currentSource = audio;
- var self = this;
- audio["onended"] = function(){
- self._playing = false;
- };
},
- _playOfAudio: function(){
- var audio = this._element;
- if(audio){
- audio.loop = this.loop;
- audio.play();
+ pause: function () {
+ if (!this._element) {
+ this.interruptPlay = true;
+ return;
}
+ this._element.pause();
},
- stop: function(){
- this._playing = false;
- if(this._AUDIO_TYPE === "AUDIO"){
- this._stopOfAudio();
- }else{
- this._stopOfWebAudio();
+ resume: function () {
+ if (!this._element) {
+ this.interruptPlay = false;
+ return;
}
+ this._element.play();
},
- _stopOfWebAudio: function(){
- var audio = this._currentSource;
- if(audio){
- audio.stop(0);
- this._currentSource = null;
- }
+ setVolume: function (volume) {
+ if (!this._element) return;
+ this._element.volume = volume;
},
- _stopOfAudio: function(){
- var audio = this._element;
- if(audio){
- audio.pause();
- if (audio.duration && audio.duration != Infinity)
- audio.currentTime = audio.duration;
- }
+ getVolume: function () {
+ if (!this._element) return;
+ return this._element.volume;
},
- pause: function(){
- this._playing = false;
- this._pause = true;
- if(this._AUDIO_TYPE === "AUDIO"){
- this._pauseOfAudio();
- }else{
- this._pauseOfWebAudio();
+ cloneNode: function () {
+ var audio = new cc.Audio(this.src);
+ if (this._AUDIO_TYPE === "AUDIO") {
+ var elem = document.createElement("audio");
+ var sources = elem.getElementsByTagName('source');
+ for (var i = 0; i < sources.length; i++) {
+ elem.appendChild(sources[i]);
+ }
+ elem.src = this.src;
+ audio.setElement(elem);
+ } else {
+ audio.setBuffer(this._element.buffer);
}
- },
+ return audio;
+ }
+});
- _pauseOfWebAudio: function(){
- this._currentTime += this._context.currentTime - this._startTime;
- var audio = this._currentSource;
- if(audio){
- audio.stop(0);
- }
- },
+cc.Audio.touchPlayList = [
+ //{ offset: 0, audio: audio }
+];
+
+cc.Audio.bindTouch = false;
+cc.Audio.touchStart = function () {
+ var list = cc.Audio.touchPlayList;
+ var item = null;
+ while (item = list.pop()) {
+ item.audio.loop = !!item.loop;
+ item.audio.play(item.offset);
+ }
+};
- _pauseOfAudio: function(){
- var audio = this._element;
- if(audio){
- audio.pause();
- }
+cc.Audio.WebAudio = function (buffer) {
+ this.buffer = buffer;
+ this.context = cc.Audio._context;
+
+ var volume = this.context['createGain']();
+ volume['gain'].value = 1;
+ volume['connect'](this.context['destination']);
+ this._volume = volume;
+
+ this._loop = false;
+
+ // The time stamp on the audio time axis when the recording begins to play.
+ this._startTime = -1;
+ // Record the currently playing Source
+ this._currentSource = null;
+ // Record the time has been played
+ this.playedLength = 0;
+
+ this._currextTimer = null;
+};
+
+cc.Audio.WebAudio.prototype = {
+ constructor: cc.Audio.WebAudio,
+
+ get paused() {
+ // If the current audio is a loop, then paused is false
+ if (this._currentSource && this._currentSource.loop)
+ return false;
+
+ // StartTime does not have value, as the default -1, it does not begin to play
+ if (this._startTime === -1)
+ return true;
+
+ // currentTime - startTime > durationTime
+ return this.context.currentTime - this._startTime > this.buffer.duration;
+ },
+ set paused(bool) {
},
- resume: function(){
- if(this._pause){
- if(this._AUDIO_TYPE === "AUDIO"){
- this._resumeOfAudio();
- }else{
- this._resumeOfWebAudio();
- }
- this._pause = false;
- this._playing = true;
- }
+ get loop() {
+ return this._loop;
+ },
+ set loop(bool) {
+ return this._loop = bool;
},
- _resumeOfWebAudio: function(){
- var audio = this._currentSource;
- if(audio){
- this._startTime = this._context.currentTime;
- var offset = this._currentTime % audio.buffer.duration;
- this._playOfWebAudio(offset);
- }
+ get volume() {
+ return this._volume['gain'].value;
+ },
+ set volume(num) {
+ return this._volume['gain'].value = num;
},
- _resumeOfAudio: function(){
- var audio = this._element;
- if(audio){
- audio.play();
- }
+ get currentTime() {
+ return this.playedLength;
+ },
+ set currentTime(num) {
+ return this.playedLength = num;
},
- setVolume: function(volume){
- if(volume > 1) volume = 1;
- if(volume < 0) volume = 0;
- this.volume = volume;
- if(this._AUDIO_TYPE === "AUDIO"){
- if(this._element){
- this._element.volume = volume;
- }
- }else{
- if(this._volume){
- this._volume["gain"].value = volume;
- }
+ play: function (offset) {
+
+ // If repeat play, you need to stop before an audio
+ if (this._currentSource && !this.paused) {
+ this._currentSource.stop(0);
+ this.playedLength = 0;
}
- },
- getVolume: function(){
- return this.volume;
- },
+ var audio = this.context["createBufferSource"]();
+ audio.buffer = this.buffer;
+ audio["connect"](this._volume);
+ audio.loop = this._loop;
- cloneNode: function(){
- var audio, self;
- if(this._AUDIO_TYPE === "AUDIO"){
- audio = new cc.Audio();
+ this._startTime = this.context.currentTime;
+ offset = offset || this.playedLength;
- var elem = document.createElement("audio");
- elem.src = this.src;
- audio.setElement(elem);
- }else{
- var volume = this._context["createGain"]();
- volume["gain"].value = 1;
- volume["connect"](this._context["destination"]);
- audio = new cc.Audio(this._context, volume, this.src);
- if(this._buffer){
- audio.setBuffer(this._buffer);
- }else{
- self = this;
- this._setBufferCallback = function(buffer){
- audio.setBuffer(buffer);
- self._setBufferCallback = null;
- };
- }
+ var duration = this.buffer.duration;
+ if (!this._loop) {
+ if (audio.start)
+ audio.start(0, offset, duration - offset);
+ else if (audio["notoGrainOn"])
+ audio["noteGrainOn"](0, offset, duration - offset);
+ else
+ audio["noteOn"](0, offset, duration - offset);
+ } else {
+ if (audio.start)
+ audio.start(0);
+ else if (audio["notoGrainOn"])
+ audio["noteGrainOn"](0);
+ else
+ audio["noteOn"](0);
}
- audio._AUDIO_TYPE = this._AUDIO_TYPE;
- return audio;
- }
-});
+ this._currentSource = audio;
-(function(polyfill){
+ // If the current audio context time stamp is 0
+ // There may be a need to touch events before you can actually start playing audio
+ // So here to add a timer to determine whether the real start playing audio, if not, then the incoming touchPlay queue
+ if (this.context.currentTime === 0) {
+ var self = this;
+ clearTimeout(this._currextTimer);
+ this._currextTimer = setTimeout(function () {
+ if (self.context.currentTime === 0) {
+ cc.Audio.touchPlayList.push({
+ offset: offset,
+ audio: self
+ });
+ }
+ }, 10);
+ }
+ },
+ pause: function () {
+ // Record the time the current has been played
+ this.playedLength = this.context.currentTime - this._startTime;
+ //If the duration of playedLendth exceeds the audio, you should take the remainder
+ this.playedLength %= this.buffer.duration;
+ var audio = this._currentSource;
+ this._currentSource = null;
+ this._startTime = -1;
+ if (audio)
+ audio.stop(0);
+ }
+};
- var SWA = polyfill.webAudio,
- SWB = polyfill.multichannel,
- SWC = polyfill.auto;
+(function (polyfill) {
+
+ var SWA = polyfill.WEB_AUDIO, SWB = polyfill.ONLY_ONE;
var support = [];
- (function(){
+ (function () {
var audio = document.createElement("audio");
- if(audio.canPlayType) {
+ if (audio.canPlayType) {
var ogg = audio.canPlayType('audio/ogg; codecs="vorbis"');
if (ogg && ogg !== "") support.push(".ogg");
var mp3 = audio.canPlayType("audio/mpeg");
@@ -429,100 +348,163 @@ cc.Audio = cc.Class.extend({
if (m4a && m4a !== "") support.push(".m4a");
}
})();
-
- if(SWA){
- var context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)();
+ try {
+ if (SWA) {
+ var context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)();
+ cc.Audio._context = context;
+ // check context integrity
+ if (
+ !context["createBufferSource"] ||
+ !context["createGain"] ||
+ !context["destination"] ||
+ !context["decodeAudioData"]
+ ) {
+ throw 'context is incomplete';
+ }
+ if (polyfill.DELAY_CREATE_CTX)
+ setTimeout(function () {
+ context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)();
+ cc.Audio._context = context;
+ }, 0);
+ }
+ } catch (error) {
+ SWA = false;
+ cc.log("browser don't support web audio");
}
var loader = {
cache: {},
- load: function(realUrl, url, res, cb){
+ useWebAudio: true,
+
+ loadBuffer: function (url, cb) {
+ if (!SWA) return; // WebAudio Buffer
+
+ var request = cc.loader.getXMLHttpRequest();
+ request.open("GET", url, true);
+ request.responseType = "arraybuffer";
+
+ // Our asynchronous callback
+ request.onload = function () {
+ if (request._timeoutId >= 0) {
+ clearTimeout(request._timeoutId);
+ }
+ context["decodeAudioData"](request.response, function (buffer) {
+ //success
+ cb(null, buffer);
+ //audio.setBuffer(buffer);
+ }, function () {
+ //error
+ cb('decode error - ' + url);
+ });
+ };
+
+ request.onerror = function () {
+ cb('request error - ' + url);
+ };
+ if (request.ontimeout === undefined) {
+ request._timeoutId = setTimeout(function () {
+ request.ontimeout();
+ }, request.timeout);
+ }
+ request.ontimeout = function () {
+ cb('request timeout - ' + url);
+ };
+
+ request.send();
+ },
+
+ load: function (realUrl, url, res, cb) {
- if(support.length === 0)
+ if (support.length === 0)
return cb("can not support audio!");
- var i;
+ var audio = cc.loader.getRes(url);
+ if (audio)
+ return cb(null, audio);
+
+ if (cc.loader.audioPath)
+ realUrl = cc.path.join(cc.loader.audioPath, realUrl);
var extname = cc.path.extname(realUrl);
var typeList = [extname];
- for(i=0; itrue if the background music is playing, otherwise false
*/
- willPlayMusic: function(){return false;},
+ willPlayMusic: function () {
+ return false;
+ },
/**
* Play music.
@@ -549,16 +535,23 @@ cc.Audio = cc.Class.extend({
*/
playMusic: function(url, loop){
var bgMusic = this._currMusic;
- if(bgMusic && bgMusic.src !== url){
+ if (bgMusic && bgMusic.getPlaying()) {
bgMusic.stop();
}
- var audio = loader.cache[url];
- if(!audio){
- cc.loader.load(url);
- audio = loader.cache[url];
+ var musicVolume = this._musicVolume;
+ var audio = cc.loader.getRes(url);
+ if (!audio) {
+ cc.loader.load(url, function () {
+ if (!audio.getPlaying() && !audio.interruptPlay) {
+ audio.setVolume(musicVolume);
+ audio.play(0, loop || false);
+ }
+ });
+ audio = cc.loader.getRes(url);
}
- audio.play(0, loop);
- audio.setVolume(this._musicVolume);
+ audio.setVolume(musicVolume);
+ audio.play(0, loop || false);
+
this._currMusic = audio;
},
@@ -571,8 +564,15 @@ cc.Audio = cc.Class.extend({
*/
stopMusic: function(releaseData){
var audio = this._currMusic;
- if(audio){
+ if (audio) {
+ var list = cc.Audio.touchPlayList;
+ for (var i=list.length-1; i>=0; --i) {
+ if (this[i] && this[i].audio === audio._element)
+ list.splice(i, 1);
+ }
+
audio.stop();
+ this._currMusic = null;
if (releaseData)
cc.loader.release(audio.src);
}
@@ -584,9 +584,9 @@ cc.Audio = cc.Class.extend({
* //example
* cc.audioEngine.pauseMusic();
*/
- pauseMusic: function(){
+ pauseMusic: function () {
var audio = this._currMusic;
- if(audio)
+ if (audio)
audio.pause();
},
@@ -596,9 +596,9 @@ cc.Audio = cc.Class.extend({
* //example
* cc.audioEngine.resumeMusic();
*/
- resumeMusic: function(){
+ resumeMusic: function () {
var audio = this._currMusic;
- if(audio)
+ if (audio)
audio.resume();
},
@@ -608,9 +608,9 @@ cc.Audio = cc.Class.extend({
* //example
* cc.audioEngine.rewindMusic();
*/
- rewindMusic: function(){
+ rewindMusic: function () {
var audio = this._currMusic;
- if(audio){
+ if (audio) {
audio.stop();
audio.play();
}
@@ -623,7 +623,7 @@ cc.Audio = cc.Class.extend({
* //example
* var volume = cc.audioEngine.getMusicVolume();
*/
- getMusicVolume: function(){
+ getMusicVolume: function () {
return this._musicVolume;
},
@@ -634,10 +634,15 @@ cc.Audio = cc.Class.extend({
* //example
* cc.audioEngine.setMusicVolume(0.5);
*/
- setMusicVolume: function(volume){
+ setMusicVolume: function (volume) {
+ volume = volume - 0;
+ if (isNaN(volume)) volume = 1;
+ if (volume > 1) volume = 1;
+ if (volume < 0) volume = 0;
+
this._musicVolume = volume;
var audio = this._currMusic;
- if(audio){
+ if (audio) {
audio.setVolume(volume);
}
},
@@ -654,17 +659,17 @@ cc.Audio = cc.Class.extend({
* cc.log("music is not playing");
* }
*/
- isMusicPlaying: function(){
+ isMusicPlaying: function () {
var audio = this._currMusic;
- if(audio){
+ if (audio) {
return audio.getPlaying();
- }else{
+ } else {
return false;
}
},
_audioPool: {},
- _maxAudioInstance: 5,
+ _maxAudioInstance: 10,
_effectVolume: 1,
/**
* Play sound effect.
@@ -675,45 +680,76 @@ cc.Audio = cc.Class.extend({
* //example
* var soundId = cc.audioEngine.playEffect(path);
*/
- playEffect: function(url, loop){
- //If the browser just support playing single audio
- if(!SWB){
- //Must be forced to shut down
- //Because playing multichannel audio will be stuck in chrome 28 (android)
+ playEffect: function (url, loop) {
+
+ if (SWB && this._currMusic && this._currMusic.getPlaying()) {
+ cc.log('Browser is only allowed to play one audio');
return null;
}
var effectList = this._audioPool[url];
- if(!effectList){
+ if (!effectList) {
effectList = this._audioPool[url] = [];
}
- var i;
-
- for(i=0; i this._maxAudioInstance) {
+ var first = effectList.shift();
+ first.stop();
+ effectList.push(first);
+ i = effectList.length - 1;
+ // cc.log("Error: %s greater than %d", url, this._maxAudioInstance);
+ }
+
+ var audio;
+ if (effectList[i]) {
audio = effectList[i];
audio.setVolume(this._effectVolume);
- audio.play(0, loop);
- }else if(SWA && i > this._maxAudioInstance){
- cc.log("Error: %s greater than %d", url, this._maxAudioInstance);
- }else{
- var audio = loader.cache[url];
- if(!audio){
- cc.loader.load(url);
- audio = loader.cache[url];
+ audio.play(0, loop || false);
+ return audio;
+ }
+
+ audio = cc.loader.getRes(url);
+
+ if (audio && SWA && audio._AUDIO_TYPE === 'AUDIO') {
+ cc.loader.release(url);
+ audio = null;
+ }
+
+ if (audio) {
+
+ if (SWA && audio._AUDIO_TYPE === 'AUDIO') {
+ loader.loadBuffer(url, function (error, buffer) {
+ audio.setBuffer(buffer);
+ audio.setVolume(cc.audioEngine._effectVolume);
+ if (!audio.getPlaying())
+ audio.play(0, loop || false);
+ });
+ } else {
+ audio = audio.cloneNode();
+ audio.setVolume(this._effectVolume);
+ audio.play(0, loop || false);
+ effectList.push(audio);
+ return audio;
}
+
+ }
+
+ var cache = loader.useWebAudio;
+ loader.useWebAudio = true;
+ cc.loader.load(url, function (audio) {
+ audio = cc.loader.getRes(url);
audio = audio.cloneNode();
- audio.setVolume(this._effectVolume);
- audio.loop = loop || false;
- audio.play();
+ audio.setVolume(cc.audioEngine._effectVolume);
+ audio.play(0, loop || false);
effectList.push(audio);
- }
+ });
+ loader.useWebAudio = cache;
return audio;
},
@@ -725,8 +761,21 @@ cc.Audio = cc.Class.extend({
* //example
* cc.audioEngine.setEffectsVolume(0.5);
*/
- setEffectsVolume: function(volume){
+ setEffectsVolume: function (volume) {
+ volume = volume - 0;
+ if (isNaN(volume)) volume = 1;
+ if (volume > 1) volume = 1;
+ if (volume < 0) volume = 0;
+
this._effectVolume = volume;
+ var audioPool = this._audioPool;
+ for (var p in audioPool) {
+ var audioList = audioPool[p];
+ if (Array.isArray(audioList))
+ for (var i = 0; i < audioList.length; i++) {
+ audioList[i].setVolume(volume);
+ }
+ }
},
/**
@@ -736,19 +785,19 @@ cc.Audio = cc.Class.extend({
* //example
* var effectVolume = cc.audioEngine.getEffectsVolume();
*/
- getEffectsVolume: function(){
+ getEffectsVolume: function () {
return this._effectVolume;
},
/**
* Pause playing sound effect.
- * @param {Number} cc.Audio The return value of function playEffect.
+ * @param {Number} audio The return value of function playEffect.
* @example
* //example
* cc.audioEngine.pauseEffect(audioID);
*/
- pauseEffect: function(audio){
- if(audio){
+ pauseEffect: function (audio) {
+ if (audio) {
audio.pause();
}
},
@@ -759,12 +808,12 @@ cc.Audio = cc.Class.extend({
* //example
* cc.audioEngine.pauseAllEffects();
*/
- pauseAllEffects: function(){
+ pauseAllEffects: function () {
var ap = this._audioPool;
- for(var p in ap){
+ for (var p in ap) {
var list = ap[p];
- for(var i=0; i
* Event callback that is invoked every time when node enters the 'stage'.
@@ -90,7 +82,8 @@ cc.ClippingNode = cc.Node.extend(/** @lends cc.ClippingNode# */{
*/
onEnter: function () {
cc.Node.prototype.onEnter.call(this);
- this._stencil.onEnter();
+ if (this._stencil)
+ this._stencil._performRecursive(cc.Node._stateCallbackType.onEnter);
},
/**
@@ -103,7 +96,8 @@ cc.ClippingNode = cc.Node.extend(/** @lends cc.ClippingNode# */{
*/
onEnterTransitionDidFinish: function () {
cc.Node.prototype.onEnterTransitionDidFinish.call(this);
- this._stencil.onEnterTransitionDidFinish();
+ if (this._stencil)
+ this._stencil._performRecursive(cc.Node._stateCallbackType.onEnterTransitionDidFinish);
},
/**
@@ -115,7 +109,7 @@ cc.ClippingNode = cc.Node.extend(/** @lends cc.ClippingNode# */{
* @function
*/
onExitTransitionDidStart: function () {
- this._stencil.onExitTransitionDidStart();
+ this._stencil._performRecursive(cc.Node._stateCallbackType.onExitTransitionDidStart);
cc.Node.prototype.onExitTransitionDidStart.call(this);
},
@@ -129,10 +123,29 @@ cc.ClippingNode = cc.Node.extend(/** @lends cc.ClippingNode# */{
* @function
*/
onExit: function () {
- this._stencil.onExit();
+ this._stencil._performRecursive(cc.Node._stateCallbackType.onExit);
cc.Node.prototype.onExit.call(this);
},
+ visit: function (parent) {
+ this._renderCmd.clippingVisit(parent && parent._renderCmd);
+ },
+
+ _visitChildren: function () {
+ var renderer = cc.renderer;
+ if (this._reorderChildDirty) {
+ this.sortAllChildren();
+ }
+ var children = this._children, child;
+ for (var i = 0, len = children.length; i < len; i++) {
+ child = children[i];
+ if (child && child._visible) {
+ child.visit(this);
+ }
+ }
+ this._renderCmd._dirtyFlag = 0;
+ },
+
/**
*
* The alpha threshold.
@@ -143,7 +156,7 @@ cc.ClippingNode = cc.Node.extend(/** @lends cc.ClippingNode# */{
* @return {Number}
*/
getAlphaThreshold: function () {
- return this.alphaThreshold;
+ return this._alphaThreshold;
},
/**
@@ -151,7 +164,11 @@ cc.ClippingNode = cc.Node.extend(/** @lends cc.ClippingNode# */{
* @param {Number} alphaThreshold
*/
setAlphaThreshold: function (alphaThreshold) {
- this.alphaThreshold = alphaThreshold;
+ if (alphaThreshold === 1 && alphaThreshold !== this._alphaThreshold) {
+ // should reset program used by _stencil
+ this._renderCmd.resetProgramByStencil();
+ }
+ this._alphaThreshold = alphaThreshold;
},
/**
@@ -189,13 +206,15 @@ cc.ClippingNode = cc.Node.extend(/** @lends cc.ClippingNode# */{
* @param {cc.Node} stencil
*/
setStencil: function (stencil) {
- if(this._stencil == stencil)
+ if (this._stencil === stencil)
return;
+ if (stencil)
+ this._originStencilProgram = stencil.getShaderProgram();
this._renderCmd.setStencil(stencil);
},
- _createRenderCmd: function(){
- if(cc._renderType === cc._RENDER_TYPE_CANVAS)
+ _createRenderCmd: function () {
+ if (cc._renderType === cc.game.RENDER_TYPE_CANVAS)
return new cc.ClippingNode.CanvasRenderCmd(this);
else
return new cc.ClippingNode.WebGLRenderCmd(this);
@@ -205,9 +224,13 @@ cc.ClippingNode = cc.Node.extend(/** @lends cc.ClippingNode# */{
var _p = cc.ClippingNode.prototype;
// Extended properties
-cc.defineGetterSetter(_p, "stencil", _p.getStencil, _p.setStencil);
/** @expose */
_p.stencil;
+cc.defineGetterSetter(_p, "stencil", _p.getStencil, _p.setStencil);
+/** @expose */
+_p.alphaThreshold;
+cc.defineGetterSetter(_p, "alphaThreshold", _p.getAlphaThreshold, _p.setAlphaThreshold);
+
/**
* Creates and initializes a clipping node with an other node as its stencil.
diff --git a/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js b/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js
index 0418b690fc..de4989921e 100644
--- a/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js
+++ b/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js
@@ -23,12 +23,13 @@
****************************************************************************/
//-------------------------- ClippingNode's canvas render cmd --------------------------------
-(function(){
- cc.ClippingNode.CanvasRenderCmd = function(renderable){
- cc.Node.CanvasRenderCmd.call(this, renderable);
+(function () {
+ cc.ClippingNode.CanvasRenderCmd = function (renderable) {
+ this._rootCtor(renderable);
this._needDraw = false;
+
this._godhelpme = false;
- this._clipElemType = null;
+ this._clipElemType = false;
this._rendererSaveCmd = new cc.CustomRenderCmd(this, this._saveCmdCallback);
this._rendererClipCmd = new cc.CustomRenderCmd(this, this._clipCmdCallback);
@@ -37,94 +38,106 @@
var proto = cc.ClippingNode.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
proto.constructor = cc.ClippingNode.CanvasRenderCmd;
- proto.initStencilBits = function(){};
+ proto.resetProgramByStencil = function () {
+
+ };
+
+ proto.initStencilBits = function () {
+ };
- proto.setStencil = function(stencil){
- if(stencil == null)
+ proto.setStencil = function (stencil) {
+ if (stencil == null)
return;
this._node._stencil = stencil;
- // For texture stencil, use the sprite itself
- //if (stencil instanceof cc.Sprite) {
- // return;
- //}
+
// For shape stencil, rewrite the draw of stencil ,only init the clip path and draw nothing.
//else
if (stencil instanceof cc.DrawNode) {
- if(stencil._buffer){
- for(var i=0; i 0; j--)
+ context.lineTo(vertices[j].x, -vertices[j].y);
+ }
}
context.clip();
}
@@ -132,11 +145,9 @@
proto._restoreCmdCallback = function (ctx) {
var locCache = cc.ClippingNode.CanvasRenderCmd._getSharedCache();
- var context = ctx || cc._renderContext;
+ var wrapper = ctx || cc._renderContext, context = wrapper.getContext();
if (this._clipElemType) {
- context.restore();
-
- // Redraw the cached canvas, so that the cliped area shows the background etc.
+ // Redraw the cached canvas, so that the clipped area shows the background etc.
context.save();
context.setTransform(1, 0, 0, 1, 0, 0);
context.globalCompositeOperation = "destination-over";
@@ -144,14 +155,17 @@
context.restore();
this._dirtyFlag = 0;
} else {
- context.restore();
+ wrapper.restore(); //use for restore clip operation
}
};
- proto.transform = function(parentCmd, recursive){
- cc.Node.CanvasRenderCmd.prototype.transform.call(this, parentCmd, recursive);
- if(this._stencil)
- this._stencil._renderCmd.transform(parentCmd, recursive);
+ proto.transform = function (parentCmd, recursive) {
+ this.originTransform(parentCmd, recursive);
+ var node = this._node;
+ if (node._stencil && node._stencil._renderCmd) {
+ node._stencil._renderCmd.transform(this, true);
+ node._stencil._dirtyFlag &= ~cc.Node._dirtyFlags.transformDirty;
+ }
};
proto._cangodhelpme = function (godhelpme) {
@@ -160,51 +174,40 @@
return cc.ClippingNode.CanvasRenderCmd.prototype._godhelpme;
};
- proto.visit = function(parentCmd){
- cc.renderer.pushRenderCommand(this);
+ proto.clippingVisit = function (parentCmd) {
var node = this._node;
- var transformRenderCmd = (node._stencil instanceof cc.Sprite) ? this : null;
- // quick return if not visible
- if (!node._visible)
- return;
-
parentCmd = parentCmd || this.getParentRenderCmd();
- if( parentCmd)
- this._curLevel = parentCmd._curLevel + 1;
+ this.visit(parentCmd);
// Composition mode, costy but support texture stencil
- this._clipElemType = (this._cangodhelpme() || node._stencil instanceof cc.Sprite);
-
- var i, children = node._children;
+ this._clipElemType = !(!this._cangodhelpme() && node._stencil instanceof cc.DrawNode);
if (!node._stencil || !node._stencil.visible) {
if (this.inverted)
- cc.Node.CanvasRenderCmd.prototype.visit.call(this, parentCmd); // draw everything
+ node._visitChildren(); // draw everything
return;
}
cc.renderer.pushRenderCommand(this._rendererSaveCmd);
- if(this._clipElemType){
+ if (this._clipElemType) {
// Draw everything first using node visit function
- cc.Node.CanvasRenderCmd.prototype.visit.call(this, parentCmd);
- }else{
- node._stencil.visit(transformRenderCmd);
+ node._visitChildren();
+ } else {
+ node._stencil.visit(node);
}
-
cc.renderer.pushRenderCommand(this._rendererClipCmd);
- this._syncStatus(parentCmd);
-
- if(this._clipElemType){
- node._stencil.visit(transformRenderCmd);
- }else{
- // Clip mode doesn't support recusive stencil, so once we used a clip stencil,
+ if (this._clipElemType) {
+ node._stencil.visit(node);
+ } else {
+ // Clip mode doesn't support recursive stencil, so once we used a clip stencil,
// so if it has ClippingNode as a child, the child must uses composition stencil.
this._cangodhelpme(true);
- var len = children.length;
+ var children = node._children;
+ var i, len = children.length;
if (len > 0) {
node.sortAllChildren();
for (i = 0; i < len; i++)
- children[i]._renderCmd.visit(this);
+ children[i].visit(node);
}
this._cangodhelpme(false);
}
@@ -217,4 +220,4 @@
cc.ClippingNode.CanvasRenderCmd._getSharedCache = function () {
return (cc.ClippingNode.CanvasRenderCmd._sharedCache) || (cc.ClippingNode.CanvasRenderCmd._sharedCache = document.createElement("canvas"));
};
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js b/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js
index 1aa5ce5ab9..6d8956a32b 100644
--- a/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js
+++ b/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js
@@ -22,36 +22,39 @@
THE SOFTWARE.
****************************************************************************/
+function setProgram (node, program) {
+ node.shaderProgram = program;
+
+ var children = node.children;
+ if (!children)
+ return;
+
+ for (var i = 0; i < children.length; i++)
+ setProgram(children[i], program);
+}
+
// ------------------------------- ClippingNode's WebGL render cmd ------------------------------
-(function(){
- cc.ClippingNode.WebGLRenderCmd = function(renderable){
- cc.Node.WebGLRenderCmd.call(this, renderable);
+(function () {
+ cc.ClippingNode.WebGLRenderCmd = function (renderable) {
+ this._rootCtor(renderable);
this._needDraw = false;
this._beforeVisitCmd = new cc.CustomRenderCmd(this, this._onBeforeVisit);
this._afterDrawStencilCmd = new cc.CustomRenderCmd(this, this._onAfterDrawStencil);
this._afterVisitCmd = new cc.CustomRenderCmd(this, this._onAfterVisit);
- this._currentStencilFunc = null;
- this._currentStencilRef = null;
- this._currentStencilValueMask = null;
- this._currentStencilFail = null;
- this._currentStencilPassDepthFail = null;
- this._currentStencilPassDepthPass = null;
- this._currentStencilWriteMask = null;
this._currentStencilEnabled = null;
- this._currentDepthWriteMask = null;
this._mask_layer_le = null;
};
- var proto = cc.ClippingNode.WebGLRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
+ var proto = cc.ClippingNode.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
proto.constructor = cc.ClippingNode.WebGLRenderCmd;
cc.ClippingNode.WebGLRenderCmd._init_once = null;
cc.ClippingNode.WebGLRenderCmd._visit_once = null;
cc.ClippingNode.WebGLRenderCmd._layer = -1;
- proto.initStencilBits = function(){
+ proto.initStencilBits = function () {
// get (only once) the number of bits of the stencil buffer
cc.ClippingNode.WebGLRenderCmd._init_once = true;
if (cc.ClippingNode.WebGLRenderCmd._init_once) {
@@ -62,56 +65,48 @@
}
};
- proto.transform = function(parentCmd, recursive){
+ proto.transform = function (parentCmd, recursive) {
var node = this._node;
- cc.Node.WebGLRenderCmd.prototype.transform.call(this, parentCmd, recursive);
- if(node._stencil)
- node._stencil._renderCmd.transform(this, recursive);
+ this.originTransform(parentCmd, recursive);
+ if (node._stencil) {
+ node._stencil._renderCmd.transform(this, true);
+ node._stencil._dirtyFlag &= ~cc.Node._dirtyFlags.transformDirty;
+ }
};
- proto.visit = function(parentCmd){
+ proto.clippingVisit = function (parentCmd) {
var node = this._node;
- // quick return if not visible
- if (!node._visible)
- return;
-
- if( node._parent && node._parent._renderCmd)
- this._curLevel = node._parent._renderCmd._curLevel + 1;
+ parentCmd = parentCmd || this.getParentRenderCmd();
+ this.visit(parentCmd);
// if stencil buffer disabled
if (cc.stencilBits < 1) {
- // draw everything, as if there where no stencil
- cc.Node.WebGLRenderCmd.prototype.visit.call(this, parentCmd);
+ // draw everything, as if there were no stencil
+ node._visitChildren();
return;
}
if (!node._stencil || !node._stencil.visible) {
if (node.inverted)
- cc.Node.WebGLRenderCmd.prototype.visit.call(this, parentCmd); // draw everything
+ node._visitChildren(); // draw everything
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.");
cc.ClippingNode.WebGLRenderCmd._visit_once = false;
}
- // draw everything, as if there where no stencil
- cc.Node.WebGLRenderCmd.prototype.visit.call(this, parentCmd);
+ // draw everything, as if there were no stencil
+ node._visitChildren();
return;
}
cc.renderer.pushRenderCommand(this._beforeVisitCmd);
- //optimize performance for javascript
- var currentStack = cc.current_stack;
- currentStack.stack.push(currentStack.top);
- this._syncStatus(parentCmd);
- currentStack.top = this._stackMatrix;
-
- //this._stencil._stackMatrix = this._stackMatrix;
- node._stencil._renderCmd.visit(this);
+ // node._stencil._stackMatrix = node._stackMatrix;
+ node._stencil.visit(node);
cc.renderer.pushRenderCommand(this._afterDrawStencilCmd);
@@ -122,41 +117,33 @@
node.sortAllChildren();
// draw children zOrder < 0
for (var i = 0; i < childLen; i++) {
- locChildren[i]._renderCmd.visit(this);
+ locChildren[i].visit(node);
}
}
cc.renderer.pushRenderCommand(this._afterVisitCmd);
- //optimize performance for javascript
- currentStack.top = currentStack.stack.pop();
+ this._dirtyFlag = 0;
};
- proto.setStencil = function(stencil){
+ proto.setStencil = function (stencil) {
var node = this._node;
- if(node._stencil)
+ if (node._stencil)
node._stencil._parent = null;
node._stencil = stencil;
- if(node._stencil)
+ if (node._stencil)
node._stencil._parent = node;
};
- proto._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();
- 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();
+ proto.resetProgramByStencil = function () {
+ var node = this._node;
+ if (node._stencil) {
+ var program = node._originStencilProgram;
+ setProgram(node._stencil, program);
+ }
};
- proto._onBeforeVisit = function(ctx){
+ proto._onBeforeVisit = function (ctx) {
var gl = ctx || cc._renderContext, node = this._node;
cc.ClippingNode.WebGLRenderCmd._layer++;
@@ -169,57 +156,52 @@
this._mask_layer_le = mask_layer | mask_layer_l;
// manually save the stencil state
this._currentStencilEnabled = gl.isEnabled(gl.STENCIL_TEST);
- this._currentStencilWriteMask = gl.getParameter(gl.STENCIL_WRITEMASK);
- this._currentStencilFunc = gl.getParameter(gl.STENCIL_FUNC);
- this._currentStencilRef = gl.getParameter(gl.STENCIL_REF);
- this._currentStencilValueMask = gl.getParameter(gl.STENCIL_VALUE_MASK);
- this._currentStencilFail = gl.getParameter(gl.STENCIL_FAIL);
- this._currentStencilPassDepthFail = gl.getParameter(gl.STENCIL_PASS_DEPTH_FAIL);
- this._currentStencilPassDepthPass = gl.getParameter(gl.STENCIL_PASS_DEPTH_PASS);
+ gl.clear(gl.DEPTH_BUFFER_BIT);
// enable stencil use
gl.enable(gl.STENCIL_TEST);
- gl.stencilMask(mask_layer);
- this._currentDepthWriteMask = gl.getParameter(gl.DEPTH_WRITEMASK);
gl.depthMask(false);
gl.stencilFunc(gl.NEVER, mask_layer, mask_layer);
- gl.stencilOp(!node.inverted ? gl.ZERO : gl.REPLACE, gl.KEEP, gl.KEEP);
-
- this._drawFullScreenQuadClearStencil();
+ gl.stencilOp(gl.REPLACE, gl.KEEP, gl.KEEP);
- gl.stencilFunc(gl.NEVER, mask_layer, mask_layer);
- gl.stencilOp(!node.inverted ? gl.REPLACE : gl.ZERO, gl.KEEP, gl.KEEP);
+ gl.stencilMask(mask_layer);
+ gl.clear(gl.STENCIL_BUFFER_BIT);
if (node.alphaThreshold < 1) { //TODO desktop
var program = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURECOLORALPHATEST);
- var alphaValueLocation = gl.getUniformLocation(program.getProgram(), cc.UNIFORM_ALPHA_TEST_VALUE_S);
// set our alphaThreshold
cc.glUseProgram(program.getProgram());
- program.setUniformLocationWith1f(alphaValueLocation, node.alphaThreshold);
+ program.setUniformLocationWith1f(cc.UNIFORM_ALPHA_TEST_VALUE_S, node.alphaThreshold);
+ program.setUniformLocationWithMatrix4fv(cc.UNIFORM_MVMATRIX_S, cc.renderer.mat4Identity.mat);
cc.setProgram(node._stencil, program);
}
};
- proto._onAfterDrawStencil = function(ctx){
+ proto._onAfterDrawStencil = function (ctx) {
var gl = ctx || cc._renderContext;
- gl.depthMask(this._currentDepthWriteMask);
-
- gl.stencilFunc(gl.EQUAL, this._mask_layer_le, this._mask_layer_le);
+ gl.depthMask(true);
+ gl.stencilFunc(!this._node.inverted ? gl.EQUAL : gl.NOTEQUAL, this._mask_layer_le, this._mask_layer_le);
gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
};
- proto._onAfterVisit = function(ctx){
+ proto._onAfterVisit = function (ctx) {
var gl = ctx || cc._renderContext;
- gl.stencilFunc(this._currentStencilFunc, this._currentStencilRef, this._currentStencilValueMask);
- gl.stencilOp(this._currentStencilFail, this._currentStencilPassDepthFail, this._currentStencilPassDepthPass);
- gl.stencilMask(this._currentStencilWriteMask);
- if (!this._currentStencilEnabled)
+ cc.ClippingNode.WebGLRenderCmd._layer--;
+
+ if (this._currentStencilEnabled) {
+ var mask_layer = 0x1 << cc.ClippingNode.WebGLRenderCmd._layer;
+ var mask_layer_l = mask_layer - 1;
+ var mask_layer_le = mask_layer | mask_layer_l;
+
+ gl.stencilMask(mask_layer);
+ gl.stencilFunc(gl.EQUAL, mask_layer_le, mask_layer_le);
+ }
+ else {
gl.disable(gl.STENCIL_TEST);
- // we are done using this layer, decrement
- cc.ClippingNode.WebGLRenderCmd._layer--;
- }
+ }
+ };
})();
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 06006dc795..980be114b4 100644
--- a/cocos2d/core/CCActionManager.js
+++ b/cocos2d/core/CCActionManager.js
@@ -30,27 +30,14 @@
* @example
* var element = new cc.HashElement();
*/
-cc.HashElement = cc.Class.extend(/** @lends cc.HashElement# */{
- actions:null,
- target:null, //ccobject
- actionIndex:0,
- currentAction:null, //CCAction
- currentActionSalvaged:false,
- paused:false,
- hh:null, //ut hash handle
- /**
- * Constructor
- */
- ctor:function () {
- this.actions = [];
- this.target = null;
- this.actionIndex = 0;
- this.currentAction = null; //CCAction
- this.currentActionSalvaged = false;
- this.paused = false;
- this.hh = null; //ut hash handle
- }
-});
+cc.HashElement = function () {
+ this.actions = [];
+ this.target = null;
+ this.actionIndex = 0;
+ this.currentAction = null; //CCAction
+ this.paused = false;
+ this.lock = false;
+};
/**
* cc.ActionManager is a class that can manage actions.
@@ -66,14 +53,11 @@ cc.HashElement = cc.Class.extend(/** @lends cc.HashElement# */{
* var mng = new cc.ActionManager();
*/
cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{
- _hashTargets:null,
- _arrayTargets:null,
- _currentTarget:null,
- _currentTargetSalvaged:false,
+ _elementPool: [],
_searchElementByTarget:function (arr, target) {
for (var k = 0; k < arr.length; k++) {
- if (target == arr[k].target)
+ if (target === arr[k].target)
return arr[k];
}
return null;
@@ -83,7 +67,26 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{
this._hashTargets = {};
this._arrayTargets = [];
this._currentTarget = null;
- this._currentTargetSalvaged = false;
+ },
+
+ _getElement: function (target, paused) {
+ var element = this._elementPool.pop();
+ if (!element) {
+ element = new cc.HashElement();
+ }
+ element.target = target;
+ element.paused = !!paused;
+ return element;
+ },
+
+ _putElement: function (element) {
+ element.actions.length = 0;
+ element.actionIndex = 0;
+ element.currentAction = null;
+ element.paused = false;
+ element.target = null;
+ element.lock = false;
+ this._elementPool.push(element);
},
/** Adds an action with a target.
@@ -96,22 +99,21 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{
*/
addAction:function (action, target, paused) {
if(!action)
- throw "cc.ActionManager.addAction(): action must be non-null";
+ throw new Error("cc.ActionManager.addAction(): action must be non-null");
if(!target)
- throw "cc.ActionManager.addAction(): action must be non-null";
+ throw new Error("cc.ActionManager.addAction(): target must be non-null");
//check if the action target already exists
var element = this._hashTargets[target.__instanceId];
- //if doesnt exists, create a hashelement and push in mpTargets
+ //if doesn't exists, create a hashelement and push in mpTargets
if (!element) {
- element = new cc.HashElement();
- element.paused = paused;
- element.target = target;
+ element = this._getElement(target, paused);
this._hashTargets[target.__instanceId] = element;
this._arrayTargets.push(element);
}
- //creates a array for that eleemnt to hold the actions
- this._actionAllocWithHashElement(element);
+ else if (!element.actions) {
+ element.actions = [];
+ }
element.actions.push(action);
action.startWithTarget(target);
@@ -139,15 +141,8 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{
return;
var element = this._hashTargets[target.__instanceId];
if (element) {
- if (element.actions.indexOf(element.currentAction) !== -1 && !(element.currentActionSalvaged))
- element.currentActionSalvaged = true;
-
element.actions.length = 0;
- if (this._currentTarget == element && !forceDelete) {
- this._currentTargetSalvaged = true;
- } else {
- this._deleteHashElement(element);
- }
+ this._deleteHashElement(element);
}
},
/** Removes an action given an action reference.
@@ -162,8 +157,11 @@ 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);
+ // update actionIndex in case we are in tick. looping over the actions
+ if (element.actionIndex >= i)
+ element.actionIndex--;
break;
}
}
@@ -177,7 +175,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 +186,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 +200,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];
@@ -274,10 +272,10 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{
* @param {Array} targetsToResume
*/
resumeTargets:function(targetsToResume){
- if(!targetsToResume)
+ if (!targetsToResume)
return;
- for(var i = 0 ; i< targetsToResume.length; i++){
+ for (var i = 0; i< targetsToResume.length; i++) {
if(targetsToResume[i])
this.resumeTarget(targetsToResume[i]);
}
@@ -287,45 +285,41 @@ 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().unscheduleUpdate(this);
},
//protected
_removeActionAtIndex:function (index, element) {
var action = element.actions[index];
- if ((action == element.currentAction) && (!element.currentActionSalvaged))
- element.currentActionSalvaged = true;
-
element.actions.splice(index, 1);
// update actionIndex in case we are in tick. looping over the actions
if (element.actionIndex >= index)
element.actionIndex--;
- if (element.actions.length == 0) {
- if (this._currentTarget == element) {
- this._currentTargetSalvaged = true;
- } else {
- this._deleteHashElement(element);
- }
+ if (element.actions.length === 0) {
+ this._deleteHashElement(element);
}
},
_deleteHashElement:function (element) {
- if (element) {
- delete this._hashTargets[element.target.__instanceId];
- cc.arrayRemoveObject(this._arrayTargets, element);
- element.actions = null;
- element.target = null;
- }
- },
-
- _actionAllocWithHashElement:function (element) {
- // 4 actions per Node by default
- if (element.actions == null) {
- element.actions = [];
+ var ret = false;
+ if (element && !element.lock) {
+ if (this._hashTargets[element.target.__instanceId]) {
+ delete this._hashTargets[element.target.__instanceId];
+ var targets = this._arrayTargets;
+ for (var i = 0, l = targets.length; i < l; i++) {
+ if (targets[i] === element) {
+ targets.splice(i, 1);
+ break;
+ }
+ }
+ this._putElement(element);
+ ret = true;
+ }
}
+ return ret;
},
/**
@@ -336,41 +330,31 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{
for (var elt = 0; elt < locTargets.length; elt++) {
this._currentTarget = locTargets[elt];
locCurrTarget = this._currentTarget;
- //this._currentTargetSalvaged = false;
- if (!locCurrTarget.paused) {
+ if (!locCurrTarget.paused && locCurrTarget.actions) {
+ locCurrTarget.lock = true;
// The 'actions' CCMutableArray may change while inside this loop.
- for (locCurrTarget.actionIndex = 0; locCurrTarget.actionIndex < locCurrTarget.actions.length;
- locCurrTarget.actionIndex++) {
+ for (locCurrTarget.actionIndex = 0; locCurrTarget.actionIndex < locCurrTarget.actions.length; locCurrTarget.actionIndex++) {
locCurrTarget.currentAction = locCurrTarget.actions[locCurrTarget.actionIndex];
if (!locCurrTarget.currentAction)
continue;
- locCurrTarget.currentActionSalvaged = false;
//use for speed
locCurrTarget.currentAction.step(dt * ( locCurrTarget.currentAction._speedMethod ? locCurrTarget.currentAction._speed : 1 ) );
- if (locCurrTarget.currentActionSalvaged) {
- // The currentAction told the node to remove it. To prevent the action from
- // accidentally deallocating itself before finishing its step, we retained
- // it. Now that step is done, it's safe to release it.
- locCurrTarget.currentAction = null;//release
- } else if (locCurrTarget.currentAction.isDone()) {
+
+ if (locCurrTarget.currentAction && locCurrTarget.currentAction.isDone()) {
locCurrTarget.currentAction.stop();
var action = locCurrTarget.currentAction;
- // Make currentAction nil to prevent removeAction from salvaging it.
locCurrTarget.currentAction = null;
this.removeAction(action);
}
locCurrTarget.currentAction = null;
}
+ locCurrTarget.lock = false;
}
-
- // elt, at this moment, is still valid
- // so it is safe to ask this here (issue #490)
-
// only delete currentTarget if no actions were scheduled during the cycle (issue #481)
- if (this._currentTargetSalvaged && locCurrTarget.actions.length === 0) {
- this._deleteHashElement(locCurrTarget);
+ if (locCurrTarget.actions.length === 0) {
+ this._deleteHashElement(locCurrTarget) && elt--;
}
}
}
diff --git a/cocos2d/core/CCCamera.js b/cocos2d/core/CCCamera.js
deleted file mode 100644
index e93cda5a24..0000000000
--- a/cocos2d/core/CCCamera.js
+++ /dev/null
@@ -1,290 +0,0 @@
-/****************************************************************************
- Copyright (c) 2008-2010 Ricardo Quesada
- Copyright (c) 2011-2012 cocos2d-x.org
- Copyright (c) 2013-2014 Chukong Technologies Inc.
-
- http://www.cocos2d-x.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be included in
- all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
-
-/**
- *
- * A CCCamera is used in every CCNode.
- * The OpenGL gluLookAt() function is used to locate the camera.
- *
- * If the object is transformed by any of the scale, rotation or position attributes, then they will override the camera.
- *
- * IMPORTANT: Either your use the camera or the rotation/scale/position properties. You can't use both.
- * World coordinates won't work if you use the camera.
- *
- * Limitations:
- * - Some nodes, like CCParallaxNode, CCParticle uses world node coordinates, and they won't work properly if you move them (or any of their ancestors)
- * using the camera.
- *
- * - It doesn't work on batched nodes like CCSprite objects when they are parented to a CCSpriteBatchNode object.
- *
- * - It is recommended to use it ONLY if you are going to create 3D effects. For 2D effecs, use the action CCFollow or position/scale/rotate. *
- *
- */
-cc.Camera = cc.Class.extend({
- _eyeX:null,
- _eyeY:null,
- _eyeZ:null,
-
- _centerX:null,
- _centerY:null,
- _centerZ:null,
-
- _upX:null,
- _upY:null,
- _upZ:null,
-
- _dirty:null,
- _lookupMatrix:null,
- /**
- * constructor of cc.Camera
- */
- ctor:function () {
- this._lookupMatrix = new cc.kmMat4();
- this.restore();
- },
-
- /**
- * Description of cc.Camera
- * @return {String}
- */
- description:function () {
- return "";
- },
-
- /**
- * sets the dirty value
- * @param value
- */
- setDirty:function (value) {
- this._dirty = value;
- },
-
- /**
- * get the dirty value
- * @return {Boolean}
- */
- isDirty:function () {
- return this._dirty;
- },
-
- /**
- * sets the camera in the default position
- */
- restore:function () {
- this._eyeX = this._eyeY = 0.0;
- this._eyeZ = cc.Camera.getZEye();
-
- this._centerX = this._centerY = this._centerZ = 0.0;
-
- this._upX = 0.0;
- this._upY = 1.0;
- this._upZ = 0.0;
-
- cc.kmMat4Identity( this._lookupMatrix );
-
- this._dirty = false;
- },
-
- /**
- * Sets the camera using gluLookAt using its eye, center and up_vector
- */
- 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);
- cc.kmMat4LookAt( this._lookupMatrix, eye, center, up);
-
- this._dirty = false;
- }
- cc.kmGLMultMatrix( this._lookupMatrix);
- },
-
- _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);
- cc.kmMat4LookAt( this._lookupMatrix, eye, center, up);
-
- this._dirty = false;
- }
- cc.kmMat4Multiply(matrix, matrix, this._lookupMatrix);
- },
-
- /**
- * sets the eye values in points
- * @param {Number} eyeX
- * @param {Number} eyeY
- * @param {Number} eyeZ
- * @deprecated This function will be deprecated sooner or later please use setEye instead.
- */
- setEyeXYZ:function (eyeX, eyeY, eyeZ) {
- this.setEye(eyeX,eyeY,eyeZ);
- },
-
- /**
- * sets the eye values in points
- * @param {Number} eyeX
- * @param {Number} eyeY
- * @param {Number} eyeZ
- */
- setEye:function (eyeX, eyeY, eyeZ) {
- this._eyeX = eyeX ;
- this._eyeY = eyeY ;
- this._eyeZ = eyeZ ;
-
- this._dirty = true;
- },
-
- /**
- * sets the center values in points
- * @param {Number} centerX
- * @param {Number} centerY
- * @param {Number} centerZ
- * @deprecated This function will be deprecated sooner or later please use setCenter instead.
- */
- setCenterXYZ:function (centerX, centerY, centerZ) {
- this.setCenter(centerX,centerY,centerZ);
- },
-
- /**
- * sets the center values in points
- * @param {Number} centerX
- * @param {Number} centerY
- * @param {Number} centerZ
- */
- setCenter:function (centerX, centerY, centerZ) {
- this._centerX = centerX ;
- this._centerY = centerY ;
- this._centerZ = centerZ ;
-
- this._dirty = true;
- },
-
- /**
- * sets the up values
- * @param {Number} upX
- * @param {Number} upY
- * @param {Number} upZ
- * @deprecated This function will be deprecated sooner or later.
- */
- setUpXYZ:function (upX, upY, upZ) {
- this.setUp(upX, upY, upZ);
- },
-
- /**
- * sets the up values
- * @param {Number} upX
- * @param {Number} upY
- * @param {Number} upZ
- */
- setUp:function (upX, upY, upZ) {
- this._upX = upX;
- this._upY = upY;
- this._upZ = upZ;
-
- this._dirty = true;
- },
-
- /**
- * get the eye vector values in points (return an object like {x:1,y:1,z:1} in HTML5)
- * @param {Number} eyeX
- * @param {Number} eyeY
- * @param {Number} eyeZ
- * @return {Object}
- * @deprecated This function will be deprecated sooner or later, please use getEye instead.
- */
- getEyeXYZ:function (eyeX, eyeY, eyeZ) {
- return {x:this._eyeX , y:this._eyeY , z: this._eyeZ };
- },
-
- /**
- * get the eye vector values in points (return an object like {x:1,y:1,z:1} in HTML5)
- * @return {Object}
- */
- getEye:function () {
- return {x:this._eyeX , y:this._eyeY , z: this._eyeZ };
- },
-
- /**
- * get the center vector values int points (return an object like {x:1,y:1,z:1} in HTML5)
- * @param {Number} centerX
- * @param {Number} centerY
- * @param {Number} centerZ
- * @return {Object}
- * @deprecated This function will be deprecated sooner or later,please use getCenter instead.
- */
- getCenterXYZ:function (centerX, centerY, centerZ) {
- return {x:this._centerX ,y:this._centerY ,z:this._centerZ };
- },
-
- /**
- * get the center vector values int points (return an object like {x:1,y:1,z:1} in HTML5)
- * @return {Object}
- */
- getCenter:function () {
- return {x:this._centerX ,y:this._centerY ,z:this._centerZ };
- },
-
- /**
- * get the up vector values (return an object like {x:1,y:1,z:1} in HTML5)
- * @param {Number} upX
- * @param {Number} upY
- * @param {Number} upZ
- * @return {Object}
- * @deprecated This function will be deprecated sooner or later,please use getUp instead.
- */
- getUpXYZ:function (upX, upY, upZ) {
- return {x:this._upX,y:this._upY,z:this._upZ};
- },
-
- /**
- * get the up vector values (return an object like {x:1,y:1,z:1} in HTML5)
- * @return {Object}
- */
- getUp:function () {
- return {x:this._upX,y:this._upY,z:this._upZ};
- },
-
- _DISALLOW_COPY_AND_ASSIGN:function (CCCamera) {
-
- }
-});
-
-/**
- * returns the Z eye
- * @return {Number}
- */
-cc.Camera.getZEye = function () {
- return cc.FLT_EPSILON;
-};
diff --git a/cocos2d/core/CCConfiguration.js b/cocos2d/core/CCConfiguration.js
index e2be6b7ba8..db58df2449 100644
--- a/cocos2d/core/CCConfiguration.js
+++ b/cocos2d/core/CCConfiguration.js
@@ -231,7 +231,7 @@ cc.configuration = /** @lends cc.configuration# */{
* gathers OpenGL / GPU information
*/
gatherGPUInfo: function(){
- if(cc._renderType === cc._RENDER_TYPE_CANVAS)
+ if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
return;
if(!this._inited)
@@ -278,7 +278,7 @@ cc.configuration = /** @lends cc.configuration# */{
if(!this._inited)
this._init();
var dict = cc.loader.getRes(url);
- if(!dict) throw "Please load the resource first : " + url;
+ if(!dict) throw new Error("Please load the resource first : " + url);
cc.assert(dict, cc._LogInfos.configuration_loadConfigFile_2, url);
var getDatas = dict["data"];
diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js
index bb572bc8dd..b8a021f43c 100644
--- a/cocos2d/core/CCDirector.js
+++ b/cocos2d/core/CCDirector.js
@@ -26,15 +26,6 @@
cc.g_NumberOfDraws = 0;
-cc.GLToClipTransform = function (transformOut) {
- var projection = new cc.kmMat4();
- cc.kmGLGetMatrix(cc.KM_GL_PROJECTION, projection);
-
- var modelview = new cc.kmMat4();
- cc.kmGLGetMatrix(cc.KM_GL_MODELVIEW, modelview);
-
- cc.kmMat4Multiply(transformOut, projection, modelview);
-};
//----------------------------------------------------------------------------------------------------------------------
/**
@@ -52,6 +43,7 @@ cc.GLToClipTransform = function (transformOut) {
* - setting the OpenGL pixel format (default on is RGB565)
* - setting the OpenGL pixel format (default on is RGB565)
* - setting the OpenGL buffer depth (default one is 0-bit)
+ * - setting the color for clear screen (default one is BLACK)
* - setting the projection (default one is 3D)
* - setting the orientation (default one is Portrait)
*
@@ -81,16 +73,9 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{
_animationInterval: 0.0,
_oldAnimationInterval: 0.0,
_projection: 0,
- _accumDt: 0.0,
_contentScaleFactor: 1.0,
- _displayStats: false,
_deltaTime: 0.0,
- _frameRate: 0.0,
-
- _FPSLabel: null,
- _SPFLabel: null,
- _drawsLabel: null,
_winSizeInPoints: null,
@@ -102,7 +87,6 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{
_projectionDelegate: null,
_runningScene: null,
- _frames: 0,
_totalFrames: 0,
_secondsPerFrame: 0,
@@ -111,9 +95,9 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{
_scheduler: null,
_actionManager: null,
_eventProjectionChanged: null,
- _eventAfterDraw: null,
- _eventAfterVisit: null,
_eventAfterUpdate: null,
+ _eventAfterVisit: null,
+ _eventAfterDraw: null,
ctor: function () {
var self = this;
@@ -132,11 +116,8 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{
// projection delegate if "Custom" projection is used
this._projectionDelegate = null;
- //FPS
- this._accumDt = 0;
- this._frameRate = 0;
- this._displayStats = false;//can remove
- this._totalFrames = this._frames = 0;
+ // FPS
+ this._totalFrames = 0;
this._lastUpdate = Date.now();
//Paused?
@@ -153,15 +134,19 @@ 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.scheduleUpdateForTarget(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);
- this._eventAfterVisit = new cc.EventCustom(cc.Director.EVENT_AFTER_VISIT);
- this._eventAfterVisit.setUserData(this);
this._eventAfterUpdate = new cc.EventCustom(cc.Director.EVENT_AFTER_UPDATE);
this._eventAfterUpdate.setUserData(this);
+ this._eventAfterVisit = new cc.EventCustom(cc.Director.EVENT_AFTER_VISIT);
+ this._eventAfterVisit.setUserData(this);
+ this._eventAfterDraw = new cc.EventCustom(cc.Director.EVENT_AFTER_DRAW);
+ this._eventAfterDraw.setUserData(this);
this._eventProjectionChanged = new cc.EventCustom(cc.Director.EVENT_PROJECTION_CHANGED);
this._eventProjectionChanged.setUserData(this);
@@ -196,7 +181,16 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{
* @param {cc.Point} uiPoint
* @return {cc.Point}
*/
- convertToGL: null,
+ convertToGL: function (uiPoint) {
+ var docElem = document.documentElement;
+ var view = cc.view;
+ var box = docElem.getBoundingClientRect();
+ box.left += window.pageXOffset - docElem.clientLeft;
+ box.top += window.pageYOffset - docElem.clientTop;
+ var x = view._devicePixelRatio * (uiPoint.x - box.left);
+ var y = view._devicePixelRatio * (box.top + box.height - uiPoint.y);
+ return view._isRotated ? {x: view._viewPortRect.width - y, y: x} : {x: x, y: y};
+ },
/**
* Converts an WebGL coordinate to a view coordinate
@@ -206,13 +200,30 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{
* @param {cc.Point} glPoint
* @return {cc.Point}
*/
- convertToUI: null,
+ convertToUI: function (glPoint) {
+ var docElem = document.documentElement;
+ var view = cc.view;
+ var box = docElem.getBoundingClientRect();
+ box.left += window.pageXOffset - docElem.clientLeft;
+ box.top += window.pageYOffset - docElem.clientTop;
+ var uiPoint = {x: 0, y: 0};
+ if (view._isRotated) {
+ uiPoint.x = box.left + glPoint.y / view._devicePixelRatio;
+ uiPoint.y = box.top + box.height - (view._viewPortRect.width - glPoint.x) / view._devicePixelRatio;
+ }
+ else {
+ uiPoint.x = box.left + glPoint.x / view._devicePixelRatio;
+ uiPoint.y = box.top + box.height - glPoint.y / view._devicePixelRatio;
+ }
+ return uiPoint;
+ },
/**
* Draw the scene. This method is called every frame. Don't call it manually.
*/
drawScene: function () {
var renderer = cc.renderer;
+
// calculate "global" dt
this.calculateDeltaTime();
@@ -222,50 +233,43 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{
cc.eventManager.dispatchEvent(this._eventAfterUpdate);
}
- this._clear();
-
/* to avoid flickr, nextScene MUST be here: after tick and before draw.
XXX: Which bug is this one. It seems that it can't be reproduced with v0.9 */
if (this._nextScene) {
this.setNextScene();
}
- if (this._beforeVisitScene)
- this._beforeVisitScene();
-
// draw the scene
if (this._runningScene) {
- if (renderer.childrenOrderDirty === true) {
+ if (renderer.childrenOrderDirty) {
cc.renderer.clearRenderCommands();
+ cc.renderer.assignedZ = 0;
this._runningScene._renderCmd._curLevel = 0; //level start from 0;
this._runningScene.visit();
renderer.resetFlag();
- } else if (renderer.transformDirty() === true)
+ }
+ else if (renderer.transformDirty()) {
renderer.transform();
-
- cc.eventManager.dispatchEvent(this._eventAfterVisit);
+ }
}
+ renderer.clear();
+
// draw the notifications node
if (this._notificationNode)
this._notificationNode.visit();
- if (this._displayStats)
- this._showStats();
-
- if (this._afterVisitScene)
- this._afterVisitScene();
+ cc.eventManager.dispatchEvent(this._eventAfterVisit);
+ cc.g_NumberOfDraws = 0;
renderer.rendering(cc._renderContext);
- cc.eventManager.dispatchEvent(this._eventAfterDraw);
this._totalFrames++;
- if (this._displayStats)
- this._calculateMPF();
- },
+ cc.eventManager.dispatchEvent(this._eventAfterDraw);
+ cc.eventManager.frameUpdateListeners();
- _beforeVisitScene: null,
- _afterVisitScene: null,
+ this._calculateMPF();
+ },
/**
* End the life of director in the next frame
@@ -364,7 +368,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;
@@ -386,7 +390,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)
@@ -396,9 +400,9 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{
// They are needed in case the director is run again
if (this._runningScene) {
- this._runningScene.onExitTransitionDidStart();
- this._runningScene.onExit();
- this._runningScene.cleanup();
+ this._runningScene._performRecursive(cc.Node._stateCallbackType.onExitTransitionDidStart);
+ this._runningScene._performRecursive(cc.Node._stateCallbackType.onExit);
+ this._runningScene._performRecursive(cc.Node._stateCallbackType.cleanup);
}
this._runningScene = null;
@@ -484,9 +488,8 @@ 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();
}
},
@@ -498,6 +501,13 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{
*/
setDepthTest: null,
+ /**
+ * set color for clear screen.
+ * Implementation can be found in CCDirectorCanvas.js/CCDirectorWebGL.js
+ * @function
+ * @param {cc.Color} clearColor
+ */
+ setClearColor: null,
/**
* Sets the default values based on the CCConfiguration info
*/
@@ -527,23 +537,23 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{
if (!newIsTransition) {
var locRunningScene = this._runningScene;
if (locRunningScene) {
- locRunningScene.onExitTransitionDidStart();
- locRunningScene.onExit();
+ locRunningScene._performRecursive(cc.Node._stateCallbackType.onExitTransitionDidStart);
+ locRunningScene._performRecursive(cc.Node._stateCallbackType.onExit);
}
// issue #709. the root node (scene) should receive the cleanup message too
// otherwise it might be leaked.
if (this._sendCleanupToScene && locRunningScene)
- locRunningScene.cleanup();
+ locRunningScene._performRecursive(cc.Node._stateCallbackType.cleanup);
}
this._runningScene = this._nextScene;
cc.renderer.childrenOrderDirty = true;
this._nextScene = null;
- if ((!runningIsTransition) && (this._runningScene != null)) {
- this._runningScene.onEnter();
- this._runningScene.onEnterTransitionDidFinish();
+ if ((!runningIsTransition) && (this._runningScene !== null)) {
+ this._runningScene._performRecursive(cc.Node._stateCallbackType.onEnter);
+ this._runningScene._performRecursive(cc.Node._stateCallbackType.onEnterTransitionDidFinish);
}
},
@@ -552,7 +562,17 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{
* @param {cc.Node} node
*/
setNotificationNode: function (node) {
+ cc.renderer.childrenOrderDirty = true;
+ if (this._notificationNode) {
+ this._notificationNode._performRecursive(cc.Node._stateCallbackType.onExitTransitionDidStart);
+ this._notificationNode._performRecursive(cc.Node._stateCallbackType.onExit);
+ this._notificationNode._performRecursive(cc.Node._stateCallbackType.cleanup);
+ }
this._notificationNode = node;
+ if (!node)
+ return;
+ this._notificationNode._performRecursive(cc.Node._stateCallbackType.onEnter);
+ this._notificationNode._performRecursive(cc.Node._stateCallbackType.onEnterTransitionDidFinish);
},
/**
@@ -618,28 +638,6 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{
*/
setAlphaBlending: null,
- _showStats: function () {
- this._frames++;
- this._accumDt += this._deltaTime;
- if (this._FPSLabel && this._SPFLabel && this._drawsLabel) {
- if (this._accumDt > cc.DIRECTOR_FPS_INTERVAL) {
- this._SPFLabel.string = this._secondsPerFrame.toFixed(3);
-
- this._frameRate = this._frames / this._accumDt;
- this._frames = 0;
- this._accumDt = 0;
-
- this._FPSLabel.string = this._frameRate.toFixed(1);
- this._drawsLabel.string = (0 | cc.g_NumberOfDraws).toString();
- }
- this._FPSLabel.visit();
- this._SPFLabel.visit();
- this._drawsLabel.visit();
- } else
- this._createStatsLabel();
- cc.g_NumberOfDraws = 0;
- },
-
/**
* Returns whether or not the replaced scene will receive the cleanup message.
* If the new scene is pushed, then the old scene won't receive the "cleanup" message.
@@ -671,7 +669,7 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{
* @return {Boolean}
*/
isDisplayStats: function () {
- return this._displayStats;
+ return cc.profiler ? cc.profiler.isShowingStats() : false;
},
/**
@@ -679,7 +677,9 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{
* @param {Boolean} displayStats
*/
setDisplayStats: function (displayStats) {
- this._displayStats = displayStats;
+ if (cc.profiler) {
+ displayStats ? cc.profiler.showStats() : cc.profiler.hideStats();
+ }
},
/**
@@ -731,32 +731,31 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{
* @param {Number} level
*/
popToSceneStackLevel: function (level) {
-
cc.assert(this._runningScene, cc._LogInfos.Director_popToSceneStackLevel_2);
var locScenesStack = this._scenesStack;
var c = locScenesStack.length;
- if (c == 0) {
+ if (level === 0) {
this.end();
return;
}
- // current level or lower -> nothing
- if (level > c)
+ // stack overflow
+ if (level >= c)
return;
// pop stack until reaching desired level
while (c > level) {
var current = locScenesStack.pop();
if (current.running) {
- current.onExitTransitionDidStart();
- current.onExit();
+ current._performRecursive(cc.Node._stateCallbackType.onExitTransitionDidStart);
+ current._performRecursive(cc.Node._stateCallbackType.onExit);
}
- current.cleanup();
+ current._performRecursive(cc.Node._stateCallbackType.cleanup);
c--;
}
this._nextScene = locScenesStack[locScenesStack.length - 1];
- this._sendCleanupToScene = false;
+ this._sendCleanupToScene = true;
},
/**
@@ -772,7 +771,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 +788,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;
}
},
@@ -802,8 +801,6 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{
return this._deltaTime;
},
- _createStatsLabel: null,
-
_calculateMPF: function () {
var now = Date.now();
this._secondsPerFrame = (now - this._lastUpdate) / 1000;
@@ -822,15 +819,15 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{
cc.Director.EVENT_PROJECTION_CHANGED = "director_projection_changed";
/**
- * The event after draw of cc.Director
+ * The event after update of cc.Director
* @constant
* @type {string}
* @example
- * cc.eventManager.addCustomListener(cc.Director.EVENT_AFTER_DRAW, function(event) {
- * cc.log("after draw event.");
+ * cc.eventManager.addCustomListener(cc.Director.EVENT_AFTER_UPDATE, function(event) {
+ * cc.log("after update event.");
* });
*/
-cc.Director.EVENT_AFTER_DRAW = "director_after_draw";
+cc.Director.EVENT_AFTER_UPDATE = "director_after_update";
/**
* The event after visit of cc.Director
@@ -844,15 +841,15 @@ cc.Director.EVENT_AFTER_DRAW = "director_after_draw";
cc.Director.EVENT_AFTER_VISIT = "director_after_visit";
/**
- * The event after update of cc.Director
+ * The event after draw of cc.Director
* @constant
* @type {string}
* @example
- * cc.eventManager.addCustomListener(cc.Director.EVENT_AFTER_UPDATE, function(event) {
- * cc.log("after update event.");
+ * cc.eventManager.addCustomListener(cc.Director.EVENT_AFTER_DRAW, function(event) {
+ * cc.log("after draw event.");
* });
*/
-cc.Director.EVENT_AFTER_UPDATE = "director_after_update";
+cc.Director.EVENT_AFTER_DRAW = "director_after_draw";
/***************************************************
* implementation of DisplayLinkDirector
@@ -942,81 +939,8 @@ cc.Director.PROJECTION_3D = 1;
cc.Director.PROJECTION_CUSTOM = 3;
/**
- * Constant for default projection of cc.Director, default projection is 3D projection
+ * Constant for default projection of cc.Director, default projection is 2D projection
* @constant
* @type {Number}
*/
cc.Director.PROJECTION_DEFAULT = cc.Director.PROJECTION_3D;
-
-if (cc._renderType === cc._RENDER_TYPE_CANVAS) {
-
- var _p = cc.Director.prototype;
-
- _p.setProjection = function (projection) {
- this._projection = projection;
- cc.eventManager.dispatchEvent(this._eventProjectionChanged);
- };
-
- _p.setDepthTest = function () {
- };
-
- _p.setOpenGLView = function (openGLView) {
- // set size
- this._winSizeInPoints.width = cc._canvas.width; //this._openGLView.getDesignResolutionSize();
- this._winSizeInPoints.height = cc._canvas.height;
- this._openGLView = openGLView || cc.view;
- if (cc.eventManager)
- cc.eventManager.setEnabled(true);
- };
-
- _p._clear = function () {
- var viewport = this._openGLView.getViewPortRect();
- cc._renderContext.clearRect(-viewport.x, viewport.y, viewport.width, -viewport.height);
- };
-
-
- _p._createStatsLabel = function () {
- var _t = this;
- var fontSize = 0;
- if (_t._winSizeInPoints.width > _t._winSizeInPoints.height)
- fontSize = 0 | (_t._winSizeInPoints.height / 320 * 24);
- else
- fontSize = 0 | (_t._winSizeInPoints.width / 320 * 24);
-
- _t._FPSLabel = new cc.LabelTTF("000.0", "Arial", fontSize);
- _t._SPFLabel = new cc.LabelTTF("0.000", "Arial", fontSize);
- _t._drawsLabel = new cc.LabelTTF("0000", "Arial", fontSize);
-
- var locStatsPosition = cc.DIRECTOR_STATS_POSITION;
- _t._drawsLabel.setPosition(_t._drawsLabel.width / 2 + locStatsPosition.x, _t._drawsLabel.height * 5 / 2 + locStatsPosition.y);
- _t._SPFLabel.setPosition(_t._SPFLabel.width / 2 + locStatsPosition.x, _t._SPFLabel.height * 3 / 2 + locStatsPosition.y);
- _t._FPSLabel.setPosition(_t._FPSLabel.width / 2 + locStatsPosition.x, _t._FPSLabel.height / 2 + locStatsPosition.y);
- };
-
- _p.getVisibleSize = function () {
- //if (this._openGLView) {
- //return this._openGLView.getVisibleSize();
- //} else {
- return this.getWinSize();
- //}
- };
-
- _p.getVisibleOrigin = function () {
- //if (this._openGLView) {
- //return this._openGLView.getVisibleOrigin();
- //} else {
- return cc.p(0, 0);
- //}
- };
-} else {
- cc.Director._fpsImage = new Image();
- cc._addEventListener(cc.Director._fpsImage, "load", function () {
- cc.Director._fpsImageLoaded = true;
- });
- if (cc._fpsImage) {
- cc.Director._fpsImage.src = cc._fpsImage;
- }
- cc.assert(cc.isFunction(cc._tmp.DirectorWebGL), cc._LogInfos.MissingFile, "CCDirectorWebGL.js");
- cc._tmp.DirectorWebGL();
- delete cc._tmp.DirectorWebGL;
-}
\ No newline at end of file
diff --git a/cocos2d/core/CCDirectorCanvas.js b/cocos2d/core/CCDirectorCanvas.js
new file mode 100644
index 0000000000..12deec5914
--- /dev/null
+++ b/cocos2d/core/CCDirectorCanvas.js
@@ -0,0 +1,82 @@
+/****************************************************************************
+ 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.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
+
+ if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
+ var _p = cc.Director.prototype;
+
+ _p.getProjection = function (projection) {
+ return this._projection;
+ };
+
+ _p.setProjection = function (projection) {
+ this._projection = projection;
+ cc.eventManager.dispatchEvent(this._eventProjectionChanged);
+ };
+
+ _p.setDepthTest = function () {
+ };
+
+ _p.setClearColor = function (clearColor) {
+ cc.renderer._clearColor = clearColor;
+ cc.renderer._clearFillStyle = 'rgb(' + clearColor.r + ',' + clearColor.g + ',' + clearColor.b +')' ;
+ };
+
+ _p.setOpenGLView = function (openGLView) {
+ // set size
+ this._winSizeInPoints.width = cc._canvas.width; //this._openGLView.getDesignResolutionSize();
+ this._winSizeInPoints.height = cc._canvas.height;
+ this._openGLView = openGLView || cc.view;
+ if (cc.eventManager)
+ cc.eventManager.setEnabled(true);
+ };
+
+ _p.getVisibleSize = function () {
+ //if (this._openGLView) {
+ //return this._openGLView.getVisibleSize();
+ //} else {
+ return this.getWinSize();
+ //}
+ };
+
+ _p.getVisibleOrigin = function () {
+ //if (this._openGLView) {
+ //return this._openGLView.getVisibleOrigin();
+ //} else {
+ return cc.p(0, 0);
+ //}
+ };
+ } else {
+ cc.Director._fpsImage = new Image();
+ cc.Director._fpsImage.addEventListener("load", function () {
+ cc.Director._fpsImageLoaded = true;
+ });
+ if (cc._fpsImage) {
+ cc.Director._fpsImage.src = cc._fpsImage;
+ }
+ }
+});
diff --git a/cocos2d/core/CCDirectorWebGL.js b/cocos2d/core/CCDirectorWebGL.js
index b9996d58f6..50ae30bdce 100644
--- a/cocos2d/core/CCDirectorWebGL.js
+++ b/cocos2d/core/CCDirectorWebGL.js
@@ -24,8 +24,12 @@
THE SOFTWARE.
****************************************************************************/
+cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
-cc._tmp.DirectorWebGL = function () {
+ // Do nothing under other render mode
+ if (cc._renderType !== cc.game.RENDER_TYPE_WEBGL) {
+ return;
+ }
/**
* OpenGL projection protocol
@@ -42,6 +46,23 @@ cc._tmp.DirectorWebGL = function () {
var _p = cc.Director.prototype;
+ var recursiveChild = function(node){
+ if(node && node._renderCmd){
+ node._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
+ var i, children = node._children;
+ for(i=0; i _t._winSizeInPoints.height)
- fontSize = 0 | (_t._winSizeInPoints.height / 320 * 24);
- else
- fontSize = 0 | (_t._winSizeInPoints.width / 320 * 24);
-
- _t._FPSLabel = new cc.LabelTTF("000.0", "Arial", fontSize);
- _t._SPFLabel = new cc.LabelTTF("0.000", "Arial", fontSize);
- _t._drawsLabel = new cc.LabelTTF("0000", "Arial", fontSize);
-
- var locStatsPosition = cc.DIRECTOR_STATS_POSITION;
- _t._drawsLabel.setPosition(_t._drawsLabel.width / 2 + locStatsPosition.x, _t._drawsLabel.height * 5 / 2 + locStatsPosition.y);
- _t._SPFLabel.setPosition(_t._SPFLabel.width / 2 + locStatsPosition.x, _t._SPFLabel.height * 3 / 2 + locStatsPosition.y);
- _t._FPSLabel.setPosition(_t._FPSLabel.width / 2 + locStatsPosition.x, _t._FPSLabel.height / 2 + locStatsPosition.y);
- };
-
- _p.convertToGL = function (uiPoint) {
- var transform = new cc.kmMat4();
- cc.GLToClipTransform(transform);
-
- var transformInv = new cc.kmMat4();
- cc.kmMat4Inverse(transformInv, transform);
-
- // 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);
-
- return cc.p(glCoord.x, glCoord.y);
- };
-
- _p.convertToUI = function (glPoint) {
- var transform = new cc.kmMat4();
- cc.GLToClipTransform(transform);
-
- var clipCoord = new cc.kmVec3();
- // 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);
-
- 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();
@@ -286,7 +177,7 @@ cc._tmp.DirectorWebGL = function () {
};
_p.getZEye = function () {
- return (this._winSizeInPoints.height / 1.1566 );
+ return (this._winSizeInPoints.height / 1.15469993750 );
};
_p.setViewport = function () {
@@ -316,12 +207,9 @@ cc._tmp.DirectorWebGL = function () {
_p.setGLDefaultValues = function () {
var _t = this;
_t.setAlphaBlending(true);
- // XXX: Fix me, should enable/disable depth test according the depth format as cocos2d-iphone did
- // [self setDepthTest: view_.depthFormat];
- _t.setDepthTest(false);
_t.setProjection(_t._projection);
// set other opengl default values
- cc._renderContext.clearColor(0.0, 0.0, 0.0, 1.0);
+ cc._renderContext.clearColor(0.0, 0.0, 0.0, 0.0);
};
-};
\ No newline at end of file
+});
diff --git a/cocos2d/core/CCDrawingPrimitivesCanvas.js b/cocos2d/core/CCDrawingPrimitivesCanvas.js
index 81596cb2e7..f94b4ca297 100644
--- a/cocos2d/core/CCDrawingPrimitivesCanvas.js
+++ b/cocos2d/core/CCDrawingPrimitivesCanvas.js
@@ -40,7 +40,7 @@ cc.DrawingPrimitiveCanvas = cc.Class.extend(/** @lends cc.DrawingPrimitiveCanvas
_renderContext:null,
/**
* Constructor of cc.DrawingPrimitiveCanvas
- * @param {CanvasRenderingContext2D} renderContext
+ * @param {cc.CanvasContextWrapper} renderContext
*/
ctor:function (renderContext) {
this._renderContext = renderContext;
@@ -56,12 +56,11 @@ cc.DrawingPrimitiveCanvas = cc.Class.extend(/** @lends cc.DrawingPrimitiveCanvas
if (!size) {
size = 1;
}
- var locScaleX = cc.view.getScaleX(), locScaleY = cc.view.getScaleY();
- var newPoint = cc.p(point.x * locScaleX, point.y * locScaleY);
- this._renderContext.beginPath();
- this._renderContext.arc(newPoint.x, -newPoint.y, size * locScaleX, 0, Math.PI * 2, false);
- this._renderContext.closePath();
- this._renderContext.fill();
+ var ctx = this._renderContext.getContext();
+ ctx.beginPath();
+ ctx.arc(point.x, -point.y, size, 0, Math.PI * 2, false);
+ ctx.closePath();
+ ctx.fill();
},
/**
@@ -72,17 +71,17 @@ cc.DrawingPrimitiveCanvas = cc.Class.extend(/** @lends cc.DrawingPrimitiveCanvas
* @param {Number} size
*/
drawPoints:function (points, numberOfPoints, size) {
- if (points == null) {
+ if (points == null)
return;
- }
+
if (!size) {
size = 1;
}
- var locContext = this._renderContext,locScaleX = cc.view.getScaleX(), locScaleY = cc.view.getScaleY();
+ var locContext = this._renderContext.getContext();
locContext.beginPath();
for (var i = 0, len = points.length; i < len; i++)
- locContext.arc(points[i].x * locScaleX, -points[i].y * locScaleY, size * locScaleX, 0, Math.PI * 2, false);
+ locContext.arc(points[i].x, -points[i].y, size, 0, Math.PI * 2, false);
locContext.closePath();
locContext.fill();
},
@@ -94,10 +93,10 @@ cc.DrawingPrimitiveCanvas = cc.Class.extend(/** @lends cc.DrawingPrimitiveCanvas
* @param {cc.Point} destination
*/
drawLine:function (origin, destination) {
- var locContext = this._renderContext, locScaleX = cc.view.getScaleX(), locScaleY = cc.view.getScaleY();
+ var locContext = this._renderContext.getContext();
locContext.beginPath();
- locContext.moveTo(origin.x * locScaleX, -origin.y * locScaleY);
- locContext.lineTo(destination.x * locScaleX, -destination.y * locScaleY);
+ locContext.moveTo(origin.x , -origin.y );
+ locContext.lineTo(destination.x, -destination.y );
locContext.closePath();
locContext.stroke();
},
@@ -108,6 +107,7 @@ cc.DrawingPrimitiveCanvas = cc.Class.extend(/** @lends cc.DrawingPrimitiveCanvas
* @param {cc.Point} destination
*/
drawRect:function (origin, destination) {
+ //todo need optimize for performance
this.drawLine(cc.p(origin.x, origin.y), cc.p(destination.x, origin.y));
this.drawLine(cc.p(destination.x, origin.y), cc.p(destination.x, destination.y));
this.drawLine(cc.p(destination.x, destination.y), cc.p(origin.x, destination.y));
@@ -148,12 +148,11 @@ cc.DrawingPrimitiveCanvas = cc.Class.extend(/** @lends cc.DrawingPrimitiveCanvas
if (vertices.length < 3)
throw new Error("Polygon's point must greater than 2");
- var firstPoint = vertices[0], locContext = this._renderContext;
- var locScaleX = cc.view.getScaleX(), locScaleY = cc.view.getScaleY();
+ var firstPoint = vertices[0], locContext = this._renderContext.getContext();
locContext.beginPath();
- locContext.moveTo(firstPoint.x * locScaleX, -firstPoint.y * locScaleY);
+ locContext.moveTo(firstPoint.x , -firstPoint.y );
for (var i = 1, len = vertices.length; i < len; i++)
- locContext.lineTo(vertices[i].x * locScaleX, -vertices[i].y * locScaleY);
+ locContext.lineTo(vertices[i].x , -vertices[i].y );
if (closePolygon)
locContext.closePath();
@@ -186,13 +185,12 @@ cc.DrawingPrimitiveCanvas = cc.Class.extend(/** @lends cc.DrawingPrimitiveCanvas
*/
drawCircle: function (center, radius, angle, segments, drawLineToCenter) {
drawLineToCenter = drawLineToCenter || false;
- var locContext = this._renderContext;
- var locScaleX = cc.view.getScaleX(), locScaleY = cc.view.getScaleY();
+ var locContext = this._renderContext.getContext();
locContext.beginPath();
var endAngle = angle - Math.PI * 2;
- locContext.arc(0 | (center.x * locScaleX), 0 | -(center.y * locScaleY), radius * locScaleX, -angle, -endAngle, false);
+ locContext.arc(0 | (center.x ), 0 | -(center.y ), radius , -angle, -endAngle, false);
if (drawLineToCenter) {
- locContext.lineTo(0 | (center.x * locScaleX), 0 | -(center.y * locScaleY));
+ locContext.lineTo(0 | (center.x ), 0 | -(center.y ));
}
locContext.stroke();
},
@@ -267,7 +265,7 @@ cc.DrawingPrimitiveCanvas = cc.Class.extend(/** @lends cc.DrawingPrimitiveCanvas
*/
drawCardinalSpline:function (config, tension, segments) {
//lazy_init();
- cc._renderContext.strokeStyle = "rgba(255,255,255,1)";
+ cc._renderContext.setStrokeStyle("rgba(255,255,255,1)");
var points = this._cacheArray;
points.length = 0;
var p, lt;
@@ -277,7 +275,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 {
@@ -308,16 +306,17 @@ cc.DrawingPrimitiveCanvas = cc.Class.extend(/** @lends cc.DrawingPrimitiveCanvas
*/
drawImage:function (image, sourcePoint, sourceSize, destPoint, destSize) {
var len = arguments.length;
+ var ctx = this._renderContext.getContext();
switch (len) {
case 2:
var height = image.height;
- this._renderContext.drawImage(image, sourcePoint.x, -(sourcePoint.y + height));
+ ctx.drawImage(image, sourcePoint.x, -(sourcePoint.y + height));
break;
case 3:
- this._renderContext.drawImage(image, sourcePoint.x, -(sourcePoint.y + sourceSize.height), sourceSize.width, sourceSize.height);
+ ctx.drawImage(image, sourcePoint.x, -(sourcePoint.y + sourceSize.height), sourceSize.width, sourceSize.height);
break;
case 5:
- this._renderContext.drawImage(image, sourcePoint.x, sourcePoint.y, sourceSize.width, sourceSize.height, destPoint.x, -(destPoint.y + destSize.height),
+ ctx.drawImage(image, sourcePoint.x, sourcePoint.y, sourceSize.width, sourceSize.height, destPoint.x, -(destPoint.y + destSize.height),
destSize.width, destSize.height);
break;
default:
@@ -328,15 +327,16 @@ cc.DrawingPrimitiveCanvas = cc.Class.extend(/** @lends cc.DrawingPrimitiveCanvas
/**
* draw a star
- * @param {CanvasRenderingContext2D} ctx canvas context
+ * @param {cc.CanvasContextWrapper} ctx canvas context
* @param {Number} radius
* @param {cc.Color} color
*/
drawStar:function (ctx, radius, color) {
- var context = ctx || this._renderContext;
- radius *= cc.view.getScaleX();
+ var wrapper = ctx || this._renderContext;
+ var context = wrapper.getContext();
var colorStr = "rgba(" + (0 | color.r) + "," + (0 | color.g) + "," + (0 | color.b);
- context.fillStyle = colorStr + ",1)";
+ wrapper.setFillStyle(colorStr + ",1)");
+ //context.fillStyle = colorStr + ",1)";
var subRadius = radius / 10;
context.beginPath();
@@ -352,11 +352,12 @@ cc.DrawingPrimitiveCanvas = cc.Class.extend(/** @lends cc.DrawingPrimitiveCanvas
context.closePath();
context.fill();
- var g1 = context.createRadialGradient(0, 0, subRadius, 0, 0, radius);
- g1.addColorStop(0, colorStr + ", 1)");
- g1.addColorStop(0.3, colorStr + ", 0.8)");
- g1.addColorStop(1.0, colorStr + ", 0.0)");
- context.fillStyle = g1;
+ var rg = context.createRadialGradient(0, 0, subRadius, 0, 0, radius);
+ rg.addColorStop(0, colorStr + ", 1)");
+ rg.addColorStop(0.3, colorStr + ", 0.8)");
+ rg.addColorStop(1.0, colorStr + ", 0.0)");
+ wrapper.setFillStyle(rg);
+ //context.fillStyle = g1;
context.beginPath();
var startAngle_1 = 0;
var endAngle_1 = cc.PI2;
@@ -367,13 +368,13 @@ cc.DrawingPrimitiveCanvas = cc.Class.extend(/** @lends cc.DrawingPrimitiveCanvas
/**
* draw a color ball
- * @param {CanvasRenderingContext2D} ctx canvas context
+ * @param {cc.CanvasContextWrapper} ctx canvas context
* @param {Number} radius
* @param {cc.Color} color
*/
drawColorBall:function (ctx, radius, color) {
- var context = ctx || this._renderContext;
- radius *= cc.view.getScaleX();
+ var wrapper = ctx || this._renderContext;
+ var context = wrapper.getContext();
var colorStr = "rgba(" +(0|color.r) + "," + (0|color.g) + "," + (0|color.b);
var subRadius = radius / 10;
@@ -382,7 +383,8 @@ cc.DrawingPrimitiveCanvas = cc.Class.extend(/** @lends cc.DrawingPrimitiveCanvas
g1.addColorStop(0.3, colorStr + ", 0.8)");
g1.addColorStop(0.6, colorStr + ", 0.4)");
g1.addColorStop(1.0, colorStr + ", 0.0)");
- context.fillStyle = g1;
+ wrapper.setFillStyle(g1);
+ //context.fillStyle = g1;
context.beginPath();
var startAngle_1 = 0;
var endAngle_1 = cc.PI2;
@@ -398,7 +400,7 @@ cc.DrawingPrimitiveCanvas = cc.Class.extend(/** @lends cc.DrawingPrimitiveCanvas
* @param {Number} y
*/
fillText:function (strText, x, y) {
- this._renderContext.fillText(strText, x, -y);
+ this._renderContext.getContext().fillText(strText, x, -y);
},
/**
@@ -409,8 +411,8 @@ cc.DrawingPrimitiveCanvas = cc.Class.extend(/** @lends cc.DrawingPrimitiveCanvas
* @param {Number} a Alpha value (0 to 255)
*/
setDrawColor:function (r, g, b, a) {
- this._renderContext.fillStyle = "rgba(" + r + "," + g + "," + b + "," + a / 255 + ")";
- this._renderContext.strokeStyle = "rgba(" + r + "," + g + "," + b + "," + a / 255 + ")";
+ this._renderContext.setFillStyle("rgba(" + r + "," + g + "," + b + "," + a / 255 + ")");
+ this._renderContext.setStrokeStyle("rgba(" + r + "," + g + "," + b + "," + a / 255 + ")");
},
/**
@@ -425,6 +427,6 @@ cc.DrawingPrimitiveCanvas = cc.Class.extend(/** @lends cc.DrawingPrimitiveCanvas
* @param {Number} width
*/
setLineWidth:function (width) {
- this._renderContext.lineWidth = width * cc.view.getScaleX();
+ this._renderContext.getContext().lineWidth = width;
}
});
\ No newline at end of file
diff --git a/cocos2d/core/CCDrawingPrimitivesWebGL.js b/cocos2d/core/CCDrawingPrimitivesWebGL.js
index f5461a01f5..6daa60cb01 100644
--- a/cocos2d/core/CCDrawingPrimitivesWebGL.js
+++ b/cocos2d/core/CCDrawingPrimitivesWebGL.js
@@ -33,9 +33,9 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL#
_renderContext:null,
_initialized:false,
_shader: null,
- _colorLocation:-1,
+ _colorLocation: "u_color",
_colorArray: null,
- _pointSizeLocation:-1,
+ _pointSizeLocation: "u_pointSize",
_pointSize:-1,
/**
* contructor of cc.DrawingPrimitiveWebGL
@@ -46,7 +46,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL#
ctx = cc._renderContext;
if (!ctx instanceof WebGLRenderingContext)
- throw "Can't initialise DrawingPrimitiveWebGL. context need is WebGLRenderingContext";
+ throw new Error("Can't initialise DrawingPrimitiveWebGL. context need is WebGLRenderingContext");
this._renderContext = ctx;
this._colorArray = new Float32Array([1.0, 1.0, 1.0, 1.0]);
@@ -59,8 +59,9 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL#
// Position and 1 color passed as a uniform (to similate glColor4ub )
//
_t._shader = cc.shaderCache.programForKey(cc.SHADER_POSITION_UCOLOR);
- _t._colorLocation = _t._renderContext.getUniformLocation(_t._shader.getProgram(), "u_color");
- _t._pointSizeLocation = _t._renderContext.getUniformLocation(_t._shader.getProgram(), "u_pointSize");
+ _t._shader._addUniformLocation(this._colorLocation);
+ _t._shader._addUniformLocation(this._pointSizeLocation);
+ _t._glProgramState = cc.GLProgramState.getOrCreateWithGLProgram(_t._shader);
_t._initialized = true;
}
@@ -81,10 +82,10 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL#
this.lazy_init();
var glContext = this._renderContext;
- this._shader.use();
+ this._glProgramState.apply();
this._shader.setUniformForModelViewAndProjectionMatrixWithMat4();
- cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POSITION);
- glContext.uniform4fv(this._colorLocation, this._colorArray);
+ glContext.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION);
+ this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray);
this._shader.setUniformLocationWith1f(this._pointSizeLocation, this._pointSize);
var pointBuffer = glContext.createBuffer();
@@ -104,16 +105,16 @@ 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();
var glContext = this._renderContext;
- this._shader.use();
+ this._glProgramState.apply();
this._shader.setUniformForModelViewAndProjectionMatrixWithMat4();
- cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POSITION);
- glContext.uniform4fv(this._colorLocation, this._colorArray);
+ glContext.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION);
+ this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray);
this._shader.setUniformLocationWith1f(this._pointSizeLocation, this._pointSize);
var pointBuffer = glContext.createBuffer();
@@ -145,10 +146,10 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL#
this.lazy_init();
var glContext = this._renderContext;
- this._shader.use();
+ this._glProgramState.apply();
this._shader.setUniformForModelViewAndProjectionMatrixWithMat4();
- cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POSITION);
- glContext.uniform4fv(this._colorLocation, this._colorArray);
+ glContext.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION);
+ this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray);
var pointBuffer = glContext.createBuffer();
glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer);
@@ -200,10 +201,10 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL#
this.lazy_init();
var glContext = this._renderContext;
- this._shader.use();
+ this._glProgramState.apply();
this._shader.setUniformForModelViewAndProjectionMatrixWithMat4();
- cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POSITION);
- glContext.uniform4fv(this._colorLocation, this._colorArray);
+ glContext.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION);
+ this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray);
var pointBuffer = glContext.createBuffer();
glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer);
@@ -231,10 +232,10 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL#
this.setDrawColor(color.r, color.g, color.b, color.a);
var glContext = this._renderContext;
- this._shader.use();
+ this._glProgramState.apply();
this._shader.setUniformForModelViewAndProjectionMatrixWithMat4();
- cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POSITION);
- glContext.uniform4fv(this._colorLocation, this._colorArray);
+ glContext.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION);
+ this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray);
var pointBuffer = glContext.createBuffer();
glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer);
@@ -279,10 +280,10 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL#
vertices[(segments + 1) * 2 + 1] = center.y;
var glContext = this._renderContext;
- this._shader.use();
+ this._glProgramState.apply();
this._shader.setUniformForModelViewAndProjectionMatrixWithMat4();
- cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POSITION);
- glContext.uniform4fv(this._colorLocation, this._colorArray);
+ glContext.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION);
+ this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray);
var pointBuffer = glContext.createBuffer();
glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer);
@@ -317,10 +318,10 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL#
vertices[segments * 2 + 1] = destination.y;
var glContext = this._renderContext;
- this._shader.use();
+ this._glProgramState.apply();
this._shader.setUniformForModelViewAndProjectionMatrixWithMat4();
- cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POSITION);
- glContext.uniform4fv(this._colorLocation, this._colorArray);
+ glContext.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION);
+ this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray);
var pointBuffer = glContext.createBuffer();
glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer);
@@ -356,10 +357,10 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL#
vertices[segments * 2 + 1] = destination.y;
var glContext = this._renderContext;
- this._shader.use();
+ this._glProgramState.apply();
this._shader.setUniformForModelViewAndProjectionMatrixWithMat4();
- cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POSITION);
- glContext.uniform4fv(this._colorLocation, this._colorArray);
+ glContext.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION);
+ this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray);
var pointBuffer = glContext.createBuffer();
glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer);
@@ -395,7 +396,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 +404,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),
@@ -416,10 +417,10 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL#
}
var glContext = this._renderContext;
- this._shader.use();
+ this._glProgramState.apply();
this._shader.setUniformForModelViewAndProjectionMatrixWithMat4();
- cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POSITION);
- glContext.uniform4fv(this._colorLocation, this._colorArray);
+ glContext.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION);
+ this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray);
var pointBuffer = glContext.createBuffer();
glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer);
diff --git a/cocos2d/core/CCScheduler.js b/cocos2d/core/CCScheduler.js
index df1f7354cc..1504bd70c0 100644
--- a/cocos2d/core/CCScheduler.js
+++ b/cocos2d/core/CCScheduler.js
@@ -24,64 +24,108 @@
THE SOFTWARE.
****************************************************************************/
+(function () {
-/**
- * Minimum priority level for user scheduling.
- * @constant
- * @type Number
- */
-cc.PRIORITY_NON_SYSTEM = cc.PRIORITY_SYSTEM + 1;
+
+var MAX_POOL_SIZE = 20;
//data structures
/**
* A list double-linked list used for "updates with priority"
- * @Class
- * @name cc.ListEntry
- * @param {cc.ListEntry} prev
- * @param {cc.ListEntry} next
+ * @param {ListEntry} prev
+ * @param {ListEntry} next
+ * @param {function} callback
* @param {cc.Class} target not retained (retained by hashUpdateEntry)
* @param {Number} priority
* @param {Boolean} paused
* @param {Boolean} markedForDeletion selector will no longer be called and entry will be removed at end of the next tick
*/
-cc.ListEntry = function (prev, next, target, priority, paused, markedForDeletion) {
+var 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;
this.markedForDeletion = markedForDeletion;
};
+var _listEntries = [];
+ListEntry.get = function (prev, next, callback, target, priority, paused, markedForDeletion) {
+ var result = _listEntries.pop();
+ if (result) {
+ result.prev = prev;
+ result.next = next;
+ result.callback = callback;
+ result.target = target;
+ result.priority = priority;
+ result.paused = paused;
+ result.markedForDeletion = markedForDeletion;
+ }
+ else {
+ result = new ListEntry(prev, next, callback, target, priority, paused, markedForDeletion);
+ }
+ return result;
+};
+ListEntry.put = function (entry) {
+ entry.prev = null;
+ entry.next = null;
+ entry.callback = null;
+ entry.target = null;
+ entry.priority = 0;
+ entry.paused = false;
+ entry.markedForDeletion = false;
+ if (_listEntries.length < MAX_POOL_SIZE)
+ _listEntries.push(entry);
+};
+
/**
* A update entry list
- * @Class
- * @name cc.HashUpdateEntry
- * @param {cc.ListEntry} list Which list does it belong to ?
- * @param {cc.ListEntry} entry entry in the list
+ * @param {Array} list Which list does it belong to ?
+ * @param {ListEntry} entry entry in the list
* @param {cc.Class} target hash key (retained)
- * @param {Array} hh
+ * @param {function} callback
*/
-cc.HashUpdateEntry = function (list, entry, target, hh) {
+var HashUpdateEntry = function (list, entry, target, callback) {
this.list = list;
this.entry = entry;
this.target = target;
- this.hh = hh;
+ this.callback = callback;
+};
+var _hashUpdateEntries = [];
+HashUpdateEntry.get = function (list, entry, target, callback) {
+ var result = _hashUpdateEntries.pop();
+ if (result) {
+ result.list = list;
+ result.entry = entry;
+ result.target = target;
+ result.callback = callback;
+ }
+ else {
+ result = new HashUpdateEntry(list, entry, target, callback);
+ }
+ return result;
+};
+HashUpdateEntry.put = function (entry) {
+ entry.list = null;
+ entry.entry = null;
+ entry.target = null;
+ entry.callback = null;
+ if (_hashUpdateEntries.length < MAX_POOL_SIZE)
+ _hashUpdateEntries.push(entry);
};
//
/**
* Hash Element used for "selectors with interval"
- * @Class
* @param {Array} timers
* @param {cc.Class} target hash key (retained)
* @param {Number} timerIndex
- * @param {cc.Timer} currentTimer
+ * @param {CallbackTimer} currentTimer
* @param {Boolean} currentTimerSalvaged
* @param {Boolean} paused
- * @param {Array} hh
*/
-cc.HashTimerEntry = function (timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused, hh) {
+var HashTimerEntry = function (timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused) {
var _t = this;
_t.timers = timers;
_t.target = target;
@@ -89,27 +133,68 @@ cc.HashTimerEntry = function (timers, target, timerIndex, currentTimer, currentT
_t.currentTimer = currentTimer;
_t.currentTimerSalvaged = currentTimerSalvaged;
_t.paused = paused;
- _t.hh = hh;
+};
+var _hashTimerEntries = [];
+HashTimerEntry.get = function (timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused) {
+ var result = _hashTimerEntries.pop();
+ if (result) {
+ result.timers = timers;
+ result.target = target;
+ result.timerIndex = timerIndex;
+ result.currentTimer = currentTimer;
+ result.currentTimerSalvaged = currentTimerSalvaged;
+ result.paused = paused;
+ }
+ else {
+ result = new HashTimerEntry(timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused);
+ }
+ return result;
+};
+HashTimerEntry.put = function (entry) {
+ entry.timers = null;
+ entry.target = null;
+ entry.timerIndex = 0;
+ entry.currentTimer = null;
+ entry.currentTimerSalvaged = false;
+ entry.paused = false;
+ if (_hashTimerEntries.length < MAX_POOL_SIZE)
+ _hashTimerEntries.push(entry);
};
/**
* Light weight timer
- * @class
* @extends cc.Class
*/
-cc.Timer = cc.Class.extend(/** @lends cc.Timer# */{
- _interval:0.0,
- _callback:null,//is called _callback before
-
- _target:null,//target of _callback
- _elapsed:0.0,
-
- _runForever:false,
- _useDelay:false,
- _timesExecuted:0,
- _repeat:0, //0 = once, 1 is 2 x executed
- _delay:0,
-
+var CallbackTimer = function () {
+ this._scheduler = null;
+ this._elapsed = -1;
+ this._runForever = false;
+ this._useDelay = false;
+ this._timesExecuted = 0;
+ this._repeat = 0;
+ this._delay = 0;
+ this._interval = 0;
+
+ this._target = null;
+ this._callback = null;
+ this._key = null;
+};
+cc.inject({
+ initWithCallback: function (scheduler, callback, target, seconds, repeat, delay, key) {
+ this._scheduler = scheduler;
+ this._target = target;
+ this._callback = callback;
+ if (key)
+ this._key = key;
+
+ this._elapsed = -1;
+ this._interval = seconds;
+ this._delay = delay;
+ this._useDelay = (this._delay > 0);
+ this._repeat = repeat;
+ this._runForever = (this._repeat === cc.REPEAT_FOREVER);
+ return true;
+ },
/**
* @return {Number} returns interval of timer
*/
@@ -119,86 +204,84 @@ cc.Timer = cc.Class.extend(/** @lends cc.Timer# */{
*/
setInterval : function(interval){this._interval = interval;},
- /**
- * @return {String|function} returns callback
- */
- getCallback : function(){return this._callback},
-
-
- /**
- * 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) {
- 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);
- },
-
/**
* triggers the 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._callback && !this._runForever && this._timesExecuted > this._repeat)
+ this.cancel();
}
}
+ },
+
+ getCallback: function(){
+ return this._callback;
+ },
+
+ getKey: function(){
+ return this._key;
+ },
+
+ trigger: function () {
+ if (this._target && this._callback){
+ this._callback.call(this._target, this._elapsed);
+ }
+ },
+
+ cancel: function () {
+ //override
+ this._scheduler.unschedule(this._callback, this._target);
}
-});
+}, CallbackTimer.prototype);
+
+var _timers = [];
+CallbackTimer.get = function () {
+ return _timers.pop() || new CallbackTimer();
+};
+CallbackTimer.put = function (timer) {
+ timer._scheduler = null;
+ timer._elapsed = -1;
+ timer._runForever = false;
+ timer._useDelay = false;
+ timer._timesExecuted = 0;
+ timer._repeat = 0;
+ timer._delay = 0;
+ timer._interval = 0;
+ timer._target = null;
+ timer._callback = null;
+ timer._key = null;
+ if (_timers.length < MAX_POOL_SIZE)
+ _timers.push(timer);
+};
/**
*
@@ -216,65 +299,112 @@ cc.Timer = cc.Class.extend(/** @lends cc.Timer# */{
*
* @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,
- _updates : null, //_updates[0] list of priority < 0, _updates[1] list of priority == 0, _updates[2] list of priority > 0,
-
- _hashForUpdates:null, // hash used to fetch quickly the list entries for pause,delete,etc
- _arrayForUpdates:null,
+ //_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,
_hashForTimers:null, //Used for "selectors with interval"
- _arrayForTimes:null,
+ _arrayForTimers:null, //Speed up indexing
+ _hashForUpdates:null, // hash used to fetch quickly the list entries for pause,delete,etc
+ //_arrayForUpdates:null, //Speed up indexing
_currentTarget:null,
_currentTargetSalvaged:false,
_updateHashLocked:false, //If true unschedule will not remove anything from a hash. Elements will only be marked for deletion.
+
ctor:function () {
- var self = this;
- self._timeScale = 1.0;
- self._updates = [[], [], []];
+ this._timeScale = 1.0;
+ this._updatesNegList = [];
+ this._updates0List = [];
+ this._updatesPosList = [];
- self._hashForUpdates = {};
- self._arrayForUpdates = [];
+ this._hashForUpdates = {};
+ this._hashForTimers = {};
+ this._currentTarget = null;
+ this._currentTargetSalvaged = false;
+ this._updateHashLocked = false;
- self._hashForTimers = {};
- self._arrayForTimers = [];
+ this._arrayForTimers = [];
+ //this._arrayForUpdates = [];
- self._currentTarget = null;
- self._currentTargetSalvaged = false;
- self._updateHashLocked = false;
},
//-----------------------private method----------------------
+
+ _schedulePerFrame: function(callback, target, priority, paused){
+ var hashElement = this._hashForUpdates[target.__instanceId];
+ if (hashElement && hashElement.entry){
+ // check if priority has changed
+ if (hashElement.entry.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 why 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);
- element.Timer = null;
- element.target = null;
- element = null;
+ var arr = this._arrayForTimers;
+ for (var i = 0, l = arr.length; i < l; i++) {
+ if (arr[i] === element) {
+ arr.splice(i, 1);
+ break;
+ }
+ }
+ HashTimerEntry.put(element);
},
_removeUpdateFromHash:function (entry) {
- var self = this, element = self._hashForUpdates[entry.target.__instanceId];
+ var self = this;
+ var element = self._hashForUpdates[entry.target.__instanceId];
if (element) {
- //list entry
- cc.arrayRemoveObject(element.list, element.entry);
+ // Remove list entry from list
+ var list = element.list, listEntry = element.entry;
+ for (var i = 0, l = list.length; i < l; i++) {
+ if (list[i] === listEntry) {
+ list.splice(i, 1);
+ break;
+ }
+ }
delete self._hashForUpdates[element.target.__instanceId];
- cc.arrayRemoveObject(self._arrayForUpdates, element);
- element.entry = null;
-
- //hash entry
- element.target = null;
+ ListEntry.put(listEntry);
+ HashUpdateEntry.put(element);
}
},
- _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 = ListEntry.get(null, null, callback, target, priority, paused, false);
// empey list ?
if (!ppList) {
@@ -292,21 +422,18 @@ 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;
+ self._hashForUpdates[target.__instanceId] = HashUpdateEntry.get(ppList, listElement, target, null);
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 = ListEntry.get(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);
- self._hashForUpdates[target.__instanceId] = hashElement;
+ self._hashForUpdates[target.__instanceId] = HashUpdateEntry.get(ppList, listElement, target, null, null);
},
//-----------------------public method-------------------------
@@ -337,33 +464,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,34 +565,51 @@ 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 tmp = callback;
+ callback = target;
+ target = tmp;
+ isSelector = true;
+ }
+ //callback, target, interval, repeat, delay, paused, key
+ //callback, target, interval, paused, key
+ if(arguments.length === 4 || arguments.length === 5){
+ key = delay;
+ paused = repeat;
+ repeat = cc.REPEAT_FOREVER;
+ delay = 0;
+ }
+ if (key === undefined) {
+ key = target.__instanceId + "";
+ }
cc.assert(target, cc._LogInfos.Scheduler_scheduleCallbackForTarget_3);
- // default arguments
- interval = interval || 0;
- repeat = (repeat == null) ? cc.REPEAT_FOREVER : repeat;
- delay = delay || 0;
- paused = paused || false;
-
- var self = this, timer;
- var element = self._hashForTimers[target.__instanceId];
+ var element = this._hashForTimers[target.__instanceId];
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;
+ element = HashTimerEntry.get(null, target, 0, null, null, paused);
+ this._arrayForTimers.push(element);
+ this._hashForTimers[target.__instanceId] = element;
+ } else {
+ cc.assert(element.paused === paused, "");
}
+ var timer, i;
if (element.timers == null) {
element.timers = [];
} else {
- for (var i = 0; i < element.timers.length; i++) {
+ for (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;
@@ -446,81 +617,54 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{
}
}
- timer = new cc.Timer(target, callback_fn, interval, repeat, delay);
+ timer = CallbackTimer.get();
+ timer.initWithCallback(this, callback, target, interval, repeat, delay, key);
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;
- }
+ scheduleUpdate: function(target, priority, paused){
+ this._schedulePerFrame(function(dt){
+ target.update(dt);
+ }, target, priority, paused);
+ },
- // 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);
+ _getUnscheduleMark: function(key, timer){
+ //key, callback
+ switch (typeof key){
+ case "number":
+ case "string":
+ return key === timer._key;
+ case "function":
+ return key === timer._callback;
}
},
+ unschedule: function (key, target) {
+ //key, target
+ //selector, target
+ //callback, target - This is in order to increase compatibility
- /**
- *
- * 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) {
// 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 ((timer == element.currentTimer) && (!element.currentTimerSalvaged)) {
+ if (this._getUnscheduleMark(key, timer)) {
+ if ((timer === element.currentTimer) && (!element.currentTimerSalvaged)) {
element.currentTimerSalvaged = true;
}
- timers.splice(i, 1)
+ timers.splice(i, 1);
+ CallbackTimer.put(timer);
//update timerIndex in case we are in tick;, looping over the actions
if (element.timerIndex >= i) {
element.timerIndex--;
}
- if (timers.length == 0) {
- if (self._currentTarget == element) {
+ if (timers.length === 0) {
+ if (self._currentTarget === element) {
self._currentTargetSalvaged = true;
} else {
self._removeHashElement(element);
@@ -532,86 +676,124 @@ 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)
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);
+ 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){
return;
}
- var self = this, element = self._hashForTimers[target.__instanceId];
+ // Custom Selectors
+ var element = this._hashForTimers[target.__instanceId];
+
if (element) {
var timers = element.timers;
- if ((!element.currentTimerSalvaged) && (timers.indexOf(element.currentTimer) >= 0)) {
+ if (timers.indexOf(element.currentTimer) > -1 &&
+ (!element.currentTimerSalvaged)) {
element.currentTimerSalvaged = true;
}
+ for (var i = 0, l = timers.length; i < l; i++) {
+ CallbackTimer.put(timers[i]);
+ }
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.
- *
- * 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);
- }
- 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);
+ var i, element, arr = this._arrayForTimers;
+ for(i=arr.length-1; i>=0; i--){
+ element = arr[i];
+ this.unscheduleAllForTarget(element.target);
+ }
+
+ // 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)
+ this.unscheduleUpdate(entry.target);
+ if (temp_length == this._updatesPosList.length)
+ i++;
+ }
+ },
+
+ isScheduled: function(callback, target){
+ //key, target
+ //selector, target
+ cc.assert(callback, "Argument callback must not be empty");
+ cc.assert(target, "Argument target must be non-nullptr");
+
+ var element = this._hashForTimers[target.__instanceId];
+
+ if (!element) {
+ return false;
+ }
+
+ if (element.timers == null){
+ return false;
+ }
+ else {
+ var timers = element.timers;
+ for (var i = 0; i < timers.length; ++i) {
+ var timer = timers[i];
+
+ if (callback === timer._callback){
+ return true;
+ }
}
+ return false;
}
},
@@ -633,25 +815,50 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{
pauseAllTargetsWithMinPriority:function (minPriority) {
var idsWithSelectors = [];
- var self = this, element, locArrayForTimers = self._arrayForTimers, locUpdates = self._updates;
+ var self = this, element, locArrayForTimers = self._arrayForTimers;
+ 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++){
- var updates = locUpdates[i];
- for(var j = 0, lj = updates.length; j < lj; j++){
- element = updates[j];
- if (element) {
- element.paused = true;
- idsWithSelectors.push(element.target);
+
+ var entry;
+ if(minPriority < 0){
+ for(i=0; i= minPriority){
+ entry.paused = true;
+ idsWithSelectors.push(entry.target);
+ }
+ }
+ }
+ }
+
+ if(minPriority <= 0){
+ for(i=0; i= minPriority){
+ entry.paused = true;
+ idsWithSelectors.push(entry.target);
}
}
}
+
return idsWithSelectors;
},
@@ -733,12 +940,110 @@ 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.
+ *
+ * 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);
+ },
+
+ /**
+ * 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.unscheduleUpdate(target);
+ },
+
+ /**
+ * 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.unschedule(target.__instanceId + "", target);
+ },
+
+ /**
+ *
+ * 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 unscheduleAll.");
+ 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);
}
});
+
/**
* Priority level reserved for system services.
* @constant
* @type Number
*/
cc.Scheduler.PRIORITY_SYSTEM = (-2147483647 - 1);
+
+/**
+ * Minimum priority level for user scheduling.
+ * @constant
+ * @type Number
+ */
+cc.Scheduler.PRIORITY_NON_SYSTEM = cc.Scheduler.PRIORITY_SYSTEM + 1;
+
+})();
diff --git a/cocos2d/core/base-nodes/CCAtlasNode.js b/cocos2d/core/base-nodes/CCAtlasNode.js
index c2b543931a..336ab7cc57 100644
--- a/cocos2d/core/base-nodes/CCAtlasNode.js
+++ b/cocos2d/core/base-nodes/CCAtlasNode.js
@@ -68,6 +68,7 @@ cc.AtlasNode = cc.Node.extend(/** @lends cc.AtlasNode# */{
_ignoreContentScaleFactor: false,
_className: "AtlasNode",
+ _texture: null,
_textureForCanvas: null,
/**
@@ -85,7 +86,7 @@ cc.AtlasNode = cc.Node.extend(/** @lends cc.AtlasNode# */{
},
_createRenderCmd: function(){
- if(cc._renderType === cc._RENDER_TYPE_CANVAS)
+ if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
this._renderCmd = new cc.AtlasNode.CanvasRenderCmd(this);
else
this._renderCmd = new cc.AtlasNode.WebGLRenderCmd(this);
@@ -202,7 +203,7 @@ cc.AtlasNode = cc.Node.extend(/** @lends cc.AtlasNode# */{
*/
initWithTileFile: function (tile, tileWidth, tileHeight, itemsToRender) {
if (!tile)
- throw "cc.AtlasNode.initWithTileFile(): title should not be null";
+ throw new Error("cc.AtlasNode.initWithTileFile(): title should not be null");
var texture = cc.textureCache.addImage(tile);
return this.initWithTexture(texture, tileWidth, tileHeight, itemsToRender);
},
@@ -244,7 +245,7 @@ cc.AtlasNode = cc.Node.extend(/** @lends cc.AtlasNode# */{
* @return {cc.Texture2D}
*/
getTexture: function(){
- return this._renderCmd.getTexture();
+ return this._texture;
},
/**
@@ -253,7 +254,7 @@ cc.AtlasNode = cc.Node.extend(/** @lends cc.AtlasNode# */{
* @param {cc.Texture2D} texture The new texture
*/
setTexture: function(texture){
- this._renderCmd.setTexture(texture);
+ this._texture = texture;
},
_setIgnoreContentScaleFactor: function (ignoreContentScaleFactor) {
diff --git a/cocos2d/core/base-nodes/CCAtlasNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCAtlasNodeCanvasRenderCmd.js
index e236ae82fb..4fb324f4a9 100644
--- a/cocos2d/core/base-nodes/CCAtlasNodeCanvasRenderCmd.js
+++ b/cocos2d/core/base-nodes/CCAtlasNodeCanvasRenderCmd.js
@@ -25,111 +25,64 @@
/**
* cc.AtlasNode's rendering objects of Canvas
*/
-(function(){
- cc.AtlasNode.CanvasRenderCmd = function(renderableObject){
- cc.Node.CanvasRenderCmd.call(this, renderableObject);
+(function () {
+ cc.AtlasNode.CanvasRenderCmd = function (renderableObject) {
+ this._rootCtor(renderableObject);
this._needDraw = false;
this._colorUnmodified = cc.color.WHITE;
- this._originalTexture = null;
- this._texture = null;
+ this._textureToRender = null;
};
var proto = cc.AtlasNode.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
proto.constructor = cc.AtlasNode.CanvasRenderCmd;
- proto.initWithTexture = function(texture, tileWidth, tileHeight, itemsToRender){
+ proto.initWithTexture = function (texture, tileWidth, tileHeight, itemsToRender) {
var node = this._node;
node._itemWidth = tileWidth;
node._itemHeight = tileHeight;
node._opacityModifyRGB = true;
- this._originalTexture = texture;
- if (!this._originalTexture) {
+ node._texture = texture;
+ if (!node._texture) {
cc.log(cc._LogInfos.AtlasNode__initWithTexture);
return false;
}
- this._texture = this._originalTexture;
+ this._textureToRender = texture;
this._calculateMaxItems();
node.quadsToDraw = itemsToRender;
return true;
};
- proto.setColor = function(color3){
+ proto.setColor = function (color3) {
var node = this._node;
var locRealColor = node._realColor;
- if ((locRealColor.r == color3.r) && (locRealColor.g == color3.g) && (locRealColor.b == color3.b))
+ if ((locRealColor.r === color3.r) && (locRealColor.g === color3.g) && (locRealColor.b === color3.b))
return;
this._colorUnmodified = color3;
this._changeTextureColor();
};
- if(cc.sys._supportCanvasNewBlendModes)
- proto._changeTextureColor = function(){
- var node = this._node;
- var locTexture = node.getTexture();
- if (locTexture && this._originalTexture) {
- var element = this._originalTexture.getHtmlElementObj();
- if(!element)
- return;
- var locElement = locTexture.getHtmlElementObj();
- var textureRect = cc.rect(0, 0, element.width, element.height);
- if (locElement instanceof HTMLCanvasElement)
- cc.Sprite.CanvasRenderCmd._generateTintImageWithMultiply(element, this._colorUnmodified, textureRect, locElement);
- else {
- locElement = cc.Sprite.CanvasRenderCmd._generateTintImageWithMultiply(element, this._colorUnmodified, textureRect);
- locTexture = new cc.Texture2D();
- locTexture.initWithElement(locElement);
- locTexture.handleLoadedTexture();
- node.setTexture(locTexture);
- }
- }
- };
- else
- proto._changeTextureColor = function(){
- var node = this._node;
- var locElement, locTexture = node.getTexture();
- if (locTexture && this._originalTexture) {
- locElement = locTexture.getHtmlElementObj();
- if (!locElement)
- return;
- var element = this._originalTexture.getHtmlElementObj();
- var cacheTextureForColor = cc.textureCache.getTextureColors(element);
- if (cacheTextureForColor) {
- var textureRect = cc.rect(0, 0, element.width, element.height);
- if (locElement instanceof HTMLCanvasElement)
- cc.Sprite.CanvasRenderCmd._generateTintImage(locElement, cacheTextureForColor, this._displayedColor, textureRect, locElement);
- else {
- locElement = cc.Sprite.CanvasRenderCmd._generateTintImage(locElement, cacheTextureForColor, this._displayedColor, textureRect);
- locTexture = new cc.Texture2D();
- locTexture.initWithElement(locElement);
- locTexture.handleLoadedTexture();
- node.setTexture(locTexture);
- }
- }
- }
- };
-
- proto.setOpacity = function(opacity){
+ proto._changeTextureColor = function () {
var node = this._node;
- cc.Node.prototype.setOpacity.call(node, opacity);
- // special opacity for premultiplied textures
- //if (node._opacityModifyRGB) {
- // node.color = this._colorUnmodified;
- //}
- };
-
- proto.getTexture = function(){
- return this._texture;
+ var texture = node._texture,
+ color = this._colorUnmodified,
+ element = texture.getHtmlElementObj();
+ var textureRect = cc.rect(0, 0, element.width, element.height);
+ if (texture === this._textureToRender)
+ this._textureToRender = texture._generateColorTexture(color.r, color.g, color.b, textureRect);
+ else
+ texture._generateColorTexture(color.r, color.g, color.b, textureRect, this._textureToRender.getHtmlElementObj());
};
- proto.setTexture = function (texture) {
- this._texture = texture;
+ proto.setOpacity = function (opacity) {
+ var node = this._node;
+ cc.Node.prototype.setOpacity.call(node, opacity);
};
- proto._calculateMaxItems = function(){
+ proto._calculateMaxItems = function () {
var node = this._node;
- var selTexture = this._texture;
+ var selTexture = node._texture;
var size = selTexture.getContentSize();
node._itemsPerColumn = 0 | (size.height / node._itemHeight);
diff --git a/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js b/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js
index 4e6a863ac6..5810d00794 100644
--- a/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js
+++ b/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js
@@ -25,14 +25,21 @@
/**
* cc.AtlasNode's rendering objects of WebGL
*/
-(function(){
- cc.AtlasNode.WebGLRenderCmd = function(renderableObject){
- cc.Node.WebGLRenderCmd.call(this, renderableObject);
+(function () {
+ cc.AtlasNode.WebGLRenderCmd = function (renderableObject) {
+ this._rootCtor(renderableObject);
this._needDraw = true;
this._textureAtlas = null;
this._colorUnmodified = cc.color.WHITE;
this._colorF32Array = null;
this._uniformColor = null;
+
+ this._matrix = new cc.math.Matrix4();
+ this._matrix.identity();
+
+ //shader stuff
+ this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURE_UCOLOR);
+ this._uniformColor = cc._renderContext.getUniformLocation(this._shaderProgram.getProgram(), "u_color");
};
var proto = cc.AtlasNode.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
@@ -53,8 +60,15 @@
proto.rendering = function (ctx) {
var context = ctx || cc._renderContext, node = this._node;
- this._shaderProgram.use();
- this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix);
+ var wt = this._worldTransform;
+ this._matrix.mat[0] = wt.a;
+ this._matrix.mat[4] = wt.c;
+ this._matrix.mat[12] = wt.tx;
+ this._matrix.mat[1] = wt.b;
+ this._matrix.mat[5] = wt.d;
+ this._matrix.mat[13] = wt.ty;
+
+ this._glProgramState.apply(this._matrix);
cc.glBlendFunc(node._blendFunc.src, node._blendFunc.dst);
if (this._uniformColor && this._colorF32Array) {
@@ -63,7 +77,7 @@
}
};
- proto.initWithTexture = function(texture, tileWidth, tileHeight, itemsToRender){
+ proto.initWithTexture = function (texture, tileWidth, tileHeight, itemsToRender) {
var node = this._node;
node._itemWidth = tileWidth;
node._itemHeight = tileHeight;
@@ -88,13 +102,10 @@
this._calculateMaxItems();
node.quadsToDraw = itemsToRender;
- //shader stuff
- this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURE_UCOLOR);
- this._uniformColor = cc._renderContext.getUniformLocation(node.shaderProgram.getProgram(), "u_color");
return true;
};
- proto.setColor = function(color3){
+ proto.setColor = function (color3) {
var temp = cc.color(color3.r, color3.g, color3.b), node = this._node;
this._colorUnmodified = color3;
var locDisplayedOpacity = this._displayedOpacity;
@@ -106,7 +117,7 @@
cc.Node.prototype.setColor.call(node, temp);
};
- proto.setOpacity = function(opacity){
+ proto.setOpacity = function (opacity) {
var node = this._node;
cc.Node.prototype.setOpacity.call(node, opacity);
// special opacity for premultiplied textures
@@ -115,23 +126,27 @@
}
};
- proto._updateColor = function(){
- var locDisplayedColor = this._displayedColor;
- this._colorF32Array = new Float32Array([locDisplayedColor.r / 255.0, locDisplayedColor.g / 255.0,
- locDisplayedColor.b / 255.0, this._displayedOpacity / 255.0]);
+ proto._updateColor = function () {
+ if (this._colorF32Array) {
+ var locDisplayedColor = this._displayedColor;
+ this._colorF32Array[0] = locDisplayedColor.r / 255.0;
+ this._colorF32Array[1] = locDisplayedColor.g / 255.0;
+ this._colorF32Array[2] = locDisplayedColor.b / 255.0;
+ this._colorF32Array[3] = this._displayedOpacity / 255.0;
+ }
};
- proto.getTexture = function(){
+ proto.getTexture = function () {
return this._textureAtlas.texture;
};
- proto.setTexture = function(texture){
+ proto.setTexture = function (texture) {
this._textureAtlas.texture = texture;
this._updateBlendFunc();
this._updateOpacityModifyRGB();
};
- proto._calculateMaxItems = function(){
+ proto._calculateMaxItems = function () {
var node = this._node;
var selTexture = this._textureAtlas.texture;
var size = selTexture.getContentSize();
@@ -141,4 +156,4 @@
node._itemsPerColumn = 0 | (size.height / node._itemHeight);
node._itemsPerRow = 0 | (size.width / node._itemWidth);
};
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js
index 2cb59b63e8..9d3e6f15e5 100644
--- a/cocos2d/core/base-nodes/CCNode.js
+++ b/cocos2d/core/base-nodes/CCNode.js
@@ -85,7 +85,6 @@ cc.s_globalOrderOfArrival = 1;
* -# The node will be rotated (rotation)
* -# The node will be scaled (scale)
* -# The grid will capture the screen
- * -# The node will be moved according to the camera values (camera)
* -# The grid will render the captured screen
*
* @class
@@ -132,6 +131,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{
_localZOrder: 0, ///< Local order (relative to its siblings) used to sort the node
_globalZOrder: 0, ///< Global order used to sort the node
_vertexZ: 0.0,
+ _customZ: NaN,
_rotationX: 0,
_rotationY: 0.0,
@@ -163,12 +163,10 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{
//since 2.0 api
_reorderChildDirty: false,
- _shaderProgram: null,
arrivalOrder: 0,
_actionManager: null,
_scheduler: null,
- _eventDispatcher: null,
_additionalTransformDirty: false,
_additionalTransform: null,
@@ -190,32 +188,23 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
* @function
*/
- ctor: function(){
- this._initNode();
- this._initRendererCmd();
- },
-
- _initNode: function () {
+ ctor: function () {
var _t = this;
_t._anchorPoint = cc.p(0, 0);
_t._contentSize = cc.size(0, 0);
_t._position = cc.p(0, 0);
- _t._normalizedPosition = cc.p(0,0);
+ _t._normalizedPosition = cc.p(0, 0);
_t._children = [];
var director = cc.director;
- _t._actionManager = director.getActionManager();
- _t._scheduler = director.getScheduler();
_t._additionalTransform = cc.affineTransformMakeIdentity();
if (cc.ComponentContainer) {
_t._componentContainer = new cc.ComponentContainer(_t);
}
-
- this._realOpacity = 255;
this._realColor = cc.color(255, 255, 255, 255);
- this._cascadeColorEnabled = false;
- this._cascadeOpacityEnabled = false;
+
+ this._renderCmd = this._createRenderCmd();
},
/**
@@ -224,72 +213,9 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{
* @returns {boolean} Whether the initialization was successful.
*/
init: function () {
- //this._initNode(); //this has been called in ctor.
return true;
},
- _arrayMakeObjectsPerformSelector: function (array, callbackType) {
- if (!array || array.length === 0)
- return;
-
- var i, len = array.length, node;
- var nodeCallbackType = cc.Node._stateCallbackType;
- switch (callbackType) {
- case nodeCallbackType.onEnter:
- for (i = 0; i < len; i++) {
- node = array[i];
- if (node)
- node.onEnter();
- }
- break;
- case nodeCallbackType.onExit:
- for (i = 0; i < len; i++) {
- node = array[i];
- if (node)
- node.onExit();
- }
- break;
- case nodeCallbackType.onEnterTransitionDidFinish:
- for (i = 0; i < len; i++) {
- node = array[i];
- if (node)
- node.onEnterTransitionDidFinish();
- }
- break;
- case nodeCallbackType.cleanup:
- for (i = 0; i < len; i++) {
- node = array[i];
- if (node)
- node.cleanup();
- }
- break;
- case nodeCallbackType.updateTransform:
- for (i = 0; i < len; i++) {
- node = array[i];
- if (node)
- node.updateTransform();
- }
- break;
- case nodeCallbackType.onExitTransitionDidStart:
- for (i = 0; i < len; i++) {
- node = array[i];
- if (node)
- node.onExitTransitionDidStart();
- }
- break;
- case nodeCallbackType.sortAllChildren:
- for (i = 0; i < len; i++) {
- node = array[i];
- if (node)
- node.sortAllChildren();
- }
- break;
- default :
- cc.assert(0, cc._LogInfos.Node__arrayMakeObjectsPerformSelector);
- break;
- }
- },
-
/**
*
Properties configuration function
* All properties in attrs will be set to the node,
@@ -380,9 +306,12 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{
* @param {Number} localZOrder
*/
setLocalZOrder: function (localZOrder) {
- this._localZOrder = localZOrder;
+ if (localZOrder === this._localZOrder)
+ return;
if (this._parent)
this._parent.reorderChild(this, localZOrder);
+ else
+ this._localZOrder = localZOrder;
cc.eventManager._setDirtyForNode(this);
},
@@ -446,7 +375,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);
}
@@ -485,7 +414,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{
* @param {Number} Var
*/
setVertexZ: function (Var) {
- this._vertexZ = Var;
+ this._customZ = this._vertexZ = Var;
},
/**
@@ -649,9 +578,13 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{
setPosition: function (newPosOrxValue, yValue) {
var locPosition = this._position;
if (yValue === undefined) {
+ if (locPosition.x === newPosOrxValue.x && locPosition.y === newPosOrxValue.y)
+ return;
locPosition.x = newPosOrxValue.x;
locPosition.y = newPosOrxValue.y;
} else {
+ if (locPosition.x === newPosOrxValue && locPosition.y === yValue)
+ return;
locPosition.x = newPosOrxValue;
locPosition.y = yValue;
}
@@ -723,7 +656,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{
* @return {Number}
*/
getPositionY: function () {
- return this._position.y;
+ return this._position.y;
},
/**
@@ -778,7 +711,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{
* @param {Boolean} visible Pass true to make the node visible, false to hide the node.
*/
setVisible: function (visible) {
- if(this._visible !== visible){
+ if (this._visible !== visible) {
this._visible = visible;
//if(visible)
this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
@@ -938,6 +871,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{
*/
setParent: function (parent) {
this._parent = parent;
+ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
},
/**
@@ -962,7 +896,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);
}
@@ -1014,8 +948,8 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{
* @function
* @param {String} name
*/
- setName: function(name){
- this._name = name;
+ setName: function (name) {
+ this._name = name;
},
/**
@@ -1023,7 +957,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{
* @function
* @returns {string} A string that identifies the node.
*/
- getName: function(){
+ getName: function () {
return this._name;
},
@@ -1072,7 +1006,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;
},
@@ -1109,9 +1043,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{
* @return {cc.ActionManager} A CCActionManager object.
*/
getActionManager: function () {
- if (!this._actionManager)
- this._actionManager = cc.director.getActionManager();
- return this._actionManager;
+ return this._actionManager || cc.director.getActionManager();
},
/**
@@ -1121,7 +1053,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;
}
@@ -1135,9 +1067,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{
* @return {cc.Scheduler} A CCScheduler object.
*/
getScheduler: function () {
- if (!this._scheduler)
- this._scheduler = cc.director.getScheduler();
- return this._scheduler;
+ return this._scheduler || cc.director.getScheduler();
},
/**
@@ -1150,7 +1080,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;
}
@@ -1161,7 +1091,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{
* @deprecated since v3.0, please use getBoundingBox instead
* @return {cc.Rect}
*/
- boundingBox: function(){
+ boundingBox: function () {
cc.log(cc._LogInfos.Node_boundingBox);
return this.getBoundingBox();
},
@@ -1188,9 +1118,6 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{
// event
cc.eventManager.removeListeners(this);
-
- // timers
- this._arrayMakeObjectsPerformSelector(this._children, cc.Node._stateCallbackType.cleanup);
},
// composition: GET
@@ -1202,10 +1129,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;
}
}
@@ -1218,16 +1145,16 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{
* @param {String} name A name to find the child node.
* @return {cc.Node} a CCNode object whose name equals to the input parameter
*/
- getChildByName: function(name){
- if(!name){
+ getChildByName: function (name) {
+ if (!name) {
cc.log("Invalid name");
return null;
}
var locChildren = this._children;
- for(var i = 0, len = locChildren.length; i < len; i++){
- if(locChildren[i]._name == name)
- return locChildren[i];
+ for (var i = 0, len = locChildren.length; i < len; i++) {
+ if (locChildren[i]._name === name)
+ return locChildren[i];
}
return null;
},
@@ -1240,18 +1167,17 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{
* @function
* @param {cc.Node} child A child node
* @param {Number} [localZOrder=] Z order for drawing priority. Please refer to setZOrder(int)
- * @param {Number} [tag=] A integer to identify the node easily. Please refer to setTag(int)
+ * @param {Number|String} [tag=] An integer or a name to identify the node easily. Please refer to setTag(int) and setName(string)
*/
addChild: function (child, localZOrder, tag) {
localZOrder = localZOrder === undefined ? child._localZOrder : localZOrder;
var name, setTag = false;
- if(cc.isUndefined(tag)){
- tag = undefined;
+ if (tag === undefined) {
name = child._name;
- } else if(cc.isString(tag)){
+ } else if (typeof tag === 'string') {
name = tag;
tag = undefined;
- } else if(cc.isNumber(tag)){
+ } else if (typeof tag === 'number') {
setTag = true;
name = "";
}
@@ -1262,12 +1188,12 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{
this._addChildHelper(child, localZOrder, tag, name, setTag);
},
- _addChildHelper: function(child, localZOrder, tag, name, setTag){
- if(!this._children)
+ _addChildHelper: function (child, localZOrder, tag, name, setTag) {
+ if (!this._children)
this._children = [];
this._insertChild(child, localZOrder);
- if(setTag)
+ if (setTag)
child.setTag(tag);
else
child.setName(name);
@@ -1275,12 +1201,13 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{
child.setParent(this);
child.setOrderOfArrival(cc.s_globalOrderOfArrival++);
- if( this._running ){
- child.onEnter();
+ if (this._running) {
+ child._performRecursive(cc.Node._stateCallbackType.onEnter);
// prevent onEnterTransitionDidFinish to be called twice when a node is added in onEnter
if (this._isTransitionFinished)
- child.onEnterTransitionDidFinish();
+ child._performRecursive(cc.Node._stateCallbackType.onEnterTransitionDidFinish);
}
+ child._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
if (this._cascadeColorEnabled)
child._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty);
if (this._cascadeOpacityEnabled)
@@ -1298,7 +1225,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);
}
@@ -1329,7 +1256,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);
@@ -1351,7 +1278,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);
@@ -1374,26 +1301,28 @@ 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 (cleanup == null)
+ if (__children !== null) {
+ if (cleanup === undefined)
cleanup = true;
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();
+ node._performRecursive(cc.Node._stateCallbackType.onExitTransitionDidStart);
+ node._performRecursive(cc.Node._stateCallbackType.onExit);
}
+
+ // If you don't do cleanup, the node's actions will not get removed and the
if (cleanup)
- node.cleanup();
+ node._performRecursive(cc.Node._stateCallbackType.cleanup);
+
// set parent nil at the end
node.parent = null;
+ node._renderCmd.detachFromParent();
}
}
this._children.length = 0;
+ cc.renderer.childrenOrderDirty = true;
}
},
@@ -1402,13 +1331,13 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{
// -1st do onExit
// -2nd cleanup
if (this._running) {
- child.onExitTransitionDidStart();
- child.onExit();
+ child._performRecursive(cc.Node._stateCallbackType.onExitTransitionDidStart);
+ child._performRecursive(cc.Node._stateCallbackType.onExit);
}
// If you don't do cleanup, the child's actions will not get removed and the
if (doCleanup)
- child.cleanup();
+ child._performRecursive(cc.Node._stateCallbackType.cleanup);
// set parent nil at the end
child.parent = null;
@@ -1422,7 +1351,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{
child._setLocalZOrder(z);
},
- setNodeDirty: function(){
+ setNodeDirty: function () {
this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
},
@@ -1434,10 +1363,15 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{
*/
reorderChild: function (child, zOrder) {
cc.assert(child, cc._LogInfos.Node_reorderChild);
+ if (this._children.indexOf(child) === -1) {
+ cc.log(cc._LogInfos.Node_reorderChild_2);
+ return;
+ }
cc.renderer.childrenOrderDirty = this._reorderChildDirty = true;
child.arrivalOrder = cc.s_globalOrderOfArrival;
cc.s_globalOrderOfArrival++;
child._setLocalZOrder(zOrder);
+ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.orderDirty);
},
/**
@@ -1454,22 +1388,22 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{
// insertion sort
var len = _children.length, i, j, tmp;
- for(i=1; i= 0){
- if(tmp._localZOrder < _children[j]._localZOrder){
- _children[j+1] = _children[j];
- }else if(tmp._localZOrder === _children[j]._localZOrder && tmp.arrivalOrder < _children[j].arrivalOrder){
- _children[j+1] = _children[j];
- }else{
+ while (j >= 0) {
+ if (tmp._localZOrder < _children[j]._localZOrder) {
+ _children[j + 1] = _children[j];
+ } else if (tmp._localZOrder === _children[j]._localZOrder && tmp.arrivalOrder < _children[j].arrivalOrder) {
+ _children[j + 1] = _children[j];
+ } else {
break;
}
j--;
}
- _children[j+1] = tmp;
+ _children[j + 1] = tmp;
}
//don't need to check children recursively, that's done in visit of each child
@@ -1490,13 +1424,13 @@ 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();
}
},
- //scene managment
+ //scene management
/**
*
* Event callback that is invoked every time when CCNode enters the 'stage'.
@@ -1509,10 +1443,72 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{
onEnter: function () {
this._isTransitionFinished = false;
this._running = true;//should be running before resumeSchedule
- this._arrayMakeObjectsPerformSelector(this._children, cc.Node._stateCallbackType.onEnter);
this.resume();
},
+ _performRecursive: function (callbackType) {
+ var nodeCallbackType = cc.Node._stateCallbackType;
+ if (callbackType >= nodeCallbackType.max) {
+ return;
+ }
+
+ var index = 0;
+ var children, child, curr, i, len;
+ var stack = cc.Node._performStacks[cc.Node._performing];
+ if (!stack) {
+ stack = [];
+ cc.Node._performStacks.push(stack);
+ }
+ stack.length = 0;
+ cc.Node._performing++;
+ curr = stack[0] = this;
+ while (curr) {
+ // Walk through children
+ children = curr._children;
+ if (children && children.length > 0) {
+ for (i = 0, len = children.length; i < len; ++i) {
+ child = children[i];
+ stack.push(child);
+ }
+ }
+ children = curr._protectedChildren;
+ if (children && children.length > 0) {
+ for (i = 0, len = children.length; i < len; ++i) {
+ child = children[i];
+ stack.push(child);
+ }
+ }
+
+ index++;
+ curr = stack[index];
+ }
+ for (i = stack.length - 1; i >= 0; --i) {
+ curr = stack[i];
+ stack[i] = null;
+ if (!curr) continue;
+
+ // Perform actual action
+ switch (callbackType) {
+ case nodeCallbackType.onEnter:
+ curr.onEnter();
+ break;
+ case nodeCallbackType.onExit:
+ curr.onExit();
+ break;
+ case nodeCallbackType.onEnterTransitionDidFinish:
+ curr.onEnterTransitionDidFinish();
+ break;
+ case nodeCallbackType.cleanup:
+ curr.cleanup();
+ break;
+ case nodeCallbackType.onExitTransitionDidStart:
+ curr.onExitTransitionDidStart();
+ break;
+ }
+ }
+ cc.Node._performing--;
+ },
+
/**
*