Initializes a TextureAtlas with a filename and with a certain capacity for Quads.
+ * The TextureAtlas capacity can be increased in runtime.
+ * WARNING: Do not reinitialize the TextureAtlas because it will leak memory.
+ * @method initWithFile
+ * @param {String} file
+ * @param {Number} capacity
+ * @return {Boolean}
+ * @example {@link utils/api/cocos/docs/cocos2d/core/textures/initWithFile.js}
+ */
+ initWithFile: function (file, capacity) {
+ // retained in property
+ var texture = cc.textureCache.addImage(file);
+ if (texture)
+ return this.initWithTexture(texture, capacity);
+ else {
+ cc.log(cc._LogInfos.TextureAtlas.initWithFile, file);
+ return false;
+ }
+ },
+
+ /**
+ *
+ * Inserts a c array of quads at a given index
+ * index must be between 0 and the atlas capacity - 1
+ * this method doesn't enlarge the array when amount + index > totalQuads
+ *
+ *
+ * @method insertQuads
+ * @param {Array} quads
+ * @param {Number} index
+ * @param {Number} amount
+ */
+ insertQuads: function (quads, index, amount) {
+ amount = amount || quads.length;
+
+ cc.assert((index + amount) <= this._capacity, cc._LogInfos.TextureAtlas.insertQuads);
+
+ var quadSize = cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT;
+ this._totalQuads += amount;
+ if (this._totalQuads > this._capacity) {
+ cc.log(cc._LogInfos.TextureAtlas.insertQuad);
+ return;
+ }
+
+ // issue #575. index can be > totalQuads
+ var remaining = (this._totalQuads - 1) - index - amount;
+ var startOffset = index * quadSize;
+ var moveLength = remaining * quadSize;
+ var lastIndex = (this._totalQuads - 1) - amount;
+
+ var i;
+ for (i = 0; i < amount; i++)
+ this._quads[lastIndex + i] = new cc.V3F_C4B_T2F_Quad(null, null, null, null, this._quadsArrayBuffer, (this._totalQuads - 1) * quadSize);
+ this._quadsReader.set(this._quadsReader.subarray(startOffset, startOffset + moveLength), startOffset + quadSize * amount);
+ for (i = 0; i < amount; i++)
+ this._setQuadToArray(quads[i], index + i);
+
+ this.dirty = true;
+ },
+
+ /**
+ * Removes the quad that is located at a certain index and inserts it at a new index
+ * This operation is faster than removing and inserting in a quad in 2 different steps
+ * @method insertQuadFromIndex
+ * @param {Number} fromIndex
+ * @param {Number} newIndex
+ */
+ insertQuadFromIndex: function (fromIndex, newIndex) {
+ if (fromIndex === newIndex)
+ return;
+
+ cc.assert(newIndex >= 0 || newIndex < this._totalQuads, cc._LogInfos.TextureAtlas.insertQuadFromIndex);
+
+ cc.assert(fromIndex >= 0 || fromIndex < this._totalQuads, cc._LogInfos.TextureAtlas.insertQuadFromIndex_2);
+
+ var quadSize = cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT;
+ var locQuadsReader = this._quadsReader;
+ var sourceArr = locQuadsReader.subarray(fromIndex * quadSize, quadSize);
+ var startOffset, moveLength;
+ if (fromIndex > newIndex) {
+ startOffset = newIndex * quadSize;
+ moveLength = (fromIndex - newIndex) * quadSize;
+ locQuadsReader.set(locQuadsReader.subarray(startOffset, startOffset + moveLength), startOffset + quadSize);
+ locQuadsReader.set(sourceArr, startOffset);
+ } else {
+ startOffset = (fromIndex + 1) * quadSize;
+ moveLength = (newIndex - fromIndex) * quadSize;
+ locQuadsReader.set(locQuadsReader.subarray(startOffset, startOffset + moveLength), startOffset - quadSize);
+ locQuadsReader.set(sourceArr, newIndex * quadSize);
+ }
+ this.dirty = true;
+ },
+
+ /**
+ * Removes a quad at a given index number.
+ * The capacity remains the same, but the total number of quads to be drawn is reduced in 1
+ * @method removeQuadAtIndex
+ * @param {Number} index
+ */
+ removeQuadAtIndex: function (index) {
+ cc.assert(index < this._totalQuads, cc._LogInfos.TextureAtlas.removeQuadAtIndex);
+
+ var quadSize = cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT;
+ this._totalQuads--;
+ this._quads.length = this._totalQuads;
+ if (index !== this._totalQuads) {
+ //move data
+ var startOffset = (index + 1) * quadSize;
+ var moveLength = (this._totalQuads - index) * quadSize;
+ this._quadsReader.set(this._quadsReader.subarray(startOffset, startOffset + moveLength), startOffset - quadSize);
+ }
+ this.dirty = true;
+ },
+
+ /**
+ * Removes a given number of quads at a given index.
+ * @method removeQuadsAtIndex
+ * @param {Number} index
+ * @param {Number} amount
+ */
+ removeQuadsAtIndex: function (index, amount) {
+ cc.assert(index + amount <= this._totalQuads, cc._LogInfos.TextureAtlas.removeQuadsAtIndex);
+
+ this._totalQuads -= amount;
+
+ if (index !== this._totalQuads) {
+ //move data
+ var quadSize = cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT;
+ var srcOffset = (index + amount) * quadSize;
+ var moveLength = (this._totalQuads - index) * quadSize;
+ var dstOffset = index * quadSize;
+ this._quadsReader.set(this._quadsReader.subarray(srcOffset, srcOffset + moveLength), dstOffset);
+ }
+ this.dirty = true;
+ },
+
+ /**
+ * Removes all Quads.
+ * The TextureAtlas capacity remains untouched. No memory is freed.
+ * The total number of quads to be drawn will be 0
+ * @method removeAllQuads
+ */
+ removeAllQuads: function () {
+ this._quads.length = 0;
+ this._totalQuads = 0;
+ },
+
+ _setDirty: function (dirty) {
+ this.dirty = dirty;
+ },
+
+ /**
+ * Resize the capacity of the CCTextureAtlas.
+ * The new capacity can be lower or higher than the current one
+ * It returns YES if the resize was successful.
+ * If it fails to resize the capacity it will return NO with a new capacity of 0.
+ * no used for js
+ * @method resizeCapacity
+ * @param {Number} newCapacity
+ * @return {Boolean}
+ */
+ resizeCapacity: function (newCapacity) {
+ if (newCapacity === this._capacity)
+ return true;
+
+ var quadSize = cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT;
+ var oldCapacity = this._capacity;
+ // update capacity and totolQuads
+ this._totalQuads = Math.min(this._totalQuads, newCapacity);
+ this._capacity = 0 | newCapacity;
+ var i, capacity = this._capacity, locTotalQuads = this._totalQuads;
+
+ if (this._quads === null) {
+ this._quads = [];
+ this._quadsArrayBuffer = new ArrayBuffer(quadSize * capacity);
+ this._quadsReader = new Uint8Array(this._quadsArrayBuffer);
+ for (i = 0; i < capacity; i++)
+ this._quads = new cc.V3F_C4B_T2F_Quad(null, null, null, null, this._quadsArrayBuffer, i * quadSize);
+ } else {
+ var newQuads, newArrayBuffer, quads = this._quads;
+ if (capacity > oldCapacity) {
+ newQuads = [];
+ newArrayBuffer = new ArrayBuffer(quadSize * capacity);
+ for (i = 0; i < locTotalQuads; i++) {
+ newQuads[i] = new cc.V3F_C4B_T2F_Quad(quads[i].tl, quads[i].bl, quads[i].tr, quads[i].br,
+ newArrayBuffer, i * quadSize);
+ }
+ for (; i < capacity; i++)
+ newQuads[i] = new cc.V3F_C4B_T2F_Quad(null, null, null, null, newArrayBuffer, i * quadSize);
+
+ this._quadsReader = new Uint8Array(newArrayBuffer);
+ this._quads = newQuads;
+ this._quadsArrayBuffer = newArrayBuffer;
+ } else {
+ var count = Math.max(locTotalQuads, capacity);
+ newQuads = [];
+ newArrayBuffer = new ArrayBuffer(quadSize * capacity);
+ for (i = 0; i < count; i++) {
+ newQuads[i] = new cc.V3F_C4B_T2F_Quad(quads[i].tl, quads[i].bl, quads[i].tr, quads[i].br,
+ newArrayBuffer, i * quadSize);
+ }
+ this._quadsReader = new Uint8Array(newArrayBuffer);
+ this._quads = newQuads;
+ this._quadsArrayBuffer = newArrayBuffer;
+ }
+ }
+
+ if (this._indices === null) {
+ this._indices = new Uint16Array(capacity * 6);
+ } else {
+ if (capacity > oldCapacity) {
+ var tempIndices = new Uint16Array(capacity * 6);
+ tempIndices.set(this._indices, 0);
+ this._indices = tempIndices;
+ } else {
+ this._indices = this._indices.subarray(0, capacity * 6);
+ }
+ }
+
+ this._setupIndices();
+ this._mapBuffers();
+ this.dirty = true;
+ return true;
+ },
+
+ /**
+ * Used internally by CCParticleBatchNode Draws n quads from an index (offset).
+ * n + start can't be greater than the capacity of the atlas
+ *
+ * @method drawNumberOfQuads
+ * @param {Number} n
+ * @param {Number} start
+ */
+ drawNumberOfQuads: null,
+
+ _releaseBuffer: function () {
+ var gl = cc._renderContext;
+ if (this._buffersVBO) {
+ if (this._buffersVBO[0])
+ gl.deleteBuffer(this._buffersVBO[0]);
+ if (this._buffersVBO[1])
+ gl.deleteBuffer(this._buffersVBO[1])
+ }
+ if (this._quadsWebBuffer)
+ gl.deleteBuffer(this._quadsWebBuffer);
+ }
+});
+
+var _p = TextureAtlas.prototype;
+
+// Extended properties
+/** @expose */
+_p.totalQuads;
+cc.defineGetterSetter(_p, "totalQuads", _p.getTotalQuads);
+/** @expose */
+_p.capacity;
+cc.defineGetterSetter(_p, "capacity", _p.getCapacity);
+/** @expose */
+_p.quads;
+cc.defineGetterSetter(_p, "quads", _p.getQuads, _p.setQuads);
+
+game.once(game.EVENT_RENDERER_INITED, function () {
+if (cc._renderType === game.RENDER_TYPE_WEBGL) {
+ JS.mixin(TextureAtlas.prototype, {
+ _setupVBO: function () {
+ var _t = this;
+ var gl = cc._renderContext;
+ //create WebGLBuffer
+ _t._buffersVBO[0] = gl.createBuffer();
+ _t._buffersVBO[1] = gl.createBuffer();
+
+ _t._quadsWebBuffer = gl.createBuffer();
+ _t._mapBuffers();
+ },
+
+ _mapBuffers: function () {
+ var _t = this;
+ var gl = cc._renderContext;
+
+ gl.bindBuffer(gl.ARRAY_BUFFER, _t._quadsWebBuffer);
+ gl.bufferData(gl.ARRAY_BUFFER, _t._quadsArrayBuffer, gl.DYNAMIC_DRAW);
+
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _t._buffersVBO[1]);
+ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, _t._indices, gl.STATIC_DRAW);
+
+ //cc.checkGLErrorDebug();
+ },
+
+ drawQuads: function () {
+ this.drawNumberOfQuads(this._totalQuads, 0);
+ },
+
+ drawNumberOfQuads: function (n, start) {
+ var _t = this;
+ start = start || 0;
+ if (0 === n || !_t.texture || !_t.texture.isLoaded())
+ return;
+
+ var gl = cc._renderContext;
+ cc.glBindTexture2D(_t.texture);
+
+ //
+ // Using VBO without VAO
+ //
+ //vertices
+ //gl.bindBuffer(gl.ARRAY_BUFFER, _t._buffersVBO[0]);
+ // XXX: update is done in draw... perhaps it should be done in a timer
+ cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POS_COLOR_TEX);
+
+ gl.bindBuffer(gl.ARRAY_BUFFER, _t._quadsWebBuffer);
+ if (_t.dirty){
+ gl.bufferData(gl.ARRAY_BUFFER, _t._quadsArrayBuffer, gl.DYNAMIC_DRAW);
+ _t.dirty = false;
+ }
+
+ gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 24, 0); // vertices
+ gl.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, 24, 12); // colors
+ gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 24, 16); // tex coords
+
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _t._buffersVBO[1]);
+
+ if (cc.TEXTURE_ATLAS_USE_TRIANGLE_STRIP)
+ gl.drawElements(gl.TRIANGLE_STRIP, n * 6, gl.UNSIGNED_SHORT, start * 6 * _t._indices.BYTES_PER_ELEMENT);
+ else
+ gl.drawElements(gl.TRIANGLES, n * 6, gl.UNSIGNED_SHORT, start * 6 * _t._indices.BYTES_PER_ELEMENT);
+
+ cc.g_NumberOfDraws++;
+ //cc.checkGLErrorDebug();
+ }
+ });
+}
+});
+
+/**
+ * Indicates whether or not the array buffer of the VBO needs to be updated.
+ * @property dirty
+ * @type {Boolean}
+ */
+
+/**
+ * Image texture for cc.TextureAtlas.
+ * @property texture
+ * @type {Image}
+ */
+
+/**
+ * Quantity of quads that can be stored with the current texture atlas size.
+ * @property capacity
+ * @type {Number}
+ * @readonly
+ */
+
+/**
+ * Quantity of quads that are going to be drawn.
+ * @property totalQuads
+ * @type {Number}
+ * @readonly
+ */
+
+/**
+ * Quads that are going to be rendered.
+ * @property quads
+ * @type {Array}
+ * @readonly
+ */
+
+cc.TextureAtlas = module.exports = TextureAtlas;
\ No newline at end of file
diff --git a/cocos2d/core/textures/CCTextureCache.js b/cocos2d/core/textures/CCTextureCache.js
new file mode 100644
index 0000000000..104607f6a1
--- /dev/null
+++ b/cocos2d/core/textures/CCTextureCache.js
@@ -0,0 +1,393 @@
+/****************************************************************************
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+var JS = require('../platform/js');
+var game = require('../CCGame');
+var Texture2D = require('./CCTexture2D');
+
+/**
+ * cc.textureCache is a singleton object, it's the global cache for cc.Texture2D
+ * @class textureCache
+ */
+var textureCache = /** @lends cc.textureCache# */{
+ _textures: {},
+ _textureColorsCache: {},
+ _textureKeySeq: (0 | Math.random() * 1000),
+
+ _loadedTexturesBefore: {},
+
+ handleLoadedTexture: null,
+
+ _initializingRenderer: function () {
+ var selPath;
+ //init texture from _loadedTexturesBefore
+ var locLoadedTexturesBefore = this._loadedTexturesBefore, locTextures = this._textures;
+ for (selPath in locLoadedTexturesBefore) {
+ var tex2d = locLoadedTexturesBefore[selPath];
+ tex2d.handleLoadedTexture();
+ locTextures[selPath] = tex2d;
+ }
+ this._loadedTexturesBefore = {};
+ },
+
+ /**
+ * Description
+ * @method description
+ * @return {String}
+ */
+ description: function () {
+ return "";
+ },
+
+ /**
+ * Returns an already created texture. Returns null if the texture doesn't exist.
+ * @method textureForKey
+ * @param {String} textureKeyName
+ * @return {Texture2D|Null}
+ * @deprecated
+ * @example {@link utils/api/cocos/docs/cocos2d/core/textures/textureForKey.js}
+ */
+ textureForKey: function (textureKeyName) {
+ cc.log(cc._LogInfos.textureCache.textureForKey);
+ return this.getTextureForKey(textureKeyName);
+ },
+
+ /**
+ * Returns an already created texture. Returns null if the texture doesn't exist.
+ * @method getTextureForKey
+ * @param {String} textureKeyName
+ * @return {Texture2D|Null}
+ * @example {@link utils/api/cocos/docs/cocos2d/core/textures/getTextureForKey.js}
+ */
+ getTextureForKey: function(textureKeyName){
+ return this._textures[textureKeyName] || this._textures[cc.loader.getAliase(textureKeyName)];
+ },
+
+ /**
+ * @method getKeyByTexture
+ * @param {Image} texture
+ * @return {String|Null}
+ * @example {@link utils/api/cocos/docs/cocos2d/core/textures/getKeyByTexture.js}
+ */
+ getKeyByTexture: function (texture) {
+ for (var key in this._textures) {
+ if (this._textures[key] === texture) {
+ return key;
+ }
+ }
+ return null;
+ },
+
+ _generalTextureKey: function (id) {
+ return "_textureKey_" + id;
+ },
+
+ /**
+ * @method getTextureColors
+ * @param {Image} texture
+ * @return {Array}
+ * @example {@link utils/api/cocos/docs/cocos2d/core/textures/getTextureColors.js}
+ */
+ getTextureColors: function (texture) {
+ var image = texture._htmlElementObj;
+ var key = this.getKeyByTexture(image);
+ if (!key) {
+ if (image instanceof HTMLImageElement)
+ key = image.src;
+ else
+ key = this._generalTextureKey(texture.__instanceId);
+ }
+
+ if (!this._textureColorsCache[key])
+ this._textureColorsCache[key] = texture._generateTextureCacheForColor();
+ return this._textureColorsCache[key];
+ },
+
+ /**
+ * Purges the dictionary of loaded textures.
+ * Call this method if you receive the "Memory Warning"
+ * In the short term: it will free some resources preventing your app from being killed
+ * In the medium term: it will allocate more resources
+ * In the long term: it will be the same
+ * @method removeAllTextures
+ * @example {@link utils/api/cocos/docs/cocos2d/core/textures/removeAllTextures.js}
+ */
+ removeAllTextures: function () {
+ var locTextures = this._textures;
+ for (var selKey in locTextures) {
+ if (locTextures[selKey])
+ locTextures[selKey].releaseTexture();
+ }
+ this._textures = {};
+ },
+
+ /**
+ * Deletes a texture from the cache given a texture.
+ * @method removeTexture
+ * @param {Image} texture
+ * @example {@link utils/api/cocos/docs/cocos2d/core/textures/removeTexture.js}
+ */
+ removeTexture: function (texture) {
+ if (!texture)
+ return;
+
+ var locTextures = this._textures;
+ for (var selKey in locTextures) {
+ if (locTextures[selKey] === texture) {
+ locTextures[selKey].releaseTexture();
+ delete(locTextures[selKey]);
+ }
+ }
+ },
+
+ /**
+ * Deletes a texture from the cache given a its key name.
+ * @method removeTextureForKey
+ * @param {String} textureKeyName
+ * @example {@link utils/api/cocos/docs/cocos2d/core/textures/removeTextureForKey.js}
+ */
+ removeTextureForKey: function (textureKeyName) {
+ if (textureKeyName == null)
+ return;
+ if (this._textures[textureKeyName])
+ delete(this._textures[textureKeyName]);
+ },
+
+ /**
+ * Returns a Texture2D object given an file image
+ * If the file image was not previously loaded, it will create a new Texture2D
+ * object and it will return it. It will use the filename as a key.
+ * Otherwise it will return a reference of a previously loaded image.
+ * Supported image extensions: .png, .jpg, .gif
+ * @method addImage
+ * @param {String} url
+ * @param {Function} cb
+ * @param {Object} target
+ * @return {Texture2D}
+ * @example {@link utils/api/cocos/docs/cocos2d/core/textures/addImage.js}
+ */
+ addImage: null,
+ addImageAsync: null,
+
+ /**
+ * Cache the image data.
+ * @method cacheImage
+ * @param {String} path
+ * @param {Image|HTMLImageElement|HTMLCanvasElement} texture
+ */
+ cacheImage: function (path, texture) {
+ if (texture instanceof Texture2D) {
+ this._textures[path] = texture;
+ return;
+ }
+ var texture2d = new Texture2D();
+ texture2d.initWithElement(texture);
+ texture2d.handleLoadedTexture();
+ this._textures[path] = texture2d;
+ },
+
+ /**
+ * Returns a Texture2D object given an UIImage image
+ * If the image was not previously loaded, it will create a new Texture2D object and it will return it.
+ * Otherwise it will return a reference of a previously loaded image
+ * The "key" parameter will be used as the "key" for the cache.
+ * If "key" is null, then a new texture will be created each time.
+ * @method addUIImage
+ * @param {HTMLImageElement|HTMLCanvasElement} image
+ * @param {String} key
+ * @return {Texture2D}
+ */
+ addUIImage: function (image, key) {
+ cc.assert(image, cc._LogInfos.textureCache.addUIImage_2);
+
+ if (key) {
+ if (this._textures[key])
+ return this._textures[key];
+ }
+
+ // prevents overloading the autorelease pool
+ var texture = new Texture2D();
+ texture.initWithImage(image);
+ if (key != null)
+ this._textures[key] = texture;
+ else
+ cc.log(cc._LogInfos.textureCache.addUIImage);
+ return texture;
+ },
+
+ /**
+ * Output to cc.log the current contents of this TextureCache
+ * This will attempt to calculate the size of each texture, and the total texture memory in use.
+ */
+ dumpCachedTextureInfo: function () {
+ var count = 0;
+ var totalBytes = 0, locTextures = this._textures;
+
+ for (var key in locTextures) {
+ var selTexture = locTextures[key];
+ count++;
+ if (selTexture.getHtmlElementObj() instanceof HTMLImageElement)
+ cc.log(cc._LogInfos.textureCache.dumpCachedTextureInfo, key, selTexture.getHtmlElementObj().src, selTexture.getPixelWidth(), selTexture.getPixelHeight());
+ else {
+ cc.log(cc._LogInfos.textureCache.dumpCachedTextureInfo_2, key, selTexture.getPixelWidth(), selTexture.getPixelHeight());
+ }
+ totalBytes += selTexture.getPixelWidth() * selTexture.getPixelHeight() * 4;
+ }
+
+ var locTextureColorsCache = this._textureColorsCache;
+ for (key in locTextureColorsCache) {
+ var selCanvasColorsArr = locTextureColorsCache[key];
+ for (var selCanvasKey in selCanvasColorsArr) {
+ var selCanvas = selCanvasColorsArr[selCanvasKey];
+ count++;
+ cc.log(cc._LogInfos.textureCache.dumpCachedTextureInfo_2, key, selCanvas.width, selCanvas.height);
+ totalBytes += selCanvas.width * selCanvas.height * 4;
+ }
+
+ }
+ cc.log(cc._LogInfos.textureCache.dumpCachedTextureInfo_3, count, totalBytes / 1024, (totalBytes / (1024.0 * 1024.0)).toFixed(2));
+ },
+
+ _clear: function () {
+ this._textures = {};
+ this._textureColorsCache = {};
+ this._textureKeySeq = (0 | Math.random() * 1000);
+ this._loadedTexturesBefore = {};
+ }
+};
+
+game.once(game.EVENT_RENDERER_INITED, function () {
+ var _p = textureCache;
+ if (cc._renderType === game.RENDER_TYPE_CANVAS) {
+ _p.handleLoadedTexture = function (url) {
+ var locTexs = this._textures;
+ //remove judge
+ var tex = locTexs[url];
+ if (!tex) {
+ tex = locTexs[url] = new Texture2D();
+ tex.url = url;
+ }
+ tex.handleLoadedTexture();
+ };
+
+ _p.addImage = function (url, cb, target) {
+
+ cc.assert(url, cc._LogInfos.Texture2D.addImage);
+
+ var locTexs = this._textures;
+ //remove judge
+ var tex = locTexs[url] || locTexs[cc.loader.getAliase(url)];
+ if (tex) {
+ if(tex.isLoaded()) {
+ cb && cb.call(target, tex);
+ return tex;
+ }
+ else
+ {
+ tex.once("load", function(){
+ cb && cb.call(target, tex);
+ }, target);
+ return tex;
+ }
+ }
+
+ tex = locTexs[url] = new Texture2D();
+ tex.url = url;
+ var loadFunc = cc.loader._checkIsImageURL(url) ? cc.loader.load : cc.loader.loadImg;
+ loadFunc.call(cc.loader, url, function (err, img) {
+ if (err)
+ return cb && cb.call(target, err);
+ textureCache.handleLoadedTexture(url);
+
+ var texResult = locTexs[url];
+ cb && cb.call(target, texResult);
+ });
+
+ return tex;
+ };
+
+ _p.addImageAsync = _p.addImage;
+
+ } else if (cc._renderType === game.RENDER_TYPE_WEBGL) {
+
+ _p.handleLoadedTexture = function (url) {
+ var locTexs = this._textures, tex, premultiplied;
+ //remove judge(webgl)
+ if (!cc.game._rendererInitialized) {
+ locTexs = this._loadedTexturesBefore;
+ }
+ tex = locTexs[url];
+ if (!tex) {
+ tex = locTexs[url] = new Texture2D();
+ tex.url = url;
+ }
+ premultiplied = cc.AUTO_PREMULTIPLIED_ALPHA_FOR_PNG && (cc.path.extname(url) === ".png");
+ tex.handleLoadedTexture(premultiplied);
+ };
+
+ _p.addImage = function (url, cb, target) {
+ cc.assert(url, cc._LogInfos.Texture2D.addImage_2);
+
+ var locTexs = this._textures;
+ //remove judge(webgl)
+ if (!cc.game._rendererInitialized) {
+ locTexs = this._loadedTexturesBefore;
+ }
+ var tex = locTexs[url] || locTexs[cc.loader.getAliase(url)];
+ if (tex) {
+ if(tex.isLoaded()) {
+ cb && cb.call(target, tex);
+ return tex;
+ }
+ else
+ {
+ tex.once("load", function(){
+ cb && cb.call(target, tex);
+ }, target);
+ return tex;
+ }
+ }
+
+ tex = locTexs[url] = new Texture2D();
+ tex.url = url;
+ var loadFunc = cc.loader._checkIsImageURL(url) ? cc.loader.load : cc.loader.loadImg;
+ loadFunc.call(cc.loader, url, function (err, img) {
+ if (err)
+ return cb && cb.call(target, err);
+ textureCache.handleLoadedTexture(url);
+
+ var texResult = locTexs[url];
+ cb && cb.call(target, texResult);
+ });
+
+ return tex;
+ };
+
+ _p.addImageAsync = _p.addImage;
+ }
+});
+
+cc.textureCache = module.exports = textureCache;
\ No newline at end of file
diff --git a/cocos2d/core/textures/index.js b/cocos2d/core/textures/index.js
new file mode 100644
index 0000000000..92efd4c750
--- /dev/null
+++ b/cocos2d/core/textures/index.js
@@ -0,0 +1,3 @@
+require('./CCTexture2D');
+require('./CCTextureAtlas');
+require('./CCTextureCache');
\ No newline at end of file
diff --git a/cocos2d/core/utils/Async.js b/cocos2d/core/utils/Async.js
new file mode 100644
index 0000000000..ee0c3ae8b1
--- /dev/null
+++ b/cocos2d/core/utils/Async.js
@@ -0,0 +1,181 @@
+/**
+ * Async Pool class, a helper of cc.async
+ * @class AsyncPool
+ * @constructor
+ * @param {Object|Array} srcObj
+ * @param {Number} limit the limit of parallel number
+ * @param {Function} iterator
+ * @param {Function} onEnd
+ * @param {Object} target
+ */
+cc.AsyncPool = function(srcObj, limit, iterator, onEnd, target){
+ var self = this;
+ self._srcObj = srcObj;
+ self._limit = limit;
+ self._pool = [];
+ self._iterator = iterator;
+ self._iteratorTarget = target;
+ self._onEnd = onEnd;
+ self._onEndTarget = target;
+ self._results = srcObj instanceof Array ? [] : {};
+
+ cc.each(srcObj, function(value, index){
+ self._pool.push({index : index, value : value});
+ });
+
+ self.size = self._pool.length;
+ self.finishedSize = 0;
+ self._workingSize = 0;
+
+ self._limit = self._limit || self.size;
+
+ self.onIterator = function(iterator, target){
+ self._iterator = iterator;
+ self._iteratorTarget = target;
+ };
+
+ self.onEnd = function(endCb, endCbTarget){
+ self._onEnd = endCb;
+ self._onEndTarget = endCbTarget;
+ };
+
+ self._handleItem = function(){
+ var self = this;
+ 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) {
+
+ self.finishedSize++;
+ self._workingSize--;
+
+ 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.flow = function(){
+ var self = this;
+ if(self._pool.length === 0) {
+ if(self._onEnd)
+ self._onEnd.call(self._onEndTarget, null, []);
+ return;
+ }
+ for(var i = 0; i < self._limit; i++)
+ self._handleItem();
+ }
+};
+
+/**
+ * @class async
+ */
+cc.async = /** @lends cc.async# */{
+ /**
+ * Do tasks series.
+ * @method series
+ * @param {Array|Object} tasks
+ * @param {Function} [cb] - callback
+ * @param {Object} [target]
+ * @return {AsyncPool}
+ */
+ series : function(tasks, cb, target){
+ var asyncPool = new cc.AsyncPool(tasks, 1, function(func, index, cb1){
+ func.call(target, cb1);
+ }, cb, target);
+ asyncPool.flow();
+ return asyncPool;
+ },
+
+ /**
+ * Do tasks parallel.
+ * @method parallel
+ * @param {Array|Object} tasks
+ * @param {Function} cb - callback
+ * @param {Object} [target]
+ * @return {AsyncPool}
+ */
+ parallel : function(tasks, cb, target){
+ var asyncPool = new cc.AsyncPool(tasks, 0, function(func, index, cb1){
+ func.call(target, cb1);
+ }, cb, target);
+ asyncPool.flow();
+ return asyncPool;
+ },
+
+ /**
+ * Do tasks waterfall.
+ * @method waterfall
+ * @param {Array|Object} tasks
+ * @param {Function} cb - callback
+ * @param {Object} [target]
+ * @return {AsyncPool}
+ */
+ 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
+ cb1.apply(null, arguments);
+ });
+ func.apply(target, args);
+ }, function (err) {
+ if (!cb)
+ return;
+ if (err)
+ return cb.call(target, err);
+ cb.apply(target, lastResults);
+ });
+ asyncPool.flow();
+ return asyncPool;
+ },
+
+ /**
+ * Do tasks by iterator.
+ * @method map
+ * @param {Array|Object} tasks
+ * @param {Function|Object} iterator
+ * @param {Function} [callback]
+ * @param {Object} [target]
+ * @return {AsyncPool}
+ */
+ map : function(tasks, iterator, callback, target){
+ var locIterator = iterator;
+ if(typeof(iterator) === "object"){
+ callback = iterator.cb;
+ target = iterator.iteratorTarget;
+ locIterator = iterator.iterator;
+ }
+ var asyncPool = new cc.AsyncPool(tasks, 0, locIterator, callback, target);
+ asyncPool.flow();
+ return asyncPool;
+ },
+
+ /**
+ * Do tasks by iterator limit.
+ * @method mapLimit
+ * @param {Array|Object} tasks
+ * @param {Number} limit
+ * @param {Function} iterator
+ * @param {Function} cb callback
+ * @param {Object} [target]
+ */
+ mapLimit : function(tasks, limit, iterator, cb, target){
+ var asyncPool = new cc.AsyncPool(tasks, limit, iterator, cb, target);
+ asyncPool.flow();
+ return asyncPool;
+ }
+};
\ No newline at end of file
diff --git a/cocos2d/core/utils/BinaryLoader.js b/cocos2d/core/utils/BinaryLoader.js
new file mode 100644
index 0000000000..440a94aee0
--- /dev/null
+++ b/cocos2d/core/utils/BinaryLoader.js
@@ -0,0 +1,159 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+require('../platform/CCLoader');
+
+/**
+ * @module cc
+ * @class loader
+ */
+
+/**
+ * Load binary data by url.
+ * @method loadBinary
+ * @param {String} url
+ * @param {Function} [cb]
+ */
+
+cc.loader.loadBinary = function (url, cb) {
+ var self = this;
+ var xhr = this.getXMLHttpRequest(),
+ errInfo = "load " + url + " failed!";
+ xhr.open("GET", url, true);
+ if (cc.loader.loadBinary._IEFilter) {
+ // IE-specific logic here
+ xhr.setRequestHeader("Accept-Charset", "x-user-defined");
+ xhr.onreadystatechange = function () {
+ if (xhr.readyState === 4 && (xhr.status === 200 || (CC_TEST && xhr.status === 0))) {
+ var fileContents = cc._convertResponseBodyToText(xhr["responseBody"]);
+ cb(null, self._str2Uint8Array(fileContents));
+ } else cb(errInfo);
+ };
+ } else {
+ if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=x-user-defined");
+ xhr.onload = function () {
+ xhr.readyState === 4 && (xhr.status === 200 || (CC_TEST && xhr.status === 0)) ? cb(null, self._str2Uint8Array(xhr.responseText)) : cb(errInfo);
+ };
+ }
+ xhr.send(null);
+};
+
+cc.loader.loadBinary._IEFilter = (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent) && window.IEBinaryToArray_ByteStr && window.IEBinaryToArray_ByteStr_Last);
+
+cc.loader._str2Uint8Array = function (strData) {
+ if (!strData)
+ return null;
+
+ var arrData = new Uint8Array(strData.length);
+ for (var i = 0; i < strData.length; i++) {
+ arrData[i] = strData.charCodeAt(i) & 0xff;
+ }
+ return arrData;
+};
+
+/**
+ * Load binary data by url synchronously.
+ * @method loadBinarySync
+ * @param {String} url
+ * @return {Uint8Array}
+ */
+cc.loader.loadBinarySync = function (url) {
+ var self = this;
+ var req = this.getXMLHttpRequest();
+ var errInfo = "load " + url + " failed!";
+ req.open('GET', url, false);
+ var arrayInfo = null;
+ if (cc.loader.loadBinary._IEFilter) {
+ req.setRequestHeader("Accept-Charset", "x-user-defined");
+ req.send(null);
+ if (req.status !== 200) {
+ cc.log(errInfo);
+ return null;
+ }
+
+ var fileContents = cc._convertResponseBodyToText(req["responseBody"]);
+ if (fileContents) {
+ arrayInfo = self._str2Uint8Array(fileContents);
+ }
+ } else {
+ if (req.overrideMimeType)
+ req.overrideMimeType('text\/plain; charset=x-user-defined');
+ req.send(null);
+ if (req.status !== 200) {
+ cc.log(errInfo);
+ return null;
+ }
+
+ arrayInfo = this._str2Uint8Array(req.responseText);
+ }
+ return arrayInfo;
+};
+
+//Compatibility with IE9
+window.Uint8Array = window.Uint8Array || window.Array;
+
+if (cc.loader.loadBinary._IEFilter) {
+ var IEBinaryToArray_ByteStr_Script =
+ "\r\n" +
+ //"\r\n";
+
+ // inject VBScript
+ //document.write(IEBinaryToArray_ByteStr_Script);
+ var myVBScript = document.createElement('script');
+ myVBScript.type = "text/vbscript";
+ myVBScript.textContent = IEBinaryToArray_ByteStr_Script;
+ document.body.appendChild(myVBScript);
+
+ // helper to convert from responseBody to a "responseText" like thing
+ cc._convertResponseBodyToText = function (binary) {
+ var byteMapping = {};
+ for (var i = 0; i < 256; i++) {
+ for (var j = 0; j < 256; j++) {
+ byteMapping[ String.fromCharCode(i + j * 256) ] =
+ String.fromCharCode(i) + String.fromCharCode(j);
+ }
+ }
+ var rawBytes = IEBinaryToArray_ByteStr(binary);
+ var lastChr = IEBinaryToArray_ByteStr_Last(binary);
+ return rawBytes.replace(/[\s\S]/g,
+ function (match) {
+ return byteMapping[match];
+ }) + lastChr;
+ };
+}
\ No newline at end of file
diff --git a/cocos2d/core/utils/CCPath.js b/cocos2d/core/utils/CCPath.js
new file mode 100644
index 0000000000..0536175933
--- /dev/null
+++ b/cocos2d/core/utils/CCPath.js
@@ -0,0 +1,162 @@
+require('../platform/CCSys');
+/**
+ * @class path
+ * @static
+ */
+cc.path = /** @lends cc.path# */{
+ normalizeRE: /[^\.\/]+\/\.\.\//,
+
+ /**
+ * Join strings to be a path.
+ * @method join
+ * @example {@link utils/api/cocos/docs/cocos2d/core/utils/CCPath/join.js}
+ * @returns {String}
+ */
+ join: function () {
+ var l = arguments.length;
+ var result = "";
+ for (var i = 0; i < l; i++) {
+ result = (result + (result === "" ? "" : "/") + arguments[i]).replace(/(\/|\\\\)$/, "");
+ }
+ return result;
+ },
+
+ /**
+ * Get the ext name of a path.
+ * @method extname
+ * @example {@link utils/api/cocos/docs/cocos2d/core/utils/CCPath/extname.js}
+ * @param {String} pathStr
+ * @returns {*}
+ */
+ extname: function (pathStr) {
+ var temp = /(\.[^\.\/\?\\]*)(\?.*)?$/.exec(pathStr);
+ return temp ? temp[1] : null;
+ },
+
+ /**
+ * Get the main name of a file name
+ * @method mainFileName
+ * @param {String} fileName
+ * @returns {String}
+ */
+ mainFileName: function(fileName){
+ if(fileName){
+
+ var idx = fileName.lastIndexOf(".");
+ if(idx !== -1)
+ return fileName.substring(0,idx);
+ }
+ return fileName;
+ },
+
+ /**
+ * Get the file name of a file path.
+ * @method basename
+ * @example {@link utils/api/cocos/docs/cocos2d/core/utils/CCPath/basename.js}
+ * @param {String} pathStr
+ * @param {String} [extname]
+ * @returns {*}
+ */
+ basename: function (pathStr, extname) {
+ var index = pathStr.indexOf("?");
+ if (index > 0) pathStr = pathStr.substring(0, index);
+ var reg = /(\/|\\\\)([^(\/|\\\\)]+)$/g;
+ 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())
+ return baseName.substring(0, baseName.length - extname.length);
+ return baseName;
+ },
+
+ /**
+ * Get dirname of a file path.
+ * @method dirname
+ * @example {@link utils/api/cocos/docs/cocos2d/core/utils/CCPath/dirname.js}
+ * @param {String} pathStr
+ * @returns {*}
+ */
+ dirname: function (pathStr) {
+ return pathStr.replace(/((.*)(\/|\\|\\\\))?(.*?\..*$)?/, '$2');
+ },
+
+ /**
+ * Change extname of a file path.
+ * @method changeExtname
+ * @example {@link utils/api/cocos/docs/cocos2d/core/utils/CCPath/changeExtname.js}
+ * @param {String} pathStr
+ * @param {String} [extname]
+ * @returns {String}
+ */
+ changeExtname: function (pathStr, extname) {
+ extname = extname || "";
+ var index = pathStr.indexOf("?");
+ var tempStr = "";
+ if (index > 0) {
+ tempStr = pathStr.substring(index);
+ pathStr = pathStr.substring(0, index);
+ }
+ index = pathStr.lastIndexOf(".");
+ if (index < 0) return pathStr + extname + tempStr;
+ return pathStr.substring(0, index) + extname + tempStr;
+ },
+ /**
+ * Change file name of a file path.
+ * @example {@link utils/api/cocos/docs/cocos2d/core/utils/CCPath/changeBasename.js}
+ * @param {String} pathStr
+ * @param {String} basename
+ * @param {Boolean} [isSameExt]
+ * @returns {String}
+ */
+ changeBasename: function (pathStr, basename, isSameExt) {
+ if (basename.indexOf(".") === 0) return this.changeExtname(pathStr, basename);
+ var index = pathStr.indexOf("?");
+ var tempStr = "";
+ var ext = isSameExt ? this.extname(pathStr) : "";
+ if (index > 0) {
+ tempStr = pathStr.substring(index);
+ pathStr = pathStr.substring(0, index);
+ }
+ 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;
+ },
+
+ // The platform-specific file separator. '\\' or '/'.
+ sep: (cc.sys.os === cc.sys.OS_WINDOWS ? '\\' : '/'),
+
+ // @param {string} path
+ // @param {boolean|string} [endsWithSep = true]
+ // @returns {string}
+ _setEndWithSep: function (path, endsWithSep) {
+ var sep = cc.path.sep;
+ if (typeof endsWithSep === 'undefined') {
+ endsWithSep = true;
+ }
+ else if (typeof endsWithSep === 'string') {
+ sep = endsWithSep;
+ endsWithSep = !!endsWithSep;
+ }
+
+ var endChar = path[path.length - 1];
+ var oldEndWithSep = (endChar === '\\' || endChar === '/');
+ if (!oldEndWithSep && endsWithSep) {
+ path += sep;
+ }
+ else if (oldEndWithSep && !endsWithSep) {
+ path = path.slice(0, -1);
+ }
+ return path;
+ }
+};
\ No newline at end of file
diff --git a/cocos2d/core/utils/CCProfiler.js b/cocos2d/core/utils/CCProfiler.js
new file mode 100644
index 0000000000..e6199e5d06
--- /dev/null
+++ b/cocos2d/core/utils/CCProfiler.js
@@ -0,0 +1,160 @@
+/**
+ * @class profiler
+ */
+cc.profiler = (function () {
+ var _inited = _showFPS = false;
+ var _frames = _frameRate = _lastSPF = _accumDt = 0;
+ var _afterProjection = _afterVisitListener = _FPSLabel = _SPFLabel = _drawsLabel = null;
+
+ var LEVEL_DET_FACTOR = 0.6, _levelDetCycle = 10;
+ var LEVELS = [0, 10, 20, 30];
+ var _fpsCount = [0, 0, 0, 0];
+ var _currLevel = 3, _analyseCount = 0, _totalFPS = 0;
+
+ var createStatsLabel = function () {
+ var fontSize = 0;
+ var w = cc.winSize.width, h = cc.winSize.height;
+ var locStatsPosition = cc.DIRECTOR_STATS_POSITION;
+ if (w > h)
+ fontSize = 0 | (h / 320 * 24);
+ else
+ fontSize = 0 | (w / 320 * 24);
+
+ _FPSLabel = new cc.LabelTTF("000.0", "Arial", fontSize);
+ _SPFLabel = new cc.LabelTTF("0.000", "Arial", fontSize);
+ _drawsLabel = new cc.LabelTTF("0000", "Arial", fontSize);
+
+ _drawsLabel.setPosition(_drawsLabel.width / 2 + locStatsPosition.x, _drawsLabel.height * 5 / 2 + locStatsPosition.y);
+ _SPFLabel.setPosition(_SPFLabel.width / 2 + locStatsPosition.x, _SPFLabel.height * 3 / 2 + locStatsPosition.y);
+ _FPSLabel.setPosition(_FPSLabel.width / 2 + locStatsPosition.x, _FPSLabel.height / 2 + locStatsPosition.y);
+ };
+
+ var analyseFPS = function (fps) {
+ var lastId = i = LEVELS.length - 1, ratio, average = 0;
+ _analyseCount++;
+ _totalFPS += fps;
+
+ for (; i >= 0; i--) {
+ if (fps >= LEVELS[i]) {
+ _fpsCount[i]++;
+ break;
+ }
+ }
+
+ if (_analyseCount >= _levelDetCycle) {
+ average = _totalFPS / _levelDetCycle;
+ for (i = lastId; i >0; i--) {
+ ratio = _fpsCount[i] / _levelDetCycle;
+ // Determined level
+ if (ratio >= LEVEL_DET_FACTOR && average >= LEVELS[i]) {
+ // Level changed
+ if (i != _currLevel) {
+ _currLevel = i;
+ profiler.onFrameRateChange && profiler.onFrameRateChange(average.toFixed(2));
+ }
+ break;
+ }
+ // If no level determined, that means the framerate is not stable
+ }
+
+ _changeCount = 0;
+ _analyseCount = 0;
+ _totalFPS = 0;
+ for (i = lastId; i > 0; i--) {
+ _fpsCount[i] = 0;
+ }
+ }
+ };
+
+ var afterVisit = function () {
+ _lastSPF = cc.director.getSecondsPerFrame();
+ _frames++;
+ _accumDt += cc.director.getDeltaTime();
+
+ if (_accumDt > cc.DIRECTOR_FPS_INTERVAL) {
+ _frameRate = _frames / _accumDt;
+ _frames = 0;
+ _accumDt = 0;
+
+ if (profiler.onFrameRateChange) {
+ analyseFPS(_frameRate);
+ }
+
+ if (_showFPS) {
+ _SPFLabel.string = _lastSPF.toFixed(3);
+ _FPSLabel.string = _frameRate.toFixed(1);
+ _drawsLabel.string = (0 | cc.g_NumberOfDraws).toString();
+ }
+ }
+
+ if (_showFPS) {
+ _FPSLabel.visit();
+ _SPFLabel.visit();
+ _drawsLabel.visit();
+ }
+ };
+
+ var afterProjection = function(){
+ _FPSLabel._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
+ _SPFLabel._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
+ _drawsLabel._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
+ };
+
+ var profiler = {
+ onFrameRateChange: null,
+
+ getSecondsPerFrame: function () {
+ return _lastSPF;
+ },
+ getFrameRate: function () {
+ return _frameRate;
+ },
+
+ setProfileDuration: function (duration) {
+ if (!isNaN(duration) && duration > 0) {
+ _levelDetCycle = duration / cc.DIRECTOR_FPS_INTERVAL;
+ }
+ },
+
+ resumeProfiling: function () {
+ cc.director.on(cc.Director.EVENT_AFTER_VISIT, afterVisit);
+ cc.director.on(cc.Director.EVENT_PROJECTION_CHANGED, afterProjection);
+ },
+
+ stopProfiling: function () {
+ cc.director.off(cc.Director.EVENT_AFTER_VISIT, afterVisit);
+ cc.director.off(cc.Director.EVENT_PROJECTION_CHANGED, afterProjection);
+ },
+
+ isShowingStats: function () {
+ return _showFPS;
+ },
+
+ showStats: function () {
+ if (!_inited) {
+ this.init();
+ }
+ if (cc.LabelTTF && !_FPSLabel) {
+ createStatsLabel();
+ }
+ if (_FPSLabel) {
+ _showFPS = true;
+ }
+ },
+
+ hideStats: function () {
+ _showFPS = false;
+ },
+
+ init: function () {
+ if (!_inited) {
+ this.resumeProfiling();
+ _inited = true;
+ }
+ }
+ };
+
+ return profiler;
+})();
+
+module.exports = cc.profiler;
\ No newline at end of file
diff --git a/cocos2d/core/utils/base-node.js b/cocos2d/core/utils/base-node.js
new file mode 100644
index 0000000000..26c4db590e
--- /dev/null
+++ b/cocos2d/core/utils/base-node.js
@@ -0,0 +1,1365 @@
+/****************************************************************************
+ Copyright (c) 2015 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+var JS = cc.js;
+var SceneGraphHelper = require('./scene-graph-helper');
+var SGProto = cc.Node.prototype;
+var Destroying = require('../platform/CCObject').Flags.Destroying;
+var DirtyFlags = require('./misc').DirtyFlags;
+
+// called after changing parent
+function setMaxZOrder (node) {
+ var siblings = node._parent.getChildren();
+ var z = 0;
+ if (siblings.length >= 2) {
+ var prevNode = siblings[siblings.length - 2];
+ z = prevNode.getOrderOfArrival() + 1;
+ }
+ node.setOrderOfArrival(z);
+ return z;
+}
+
+/**
+ * A base node for CCENode and CCEScene, it will:
+ * - provide the same api with origin cocos2d rendering node (SGNode)
+ * - maintains properties of the internal SGNode
+ * - retain and release the SGNode
+ * - serialize datas for SGNode (but SGNode itself will not being serialized)
+ * - notifications if some properties changed
+ * - define some interfaces shares between CCENode and CCEScene
+ *
+ * @class _BaseNode
+ * @extends Object
+ */
+var BaseNode = cc.Class(/** @lends cc.ENode# */{
+ extends: cc.Object,
+
+ properties: {
+
+ // SERIALIZABLE
+
+ _name: '',
+ _opacity: 255,
+ _color: cc.Color.WHITE,
+ _cascadeOpacityEnabled: true,
+ _parent: null,
+ _anchorPoint: cc.p(0.5, 0.5),
+ _contentSize: cc.size(0, 0),
+ _children: [],
+ _rotationX: 0,
+ _rotationY: 0.0,
+ _scaleX: 1.0,
+ _scaleY: 1.0,
+ _position: cc.p(0, 0),
+ _skewX: 0,
+ _skewY: 0,
+ _localZOrder: 0,
+ _globalZOrder: 0,
+ _ignoreAnchorPointForPosition: false,
+ _tag: cc.NODE_TAG_INVALID,
+ _opacityModifyRGB: false,
+
+ // API
+
+ /**
+ * Name of node
+ * @property name
+ * @type {String}
+ */
+ name: {
+ get: function () {
+ return this._name;
+ },
+ set: function (value) {
+ this._name = value;
+ },
+ },
+
+ /**
+ * Parent node
+ * @property name
+ * @type {ENode}
+ */
+ parent: {
+ get: function () {
+ return this._parent;
+ },
+ set: function (value) {
+ if (this._parent === value) {
+ return;
+ }
+ var node = this._sgNode;
+ if (node._parent) {
+ node._parent.removeChild(node, false);
+ }
+ if (value) {
+ var parent = value._sgNode;
+ parent.addChild(node);
+ setMaxZOrder(node);
+ value._children.push(this);
+ }
+ //
+ var oldParent = this._parent;
+ this._parent = value || null;
+ if (oldParent) {
+ if (!(oldParent._objFlags & Destroying)) {
+ var removeAt = oldParent._children.indexOf(this);
+ if (removeAt < 0 && CC_EDITOR) {
+ return cc.error('Internal error, should not remove unknown node from parent.');
+ }
+ oldParent._children.splice(removeAt, 1);
+ this._onHierarchyChanged(oldParent);
+ }
+ }
+ else if (value) {
+ this._onHierarchyChanged(null);
+ }
+ },
+ },
+
+ /**
+ * uuid
+ * @property _id
+ * @type {String}
+ * @private
+ */
+ _id: {
+ default: '',
+ editorOnly: true
+ },
+
+ /**
+ * The uuid for editor, will be stripped before building project
+ * @type {String}
+ * @readOnly
+ */
+ uuid: {
+ get: function () {
+ return this._id || (this._id = Editor.uuid());
+ }
+ },
+
+ /**
+ * Skew x
+ * @property skewX
+ * @type {Number}
+ */
+ skewX: {
+ get: SGProto.getSkewX,
+ set: function (value) {
+ this._skewX = value;
+ this._sgNode.skewX = value;
+ }
+ },
+
+ /**
+ * Skew y
+ * @property skewY
+ * @type {Number}
+ */
+ skewY: {
+ get: SGProto.getSkewY,
+ set: function (value) {
+ this._skewY = value;
+ this._sgNode._skewY = value;
+ }
+ },
+
+ /**
+ * Z order in depth which stands for the drawing order.
+ * @property zIndex
+ * @type {Number}
+ */
+ zIndex: {
+ get: SGProto.getLocalZOrder,
+ set: function (value) {
+ this._localZOrder = value;
+ this._sgNode.zIndex = value;
+ }
+ },
+
+ /**
+ * Rotation of node
+ * @property rotation
+ * @type {Number}
+ */
+ rotation: {
+ get: SGProto.getRotation,
+ set: function (value) {
+ this._rotationX = this._rotationY = value;
+ this._sgNode.rotation = value;
+ },
+ tooltip: "The clockwise degrees of rotation relative to the parent"
+ },
+
+ /**
+ * Rotation on x axis
+ * @property rotationX
+ * @type {Number}
+ */
+ rotationX: {
+ get: SGProto.getRotationX,
+ set: function (value) {
+ this._rotationX = value;
+ this._sgNode.rotationX = value;
+ },
+ },
+
+ /**
+ * Rotation on y axis
+ * @property rotationX
+ * @type {Number}
+ */
+ rotationY: {
+ get: SGProto.getRotationY,
+ set: function (value) {
+ this._rotationY = value;
+ this._sgNode.rotationY = value;
+ },
+ },
+
+ /**
+ * Scale on x axis
+ * @property scaleX
+ * @type {Number}
+ */
+ scaleX: {
+ get: SGProto.getScaleX,
+ set: function (value) {
+ this._scaleX = value;
+ this._sgNode.scaleX = value;
+ },
+ },
+
+ /**
+ * Scale on y axis
+ * @property scaleY
+ * @type {Number}
+ */
+ scaleY: {
+ get: SGProto.getScaleY,
+ set: function (value) {
+ this._scaleY = value;
+ this._sgNode.scaleY = value;
+ },
+ },
+
+ /**
+ * position of node.
+ * @property position
+ * @type {Vec2}
+ */
+ position: {
+ get: SGProto.getPosition,
+ set: function (value) {
+ this._position.x = value.x;
+ this._sgNode.x = value.x;
+
+ this._position.y = value.y;
+ this._sgNode.y = value.y;
+ }
+ },
+
+ /**
+ * x axis position of node.
+ * @property x
+ * @type {Number}
+ */
+ x: {
+ get: SGProto.getPositionX,
+ set: function (value) {
+ this._position.x = value;
+ this._sgNode.x = value;
+ },
+ },
+
+ /**
+ * y axis position of node.
+ * @property y
+ * @type {Number}
+ */
+ y: {
+ get: SGProto.getPositionY,
+ set: function (value) {
+ this._position.y = value;
+ this._sgNode.y = value;
+ },
+ },
+
+ /**
+ * All children nodes
+ * @property children
+ * @type {ENode[]}
+ * @readOnly
+ */
+ children: {
+ get: function () {
+ return this._children;
+ }
+ },
+
+ /**
+ * All children nodes.
+ * @property childrenCount
+ * @type {Number}
+ * @readOnly
+ */
+ childrenCount: {
+ get: function () {
+ return this._children.length;
+ }
+ },
+
+ /**
+ * Anchor point's position on x axis.
+ * @property anchorX
+ * @type {Number}
+ */
+ anchorX: {
+ get: SGProto._getAnchorX,
+ set: function (value) {
+ this._anchorPoint.x = value;
+ this._onAnchorChanged();
+ },
+ },
+
+ /**
+ * Anchor point's position on y axis.
+ * @property anchorY
+ * @type {Number}
+ */
+ anchorY: {
+ get: SGProto._getAnchorY,
+ set: function (value) {
+ this._anchorPoint.y = value;
+ this._onAnchorChanged();
+ },
+ },
+
+ /**
+ * Width of node.
+ * @property width
+ * @type {Number}
+ */
+ width: {
+ get: function () {
+ if (this._sizeProvider) {
+ var w = this._sizeProvider._getWidth();
+ this._contentSize.width = w;
+ return w;
+ }
+ else {
+ return this._contentSize.width;
+ }
+ },
+ set: function (value) {
+ if (this._sizeProvider) {
+ this._sizeProvider.setContentSize(new cc.Size(value, this._sizeProvider._getHeight()));
+ }
+ this._contentSize.width = value;
+ },
+ },
+
+ /**
+ * Height of node.
+ * @property height
+ * @type {Number}
+ */
+ height: {
+ get: function () {
+ if (this._sizeProvider) {
+ var h = this._sizeProvider._getHeight();
+ this._contentSize.height = h;
+ return h;
+ }
+ else {
+ return this._contentSize.height;
+ }
+ },
+ set: function (value) {
+ if (this._sizeProvider) {
+ this._sizeProvider.setContentSize(new cc.Size(this._sizeProvider._getWidth(), value));
+ }
+ this._contentSize.height = value;
+ },
+ },
+
+ //running: {
+ // get: SGProto.isRunning
+ //},
+
+ /**
+ * Indicate whether ignore the anchor point property for positioning.
+ * @property ignoreAnchor
+ * @type {Boolean}
+ */
+ ignoreAnchor: {
+ get: SGProto.isIgnoreAnchorPointForPosition,
+ set: function (value) {
+ this._ignoreAnchorPointForPosition = value;
+ this._sgNode.ignoreAnchor = value;
+ this._onAnchorChanged();
+ },
+ },
+
+ /**
+ * Tag of node.
+ * @property tag
+ * @type {Number}
+ */
+ tag: {
+ get: function () {
+ return this._tag;
+ },
+ set: function (value) {
+ this._tag = value;
+ this._sgNode.tag = value;
+ },
+ },
+
+ /**
+ * Opacity of node, default value is 255.
+ * @property tag
+ * @type {Number}
+ */
+ opacity: {
+ get: function () {
+ return this._opacity;
+ },
+ set: function (value) {
+ this._opacity = value;
+ this._sgNode.opacity = value;
+ this._onColorChanged();
+ },
+ range: [0, 255]
+ },
+
+ /**
+ * Indicate whether node's opacity value affect its child nodes, default value is false.
+ * @property cascadeOpacity
+ * @type {Boolean}
+ */
+ cascadeOpacity: {
+ get: SGProto.isCascadeOpacityEnabled,
+ set: function (value) {
+ if (this._cascadeOpacityEnabled !== value) {
+ this._cascadeOpacityEnabled = value;
+ this._sgNode.cascadeOpacity = value;
+ this._onCascadeChanged();
+ }
+ },
+ },
+
+ /**
+ * Color of node, default value is white: (255, 255, 255).
+ * @property color
+ * @type {Color}
+ */
+ color: {
+ get: function () {
+ var color = this._color;
+ return new cc.Color(color.r, color.g, color.b, color.a);
+ },
+ set: function (value) {
+ var color = this._color;
+ color.r = value.r;
+ color.g = value.g;
+ color.b = value.b;
+ if (CC_DEV && value.a !== 255) {
+ cc.warn('Should not set alpha via "color", use "opacity" please.');
+ }
+ //this._sgNode.color = value;
+ this._onColorChanged();
+ },
+ },
+ },
+
+ ctor: function () {
+ // dont reset _id when destroyed
+ Object.defineProperty(this, '_id', {
+ value: '',
+ enumerable: false
+ });
+
+ var sgNode = this._sgNode = new cc.Node();
+ if (!cc.game._isCloning) {
+ sgNode.cascadeOpacity = true;
+ }
+
+ this._dirtyFlags = DirtyFlags.ALL;
+
+ /**
+ * Current active scene graph node which provides content size.
+ *
+ * @property _sizeProvider
+ * @type {cc.Node}
+ * @private
+ */
+ this._sizeProvider = null;
+ },
+
+ // ABSTRACT INTERFACES
+
+ // called when the node's parent changed
+ _onHierarchyChanged: null,
+ // called when the node's color or opacity changed
+ _onColorChanged: null,
+ // called when the node's anchor changed
+ _onAnchorChanged: null,
+ // called when the node's cascadeOpacity or cascadeColor changed
+ _onCascadeChanged: null,
+ // called when the node's isOpacityModifyRGB changed
+ _onOpacityModifyRGBChanged: null,
+
+
+ /**
+ * Initializes the instance of cc.ENode
+ * @method init
+ * @returns {Boolean} Whether the initialization was successful.
+ * @deprecated, no need anymore
+ */
+ init: function () {
+ return true;
+ },
+
+ /**
+ * Properties configuration function
+ * All properties in attrs will be set to the node,
+ * when the setter of the node is available,
+ * the property will be set via setter function.
+ *
+ * @method attr
+ * @param {Object} attrs - Properties to be set to node
+ */
+ attr: SGProto.attr,
+
+ //Helper function used by `setLocalZOrder`. Don't use it unless you know what you are doing.
+ _setLocalZOrder: function (localZOrder) {
+ this._localZOrder = localZOrder;
+ this._sgNode._localZOrder = localZOrder;
+ },
+
+ /**
+ * Defines the oder in which the nodes are renderer.
+ * Nodes that have a Global Z Order lower, are renderer first.
+ *
+ * In case two or more nodes have the same Global Z Order, the oder is not guaranteed.
+ * The only exception if the Nodes have a Global Z Order == 0. In that case, the Scene Graph order is used.
+ *
+ * By default, all nodes have a Global Z Order = 0. That means that by default, the Scene Graph order is used to render the nodes.
+ *
+ * Global Z Order is useful when you need to render nodes in an order different than the Scene Graph order.
+ *
+ * Limitations: Global Z Order can't be used used by Nodes that have SpriteBatchNode as one of their ancestors.
+ * And if ClippingNode is one of the ancestors, then "global Z order" will be relative to the ClippingNode.
+ * @method setGlobalZOrder
+ * @param {Number} globalZOrder
+ */
+ setGlobalZOrder: function (globalZOrder) {
+ this._globalZOrder = globalZOrder;
+ this._sgNode.setGlobalZOrder(globalZOrder);
+ },
+
+ /**
+ * Return the Node's Global Z Order.
+ * @method getGlobalZOrder
+ * @returns {number} The node's global Z order
+ */
+ getGlobalZOrder: SGProto.getGlobalZOrder,
+
+ /**
+ * Returns the scale factor of the node.
+ * @warning: Assertion will fail when _scaleX != _scaleY.
+ * @method getScale
+ * @return {Number} The scale factor
+ */
+ getScale: SGProto.getScale,
+
+ /**
+ * Sets the scale factor of the node. 1.0 is the default scale factor. This function can modify the X and Y scale at the same time.
+ * @method setScale
+ * @param {Number} scale - or scaleX value
+ * @param {Number} [scaleY=]
+ */
+ setScale: function (scale, scaleY) {
+ if (scale instanceof cc.Vec2) {
+ scaleY = scale.y;
+ scale = scale.x
+ }
+
+ this._scaleX = scale;
+ this._scaleY = (scaleY || scaleY === 0) ? scaleY : scale;
+ this._sgNode.setScale(scale, scaleY);
+ },
+
+ /**
+ * Returns a copy of the position (x,y) of the node in cocos2d coordinates. (0,0) is the left-bottom corner.
+ * @method getPosition
+ * @return {Vec2} The position (x,y) of the node in OpenGL coordinates
+ */
+ getPosition: SGProto.getPosition,
+
+ /**
+ *
+ * Changes the position (x,y) of the node in cocos2d coordinates.
+ * The original point (0,0) is at the left-bottom corner of screen.
+ * Usually we use cc.p(x,y) to compose CCPoint object.
+ * and Passing two numbers (x,y) is more efficient than passing CCPoint object.
+ *
+ * @method setPosition
+ * @param {Vec2|Number} newPosOrxValue - The position (x,y) of the node in coordinates or the X coordinate for position
+ * @param {Number} [yValue] - Y coordinate for position
+ * @example {@link utils/api/cocos/docs/cocos2d/core/utils/node-wrapper/setPosition.js}
+ */
+ 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;
+ }
+ this._sgNode.setPosition(newPosOrxValue, yValue);
+ },
+
+ /**
+ * Returns a copy of the anchor point.
+ * Anchor point is the point around which all transformations and positioning manipulations take place.
+ * It's like a pin in the node where it is "attached" to its parent.
+ * The anchorPoint is normalized, like a percentage. (0,0) means the bottom-left corner and (1,1) means the top-right corner.
+ * But you can use values higher than (1,1) and lower than (0,0) too.
+ * The default anchor point is (0.5,0.5), so it starts at the center of the node.
+ * @method getAnchorPoint
+ * @return {Vec2} The anchor point of node.
+ */
+ getAnchorPoint: SGProto.getAnchorPoint,
+
+ /**
+ *
+ * Sets the anchor point in percent.
+ *
+ * anchor point is the point around which all transformations and positioning manipulations take place.
+ * It's like a pin in the node where it is "attached" to its parent.
+ * The anchorPoint is normalized, like a percentage. (0,0) means the bottom-left corner and (1,1) means the top-right corner.
+ * But you can use values higher than (1,1) and lower than (0,0) too.
+ * The default anchor point is (0.5,0.5), so it starts at the center of the node.
+ *
+ * @method setAnchorPoint
+ * @param {Vec2|Number} point - The anchor point of node or The x axis anchor of node.
+ * @param {Number} [y] - The y axis anchor of node.
+ */
+ setAnchorPoint: function (point, y) {
+ var locAnchorPoint = this._anchorPoint;
+ if (y === undefined) {
+ if ((point.x === locAnchorPoint.x) && (point.y === locAnchorPoint.y))
+ return;
+ locAnchorPoint.x = point.x;
+ locAnchorPoint.y = point.y;
+ } else {
+ if ((point === locAnchorPoint.x) && (y === locAnchorPoint.y))
+ return;
+ locAnchorPoint.x = point;
+ locAnchorPoint.y = y;
+ }
+ this._onAnchorChanged();
+ },
+
+ /**
+ * Returns a copy of the anchor point in absolute pixels.
+ * you can only read it. If you wish to modify it, use setAnchorPoint
+ * @see cc.ENode#getAnchorPoint
+ * @method getAnchorPointInPoints
+ * @return {Vec2} The anchor point in absolute pixels.
+ */
+ getAnchorPointInPoints: function () {
+ return this._sgNode.getAnchorPointInPoints();
+ },
+
+ /**
+ * Returns a copy the untransformed size of the node.
+ * The contentSize remains the same no matter the node is scaled or rotated.
+ * All nodes has a size. Layer and Scene has the same size of the screen by default.
+ * @method getContentSize
+ * @param {Boolean} [ignoreSizeProvider=false] - true if you need to get the original size of the node
+ * @return {Size} The untransformed size of the node.
+ */
+ getContentSize: function (ignoreSizeProvider) {
+ if (this._sizeProvider && !ignoreSizeProvider) {
+ var size = this._sizeProvider.getContentSize();
+ this._contentSize = size;
+ return size;
+ }
+ else {
+ return cc.size(this._contentSize);
+ }
+ },
+
+ /**
+ *
+ * Sets the untransformed size of the node.
+ *
+ * The contentSize remains the same no matter the node is scaled or rotated.
+ * All nodes has a size. Layer and Scene has the same size of the screen.
+ *
+ * @method setContentSize
+ * @param {Size|Number} size - The untransformed size of the node or The untransformed size's width of the node.
+ * @param {Number} [height] - The untransformed size's height of the node.
+ */
+ setContentSize: function (size, height) {
+ var locContentSize = this._contentSize;
+ if (height === undefined) {
+ if ((size.width === locContentSize.width) && (size.height === locContentSize.height))
+ return;
+ locContentSize.width = size.width;
+ locContentSize.height = size.height;
+ } else {
+ if ((size === locContentSize.width) && (height === locContentSize.height))
+ return;
+ locContentSize.width = size;
+ locContentSize.height = height;
+ }
+ if (this._sizeProvider) {
+ this._sizeProvider.setContentSize(locContentSize);
+ }
+ },
+
+ /**
+ * Returns a "local" axis aligned bounding box of the node.
+ * The returned box is relative only to its parent.
+ * @method getBoundingBox
+ * @return {Rect} The calculated bounding box of the node
+ */
+ getBoundingBox: function () {
+ return this._sgNode.getBoundingBox();
+ },
+
+ /**
+ * Stops all running actions and schedulers
+ * @method cleanup
+ */
+ cleanup: function () {
+ //// actions
+ //this.stopAllActions();
+ //this.unscheduleAllCallbacks();
+ //
+ //// event
+ //cc.eventManager.removeListeners(this);
+
+ // children
+ SGProto._arrayMakeObjectsPerformSelector(this._children, cc.Node._stateCallbackType.cleanup);
+ },
+
+ // composition: GET
+
+ /**
+ * Returns a child from the container given its tag
+ * @method getChildByTag
+ * @param {Number} aTag - An identifier to find the child node.
+ * @return {ENode} a CCNode object whose tag equals to the input parameter
+ */
+ getChildByTag: SGProto.getChildByTag,
+
+ /**
+ * Returns a child from the container given its name
+ * @method getChildByName
+ * @param {String} name - A name to find the child node.
+ * @return {ENode} a CCNode object whose name equals to the input parameter
+ */
+ getChildByName: SGProto.getChildByName,
+
+ // composition: ADD
+
+ /** "add" logic MUST only be in this method
+ *
+ * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately.
+ * @method addChild
+ * @param {ENode} child - A child node
+ * @param {Number} [localZOrder=] - Z order for drawing priority. Please refer to setZOrder(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.js.isUndefined(tag)){
+ tag = undefined;
+ name = child._name;
+ } else if(cc.js.isString(tag)){
+ name = tag;
+ tag = undefined;
+ } else if(cc.js.isNumber(tag)){
+ setTag = true;
+ name = "";
+ }
+
+ cc.assert(child, cc._LogInfos.Node.addChild_3);
+ cc.assert(child._parent === null, "child already added. It can't be added again");
+
+ this._addChildHelper(child, localZOrder, tag, name, setTag);
+ },
+
+ _addChildHelper: function(child, localZOrder, tag, name, setTag){
+ this._insertChild(child, localZOrder);
+ if (setTag)
+ child.setTag(tag);
+ else
+ child.setName(name);
+ },
+
+ _insertChild: function (child, z) {
+ child.parent = this;
+ child._setLocalZOrder(z);
+ },
+
+ // composition: REMOVE
+
+ /**
+ * Remove itself from its parent node. If cleanup is true, then also remove all actions and callbacks.
+ * If the cleanup parameter is not passed, it will force a cleanup.
+ * If the node orphan, then nothing happens.
+ * @method removeFromParent
+ * @param {Boolean} [cleanup=true] - true if all actions and callbacks on this node should be removed, false otherwise.
+ * @see cc.ENode#removeFromParentAndCleanup
+ */
+ removeFromParent: function (cleanup) {
+ if (this._parent) {
+ if (cleanup === undefined)
+ cleanup = true;
+ this._parent.removeChild(this, cleanup);
+ }
+ },
+
+ /** Removes a child from the container. It will also cleanup all running actions depending on the cleanup parameter.
+ * If the cleanup parameter is not passed, it will force a cleanup.
+ * "remove" logic MUST only be on this method
+ * If a class wants to extend the 'removeChild' behavior it only needs
+ * to override this method
+ * @method removeChild
+ * @param {ENode} child - The child node which will be removed.
+ * @param {Boolean} [cleanup=true] - true if all running actions and callbacks on the child node will be cleanup, false otherwise.
+ */
+ removeChild: function (child, cleanup) {
+ // explicit nil handling
+ if (this._children.length === 0)
+ return;
+
+ if (cleanup === undefined)
+ cleanup = true;
+ if (this._children.indexOf(child) > -1)
+ this._detachChild(child, cleanup);
+ },
+
+ /**
+ * Removes a child from the container by tag value. It will also cleanup all running actions depending on the cleanup parameter.
+ * If the cleanup parameter is not passed, it will force a cleanup.
+ * @method removeChildByTag
+ * @param {Number} tag - An integer number that identifies a child node
+ * @param {Boolean} [cleanup=true] - true if all running actions and callbacks on the child node will be cleanup, false otherwise.
+ * @see cc.ENode#removeChildByTag
+ */
+ removeChildByTag: function (tag, cleanup) {
+ if (tag === cc.NODE_TAG_INVALID)
+ cc.log(cc._LogInfos.Node.removeChildByTag);
+
+ var child = this.getChildByTag(tag);
+ if (!child)
+ cc.log(cc._LogInfos.Node.removeChildByTag_2, tag);
+ else
+ this.removeChild(child, cleanup);
+ },
+
+ /**
+ * Removes all children from the container and do a cleanup all running actions depending on the cleanup parameter.
+ * If the cleanup parameter is not passed, it will force a cleanup.
+ * @method removeAllChildren
+ * @param {Boolean} [cleanup=true] - true if all running actions on all children nodes should be cleanup, false otherwise.
+ */
+ removeAllChildren: function (cleanup) {
+ // not using detachChild improves speed here
+ var children = this._children;
+ if (cleanup === undefined)
+ cleanup = true;
+ for (var i = 0; i < children.length; i++) {
+ var node = children[i];
+ if (node) {
+ //if (this._running) {
+ // node.onExitTransitionDidStart();
+ // node.onExit();
+ //}
+
+ // If you don't do cleanup, the node's actions will not get removed and the
+ if (cleanup)
+ node.cleanup();
+
+ node.parent = null;
+ }
+ }
+ this._children.length = 0;
+ },
+
+ _detachChild: function (child, doCleanup) {
+ // IMPORTANT:
+ // - 1st do onExit
+ // - 2nd cleanup
+ //if (this._running) {
+ // child.onExitTransitionDidStart();
+ // child.onExit();
+ //}
+
+ // If you don't do cleanup, the child's actions will not get removed and the
+ if (doCleanup)
+ child.cleanup();
+
+ child.parent = null;
+ cc.js.array.remove(this._children, child);
+ },
+
+ setNodeDirty: function(){
+ this._sgNode.setNodeDirty();
+ },
+
+ /**
+ * Returns the matrix that transform parent's space coordinates to the node's (local) space coordinates.
+ * The matrix is in Pixels.
+ * @method getParentToNodeTransform
+ * @return {AffineTransform}
+ */
+ getParentToNodeTransform: function () {
+ return this._sgNode.getParentToNodeTransform();
+ },
+
+ /**
+ * Returns the world affine transform matrix. The matrix is in Pixels.
+ * @method getNodeToWorldTransform
+ * @return {AffineTransform}
+ */
+ getNodeToWorldTransform: function () {
+ return this._sgNode.getNodeToWorldTransform();
+ },
+
+ /**
+ * Returns the inverse world affine transform matrix. The matrix is in Pixels.
+ * @method getWorldToNodeTransform
+ * @return {AffineTransform}
+ */
+ getWorldToNodeTransform: function () {
+ return this._sgNode.getWorldToNodeTransform();
+ },
+
+ /**
+ * Converts a Point to node (local) space coordinates. The result is in Points.
+ * @method convertToNodeSpace
+ * @param {Vec2} worldPoint
+ * @return {Vec2}
+ */
+ convertToNodeSpace: function (worldPoint) {
+ return this._sgNode.convertToNodeSpace(worldPoint);
+ },
+
+ /**
+ * Converts a Point to world space coordinates. The result is in Points.
+ * @method convertToWorldSpace
+ * @param {Vec2} nodePoint
+ * @return {Vec2}
+ */
+ convertToWorldSpace: function (nodePoint) {
+ return this._sgNode.convertToWorldSpace(nodePoint);
+ },
+
+ /**
+ * Converts a Point to node (local) space coordinates. The result is in Points.
+ * treating the returned/received node point as anchor relative.
+ * @method convertToNodeSpaceAR
+ * @param {Vec2} worldPoint
+ * @return {Vec2}
+ */
+ convertToNodeSpaceAR: function (worldPoint) {
+ return this._sgNode.convertToNodeSpaceAR(worldPoint);
+ },
+
+ /**
+ * Converts a local Point to world space coordinates.The result is in Points.
+ * treating the returned/received node point as anchor relative.
+ * @method convertToWorldSpaceAR
+ * @param {Vec2} nodePoint
+ * @return {Vec2}
+ */
+ convertToWorldSpaceAR: function (nodePoint) {
+ return this._sgNode.convertToWorldSpaceAR(nodePoint);
+ },
+
+ _convertToWindowSpace: function (nodePoint) {
+ return this._sgNode._convertToWindowSpace(nodePoint);
+ },
+
+ /**
+ * convenience methods which take a cc.Touch instead of cc.Vec2
+ * @method convertTouchToNodeSpace
+ * @param {Touch} touch - The touch object
+ * @return {Vec2}
+ */
+ convertTouchToNodeSpace: function (touch) {
+ return this._sgNode.convertTouchToNodeSpace(touch)
+ },
+
+ /**
+ * converts a cc.Touch (world coordinates) into a local coordinate. This method is AR (Anchor Relative).
+ * @method convertTouchToNodeSpaceAR
+ * @param {Touch} touch - The touch object
+ * @return {Vec2}
+ */
+ convertTouchToNodeSpaceAR: function (touch) {
+ return this._sgNode.convertTouchToNodeSpaceAR(touch);
+ },
+
+ /**
+ * Returns the matrix that transform the node's (local) space coordinates into the parent's space coordinates.
+ * The matrix is in Pixels.
+ * @method getNodeToParentTransform
+ * @return {AffineTransform} The affine transform object
+ */
+ getNodeToParentTransform: function (ancestor) {
+ return this._sgNode.getNodeToParentTransform();
+ },
+
+ /**
+ * Returns a "world" axis aligned bounding box of the node.
+ * @method getBoundingBoxToWorld
+ * @return {Rect}
+ */
+ getBoundingBoxToWorld: function () {
+ return this._sgNode.getBoundingBoxToWorld();
+ },
+
+ _getBoundingBoxToCurrentNode: function (parentTransform) {
+ return this._sgNode._getBoundingBoxToCurrentNode(parentTransform);
+ },
+
+ /**
+ * Returns the displayed opacity of Node,
+ * the difference between displayed opacity and opacity is that displayed opacity is calculated based on opacity and parent node's opacity when cascade opacity enabled.
+ * @method getDisplayedOpacity
+ * @returns {number} displayed opacity
+ */
+ getDisplayedOpacity: function () {
+ return this._sgNode.getDisplayedOpacity();
+ },
+
+ /**
+ * Update displayed opacity
+ * @method
+ * @param {Number} parentOpacity
+ */
+ _updateDisplayedOpacity: function (parentOpacity) {
+ this._sgNode.updateDisplayedOpacity(parentOpacity);
+ },
+
+ /**
+ * Returns the displayed color of Node,
+ * the difference between displayed color and color is that displayed color is calculated based on color and parent node's color when cascade color enabled.
+ * @method getDisplayedColor
+ * @returns {Color}
+ */
+ getDisplayedColor: function () {
+ return this._sgNode.getDisplayedColor();
+ },
+
+ /**
+ * Update the displayed color of Node
+ * @method
+ * @param {Color} parentColor
+ */
+ _updateDisplayedColor: function (parentColor) {
+ this._sgNode._updateDisplayedColor(parentColor);
+ },
+
+ /**
+ * Set whether color should be changed with the opacity value,
+ * useless in cc.Node, but this function is override in some class to have such behavior.
+ * @method setOpacityModifyRGB
+ * @param {Boolean} opacityValue
+ */
+ setOpacityModifyRGB: function (opacityValue) {
+ if (this._opacityModifyRGB !== opacityValue) {
+ this._opacityModifyRGB = opacityValue;
+ this._sgNode.setOpacityModifyRGB(opacityValue);
+ this._onOpacityModifyRGBChanged();
+ }
+ },
+
+ /**
+ * Get whether color should be changed with the opacity value
+ * @method isOpacityModifyRGB
+ * @return {Boolean}
+ */
+ isOpacityModifyRGB: function () {
+ return this._opacityModifyRGB;
+ },
+
+ // HIERARCHY METHODS
+
+ /**
+ * Get the sibling index.
+ *
+ * @method getSiblingIndex
+ * @return {number}
+ */
+ getSiblingIndex: function () {
+ if (this._parent) {
+ return this._parent._children.indexOf(this);
+ }
+ else {
+ return 0;
+ }
+ },
+
+ /**
+ * Set the sibling index of this node.
+ *
+ * @method setSiblingIndex
+ * @param {Number} index
+ */
+ setSiblingIndex: function (index) {
+ if (!this._parent) {
+ return;
+ }
+ var array = this._parent._children;
+ index = index !== -1 ? index : array.length - 1;
+ var oldIndex = array.indexOf(this);
+ if (index !== oldIndex) {
+ array.splice(oldIndex, 1);
+ if (index < array.length) {
+ array.splice(index, 0, this);
+ }
+ else {
+ array.push(this);
+ }
+
+ // update rendering scene graph, sort them by arrivalOrder
+ var siblings = this._parent._children;
+ for (var i = 0, len = siblings.length; i < len; i++) {
+ var sibling = siblings[i];
+ sibling._sgNode.arrivalOrder = i;
+ }
+ cc.renderer.childrenOrderDirty = this._parent._sgNode._reorderChildDirty = true;
+ }
+ },
+
+ /**
+ * Is this node a child of the given node?
+ *
+ * @method isChildOf
+ * @param {ENode} parent
+ * @return {Boolean} - Returns true if this node is a child, deep child or identical to the given node.
+ */
+ isChildOf: function (parent) {
+ var child = this;
+ do {
+ if (child === parent) {
+ return true;
+ }
+ child = child._parent;
+ }
+ while (child);
+ return false;
+ },
+
+ // The deserializer for sgNode which will be called before components onLoad
+ _onBatchCreated: function () {
+ var sgNode = this._sgNode;
+ sgNode.setOpacity(this._opacity);
+ sgNode.setCascadeOpacityEnabled(this._cascadeOpacityEnabled);
+ sgNode.setRotationX(this._rotationX);
+ sgNode.setRotationY(this._rotationY);
+ sgNode.setScale(this._scaleX, this._scaleY);
+ sgNode.setPosition(this._position);
+ sgNode.setSkewX(this._skewX);
+ sgNode.setSkewY(this._skewY);
+ sgNode.setLocalZOrder(this._localZOrder);
+ sgNode.setGlobalZOrder(this._globalZOrder);
+ sgNode.ignoreAnchorPointForPosition(this._ignoreAnchorPointForPosition);
+ sgNode.setTag(this._tag);
+ sgNode.setOpacityModifyRGB(this._opacityModifyRGB);
+
+ if (this._parent) {
+ this._parent._sgNode.addChild(sgNode);
+ }
+
+ var children = this._children;
+ for (var i = 0, len = children.length; i < len; i++) {
+ children[i]._onBatchCreated();
+ }
+ },
+
+ _removeSgNode: SceneGraphHelper.removeSgNode,
+});
+
+
+(function () {
+
+ // Define public getter and setter methods to ensure api compatibility.
+
+ var SameNameGetSets = ['name', 'skewX', 'skewY', 'rotation', 'rotationX', 'rotationY',
+ 'scale', 'scaleX', 'scaleY', 'children', 'childrenCount', 'parent', 'running',
+ /*'actionManager',*/ 'scheduler', /*'shaderProgram',*/ 'opacity', 'color', 'tag'];
+ var DiffNameGetSets = {
+ x: ['getPositionX', 'setPositionX'],
+ y: ['getPositionY', 'setPositionY'],
+ zIndex: ['getLocalZOrder', 'setLocalZOrder'],
+ //running: ['isRunning'],
+ ignoreAnchor: ['isIgnoreAnchorPointForPosition', 'ignoreAnchorPointForPosition'],
+ opacityModifyRGB: ['isOpacityModifyRGB'],
+ cascadeOpacity: ['isCascadeOpacityEnabled', 'setCascadeOpacityEnabled'],
+ cascadeColor: ['isCascadeColorEnabled', 'setCascadeColorEnabled'],
+ //// privates
+ //width: ['_getWidth', '_setWidth'],
+ //height: ['_getHeight', '_setHeight'],
+ //anchorX: ['_getAnchorX', '_setAnchorX'],
+ //anchorY: ['_getAnchorY', '_setAnchorY'],
+ };
+ var propName, np = BaseNode.prototype;
+ for (var i = 0; i < SameNameGetSets.length; i++) {
+ propName = SameNameGetSets[i];
+ var suffix = propName[0].toUpperCase() + propName.slice(1);
+ var pd = Object.getOwnPropertyDescriptor(np, propName);
+ if (pd) {
+ if (pd.get) np['get' + suffix] = pd.get;
+ if (pd.set) np['set' + suffix] = pd.set;
+ }
+ else {
+ JS.getset(np, propName, np['get' + suffix], np['set' + suffix]);
+ }
+ }
+ for (propName in DiffNameGetSets) {
+ var getset = DiffNameGetSets[propName];
+ var pd = Object.getOwnPropertyDescriptor(np, propName);
+ if (pd) {
+ np[getset[0]] = pd.get;
+ if (getset[1]) np[getset[1]] = pd.set;
+ }
+ else {
+ JS.getset(np, propName, np[getset[0]], np[getset[1]]);
+ }
+ }
+})();
+
+/**
+ * Scale of node
+ * @property scale
+ * @type {Number}
+ */
+
+/**
+ * Sets the x axis position of the node in cocos2d coordinates.
+ * @method getPositionX
+ * @param {Number} x - The new position in x axis
+ */
+
+/**
+ * Returns the x axis position of the node in cocos2d coordinates.
+ * @method setPositionX
+ * @return {Number}
+ */
+
+/**
+ * Returns the y axis position of the node in cocos2d coordinates.
+ * @method getPositionY
+ * @return {Number}
+ */
+
+/**
+ * Sets the y axis position of the node in cocos2d coordinates.
+ * @method setPositionY
+ * @param {Number} y - The new position in y axis
+ */
+
+/**
+ * Returns the local Z order of this node.
+ * @method getLocalZOrder
+ * @returns {Number} The local (relative to its siblings) Z order.
+ */
+
+/**
+ * LocalZOrder is the 'key' used to sort the node relative to its siblings.
+ *
+ * The Node's parent will sort all its children based ont the LocalZOrder value.
+ * If two nodes have the same LocalZOrder, then the node that was added first to the children's array
+ * will be in front of the other node in the array.
+ *
+ * Also, the Scene Graph is traversed using the "In-Order" tree traversal algorithm ( http://en.wikipedia.org/wiki/Tree_traversal#In-order )
+ *
+ * And Nodes that have LocalZOder values < 0 are the "left" subtree
+ * While Nodes with LocalZOder >=0 are the "right" subtree.
+ * @method setLocalZOrder
+ * @param {Number} localZOrder
+ */
+
+/**
+ * Returns whether the anchor point will be ignored when you position this node.
+ * When anchor point ignored, position will be calculated based on the origin point (0, 0) in parent's coordinates.
+ * @method isIgnoreAnchorPointForPosition
+ * @return {Boolean} true if the anchor point will be ignored when you position this node.
+ */
+
+/**
+ *
+ * Sets whether the anchor point will be ignored when you position this node.
+ * When anchor point ignored, position will be calculated based on the origin point (0, 0) in parent's coordinates.
+ * This is an internal method, only used by CCLayer and CCScene. Don't call it outside framework.
+ * The default value is false, while in CCLayer and CCScene are true
+ *
+ * @method ignoreAnchorPointForPosition
+ * @param {Boolean} newValue - true if anchor point will be ignored when you position this node
+ */
+
+/**
+ * Returns whether node's opacity value affect its child nodes.
+ * @method isCascadeOpacityEnabled
+ * @returns {Boolean}
+ */
+
+/**
+ * Enable or disable cascade opacity, if cascade enabled, child nodes' opacity will be the multiplication of parent opacity and its own opacity.
+ * @method setCascadeOpacityEnabled
+ * @param {Boolean} cascadeOpacityEnabled
+ */
+
+/**
+ * Returns whether node's color value affect its child nodes.
+ * @method isCascadeColorEnabled
+ * @returns {Boolean}
+ */
+
+/**
+ * Enable or disable cascade color, if cascade enabled, child nodes' opacity will be the cascade value of parent color and its own color.
+ * @method setCascadeColorEnabled
+ * @param {Boolean} cascadeColorEnabled
+ */
+
+
+cc._BaseNode = module.exports = BaseNode;
diff --git a/cocos2d/core/utils/find.js b/cocos2d/core/utils/find.js
new file mode 100644
index 0000000000..bccf007628
--- /dev/null
+++ b/cocos2d/core/utils/find.js
@@ -0,0 +1,66 @@
+/**
+ * Finds a node by hierarchy path, the path is case-sensitive.
+ * It will traverse the hierarchy by splitting the path using '/' character.
+ * This function will still returns the node even if it is inactive.
+ * It is recommended to not use this function every frame instead cache the result at startup.
+ *
+ * @method find
+ * @static
+ * @param {String} path
+ * @param {ENode} [referenceNode]
+ * @return {ENode} the node or null if not found
+ */
+cc.find = module.exports = function (path, referenceNode) {
+ if (path == null) {
+ cc.error('Argument must be non-nil');
+ return null;
+ }
+ if (!referenceNode) {
+ var scene = cc.director.getScene();
+ if (!scene) {
+ cc.warn('Can not get current scene.');
+ return null;
+ }
+ referenceNode = scene;
+ }
+
+ var match = referenceNode;
+ var startIndex = (path[0] !== '/') ? 0 : 1; // skip first '/'
+ var nameList = path.split('/');
+
+ // parse path
+ for (var n = startIndex; n < nameList.length; n++) {
+ var name = nameList[n];
+ var findByComp = name[0] === '<' && name[name.length - 1] === '>';
+ var Comp;
+ if (findByComp) {
+ var compName = name.slice(1, -1);
+ Comp = cc.js.getClassByName(compName);
+ if (!Comp) {
+ cc.warn('Failed to find component ' + compName);
+ return null;
+ }
+ }
+ // visit sub nodes
+ var children = match._children;
+ match = null;
+ for (var t = 0, len = children.length; t < len; ++t) {
+ var subChild = children[t];
+ if (findByComp) {
+ if (subChild.getComponent(Comp)) {
+ match = subChild;
+ break;
+ }
+ }
+ else if (subChild.name === name) {
+ match = subChild;
+ break;
+ }
+ }
+ if (!match) {
+ return null;
+ }
+ }
+
+ return match;
+};
diff --git a/cocos2d/core/utils/index.js b/cocos2d/core/utils/index.js
new file mode 100644
index 0000000000..ed36db128f
--- /dev/null
+++ b/cocos2d/core/utils/index.js
@@ -0,0 +1,4 @@
+require('./Async');
+require('./CCPath');
+require('./CCProfiler');
+require('./find');
diff --git a/cocos2d/core/utils/misc.js b/cocos2d/core/utils/misc.js
new file mode 100644
index 0000000000..f50b2d836c
--- /dev/null
+++ b/cocos2d/core/utils/misc.js
@@ -0,0 +1,47 @@
+var JS = cc.js;
+
+var misc = {};
+
+misc.propertyDefine = function (ctor, sameNameGetSets, diffNameGetSets) {
+ var propName, np = ctor.prototype;
+ for (var i = 0; i < sameNameGetSets.length; i++) {
+ propName = sameNameGetSets[i];
+ var suffix = propName[0].toUpperCase() + propName.slice(1);
+ var pd = Object.getOwnPropertyDescriptor(np, propName);
+ if (pd) {
+ if (pd.get) np['get' + suffix] = pd.get;
+ if (pd.set) np['set' + suffix] = pd.set;
+ }
+ else {
+ JS.getset(np, propName, np['get' + suffix], np['set' + suffix]);
+ }
+ }
+ for (propName in diffNameGetSets) {
+ var getset = diffNameGetSets[propName];
+ var pd = Object.getOwnPropertyDescriptor(np, propName);
+ if (pd) {
+ np[getset[0]] = pd.get;
+ if (getset[1]) np[getset[1]] = pd.set;
+ }
+ else {
+ JS.getset(np, propName, np[getset[0]], np[getset[1]]);
+ }
+ }
+};
+
+var DirtyFlags = misc.DirtyFlags = {
+ TRANSFORM: 1 << 0,
+ SIZE: 1 << 1,
+ //Visible:
+ //Color:
+ //Opacity
+ //Cache
+ //Order
+ //Text
+ //Gradient
+ ALL: (1 << 2) - 1
+};
+
+DirtyFlags.WIDGET = DirtyFlags.TRANSFORM | DirtyFlags.SIZE;
+
+module.exports = misc;
diff --git a/cocos2d/core/utils/scene-graph-helper.js b/cocos2d/core/utils/scene-graph-helper.js
new file mode 100644
index 0000000000..592517e1d2
--- /dev/null
+++ b/cocos2d/core/utils/scene-graph-helper.js
@@ -0,0 +1,63 @@
+ï»ż
+// Helps to maintain the actual scene graph for Entity-Component.
+
+var SceneGraphUtils = {
+ removeSgNode: function () {
+ var node = this._sgNode;
+ if (node) {
+ if (node._parent) {
+ node._parent.removeChild(node);
+ }
+ this._sgNode = null;
+ }
+ },
+};
+
+if (CC_DEV) {
+ SceneGraphUtils._getChildrenOffset = function (entityParent) {
+ if (entityParent) {
+ var sgParent = entityParent._sgNode;
+ var firstChildEntity = entityParent._children[0];
+ if (firstChildEntity) {
+ var firstChildSg = firstChildEntity._sgNode;
+ var offset = sgParent._children.indexOf(firstChildSg);
+ if (offset !== -1) {
+ return offset;
+ }
+ else {
+ cc.error("%s's scene graph node not contains in the parent's children", firstChildEntity.name);
+ return -1;
+ }
+ }
+ else {
+ return sgParent._children.length;
+ }
+ }
+ else {
+ return 0; // the root of hierarchy
+ }
+ };
+ SceneGraphUtils.checkMatchCurrentScene = function () {
+ var scene = cc.director.getScene();
+ var sgScene = cc.director.getRunningScene();
+ function checkMatch (ent, sgNode) {
+ if (ent._sgNode !== sgNode) {
+ throw new Error('scene graph node not equal: ' + ent.name);
+ }
+
+ var childCount = ent._children.length;
+ var childrenOffset = SceneGraphUtils._getChildrenOffset(ent);
+ if (sgNode._children.length !== childCount + childrenOffset) {
+ throw new Error('Mismatched child scene graphs: ' + ent.name);
+ }
+ for (var i = 0; i < childCount; i++) {
+ checkMatch(ent._children[i], sgNode._children[childrenOffset + i]);
+ }
+ }
+
+ checkMatch(scene, sgScene);
+ };
+ cc._Test.SceneGraphUtils = SceneGraphUtils;
+}
+
+module.exports = SceneGraphUtils;
diff --git a/cocos2d/core/value-types/CCAffineTransform.js b/cocos2d/core/value-types/CCAffineTransform.js
new file mode 100644
index 0000000000..6295ecd633
--- /dev/null
+++ b/cocos2d/core/value-types/CCAffineTransform.js
@@ -0,0 +1,288 @@
+/****************************************************************************
+ 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.AffineTransform class represent an affine transform matrix. It's composed basically by translation, rotation, scale transformations.
+ * Please do not use its constructor directly, use cc.affineTransformMake alias function instead.
+ *
+ * @class AffineTransform
+ * @param {Number} a
+ * @param {Number} b
+ * @param {Number} c
+ * @param {Number} d
+ * @param {Number} tx
+ * @param {Number} ty
+ * @see cc.affineTransformMake
+ */
+cc.AffineTransform = function (a, b, c, d, tx, ty) {
+ this.a = a;
+ this.b = b;
+ this.c = c;
+ this.d = d;
+ this.tx = tx;
+ this.ty = ty;
+};
+
+/**
+ * Create a cc.AffineTransform object with all contents in the matrix
+ * @method affineTransformMake
+ *
+ * @param {Number} a
+ * @param {Number} b
+ * @param {Number} c
+ * @param {Number} d
+ * @param {Number} tx
+ * @param {Number} ty
+ * @return {AffineTransform}
+ */
+cc.affineTransformMake = function (a, b, c, d, tx, ty) {
+ return {a: a, b: b, c: c, d: d, tx: tx, ty: ty};
+};
+
+/**
+ * Apply the affine transformation on a point.
+ * @method pointApplyAffineTransform
+ *
+ * @param {Vec2|Number} point - or x.
+ * @param {AffineTransform|Number} transOrY - transform matrix or y.
+ * @param {AffineTransform} t - transform matrix or y.
+ * @return {Vec2}
+ */
+cc.pointApplyAffineTransform = function (point, transOrY, t) {
+ var x, y;
+ if (t === undefined) {
+ t = transOrY;
+ x = point.x;
+ y = point.y;
+ } else {
+ x = point;
+ y = transOrY;
+ }
+ return {x: t.a * x + t.c * y + t.tx, y: t.b * x + t.d * y + t.ty};
+};
+
+cc._pointApplyAffineTransform = function (x, y, t) { //it will remove.
+ return cc.pointApplyAffineTransform(x, y, t);
+};
+
+/**
+ * Apply the affine transformation on a size.
+ * @method sizeApplyAffineTransform
+ *
+ * @param {Size} size
+ * @param {AffineTransform} t
+ * @return {Size}
+ */
+cc.sizeApplyAffineTransform = function (size, t) {
+ return {width: t.a * size.width + t.c * size.height, height: t.b * size.width + t.d * size.height};
+};
+
+/**
+ * Create a identity transformation matrix:
+ * [ 1, 0, 0,
+ * 0, 1, 0 ]
+ *
+ * @method affineTransformMakeIdentity
+ * @return {AffineTransform}
+ */
+cc.affineTransformMakeIdentity = function () {
+ return {a: 1.0, b: 0.0, c: 0.0, d: 1.0, tx: 0.0, ty: 0.0};
+};
+
+/**
+ * Create a identity transformation matrix:
+ * [ 1, 0, 0,
+ * 0, 1, 0 ]
+ *
+ * @method affineTransformIdentity
+ * @return {AffineTransform}
+ * @deprecated since v3.0, please use cc.affineTransformMakeIdentity() instead
+ * @see cc.affineTransformMakeIdentity
+ */
+cc.affineTransformIdentity = function () {
+ return {a: 1.0, b: 0.0, c: 0.0, d: 1.0, tx: 0.0, ty: 0.0};
+};
+
+/**
+ * Apply the affine transformation on a rect.
+ *
+ * @method rectApplyAffineTransform
+ * @param {Rect} rect
+ * @param {AffineTransform} anAffineTransform
+ * @return {Rect}
+ */
+cc.rectApplyAffineTransform = function (rect, anAffineTransform) {
+ var top = cc.rectGetMinY(rect);
+ var left = cc.rectGetMinX(rect);
+ var right = cc.rectGetMaxX(rect);
+ var bottom = cc.rectGetMaxY(rect);
+
+ var topLeft = cc.pointApplyAffineTransform(left, top, anAffineTransform);
+ var topRight = cc.pointApplyAffineTransform(right, top, anAffineTransform);
+ var bottomLeft = cc.pointApplyAffineTransform(left, bottom, anAffineTransform);
+ var bottomRight = cc.pointApplyAffineTransform(right, bottom, anAffineTransform);
+
+ var minX = Math.min(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x);
+ var maxX = Math.max(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x);
+ var minY = Math.min(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y);
+ var maxY = Math.max(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y);
+
+ return cc.rect(minX, minY, (maxX - minX), (maxY - minY));
+};
+
+cc._rectApplyAffineTransformIn = function(rect, anAffineTransform){
+ var top = cc.rectGetMinY(rect);
+ var left = cc.rectGetMinX(rect);
+ var right = cc.rectGetMaxX(rect);
+ var bottom = cc.rectGetMaxY(rect);
+
+ var topLeft = cc.pointApplyAffineTransform(left, top, anAffineTransform);
+ var topRight = cc.pointApplyAffineTransform(right, top, anAffineTransform);
+ var bottomLeft = cc.pointApplyAffineTransform(left, bottom, anAffineTransform);
+ var bottomRight = cc.pointApplyAffineTransform(right, bottom, anAffineTransform);
+
+ var minX = Math.min(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x);
+ var maxX = Math.max(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x);
+ var minY = Math.min(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y);
+ var maxY = Math.max(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y);
+
+ rect.x = minX;
+ rect.y = minY;
+ rect.width = maxX - minX;
+ rect.height = maxY - minY;
+ return rect;
+};
+
+/**
+ * Create a new affine transformation with a base transformation matrix and a translation based on it.
+ *
+ * @method affineTransformTranslate
+ * @param {AffineTransform} t - The base affine transform object.
+ * @param {Number} tx - The translation on x axis.
+ * @param {Number} ty - The translation on y axis.
+ * @return {AffineTransform}
+ */
+cc.affineTransformTranslate = function (t, tx, ty) {
+ return {
+ a: t.a,
+ b: t.b,
+ c: t.c,
+ d: t.d,
+ tx: t.tx + t.a * tx + t.c * ty,
+ ty: t.ty + t.b * tx + t.d * ty
+ };
+};
+
+/**
+ * Create a new affine transformation with a base transformation matrix and a scale based on it.
+ * @method affineTransformScale
+ * @param {AffineTransform} t - The base affine transform object.
+ * @param {Number} sx - The scale on x axis.
+ * @param {Number} sy - The scale on y axis.
+ * @return {AffineTransform}
+ */
+cc.affineTransformScale = function (t, sx, sy) {
+ return {a: t.a * sx, b: t.b * sx, c: t.c * sy, d: t.d * sy, tx: t.tx, ty: t.ty};
+};
+
+/**
+ * Create a new affine transformation with a base transformation matrix and a rotation based on it.
+ * @method affineTransformRotate
+ * @param {AffineTransform} aTransform - The base affine transform object.
+ * @param {Number} anAngle - The angle to rotate.
+ * @return {AffineTransform}
+ */
+cc.affineTransformRotate = function (aTransform, anAngle) {
+ var fSin = Math.sin(anAngle);
+ var fCos = Math.cos(anAngle);
+
+ return {a: aTransform.a * fCos + aTransform.c * fSin,
+ b: aTransform.b * fCos + aTransform.d * fSin,
+ c: aTransform.c * fCos - aTransform.a * fSin,
+ d: aTransform.d * fCos - aTransform.b * fSin,
+ tx: aTransform.tx,
+ ty: aTransform.ty};
+};
+
+/**
+ * Concatenate a transform matrix to another and return the result:
+ * t' = t1 * t2
+ * @method affineTransformConcat
+ * @param {AffineTransform} t1 - The first transform object.
+ * @param {AffineTransform} t2 - The transform object to concatenate.
+ * @return {AffineTransform} The result of concatenation.
+ */
+cc.affineTransformConcat = function (t1, t2) {
+ return {a: t1.a * t2.a + t1.b * t2.c, //a
+ b: t1.a * t2.b + t1.b * t2.d, //b
+ c: t1.c * t2.a + t1.d * t2.c, //c
+ d: t1.c * t2.b + t1.d * t2.d, //d
+ tx: t1.tx * t2.a + t1.ty * t2.c + t2.tx, //tx
+ ty: t1.tx * t2.b + t1.ty * t2.d + t2.ty}; //ty
+};
+
+/**
+ * Concatenate a transform matrix to another
+ * The results are reflected in the first matrix.
+ * t' = t1 * t2
+ * @method affineTransformConcatIn
+ * @param {cc.AffineTransform} t1 - The first transform object.
+ * @param {cc.AffineTransform} t2 - The transform object to concatenate.
+ * @return {cc.AffineTransform} The result of concatenation.
+ */
+cc.affineTransformConcatIn = function (t1, t2) {
+ var a = t1.a, b = t1.b, c = t1.c, d = t1.d, tx = t1.tx, ty = t1.ty;
+ t1.a = a * t2.a + b * t2.c;
+ t1.b = a * t2.b + b * t2.d;
+ t1.c = c * t2.a + d * t2.c;
+ t1.d = c * t2.b + d * t2.d;
+ t1.tx = tx * t2.a + ty * t2.c + t2.tx;
+ t1.ty = tx * t2.b + ty * t2.d + t2.ty;
+ return t1;
+};
+
+/**
+ * Return true if an affine transform equals to another, false otherwise.
+ * @method affineTransformEqualToTransform
+ * @param {AffineTransform} t1
+ * @param {AffineTransform} t2
+ * @return {Boolean}
+ */
+cc.affineTransformEqualToTransform = function (t1, t2) {
+ return ((t1.a === t2.a) && (t1.b === t2.b) && (t1.c === t2.c) && (t1.d === t2.d) && (t1.tx === t2.tx) && (t1.ty === t2.ty));
+};
+
+/**
+ * Get the invert transform of an AffineTransform object.
+ * @method affineTransformInvert
+ * @param {AffineTransform} t
+ * @return {AffineTransform} The inverted transform object.
+ */
+cc.affineTransformInvert = function (t) {
+ var determinant = 1 / (t.a * t.d - t.b * t.c);
+ return {a: determinant * t.d, b: -determinant * t.b, c: -determinant * t.c, d: determinant * t.a,
+ tx: determinant * (t.c * t.ty - t.d * t.tx), ty: determinant * (t.b * t.tx - t.a * t.ty)};
+};
diff --git a/cocos2d/core/value-types/CCColor.js b/cocos2d/core/value-types/CCColor.js
new file mode 100644
index 0000000000..51d2102ef8
--- /dev/null
+++ b/cocos2d/core/value-types/CCColor.js
@@ -0,0 +1,491 @@
+var ValueType = require('./CCValueType');
+var JS = require('../platform/js');
+
+var Color = (function () {
+
+ /**
+ * Representation of RGBA colors.
+ *
+ * Each color component is a floating point value with a range from 0 to 1.
+ *
+ * You can also use the convenience method <% crosslink cc.fireColor cc.fireColor %> to create a new Color.
+ *
+ * @class Color
+ * @extends ValueType
+ * @constructor
+ * @param {Number} [r=0] - red component of the color.
+ * @param {Number} [g=0] - green component of the color.
+ * @param {Number} [b=0] - blue component of the color.
+ * @param {Number} [a=255] - alpha component of the color.
+ */
+ function Color( r, g, b, a ) {
+ if (typeof r === 'object') {
+ g = r.g;
+ b = r.b;
+ a = r.a;
+ r = r.r;
+ }
+ this.r = typeof r === 'number' ? r : 0;
+ this.g = typeof g === 'number' ? g : 0;
+ this.b = typeof b === 'number' ? b : 0;
+ this.a = typeof a === 'number' ? a : 255;
+ }
+ JS.extend(Color, ValueType);
+ require('../platform/CCClass').fastDefine('cc.Color', Color, ['r', 'g', 'b', 'a']);
+
+ var DefaultColors = {
+ // color: [r, g, b, a]
+ /**
+ * @property WHITE
+ * @type {Color}
+ * @static
+ */
+ WHITE: [255, 255, 255, 255],
+ /**
+ * @property BLACK
+ * @type {Color}
+ * @static
+ */
+ BLACK: [0, 0, 0, 255],
+ /**
+ * @property TRANSPARENT
+ * @type {Color}
+ * @static
+ */
+ TRANSPARENT:[0, 0, 0, 0],
+ /**
+ * @property GRAY
+ * @type {Color}
+ * @static
+ */
+ GRAY: [127.5, 127.5, 127.5],
+ /**
+ * @property RED
+ * @type {Color}
+ * @static
+ */
+ RED: [255, 0, 0],
+ /**
+ * @property GREEN
+ * @type {Color}
+ * @static
+ */
+ GREEN: [0, 255, 0],
+ /**
+ * @property BLUE
+ * @type {Color}
+ * @static
+ */
+ BLUE: [0, 0, 255],
+ /**
+ * @property YELLOW
+ * @type {Color}
+ * @static
+ */
+ YELLOW: [255, 235, 4],
+ /**
+ * @property ORANGE
+ * @type {Color}
+ * @static
+ */
+ ORANGE: [255, 127, 0],
+ /**
+ * @property CYAN
+ * @type {Color}
+ * @static
+ */
+ CYAN: [0, 255, 255],
+ /**
+ * @property MAGENTA
+ * @type {Color}
+ * @static
+ */
+ MAGENTA: [255, 0, 255]
+ };
+ for (var colorName in DefaultColors) {
+ var colorGetter = (function (r, g, b, a) {
+ return function () {
+ return new Color(r, g, b, a);
+ };
+ }).apply(null, DefaultColors[colorName]);
+ Object.defineProperty(Color, colorName, { get: colorGetter });
+ }
+
+ /**
+ * Clone a new color from the current color.
+ * @method clone
+ * @return {Color} Newly created color.
+ */
+ Color.prototype.clone = function () {
+ return new Color(this.r, this.g, this.b, this.a);
+ };
+
+ /**
+ * @method equals
+ * @param {Color} other
+ * @return {Boolean}
+ */
+ Color.prototype.equals = function (other) {
+ return other &&
+ this.r === other.r &&
+ this.g === other.g &&
+ this.b === other.b &&
+ this.a === other.a;
+ };
+
+ /**
+ * @method lerp
+ * @param {Color} to
+ * @param {number} ratio - the interpolation coefficient.
+ * @param {Color} [out] - optional, the receiving vector.
+ * @return {Color}
+ */
+ Color.prototype.lerp = function (to, ratio, out) {
+ out = out || new Color();
+ var r = this.r;
+ var g = this.g;
+ var b = this.b;
+ var a = this.a;
+ out.r = r + (to.r - r) * ratio;
+ out.g = g + (to.g - g) * ratio;
+ out.b = b + (to.b - b) * ratio;
+ out.a = a + (to.a - a) * ratio;
+ return out;
+ };
+
+ /**
+ * @method toString
+ * @return {String}
+ */
+ Color.prototype.toString = function () {
+ return "rgba(" +
+ this.r.toFixed() + ", " +
+ this.g.toFixed() + ", " +
+ this.b.toFixed() + ", " +
+ this.a.toFixed() + ")"
+ ;
+ };
+
+ /**
+ * @method setR
+ * @param {Number} red - the new Red component.
+ * @return {Color} this color.
+ */
+ Color.prototype.setR = function (red) {
+ this.r = red;
+ return this;
+ };
+ /**
+ * @method setG
+ * @param {Number} green - the new Green component.
+ * @return {Color} this color.
+ */
+ Color.prototype.setG = function (green) {
+ this.g = green;
+ return this;
+ };
+ /**
+ * @method setB
+ * @param {Number} blue - the new Blue component.
+ * @return {Color} this color.
+ */
+ Color.prototype.setB = function (blue) {
+ this.b = blue;
+ return this;
+ };
+ /**
+ * @method setA
+ * @param {Number} alpha - the new Alpha component.
+ * @return {Color} this color.
+ */
+ Color.prototype.setA = function (alpha) {
+ this.a = alpha;
+ return this;
+ };
+
+ /**
+ * @method toCSS
+ * @param {String} opt - "rgba", "rgb", "#rgb" or "#rrggbb".
+ * @return {String}
+ */
+ Color.prototype.toCSS = function ( opt ) {
+ if ( opt === 'rgba' ) {
+ return "rgba(" +
+ (this.r | 0 ) + "," +
+ (this.g | 0 ) + "," +
+ (this.b | 0 ) + "," +
+ (this.a / 255).toFixed(2) + ")"
+ ;
+ }
+ else if ( opt === 'rgb' ) {
+ return "rgb(" +
+ (this.r | 0 ) + "," +
+ (this.g | 0 ) + "," +
+ (this.b | 0 ) + ")"
+ ;
+ }
+ else {
+ return '#' + this.toHEX(opt);
+ }
+ };
+
+ /**
+ * Clamp this color to make all components between 0 to 1.
+ * @method clamp
+ */
+ Color.prototype.clamp = function () {
+ this.r = cc.clampf(this.r, 0, 255);
+ this.g = cc.clampf(this.g, 0, 255);
+ this.b = cc.clampf(this.b, 0, 255);
+ this.a = cc.clampf(this.a, 0, 255);
+ };
+
+ /**
+ * @method fromHEX
+ * @param {String} hexString
+ * @return {Color}
+ * @chainable
+ */
+ Color.prototype.fromHEX = function (hexString) {
+ var hex = parseInt(((hexString.indexOf('#') > -1) ? hexString.substring(1) : hexString), 16);
+ this.r = (hex >> 16);
+ this.g = ((hex & 0x00FF00) >> 8);
+ this.b = ((hex & 0x0000FF));
+ return this;
+ };
+
+ /**
+ * @method toHEX
+ * @param {String} fmt - "#rgb" or "#rrggbb".
+ * @return {String}
+ */
+ Color.prototype.toHEX = function ( fmt ) {
+ var hex = [
+ (this.r | 0 ).toString(16),
+ (this.g | 0 ).toString(16),
+ (this.b | 0 ).toString(16),
+ ];
+ var i = -1;
+ if ( fmt === '#rgb' ) {
+ for ( i = 0; i < hex.length; ++i ) {
+ if ( hex[i].length > 1 ) {
+ hex[i] = hex[i][0];
+ }
+ }
+ }
+ else if ( fmt === '#rrggbb' ) {
+ for ( i = 0; i < hex.length; ++i ) {
+ if ( hex[i].length === 1 ) {
+ hex[i] = '0' + hex[i];
+ }
+ }
+ }
+ return hex.join('');
+ };
+
+ /**
+ * Convert to 24bit rgb value.
+ * @method toRGBValue
+ * @return {Number}
+ */
+ Color.prototype.toRGBValue = function () {
+ return (cc.clampf(this.r, 0, 255) << 16) +
+ (cc.clampf(this.g, 0, 255) << 8) +
+ (cc.clampf(this.b, 0, 255));
+ };
+
+ /**
+ * @method fromHSV
+ * @param {Number} h
+ * @param {Number} s
+ * @param {Number} v
+ * @return {Color}
+ * @chainable
+ */
+ Color.prototype.fromHSV = function ( h, s, v ) {
+ var rgb = Color.hsv2rgb( h, s, v );
+ this.r = rgb.r;
+ this.g = rgb.g;
+ this.b = rgb.b;
+ return this;
+ };
+
+ /**
+ * @method toHSV
+ * @return {Object} - {h: number, s: number, v: number}.
+ */
+ Color.prototype.toHSV = function () {
+ return Color.rgb2hsv( this.r, this.g, this.b );
+ };
+
+ return Color;
+})();
+
+/**
+ * @method rgb2hsv
+ * @param {Number} r - red, must be [0, 255].
+ * @param {Number} g - red, must be [0, 255].
+ * @param {Number} b - red, must be [0, 255].
+ * @return {Object} - {h: number, s: number, v: number}.
+ */
+Color.rgb2hsv = function ( r, g, b ) {
+ r = r / 255;
+ g = g / 255;
+ b = b / 255;
+ var hsv = { h: 0, s: 0, v: 0 };
+ var max = Math.max(r,g,b);
+ var min = Math.min(r,g,b);
+ var delta = 0;
+ hsv.v = max;
+ hsv.s = max ? (max - min) / max : 0;
+ if (!hsv.s) hsv.h = 0;
+ else {
+ delta = max - min;
+ if (r === max) hsv.h = (g - b) / delta;
+ else if (g === max) hsv.h = 2 + (b - r) / delta;
+ else hsv.h = 4 + (r - g) / delta;
+ hsv.h /= 6;
+ if (hsv.h < 0) hsv.h += 1.0;
+ }
+ return hsv;
+};
+
+/**
+ * @method hsv2rgb
+ * @param {Number} h
+ * @param {Number} s
+ * @param {Number} v
+ * @return {Object} - {r: number, g: number, b: number}}, rgb will be in [0, 255].
+ */
+Color.hsv2rgb = function ( h, s, v ) {
+ var rgb = { r: 0, g: 0, b: 0 };
+ if (s === 0) {
+ rgb.r = rgb.g = rgb.b = v;
+ }
+ else {
+ if (v === 0) {
+ rgb.r = rgb.g = rgb.b = 0;
+ }
+ else {
+ if (h === 1) h = 0;
+ h *= 6;
+ s = s;
+ v = v;
+ var i = Math.floor(h);
+ var f = h - i;
+ var p = v * (1 - s);
+ var q = v * (1 - (s * f));
+ var t = v * (1 - (s * (1 - f)));
+ switch (i) {
+ case 0:
+ rgb.r = v;
+ rgb.g = t;
+ rgb.b = p;
+ break;
+
+ case 1:
+ rgb.r = q;
+ rgb.g = v;
+ rgb.b = p;
+ break;
+
+ case 2:
+ rgb.r = p;
+ rgb.g = v;
+ rgb.b = t;
+ break;
+
+ case 3:
+ rgb.r = p;
+ rgb.g = q;
+ rgb.b = v;
+ break;
+
+ case 4:
+ rgb.r = t;
+ rgb.g = p;
+ rgb.b = v;
+ break;
+
+ case 5:
+ rgb.r = v;
+ rgb.g = p;
+ rgb.b = q;
+ break;
+ }
+ }
+ }
+ rgb.r *= 255;
+ rgb.g *= 255;
+ rgb.b *= 255;
+ return rgb;
+};
+
+cc.Color = Color;
+
+/**
+ * The convenience method to create a new <% crosslink cc.Color color %>
+ * Alpha channel is optional. Default value is 255.
+ * @method color
+ * @param {Number} [r=0]
+ * @param {Number} [g=0]
+ * @param {Number} [b=0]
+ * @param {Number} [a=255]
+ * @return {Color}
+ *
+ * @examples {@link utils/api/cocos/docs/cocos2d/core/value-types/CCColor/color.js}
+ */
+cc.color = function color (r, g, b, a) {
+ if (JS.isString(r)) {
+ var result = new cc.Color();
+ return result.fromHEX(r);
+ }
+ if (cc.js.isObject(r)) {
+ return new cc.Color(r.r, r.g, r.b, r.a);
+ }
+ return new cc.Color(r, g, b, a);
+};
+
+
+// Functional style API, for backward compatibility
+
+/**
+ * returns true if both ccColor3B are equal. Otherwise it returns false.
+ * @method colorEqual
+ * @param {Color} color1
+ * @param {Color} color2
+ * @return {Boolean} true if both ccColor3B are equal. Otherwise it returns false.
+ */
+cc.colorEqual = function (color1, color2) {
+ return color1.r === color2.r && color1.g === color2.g && color1.b === color2.b;
+};
+
+/**
+ * convert a string of color for style to Color.
+ * e.g. "#ff06ff" to : cc.color(255,6,255)
+ * @method hexToColor
+ * @param {String} hex
+ * @return {Color}
+ */
+cc.hexToColor = function (hex) {
+ hex = hex.replace(/^#?/, "0x");
+ var c = parseInt(hex);
+ var r = (c >> 16);
+ var g = ((c & 0x00FF00) >> 8);
+ var b = ((c & 0x0000FF));
+ return cc.color(r, g, b);
+};
+
+/**
+ * convert Color to a string of color for style.
+ * e.g. cc.color(255,6,255) to : "#ff06ff"
+ * @method colorToHex
+ * @param {Color} color
+ * @return {String}
+ */
+cc.colorToHex = function (color) {
+ var hR = color.r.toString(16), hG = color.g.toString(16), hB = color.b.toString(16);
+ return "#" + (color.r < 16 ? ("0" + hR) : hR) + (color.g < 16 ? ("0" + hG) : hG) + (color.b < 16 ? ("0" + hB) : hB);
+};
+
+module.exports = cc.Color;
\ No newline at end of file
diff --git a/cocos2d/core/value-types/CCEnum.js b/cocos2d/core/value-types/CCEnum.js
new file mode 100644
index 0000000000..1c1e142c7d
--- /dev/null
+++ b/cocos2d/core/value-types/CCEnum.js
@@ -0,0 +1,132 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+// enum
+
+/**
+ * Define an enum type. If a enum item has a value of -1, it will be given an Integer number according to it's order in the list. Otherwise it will use the value specified by user who writes the enum definition.
+ * @method defineEnum
+ * @param {object} obj - a JavaScript literal object containing enum names and values
+ * @return {object} the defined enum type
+ *
+ * @example
+ Texture.WrapMode = cc.Enum({
+ Repeat: -1,
+ Clamp: -1
+});
+ // Texture.WrapMode.Repeat == 0
+ // Texture.WrapMode.Clamp == 1
+ // Texture.WrapMode[0] == "Repeat"
+ // Texture.WrapMode[1] == "Clamp"
+
+ var FlagType = cc.Enum({
+ Flag1: 1,
+ Flag2: 2,
+ Flag3: 4,
+ Flag4: 8,
+});
+ var AtlasSizeList = cc.Enum({
+ 128: 128,
+ 256: 256,
+ 512: 512,
+ 1024: 1024,
+});
+ */
+
+cc.Enum = function (obj) {
+ var enumType = {};
+ Object.defineProperty(enumType, '__enums__', {
+ value: undefined,
+ writable: true
+ });
+
+ var lastIndex = -1;
+ for (var key in obj) {
+ var val = obj[key];
+ if (val === -1) {
+ val = ++lastIndex;
+ }
+ else {
+ lastIndex = val;
+ }
+ enumType[key] = val;
+
+ var reverseKey = '' + val;
+ if (key !== reverseKey) {
+ Object.defineProperty(enumType, reverseKey, {
+ value: key,
+ enumerable: false
+ });
+ }
+ }
+ return enumType;
+};
+
+cc.Enum.isEnum = function (enumType) {
+ return enumType && enumType.hasOwnProperty('__enums__');
+};
+
+/**
+ * @method getList
+ * @param {Object} enumDef - the enum type defined from cc.Enum
+ * @return {Object[]}
+ * @private
+ */
+cc.Enum.getList = function (enumDef) {
+ if ( enumDef.__enums__ !== undefined )
+ return enumDef.__enums__;
+
+ var enums = [];
+ for ( var entry in enumDef ) {
+ if ( enumDef.hasOwnProperty(entry) ) {
+ var value = enumDef[entry];
+ var isInteger = typeof value === 'number' && (value | 0) === value; // polyfill Number.isInteger
+ if ( isInteger ) {
+ enums.push( { name: entry, value: value } );
+ }
+ }
+ }
+ enums.sort( function ( a, b ) { return a.value - b.value; } );
+
+ enumDef.__enums__ = enums;
+ return enums;
+};
+
+if (CC_DEV) {
+ // check key order in object literal
+ var _TestEnum = cc.Enum({
+ ZERO: -1,
+ ONE: -1,
+ TWO: -1,
+ THREE: -1
+ });
+ if (_TestEnum.ZERO !== 0 || _TestEnum.ONE !== 1 || _TestEnum.TWO !== 2 || _TestEnum.THREE !== 3) {
+ cc.error('Sorry, "cc.Enum" not available on this platform, ' +
+ 'please report this error here: https://github.com/fireball-x/fireball/issues/new');
+ }
+}
+
+module.exports = cc.Enum;
\ No newline at end of file
diff --git a/cocos2d/core/value-types/CCRect.js b/cocos2d/core/value-types/CCRect.js
new file mode 100644
index 0000000000..9089b05f97
--- /dev/null
+++ b/cocos2d/core/value-types/CCRect.js
@@ -0,0 +1,416 @@
+var ValueType = require('./CCValueType');
+var JS = require('../platform/js');
+
+/**
+ * A 2D rectangle defined by x, y position and width, height.
+ *
+ * see {% crosslink cc.Rect cc.rect %}
+ *
+ * @class Rect
+ * @extends ValueType
+ * @constructor
+ * @param {Number} [x=0]
+ * @param {Number} [y=0]
+ * @param {Number} [w=0]
+ * @param {Number} [h=0]
+ */
+function Rect (x, y, w, h) {
+ if (typeof x === 'object') {
+ y = x.y;
+ w = x.width;
+ h = x.height;
+ x = x.x;
+ }
+ this.x = typeof x === 'number' ? x : 0.0;
+ this.y = typeof y === 'number' ? y : 0.0;
+ this.width = typeof w === 'number' ? w : 0.0;
+ this.height = typeof h === 'number' ? h : 0.0;
+}
+JS.extend(Rect, ValueType);
+require('../platform/CCClass').fastDefine('cc.Rect', Rect, ['x', 'y', 'width', 'height']);
+
+/**
+ * Creates a rectangle from two coordinate values.
+ * @static
+ * @method fromMinMax
+ * @param {Vec2} v1
+ * @param {Vec2} v2
+ * @return {Rect}
+ */
+Rect.fromMinMax = function (v1, v2) {
+ var min_x = Math.min(v1.x, v2.x);
+ var min_y = Math.min(v1.y, v2.y);
+ var max_x = Math.max(v1.x, v2.x);
+ var max_y = Math.max(v1.y, v2.y);
+
+ return new Rect(min_x, min_y, max_x - min_x, max_y - min_y);
+};
+
+/**
+ * Checks if rect contains.
+ * @static
+ * @method contain
+ * @param a {Rect} Rect a
+ * @param b {Rect} Rect b
+ * @return {Number} The contains result, 1 is a contains b, -1 is b contains a, 0 is no contains.
+ */
+Rect.contain = function _Contain (a, b) {
+ if (a.x <= b.x &&
+ a.x + a.width >= b.x + b.width &&
+ a.y <= b.y &&
+ a.y + a.height >= b.y + b.height) {
+ // a contains b
+ return 1;
+ }
+ if (b.x <= a.x &&
+ b.x + b.width >= a.x + a.width &&
+ b.y <= a.y &&
+ b.y + b.height >= a.y + a.height) {
+ // b contains a
+ return -1;
+ }
+ return 0;
+};
+
+var proto = Rect.prototype;
+
+/**
+ * @method clone
+ * @return {Rect}
+ */
+proto.clone = function () {
+ return new Rect(this.x, this.y, this.width, this.height);
+};
+
+/**
+ * @method equals
+ * @param {Rect} other
+ * @return {Boolean}
+ */
+proto.equals = function (other) {
+ return other &&
+ this.x === other.x &&
+ this.y === other.y &&
+ this.width === other.width &&
+ this.height === other.height;
+};
+
+/**
+ * @method lerp
+ * @param {Rect} to
+ * @param {Number} ratio - the interpolation coefficient.
+ * @param {Rect} [out] - optional, the receiving vector.
+ * @return {Rect}
+ */
+proto.lerp = function (to, ratio, out) {
+ out = out || new Rect();
+ var x = this.x;
+ var y = this.y;
+ var width = this.width;
+ var height = this.height;
+ out.x = x + (to.x - x) * ratio;
+ out.y = y + (to.y - y) * ratio;
+ out.width = width + (to.width - width) * ratio;
+ out.height = height + (to.height - height) * ratio;
+ return out;
+};
+
+/**
+ * @method toString
+ * @return {String}
+ */
+proto.toString = function () {
+ return '(' + this.x.toFixed(2) + ', ' + this.y.toFixed(2) + ', ' + this.width.toFixed(2) +
+ ', ' + this.height.toFixed(2) + ')';
+};
+
+/**
+ * @property xMin
+ * @type {Number}
+ */
+Object.defineProperty(proto, 'xMin', {
+ get: function () { return this.x; },
+ set: function (value) {
+ this.width += this.x - value;
+ this.x = value;
+ }
+});
+
+/**
+ * @property yMin
+ * @type {Number}
+ */
+Object.defineProperty(proto, 'yMin', {
+ get: function () { return this.y; },
+ set: function (value) {
+ this.height += this.y - value;
+ this.y = value;
+ }
+});
+
+/**
+ * @property xMax
+ * @type {Number}
+ */
+Object.defineProperty(proto, 'xMax', {
+ get: function () { return this.x + this.width; },
+ set: function (value) { this.width = value - this.x; }
+});
+
+/**
+ * @property yMax
+ * @type {Number}
+ */
+Object.defineProperty(proto, 'yMax', {
+ get: function () { return this.y + this.height; },
+ set: function (value) { this.height = value - this.y; }
+});
+
+/**
+ * @property center
+ * @type {Number}
+ */
+Object.defineProperty(proto, 'center', {
+ get: function () {
+ return new cc.Vec2(this.x + this.width * 0.5,
+ this.y + this.height * 0.5);
+ },
+ set: function (value) {
+ this.x = value.x - this.width * 0.5;
+ this.y = value.y - this.height * 0.5;
+ }
+});
+
+/**
+ * @property {Size} size
+ */
+Object.defineProperty(proto, 'size', {
+ get: function () {
+ return new cc.Size(this.width, this.height);
+ },
+ set: function (value) {
+ this.width = value.width;
+ this.height = value.height;
+ }
+});
+
+/**
+ * @method intersects
+ * @param {Rect} rect
+ * @type {Boolean}
+ */
+proto.intersects = function (rect) {
+ return cc.rectIntersectsRect(this, rect);
+};
+
+/**
+ * Returns true if the point inside this rectangle.
+ * @method contains
+ * @param {Vec2} point
+ * @type {Boolean}
+ */
+proto.contains = function (point) {
+ return (this.x <= point.x &&
+ this.x + this.width >= point.x &&
+ this.y <= point.y &&
+ this.y + this.height >= point.y);
+};
+
+/**
+ * Returns true if the other rect totally inside this rectangle.
+ * @method containsRect
+ * @param {Rect} rect
+ * @type {Boolean}
+ */
+proto.containsRect = function (rect) {
+ return (this.x <= rect.x &&
+ this.x + this.width >= rect.x + rect.width &&
+ this.y <= rect.y &&
+ this.y + this.height >= rect.y + rect.height);
+};
+
+cc.Rect = Rect;
+
+
+
+/**
+ * The convenience method to create a new Rect.
+ * @method rect
+ * @param {Number[]|Number} [x=0]
+ * @param {Number} [y=0]
+ * @param {Number} [w=0]
+ * @param {Number} [h=0]
+ * @return {Rect}
+ */
+cc.rect = function rect (x, y, w, h) {
+ return new Rect(x, y, w, h);
+};
+
+
+// Functional style API, for backward compatibility
+
+/**
+ * Check whether a rect's value equals to another.
+ * @method rectEqualToRect
+ * @param {Rect} rect1
+ * @param {Rect} rect2
+ * @return {Boolean}
+ */
+cc.rectEqualToRect = function (rect1, rect2) {
+ return rect1 && rect2 && (rect1.x === rect2.x) && (rect1.y === rect2.y) && (rect1.width === rect2.width) && (rect1.height === rect2.height);
+};
+
+cc._rectEqualToZero = function(rect){
+ return rect && (rect.x === 0) && (rect.y === 0) && (rect.width === 0) && (rect.height === 0);
+};
+
+/**
+ * Check whether the rect1 contains rect2.
+ * @method rectContainsRect
+ * @param {Rect} rect1
+ * @param {Rect} rect2
+ * @return {Boolean}
+ */
+cc.rectContainsRect = function (rect1, rect2) {
+ if (!rect1 || !rect2)
+ return false;
+ return !((rect1.x >= rect2.x) || (rect1.y >= rect2.y) ||
+ ( rect1.x + rect1.width <= rect2.x + rect2.width) ||
+ ( rect1.y + rect1.height <= rect2.y + rect2.height));
+};
+
+/**
+ * Returns the rightmost x-value of a rect.
+ * @method rectGetMaxX
+ * @param {Rect} rect
+ * @return {Number} The rightmost x value.
+ */
+cc.rectGetMaxX = function (rect) {
+ return (rect.x + rect.width);
+};
+
+/**
+ * Return the midpoint x-value of a rect.
+ * @method rectGetMidX
+ * @param {Rect} rect
+ * @return {Number} The midpoint x value.
+ */
+cc.rectGetMidX = function (rect) {
+ return (rect.x + rect.width / 2.0);
+};
+/**
+ * Returns the leftmost x-value of a rect.
+ * @method rectGetMinX
+ * @param {Rect} rect
+ * @return {Number} The leftmost x value.
+ */
+cc.rectGetMinX = function (rect) {
+ return rect.x;
+};
+
+/**
+ * Return the topmost y-value of a rect.
+ * @method rectGetMaxY
+ * @param {Rect} rect
+ * @return {Number} The topmost y value.
+ */
+cc.rectGetMaxY = function (rect) {
+ return(rect.y + rect.height);
+};
+
+/**
+ * Return the midpoint y-value of `rect'.
+ * @method rectGetMidY
+ * @param {Rect} rect
+ * @return {Number} The midpoint y value.
+ */
+cc.rectGetMidY = function (rect) {
+ return rect.y + rect.height / 2.0;
+};
+
+/**
+ * Return the bottommost y-value of a rect.
+ * @method rectGetMinY
+ * @param {Rect} rect
+ * @return {Number} The bottommost y value.
+ */
+cc.rectGetMinY = function (rect) {
+ return rect.y;
+};
+
+/**
+ * Check whether a rect contains a point.
+ * @method rectContainsPoint
+ * @param {Rect} rect
+ * @param {Vec2} point
+ * @return {Boolean}
+ */
+cc.rectContainsPoint = function (rect, point) {
+ return (point.x >= cc.rectGetMinX(rect) && point.x <= cc.rectGetMaxX(rect) &&
+ point.y >= cc.rectGetMinY(rect) && point.y <= cc.rectGetMaxY(rect)) ;
+};
+
+/**
+ * Check whether a rect intersect with another.
+ * @method rectIntersectsRect
+ * @param {Rect} rectA
+ * @param {Rect} rectB
+ * @return {Boolean}
+ */
+cc.rectIntersectsRect = function (ra, rb) {
+ var maxax = ra.x + ra.width,
+ maxay = ra.y + ra.height,
+ maxbx = rb.x + rb.width,
+ maxby = rb.y + rb.height;
+ return !(maxax < rb.x || maxbx < ra.x || maxay < rb.y || maxby < ra.y);
+};
+
+/**
+ * Check whether a rect overlaps another.
+ * @method rectOverlapsRect
+ * @param {Rect} rectA
+ * @param {Rect} rectB
+ * @return {Boolean}
+ */
+cc.rectOverlapsRect = function (rectA, rectB) {
+ return !((rectA.x + rectA.width < rectB.x) ||
+ (rectB.x + rectB.width < rectA.x) ||
+ (rectA.y + rectA.height < rectB.y) ||
+ (rectB.y + rectB.height < rectA.y));
+};
+
+/**
+ * Returns the smallest rectangle that contains the two source rectangles.
+ * @method rectUnion
+ * @param {Rect} rectA
+ * @param {Rect} rectB
+ * @return {Rect}
+ */
+cc.rectUnion = function (rectA, rectB) {
+ var rect = cc.rect(0, 0, 0, 0);
+ rect.x = Math.min(rectA.x, rectB.x);
+ rect.y = Math.min(rectA.y, rectB.y);
+ rect.width = Math.max(rectA.x + rectA.width, rectB.x + rectB.width) - rect.x;
+ rect.height = Math.max(rectA.y + rectA.height, rectB.y + rectB.height) - rect.y;
+ return rect;
+};
+
+/**
+ * Returns the overlapping portion of 2 rectangles.
+ * @method rectUnion
+ * @param {Rect} rectA
+ * @param {Rect} rectB
+ * @return {Rect}
+ */
+cc.rectIntersection = function (rectA, rectB) {
+ var intersection = cc.rect(
+ Math.max(cc.rectGetMinX(rectA), cc.rectGetMinX(rectB)),
+ Math.max(cc.rectGetMinY(rectA), cc.rectGetMinY(rectB)),
+ 0, 0);
+
+ intersection.width = Math.min(cc.rectGetMaxX(rectA), cc.rectGetMaxX(rectB)) - cc.rectGetMinX(intersection);
+ intersection.height = Math.min(cc.rectGetMaxY(rectA), cc.rectGetMaxY(rectB)) - cc.rectGetMinY(intersection);
+ return intersection;
+};
+
+module.exports = cc.Rect;
\ No newline at end of file
diff --git a/cocos2d/core/value-types/CCSize.js b/cocos2d/core/value-types/CCSize.js
new file mode 100644
index 0000000000..fd97f7db1a
--- /dev/null
+++ b/cocos2d/core/value-types/CCSize.js
@@ -0,0 +1,104 @@
+var ValueType = require('./CCValueType');
+var JS = require('../platform/js');
+
+/**
+ * cc.Size is the class for size object, please do not use its constructor to create sizes, use cc.size() alias function instead.
+ * It will be deprecated soon, please use cc.Vec2 instead
+ * @class Size
+ * @param {Number} width
+ * @param {Number} height
+ * @see cc.size
+ */
+function Size (width, height) {
+ if (typeof width === 'object') {
+ height = width.height;
+ width = width.width;
+ }
+ this.width = typeof width === 'number' ? width : 0;
+ this.height = typeof height === 'number' ? height : 0;
+}
+JS.extend(Size, ValueType);
+require('../platform/CCClass').fastDefine('cc.Size', Size, ['width', 'height']);
+
+/**
+ * return a Size object with width = 0 and height = 0.
+ * @property ZERO
+ * @type {Size}
+ * @default new Size(0, 0)
+ * @static
+ */
+JS.get(Size, 'ZERO', function () {
+ return new Size(0.0, 0.0);
+});
+
+var proto = Size.prototype;
+
+/**
+ * @method clone
+ * @return {Size}
+ */
+proto.clone = function () {
+ return new Size(this.width, this.height);
+};
+
+/**
+ * @method equals
+ * @param {Size} other
+ * @return {Boolean}
+ */
+proto.equals = function (other) {
+ return other &&
+ this.width === other.width &&
+ this.height === other.height;
+};
+
+/**
+ * @method lerp
+ * @param {Rect} to
+ * @param {Number} ratio - the interpolation coefficient.
+ * @param {Size} [out] - optional, the receiving vector.
+ * @return {Size}
+ */
+proto.lerp = function (to, ratio, out) {
+ out = out || new Size();
+ var width = this.width;
+ var height = this.height;
+ out.width = width + (to.width - width) * ratio;
+ out.height = height + (to.height - height) * ratio;
+ return out;
+};
+
+/**
+ * @method toString
+ * @return {String}
+ */
+proto.toString = function () {
+ return '(' + this.width.toFixed(2) + ', ' + this.height.toFixed(2) + ')';
+};
+
+/**
+ * Helper function that creates a cc.Size.
+ * Please use cc.p or cc.v2 instead, it will soon replace cc.Size.
+ *
+ * @method size
+ * @param {Number|Size} w - width or a size object
+ * @param {Number} h - height
+ * @return {Size}
+ * @example {@link utils/api/cocos/docs/cocos2d/core/value-types/CCSize/size.js}
+ */
+cc.size = function (w, h) {
+ return new Size(w, h);
+};
+
+/**
+ * Check whether a point's value equals to another.
+ * @method sizeEqualToSize
+ * @param {Size} size1
+ * @param {Size} size2
+ * @return {Boolean}
+ */
+cc.sizeEqualToSize = function (size1, size2) {
+ return (size1 && size2 && (size1.width === size2.width) && (size1.height === size2.height));
+};
+
+cc.Size = module.exports = Size;
diff --git a/cocos2d/core/value-types/CCTypes.js b/cocos2d/core/value-types/CCTypes.js
new file mode 100644
index 0000000000..55bfe5936d
--- /dev/null
+++ b/cocos2d/core/value-types/CCTypes.js
@@ -0,0 +1,282 @@
+/****************************************************************************
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2015 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+/**
+ * the device accelerometer reports values for each axis in units of g-force.
+ * @class Acceleration
+ * @constructor
+ * @param {Number} x
+ * @param {Number} y
+ * @param {Number} z
+ * @param {Number} timestamp
+ */
+cc.Acceleration = function (x, y, z, timestamp) {
+ this.x = x || 0;
+ this.y = y || 0;
+ this.z = z || 0;
+ this.timestamp = timestamp || 0;
+};
+
+/**
+ * Blend Function used for textures.
+ * @Class BlendFunc
+ * @Constructor
+ * @param {Number} src1 source blend function
+ * @param {Number} dst1 destination blend function
+ */
+cc.BlendFunc = function (src1, dst1) {
+ this.src = src1;
+ this.dst = dst1;
+};
+
+cc.BlendFunc._disable = function(){
+ return new cc.BlendFunc(cc.ONE, cc.ZERO);
+};
+cc.BlendFunc._alphaPremultiplied = function(){
+ return new cc.BlendFunc(cc.ONE, cc.ONE_MINUS_SRC_ALPHA);
+};
+cc.BlendFunc._alphaNonPremultiplied = function(){
+ return new cc.BlendFunc(cc.SRC_ALPHA, cc.ONE_MINUS_SRC_ALPHA);
+};
+cc.BlendFunc._additive = function(){
+ return new cc.BlendFunc(cc.SRC_ALPHA, cc.ONE);
+};
+
+/** @expose */
+cc.BlendFunc.DISABLE;
+cc.js.get(cc.BlendFunc, "DISABLE", cc.BlendFunc._disable);
+/** @expose */
+cc.BlendFunc.ALPHA_PREMULTIPLIED;
+cc.js.get(cc.BlendFunc, "ALPHA_PREMULTIPLIED", cc.BlendFunc._alphaPremultiplied);
+/** @expose */
+cc.BlendFunc.ALPHA_NON_PREMULTIPLIED;
+cc.js.get(cc.BlendFunc, "ALPHA_NON_PREMULTIPLIED", cc.BlendFunc._alphaNonPremultiplied);
+/** @expose */
+cc.BlendFunc.ADDITIVE;
+cc.js.get(cc.BlendFunc, "ADDITIVE", cc.BlendFunc._additive);
+
+/**
+ * @method blendFuncDisable
+ * @returns {BlendFunc}
+ */
+cc.blendFuncDisable = function () {
+ return new cc.BlendFunc(cc.ONE, cc.ZERO);
+};
+
+/**
+ * Common usage:
+ *
+ * var fontDef = new cc.FontDefinition();
+ * fontDef.fontName = "Arial";
+ * fontDef.fontSize = 12;
+ * ...
+ *
+ * OR using inline definition usefull for constructor injection
+ *
+ * var fontDef = new cc.FontDefinition({
+ * fontName: "Arial",
+ * fontSize: 12
+ * });
+ *
+ * @class FontDefinition
+ * @param {Object} properties - (OPTIONAL) Allow inline FontDefinition
+ * @constructor
+ */
+cc.FontDefinition = function (properties) {
+ var _t = this;
+ _t.fontName = "Arial";
+ _t.fontSize = 12;
+ _t.textAlign = cc.TextAlignment.CENTER;
+ _t.verticalAlign = cc.VerticalTextAlignment.TOP;
+ _t.fillStyle = cc.color(255, 255, 255, 255);
+ _t.boundingWidth = 0;
+ _t.boundingHeight = 0;
+
+ _t.strokeEnabled = false;
+ _t.strokeStyle = cc.color(255, 255, 255, 255);
+ _t.lineWidth = 1;
+ _t.lineHeight = "normal";
+ _t.fontStyle = "normal";
+ _t.fontWeight = "normal";
+
+ _t.shadowEnabled = false;
+ _t.shadowOffsetX = 0;
+ _t.shadowOffsetY = 0;
+ _t.shadowBlur = 0;
+ _t.shadowOpacity = 1.0;
+
+ //properties mapping:
+ if(properties && properties instanceof Object){
+ for(var key in properties){
+ _t[key] = properties[key];
+ }
+ }
+};
+/**
+ * Web ONLY
+ * */
+cc.FontDefinition.prototype._getCanvasFontStr = function(){
+ var lineHeight = !this.lineHeight.charAt ? this.lineHeight+"px" : this.lineHeight;
+ return this.fontStyle + " " + this.fontWeight + " " + this.fontSize + "px/"+lineHeight+" '" + this.fontName + "'";
+};
+
+/**
+ * Enum for sprite type
+ * @enum SpriteType
+ */
+cc.SpriteType = cc.Enum({
+ /**
+ * @property {Number} SIMPLE
+ */
+ SIMPLE: 0,
+ /**
+ * @property {Number} SLICED
+ */
+ SLICED: 1,
+ ///*
+ // * @property {Number} TILED
+ // */
+ //TILED : 2,
+ ///*
+ // * @property {Number} FILLED
+ // */
+ //FILLED: 3
+});
+
+/**
+ * Enum for text alignment
+ * @enum TextAlignment
+ */
+cc.TextAlignment = cc.Enum({
+ /**
+ * @property {Number} LEFT
+ */
+ LEFT: 0,
+ /**
+ * @property {Number} CENTER
+ */
+ CENTER: 1,
+ /**
+ * @property {Number} RIGHT
+ */
+ RIGHT: 2
+});
+
+/**
+ * Enum for vertical text alignment
+ * @enum VerticalTextAlignment
+ */
+cc.VerticalTextAlignment = cc.Enum({
+ /**
+ * @property {Number} TOP
+ */
+ TOP: 0,
+ /**
+ * @property {Number} CENTER
+ */
+ CENTER: 1,
+ /**
+ * @property {Number} BOTTOM
+ */
+ BOTTOM: 2
+});
+
+cc._Dictionary = cc.Class({
+
+ ctor: function () {
+ this._keyMapTb = {};
+ this._valueMapTb = {};
+ this.__currId = 2 << (0 | (Math.random() * 10));
+ },
+
+ __getKey: function () {
+ this.__currId++;
+ return "key_" + this.__currId;
+ },
+
+ setObject: function (value, key) {
+ if (key == null)
+ return;
+
+ var keyId = this.__getKey();
+ this._keyMapTb[keyId] = key;
+ this._valueMapTb[keyId] = value;
+ },
+
+ objectForKey: function (key) {
+ if (key == null)
+ return null;
+
+ var locKeyMapTb = this._keyMapTb;
+ for (var keyId in locKeyMapTb) {
+ if (locKeyMapTb[keyId] === key)
+ return this._valueMapTb[keyId];
+ }
+ return null;
+ },
+
+ valueForKey: function (key) {
+ return this.objectForKey(key);
+ },
+
+ removeObjectForKey: function (key) {
+ if (key == null)
+ return;
+
+ var locKeyMapTb = this._keyMapTb;
+ for (var keyId in locKeyMapTb) {
+ if (locKeyMapTb[keyId] === key) {
+ delete this._valueMapTb[keyId];
+ delete locKeyMapTb[keyId];
+ return;
+ }
+ }
+ },
+
+ removeObjectsForKeys: function (keys) {
+ if (keys == null)
+ return;
+
+ for (var i = 0; i < keys.length; i++)
+ this.removeObjectForKey(keys[i]);
+ },
+
+ allKeys: function () {
+ var keyArr = [], locKeyMapTb = this._keyMapTb;
+ for (var key in locKeyMapTb)
+ keyArr.push(locKeyMapTb[key]);
+ return keyArr;
+ },
+
+ removeAllObjects: function () {
+ this._keyMapTb = {};
+ this._valueMapTb = {};
+ },
+
+ count: function () {
+ return this.allKeys().length;
+ }
+});
diff --git a/cocos2d/core/value-types/CCTypesWebGL.js b/cocos2d/core/value-types/CCTypesWebGL.js
new file mode 100644
index 0000000000..debcf98c2e
--- /dev/null
+++ b/cocos2d/core/value-types/CCTypesWebGL.js
@@ -0,0 +1,662 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+// define some types with ArrayBuffer for WebGL
+
+/**
+ * @class WebGLColor
+ * @param {Number} r
+ * @param {Number} g
+ * @param {Number} b
+ * @param {Number} a
+ * @param {Array} arrayBuffer
+ * @param {Number} offset
+ * @constructor
+ */
+cc.WebGLColor = function (r, g, b, a, arrayBuffer, offset) {
+ this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.WebGLColor.BYTES_PER_ELEMENT);
+ this._offset = offset || 0;
+
+ var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = Uint8Array.BYTES_PER_ELEMENT;
+ this._rU8 = new Uint8Array(locArrayBuffer, locOffset, 1);
+ this._gU8 = new Uint8Array(locArrayBuffer, locOffset + locElementLen, 1);
+ this._bU8 = new Uint8Array(locArrayBuffer, locOffset + locElementLen * 2, 1);
+ this._aU8 = new Uint8Array(locArrayBuffer, locOffset + locElementLen * 3, 1);
+
+ this._rU8[0] = r || 0;
+ this._gU8[0] = g || 0;
+ this._bU8[0] = b || 0;
+ this._aU8[0] = (a == null) ? 255 : a;
+
+ if (a === undefined)
+ this.a_undefined = true;
+};
+/**
+ * @constant
+ * @type {Number}
+ */
+cc.WebGLColor.BYTES_PER_ELEMENT = 4;
+var _p = cc.WebGLColor.prototype;
+_p._getR = function () {
+ return this._rU8[0];
+};
+_p._setR = function (value) {
+ this._rU8[0] = value < 0 ? 0 : value;
+};
+_p._getG = function () {
+ return this._gU8[0];
+};
+_p._setG = function (value) {
+ this._gU8[0] = value < 0 ? 0 : value;
+};
+_p._getB = function () {
+ return this._bU8[0];
+};
+_p._setB = function (value) {
+ this._bU8[0] = value < 0 ? 0 : value;
+};
+_p._getA = function () {
+ return this._aU8[0];
+};
+_p._setA = function (value) {
+ this._aU8[0] = value < 0 ? 0 : value;
+};
+/** @expose */
+_p.r;
+cc.js.getset(_p, "r", _p._getR, _p._setR);
+/** @expose */
+_p.g;
+cc.js.getset(_p, "g", _p._getG, _p._setG);
+/** @expose */
+_p.b;
+cc.js.getset(_p, "b", _p._getB, _p._setB);
+/** @expose */
+_p.a;
+cc.js.getset(_p, "a", _p._getA, _p._setA);
+
+//redefine cc.Vertex2F
+/**
+ * @class Vertex2F
+ * @param {Number} x
+ * @param {Number}y
+ * @param {Array} arrayBuffer
+ * @param {Number}offset
+ * @constructor
+ */
+cc.Vertex2F = function (x, y, arrayBuffer, offset) {
+ this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.Vertex2F.BYTES_PER_ELEMENT);
+ this._offset = offset || 0;
+
+ this._xF32 = new Float32Array(this._arrayBuffer, this._offset, 1);
+ this._yF32 = new Float32Array(this._arrayBuffer, this._offset + 4, 1);
+ this._xF32[0] = x || 0;
+ this._yF32[0] = y || 0;
+};
+/**
+ * @constant
+ * @type {Number}
+ */
+cc.Vertex2F.BYTES_PER_ELEMENT = 8;
+
+_p = cc.Vertex2F.prototype;
+_p._getX = function () {
+ return this._xF32[0];
+};
+_p._setX = function (xValue) {
+ this._xF32[0] = xValue;
+};
+_p._getY = function () {
+ return this._yF32[0];
+};
+_p._setY = function (yValue) {
+ this._yF32[0] = yValue;
+};
+/** @expose */
+_p.x;
+cc.js.getset(_p, "x", _p._getX, _p._setX);
+/** @expose */
+_p.y;
+cc.js.getset(_p, "y", _p._getY, _p._setY);
+
+// redefine cc.Vertex3F
+/**
+ * @class Vertex3F
+ * @param {Number} x
+ * @param {Number} y
+ * @param {Number}z
+ * @param {Array} arrayBuffer
+ * @param {Number} offset
+ * @constructor
+ */
+cc.Vertex3F = function (x, y, z, arrayBuffer, offset) {
+ this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.Vertex3F.BYTES_PER_ELEMENT);
+ this._offset = offset || 0;
+
+ var locArrayBuffer = this._arrayBuffer, locOffset = this._offset;
+ this._xF32 = new Float32Array(locArrayBuffer, locOffset, 1);
+ this._xF32[0] = x || 0;
+ this._yF32 = new Float32Array(locArrayBuffer, locOffset + Float32Array.BYTES_PER_ELEMENT, 1);
+ this._yF32[0] = y || 0;
+ this._zF32 = new Float32Array(locArrayBuffer, locOffset + Float32Array.BYTES_PER_ELEMENT * 2, 1);
+ this._zF32[0] = z || 0;
+};
+/**
+ * @constant
+ * @type {Number}
+ */
+cc.Vertex3F.BYTES_PER_ELEMENT = 12;
+
+_p = cc.Vertex3F.prototype;
+_p._getX = function () {
+ return this._xF32[0];
+};
+_p._setX = function (xValue) {
+ this._xF32[0] = xValue;
+};
+_p._getY = function () {
+ return this._yF32[0];
+};
+_p._setY = function (yValue) {
+ this._yF32[0] = yValue;
+};
+_p._getZ = function () {
+ return this._zF32[0];
+};
+_p._setZ = function (zValue) {
+ this._zF32[0] = zValue;
+};
+/** @expose */
+_p.x;
+cc.js.getset(_p, "x", _p._getX, _p._setX);
+/** @expose */
+_p.y;
+cc.js.getset(_p, "y", _p._getY, _p._setY);
+/** @expose */
+_p.z;
+cc.js.getset(_p, "z", _p._getZ, _p._setZ);
+
+// redefine cc.Tex2F
+/**
+ * @class Tex2F
+ * @param {Number} u
+ * @param {Number} v
+ * @param {Array} arrayBuffer
+ * @param {Number} offset
+ * @constructor
+ */
+cc.Tex2F = function (u, v, arrayBuffer, offset) {
+ this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.Tex2F.BYTES_PER_ELEMENT);
+ this._offset = offset || 0;
+
+ this._uF32 = new Float32Array(this._arrayBuffer, this._offset, 1);
+ this._vF32 = new Float32Array(this._arrayBuffer, this._offset + 4, 1);
+ this._uF32[0] = u || 0;
+ this._vF32[0] = v || 0;
+};
+/**
+ * @constants
+ * @type {Number}
+ */
+cc.Tex2F.BYTES_PER_ELEMENT = 8;
+
+_p = cc.Tex2F.prototype;
+_p._getU = function () {
+ return this._uF32[0];
+};
+_p._setU = function (xValue) {
+ this._uF32[0] = xValue;
+};
+_p._getV = function () {
+ return this._vF32[0];
+};
+_p._setV = function (yValue) {
+ this._vF32[0] = yValue;
+};
+/** @expose */
+_p.u;
+cc.js.getset(_p, "u", _p._getU, _p._setU);
+/** @expose */
+_p.v;
+cc.js.getset(_p, "v", _p._getV, _p._setV);
+
+//redefine cc.Quad2
+/**
+ * @class Quad2
+ * @param {Vertex2F} tl
+ * @param {Vertex2F} tr
+ * @param {Vertex2F} bl
+ * @param {Vertex2F} br
+ * @param {Array} arrayBuffer
+ * @param {Number} offset
+ * @constructor
+ */
+cc.Quad2 = function (tl, tr, bl, br, arrayBuffer, offset) {
+ this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.Quad2.BYTES_PER_ELEMENT);
+ this._offset = offset || 0;
+
+ var locArrayBuffer = this._arrayBuffer, locElementLen = cc.Vertex2F.BYTES_PER_ELEMENT;
+ this._tl = tl ? new cc.Vertex2F(tl.x, tl.y, locArrayBuffer, 0) : new cc.Vertex2F(0, 0, locArrayBuffer, 0);
+ this._tr = tr ? new cc.Vertex2F(tr.x, tr.y, locArrayBuffer, locElementLen) : new cc.Vertex2F(0, 0, locArrayBuffer, locElementLen);
+ this._bl = bl ? new cc.Vertex2F(bl.x, bl.y, locArrayBuffer, locElementLen * 2) : new cc.Vertex2F(0, 0, locArrayBuffer, locElementLen * 2);
+ this._br = br ? new cc.Vertex2F(br.x, br.y, locArrayBuffer, locElementLen * 3) : new cc.Vertex2F(0, 0, locArrayBuffer, locElementLen * 3);
+};
+/**
+ * @constant
+ * @type {number}
+ */
+cc.Quad2.BYTES_PER_ELEMENT = 32;
+
+_p = cc.Quad2.prototype;
+_p._getTL = function () {
+ return this._tl;
+};
+_p._setTL = function (tlValue) {
+ this._tl.x = tlValue.x;
+ this._tl.y = tlValue.y;
+};
+_p._getTR = function () {
+ return this._tr;
+};
+_p._setTR = function (trValue) {
+ this._tr.x = trValue.x;
+ this._tr.y = trValue.y;
+};
+_p._getBL = function() {
+ return this._bl;
+};
+_p._setBL = function (blValue) {
+ this._bl.x = blValue.x;
+ this._bl.y = blValue.y;
+};
+_p._getBR = function () {
+ return this._br;
+};
+_p._setBR = function (brValue) {
+ this._br.x = brValue.x;
+ this._br.y = brValue.y;
+};
+
+/** @expose */
+_p.tl;
+cc.js.getset(_p, "tl", _p._getTL, _p._setTL);
+/** @expose */
+_p.tr;
+cc.js.getset(_p, "tr", _p._getTR, _p._setTR);
+/** @expose */
+_p.bl;
+cc.js.getset(_p, "bl", _p._getBL, _p._setBL);
+/** @expose */
+_p.br;
+cc.js.getset(_p, "br", _p._getBR, _p._setBR);
+
+/**
+ * A 3D Quad. 4 * 3 floats
+ * @Class Quad3
+ * @Construct
+ * @param {Vertex3F} bl1
+ * @param {Vertex3F} br1
+ * @param {Vertex3F} tl1
+ * @param {Vertex3F} tr1
+ */
+cc.Quad3 = function (bl1, br1, tl1, tr1) {
+ this.bl = bl1 || new cc.Vertex3F(0, 0, 0);
+ this.br = br1 || new cc.Vertex3F(0, 0, 0);
+ this.tl = tl1 || new cc.Vertex3F(0, 0, 0);
+ this.tr = tr1 || new cc.Vertex3F(0, 0, 0);
+};
+
+//redefine cc.V3F_C4B_T2F
+/**
+ * @class V3F_C4B_T2F
+ * @param {Vertex3F} vertices
+ * @param {Color} colors
+ * @param {Tex2F} texCoords
+ * @param {Array} arrayBuffer
+ * @param {Number} offset
+ * @constructor
+ */
+cc.V3F_C4B_T2F = function (vertices, colors, texCoords, arrayBuffer, offset) {
+ this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.V3F_C4B_T2F.BYTES_PER_ELEMENT);
+ this._offset = offset || 0;
+
+ var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = cc.Vertex3F.BYTES_PER_ELEMENT;
+ this._vertices = vertices ? new cc.Vertex3F(vertices.x, vertices.y, vertices.z, locArrayBuffer, locOffset) :
+ new cc.Vertex3F(0, 0, 0, locArrayBuffer, locOffset);
+ this._colors = colors ? new cc.WebGLColor(colors.r, colors.g, colors.b, colors.a, locArrayBuffer, locOffset + locElementLen) :
+ new cc.WebGLColor(0, 0, 0, 0, locArrayBuffer, locOffset + locElementLen);
+ this._texCoords = texCoords ? new cc.Tex2F(texCoords.u, texCoords.v, locArrayBuffer, locOffset + locElementLen + cc.WebGLColor.BYTES_PER_ELEMENT) :
+ new cc.Tex2F(0, 0, locArrayBuffer, locOffset + locElementLen + cc.WebGLColor.BYTES_PER_ELEMENT);
+};
+/**
+ * @constant
+ * @type {Number}
+ */
+cc.V3F_C4B_T2F.BYTES_PER_ELEMENT = 24;
+
+_p = cc.V3F_C4B_T2F.prototype;
+_p._getVertices = function () {
+ return this._vertices;
+};
+_p._setVertices = function (verticesValue) {
+ var locVertices = this._vertices;
+ locVertices.x = verticesValue.x;
+ locVertices.y = verticesValue.y;
+ locVertices.z = verticesValue.z;
+};
+_p._getColor = function () {
+ return this._colors;
+};
+_p._setColor = function (colorValue) {
+ var locColors = this._colors;
+ locColors.r = colorValue.r;
+ locColors.g = colorValue.g;
+ locColors.b = colorValue.b;
+ locColors.a = colorValue.a;
+};
+_p._getTexCoords = function () {
+ return this._texCoords;
+};
+_p._setTexCoords = function (texValue) {
+ this._texCoords.u = texValue.u;
+ this._texCoords.v = texValue.v;
+};
+/** @expose */
+_p.vertices;
+cc.js.getset(_p, "vertices", _p._getVertices, _p._setVertices);
+/** @expose */
+_p.colors;
+cc.js.getset(_p, "colors", _p._getColor, _p._setColor);
+/** @expose */
+_p.texCoords;
+cc.js.getset(_p, "texCoords", _p._getTexCoords, _p._setTexCoords);
+
+//redefine cc.V3F_C4B_T2F_Quad
+/**
+ * @class V3F_C4B_T2F_Quad
+ * @param {V3F_C4B_T2F} tl
+ * @param {V3F_C4B_T2F} bl
+ * @param {V3F_C4B_T2F} tr
+ * @param {V3F_C4B_T2F} br
+ * @param {Array} arrayBuffer
+ * @param {Number} offset
+ * @constructor
+ */
+cc.V3F_C4B_T2F_Quad = function (tl, bl, tr, br, arrayBuffer, offset) {
+ this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT);
+ this._offset = offset || 0;
+
+ var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = cc.V3F_C4B_T2F.BYTES_PER_ELEMENT;
+ this._tl = tl ? new cc.V3F_C4B_T2F(tl.vertices, tl.colors, tl.texCoords, locArrayBuffer, locOffset) :
+ new cc.V3F_C4B_T2F(null, null, null, locArrayBuffer, locOffset);
+ this._bl = bl ? new cc.V3F_C4B_T2F(bl.vertices, bl.colors, bl.texCoords, locArrayBuffer, locOffset + locElementLen) :
+ new cc.V3F_C4B_T2F(null, null, null, locArrayBuffer, locOffset + locElementLen);
+ this._tr = tr ? new cc.V3F_C4B_T2F(tr.vertices, tr.colors, tr.texCoords, locArrayBuffer, locOffset + locElementLen * 2) :
+ new cc.V3F_C4B_T2F(null, null, null, locArrayBuffer, locOffset + locElementLen * 2);
+ this._br = br ? new cc.V3F_C4B_T2F(br.vertices, br.colors, br.texCoords, locArrayBuffer, locOffset + locElementLen * 3) :
+ new cc.V3F_C4B_T2F(null, null, null, locArrayBuffer, locOffset + locElementLen * 3);
+};
+/**
+ * @constant
+ * @type {Number}
+ */
+cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT = 96;
+_p = cc.V3F_C4B_T2F_Quad.prototype;
+_p._getTL = function () {
+ return this._tl;
+};
+_p._setTL = function (tlValue) {
+ var locTl = this._tl;
+ locTl.vertices = tlValue.vertices;
+ locTl.colors = tlValue.colors;
+ locTl.texCoords = tlValue.texCoords;
+};
+_p._getBL = function () {
+ return this._bl;
+};
+_p._setBL = function (blValue) {
+ var locBl = this._bl;
+ locBl.vertices = blValue.vertices;
+ locBl.colors = blValue.colors;
+ locBl.texCoords = blValue.texCoords;
+};
+_p._getTR = function () {
+ return this._tr;
+};
+_p._setTR = function (trValue) {
+ var locTr = this._tr;
+ locTr.vertices = trValue.vertices;
+ locTr.colors = trValue.colors;
+ locTr.texCoords = trValue.texCoords;
+};
+_p._getBR = function () {
+ return this._br;
+};
+_p._setBR = function (brValue) {
+ var locBr = this._br;
+ locBr.vertices = brValue.vertices;
+ locBr.colors = brValue.colors;
+ locBr.texCoords = brValue.texCoords;
+};
+_p._getArrayBuffer = function () {
+ return this._arrayBuffer;
+};
+
+/** @expose */
+_p.tl;
+cc.js.getset(_p, "tl", _p._getTL, _p._setTL);
+/** @expose */
+_p.tr;
+cc.js.getset(_p, "tr", _p._getTR, _p._setTR);
+/** @expose */
+_p.bl;
+cc.js.getset(_p, "bl", _p._getBL, _p._setBL);
+/** @expose */
+_p.br;
+cc.js.getset(_p, "br", _p._getBR, _p._setBR);
+/** @expose */
+_p.arrayBuffer;
+cc.js.get(_p, "arrayBuffer", _p._getArrayBuffer);
+
+/**
+ * @method V3F_C4B_T2F_QuadZero
+ * @returns {V3F_C4B_T2F_Quad}
+ */
+cc.V3F_C4B_T2F_QuadZero = function () {
+ return new cc.V3F_C4B_T2F_Quad();
+};
+
+/**
+ * @method V3F_C4B_T2F_QuadCopy
+ * @param {V3F_C4B_T2F_Quad} sourceQuad
+ * @return {V3F_C4B_T2F_Quad}
+ */
+cc.V3F_C4B_T2F_QuadCopy = function (sourceQuad) {
+ if (!sourceQuad)
+ return cc.V3F_C4B_T2F_QuadZero();
+
+ //return new cc.V3F_C4B_T2F_Quad(sourceQuad,tl,sourceQuad,bl,sourceQuad.tr,sourceQuad.br,null,0);
+ var srcTL = sourceQuad.tl, srcBL = sourceQuad.bl, srcTR = sourceQuad.tr, srcBR = sourceQuad.br;
+ return {
+ tl: {vertices: {x: srcTL.vertices.x, y: srcTL.vertices.y, z: srcTL.vertices.z},
+ colors: {r: srcTL.colors.r, g: srcTL.colors.g, b: srcTL.colors.b, a: srcTL.colors.a},
+ texCoords: {u: srcTL.texCoords.u, v: srcTL.texCoords.v}},
+ bl: {vertices: {x: srcBL.vertices.x, y: srcBL.vertices.y, z: srcBL.vertices.z},
+ colors: {r: srcBL.colors.r, g: srcBL.colors.g, b: srcBL.colors.b, a: srcBL.colors.a},
+ texCoords: {u: srcBL.texCoords.u, v: srcBL.texCoords.v}},
+ tr: {vertices: {x: srcTR.vertices.x, y: srcTR.vertices.y, z: srcTR.vertices.z},
+ colors: {r: srcTR.colors.r, g: srcTR.colors.g, b: srcTR.colors.b, a: srcTR.colors.a},
+ texCoords: {u: srcTR.texCoords.u, v: srcTR.texCoords.v}},
+ br: {vertices: {x: srcBR.vertices.x, y: srcBR.vertices.y, z: srcBR.vertices.z},
+ colors: {r: srcBR.colors.r, g: srcBR.colors.g, b: srcBR.colors.b, a: srcBR.colors.a},
+ texCoords: {u: srcBR.texCoords.u, v: srcBR.texCoords.v}}
+ };
+};
+
+/**
+ * @method V3F_C4B_T2F_QuadsCopy
+ * @param {Array} sourceQuads
+ * @returns {Array}
+ */
+cc.V3F_C4B_T2F_QuadsCopy = function (sourceQuads) {
+ if (!sourceQuads)
+ return [];
+
+ var retArr = [];
+ for (var i = 0; i < sourceQuads.length; i++) {
+ retArr.push(cc.V3F_C4B_T2F_QuadCopy(sourceQuads[i]));
+ }
+ return retArr;
+};
+
+//redefine cc.V2F_C4B_T2F
+/**
+ * @class V2F_C4B_T2F
+ * @param {Vertex2F} vertices
+ * @param {Color} colors
+ * @param {Tex2F} texCoords
+ * @param {Array} arrayBuffer
+ * @param {Number} offset
+ * @constructor
+ */
+cc.V2F_C4B_T2F = function (vertices, colors, texCoords, arrayBuffer, offset) {
+ this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.V2F_C4B_T2F.BYTES_PER_ELEMENT);
+ this._offset = offset || 0;
+
+ var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = cc.Vertex2F.BYTES_PER_ELEMENT;
+ this._vertices = vertices ? new cc.Vertex2F(vertices.x, vertices.y, locArrayBuffer, locOffset) :
+ new cc.Vertex2F(0, 0, locArrayBuffer, locOffset);
+ this._colors = colors ? new cc.WebGLColor(colors.r, colors.g, colors.b, colors.a, locArrayBuffer, locOffset + locElementLen) :
+ new cc.WebGLColor(0, 0, 0, 0, locArrayBuffer, locOffset + locElementLen);
+ this._texCoords = texCoords ? new cc.Tex2F(texCoords.u, texCoords.v, locArrayBuffer, locOffset + locElementLen + cc.WebGLColor.BYTES_PER_ELEMENT) :
+ new cc.Tex2F(0, 0, locArrayBuffer, locOffset + locElementLen + cc.WebGLColor.BYTES_PER_ELEMENT);
+};
+
+/**
+ * @constant
+ * @type {Number}
+ */
+cc.V2F_C4B_T2F.BYTES_PER_ELEMENT = 20;
+_p = cc.V2F_C4B_T2F.prototype;
+_p._getVertices = function () {
+ return this._vertices;
+};
+_p._setVertices = function (verticesValue) {
+ this._vertices.x = verticesValue.x;
+ this._vertices.y = verticesValue.y;
+};
+_p._getColor = function () {
+ return this._colors;
+};
+_p._setColor = function (colorValue) {
+ var locColors = this._colors;
+ locColors.r = colorValue.r;
+ locColors.g = colorValue.g;
+ locColors.b = colorValue.b;
+ locColors.a = colorValue.a;
+};
+_p._getTexCoords = function () {
+ return this._texCoords;
+};
+_p._setTexCoords = function (texValue) {
+ this._texCoords.u = texValue.u;
+ this._texCoords.v = texValue.v;
+};
+
+/** @expose */
+_p.vertices;
+cc.js.getset(_p, "vertices", _p._getVertices, _p._setVertices);
+/** @expose */
+_p.colors;
+cc.js.getset(_p, "colors", _p._getColor, _p._setColor);
+/** @expose */
+_p.texCoords;
+cc.js.getset(_p, "texCoords", _p._getTexCoords, _p._setTexCoords);
+
+//redefine cc.V2F_C4B_T2F_Triangle
+/**
+ * @class V2F_C4B_T2F_Triangle
+ * @param {V2F_C4B_T2F} a
+ * @param {V2F_C4B_T2F} b
+ * @param {V2F_C4B_T2F} c
+ * @param {Array} arrayBuffer
+ * @param {Number} offset
+ * @constructor
+ */
+cc.V2F_C4B_T2F_Triangle = function (a, b, c, arrayBuffer, offset) {
+ this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT);
+ this._offset = offset || 0;
+
+ var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = cc.V2F_C4B_T2F.BYTES_PER_ELEMENT;
+ this._a = a ? new cc.V2F_C4B_T2F(a.vertices, a.colors, a.texCoords, locArrayBuffer, locOffset) :
+ new cc.V2F_C4B_T2F(null, null, null, locArrayBuffer, locOffset);
+ this._b = b ? new cc.V2F_C4B_T2F(b.vertices, b.colors, b.texCoords, locArrayBuffer, locOffset + locElementLen) :
+ new cc.V2F_C4B_T2F(null, null, null, locArrayBuffer, locOffset + locElementLen);
+ this._c = c ? new cc.V2F_C4B_T2F(c.vertices, c.colors, c.texCoords, locArrayBuffer, locOffset + locElementLen * 2) :
+ new cc.V2F_C4B_T2F(null, null, null, locArrayBuffer, locOffset + locElementLen * 2);
+};
+/**
+ * @constant
+ * @type {Number}
+ */
+cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT = 60;
+_p = cc.V2F_C4B_T2F_Triangle.prototype;
+_p._getA = function () {
+ return this._a;
+};
+_p._setA = function (aValue) {
+ var locA = this._a;
+ locA.vertices = aValue.vertices;
+ locA.colors = aValue.colors;
+ locA.texCoords = aValue.texCoords;
+};
+_p._getB = function () {
+ return this._b;
+};
+_p._setB = function (bValue) {
+ var locB = this._b;
+ locB.vertices = bValue.vertices;
+ locB.colors = bValue.colors;
+ locB.texCoords = bValue.texCoords;
+};
+_p._getC = function () {
+ return this._c;
+};
+_p._setC = function (cValue) {
+ var locC = this._c;
+ locC.vertices = cValue.vertices;
+ locC.colors = cValue.colors;
+ locC.texCoords = cValue.texCoords;
+};
+
+/** @expose */
+_p.a;
+cc.js.getset(_p, "a", _p._getA, _p._setA);
+/** @expose */
+_p.b;
+cc.js.getset(_p, "b", _p._getB, _p._setB);
+/** @expose */
+_p.c;
+cc.js.getset(_p, "c", _p._getC, _p._setC);
\ No newline at end of file
diff --git a/cocos2d/core/value-types/CCValueType.js b/cocos2d/core/value-types/CCValueType.js
new file mode 100644
index 0000000000..bfabfff944
--- /dev/null
+++ b/cocos2d/core/value-types/CCValueType.js
@@ -0,0 +1,57 @@
+var JS = require('../platform/js');
+
+/**
+ * The base class of all value types.
+ * @class ValueType
+ * @constructor
+ */
+function ValueType () {}
+JS.setClassName('cc.ValueType', ValueType);
+
+JS.mixin(ValueType.prototype, {
+ /**
+ * !#en This method returns an exact copy of current value.
+ * !#zh ć
éćœććŒïŒèŻ„æčæłèżćäžäžȘæ°ćŻčè±ĄïŒæ°ćŻčè±ĄçćŒćććŻčè±Ąçžçă
+ * @method clone
+ * @return {ValueType}
+ */
+ clone: CC_EDITOR && function () {
+ cc.error("%.clone not yet implemented.", JS.getClassName(this));
+ return null;
+ },
+
+ /**
+ * Compares this object with the other one.
+ * @method equals
+ * @param {ValueType} other
+ * @return {Boolean}
+ */
+ equals: CC_EDITOR && function (other) {
+ cc.error("%.equals not yet implemented.", JS.getClassName(this));
+ return false;
+ },
+
+ /**
+ * @method toString
+ * @return {string}
+ */
+ toString: function () {
+ return '' + {};
+ },
+
+ /**
+ * Linearly interpolates between this value to to value by ratio which is in the range [0, 1].
+ * When ratio = 0 returns this. When ratio = 1 return to. When ratio = 0.5 returns the average of this and to.
+ * @method lerp
+ * @param {ValueType} to - the to value
+ * @param {number} ratio - the interpolation coefficient
+ * @return {ValueType}
+ */
+ lerp: CC_EDITOR && function (to, ratio) {
+ cc.warn("%.lerp not yet implemented.", JS.getClassName(this));
+ return this.clone();
+ }
+});
+
+cc.ValueType = ValueType;
+module.exports = ValueType;
diff --git a/cocos2d/core/value-types/CCVec2.js b/cocos2d/core/value-types/CCVec2.js
new file mode 100644
index 0000000000..750a887748
--- /dev/null
+++ b/cocos2d/core/value-types/CCVec2.js
@@ -0,0 +1,483 @@
+var ValueType = require('./CCValueType');
+var JS = require('../platform/js');
+var FireClass = require('../platform/CCClass');
+
+/**
+ * Representation of 2D vectors and points.
+ *
+ * see {% crosslink cc.Vec2 cc.v2 %}
+ * @class Vec2
+ * @extends ValueType
+ * @constructor
+ * @param {number} [x=0]
+ * @param {number} [y=0]
+ */
+function Vec2 (x, y) {
+ if (typeof x === 'object') {
+ y = x.y;
+ x = x.x;
+ }
+ this.x = (typeof x === 'number' ? x : 0.0);
+ this.y = (typeof y === 'number' ? y : 0.0);
+}
+JS.extend(Vec2, ValueType);
+FireClass.fastDefine('cc.Vec2', Vec2, ['x', 'y']);
+
+JS.mixin(Vec2.prototype, {
+
+ /**
+ * !#en clone a Vec2 value
+ * !#zh ć
éäžäžȘ Vec2 ćŒ
+ * @method clone
+ * @return {Vec2}
+ */
+ clone: function () {
+ return new Vec2(this.x, this.y);
+ },
+
+ /**
+ * @method set
+ * @param {Vec2} newValue - !#en new value to set. !#zh èŠèźŸçœźçæ°ćŒ
+ * @return {Vec2} returns this
+ * @chainable
+ */
+ set: function (newValue) {
+ this.x = newValue.x;
+ this.y = newValue.y;
+ return this;
+ },
+
+ /**
+ * @method equals
+ * @param {Vec2} other
+ * @return {Boolean}
+ */
+ equals: function (other) {
+ return other && this.x === other.x && this.y === other.y;
+ },
+
+ /**
+ * @method toString
+ * @return {string}
+ */
+ toString: function () {
+ return "(" +
+ this.x.toFixed(2) + ", " +
+ this.y.toFixed(2) + ")"
+ ;
+ },
+
+ /**
+ * @method lerp
+ * @param {Vec2} to
+ * @param {number} ratio - the interpolation coefficient
+ * @param {Vec2} [out] - optional, the receiving vector
+ * @return {Vec2}
+ */
+ lerp: function (to, ratio, out) {
+ out = out || new Vec2();
+ var x = this.x;
+ var y = this.y;
+ out.x = x + (to.x - x) * ratio;
+ out.y = y + (to.y - y) * ratio;
+ return out;
+ },
+
+ /**
+ * Adds this vector. If you want to save result to another vector, use add() instead.
+ * @method addSelf
+ * @param {Vec2} vector
+ * @return {Vec2} returns this
+ * @chainable
+ */
+ addSelf: function (vector) {
+ this.x += vector.x;
+ this.y += vector.y;
+ return this;
+ },
+
+ /**
+ * Adds two vectors, and returns the new result.
+ * @method add
+ * @param {Vec2} vector
+ * @param {Vec2} [out] - optional, the receiving vector
+ * @return {Vec2} the result
+ */
+ add: function (vector, out) {
+ out = out || new Vec2();
+ out.x = this.x + vector.x;
+ out.y = this.y + vector.y;
+ return out;
+ },
+
+ /**
+ * Subtracts one vector from this. If you want to save result to another vector, use sub() instead.
+ * @method subSelf
+ * @param {Vec2} vector
+ * @return {Vec2} returns this
+ * @chainable
+ */
+ subSelf: function (vector) {
+ this.x -= vector.x;
+ this.y -= vector.y;
+ return this;
+ },
+
+ /**
+ * Subtracts one vector from this, and returns the new result.
+ * @method sub
+ * @param {Vec2} vector
+ * @param {Vec2} [out] - optional, the receiving vector
+ * @return {Vec2} the result
+ */
+ sub: function (vector, out) {
+ out = out || new Vec2();
+ out.x = this.x - vector.x;
+ out.y = this.y - vector.y;
+ return out;
+ },
+
+ /**
+ * Multiplies this by a number. If you want to save result to another vector, use mul() instead.
+ * @method mulSelf
+ * @param {number} num
+ * @return {Vec2} returns this
+ * @chainable
+ */
+ mulSelf: function (num) {
+ this.x *= num;
+ this.y *= num;
+ return this;
+ },
+
+ /**
+ * Multiplies by a number, and returns the new result.
+ * @method mul
+ * @param {number} num
+ * @param {Vec2} [out] - optional, the receiving vector
+ * @return {Vec2} the result
+ */
+ mul: function (num, out) {
+ out = out || new Vec2();
+ out.x = this.x * num;
+ out.y = this.y * num;
+ return out;
+ },
+
+ /**
+ * Multiplies two vectors.
+ * @method scaleSelf
+ * @param {Vec2} vector
+ * @return {Vec2} returns this
+ * @chainable
+ */
+ scaleSelf: function (vector) {
+ this.x *= vector.x;
+ this.y *= vector.y;
+ return this;
+ },
+
+ /**
+ * Multiplies two vectors, and returns the new result.
+ * @method scale
+ * @param {Vec2} vector
+ * @param {Vec2} [out] - optional, the receiving vector
+ * @return {Vec2} the result
+ */
+ scale: function (vector, out) {
+ out = out || new Vec2();
+ out.x = this.x * vector.x;
+ out.y = this.y * vector.y;
+ return out;
+ },
+
+ /**
+ * Divides by a number. If you want to save result to another vector, use div() instead.
+ * @method divSelf
+ * @param {Vec2} vector
+ * @return {Vec2} returns this
+ * @chainable
+ */
+ divSelf: function (num) {
+ this.x /= num;
+ this.y /= num;
+ return this;
+ },
+
+ /**
+ * Divides by a number, and returns the new result.
+ * @method div
+ * @param {Vec2} vector
+ * @param {Vec2} [out] - optional, the receiving vector
+ * @return {Vec2} the result
+ */
+ div: function (num, out) {
+ out = out || new Vec2();
+ out.x = this.x / num;
+ out.y = this.y / num;
+ return out;
+ },
+
+ /**
+ * Negates the components. If you want to save result to another vector, use neg() instead.
+ * @method negSelf
+ * @return {Vec2} returns this
+ * @chainable
+ */
+ negSelf: function () {
+ this.x = -this.x;
+ this.y = -this.y;
+ return this;
+ },
+
+ /**
+ * Negates the components, and returns the new result.
+ * @method neg
+ * @param {Vec2} [out] - optional, the receiving vector
+ * @return {Vec2} the result
+ */
+ neg: function (out) {
+ out = out || new Vec2();
+ out.x = -this.x;
+ out.y = -this.y;
+ return out;
+ },
+
+ /**
+ * Dot product
+ * @method dot
+ * @param {Vec2} [vector]
+ * @return {number} the result
+ */
+ dot: function (vector) {
+ return this.x * vector.x + this.y * vector.y;
+ },
+
+ /**
+ * Cross product
+ * @method cross
+ * @param {Vec2} [vector]
+ * @return {number} the result
+ */
+ cross: function (vector) {
+ return this.y * vector.x - this.x * vector.y;
+ },
+
+ /**
+ * Returns the length of this vector.
+ * @method mag
+ * @return {number} the result
+ */
+ mag: function () {
+ return Math.sqrt(this.x * this.x + this.y * this.y);
+ },
+
+ /**
+ * Returns the squared length of this vector.
+ * @method magSqr
+ * @return {number} the result
+ */
+ magSqr: function () {
+ return this.x * this.x + this.y * this.y;
+ },
+
+ /**
+ * Make the length of this vector to 1.
+ * @method normalizeSelf
+ * @return {Vec2} returns this
+ * @chainable
+ */
+ normalizeSelf: function () {
+ var magSqr = this.x * this.x + this.y * this.y;
+ if (magSqr === 1.0)
+ return this;
+
+ if (magSqr === 0.0) {
+ console.warn("Can't normalize zero vector");
+ return this;
+ }
+
+ var invsqrt = 1.0 / Math.sqrt(magSqr);
+ this.x *= invsqrt;
+ this.y *= invsqrt;
+
+ return this;
+ },
+
+ /**
+ * Returns this vector with a magnitude of 1.
+ *
+ * Note that the current vector is unchanged and a new normalized vector is returned. If you want to normalize the current vector, use normalizeSelf function.
+ * @method normalize
+ * @param {Vec2} [out] - optional, the receiving vector
+ * @return {Vec2} result
+ */
+ normalize: function (out) {
+ out = out || new Vec2();
+ out.x = this.x;
+ out.y = this.y;
+ out.normalizeSelf();
+ return out;
+ },
+
+ /**
+ * Get angle in radian between this and vector
+ * @method angle
+ * @param {Vec2} vector
+ * @return {number} from 0 to Math.PI
+ */
+ angle: function (vector) {
+ var magSqr1 = this.magSqr();
+ var magSqr2 = vector.magSqr();
+
+ if (magSqr1 === 0 || magSqr2 === 0) {
+ console.warn("Can't get angle between zero vector");
+ return 0.0;
+ }
+
+ var dot = this.dot(vector);
+ var theta = dot / (Math.sqrt(magSqr1 * magSqr2));
+ theta = cc.clampf(theta, -1.0, 1.0);
+ return Math.acos(theta);
+ },
+
+ /**
+ * Get angle in radian between this and vector with direction
+ * @method signAngle
+ * @param {Vec2} vector
+ * @return {number} from -MathPI to Math.PI
+ */
+ signAngle: function (vector) {
+ // NOTE: this algorithm will return 0.0 without signed if vectors are parallex
+ // var angle = this.angle(vector);
+ // var cross = this.cross(vector);
+ // return Math.sign(cross) * angle;
+
+ return Math.atan2(this.y, this.x) - Math.atan2(vector.y, vector.x);
+ },
+
+ /**
+ * rotate
+ * @method rotate
+ * @param {number} radians
+ * @param {Vec2} [out] - optional, the receiving vector
+ * @return {Vec2} the result
+ */
+ rotate: function (radians, out) {
+ out = out || new Vec2();
+ out.x = this.x;
+ out.y = this.y;
+ return out.rotateSelf(radians);
+ },
+
+ /**
+ * rotate self
+ * @method rotateSelf
+ * @param {number} radians
+ * @return {Vec2} returns this
+ * @chainable
+ */
+ rotateSelf: function (radians) {
+ var sin = Math.sin(radians);
+ var cos = Math.cos(radians);
+ var x = this.x;
+ this.x = cos * x - sin * this.y;
+ this.y = sin * x + cos * this.y;
+ return this;
+ }
+
+ //_serialize: function () {
+ // return [this.x, this.y];
+ //},
+ //_deserialize: function (data) {
+ // this.x = data[0];
+ // this.y = data[1];
+ //}
+});
+
+// static
+
+/**
+ * return a Vec2 object with x = 1 and y = 1
+ * @property ONE
+ * @type Vec2
+ * @static
+ */
+JS.get(Vec2, 'ONE', function () {
+ return new Vec2(1.0, 1.0);
+});
+
+/**
+ * return a Vec2 object with x = 0 and y = 0
+ * @property ZERO
+ * @type Vec2
+ * @static
+ */
+JS.get(Vec2, 'ZERO', function () {
+ return new Vec2(0.0, 0.0);
+});
+
+/**
+ * return a Vec2 object with x = 0 and y = 1
+ * @property up
+ * @type Vec2
+ * @static
+ */
+JS.get(Vec2, 'UP', function () {
+ return new Vec2(0.0, 1.0);
+});
+
+/**
+ * return a Vec2 object with x = 1 and y = 0
+ * @property RIGHT
+ * @type Vec2
+ * @static
+ */
+JS.get(Vec2, 'RIGHT', function () {
+ return new Vec2(1.0, 0.0);
+});
+
+cc.Vec2 = Vec2;
+var proto = Vec2.prototype;
+
+
+/**
+ * The convenience method to create a new {% crosslink Vec2 Vec2 %}
+ * @method v2
+ * @param {Number|Object} [x=0]
+ * @param {Number} [y=0]
+ * @return {Vec2}
+ */
+cc.v2 = function v2 (x, y) {
+ return new Vec2(x, y);
+};
+
+/**
+ * Helper function that creates a cc.Vec2.
+ * @function
+ * @param {Number|Object} [x=0] a Number or a size object
+ * @param {Number} [y=0]
+ * @return {cc.Vec2}
+ * @example
+ * var point1 = cc.p();
+ * var point2 = cc.p(100, 100);
+ * var point3 = cc.p(point2);
+ * var point4 = cc.p({x: 100, y: 100});
+ */
+cc.p = cc.v2;
+
+
+// Functional style API, for backward compatibility
+
+/**
+ * Check whether a point's value equals to another
+ * @function
+ * @param {cc.Vec2} point1
+ * @param {cc.Vec2} point2
+ * @return {Boolean}
+ */
+cc.pointEqualToPoint = function (point1, point2) {
+ return point1 && point2 && (point1.x === point2.x) && (point1.y === point2.y);
+};
+
+module.exports = cc.Vec2;
\ No newline at end of file
diff --git a/cocos2d/core/value-types/index.js b/cocos2d/core/value-types/index.js
new file mode 100644
index 0000000000..12f0c3ff26
--- /dev/null
+++ b/cocos2d/core/value-types/index.js
@@ -0,0 +1,9 @@
+require('./CCValueType');
+require('./CCEnum');
+require('./CCVec2');
+require('./CCSize');
+require('./CCRect');
+require('./CCColor');
+require('./CCTypes');
+require('./CCAffineTransform')
+require('./CCTypesWebGL');
\ No newline at end of file
diff --git a/cocos2d/deprecated.js b/cocos2d/deprecated.js
new file mode 100644
index 0000000000..d85d39a106
--- /dev/null
+++ b/cocos2d/deprecated.js
@@ -0,0 +1,503 @@
+if (CC_DEV) {
+ var js = cc.js;
+
+ var INFO = cc._LogInfos.deprecated;
+
+ /**
+ * Inject all of the properties in source objects to target object and return the target object.
+ * @param {object} target
+ * @param {object} *sources
+ * @name cc.inject
+ * @memberof cc
+ * @deprecated
+ * @returns {object}
+ */
+ js.get(cc, "inject", function () {
+ cc.warn(INFO + " The first argument should be the destination object", 'cc.inject', 'cc.js.addon');
+ return js.addon;
+ });
+
+ /**
+ * Copy all of the properties in source objects to target object and return the target object.
+ * @param {object} target
+ * @param {object} *sources
+ * @name cc.extend
+ * @memberof cc
+ * @deprecated
+ * @returns {object}
+ */
+ js.get(cc, "extend", function () {
+ cc.warn(INFO, 'cc.extend', 'cc.js.mixin');
+ return js.mixin;
+ });
+
+ /**
+ * Create new DOM element by tag name
+ * @name cc.newElement
+ * @memberof cc
+ * @deprecated
+ * @returns {object}
+ */
+ js.get(cc, "newElement", function () {
+ cc.warn(INFO, 'cc.newElement', 'document.createElement');
+ return document.createElement;
+ });
+
+ /**
+ * Check the obj whether is function or not
+ * @name cc.isFunction
+ * @memberof cc
+ * @deprecated
+ * @param {*} obj
+ * @returns {boolean}
+ */
+ js.get(cc, "isFunction", function () {
+ cc.warn(INFO, 'cc.isFunction', 'cc.js.isFunction');
+ return js.isFunction;
+ });
+
+ /**
+ * Check the obj whether is number or not
+ * @name cc.isNumber
+ * @memberof cc
+ * @deprecated
+ * @param {*} obj
+ * @returns {boolean}
+ */
+ js.get(cc, "isNumber", function () {
+ cc.warn(INFO, 'cc.isNumber', 'cc.js.isNumber');
+ return js.isNumber;
+ });
+
+ /**
+ * Check the obj whether is string or not
+ * @name cc.isString
+ * @memberof cc
+ * @deprecated
+ * @param {*} obj
+ * @returns {boolean}
+ */
+ js.get(cc, "isString", function () {
+ cc.warn(INFO, 'cc.isString', 'cc.js.isString');
+ return js.isString;
+ });
+
+ /**
+ * Check the obj whether is array or not
+ * @name cc.isArray
+ * @memberof cc
+ * @deprecated
+ * @param {*} obj
+ * @returns {boolean}
+ */
+ js.get(cc, "isArray", function () {
+ cc.warn(INFO, 'cc.isArray', 'cc.js.isArray');
+ return js.isArray;
+ });
+
+ /**
+ * Check the obj whether is undefined or not
+ * @name cc.isUndefined
+ * @memberof cc
+ * @deprecated
+ * @param {*} obj
+ * @returns {boolean}
+ */
+ js.get(cc, "isUndefined", function () {
+ cc.warn(INFO, 'cc.isUndefined', 'cc.js.isUndefined');
+ return js.isUndefined;
+ });
+
+ /**
+ * Check the obj whether is object or not
+ * @name cc.isObject
+ * @memberof cc
+ * @deprecated
+ * @param {*} obj
+ * @returns {boolean}
+ */
+ js.get(cc, "isObject", function () {
+ cc.warn(INFO, 'cc.isObject', 'cc.js.isObject');
+ return js.isObject;
+ });
+
+ /**
+ * cc.Point is the class for point object, please do not use its constructor to create points, use cc.p() alias function instead.
+ * @class cc.Point
+ * @memberof cc
+ * @deprecated
+ * @param {Number} x
+ * @param {Number} y
+ * @see cc.Vec2
+ */
+ js.obsoletes(cc, 'cc', {
+ "Point": 'Vec2'
+ });
+
+ /**
+ * Verify Array's Type
+ * @memberof cc
+ * @deprecated
+ * @param {Array} arr
+ * @param {function} type
+ * @return {Boolean}
+ * @function
+ */
+ js.get(cc, 'arrayVerifyType', function () {
+ cc.warn(INFO, 'cc.arrayVerifyType', 'cc.js.array.verifyType');
+ return cc.js.array.verifyType;
+ });
+
+ /**
+ * Searches for the first occurance of object and removes it. If object is not found the function has no effect.
+ * @function
+ * @memberof cc
+ * @deprecated
+ * @param {Array} arr Source Array
+ * @param {*} delObj remove object
+ */
+ js.get(cc, 'arrayRemoveObject', function () {
+ cc.warn(INFO, 'cc.arrayRemoveObject', 'cc.js.array.remove');
+ return cc.js.array.remove;
+ });
+
+ /**
+ * Removes from arr all values in minusArr. For each Value in minusArr, the first matching instance in arr will be removed.
+ * @function
+ * @memberof cc
+ * @deprecated
+ * @param {Array} arr Source Array
+ * @param {Array} minusArr minus Array
+ */
+ js.get(cc, 'arrayRemoveArray', function () {
+ cc.warn(INFO, 'cc.arrayRemoveArray', 'cc.js.array.removeArray');
+ return cc.js.array.removeArray;
+ });
+
+ /**
+ * Inserts some objects at index
+ * @function
+ * @memberof cc
+ * @deprecated
+ * @param {Array} arr
+ * @param {Array} addObjs
+ * @param {Number} index
+ * @return {Array}
+ */
+ js.get(cc, 'arrayAppendObjectsToIndex', function() {
+ cc.warn(INFO, 'cc.arrayAppendObjectsToIndex', 'cc.js.array.appendObjectsAt');
+ return cc.js.array.appendObjectsAt;
+ });
+
+ /**
+ * Copy an array's item to a new array (its performance is better than Array.slice)
+ * @memberof cc
+ * @deprecated
+ * @param {Array} arr
+ * @return {Array}
+ */
+ js.get(cc, 'copyArray', function() {
+ cc.warn(INFO, 'cc.copyArray', 'cc.js.array.copy');
+ return cc.js.array.copy;
+ });
+
+ function deprecateEnum (obj, oldPath, newPath, hasTypePrefixBefore) {
+ hasTypePrefixBefore = hasTypePrefixBefore !== false;
+ var enumDef = eval(newPath);
+ var entries = cc.Enum.getList(enumDef);
+ var delimiter = hasTypePrefixBefore ? '_' : '.';
+ for (var i = 0; i < entries.length; i++) {
+ var entry = entries[i].name;
+ var oldPropName;
+ if (hasTypePrefixBefore) {
+ var oldTypeName = oldPath.split('.').slice(-1)[0];
+ oldPropName = oldTypeName + '_' + entry;
+ }
+ else {
+ oldPropName = entry;
+ }
+ js.get(obj, oldPropName, function (entry) {
+ cc.warn(INFO, oldPath + delimiter + entry, newPath + '.' + entry);
+ return enumDef[entry];
+ }.bind(null, entry));
+ }
+ }
+
+ deprecateEnum(cc, 'cc.TEXT_ALIGNMENT', 'cc.TextAlignment');
+ deprecateEnum(cc, 'cc.VERTICAL_TEXT_ALIGNMENT', 'cc.VerticalTextAlignment');
+ deprecateEnum(cc.ParticleSystem, 'cc.ParticleSystem.TYPE', 'cc.ParticleSystem.Type');
+ deprecateEnum(cc.ParticleSystem, 'cc.ParticleSystem.MODE', 'cc.ParticleSystem.Mode');
+ deprecateEnum(cc.EParticleSystem, 'cc.EParticleSystem.TYPE', 'cc.EParticleSystem.PositionType');
+ deprecateEnum(cc.EParticleSystem, 'cc.EParticleSystem.MODE', 'cc.EParticleSystem.EmitterMode');
+ deprecateEnum(ccui.ScrollView, 'ccui.ScrollView.DIR', 'ccui.ScrollView.Dir');
+ deprecateEnum(ccui.ScrollView, 'ccui.ScrollView.EVENT', 'ccui.ScrollView.Event');
+ deprecateEnum(ccui.Layout, 'ccui.Layout', 'ccui.Layout.Type', false);
+ deprecateEnum(ccui.LoadingBar, 'ccui.LoadingBar.TYPE', 'ccui.LoadingBar.Type');
+ deprecateEnum(ccui.RelativeLayoutParameter, 'ccui.RelativeLayoutParameter', 'ccui.RelativeLayoutParameter.Type', false);
+ deprecateEnum(cc.ProgressTimer, 'cc.ProgressTimer.TYPE', 'cc.ProgressTimer.Type');
+ deprecateEnum(cc.game, 'cc.game.DEBUG_MODE', 'cc.DebugMode');
+ if (cc.EditBox) {
+ deprecateEnum(cc, 'cc.KEYBOARD_RETURNTYPE', 'cc.KeyboardReturnType');
+ deprecateEnum(cc, 'cc.EDITBOX_INPUT_MODE', 'cc.EditBox.InputMode');
+ deprecateEnum(cc, 'cc.EDITBOX_INPUT_FLAG', 'cc.EditBox.InputFlag');
+ }
+ cc.game.once(cc.game.EVENT_RENDERER_INITED, function () {
+ deprecateEnum(cc, 'cc', 'cc.Texture2D.WrapMode', false);
+ });
+
+ function markAsRemoved (ownerCtor, removedProps, ownerName) {
+ ownerName = ownerName || js.getClassName(ownerCtor);
+ removedProps.forEach(function (prop) {
+ function error () {
+ cc.error('Sorry, %s.%s is removed.', ownerName, prop);
+ }
+ js.getset(ownerCtor.prototype, prop, error, error);
+ });
+ }
+
+ function provideClearError (owner, obj) {
+ var className = cc.js.getClassName(owner);
+ var Info = 'Sorry,' + className + '.%s is removed, please use %s instead.';
+ for (var prop in obj) {
+ function define (prop, getset) {
+ function accessor (newProp) {
+ cc.error(Info, prop, newProp);
+ }
+ if (!Array.isArray(getset)) {
+ getset = getset.split(',')
+ .map(function (x) {
+ return x.trim();
+ });
+ }
+ js.getset(owner, prop, accessor.bind(null, getset[0]), getset[1] && accessor.bind(null, getset[1]));
+ }
+ var getset = obj[prop];
+ if (prop[0] === '*') {
+ // get set
+ var etProp = prop.slice(1);
+ define('g' + etProp, getset);
+ define('s' + etProp, getset);
+ }
+ else {
+ prop.split(',')
+ .map(function (x) {
+ return x.trim();
+ })
+ .forEach(function (x) {
+ define(x, getset);
+ });
+ }
+ }
+ }
+
+ function shouldNotUseNodeProp (component) {
+ var compName = cc.js.getClassName(component);
+ var Info = 'Sorry, ' + compName + '.%s is removed, please use cc.ENode.%s instead.';
+ var compProto = component.prototype;
+ for (var prop in cc.ENode.prototype) {
+ (function (prop) {
+ if (!(prop in compProto) && prop[0] !== '_') {
+ js.getset(compProto, prop,
+ function () {
+ cc.error(Info, prop, prop);
+ },
+ function () {
+ cc.error(Info, prop, prop);
+ }
+ );
+ }
+ })(prop);
+ }
+ }
+
+ // cc.ENode
+
+ markAsRemoved(cc.ENode, [
+ '_componentContainer',
+ '_camera',
+ '_additionalTransform',
+ '_scheduler',
+ '_actionManager',
+ 'actionManager',
+ '_isTransitionFinished',
+ '_additionalTransformDirty',
+ '_shaderProgram',
+ 'shaderProgram',
+ '_reorderChildDirty',
+ '_normalizedPositionDirty',
+ '_normalizedPosition',
+ '_usingNormalizedPosition',
+ '_renderCmd',
+ '_vertexZ',
+ '_showNode',
+ '_arrayMakeObjectsPerformSelector',
+ 'getActionManager',
+ 'setActionManager',
+ 'getScheduler',
+ 'setScheduler',
+ 'sortAllChildren',
+ 'reorderChild',
+ 'draw',
+ 'transformAncestors',
+ 'onEnter',
+ 'onEnterTransitionDidFinish',
+ 'onExitTransitionDidStart',
+ 'onExit',
+ 'runAction',
+ 'stopAllActions',
+ 'stopAction',
+ 'stopActionByTag',
+ 'getActionByTag',
+ 'getNumberOfRunningActions',
+ 'scheduleUpdate',
+ 'scheduleUpdateWithPriority',
+ 'unscheduleUpdate',
+ 'schedule',
+ 'scheduleOnce',
+ 'unschedule',
+ 'unscheduleAllCallbacks',
+ 'resumeSchedulerAndActions',
+ 'resume',
+ 'pauseSchedulerAndActions',
+ 'pause',
+ 'setAdditionalTransform',
+ 'updateTransform',
+ 'retain',
+ 'release',
+ 'visit',
+ 'transform',
+ 'getCamera',
+ 'grid',
+ 'getGrid',
+ 'setGrid',
+ 'getShaderProgram',
+ 'setShaderProgram',
+ 'getGLServerState',
+ 'setGLServerState',
+ '_initRendererCmd',
+ '_createRenderCmd',
+ 'updateDisplayedOpacity',
+ 'updateDisplayedColor',
+ 'userData',
+ 'userObject',
+ '_cascadeColorEnabled',
+ 'cascadeColor'
+ ]);
+ provideClearError(cc.ENode.prototype, {
+ arrivalOrder: 'getSiblingIndex, setSiblingIndex',
+ _visible: '_activeInHierarchy, active',
+ _running: '_activeInHierarchy, active',
+ running: 'activeInHierarchy, active',
+ _realOpacity: '_opacity, _opacity',
+ _realColor: '_color, _color',
+ getZOrder: 'getLocalZOrder',
+ setZOrder: 'setLocalZOrder',
+ getOrderOfArrival: 'getSiblingIndex',
+ setOrderOfArrival: 'setSiblingIndex',
+ boundingBox: 'getBoundingBox',
+ removeFromParentAndCleanup: 'removeFromParent',
+ removeAllChildrenWithCleanup: 'removeAllChildren',
+ parentToNodeTransform: 'getParentToNodeTransform',
+ nodeToWorldTransform: 'getNodeToWorlshaderProgramdTransform',
+ worldToNodeTransform: 'getWorldToNodeTransform',
+ nodeToParentTransform: 'getNodeToParentTransform',
+ getNodeToParentAffineTransform: 'getNodeToParentTransform',
+ });
+
+ // cc.SpriteRenderer
+
+ markAsRemoved(cc.SpriteRenderer, [
+ 'textureLoaded',
+ 'setBlendFunc',
+ 'getBlendFunc',
+ 'setState',
+ 'getState',
+ ]);
+ provideClearError(cc.SpriteRenderer, {
+ create: 'node.addComponent',
+ createWithTexture: 'node.addComponent',
+ createWithSpriteFrameName: 'node.addComponent',
+ createWithSpriteFrame: 'node.addComponent',
+ });
+ provideClearError(cc.SpriteRenderer.prototype, {
+ ignoreAnchorPointForPosition: 'instance.ignoreAnchor',
+ });
+ shouldNotUseNodeProp(cc.SpriteRenderer);
+
+ // Particle
+ markAsRemoved(cc.EParticleSystem, [
+ 'batchNode',
+ 'drawMode',
+ 'getDrawMode',
+ 'setDrawMode',
+ 'shapeType',
+ 'getShapeType',
+ 'setShapeType',
+ 'atlasIndex',
+ 'init',
+ 'initParticle',
+ 'updateWithNoTime',
+ ]);
+ provideClearError(cc.EParticleSystem, {
+ initWithFile: 'instance.file',
+ initWithDictionary: 'instance.file',
+ initWithTotalParticles: 'instance.totalParticles'
+ });
+ provideClearError(cc.EParticleSystem.prototype, {
+ destroyParticleSystem: 'destroy',
+ clone: 'cc.instantiate',
+ isActive: 'active',
+ '*etParticleCount': 'particleCount',
+ '*etDuration': 'duration',
+ '*etSourcePosition': 'sourcePos',
+ '*etPosVar': 'posVar',
+ '*etGravity': 'gravity',
+ '*etSpeed': 'speed',
+ '*etSpeedVar': 'speedVar',
+ '*etTangentialAccel': 'tangentialAccel',
+ '*etTangentialAccelVar': 'tangentialAccelVar',
+ '*etRadialAccel': 'radialAccel',
+ '*etRadialAccelVar': 'radialAccelVar',
+ '*etRotationIsDir': 'rotationIsDir',
+ '*etStartRadius': 'startRadius',
+ '*etStartRadiusVar': 'startRadiusVar',
+ '*etEndRadius': 'endRadius',
+ '*etEndRadiusVar': 'endRadiusVar',
+ '*etRotatePerSecond': 'rotatePerS',
+ '*etRotatePerSecondVar': 'rotatePerSVar',
+ '*etStartColor': 'startColor',
+ '*etStartColorVar': 'startColorVar',
+ '*etEndColor': 'endColor',
+ '*etEndColorVar': 'endColorVar',
+ '*etTotalParticles': 'totalParticles',
+ '*etTexture': 'texture',
+ });
+ shouldNotUseNodeProp(cc.EParticleSystem);
+ js.obsoletes(cc.EParticleSystem, 'cc.EParticleSystem', {
+ Type: 'PositionType',
+ Mode: 'EmitterMode'
+ });
+
+ // cc.Node
+ markAsRemoved(cc.Node, [
+ '_normalizedPositionDirty',
+ '_normalizedPosition',
+ '_usingNormalizedPosition',
+ 'grid',
+ 'userData',
+ 'userObject',
+ 'getNormalizedPosition',
+ 'setNormalizedPosition',
+ 'getCamera',
+ 'getUserData',
+ 'setUserData',
+ 'getUserObject',
+ 'setUserObject',
+ 'getComponent',
+ 'addComponent',
+ 'removeComponent',
+ 'removeAllComponents',
+ 'enumerateChildren'
+ ], 'cc.Node');
+
+}
diff --git a/cocos2d/effects/CCGrabber.js b/cocos2d/effects/CCGrabber.js
new file mode 100644
index 0000000000..bbc754ae67
--- /dev/null
+++ b/cocos2d/effects/CCGrabber.js
@@ -0,0 +1,110 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+/**
+ * FBO class that grabs the the contents of the screen
+ * @class
+ * @extends cc._Class
+ */
+cc.Grabber = cc._Class.extend({
+ _FBO:null,
+ _oldFBO:null,
+ _oldClearColor:null,
+
+ _gl:null,
+
+ /**
+ * constructor of cc.Grabber
+ */
+ ctor:function () {
+ cc.sys._checkWebGLRenderMode();
+ this._gl = cc._renderContext;
+ this._oldClearColor = [0, 0, 0, 0];
+ this._oldFBO = null;
+ // generate FBO
+ this._FBO = this._gl.createFramebuffer();
+ },
+
+ /**
+ * grab
+ * @param {cc.Texture2D} texture
+ */
+ grab:function (texture) {
+ var locGL = this._gl;
+ this._oldFBO = locGL.getParameter(locGL.FRAMEBUFFER_BINDING);
+ // bind
+ locGL.bindFramebuffer(locGL.FRAMEBUFFER, this._FBO);
+ // associate texture with FBO
+ locGL.framebufferTexture2D(locGL.FRAMEBUFFER, locGL.COLOR_ATTACHMENT0, locGL.TEXTURE_2D, texture._webTextureObj, 0);
+
+ // check if it worked (probably worth doing :) )
+ var status = locGL.checkFramebufferStatus(locGL.FRAMEBUFFER);
+ if (status !== locGL.FRAMEBUFFER_COMPLETE)
+ cc.log("Frame Grabber: could not attach texture to frmaebuffer");
+ locGL.bindFramebuffer(locGL.FRAMEBUFFER, this._oldFBO);
+ },
+
+ /**
+ * should be invoked before drawing
+ * @param {cc.Texture2D} texture
+ */
+ beforeRender:function (texture) {
+ var locGL = this._gl;
+ this._oldFBO = locGL.getParameter(locGL.FRAMEBUFFER_BINDING);
+ locGL.bindFramebuffer(locGL.FRAMEBUFFER, this._FBO);
+
+ // save clear color
+ this._oldClearColor = locGL.getParameter(locGL.COLOR_CLEAR_VALUE);
+
+ // BUG XXX: doesn't work with RGB565.
+ locGL.clearColor(0, 0, 0, 0);
+
+ // BUG #631: To fix #631, uncomment the lines with #631
+ // Warning: But it CCGrabber won't work with 2 effects at the same time
+ // glClearColor(0.0f,0.0f,0.0f,1.0f); // #631
+
+ locGL.clear(locGL.COLOR_BUFFER_BIT | locGL.DEPTH_BUFFER_BIT);
+
+ // glColorMask(true, true, true, false); // #631
+ },
+
+ /**
+ * should be invoked after drawing
+ * @param {cc.Texture2D} texture
+ */
+ afterRender:function (texture) {
+ var locGL = this._gl;
+ locGL.bindFramebuffer(locGL.FRAMEBUFFER, this._oldFBO);
+ locGL.colorMask(true, true, true, true); // #631
+ },
+
+ /**
+ * delete FBO
+ */
+ destroy:function(){
+ this._gl.deleteFramebuffer(this._FBO);
+ }
+});
diff --git a/cocos2d/effects/CCGrid.js b/cocos2d/effects/CCGrid.js
new file mode 100644
index 0000000000..dc6a59182d
--- /dev/null
+++ b/cocos2d/effects/CCGrid.js
@@ -0,0 +1,846 @@
+/****************************************************************************
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2009 On-Core
+
+ 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.Grid
+ * @class
+ * @extends cc._Class
+ */
+cc.GridBase = cc._Class.extend(/** @lends cc.GridBase# */{
+ _active:false,
+ _reuseGrid:0,
+ _gridSize:null,
+ _gridRect:null,
+ _texture:null,
+ _step:null,
+ _grabber:null,
+ _isTextureFlipped:false,
+ _shaderProgram:null,
+ _directorProjection:0,
+
+ _dirty:false,
+
+ /**
+ * create one cc.GridBase Object
+ * Constructor of cc.GridBase
+ * @param {cc.Size} gridSize
+ * @param {cc.Texture2D} [texture=]
+ * @param {Boolean} [flipped=]
+ * @param {cc.Rect} rect
+ */
+ ctor:function (gridSize, texture, flipped, rect) {
+ cc.sys._checkWebGLRenderMode();
+ this._active=false;
+ this._reuseGrid=0;
+ this._gridSize=null;
+ this._gridRect=new cc.rect();
+ this._texture=null;
+ this._step = cc.p(0, 0);
+ this._grabber=null;
+ this._isTextureFlipped=false;
+ this._shaderProgram=null;
+ this._directorProjection=0;
+ this._dirty=false;
+
+ if(gridSize !== undefined)
+ this.initWithSize(gridSize, texture, flipped, rect);
+ },
+
+ /**
+ * whether or not the grid is active
+ * @return {Boolean}
+ */
+ isActive:function () {
+ return this._active;
+ },
+
+ /**
+ * whether or not the grid is active
+ * @param {Number} active
+ */
+ setActive:function (active) {
+ this._active = active;
+ if (!active) {
+ var director = cc.director;
+ var proj = director.getProjection();
+ director.setProjection(proj);
+ }
+ },
+
+ /**
+ * get number of times that the grid will be reused
+ * @return {Number}
+ */
+ getReuseGrid:function () {
+ return this._reuseGrid;
+ },
+ /**
+ * set number of times that the grid will be reused
+ * @param reuseGrid
+ */
+ setReuseGrid:function (reuseGrid) {
+ this._reuseGrid = reuseGrid;
+ },
+
+ /**
+ * get size of the grid
+ * @return {cc.Size}
+ */
+ getGridSize:function () {
+ return cc.size(this._gridSize.width, this._gridSize.height);
+ },
+
+ /**
+ * set size of the grid
+ * @param {cc.Size} gridSize
+ */
+ setGridSize:function (gridSize) {
+ this._gridSize.width = parseInt(gridSize.width);
+ this._gridSize.height = parseInt(gridSize.height);
+ },
+
+ /**
+ * set rect of the grid
+ * @param {cc.Rect} rect
+ */
+ setGridRect:function (rect) {
+ this._gridRect = rect;
+ },
+
+ /**
+ * get rect of the grid
+ * @return {cc.Rect} rect
+ */
+ getGridRect:function () {
+ return this._gridRect;
+ },
+
+ /**
+ * get pixels between the grids
+ * @return {cc.Vec2}
+ */
+ getStep:function () {
+ return cc.p(this._step.x, this._step.y);
+ },
+
+ /**
+ * set pixels between the grids
+ * @param {cc.Vec2} step
+ */
+ setStep:function (step) {
+ this._step.x = step.x;
+ this._step.y = step.y;
+ },
+
+ /**
+ * get whether or not the texture is flipped
+ * @return {Boolean}
+ */
+ isTextureFlipped:function () {
+ return this._isTextureFlipped;
+ },
+
+ /**
+ * set whether or not the texture is flipped
+ * @param {Boolean} flipped
+ */
+ setTextureFlipped:function (flipped) {
+ if (this._isTextureFlipped !== flipped) {
+ this._isTextureFlipped = flipped;
+ this.calculateVertexPoints();
+ }
+ },
+
+ /**
+ *
+ * @param {cc.Size} gridSize
+ * @param {cc.Texture2D} [texture=]
+ * @param {Boolean} [flipped=false]
+ * @param {cc.Rect} [rect=]
+ * @returns {boolean}
+ */
+ initWithSize:function (gridSize, texture, flipped, rect) {
+ if (!texture) {
+ var director = cc.director;
+ var winSize = director.getWinSizeInPixels();
+
+ var POTWide = cc.NextPOT(winSize.width);
+ var POTHigh = cc.NextPOT(winSize.height);
+
+ var data = new Uint8Array(POTWide * POTHigh * 4);
+ if (!data) {
+ cc.log("cocos2d: CCGrid: not enough memory.");
+ return false;
+ }
+
+ texture = new cc.Texture2D();
+ // we only use rgba8888
+ texture.initWithData(data, cc.Texture2D.PIXEL_FORMAT_RGBA8888, POTWide, POTHigh, winSize);
+ if (!texture) {
+ cc.log("cocos2d: CCGrid: error creating texture");
+ return false;
+ }
+ }
+
+ flipped = flipped || false;
+
+ this._active = false;
+ this._reuseGrid = 0;
+ this._gridSize = gridSize;
+ this._texture = texture;
+ this._isTextureFlipped = flipped;
+ if(rect === undefined || cc._rectEqualToZero(rect))
+ {
+ var size = this._texture.getContentSize();
+ rect = new cc.rect(0,0,size.width,size.height);
+ }
+
+ this._gridRect = rect;
+
+ this._step.x = this._gridRect.width / gridSize.width;
+ this._step.y = this._gridRect.height / gridSize.height;
+
+ this._grabber = new cc.Grabber();
+ if (!this._grabber)
+ return false;
+ this._grabber.grab(this._texture);
+ this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURE);
+ this.calculateVertexPoints();
+ return true;
+ },
+
+ beforeDraw:function () {
+ // save projection
+ this._directorProjection = cc.director.getProjection();
+
+ //this.set2DProjection(); //TODO why?
+ this._grabber.beforeRender(this._texture);
+ },
+
+ afterDraw:function (target) {
+ this._grabber.afterRender(this._texture);
+
+ // restore projection
+ //cc.director.setProjection(this._directorProjection);
+
+ if (target && target.getCamera().isDirty()) {
+ var offset = target.getAnchorPointInPoints();
+
+ //TODO hack
+ var stackMatrix = target._renderCmd._stackMatrix;
+ //
+ // XXX: Camera should be applied in the AnchorPoint
+ //
+ //cc.kmGLTranslatef(offset.x, offset.y, 0);
+ var translation = cc.math.Matrix4.createByTranslation(offset.x, offset.y, 0);
+ stackMatrix.multiply(translation);
+
+ //target.getCamera().locate();
+ target._camera._locateForRenderer(stackMatrix);
+
+ //cc.kmGLTranslatef(-offset.x, -offset.y, 0);
+ translation = cc.math.Matrix4.createByTranslation(-offset.x, -offset.y, 0, translation);
+ stackMatrix.multiply(translation);
+ }
+
+ cc.glBindTexture2D(this._texture);
+ this.beforeBlit();
+ this.blit(target);
+ this.afterBlit();
+ },
+
+ beforeBlit: function () {
+ },
+
+ afterBlit: function () {
+ },
+
+ blit:function () {
+ cc.log("cc.GridBase.blit(): Shall be overridden in subclass.");
+ },
+
+ reuse:function () {
+ cc.log("cc.GridBase.reuse(): Shall be overridden in subclass.");
+ },
+
+ calculateVertexPoints:function () {
+ cc.log("cc.GridBase.calculateVertexPoints(): Shall be overridden in subclass.");
+ },
+
+ set2DProjection:function () {
+ var winSize = cc.director.getWinSizeInPixels();
+
+ var gl = cc._renderContext;
+ gl.viewport(0, 0, winSize.width , winSize.height);
+ cc.kmGLMatrixMode(cc.KM_GL_PROJECTION);
+ cc.kmGLLoadIdentity();
+
+ var orthoMatrix = cc.math.Matrix4.createOrthographicProjection(0, winSize.width, 0, winSize.height, -1, 1);
+ cc.kmGLMultMatrix(orthoMatrix);
+
+ cc.kmGLMatrixMode(cc.KM_GL_MODELVIEW);
+ cc.kmGLLoadIdentity();
+ cc.setProjectionMatrixDirty()
+ }
+});
+
+/**
+ * create one cc.GridBase Object
+ * @deprecated
+ * @param {cc.Size} gridSize
+ * @param {cc.Texture2D} [texture=]
+ * @param {Boolean} [flipped=]
+ * @param {cc.Rect} [rect=]
+ * @return {cc.GridBase}
+ */
+cc.GridBase.create = function (gridSize, texture, flipped, rect) {
+ return new cc.GridBase(gridSize, texture, flipped, rect);
+};
+
+/**
+ * cc.Grid3D is a 3D grid implementation. Each vertex has 3 dimensions: x,y,z
+ * @class
+ * @extends cc.GridBase
+ */
+cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{
+ _texCoordinates:null,
+ _vertices:null,
+ _originalVertices:null,
+ _indices:null,
+
+ _texCoordinateBuffer:null,
+ _verticesBuffer:null,
+ _indicesBuffer:null,
+
+ _needDepthTestForBlit: false,
+ _oldDepthTestValue: false,
+ _oldDepthWriteValue: false,
+
+ /**
+ * create one Grid3D object
+ * Constructor of cc.Grid3D
+ * @param {cc.Size} gridSize
+ * @param {cc.Texture2D} [texture=]
+ * @param {Boolean} [flipped=]
+ * @param {cc.Rect} [rect=]
+ */
+ ctor:function (gridSize, texture, flipped, rect) {
+ cc.GridBase.prototype.ctor.call(this);
+ this._texCoordinates=null;
+ this._vertices=null;
+ this._originalVertices=null;
+ this._indices=null;
+
+ this._texCoordinateBuffer=null;
+ this._verticesBuffer=null;
+ this._indicesBuffer=null;
+
+ if(gridSize !== undefined)
+ this.initWithSize(gridSize, texture, flipped, rect);
+ },
+
+ /**
+ * returns the vertex at a given position
+ * It will be deprecated in future, please use getVertex instead.
+ * @param {cc.Vec2} pos
+ * @return {cc.Vertex3F}
+ */
+ vertex:function (pos) {
+ return this.getVertex(pos);
+ },
+
+ /**
+ * returns the vertex at a given position
+ * @param {cc.Vec2} pos
+ * @return {cc.Vertex3F}
+ */
+ getVertex: function(pos){
+ if(pos.x !== (0| pos.x) || pos.y !== (0| pos.y))
+ cc.log("cc.Grid3D.vertex() : Numbers must be integers");
+ var index = 0 | ((pos.x * (this._gridSize.height + 1) + pos.y) * 3);
+ var locVertices = this._vertices;
+ return new cc.Vertex3F(locVertices[index], locVertices[index + 1], locVertices[index + 2]);
+ },
+
+ /**
+ * returns the original (non-transformed) vertex at a given position
+ * It will be deprecated in future, please use getOriginalVertex instead.
+ * @param {cc.Vec2} pos
+ * @return {cc.Vertex3F}
+ */
+ originalVertex:function (pos) {
+ return this.getOriginalVertex(pos);
+ },
+
+ /**
+ * returns the original (non-transformed) vertex at a given position
+ * @param {cc.Vec2} pos
+ * @return {cc.Vertex3F}
+ */
+ getOriginalVertex: function(pos) {
+ if(pos.x !== (0| pos.x) || pos.y !== (0| pos.y))
+ cc.log("cc.Grid3D.originalVertex() : Numbers must be integers");
+ var index = 0 | ((pos.x * (this._gridSize.height + 1) + pos.y) * 3);
+ var locOriginalVertices = this._originalVertices;
+ return new cc.Vertex3F(locOriginalVertices[index], locOriginalVertices[index + 1], locOriginalVertices[index + 2]);
+ },
+
+ /**
+ * sets a new vertex at a given position
+ * @param {cc.Vec2} pos
+ * @param {cc.Vertex3F} vertex
+ */
+ setVertex:function (pos, vertex) {
+ if(pos.x !== (0| pos.x) || pos.y !== (0| pos.y))
+ cc.log("cc.Grid3D.setVertex() : Numbers must be integers");
+ var index = 0 | ((pos.x * (this._gridSize.height + 1) + pos.y) * 3);
+ var vertArray = this._vertices;
+ vertArray[index] = vertex.x;
+ vertArray[index + 1] = vertex.y;
+ vertArray[index + 2] = vertex.z;
+ this._dirty = true;
+ },
+
+ beforeBlit: function () {
+ if (this._needDepthTestForBlit) {
+ var gl = cc._renderContext;
+ this._oldDepthTestValue = gl.isEnabled(gl.DEPTH_TEST);
+ this._oldDepthWriteValue = gl.getParameter(gl.DEPTH_WRITEMASK);
+ //CHECK_GL_ERROR_DEBUG();
+ gl.enable(gl.DEPTH_TEST);
+ gl.depthMask(true);
+ }
+ },
+
+ afterBlit: function () {
+ if (this._needDepthTestForBlit) {
+ var gl = cc._renderContext;
+ if (this._oldDepthTestValue)
+ gl.enable(gl.DEPTH_TEST);
+ else
+ gl.disable(gl.DEPTH_TEST);
+ gl.depthMask(this._oldDepthWriteValue);
+ }
+ },
+
+ blit:function (target) {
+ var n = this._gridSize.width * this._gridSize.height;
+ cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POSITION | cc.VERTEX_ATTRIB_FLAG_TEX_COORDS);
+ this._shaderProgram.use();
+ //this._shaderProgram.setUniformsForBuiltins();
+ this._shaderProgram._setUniformForMVPMatrixWithMat4(target._renderCmd._stackMatrix);
+
+ var gl = cc._renderContext, locDirty = this._dirty;
+ //
+ // Attributes
+ //
+ // position
+ gl.bindBuffer(gl.ARRAY_BUFFER, this._verticesBuffer);
+ if (locDirty)
+ gl.bufferData(gl.ARRAY_BUFFER, this._vertices, gl.DYNAMIC_DRAW);
+ gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 0, 0);
+
+ // texCoords
+ gl.bindBuffer(gl.ARRAY_BUFFER, this._texCoordinateBuffer);
+ if (locDirty)
+ gl.bufferData(gl.ARRAY_BUFFER, this._texCoordinates, gl.DYNAMIC_DRAW);
+ gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 0, 0);
+
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indicesBuffer);
+ if (locDirty)
+ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this._indices, gl.STATIC_DRAW);
+ gl.drawElements(gl.TRIANGLES, n * 6, gl.UNSIGNED_SHORT, 0);
+ if (locDirty)
+ this._dirty = false;
+ cc.incrementGLDraws(1);
+ },
+
+ reuse:function () {
+ if (this._reuseGrid > 0) {
+ var locOriginalVertices = this._originalVertices, locVertices = this._vertices;
+ for (var i = 0, len = this._vertices.length; i < len; i++)
+ locOriginalVertices[i] = locVertices[i];
+ --this._reuseGrid;
+ }
+ },
+
+ calculateVertexPoints:function () {
+ var gl = cc._renderContext;
+
+ var width = this._texture.getPixelWidth();
+ var height = this._texture.getPixelHeight();
+ var imageH = this._texture.getContentSizeInPixels().height;
+ var locGridSize = this._gridSize;
+
+ var numOfPoints = (locGridSize.width + 1) * (locGridSize.height + 1);
+ this._vertices = new Float32Array(numOfPoints * 3);
+ this._texCoordinates = new Float32Array(numOfPoints * 2);
+ this._indices = new Uint16Array(locGridSize.width * locGridSize.height * 6);
+
+ if(this._verticesBuffer)
+ gl.deleteBuffer(this._verticesBuffer);
+ this._verticesBuffer = gl.createBuffer();
+ if(this._texCoordinateBuffer)
+ gl.deleteBuffer(this._texCoordinateBuffer);
+ this._texCoordinateBuffer = gl.createBuffer();
+ if(this._indicesBuffer)
+ gl.deleteBuffer(this._indicesBuffer);
+ this._indicesBuffer = gl.createBuffer();
+
+ var x, y, i, locIndices = this._indices, locTexCoordinates = this._texCoordinates;
+ var locIsTextureFlipped = this._isTextureFlipped, locVertices = this._vertices;
+ for (x = 0; x < locGridSize.width; ++x) {
+ for (y = 0; y < locGridSize.height; ++y) {
+ var idx = (y * locGridSize.width) + x;
+ var x1 = x * this._step.x + this._gridRect.x;
+ var x2 = x1 + this._step.x;
+ var y1 = y * this._step.y + this._gridRect.y;
+ var y2 = y1 + this._step.y;
+
+ var a = (x * (locGridSize.height + 1) + y);
+ var b = ((x + 1) * (locGridSize.height + 1) + y);
+ var c = ((x + 1) * (locGridSize.height + 1) + (y + 1));
+ var d = (x * (locGridSize.height + 1) + (y + 1));
+
+ locIndices[idx * 6] = a;
+ locIndices[idx * 6 + 1] = b;
+ locIndices[idx * 6 + 2] = d;
+ locIndices[idx * 6 + 3] = b;
+ locIndices[idx * 6 + 4] = c;
+ locIndices[idx * 6 + 5] = d;
+
+ var l1 = [a * 3, b * 3, c * 3, d * 3];
+ var e = {x:x1, y:y1, z:0}; //new cc.Vertex3F(x1, y1, 0);
+ var f = {x:x2, y:y1, z:0}; //new cc.Vertex3F(x2, y1, 0);
+ var g = {x:x2, y:y2, z:0}; // new cc.Vertex3F(x2, y2, 0);
+ var h = {x:x1, y:y2, z:0}; //new cc.Vertex3F(x1, y2, 0);
+
+ var l2 = [e, f, g, h];
+ var tex1 = [a * 2, b * 2, c * 2, d * 2];
+ var tex2 = [cc.p(x1, y1), cc.p(x2, y1), cc.p(x2, y2), cc.p(x1, y2)];
+ for (i = 0; i < 4; ++i) {
+ locVertices[l1[i]] = l2[i].x;
+ locVertices[l1[i] + 1] = l2[i].y;
+ locVertices[l1[i] + 2] = l2[i].z;
+ locTexCoordinates[tex1[i]] = tex2[i].x / width;
+ if (locIsTextureFlipped)
+ locTexCoordinates[tex1[i] + 1] = (imageH - tex2[i].y) / height;
+ else
+ locTexCoordinates[tex1[i] + 1] = tex2[i].y / height;
+ }
+ }
+ }
+ this._originalVertices = new Float32Array(this._vertices);
+
+ gl.bindBuffer(gl.ARRAY_BUFFER, this._verticesBuffer);
+ gl.bufferData(gl.ARRAY_BUFFER, this._vertices, gl.DYNAMIC_DRAW);
+ gl.bindBuffer(gl.ARRAY_BUFFER, this._texCoordinateBuffer);
+ gl.bufferData(gl.ARRAY_BUFFER, this._texCoordinates, gl.DYNAMIC_DRAW);
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indicesBuffer);
+ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this._indices, gl.STATIC_DRAW);
+ this._dirty = true;
+ },
+
+ setNeedDepthTestForBlit: function(needDepthTest){
+ this._needDepthTestForBlit = needDepthTest;
+ },
+
+ getNeedDepthTestForBlit: function(){
+ return this._needDepthTestForBlit;
+ }
+});
+
+/**
+ * create one Grid3D object
+ * @deprecated
+ * @param {cc.Size} gridSize
+ * @param {cc.Texture2D} [texture=]
+ * @param {Boolean} [flipped=]
+ * @return {cc.Grid3D}
+ */
+cc.Grid3D.create = function (gridSize, texture, flipped) {
+ return new cc.Grid3D(gridSize, texture, flipped);
+};
+
+/**
+ * cc.TiledGrid3D is a 3D grid implementation. It differs from Grid3D in that
+ * the tiles can be separated from the grid.
+ * @class
+ * @extends cc.GridBase
+ */
+cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{
+ _texCoordinates:null,
+ _vertices:null,
+ _originalVertices:null,
+ _indices:null,
+
+ _texCoordinateBuffer:null,
+ _verticesBuffer:null,
+ _indicesBuffer:null,
+
+ /**
+ * create one TiledGrid3D object
+ * Constructor of cc.TiledGrid3D
+ * @param {cc.Size} gridSize
+ * @param {cc.Texture2D} [texture=]
+ * @param {Boolean} [flipped=]
+ */
+ ctor:function (gridSize, texture, flipped, rect) {
+ cc.GridBase.prototype.ctor.call(this);
+ this._texCoordinates=null;
+ this._vertices=null;
+ this._originalVertices=null;
+ this._indices=null;
+
+ this._texCoordinateBuffer=null;
+ this._verticesBuffer=null;
+ this._indicesBuffer=null;
+
+ if(gridSize !== undefined)
+ this.initWithSize(gridSize, texture, flipped, rect);
+ },
+
+ /**
+ * returns the tile at the given position
+ * It will be deprecated in future, please use getTile instead.
+ * @param {cc.Vec2} pos
+ * @return {cc.Quad3}
+ */
+ tile:function (pos) {
+ return this.getTile(pos);
+ },
+
+ /**
+ * returns the tile at the given position
+ * @param {cc.Vec2} pos
+ * @return {cc.Quad3}
+ */
+ getTile: function(pos){
+ if(pos.x !== (0| pos.x) || pos.y !== (0| pos.y))
+ cc.log("cc.TiledGrid3D.tile() : Numbers must be integers");
+
+ var idx = (this._gridSize.height * pos.x + pos.y) * 4 * 3;
+ var locVertices = this._vertices;
+ return new cc.Quad3(new cc.Vertex3F(locVertices[idx], locVertices[idx + 1], locVertices[idx + 2]),
+ new cc.Vertex3F(locVertices[idx + 3], locVertices[idx + 4], locVertices[idx + 5]),
+ new cc.Vertex3F(locVertices[idx + 6 ], locVertices[idx + 7], locVertices[idx + 8]),
+ new cc.Vertex3F(locVertices[idx + 9], locVertices[idx + 10], locVertices[idx + 11]));
+ },
+
+ /**
+ * returns the original tile (untransformed) at the given position
+ * @param {cc.Vec2} pos
+ * @return {cc.Quad3}
+ */
+ getOriginalTile:function (pos) {
+ if(pos.x !== (0| pos.x) || pos.y !== (0| pos.y))
+ cc.log("cc.TiledGrid3D.originalTile() : Numbers must be integers");
+
+ var idx = (this._gridSize.height * pos.x + pos.y) * 4 * 3;
+ var locOriginalVertices = this._originalVertices;
+ return new cc.Quad3(new cc.Vertex3F(locOriginalVertices[idx], locOriginalVertices[idx + 1], locOriginalVertices[idx + 2]),
+ new cc.Vertex3F(locOriginalVertices[idx + 3], locOriginalVertices[idx + 4], locOriginalVertices[idx + 5]),
+ new cc.Vertex3F(locOriginalVertices[idx + 6 ], locOriginalVertices[idx + 7], locOriginalVertices[idx + 8]),
+ new cc.Vertex3F(locOriginalVertices[idx + 9], locOriginalVertices[idx + 10], locOriginalVertices[idx + 11]));
+ },
+
+ /**
+ * returns the original tile (untransformed) at the given position.
+ * It will be deprecated in future, please use getOriginalTile instead.
+ * @param {cc.Vec2} pos
+ * @return {cc.Quad3}
+ */
+ originalTile: function(pos) {
+ return this.getOriginalTile(pos);
+ },
+
+ /**
+ * sets a new tile
+ * @param {cc.Vec2} pos
+ * @param {cc.Quad3} coords
+ */
+ setTile:function (pos, coords) {
+ if(pos.x !== (0| pos.x) || pos.y !== (0| pos.y))
+ cc.log("cc.TiledGrid3D.setTile() : Numbers must be integers");
+
+ var idx = (this._gridSize.height * pos.x + pos.y) * 12;
+ var locVertices = this._vertices;
+ locVertices[idx] = coords.bl.x;
+ locVertices[idx + 1] = coords.bl.y;
+ locVertices[idx + 2] = coords.bl.z;
+ locVertices[idx + 3] = coords.br.x;
+ locVertices[idx + 4] = coords.br.y;
+ locVertices[idx + 5] = coords.br.z;
+ locVertices[idx + 6] = coords.tl.x;
+ locVertices[idx + 7] = coords.tl.y;
+ locVertices[idx + 8] = coords.tl.z;
+ locVertices[idx + 9] = coords.tr.x;
+ locVertices[idx + 10] = coords.tr.y;
+ locVertices[idx + 11] = coords.tr.z;
+ this._dirty = true;
+ },
+
+ blit: function (target) {
+ var n = this._gridSize.width * this._gridSize.height;
+
+ this._shaderProgram.use();
+ this._shaderProgram._setUniformForMVPMatrixWithMat4(target._renderCmd._stackMatrix);
+ //this._shaderProgram.setUniformsForBuiltins();
+
+ //
+ // Attributes
+ //
+ var gl = cc._renderContext, locDirty = this._dirty;
+ cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POSITION | cc.VERTEX_ATTRIB_FLAG_TEX_COORDS);
+
+ // position
+ gl.bindBuffer(gl.ARRAY_BUFFER, this._verticesBuffer);
+ if (locDirty)
+ gl.bufferData(gl.ARRAY_BUFFER, this._vertices, gl.DYNAMIC_DRAW);
+ gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 0, this._vertices);
+
+ // texCoords
+ gl.bindBuffer(gl.ARRAY_BUFFER, this._texCoordinateBuffer);
+ if (locDirty)
+ gl.bufferData(gl.ARRAY_BUFFER, this._texCoordinates, gl.DYNAMIC_DRAW);
+ gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 0, this._texCoordinates);
+
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indicesBuffer);
+ if (locDirty)
+ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this._indices, gl.STATIC_DRAW);
+ gl.drawElements(gl.TRIANGLES, n * 6, gl.UNSIGNED_SHORT, 0);
+ if (locDirty)
+ this._dirty = false;
+ cc.incrementGLDraws(1);
+ },
+
+ reuse:function () {
+ if (this._reuseGrid > 0) {
+ var locVertices = this._vertices, locOriginalVertices = this._originalVertices;
+ for (var i = 0; i < locVertices.length; i++)
+ locOriginalVertices[i] = locVertices[i];
+ --this._reuseGrid;
+ }
+ },
+
+ calculateVertexPoints:function () {
+ var width = this._texture.getPixelWidth();
+ var height = this._texture.getPixelHeight();
+ var imageH = this._texture.getContentSizeInPixels().height;
+ var locGridSize = this._gridSize;
+
+ var numQuads = locGridSize.width * locGridSize.height;
+ this._vertices = new Float32Array(numQuads * 12);
+ this._texCoordinates = new Float32Array(numQuads * 8);
+ this._indices = new Uint16Array(numQuads * 6);
+
+ var gl = cc._renderContext;
+ if(this._verticesBuffer)
+ gl.deleteBuffer(this._verticesBuffer);
+ this._verticesBuffer = gl.createBuffer();
+ if(this._texCoordinateBuffer)
+ gl.deleteBuffer(this._texCoordinateBuffer);
+ this._texCoordinateBuffer = gl.createBuffer();
+ if(this._indicesBuffer)
+ gl.deleteBuffer(this._indicesBuffer);
+ this._indicesBuffer = gl.createBuffer();
+
+ var x, y, i = 0;
+ var locStep = this._step, locVertices = this._vertices, locTexCoords = this._texCoordinates, locIsTextureFlipped = this._isTextureFlipped;
+ for (x = 0; x < locGridSize.width; x++) {
+ for (y = 0; y < locGridSize.height; y++) {
+ var x1 = x * locStep.x;
+ var x2 = x1 + locStep.x;
+ var y1 = y * locStep.y;
+ var y2 = y1 + locStep.y;
+
+ locVertices[i * 12] = x1;
+ locVertices[i * 12 + 1] = y1;
+ locVertices[i * 12 + 2] = 0;
+ locVertices[i * 12 + 3] = x2;
+ locVertices[i * 12 + 4] = y1;
+ locVertices[i * 12 + 5] = 0;
+ locVertices[i * 12 + 6] = x1;
+ locVertices[i * 12 + 7] = y2;
+ locVertices[i * 12 + 8] = 0;
+ locVertices[i * 12 + 9] = x2;
+ locVertices[i * 12 + 10] = y2;
+ locVertices[i * 12 + 11] = 0;
+
+ var newY1 = y1;
+ var newY2 = y2;
+
+ if (locIsTextureFlipped) {
+ newY1 = imageH - y1;
+ newY2 = imageH - y2;
+ }
+
+ locTexCoords[i * 8] = x1 / width;
+ locTexCoords[i * 8 + 1] = newY1 / height;
+ locTexCoords[i * 8 + 2] = x2 / width;
+ locTexCoords[i * 8 + 3] = newY1 / height;
+ locTexCoords[i * 8 + 4] = x1 / width;
+ locTexCoords[i * 8 + 5] = newY2 / height;
+ locTexCoords[i * 8 + 6] = x2 / width;
+ locTexCoords[i * 8 + 7] = newY2 / height;
+ i++;
+ }
+ }
+
+ var locIndices = this._indices;
+ for (x = 0; x < numQuads; x++) {
+ locIndices[x * 6 + 0] = (x * 4 + 0);
+ locIndices[x * 6 + 1] = (x * 4 + 1);
+ locIndices[x * 6 + 2] = (x * 4 + 2);
+
+ locIndices[x * 6 + 3] = (x * 4 + 1);
+ locIndices[x * 6 + 4] = (x * 4 + 2);
+ locIndices[x * 6 + 5] = (x * 4 + 3);
+ }
+ this._originalVertices = new Float32Array(this._vertices);
+
+ gl.bindBuffer(gl.ARRAY_BUFFER, this._verticesBuffer);
+ gl.bufferData(gl.ARRAY_BUFFER, this._vertices, gl.DYNAMIC_DRAW);
+ gl.bindBuffer(gl.ARRAY_BUFFER, this._texCoordinateBuffer);
+ gl.bufferData(gl.ARRAY_BUFFER, this._texCoordinates, gl.DYNAMIC_DRAW);
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indicesBuffer);
+ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this._indices, gl.DYNAMIC_DRAW);
+ this._dirty = true;
+ }
+});
+
+/**
+ * create one TiledGrid3D object
+ * @deprecated since v3.0, please use new cc.TiledGrid3D(gridSize, texture, flipped) instead
+ * @param {cc.Size} gridSize
+ * @param {cc.Texture2D} [texture=]
+ * @param {Boolean} [flipped=]
+ * @return {cc.TiledGrid3D}
+ */
+cc.TiledGrid3D.create = function (gridSize, texture, flipped) {
+ return new cc.TiledGrid3D(gridSize, texture, flipped);
+};
diff --git a/cocos2d/kazmath/SIMDPolyfill.js b/cocos2d/kazmath/SIMDPolyfill.js
new file mode 100644
index 0000000000..7c65b0a214
--- /dev/null
+++ b/cocos2d/kazmath/SIMDPolyfill.js
@@ -0,0 +1,78 @@
+/**
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2008, Luke Benstead.
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without modification,
+ are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+(function(cc) {
+ var _useSIMD = false;
+
+ var mat4Proto = cc.math.Matrix4.prototype;
+ var mat4Inverse = mat4Proto.inverse;
+ var mat4IsIdentity = mat4Proto.isIdentity;
+ var mat4Transpose = mat4Proto.transpose;
+ var mat4Multiply = mat4Proto.multiply;
+ var mat4GetMat4MultiplyValue = mat4Proto.getMat4MultiplyValue;
+ var mat4AssignFrom = mat4Proto.assignFrom;
+ var mat4Equals = mat4Proto.equals;
+ var mat4LookAt = mat4Proto.lookAt;
+
+ var vec3Proto = cc.math.Vec3.prototype;
+ var vec3TransformCoord = vec3Proto.transformCoord;
+
+ function _isEnabledSIMD () {
+ return _useSIMD;
+ }
+
+ function _enableSIMD (enable) {
+ if(typeof(SIMD) === 'undefined')
+ return;
+
+ if (enable) {
+ mat4Proto.inverse = mat4Proto.inverseSIMD;
+ mat4Proto.isIdentity = mat4Proto.isIdentitySIMD;
+ mat4Proto.transpose = mat4Proto.transposeSIMD;
+ mat4Proto.multiply = mat4Proto.multiplySIMD;
+ mat4Proto.getMat4MultiplyValue = mat4Proto.getMat4MultiplyValueSIMD;
+ mat4Proto.assignFrom = mat4Proto.assignFromSIMD;
+ mat4Proto.equals = mat4Proto.equalsSIMD;
+ mat4Proto.lookAt = mat4Proto.lookAtSIMD;
+ vec3Proto.transformCoord = vec3Proto.transformCoordSIMD;
+ } else {
+ mat4Proto.inverse = mat4Inverse;
+ mat4Proto.isIdentity = mat4IsIdentity;
+ mat4Proto.transpose = mat4Transpose;
+ mat4Proto.multiply = mat4Multiply;
+ mat4Proto.getMat4MultiplyValue = mat4GetMat4MultiplyValue;
+ mat4Proto.assignFrom = mat4AssignFrom;
+ mat4Proto.equals = mat4Equals;
+ mat4Proto.lookAt = mat4LookAt;
+ vec3Proto.transformCoord = vec3TransformCoord;
+ }
+ _useSIMD = enable;
+ }
+
+ cc.defineGetterSetter(cc.sys, "useSIMD", _isEnabledSIMD, _enableSIMD);
+})(cc);
\ No newline at end of file
diff --git a/cocos2d/kazmath/aabb.js b/cocos2d/kazmath/aabb.js
new file mode 100644
index 0000000000..8c5dc5b664
--- /dev/null
+++ b/cocos2d/kazmath/aabb.js
@@ -0,0 +1,78 @@
+/**
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2008, Luke Benstead.
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without modification,
+ are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * A structure that represents an axis-aligned bounding box.
+ * cc.kmAABB => cc.math.AABB
+ */
+cc.math.AABB = function (min, max) {
+ /** The max corner of the box */
+ this.min = min || new cc.math.Vec3();
+ /** The min corner of the box */
+ this.max = max || new cc.math.Vec3();
+};
+
+/**
+ * Returns true if point is in the specified AABB, returns false otherwise.
+ * @param {cc.math.Vec3} point
+ * @returns {boolean}
+ */
+cc.math.AABB.prototype.containsPoint = function (point) {
+ return (point.x >= this.min.x && point.x <= this.max.x &&
+ point.y >= this.min.y && point.y <= this.max.y &&
+ point.z >= this.min.z && point.z <= this.max.z);
+};
+
+/**
+ * Returns true if point is in the specified AABB, returns
+ * false otherwise.
+ */
+cc.math.AABB.containsPoint = function (pPoint, pBox) {
+ return (pPoint.x >= pBox.min.x && pPoint.x <= pBox.max.x &&
+ pPoint.y >= pBox.min.y && pPoint.y <= pBox.max.y &&
+ pPoint.z >= pBox.min.z && pPoint.z <= pBox.max.z);
+};
+
+/**
+ * Assigns aabb to current AABB object
+ * @param {cc.math.AABB} aabb
+ */
+cc.math.AABB.prototype.assignFrom = function(aabb){
+ this.min.assignFrom(aabb.min);
+ this.max.assignFrom(aabb.max);
+};
+
+/**
+ * Assigns pIn to pOut, returns pOut.
+ */
+cc.math.AABB.assign = function (pOut, pIn) { //cc.kmAABBAssign
+ pOut.min.assignFrom(pIn.min);
+ pOut.max.assignFrom(pIn.max);
+ return pOut;
+};
+
diff --git a/cocos2d/kazmath/gl/mat4stack.js b/cocos2d/kazmath/gl/mat4stack.js
new file mode 100644
index 0000000000..ecd3aceba3
--- /dev/null
+++ b/cocos2d/kazmath/gl/mat4stack.js
@@ -0,0 +1,98 @@
+/**
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2008, Luke Benstead.
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without modification,
+ are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+(function(cc){
+ /**
+ * The stack of cc.math.Matrix4
+ * @param {cc.math.Matrix4} [top]
+ * @param {Array} [stack]
+ * @constructor
+ */
+ cc.math.Matrix4Stack = function(top, stack) {
+ this.top = top;
+ this.stack = stack || [];
+ //this._matrixPool = []; // use pool in next version
+ };
+ cc.km_mat4_stack = cc.math.Matrix4Stack;
+ var proto = cc.math.Matrix4Stack.prototype;
+
+ proto.initialize = function() { //cc.km_mat4_stack_initialize
+ this.stack.length = 0;
+ this.top = null;
+ };
+
+ //for compatibility
+ cc.km_mat4_stack_push = function(stack, item){
+ stack.stack.push(stack.top);
+ stack.top = new cc.math.Matrix4(item);
+ };
+
+ cc.km_mat4_stack_pop = function(stack, pOut){
+ stack.top = stack.stack.pop();
+ };
+
+ cc.km_mat4_stack_release = function(stack){
+ stack.stack = null;
+ stack.top = null;
+ };
+
+ proto.push = function(item) {
+ item = item || this.top;
+ this.stack.push(this.top);
+ this.top = new cc.math.Matrix4(item);
+ //this.top = this._getFromPool(item);
+ };
+
+ proto.pop = function() {
+ //this._putInPool(this.top);
+ this.top = this.stack.pop();
+ };
+
+ proto.release = function(){
+ this.stack = null;
+ this.top = null;
+ this._matrixPool = null;
+ };
+
+ proto._getFromPool = function (item) {
+ var pool = this._matrixPool;
+ if (pool.length === 0)
+ return new cc.math.Matrix4(item);
+ var ret = pool.pop();
+ ret.assignFrom(item);
+ return ret;
+ };
+
+ proto._putInPool = function(matrix){
+ this._matrixPool.push(matrix);
+ };
+})(cc);
+
+
+
+
diff --git a/cocos2d/kazmath/gl/matrix.js b/cocos2d/kazmath/gl/matrix.js
new file mode 100644
index 0000000000..d1c5683587
--- /dev/null
+++ b/cocos2d/kazmath/gl/matrix.js
@@ -0,0 +1,167 @@
+/**
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2008, Luke Benstead.
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without modification,
+ are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+(function(cc) {
+ cc.KM_GL_MODELVIEW = 0x1700;
+ cc.KM_GL_PROJECTION = 0x1701;
+ cc.KM_GL_TEXTURE = 0x1702;
+
+ cc.modelview_matrix_stack = new cc.math.Matrix4Stack();
+ cc.projection_matrix_stack = new cc.math.Matrix4Stack();
+ cc.texture_matrix_stack = new cc.math.Matrix4Stack();
+
+ cc.current_stack = null;
+ var initialized = false;
+
+ cc.lazyInitialize = function () {
+ if (!initialized) {
+ var identity = new cc.math.Matrix4(); //Temporary identity matrix
+
+ //Initialize all 3 stacks
+ cc.modelview_matrix_stack.initialize();
+ cc.projection_matrix_stack.initialize();
+ cc.texture_matrix_stack.initialize();
+
+ cc.current_stack = cc.modelview_matrix_stack;
+ cc.initialized = true;
+ identity.identity();
+
+ //Make sure that each stack has the identity matrix
+ cc.modelview_matrix_stack.push(identity);
+ cc.projection_matrix_stack.push(identity);
+ cc.texture_matrix_stack.push(identity);
+ }
+ };
+
+ cc.lazyInitialize();
+
+ cc.kmGLFreeAll = function () {
+ //Clear the matrix stacks
+ cc.modelview_matrix_stack.release();
+ cc.modelview_matrix_stack = null;
+ cc.projection_matrix_stack.release();
+ cc.projection_matrix_stack = null;
+ cc.texture_matrix_stack.release();
+ cc.texture_matrix_stack = null;
+
+ //Delete the matrices
+ cc.initialized = false; //Set to uninitialized
+ cc.current_stack = null; //Set the current stack to point nowhere
+ };
+
+ cc.kmGLPushMatrix = function () {
+ cc.current_stack.push(cc.current_stack.top);
+ };
+
+ cc.kmGLPushMatrixWitMat4 = function (saveMat) {
+ cc.current_stack.stack.push(cc.current_stack.top);
+ saveMat.assignFrom(cc.current_stack.top);
+ cc.current_stack.top = saveMat;
+ };
+
+ cc.kmGLPopMatrix = function () {
+ //No need to lazy initialize, you shouldnt be popping first anyway!
+ //cc.km_mat4_stack_pop(cc.current_stack, null);
+ cc.current_stack.top = cc.current_stack.stack.pop();
+ };
+
+ cc.kmGLMatrixMode = function (mode) {
+ //cc.lazyInitialize();
+ switch (mode) {
+ case cc.KM_GL_MODELVIEW:
+ cc.current_stack = cc.modelview_matrix_stack;
+ break;
+ case cc.KM_GL_PROJECTION:
+ cc.current_stack = cc.projection_matrix_stack;
+ break;
+ case cc.KM_GL_TEXTURE:
+ cc.current_stack = cc.texture_matrix_stack;
+ break;
+ default:
+ throw new Error("Invalid matrix mode specified"); //TODO: Proper error handling
+ break;
+ }
+ };
+
+ cc.kmGLLoadIdentity = function () {
+ //cc.lazyInitialize();
+ cc.current_stack.top.identity(); //Replace the top matrix with the identity matrix
+ };
+
+ cc.kmGLLoadMatrix = function (pIn) {
+ //cc.lazyInitialize();
+ cc.current_stack.top.assignFrom(pIn);
+ };
+
+ cc.kmGLMultMatrix = function (pIn) {
+ //cc.lazyInitialize();
+ cc.current_stack.top.multiply(pIn);
+ };
+
+ var tempMatrix = new cc.math.Matrix4(); //an internal matrix
+ cc.kmGLTranslatef = function (x, y, z) {
+ //Create a rotation matrix using translation
+ var translation = cc.math.Matrix4.createByTranslation(x, y, z, tempMatrix);
+
+ //Multiply the rotation matrix by the current matrix
+ cc.current_stack.top.multiply(translation);
+ };
+
+ var tempVector3 = new cc.math.Vec3();
+ cc.kmGLRotatef = function (angle, x, y, z) {
+ tempVector3.fill(x, y, z);
+ //Create a rotation matrix using the axis and the angle
+ var rotation = cc.math.Matrix4.createByAxisAndAngle(tempVector3, cc.degreesToRadians(angle), tempMatrix);
+
+ //Multiply the rotation matrix by the current matrix
+ cc.current_stack.top.multiply(rotation);
+ };
+
+ cc.kmGLScalef = function (x, y, z) {
+ var scaling = cc.math.Matrix4.createByScale(x, y, z, tempMatrix);
+ cc.current_stack.top.multiply(scaling);
+ };
+
+ cc.kmGLGetMatrix = function (mode, pOut) {
+ //cc.lazyInitialize();
+ switch (mode) {
+ case cc.KM_GL_MODELVIEW:
+ pOut.assignFrom(cc.modelview_matrix_stack.top);
+ break;
+ case cc.KM_GL_PROJECTION:
+ pOut.assignFrom(cc.projection_matrix_stack.top);
+ break;
+ case cc.KM_GL_TEXTURE:
+ pOut.assignFrom(cc.texture_matrix_stack.top);
+ break;
+ default:
+ throw new Error("Invalid matrix mode specified"); //TODO: Proper error handling
+ break;
+ }
+ };
+})(cc);
diff --git a/cocos2d/kazmath/mat3.js b/cocos2d/kazmath/mat3.js
new file mode 100644
index 0000000000..aa04fe3d1d
--- /dev/null
+++ b/cocos2d/kazmath/mat3.js
@@ -0,0 +1,344 @@
+/**
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2008, Luke Benstead.
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without modification,
+ are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+window.Uint16Array = window.Uint16Array || window.Array;
+window.Float32Array = window.Float32Array || window.Array;
+(function(cc){
+ cc.math.Matrix3 = function(mat3) {
+ if (mat3 && mat3.mat) {
+ this.mat = new Float32Array(mat3.mat);
+ } else {
+ this.mat = new Float32Array(9);
+ }
+ };
+ cc.kmMat3 = cc.math.Matrix3;
+ var proto = cc.math.Matrix3.prototype;
+
+ proto.fill = function(mat3) { //cc.kmMat3Fill
+ var mat = this.mat, matIn = mat3.mat;
+ mat[0] = matIn[0];
+ mat[1] = matIn[1];
+ mat[2] = matIn[2];
+ mat[3] = matIn[3];
+ mat[4] = matIn[4];
+ mat[5] = matIn[5];
+ mat[6] = matIn[6];
+ mat[7] = matIn[7];
+ mat[8] = matIn[8];
+ return this;
+ };
+
+ proto.adjugate = function(){ //= cc.kmMat3Adjugate
+ var mat = this.mat;
+ var m0 = mat[0], m1 = mat[1], m2 = mat[2], m3 = mat[3], m4 = mat[4],
+ m5 = mat[5], m6 = mat[6], m7 = mat[7], m8 = mat[8];
+ mat[0] = m4 * m8 - m5 * m7;
+ mat[1] = m2 * m7 - m1 * m8;
+ mat[2] = m1 * m5 - m2 * m4;
+ mat[3] = m5 * m6 - m3 * m8;
+ mat[4] = m0 * m8 - m2 * m6;
+ mat[5] = m2 * m3 - m0 * m5;
+ mat[6] = m3 * m7 - m4 * m6;
+
+ // XXX: pIn.mat[9] is invalid!
+ //mat[7] = m1 * m6 - pIn.mat[9] * m7;
+ mat[8] = m0 * m4 - m1 * m3;
+ return this;
+ };
+
+ proto.identity = function() { //cc.kmMat3Identity
+ var mat = this.mat;
+ mat[1] = mat[2] = mat[3] =
+ mat[5] = mat[6] = mat[7] = 0;
+ mat[0] = mat[4] = mat[8] = 1.0;
+ return this;
+ };
+
+ var tmpMatrix = new cc.math.Matrix3(); // internal matrix
+
+ proto.inverse = function(determinate){ //cc.kmMat3Inverse
+ if (determinate === 0.0)
+ return this;
+ tmpMatrix.assignFrom(this);
+ var detInv = 1.0 / determinate;
+ this.adjugate();
+ this.multiplyScalar(detInv);
+ return this;
+ };
+
+ proto.isIdentity = function(){ //= cc.kmMat3IsIdentity
+ var mat = this.mat;
+ return (mat[0] === 1 && mat[1] === 0 && mat[2] === 0
+ && mat[3] === 0 && mat[4] === 1 && mat[5] === 0
+ && mat[6] === 0 && mat[7] === 0 && mat[8] === 1);
+ };
+
+ proto.transpose = function(){ // cc.kmMat3Transpose
+ var mat = this.mat;
+ var m1 = mat[1], m2 = mat[2], m3 = mat[3], m5 = mat[5],
+ m6 = mat[6], m7 = mat[7];
+ // m0 = mat[0],m8 = mat[8], m4 = mat[4];
+ //mat[0] = m0;
+ //mat[8] = m8;
+ //mat[4] = m4
+ mat[1] = m3;
+ mat[2] = m6;
+ mat[3] = m1;
+ mat[5] = m7;
+ mat[6] = m2;
+ mat[7] = m5;
+ return this;
+ };
+
+ proto.determinant = function(){
+ var mat = this.mat;
+ /*
+ calculating the determinant following the rule of sarus,
+ | 0 3 6 | 0 3 |
+ m = | 1 4 7 | 1 4 |
+ | 2 5 8 | 2 5 |
+ now sum up the products of the diagonals going to the right (i.e. 0,4,8)
+ and substract the products of the other diagonals (i.e. 2,4,6)
+ */
+ var output = mat[0] * mat[4] * mat[8] + mat[1] * mat[5] * mat[6] + mat[2] * mat[3] * mat[7];
+ output -= mat[2] * mat[4] * mat[6] + mat[0] * mat[5] * mat[7] + mat[1] * mat[3] * mat[8];
+ return output;
+ };
+
+ proto.multiply = function(mat3){
+ var m1 = this.mat, m2 = mat3.mat;
+ var a0 = m1[0], a1 = m1[1], a2 = m1[2], a3 = m1[3], a4 = m1[4], a5 = m1[5],
+ a6 = m1[6], a7 = m1[7], a8 = m1[8];
+ var b0 = m2[0], b1 = m2[1], b2 = m2[2], b3 = m2[3], b4 = m2[4], b5 = m2[5],
+ b6 = m2[6], b7 = m2[7], b8 = m2[8];
+
+ m1[0] = a0 * b0 + a3 * b1 + a6 * b2;
+ m1[1] = a1 * b0 + a4 * b1 + a7 * b2;
+ m1[2] = a2 * b0 + a5 * b1 + a8 * b2;
+
+ m1[3] = a2 * b0 + a5 * b1 + a8 * b2;
+ m1[4] = a1 * b3 + a4 * b4 + a7 * b5;
+ m1[5] = a2 * b3 + a5 * b4 + a8 * b5;
+
+ m1[6] = a0 * b6 + a3 * b7 + a6 * b8;
+ m1[7] = a1 * b6 + a4 * b7 + a7 * b8;
+ m1[8] = a2 * b6 + a5 * b7 + a8 * b8;
+ return this;
+ };
+
+ proto.multiplyScalar = function(factor) {
+ var mat = this.mat;
+ mat[0] *= factor;
+ mat[1] *= factor;
+ mat[2] *= factor;
+ mat[3] *= factor;
+ mat[4] *= factor;
+ mat[5] *= factor;
+ mat[6] *= factor;
+ mat[7] *= factor;
+ mat[8] *= factor;
+ return this;
+ };
+
+ cc.math.Matrix3.rotationAxisAngle = function(axis, radians) { //cc.kmMat3RotationAxisAngle
+ var rcos = Math.cos(radians), rsin = Math.sin(radians);
+ var retMat = new cc.math.Matrix3();
+ var mat = retMat.mat;
+
+ mat[0] = rcos + axis.x * axis.x * (1 - rcos);
+ mat[1] = axis.z * rsin + axis.y * axis.x * (1 - rcos);
+ mat[2] = -axis.y * rsin + axis.z * axis.x * (1 - rcos);
+
+ mat[3] = -axis.z * rsin + axis.x * axis.y * (1 - rcos);
+ mat[4] = rcos + axis.y * axis.y * (1 - rcos);
+ mat[5] = axis.x * rsin + axis.z * axis.y * (1 - rcos);
+
+ mat[6] = axis.y * rsin + axis.x * axis.z * (1 - rcos);
+ mat[7] = -axis.x * rsin + axis.y * axis.z * (1 - rcos);
+ mat[8] = rcos + axis.z * axis.z * (1 - rcos);
+
+ return retMat;
+ };
+
+ proto.assignFrom = function(matIn){ // cc.kmMat3Assign
+ if(this === matIn) {
+ cc.log("cc.math.Matrix3.assign(): current matrix equals matIn");
+ return this;
+ }
+ var mat = this.mat, m2 = matIn.mat;
+ mat[0] = m2[0];
+ mat[1] = m2[1];
+ mat[2] = m2[2];
+ mat[3] = m2[3];
+ mat[4] = m2[4];
+ mat[5] = m2[5];
+ mat[6] = m2[6];
+ mat[7] = m2[7];
+ mat[8] = m2[8];
+ return this;
+ };
+
+ proto.equals = function(mat3) {
+ if (this === mat3)
+ return true;
+ var EPSILON = cc.math.EPSILON,m1 = this.mat, m2 = mat3.mat;
+ for (var i = 0; i < 9; ++i) {
+ if (!(m1[i] + EPSILON > m2[i] && m1[i] - EPSILON < m2[i]))
+ return false;
+ }
+ return true;
+ };
+
+ cc.math.Matrix3.createByRotationX = function(radians) {
+ var retMat = new cc.math.Matrix3(), mat = retMat.mat;
+ mat[0] = 1.0;
+ mat[1] = 0.0;
+ mat[2] = 0.0;
+
+ mat[3] = 0.0;
+ mat[4] = Math.cos(radians);
+ mat[5] = Math.sin(radians);
+
+ mat[6] = 0.0;
+ mat[7] = -Math.sin(radians);
+ mat[8] = Math.cos(radians);
+ return retMat;
+ };
+
+ cc.math.Matrix3.createByRotationY = function(radians) {
+ /*
+ | cos(A) 0 sin(A) |
+ M = | 0 1 0 |
+ | -sin(A) 0 cos(A) |
+ */
+ var retMat = new cc.math.Matrix3(), mat = retMat.mat;
+ mat[0] = Math.cos(radians);
+ mat[1] = 0.0;
+ mat[2] = -Math.sin(radians);
+
+ mat[3] = 0.0;
+ mat[4] = 1.0;
+ mat[5] = 0.0;
+
+ mat[6] = Math.sin(radians);
+ mat[7] = 0.0;
+ mat[8] = Math.cos(radians);
+ return retMat;
+ };
+
+ cc.math.Matrix3.createByRotationZ = function(radians) {
+ /*
+ | cos(A) -sin(A) 0 |
+ M = | sin(A) cos(A) 0 |
+ | 0 0 1 |
+ */
+ var retMat = new cc.math.Matrix3(), mat = retMat.mat;
+ mat[0] = Math.cos(radians);
+ mat[1] = -Math.sin(radians);
+ mat[2] = 0.0;
+
+ mat[3] = Math.sin(radians);
+ mat[4] = Math.cos(radians);
+ mat[5] = 0.0;
+
+ mat[6] = 0.0;
+ mat[7] = 0.0;
+ mat[8] = 1.0;
+ return retMat;
+ };
+
+ cc.math.Matrix3.createByRotation = function(radians) {
+ /*
+ | cos(A) -sin(A) 0 |
+ M = | sin(A) cos(A) 0 |
+ | 0 0 1 |
+ */
+ var retMat = new cc.math.Matrix3(), mat = retMat.mat;
+ mat[0] = Math.cos(radians);
+ mat[1] = Math.sin(radians);
+ mat[2] = 0.0;
+
+ mat[3] = -Math.sin(radians);
+ mat[4] = Math.cos(radians);
+ mat[5] = 0.0;
+
+ mat[6] = 0.0;
+ mat[7] = 0.0;
+ mat[8] = 1.0;
+ return retMat;
+ };
+
+ cc.math.Matrix3.createByScale = function(x, y) {
+ var ret = new cc.math.Matrix3();
+ ret.identity();
+ ret.mat[0] = x;
+ ret.mat[4] = y;
+ return ret;
+ };
+
+ cc.math.Matrix3.createByTranslation = function(x, y){
+ var ret = new cc.math.Matrix3();
+ ret.identity();
+ ret.mat[6] = x;
+ ret.mat[7] = y;
+ return ret;
+ };
+
+ cc.math.Matrix3.createByQuaternion = function(quaternion) { //cc.kmMat3RotationQuaternion
+ if(!quaternion)
+ return null;
+
+ var ret = new cc.math.Matrix3(), mat = ret.mat;
+ // First row
+ mat[0] = 1.0 - 2.0 * (quaternion.y * quaternion.y + quaternion.z * quaternion.z);
+ mat[1] = 2.0 * (quaternion.x * quaternion.y - quaternion.w * quaternion.z);
+ mat[2] = 2.0 * (quaternion.x * quaternion.z + quaternion.w * quaternion.y);
+
+ // Second row
+ mat[3] = 2.0 * (quaternion.x * quaternion.y + quaternion.w * quaternion.z);
+ mat[4] = 1.0 - 2.0 * (quaternion.x * quaternion.x + quaternion.z * quaternion.z);
+ mat[5] = 2.0 * (quaternion.y * quaternion.z - quaternion.w * quaternion.x);
+
+ // Third row
+ mat[6] = 2.0 * (quaternion.x * quaternion.z - quaternion.w * quaternion.y);
+ mat[7] = 2.0 * (quaternion.y * quaternion.z + quaternion.w * quaternion.x);
+ mat[8] = 1.0 - 2.0 * (quaternion.x * quaternion.x + quaternion.y * quaternion.y);
+ return ret;
+ };
+
+ proto.rotationToAxisAngle = function() { //cc.kmMat3RotationToAxisAngle
+ return cc.math.Quaternion.rotationMatrix(this).toAxisAndAngle();
+ }
+})(cc);
+
+
+
+
+
+
+
diff --git a/cocos2d/kazmath/mat4.js b/cocos2d/kazmath/mat4.js
new file mode 100644
index 0000000000..d211589531
--- /dev/null
+++ b/cocos2d/kazmath/mat4.js
@@ -0,0 +1,1014 @@
+/**
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2008, Luke Benstead.
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without modification,
+ are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+(function(cc) {
+ /**
+ *
+ * A 4x4 matrix
+ *
+ * mat =
+ * | 0 4 8 12 |
+ * | 1 5 9 13 |
+ * | 2 6 10 14 |
+ * | 3 7 11 15 |
+ *
+ * @param {cc.math.Matrix4} [mat4]
+ */
+ cc.math.Matrix4 = function (mat4) {
+ if(mat4 && mat4.mat){
+ this.mat = new Float32Array(mat4.mat);
+ } else {
+ this.mat = new Float32Array(16);
+ }
+ };
+ cc.kmMat4 = cc.math.Matrix4;
+ var proto = cc.math.Matrix4.prototype;
+
+ /**
+ * Fills a cc.math.Matrix4 structure with the values from a 16 element array of floats
+ * @param {Array} scalarArr
+ */
+ proto.fill = function(scalarArr){ //cc.kmMat4Fill
+ var mat = this.mat;
+ for(var i = 0; i < 16; i++){
+ mat[i] = scalarArr[i];
+ }
+ return this;
+ };
+
+ /**
+ * Sets pOut to an identity matrix returns pOut
+ * @Params pOut - A pointer to the matrix to set to identity
+ * @Return Returns pOut so that the call can be nested
+ */
+ cc.kmMat4Identity = function (pOut) {
+ var mat = pOut.mat;
+ mat[1] = mat[2] = mat[3] = mat[4] = mat[6] = mat[7]
+ = mat[8] = mat[9] = mat[11] = mat[12] = mat[13] = mat[14] = 0;
+ mat[0] = mat[5] = mat[10] = mat[15] = 1.0;
+ return pOut;
+ };
+
+ /**
+ * Sets matrix to identity value.
+ * @returns {cc.math.Matrix4}
+ */
+ proto.identity = function(){
+ var mat = this.mat;
+ mat[1] = mat[2] = mat[3] = mat[4] = mat[6] = mat[7]
+ = mat[8] = mat[9] = mat[11] = mat[12] = mat[13] = mat[14] = 0;
+ mat[0] = mat[5] = mat[10] = mat[15] = 1.0;
+ return this;
+ };
+
+ proto.get = function(row, col){
+ return this.mat[row + 4 * col];
+ };
+
+ proto.set = function(row, col, value){
+ this.mat[row + 4 * col] = value;
+ };
+
+ proto.swap = function(r1, c1, r2, c2) {
+/* var tmp = this.get(r1, c1);
+ this.set(r1, c1, this.get(r2, c2));
+ this.set(r2, c2, tmp);*/
+ var mat = this.mat, tmp = mat[r1 + 4 * c1];
+ mat[r1 + 4 * c1] = mat[r2 + 4 * c2];
+ mat[r2 + 4 * c2] = tmp;
+ };
+
+ //Returns an upper and a lower triangular matrix which are L and R in the Gauss algorithm
+ cc.math.Matrix4._gaussj = function (a, b) {
+ var i, icol = 0, irow = 0, j, k, l, ll, n = 4, m = 4, selElement;
+ var big, dum, pivinv;
+ var indxc = [0, 0, 0, 0], indxr = [0, 0, 0, 0], ipiv = [0, 0, 0, 0];
+
+ /* for (j = 0; j < n; j++) {
+ ipiv[j] = 0;
+ }*/
+
+ for (i = 0; i < n; i++) {
+ big = 0.0;
+ for (j = 0; j < n; j++) {
+ if (ipiv[j] !== 1) {
+ for (k = 0; k < n; k++) {
+ if (ipiv[k] === 0) {
+ selElement = Math.abs(a.get(j, k));
+ if (selElement >= big) {
+ big = selElement;
+ irow = j;
+ icol = k;
+ }
+ }
+ }
+ }
+ }
+ ++(ipiv[icol]);
+ if (irow !== icol) {
+ for (l = 0; l < n; l++)
+ a.swap(irow, l, icol, l);
+ for (l = 0; l < m; l++)
+ b.swap(irow, l, icol, l);
+ }
+ indxr[i] = irow;
+ indxc[i] = icol;
+ if (a.get(icol, icol) === 0.0)
+ return false;
+
+ pivinv = 1.0 / a.get(icol, icol);
+ a.set(icol, icol, 1.0);
+ for (l = 0; l < n; l++)
+ a.set(icol, l, a.get(icol, l) * pivinv);
+
+ for (l = 0; l < m; l++)
+ b.set(icol, l, b.get(icol, l) * pivinv);
+
+ for (ll = 0; ll < n; ll++) {
+ if (ll !== icol) {
+ dum = a.get(ll, icol);
+ a.set(ll, icol, 0.0);
+ for (l = 0; l < n; l++)
+ a.set(ll, l, a.get(ll, l) - a.get(icol, l) * dum);
+
+ for (l = 0; l < m; l++)
+ b.set(ll, l, a.get(ll, l) - b.get(icol, l) * dum);
+ }
+ }
+ }
+ // This is the end of the main loop over columns of the reduction. It only remains to unscram-
+ // ble the solution in view of the column interchanges. We do this by interchanging pairs of
+ // columns in the reverse order that the permutation was built up.
+ for (l = n - 1; l >= 0; l--) {
+ if (indxr[l] !== indxc[l]) {
+ for (k = 0; k < n; k++)
+ a.swap(k, indxr[l], k, indxc[l]);
+ }
+ }
+ return true;
+ };
+
+ var identityMatrix = new cc.math.Matrix4().identity();
+ /**
+ * Calculates the inverse of pM and stores the result in pOut.
+ * Please use matrix4's inverse function instead.
+ * @Return Returns NULL if there is no inverse, else pOut
+ */
+ cc.kmMat4Inverse = function (pOut, pM) {
+ var inv = new cc.math.Matrix4(pM);
+ var tmp = new cc.math.Matrix4(identityMatrix);
+ if (cc.math.Matrix4._gaussj(inv, tmp) === false)
+ return null;
+ pOut.assignFrom(inv);
+ return pOut;
+ };
+
+ /**
+ * Calculates the inverse of current matrix.
+ * @returns {cc.math.Matrix4} Returns null if there is no inverse, else returns a new inverse matrix object
+ */
+ proto.inverse = function(){ //cc.kmMat4Inverse
+ var inv = new cc.math.Matrix4(this);
+ var tmp = new cc.math.Matrix4(identityMatrix);
+ if (cc.math.Matrix4._gaussj(inv, tmp) === false)
+ return null;
+ return inv;
+ };
+
+ /**
+ * Returns true if current matrix is an identity matrix, false otherwise
+ */
+ proto.isIdentity = function () { // cc.kmMat4IsIdentity
+ var mat = this.mat;
+ return (mat[0] === 1 && mat[1] === 0 && mat[2] === 0 && mat[3] === 0
+ && mat[4] === 0 && mat[5] === 1 && mat[6] === 0 && mat[7] === 0
+ && mat[8] === 0 && mat[9] === 0 && mat[10] === 1 && mat[11] === 0
+ && mat[12] === 0 && mat[13] === 0 && mat[14] === 0 && mat[15] === 1);
+ };
+
+ /**
+ * transpose the current matrix
+ */
+ proto.transpose = function() { // cc.kmMat4Transpose
+ var mat = this.mat;
+ var m1 = mat[1], m2 = mat[2], m3 = mat[3],
+ m4 = mat[4], m6 = mat[6], m7 = mat[7],
+ m8 = mat[8], m9 = mat[9], m11 = mat[11],
+ m12 = mat[12], m13 = mat[13], m14 = mat[14];
+ mat[1] = m4;
+ mat[2] = m8;
+ mat[3] = m12;
+
+ mat[4] = m1;
+ mat[6] = m9;
+ mat[7] = m13;
+
+ mat[8] = m2;
+ mat[9] = m6;
+ mat[11] = m14;
+
+ mat[12] = m3;
+ mat[13] = m7;
+ mat[14] = m11;
+ return this;
+ };
+
+ /**
+ * Multiplies pM1 with pM2, stores the result in pOut, returns pOut
+ */
+ cc.kmMat4Multiply = function (pOut, pM1, pM2) {
+ // Cache the matrix values (makes for huge speed increases!)
+ var outArray = pOut.mat, mat1 = pM1.mat, mat2 = pM2.mat;
+ var a00 = mat1[0], a01 = mat1[1], a02 = mat1[2], a03 = mat1[3];
+ var a10 = mat1[4], a11 = mat1[5], a12 = mat1[6], a13 = mat1[7];
+ var a20 = mat1[8], a21 = mat1[9], a22 = mat1[10], a23 = mat1[11];
+ var a30 = mat1[12], a31 = mat1[13], a32 = mat1[14], a33 = mat1[15];
+
+ var b00 = mat2[0], b01 = mat2[1], b02 = mat2[2], b03 = mat2[3];
+ var b10 = mat2[4], b11 = mat2[5], b12 = mat2[6], b13 = mat2[7];
+ var b20 = mat2[8], b21 = mat2[9], b22 = mat2[10], b23 = mat2[11];
+ var b30 = mat2[12], b31 = mat2[13], b32 = mat2[14], b33 = mat2[15];
+
+ outArray[0] = b00 * a00 + b01 * a10 + b02 * a20 + b03 * a30;
+ outArray[1] = b00 * a01 + b01 * a11 + b02 * a21 + b03 * a31;
+ outArray[2] = b00 * a02 + b01 * a12 + b02 * a22 + b03 * a32;
+ outArray[3] = b00 * a03 + b01 * a13 + b02 * a23 + b03 * a33;
+ outArray[4] = b10 * a00 + b11 * a10 + b12 * a20 + b13 * a30;
+ outArray[5] = b10 * a01 + b11 * a11 + b12 * a21 + b13 * a31;
+ outArray[6] = b10 * a02 + b11 * a12 + b12 * a22 + b13 * a32;
+ outArray[7] = b10 * a03 + b11 * a13 + b12 * a23 + b13 * a33;
+ outArray[8] = b20 * a00 + b21 * a10 + b22 * a20 + b23 * a30;
+ outArray[9] = b20 * a01 + b21 * a11 + b22 * a21 + b23 * a31;
+ outArray[10] = b20 * a02 + b21 * a12 + b22 * a22 + b23 * a32;
+ outArray[11] = b20 * a03 + b21 * a13 + b22 * a23 + b23 * a33;
+ outArray[12] = b30 * a00 + b31 * a10 + b32 * a20 + b33 * a30;
+ outArray[13] = b30 * a01 + b31 * a11 + b32 * a21 + b33 * a31;
+ outArray[14] = b30 * a02 + b31 * a12 + b32 * a22 + b33 * a32;
+ outArray[15] = b30 * a03 + b31 * a13 + b32 * a23 + b33 * a33;
+ return pOut;
+ };
+
+ /**
+ * current matrix multiplies with other matrix mat4
+ * @param {cc.math.Matrix4} mat4
+ * @returns {cc.math.Matrix4}
+ */
+ proto.multiply = function(mat4){
+ // Cache the matrix values (makes for huge speed increases!)
+ var mat = this.mat, mat2 = mat4.mat;
+ var a00 = mat[0], a01 = mat[1], a02 = mat[2], a03 = mat[3];
+ var a10 = mat[4], a11 = mat[5], a12 = mat[6], a13 = mat[7];
+ var a20 = mat[8], a21 = mat[9], a22 = mat[10], a23 = mat[11];
+ var a30 = mat[12], a31 = mat[13], a32 = mat[14], a33 = mat[15];
+
+ var b00 = mat2[0], b01 = mat2[1], b02 = mat2[2], b03 = mat2[3];
+ var b10 = mat2[4], b11 = mat2[5], b12 = mat2[6], b13 = mat2[7];
+ var b20 = mat2[8], b21 = mat2[9], b22 = mat2[10], b23 = mat2[11];
+ var b30 = mat2[12], b31 = mat2[13], b32 = mat2[14], b33 = mat2[15];
+
+ mat[0] = b00 * a00 + b01 * a10 + b02 * a20 + b03 * a30;
+ mat[1] = b00 * a01 + b01 * a11 + b02 * a21 + b03 * a31;
+ mat[2] = b00 * a02 + b01 * a12 + b02 * a22 + b03 * a32;
+ mat[3] = b00 * a03 + b01 * a13 + b02 * a23 + b03 * a33;
+ mat[4] = b10 * a00 + b11 * a10 + b12 * a20 + b13 * a30;
+ mat[5] = b10 * a01 + b11 * a11 + b12 * a21 + b13 * a31;
+ mat[6] = b10 * a02 + b11 * a12 + b12 * a22 + b13 * a32;
+ mat[7] = b10 * a03 + b11 * a13 + b12 * a23 + b13 * a33;
+ mat[8] = b20 * a00 + b21 * a10 + b22 * a20 + b23 * a30;
+ mat[9] = b20 * a01 + b21 * a11 + b22 * a21 + b23 * a31;
+ mat[10] = b20 * a02 + b21 * a12 + b22 * a22 + b23 * a32;
+ mat[11] = b20 * a03 + b21 * a13 + b22 * a23 + b23 * a33;
+ mat[12] = b30 * a00 + b31 * a10 + b32 * a20 + b33 * a30;
+ mat[13] = b30 * a01 + b31 * a11 + b32 * a21 + b33 * a31;
+ mat[14] = b30 * a02 + b31 * a12 + b32 * a22 + b33 * a32;
+ mat[15] = b30 * a03 + b31 * a13 + b32 * a23 + b33 * a33;
+ return this;
+ };
+
+ cc.getMat4MultiplyValue = function (pM1, pM2) {
+ var m1 = pM1.mat, m2 = pM2.mat;
+ var mat = new Float32Array(16);
+
+ mat[0] = m1[0] * m2[0] + m1[4] * m2[1] + m1[8] * m2[2] + m1[12] * m2[3];
+ mat[1] = m1[1] * m2[0] + m1[5] * m2[1] + m1[9] * m2[2] + m1[13] * m2[3];
+ mat[2] = m1[2] * m2[0] + m1[6] * m2[1] + m1[10] * m2[2] + m1[14] * m2[3];
+ mat[3] = m1[3] * m2[0] + m1[7] * m2[1] + m1[11] * m2[2] + m1[15] * m2[3];
+
+ mat[4] = m1[0] * m2[4] + m1[4] * m2[5] + m1[8] * m2[6] + m1[12] * m2[7];
+ mat[5] = m1[1] * m2[4] + m1[5] * m2[5] + m1[9] * m2[6] + m1[13] * m2[7];
+ mat[6] = m1[2] * m2[4] + m1[6] * m2[5] + m1[10] * m2[6] + m1[14] * m2[7];
+ mat[7] = m1[3] * m2[4] + m1[7] * m2[5] + m1[11] * m2[6] + m1[15] * m2[7];
+
+ mat[8] = m1[0] * m2[8] + m1[4] * m2[9] + m1[8] * m2[10] + m1[12] * m2[11];
+ mat[9] = m1[1] * m2[8] + m1[5] * m2[9] + m1[9] * m2[10] + m1[13] * m2[11];
+ mat[10] = m1[2] * m2[8] + m1[6] * m2[9] + m1[10] * m2[10] + m1[14] * m2[11];
+ mat[11] = m1[3] * m2[8] + m1[7] * m2[9] + m1[11] * m2[10] + m1[15] * m2[11];
+
+ mat[12] = m1[0] * m2[12] + m1[4] * m2[13] + m1[8] * m2[14] + m1[12] * m2[15];
+ mat[13] = m1[1] * m2[12] + m1[5] * m2[13] + m1[9] * m2[14] + m1[13] * m2[15];
+ mat[14] = m1[2] * m2[12] + m1[6] * m2[13] + m1[10] * m2[14] + m1[14] * m2[15];
+ mat[15] = m1[3] * m2[12] + m1[7] * m2[13] + m1[11] * m2[14] + m1[15] * m2[15];
+
+ return mat;
+ };
+
+ /**
+ * Assigns the value of pIn to pOut
+ */
+ cc.kmMat4Assign = function (pOut, pIn) {
+ if (pOut === pIn) {
+ cc.log("cc.kmMat4Assign(): pOut equals pIn");
+ return pOut;
+ }
+
+ var outArr = pOut.mat;
+ var inArr = pIn.mat;
+
+ outArr[0] = inArr[0];
+ outArr[1] = inArr[1];
+ outArr[2] = inArr[2];
+ outArr[3] = inArr[3];
+
+ outArr[4] = inArr[4];
+ outArr[5] = inArr[5];
+ outArr[6] = inArr[6];
+ outArr[7] = inArr[7];
+
+ outArr[8] = inArr[8];
+ outArr[9] = inArr[9];
+ outArr[10] = inArr[10];
+ outArr[11] = inArr[11];
+
+ outArr[12] = inArr[12];
+ outArr[13] = inArr[13];
+ outArr[14] = inArr[14];
+ outArr[15] = inArr[15];
+ return pOut;
+ };
+
+ /**
+ * Assigns the value of current matrix from mat4
+ * @param {cc.math.Matrix4} mat4
+ * @returns {cc.math.Matrix4}
+ */
+ proto.assignFrom = function(mat4) {
+ if (this === mat4) {
+ cc.log("cc.mat.Matrix4.assignFrom(): mat4 equals current matrix");
+ return this;
+ }
+ var outArr = this.mat, inArr = mat4.mat;
+
+ outArr[0] = inArr[0];
+ outArr[1] = inArr[1];
+ outArr[2] = inArr[2];
+ outArr[3] = inArr[3];
+
+ outArr[4] = inArr[4];
+ outArr[5] = inArr[5];
+ outArr[6] = inArr[6];
+ outArr[7] = inArr[7];
+
+ outArr[8] = inArr[8];
+ outArr[9] = inArr[9];
+ outArr[10] = inArr[10];
+ outArr[11] = inArr[11];
+
+ outArr[12] = inArr[12];
+ outArr[13] = inArr[13];
+ outArr[14] = inArr[14];
+ outArr[15] = inArr[15];
+ return this;
+ };
+
+ /**
+ * Returns true if current matrix equal mat4 (approximately)
+ * @param {cc.math.Matrix4} mat4
+ * @returns {boolean}
+ */
+ proto.equals = function(mat4) {
+ if (this === mat4) {
+ cc.log("cc.kmMat4AreEqual(): pMat1 and pMat2 are same object.");
+ return true;
+ }
+ var matA = this.mat, matB = mat4.mat, EPSILON = cc.math.EPSILON;
+ for (var i = 0; i < 16; i++) {
+ if (!(matA[i] + EPSILON > matB[i] && matA[i] - EPSILON < matB[i]))
+ return false;
+ }
+ return true;
+ };
+
+ /**
+ * Builds an X-axis rotation matrix and stores it in matrix, returns matrix, if matrix is null, create a new matrix
+ * @param {Number} radians
+ * @param {cc.math.Matrix4} [matrix]
+ * @returns {cc.math.Matrix4}
+ */
+ cc.math.Matrix4.createByRotationX = function(radians, matrix) { //cc.kmMat4RotationX
+ /*
+ | 1 0 0 0 |
+ M = | 0 cos(A) -sin(A) 0 |
+ | 0 sin(A) cos(A) 0 |
+ | 0 0 0 1 |
+ */
+ matrix = matrix || new cc.math.Matrix4();
+ var mat = matrix.mat;
+ mat[0] = 1.0;
+ mat[3] = mat[2] = mat[1] = 0.0;
+
+ mat[4] = 0.0;
+ mat[5] = Math.cos(radians);
+ mat[6] = Math.sin(radians);
+ mat[7] = 0.0;
+
+ mat[8] = 0.0;
+ mat[9] = -Math.sin(radians);
+ mat[10] = Math.cos(radians);
+ mat[11] = 0.0;
+
+ mat[14] = mat[13] = mat[12] = 0.0;
+ mat[15] = 1.0;
+ return matrix;
+ };
+
+ /**
+ * Builds a rotation matrix using the rotation around the Y-axis, The result is stored in matrix, matrix is returned.
+ * @param {Number} radians
+ * @param {cc.math.Matrix4} [matrix]
+ * @returns {*}
+ */
+ cc.math.Matrix4.createByRotationY = function(radians, matrix) { // cc.kmMat4RotationY
+ /*
+ | cos(A) 0 sin(A) 0 |
+ M = | 0 1 0 0 |
+ | -sin(A) 0 cos(A) 0 |
+ | 0 0 0 1 |
+ */
+ matrix = matrix || new cc.math.Matrix4();
+ var mat = matrix.mat;
+ mat[0] = Math.cos(radians);
+ mat[1] = 0.0;
+ mat[2] = -Math.sin(radians);
+ mat[3] = 0.0;
+
+ mat[7] = mat[6] = mat[4] = 0.0;
+ mat[5] = 1.0;
+
+ mat[8] = Math.sin(radians);
+ mat[9] = 0.0;
+ mat[10] = Math.cos(radians);
+ mat[11] = 0.0;
+
+ mat[14] = mat[13] = mat[12] = 0.0;
+ mat[15] = 1.0;
+ return matrix;
+ };
+
+ /**
+ * Builds a rotation matrix around the Z-axis. The resulting matrix is stored in matrix. matrix is returned.
+ * @param {Number} radians
+ * @param {cc.math.Matrix4} matrix
+ * @return {cc.math.Matrix4}
+ */
+ cc.math.Matrix4.createByRotationZ = function(radians, matrix){ // cc.kmMat4RotationZ
+ /*
+ | cos(A) -sin(A) 0 0 |
+ M = | sin(A) cos(A) 0 0 |
+ | 0 0 1 0 |
+ | 0 0 0 1 |
+ */
+ matrix = matrix || new cc.math.Matrix4();
+ var mat = matrix.mat;
+ mat[0] = Math.cos(radians);
+ mat[1] = Math.sin(radians);
+ mat[3] = mat[2] = 0.0;
+
+ mat[4] = -Math.sin(radians);
+ mat[5] = Math.cos(radians);
+ mat[7] = mat[6] = 0.0;
+
+ mat[11] = mat[9] = mat[8] = 0.0;
+ mat[10] = 1.0;
+
+ mat[14] = mat[13] = mat[12] = 0.0;
+ mat[15] = 1.0;
+
+ return matrix;
+ };
+
+ /**
+ * Builds a rotation matrix from pitch, yaw and roll. The resulting matrix is stored in parameter matrix and returns.
+ * @param {Number} pitch
+ * @param {Number} yaw
+ * @param {Number} roll
+ * @param {cc.math.Matrix4} [matrix] if matrix is undefined, creates a new matrix.
+ * @returns {cc.math.Matrix4}
+ */
+ cc.math.Matrix4.createByPitchYawRoll = function(pitch, yaw, roll, matrix) {
+ matrix = matrix || new cc.math.Matrix4();
+ var cr = Math.cos(pitch), sr = Math.sin(pitch);
+ var cp = Math.cos(yaw), sp = Math.sin(yaw);
+ var cy = Math.cos(roll), sy = Math.sin(roll);
+ var srsp = sr * sp, crsp = cr * sp;
+ var mat = matrix.mat;
+
+ mat[0] = cp * cy;
+ mat[4] = cp * sy;
+ mat[8] = -sp;
+
+ mat[1] = srsp * cy - cr * sy;
+ mat[5] = srsp * sy + cr * cy;
+ mat[9] = sr * cp;
+
+ mat[2] = crsp * cy + sr * sy;
+ mat[6] = crsp * sy - sr * cy;
+ mat[10] = cr * cp;
+
+ mat[3] = mat[7] = mat[11] = 0.0;
+ mat[15] = 1.0;
+ return matrix;
+ };
+
+ /**
+ * Builds a matrix by a quaternion.
+ * @param {cc.math.Quaternion} quaternion
+ * @param {cc.math.Matrix4} [matrix] if matrix is undefined, creates a new matrix.
+ * @returns {cc.math.Matrix4}
+ */
+ cc.math.Matrix4.createByQuaternion = function(quaternion, matrix) {
+ matrix = matrix || new cc.math.Matrix4();
+ var mat = matrix.mat;
+ mat[0] = 1.0 - 2.0 * (quaternion.y * quaternion.y + quaternion.z * quaternion.z );
+ mat[1] = 2.0 * (quaternion.x * quaternion.y + quaternion.z * quaternion.w);
+ mat[2] = 2.0 * (quaternion.x * quaternion.z - quaternion.y * quaternion.w);
+ mat[3] = 0.0;
+
+ // Second row
+ mat[4] = 2.0 * ( quaternion.x * quaternion.y - quaternion.z * quaternion.w );
+ mat[5] = 1.0 - 2.0 * ( quaternion.x * quaternion.x + quaternion.z * quaternion.z );
+ mat[6] = 2.0 * (quaternion.z * quaternion.y + quaternion.x * quaternion.w );
+ mat[7] = 0.0;
+
+ // Third row
+ mat[8] = 2.0 * ( quaternion.x * quaternion.z + quaternion.y * quaternion.w );
+ mat[9] = 2.0 * ( quaternion.y * quaternion.z - quaternion.x * quaternion.w );
+ mat[10] = 1.0 - 2.0 * ( quaternion.x * quaternion.x + quaternion.y * quaternion.y );
+ mat[11] = 0.0;
+
+ // Fourth row
+ mat[14] = mat[13] = mat[12] = 0;
+ mat[15] = 1.0;
+ return matrix;
+ };
+
+ /**
+ * Build a 4x4 OpenGL transformation matrix using a 3x3 rotation matrix, and a 3d vector representing a translation.
+ * @param {cc.math.Matrix3} rotation
+ * @param {cc.math.Vec3} translation
+ * @param {cc.math.Matrix4} [matrix] if matrix is undefined, creates a new matrix.
+ * @returns {cc.math.Matrix4}
+ */
+ cc.math.Matrix4.createByRotationTranslation = function(rotation, translation, matrix) {
+ matrix = matrix || new cc.math.Matrix4();
+ var mat = matrix.mat, rMat = rotation.mat;
+ mat[0] = rMat[0];
+ mat[1] = rMat[1];
+ mat[2] = rMat[2];
+ mat[3] = 0.0;
+
+ mat[4] = rMat[3];
+ mat[5] = rMat[4];
+ mat[6] = rMat[5];
+ mat[7] = 0.0;
+
+ mat[8] = rMat[6];
+ mat[9] = rMat[7];
+ mat[10] = rMat[8];
+ mat[11] = 0.0;
+
+ mat[12] = translation.x;
+ mat[13] = translation.y;
+ mat[14] = translation.z;
+ mat[15] = 1.0;
+ return matrix;
+ };
+
+ /**
+ * Builds a scaling matrix
+ * @param {Number} x
+ * @param {Number} y
+ * @param {Number} z
+ * @param {cc.math.Matrix4} [matrix] if matrix is undefined, creates a new matrix.
+ * @returns {cc.math.Matrix4}
+ */
+ cc.math.Matrix4.createByScale = function(x, y, z, matrix) { //cc.kmMat4Scaling
+ matrix = matrix || new cc.math.Matrix4();
+ var mat = matrix.mat;
+ mat[0] = x;
+ mat[5] = y;
+ mat[10] = z;
+ mat[15] = 1.0;
+ mat[1] = mat[2] = mat[3] = mat[4] = mat[6] = mat[7] =
+ mat[8] = mat[9] = mat[11] = mat[12] = mat[13] = mat[14] = 0;
+ return matrix;
+ };
+
+ /**
+ * Builds a translation matrix. All other elements in the matrix
+ * will be set to zero except for the diagonal which is set to 1.0
+ */
+ cc.kmMat4Translation = function (pOut, x, y, z) {
+ //FIXME: Write a test for this
+ pOut.mat[0] = pOut.mat[5] = pOut.mat[10] = pOut.mat[15] = 1.0;
+ pOut.mat[1] = pOut.mat[2] = pOut.mat[3] =
+ pOut.mat[4] = pOut.mat[6] = pOut.mat[7] =
+ pOut.mat[8] = pOut.mat[9] = pOut.mat[11] = 0.0;
+ pOut.mat[12] = x;
+ pOut.mat[13] = y;
+ pOut.mat[14] = z;
+ return pOut;
+ };
+
+ /**
+ * Builds a translation matrix.
+ * @param {Number} x
+ * @param {Number} y
+ * @param {Number} z
+ * @param {cc.math.Matrix4} [matrix] if matrix is undefined, creates a new matrix.
+ * @returns {cc.math.Matrix4}
+ */
+ cc.math.Matrix4.createByTranslation = function(x, y, z, matrix){ //cc.kmMat4Translation
+ matrix = matrix || new cc.math.Matrix4();
+ matrix.identity();
+ matrix.mat[12] = x;
+ matrix.mat[13] = y;
+ matrix.mat[14] = z;
+ return matrix;
+ };
+
+ /**
+ * Get the up vector from a matrix.
+ * @returns {cc.math.Vec3}
+ */
+ proto.getUpVec3 = function() {
+ var mat = this.mat;
+ var ret = new cc.math.Vec3(mat[4],mat[5], mat[6]);
+ return ret.normalize();
+ };
+
+ /**
+ * Extract the right vector from a 4x4 matrix.
+ * @returns {cc.math.Vec3}
+ */
+ proto.getRightVec3 = function(){
+ var mat = this.mat;
+ var ret = new cc.math.Vec3(mat[0],mat[1], mat[2]);
+ return ret.normalize();
+ };
+
+ /**
+ * Extract the forward vector from a 4x4 matrix.
+ * @returns {cc.math.Vec3}
+ */
+ proto.getForwardVec3 = function() {
+ var mat = this.mat;
+ var ret = new cc.math.Vec3(mat[8],mat[9], mat[10]);
+ return ret.normalize();
+ };
+
+ /**
+ * Creates a perspective projection matrix in the
+ * same way as gluPerspective
+ */
+ cc.kmMat4PerspectiveProjection = function (pOut, fovY, aspect, zNear, zFar) {
+ var r = cc.degreesToRadians(fovY / 2);
+ var deltaZ = zFar - zNear;
+ var s = Math.sin(r);
+
+ if (deltaZ === 0 || s === 0 || aspect === 0)
+ return null;
+
+ //cos(r) / sin(r) = cot(r)
+ var cotangent = Math.cos(r) / s;
+ pOut.identity();
+ pOut.mat[0] = cotangent / aspect;
+ pOut.mat[5] = cotangent;
+ pOut.mat[10] = -(zFar + zNear) / deltaZ;
+ pOut.mat[11] = -1;
+ pOut.mat[14] = -2 * zNear * zFar / deltaZ;
+ pOut.mat[15] = 0;
+
+ return pOut;
+ };
+
+ /**
+ * Creates a perspective projection matrix in the same way as gluPerspective
+ * @param {Number} fovY
+ * @param {Number} aspect
+ * @param {Number} zNear
+ * @param {Number} zFar
+ * @returns {cc.math.Matrix4|Null}
+ */
+ cc.math.Matrix4.createPerspectiveProjection = function(fovY, aspect, zNear, zFar){
+ var r = cc.degreesToRadians(fovY / 2), deltaZ = zFar - zNear;
+ var s = Math.sin(r);
+
+ if (deltaZ === 0 || s === 0 || aspect === 0)
+ return null;
+
+ //cos(r) / sin(r) = cot(r)
+ var cotangent = Math.cos(r) / s;
+ var matrix = new cc.math.Matrix4(), mat = matrix.mat;
+ matrix.identity();
+ mat[0] = cotangent / aspect;
+ mat[5] = cotangent;
+ mat[10] = -(zFar + zNear) / deltaZ;
+ mat[11] = -1;
+ mat[14] = -2 * zNear * zFar / deltaZ;
+ mat[15] = 0;
+ return matrix;
+ };
+
+ /** Creates an orthographic projection matrix like glOrtho */
+ cc.kmMat4OrthographicProjection = function (pOut, left, right, bottom, top, nearVal, farVal) {
+ pOut.identity();
+ pOut.mat[0] = 2 / (right - left);
+ pOut.mat[5] = 2 / (top - bottom);
+ pOut.mat[10] = -2 / (farVal - nearVal);
+ pOut.mat[12] = -((right + left) / (right - left));
+ pOut.mat[13] = -((top + bottom) / (top - bottom));
+ pOut.mat[14] = -((farVal + nearVal) / (farVal - nearVal));
+ return pOut;
+ };
+
+ /**
+ * Creates an orthographic projection matrix like glOrtho
+ * @param {Number} left
+ * @param {Number} right
+ * @param {Number} bottom
+ * @param {Number} top
+ * @param {Number} nearVal
+ * @param {Number} farVal
+ * @returns {cc.math.Matrix4}
+ */
+ cc.math.Matrix4.createOrthographicProjection = function (left, right, bottom, top, nearVal, farVal) {
+ var matrix = new cc.math.Matrix4(), mat = matrix.mat;
+ matrix.identity();
+ mat[0] = 2 / (right - left);
+ mat[5] = 2 / (top - bottom);
+ mat[10] = -2 / (farVal - nearVal);
+ mat[12] = -((right + left) / (right - left));
+ mat[13] = -((top + bottom) / (top - bottom));
+ mat[14] = -((farVal + nearVal) / (farVal - nearVal));
+ return matrix;
+ };
+
+ /**
+ * Builds a translation matrix in the same way as gluLookAt()
+ * the resulting matrix is stored in pOut. pOut is returned.
+ */
+ cc.kmMat4LookAt = function (pOut, pEye, pCenter, pUp) {
+ var f = new cc.math.Vec3(pCenter), up = new cc.math.Vec3(pUp);
+ f.subtract(pEye);
+ f.normalize();
+ up.normalize();
+
+ var s = new cc.math.Vec3(f);
+ s.cross(up);
+ s.normalize();
+
+ var u = new cc.math.Vec3(s);
+ u.cross(f);
+ s.normalize();
+
+ pOut.identity();
+
+ pOut.mat[0] = s.x;
+ pOut.mat[4] = s.y;
+ pOut.mat[8] = s.z;
+
+ pOut.mat[1] = u.x;
+ pOut.mat[5] = u.y;
+ pOut.mat[9] = u.z;
+
+ pOut.mat[2] = -f.x;
+ pOut.mat[6] = -f.y;
+ pOut.mat[10] = -f.z;
+
+ var translate = cc.math.Matrix4.createByTranslation(-pEye.x, -pEye.y, -pEye.z);
+ pOut.multiply(translate);
+ return pOut;
+ };
+
+ var tempMatrix = new cc.math.Matrix4(); // an internal matrix
+ proto.lookAt = function(eyeVec, centerVec, upVec) {
+ var f = new cc.math.Vec3(centerVec), up = new cc.math.Vec3(upVec), mat = this.mat;
+ f.subtract(eyeVec);
+ f.normalize();
+ up.normalize();
+
+ var s = new cc.math.Vec3(f);
+ s.cross(up);
+ s.normalize();
+
+ var u = new cc.math.Vec3(s);
+ u.cross(f);
+ s.normalize();
+
+ this.identity();
+ mat[0] = s.x;
+ mat[4] = s.y;
+ mat[8] = s.z;
+
+ mat[1] = u.x;
+ mat[5] = u.y;
+ mat[9] = u.z;
+
+ mat[2] = -f.x;
+ mat[6] = -f.y;
+ mat[10] = -f.z;
+
+ tempMatrix = cc.math.Matrix4.createByTranslation(-eyeVec.x, -eyeVec.y, -eyeVec.z, tempMatrix);
+ this.multiply(tempMatrix);
+ return this;
+ };
+
+ /**
+ * Build a rotation matrix from an axis and an angle. Result is stored in pOut.
+ * pOut is returned.
+ */
+ cc.kmMat4RotationAxisAngle = function (pOut, axis, radians) {
+ var rcos = Math.cos(radians), rsin = Math.sin(radians);
+
+ var normalizedAxis = new cc.math.Vec3(axis);
+ normalizedAxis.normalize();
+
+ pOut.mat[0] = rcos + normalizedAxis.x * normalizedAxis.x * (1 - rcos);
+ pOut.mat[1] = normalizedAxis.z * rsin + normalizedAxis.y * normalizedAxis.x * (1 - rcos);
+ pOut.mat[2] = -normalizedAxis.y * rsin + normalizedAxis.z * normalizedAxis.x * (1 - rcos);
+ pOut.mat[3] = 0.0;
+
+ pOut.mat[4] = -normalizedAxis.z * rsin + normalizedAxis.x * normalizedAxis.y * (1 - rcos);
+ pOut.mat[5] = rcos + normalizedAxis.y * normalizedAxis.y * (1 - rcos);
+ pOut.mat[6] = normalizedAxis.x * rsin + normalizedAxis.z * normalizedAxis.y * (1 - rcos);
+ pOut.mat[7] = 0.0;
+
+ pOut.mat[8] = normalizedAxis.y * rsin + normalizedAxis.x * normalizedAxis.z * (1 - rcos);
+ pOut.mat[9] = -normalizedAxis.x * rsin + normalizedAxis.y * normalizedAxis.z * (1 - rcos);
+ pOut.mat[10] = rcos + normalizedAxis.z * normalizedAxis.z * (1 - rcos);
+ pOut.mat[11] = 0.0;
+
+ pOut.mat[12] = 0.0;
+ pOut.mat[13] = 0.0;
+ pOut.mat[14] = 0.0;
+ pOut.mat[15] = 1.0;
+
+ return pOut;
+ };
+
+ /**
+ * Build a rotation matrix from an axis and an angle.
+ * @param {cc.math.Vec3} axis
+ * @param {Number} radians
+ * @param {cc.math.Matrix4} [matrix]
+ * @returns {cc.math.Matrix4}
+ */
+ cc.math.Matrix4.createByAxisAndAngle = function(axis, radians, matrix) {
+ matrix = matrix || new cc.math.Matrix4();
+ var mat = this.mat, rcos = Math.cos(radians), rsin = Math.sin(radians) ;
+
+ var normalizedAxis = new cc.math.Vec3(axis);
+ normalizedAxis.normalize();
+
+ mat[0] = rcos + normalizedAxis.x * normalizedAxis.x * (1 - rcos);
+ mat[1] = normalizedAxis.z * rsin + normalizedAxis.y * normalizedAxis.x * (1 - rcos);
+ mat[2] = -normalizedAxis.y * rsin + normalizedAxis.z * normalizedAxis.x * (1 - rcos);
+ mat[3] = 0.0;
+
+ mat[4] = -normalizedAxis.z * rsin + normalizedAxis.x * normalizedAxis.y * (1 - rcos);
+ mat[5] = rcos + normalizedAxis.y * normalizedAxis.y * (1 - rcos);
+ mat[6] = normalizedAxis.x * rsin + normalizedAxis.z * normalizedAxis.y * (1 - rcos);
+ mat[7] = 0.0;
+
+ mat[8] = normalizedAxis.y * rsin + normalizedAxis.x * normalizedAxis.z * (1 - rcos);
+ mat[9] = -normalizedAxis.x * rsin + normalizedAxis.y * normalizedAxis.z * (1 - rcos);
+ mat[10] = rcos + normalizedAxis.z * normalizedAxis.z * (1 - rcos);
+ mat[11] = 0.0;
+
+ mat[12] = mat[13] = mat[14] = 0.0;
+ mat[15] = 1.0;
+ return matrix;
+ };
+
+ /**
+ * Extract a 3x3 rotation matrix from the input 4x4 transformation.
+ * @returns {cc.math.Matrix3}
+ */
+ proto.extractRotation = function(){
+ var matrix = new cc.math.Matrix3(), mat4 = this.mat, mat3 = matrix.mat;
+ mat3[0] = mat4[0];
+ mat3[1] = mat4[1];
+ mat3[2] = mat4[2];
+
+ mat3[3] = mat4[4];
+ mat3[4] = mat4[5];
+ mat3[5] = mat4[6];
+
+ mat3[6] = mat4[8];
+ mat3[7] = mat4[9];
+ mat3[8] = mat4[10];
+ return matrix;
+ };
+
+ proto.extractPlane = function(planeType) {
+ var plane = new cc.math.Plane(), mat = this.mat;
+ switch (planeType) {
+ case cc.math.Plane.RIGHT:
+ plane.a = mat[3] - mat[0];
+ plane.b = mat[7] - mat[4];
+ plane.c = mat[11] - mat[8];
+ plane.d = mat[15] - mat[12];
+ break;
+ case cc.math.Plane.LEFT:
+ plane.a = mat[3] + mat[0];
+ plane.b = mat[7] + mat[4];
+ plane.c = mat[11] + mat[8];
+ plane.d = mat[15] + mat[12];
+ break;
+ case cc.math.Plane.BOTTOM:
+ plane.a = mat[3] + mat[1];
+ plane.b = mat[7] + mat[5];
+ plane.c = mat[11] + mat[9];
+ plane.d = mat[15] + mat[13];
+ break;
+ case cc.math.Plane.TOP:
+ plane.a = mat[3] - mat[1];
+ plane.b = mat[7] - mat[5];
+ plane.c = mat[11] - mat[9];
+ plane.d = mat[15] - mat[13];
+ break;
+ case cc.math.Plane.FAR:
+ plane.a = mat[3] - mat[2];
+ plane.b = mat[7] - mat[6];
+ plane.c = mat[11] - mat[10];
+ plane.d = mat[15] - mat[14];
+ break;
+ case cc.math.Plane.NEAR:
+ plane.a = mat[3] + mat[2];
+ plane.b = mat[7] + mat[6];
+ plane.c = mat[11] + mat[10];
+ plane.d = mat[15] + mat[14];
+ break;
+ default:
+ cc.log("cc.math.Matrix4.extractPlane: Invalid plane index");
+ break;
+ }
+
+ var t = Math.sqrt(plane.a * plane.a + plane.b * plane.b + plane.c * plane.c);
+ plane.a /= t;
+ plane.b /= t;
+ plane.c /= t;
+ plane.d /= t;
+ return plane;
+ };
+
+ /**
+ * Take the rotation from a 4x4 transformation matrix, and return it as an axis and an angle (in radians)
+ * @returns {*|{axis: cc.math.Vec3, angle: number}}
+ */
+ proto.toAxisAndAngle = function() {
+ /*Surely not this easy?*/
+ var rotation = this.extractRotation();
+ var temp = cc.math.Quaternion.rotationMatrix(rotation);
+ return temp.toAxisAndAngle();
+ };
+})(cc);
+
+
+
+
diff --git a/cocos2d/kazmath/mat4SIMD.js b/cocos2d/kazmath/mat4SIMD.js
new file mode 100644
index 0000000000..f716de796b
--- /dev/null
+++ b/cocos2d/kazmath/mat4SIMD.js
@@ -0,0 +1,428 @@
+/**
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2008, Luke Benstead.
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without modification,
+ are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+(function(cc) {
+ var proto = cc.math.Matrix4.prototype;
+
+ cc.kmMat4InverseSIMD = function (pOut, pM) {
+ pOut = pM.inverseSIMD();
+ return pOut;
+ };
+
+ proto.inverseSIMD = function(){
+ var inv = new cc.math.Matrix4();
+ var src = this.mat;
+ var dest = inv.mat;
+ var src0, src1, src2, src3;
+ var row0, row1, row2, row3;
+ var tmp1;
+ var minor0, minor1, minor2, minor3;
+ var det;
+
+ // Load the 4 rows
+ var src0 = SIMD.float32x4.load(src, 0);
+ var src1 = SIMD.float32x4.load(src, 4);
+ var src2 = SIMD.float32x4.load(src, 8);
+ var src3 = SIMD.float32x4.load(src, 12);
+
+ // Transpose the source matrix. Sort of. Not a true transpose operation
+
+ tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
+ row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
+ row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
+ row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
+
+ tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
+ row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
+ row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
+ row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
+
+ // ----
+ tmp1 = SIMD.float32x4.mul(row2, row3);
+ tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
+ minor0 = SIMD.float32x4.mul(row1, tmp1);
+ minor1 = SIMD.float32x4.mul(row0, tmp1);
+ tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
+ minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
+ minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
+ minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
+
+ // ----
+ tmp1 = SIMD.float32x4.mul(row1, row2);
+ tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
+ minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
+ minor3 = SIMD.float32x4.mul(row0, tmp1);
+ tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
+ minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
+ minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
+ minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
+
+ // ----
+ tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
+ tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
+ row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
+ minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
+ minor2 = SIMD.float32x4.mul(row0, tmp1);
+ tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
+ minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
+ minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
+ minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
+
+ // ----
+ tmp1 = SIMD.float32x4.mul(row0, row1);
+ tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
+ minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
+ minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
+ tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
+ minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
+ minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
+
+ // ----
+ tmp1 = SIMD.float32x4.mul(row0, row3);
+ tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
+ minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
+ minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
+ tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
+ minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
+ minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
+
+ // ----
+ tmp1 = SIMD.float32x4.mul(row0, row2);
+ tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
+ minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
+ minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
+ tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
+ minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
+ minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
+
+ // Compute determinant
+ det = SIMD.float32x4.mul(row0, minor0);
+ det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
+ det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
+ tmp1 = SIMD.float32x4.reciprocalApproximation(det);
+ det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
+ det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
+
+ // Compute final values by multiplying with 1/det
+ minor0 = SIMD.float32x4.mul(det, minor0);
+ minor1 = SIMD.float32x4.mul(det, minor1);
+ minor2 = SIMD.float32x4.mul(det, minor2);
+ minor3 = SIMD.float32x4.mul(det, minor3);
+
+ SIMD.float32x4.store(dest, 0, minor0);
+ SIMD.float32x4.store(dest, 4, minor1);
+ SIMD.float32x4.store(dest, 8, minor2);
+ SIMD.float32x4.store(dest, 12, minor3);
+
+ return inv;
+ };
+
+ var identityMatrix = new cc.math.Matrix4().identity();
+ proto.isIdentitySIMD = function () {
+ var inx4 = SIMD.float32x4.load(this.mat, 0);
+ var identityx4 = SIMD.float32x4.load(identityMatrix.mat, 0);
+ var ret = SIMD.float32x4.equal(inx4, identityx4);
+ if(ret.signMask === 0x00)
+ return false;
+
+ inx4 = SIMD.float32x4.load(this.mat, 4);
+ identityx4 = SIMD.float32x4.load(identityMatrix.mat, 4);
+ ret = SIMD.float32x4.equal(inx4, identityx4);
+ if(ret.signMask === 0x00)
+ return false;
+
+ inx4 = SIMD.float32x4.load(this.mat, 8);
+ identityx4 = SIMD.float32x4.load(identityMatrix.mat, 8);
+ ret = SIMD.float32x4.equal(inx4, identityx4);
+ if(ret.signMask === 0x00)
+ return false;
+
+ inx4 = SIMD.float32x4.load(this.mat, 12);
+ identityx4 = SIMD.float32x4.load(identityMatrix.mat, 12);
+ ret = SIMD.float32x4.equal(inx4, identityx4);
+ if(ret.signMask === 0x00)
+ return false;
+ return true;
+ };
+
+ proto.transposeSIMD = function () {
+ var outArr = this.mat, inArr = this.mat;
+ var src0 = SIMD.float32x4.load(inArr, 0);
+ var src1 = SIMD.float32x4.load(inArr, 4);
+ var src2 = SIMD.float32x4.load(inArr, 8);
+ var src3 = SIMD.float32x4.load(inArr, 12);
+ var dst0;
+ var dst1;
+ var dst2;
+ var dst3;
+ var tmp01;
+ var tmp23;
+
+ tmp01 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
+ tmp23 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
+ dst0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
+ dst1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
+
+ tmp01 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
+ tmp23 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
+ dst2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
+ dst3 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
+
+ SIMD.float32x4.store(outArr, 0, dst0);
+ SIMD.float32x4.store(outArr, 4, dst1);
+ SIMD.float32x4.store(outArr, 8, dst2);
+ SIMD.float32x4.store(outArr, 12, dst3);
+ return this;
+ };
+
+ cc.kmMat4MultiplySIMD = function (pOut, pM1, pM2) {
+ pOut = new cc.math.Matrix4(pM1);
+ return pOut.multiplySIMD(pM2);
+ };
+
+ proto.multiplySIMD = function(mat4) {
+ var a = this.mat;
+ var b = mat4.mat;
+ var out = this.mat;
+
+ var a0 = SIMD.float32x4.load(a,0);
+ var a1 = SIMD.float32x4.load(a,4);
+ var a2 = SIMD.float32x4.load(a,8);
+ var a3 = SIMD.float32x4.load(a,12);
+ var b0 = SIMD.float32x4.load(b, 0);
+ SIMD.float32x4.store(out, 0, SIMD.float32x4.add(
+ SIMD.float32x4.mul(
+ SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0),
+ SIMD.float32x4.add(
+ SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1),
+ SIMD.float32x4.add(
+ SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2),
+ SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
+ var b1 = SIMD.float32x4.load(b, 4);
+ SIMD.float32x4.store(out, 4, SIMD.float32x4.add(
+ SIMD.float32x4.mul(
+ SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0),
+ SIMD.float32x4.add(
+ SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1),
+ SIMD.float32x4.add(
+ SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2),
+ SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
+ var b2 = SIMD.float32x4.load(b, 8);
+ SIMD.float32x4.store(out, 8, SIMD.float32x4.add(
+ SIMD.float32x4.mul(
+ SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0),
+ SIMD.float32x4.add(
+ SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1),
+ SIMD.float32x4.add(
+ SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2),
+ SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
+ var b3 = SIMD.float32x4.load(b, 12);
+ SIMD.float32x4.store(out, 12, SIMD.float32x4.add(
+ SIMD.float32x4.mul(
+ SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0),
+ SIMD.float32x4.add(
+ SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1),
+ SIMD.float32x4.add(
+ SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2),
+ SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
+
+ return this;
+ };
+
+ cc.getMat4MultiplyValueSIMD = function (pM1, pM2) {
+ var mat = new cc.math.Matrix4(pM1);
+ return mat.multiplySIMD(pM2);
+ };
+
+ cc.kmMat4AssignSIMD = function (pOut, pIn) {
+ if(pOut == pIn) {
+ cc.log("cc.kmMat4Assign(): pOut equals pIn");//TODO: ADD SIMD?
+ return pOut;
+ }
+
+ return pOut.assignFromSIMD(pIn);
+ };
+
+ proto.assignFromSIMD = function (mat4) {
+ if(this == mat4) {
+ cc.log("cc.mat.Matrix4.assignFrom(): mat4 equals current matrix");//TODO: ADD SIMD?
+ return this;
+ }
+
+ var outArr = this.mat;
+ var inArr = mat4.mat;
+
+ SIMD.float32x4.store(outArr, 0, SIMD.float32x4.load(inArr, 0));
+ SIMD.float32x4.store(outArr, 4, SIMD.float32x4.load(inArr, 4));
+ SIMD.float32x4.store(outArr, 8, SIMD.float32x4.load(inArr, 8));
+ SIMD.float32x4.store(outArr, 12, SIMD.float32x4.load(inArr, 12));
+
+ return this;
+ };
+
+ proto.equalsSIMD = function (mat4) {
+ if(this === mat4){
+ cc.log("cc.kmMat4AreEqual(): pMat1 and pMat2 are same object.");
+ return true;
+ }
+ var m10 = SIMD.float32x4.load(this.mat, 0);
+ var m20 = SIMD.float32x4.load(mat4.mat, 0);
+
+ var epsilon = SIMD.float32x4.splat(cc.math.EPSILON);
+
+ var ret = SIMD.float32x4.lessThanOrEqual(SIMD.float32x4.abs(SIMD.float32x4.sub(m10, m20)), epsilon);
+ if (ret.signMask === 0)
+ return false;
+
+ var m11 = SIMD.float32x4.load(this.mat, 4);
+ var m21 = SIMD.float32x4.load(mat4.mat, 4);
+ ret = SIMD.float32x4.lessThanOrEqual(SIMD.float32x4.abs(SIMD.float32x4.sub(m11, m21)), epsilon);
+ if (ret.signMask === 0)
+ return false;
+
+ var m12 = SIMD.float32x4.load(this.mat, 8);
+ var m22 = SIMD.float32x4.load(mat4.mat, 8);
+ ret = SIMD.float32x4.lessThanOrEqual(SIMD.float32x4.abs(SIMD.float32x4.sub(m12, m22)), epsilon);
+ if (ret.signMask === 0)
+ return false;
+
+ var m13 = SIMD.float32x4.load(this.mat, 12);
+ var m23 = SIMD.float32x4.load(mat4.mat, 12);
+ ret = SIMD.float32x4.lessThanOrEqual(SIMD.float32x4.abs(SIMD.float32x4.sub(m13, m23)), epsilon);
+ if (ret.signMask === 0)
+ return false;
+ return true;
+ };
+
+ cc.kmMat4LookAtSIMD = function (pOut, pEye, pCenter, pUp) {
+ return pOut.lookAtSIMD(pEye, pCenter, pUp);
+ };
+
+ proto.lookAtSIMD = function(eyeVec, centerVec, upVec) {
+ var out = this.mat;
+
+ var center = SIMD.float32x4(centerVec.x, centerVec.y, centerVec.z, 0.0);
+ var eye = SIMD.float32x4(eyeVec.x, eyeVec.y, eyeVec.z, 0.0);
+ var up = SIMD.float32x4(upVec.x, upVec.y, upVec.z, 0.0);
+
+ // cc.kmVec3Subtract(f, pCenter, pEye);
+ var f = SIMD.float32x4.sub(center, eye);
+ // cc.kmVec3Normalize(f, f);
+ var tmp = SIMD.float32x4.mul(f, f);
+ tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
+ f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
+
+ // cc.kmVec3Assign(up, pUp);
+ // cc.kmVec3Normalize(up, up);
+ tmp = SIMD.float32x4.mul(up, up);
+ tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
+ up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
+
+ // cc.kmVec3Cross(s, f, up);
+ var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)),
+ SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3)));
+ // cc.kmVec3Normalize(s, s);
+ tmp = SIMD.float32x4.mul(s, s);
+ tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
+ s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
+
+ // cc.kmVec3Cross(u, s, f);
+ var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)),
+ SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3)));
+ // cc.kmVec3Normalize(s, s);
+ tmp = SIMD.float32x4.mul(s, s);
+ tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
+ s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
+
+ //cc.kmMat4Identity(pOut);
+ //pOut.mat[0] = s.x;
+ //pOut.mat[4] = s.y;
+ //pOut.mat[8] = s.z;
+ //pOut.mat[1] = u.x;
+ //pOut.mat[5] = u.y;
+ //pOut.mat[9] = u.z;
+ //pOut.mat[2] = -f.x;
+ //pOut.mat[6] = -f.y;
+ //pOut.mat[10] = -f.z;
+ var zero = SIMD.float32x4.splat(0.0);
+ f = SIMD.float32x4.neg(f);
+ var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
+ var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
+ var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
+ var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
+
+ var tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
+ var tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
+ var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
+ var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
+
+ // cc.kmMat4Translation(translate, -pEye.x, -pEye.y, -pEye.z);
+ var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
+ var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
+ var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
+ var b3 = SIMD.float32x4.neg(eye);
+ b3 = SIMD.float32x4.withW(b3, 1.0);
+
+ // cc.kmMat4Multiply(pOut, pOut, translate);
+ SIMD.float32x4.store(out, 0, SIMD.float32x4.add(
+ SIMD.float32x4.mul(
+ SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0),
+ SIMD.float32x4.add(
+ SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1),
+ SIMD.float32x4.add(
+ SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2),
+ SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
+ SIMD.float32x4.store(out, 4, SIMD.float32x4.add(
+ SIMD.float32x4.mul(
+ SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0),
+ SIMD.float32x4.add(
+ SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1),
+ SIMD.float32x4.add(
+ SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2),
+ SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
+ SIMD.float32x4.store(out, 8, SIMD.float32x4.add(
+ SIMD.float32x4.mul(
+ SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0),
+ SIMD.float32x4.add(
+ SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1),
+ SIMD.float32x4.add(
+ SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2),
+ SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
+ SIMD.float32x4.store(out, 12, SIMD.float32x4.add(
+ SIMD.float32x4.mul(
+ SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0),
+ SIMD.float32x4.add(
+ SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1),
+ SIMD.float32x4.add(
+ SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2),
+ SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
+ return this;
+ };
+
+
+})(cc);
diff --git a/cocos2d/kazmath/plane.js b/cocos2d/kazmath/plane.js
new file mode 100644
index 0000000000..94ab4e9b71
--- /dev/null
+++ b/cocos2d/kazmath/plane.js
@@ -0,0 +1,137 @@
+/**
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2008, Luke Benstead.
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without modification,
+ are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * @ignore
+ */
+(function(cc){
+ cc.math.Plane = function (a, b, c, d) {
+ if (a && b === undefined) {
+ this.a = a.a;
+ this.b = a.b;
+ this.c = a.c;
+ this.d = a.d;
+ } else {
+ this.a = a || 0;
+ this.b = b || 0;
+ this.c = c || 0;
+ this.d = d || 0;
+ }
+ };
+ cc.kmPlane = cc.math.Plane;
+ var proto = cc.math.Plane.prototype;
+
+ cc.math.Plane.LEFT = 0;
+
+ cc.math.Plane.RIGHT = 1;
+
+ cc.math.Plane.BOTTOM = 2;
+
+ cc.math.Plane.TOP = 3;
+
+ cc.math.Plane.NEAR = 4;
+
+ cc.math.Plane.FAR = 5;
+
+ cc.math.Plane.POINT_INFRONT_OF_PLANE = 0;
+
+ cc.math.Plane.POINT_BEHIND_PLANE = 1;
+
+ cc.math.Plane.POINT_ON_PLANE = 2;
+
+ proto.dot = function(vec4){ //cc.kmPlaneDot
+ return (this.a * vec4.x + this.b * vec4.y + this.c * vec4.z + this.d * vec4.w);
+ };
+
+ proto.dotCoord = function(vec3) { //=cc.kmPlaneDotCoord
+ return (this.a * vec3.x + this.b * vec3.y + this.c * vec3.z + this.d);
+ };
+
+ proto.dotNormal = function(vec3) { //=cc.kmPlaneDotNormal
+ return (this.a * vec3.x + this.b * vec3.y + this.c * vec3.z);
+ };
+
+ cc.math.Plane.fromPointNormal = function(vec3, normal) { //cc.kmPlaneFromPointNormal
+ /*
+ Planea = Nx
+ Planeb = Ny
+ Planec = Nz
+ Planed = âNâ
P
+ */
+ return new cc.math.Plane(normal.x, normal.y, normal.z, -normal.dot(vec3));
+ };
+
+ cc.math.Plane.fromPoints = function(vec1, vec2, vec3) { //cc.kmPlaneFromPoints
+ /*
+ v = (B â A) Ă (C â A)
+ n = 1â|v| v
+ Outa = nx
+ Outb = ny
+ Outc = nz
+ Outd = ânâ
A
+ */
+ var v1 = new cc.math.Vec3(vec2), v2 = new cc.math.Vec3(vec3), plane = new cc.math.Plane();
+ v1.subtract(vec1); //Create the vectors for the 2 sides of the triangle
+ v2.subtract(vec1);
+ v1.cross(v2); // Use the cross product to get the normal
+ v1.normalize(); //Normalize it and assign to pOut.m_N
+
+ plane.a = v1.x;
+ plane.b = v1.y;
+ plane.c = v1.z;
+ plane.d = v1.scale(-1.0).dot(vec1);
+ return plane;
+ };
+
+ proto.normalize = function(){ //cc.kmPlaneNormalize
+ var n = new cc.math.Vec3(this.a, this.b, this.c), l = 1.0 / n.length(); //Get 1/length
+ n.normalize(); //Normalize the vector and assign to pOut
+ this.a = n.x;
+ this.b = n.y;
+ this.c = n.z;
+ this.d = this.d * l; //Scale the D value and assign to pOut
+ return this;
+ };
+
+ proto.classifyPoint = function(vec3) {
+ // This function will determine if a point is on, in front of, or behind
+ // the plane. First we store the dot product of the plane and the point.
+ var distance = this.a * vec3.x + this.b * vec3.y + this.c * vec3.z + this.d;
+
+ // Simply put if the dot product is greater than 0 then it is infront of it.
+ // If it is less than 0 then it is behind it. And if it is 0 then it is on it.
+ if(distance > 0.001)
+ return cc.math.Plane.POINT_INFRONT_OF_PLANE;
+ if(distance < -0.001)
+ return cc.math.Plane.POINT_BEHIND_PLANE;
+ return cc.math.Plane.POINT_ON_PLANE;
+ };
+})(cc);
+
+
+
diff --git a/cocos2d/kazmath/quaternion.js b/cocos2d/kazmath/quaternion.js
new file mode 100644
index 0000000000..fcbd652da9
--- /dev/null
+++ b/cocos2d/kazmath/quaternion.js
@@ -0,0 +1,459 @@
+/**
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2008, Luke Benstead.
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without modification,
+ are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+(function(cc) {
+ /**
+ * The Quaternion class
+ * @param {Number|cc.math.Quaternion} [x=0]
+ * @param {Number} [y=0]
+ * @param {Number} [z=0]
+ * @param {Number} [w=0]
+ * @constructor
+ */
+ cc.math.Quaternion = function (x, y, z, w) {
+ if (x && y === undefined) {
+ this.x = x.x;
+ this.y = x.y;
+ this.z = x.z;
+ this.w = x.w;
+ } else {
+ this.x = x || 0;
+ this.y = y || 0;
+ this.z = z || 0;
+ this.w = w || 0;
+ }
+ };
+ cc.kmQuaternion = cc.math.Quaternion;
+ var proto = cc.math.Quaternion.prototype;
+
+ /**
+ * Sets the conjugate of quaternion to self
+ * @param {cc.math.Quaternion} quaternion
+ */
+ proto.conjugate = function (quaternion) { //= cc.kmQuaternionConjugate
+ this.x = -quaternion.x;
+ this.y = -quaternion.y;
+ this.z = -quaternion.z;
+ this.w = quaternion.w;
+ return this;
+ };
+
+ /**
+ * Returns the dot product of the current quaternion and parameter quaternion
+ * @param quaternion
+ * @returns {number}
+ */
+ proto.dot = function(quaternion) { // = cc.kmQuaternionDot
+ // A dot B = B dot A = AtBt + AxBx + AyBy + AzBz
+ return (this.w * quaternion.w + this.x * quaternion.x + this.y * quaternion.y + this.z * quaternion.z);
+ };
+
+ /**
+ * Returns the exponential of the quaternion, this function doesn't implemented.
+ * @returns {cc.math.Quaternion}
+ */
+ proto.exponential = function(){ //=cc.kmQuaternionExp
+ return this;
+ };
+
+ /**
+ * Makes the current quaternion an identity quaternion
+ */
+ proto.identity = function(){ //=cc.kmQuaternionIdentity
+ this.x = 0.0;
+ this.y = 0.0;
+ this.z = 0.0;
+ this.w = 1.0;
+ return this;
+ };
+
+ /**
+ * Inverses the value of current Quaternion
+ */
+ proto.inverse = function(){ //=cc.kmQuaternionInverse
+ var len = this.length();
+ if (Math.abs(len) > cc.math.EPSILON) {
+ this.x = 0.0;
+ this.y = 0.0;
+ this.z = 0.0;
+ this.w = 0.0;
+ return this;
+ }
+
+ ///Get the conjugute and divide by the length
+ this.conjugate(this).scale(1.0 / len);
+ return this;
+ };
+
+ /**
+ * Returns true if the quaternion is an identity quaternion
+ * @returns {boolean}
+ */
+ proto.isIdentity = function(){ //=cc.kmQuaternionIsIdentity
+ return (this.x === 0.0 && this.y === 0.0 && this.z === 0.0 && this.w === 1.0);
+ };
+
+ /**
+ * Returns the length of the quaternion
+ * @returns {number}
+ */
+ proto.length = function() { //=cc.kmQuaternionLength
+ return Math.sqrt(this.lengthSq());
+ };
+
+ /**
+ * Returns the length of the quaternion squared (prevents a sqrt)
+ * @returns {number}
+ */
+ proto.lengthSq = function() { //=cc.kmQuaternionLengthSq
+ return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
+ };
+
+ /**
+ * Uses current quaternion multiplies other quaternion.
+ * @param {cc.math.Quaternion} quaternion
+ * @returns {cc.math.Quaternion}
+ */
+ proto.multiply = function(quaternion) { //cc.kmQuaternionMultiply
+ var x = this.x, y = this.y, z = this.z, w = this.w;
+ this.w = w * quaternion.w - x * quaternion.x - y * quaternion.y - z * quaternion.z;
+ this.x = w * quaternion.x + x * quaternion.w + y * quaternion.z - z * quaternion.y;
+ this.y = w * quaternion.y + y * quaternion.w + z * quaternion.x - x * quaternion.z;
+ this.z = w * quaternion.z + z * quaternion.w + x * quaternion.y - y * quaternion.x;
+ return this;
+ };
+
+ /**
+ * Normalizes a quaternion
+ * @returns {cc.math.Quaternion}
+ */
+ proto.normalize = function(){ //=cc.kmQuaternionNormalize
+ var length = this.length();
+ if (Math.abs(length) <= cc.math.EPSILON)
+ throw new Error("current quaternion is an invalid value");
+ this.scale(1.0 / length);
+ return this;
+ };
+
+ /**
+ * Rotates a quaternion around an axis and an angle
+ * @param {cc.math.Vec3} axis
+ * @param {Number} angle
+ */
+ proto.rotationAxis = function(axis, angle){ //cc.kmQuaternionRotationAxis
+ var rad = angle * 0.5, scale = Math.sin(rad);
+ this.w = Math.cos(rad);
+ this.x = axis.x * scale;
+ this.y = axis.y * scale;
+ this.z = axis.z * scale;
+ return this;
+ };
+
+ /**
+ * Creates a quaternion from a rotation matrix
+ * @param mat3
+ * @returns {*}
+ */
+ cc.math.Quaternion.rotationMatrix = function (mat3) { //cc.kmQuaternionRotationMatrix
+ if (!mat3)
+ return null;
+
+ var x, y, z, w;
+ var m4x4 = [], mat = mat3.mat, scale = 0.0;
+
+ /* 0 3 6
+ 1 4 7
+ 2 5 8
+
+ 0 1 2 3
+ 4 5 6 7
+ 8 9 10 11
+ 12 13 14 15*/
+ m4x4[0] = mat[0];
+ m4x4[1] = mat[3];
+ m4x4[2] = mat[6];
+ m4x4[4] = mat[1];
+ m4x4[5] = mat[4];
+ m4x4[6] = mat[7];
+ m4x4[8] = mat[2];
+ m4x4[9] = mat[5];
+ m4x4[10] = mat[8];
+ m4x4[15] = 1;
+ var pMatrix = m4x4[0];
+
+ var diagonal = pMatrix[0] + pMatrix[5] + pMatrix[10] + 1;
+ if (diagonal > cc.math.EPSILON) {
+ // Calculate the scale of the diagonal
+ scale = Math.sqrt(diagonal) * 2;
+
+ // Calculate the x, y, x and w of the quaternion through the respective equation
+ x = ( pMatrix[9] - pMatrix[6] ) / scale;
+ y = ( pMatrix[2] - pMatrix[8] ) / scale;
+ z = ( pMatrix[4] - pMatrix[1] ) / scale;
+ w = 0.25 * scale;
+ } else {
+ // If the first element of the diagonal is the greatest value
+ if (pMatrix[0] > pMatrix[5] && pMatrix[0] > pMatrix[10]) {
+ // Find the scale according to the first element, and double that value
+ scale = Math.sqrt(1.0 + pMatrix[0] - pMatrix[5] - pMatrix[10]) * 2.0;
+
+ // Calculate the x, y, x and w of the quaternion through the respective equation
+ x = 0.25 * scale;
+ y = (pMatrix[4] + pMatrix[1] ) / scale;
+ z = (pMatrix[2] + pMatrix[8] ) / scale;
+ w = (pMatrix[9] - pMatrix[6] ) / scale;
+ }
+ // Else if the second element of the diagonal is the greatest value
+ else if (pMatrix[5] > pMatrix[10]) {
+ // Find the scale according to the second element, and double that value
+ scale = Math.sqrt(1.0 + pMatrix[5] - pMatrix[0] - pMatrix[10]) * 2.0;
+
+ // Calculate the x, y, x and w of the quaternion through the respective equation
+ x = (pMatrix[4] + pMatrix[1] ) / scale;
+ y = 0.25 * scale;
+ z = (pMatrix[9] + pMatrix[6] ) / scale;
+ w = (pMatrix[2] - pMatrix[8] ) / scale;
+ } else {
+ // Else the third element of the diagonal is the greatest value
+
+ // Find the scale according to the third element, and double that value
+ scale = Math.sqrt(1.0 + pMatrix[10] - pMatrix[0] - pMatrix[5]) * 2.0;
+
+ // Calculate the x, y, x and w of the quaternion through the respective equation
+ x = (pMatrix[2] + pMatrix[8] ) / scale;
+ y = (pMatrix[9] + pMatrix[6] ) / scale;
+ z = 0.25 * scale;
+ w = (pMatrix[4] - pMatrix[1] ) / scale;
+ }
+ }
+ return new cc.math.Quaternion(x, y, z, w);
+ };
+
+ /**
+ * Create a quaternion from yaw, pitch and roll
+ * @param yaw
+ * @param pitch
+ * @param roll
+ * @returns {cc.math.Quaternion}
+ */
+ cc.math.Quaternion.rotationYawPitchRoll = function (yaw, pitch, roll) { //cc.kmQuaternionRotationYawPitchRoll
+ var ex, ey, ez; // temp half euler angles
+ var cr, cp, cy, sr, sp, sy, cpcy, spsy; // temp vars in roll,pitch yaw
+
+ ex = cc.degreesToRadians(pitch) / 2.0; // convert to rads and half them
+ ey = cc.degreesToRadians(yaw) / 2.0;
+ ez = cc.degreesToRadians(roll) / 2.0;
+
+ cr = Math.cos(ex);
+ cp = Math.cos(ey);
+ cy = Math.cos(ez);
+
+ sr = Math.sin(ex);
+ sp = Math.sin(ey);
+ sy = Math.sin(ez);
+
+ cpcy = cp * cy;
+ spsy = sp * sy;
+
+ var ret = new cc.math.Quaternion();
+ ret.w = cr * cpcy + sr * spsy;
+ ret.x = sr * cpcy - cr * spsy;
+ ret.y = cr * sp * cy + sr * cp * sy;
+ ret.z = cr * cp * sy - sr * sp * cy;
+ ret.normalize();
+ return ret;
+ };
+
+ /**
+ * Interpolate with other quaternions
+ * @param {cc.math.Quaternion} quaternion
+ * @param {Number} t
+ * @returns {cc.math.Quaternion}
+ */
+ proto.slerp = function(quaternion, t) { //=cc.kmQuaternionSlerp
+ if (this.x === quaternion.x && this.y === quaternion.y && this.z === quaternion.z && this.w === quaternion.w) {
+ return this;
+ }
+ var ct = this.dot(quaternion), theta = Math.acos(ct), st = Math.sqrt(1.0 - cc.math.square(ct));
+ var stt = Math.sin(t * theta) / st, somt = Math.sin((1.0 - t) * theta) / st;
+ var temp2 = new cc.math.Quaternion(quaternion);
+ this.scale(somt);
+ temp2.scale(stt);
+ this.add(temp2);
+ return this;
+ };
+
+ /**
+ * Get the axis and angle of rotation from a quaternion
+ * @returns {{axis: cc.math.Vec3, angle: number}}
+ */
+ proto.toAxisAndAngle = function(){ //=cc.kmQuaternionToAxisAngle
+ var tempAngle; // temp angle
+ var scale; // temp vars
+ var retAngle, retAxis = new cc.math.Vec3();
+
+ tempAngle = Math.acos(this.w);
+ scale = Math.sqrt(cc.math.square(this.x) + cc.math.square(this.y) + cc.math.square(this.z));
+
+ if (((scale > -cc.math.EPSILON) && scale < cc.math.EPSILON)
+ || (scale < 2 * Math.PI + cc.math.EPSILON && scale > 2 * Math.PI - cc.math.EPSILON)) { // angle is 0 or 360 so just simply set axis to 0,0,1 with angle 0
+ retAngle = 0.0;
+ retAxis.x = 0.0;
+ retAxis.y = 0.0;
+ retAxis.z = 1.0;
+ } else {
+ retAngle = tempAngle * 2.0; // angle in radians
+ retAxis.x = this.x / scale;
+ retAxis.y = this.y / scale;
+ retAxis.z = this.z / scale;
+ retAxis.normalize();
+ }
+ return {axis: retAxis, angle: retAngle};
+ };
+
+ /**
+ * Scale a quaternion
+ * @param {Number} scale
+ */
+ proto.scale = function(scale) { //cc.kmQuaternionScale
+ this.x *= scale;
+ this.y *= scale;
+ this.z *= scale;
+ this.w *= scale;
+ return this;
+ };
+
+ /**
+ * Assign current quaternion value from a quaternion.
+ * @param {cc.math.Quaternion} quaternion
+ * @returns {cc.math.Quaternion} current quaternion
+ */
+ proto.assignFrom = function(quaternion){ //=cc.kmQuaternionAssign
+ this.x = quaternion.x;
+ this.y = quaternion.y;
+ this.z = quaternion.z;
+ this.w = quaternion.w;
+ return this;
+ };
+
+ /**
+ * Adds other quaternion
+ * @param {cc.math.Quaternion} quaternion
+ * @returns {cc.math.Quaternion}
+ */
+ proto.add = function(quaternion) { //cc.kmQuaternionAdd
+ this.x += quaternion.x;
+ this.y += quaternion.y;
+ this.z += quaternion.z;
+ this.w += quaternion.w;
+ return this;
+ };
+
+ /**
+ *
+ * Adapted from the OGRE engine!
+ * Gets the shortest arc quaternion to rotate this vector to the destination vector.
+ * @remarks
+ * If you call this with a destination vector that is close to the inverse
+ * of this vector, we will rotate 180 degrees around the 'fallbackAxis'
+ * (if specified, or a generated axis if not) since in this case ANY axis of rotation is valid.
+ *
+ * @param {cc.math.Vec3} vec1
+ * @param {cc.math.Vec3} vec2
+ * @param {cc.math.Vec3} fallback
+ * @returns {cc.math.Quaternion}
+ */
+ cc.math.Quaternion.rotationBetweenVec3 = function(vec1, vec2, fallback) { //cc.kmQuaternionRotationBetweenVec3
+ var v1 = new cc.math.Vec3(vec1), v2 = new cc.math.Vec3(vec2);
+ v1.normalize();
+ v2.normalize();
+ var a = v1.dot(v2), quaternion = new cc.math.Quaternion();
+
+ if (a >= 1.0) {
+ quaternion.identity();
+ return quaternion;
+ }
+
+ if (a < (1e-6 - 1.0)) {
+ if (Math.abs(fallback.lengthSq()) < cc.math.EPSILON) {
+ quaternion.rotationAxis(fallback, Math.PI);
+ } else {
+ var axis = new cc.math.Vec3(1.0, 0.0, 0.0);
+ axis.cross(vec1);
+
+ //If axis is zero
+ if (Math.abs(axis.lengthSq()) < cc.math.EPSILON) {
+ axis.fill(0.0, 1.0, 0.0);
+ axis.cross(vec1);
+ }
+ axis.normalize();
+ quaternion.rotationAxis(axis, Math.PI);
+ }
+ } else {
+ var s = Math.sqrt((1 + a) * 2), invs = 1 / s;
+ v1.cross(v2);
+ quaternion.x = v1.x * invs;
+ quaternion.y = v1.y * invs;
+ quaternion.z = v1.z * invs;
+ quaternion.w = s * 0.5;
+ quaternion.normalize();
+ }
+ return quaternion;
+ };
+
+ /**
+ * Current quaternion multiplies a vec3
+ * @param {cc.math.Vec3} vec
+ * @returns {cc.math.Vec3}
+ */
+ proto.multiplyVec3 = function(vec){ //=cc.kmQuaternionMultiplyVec3
+ var x = this.x, y = this.y, z = this.z, retVec = new cc.math.Vec3(vec);
+ var uv = new cc.math.Vec3(x, y, z), uuv = new cc.math.Vec3(x, y, z);
+ uv.cross(vec);
+ uuv.cross(uv);
+ uv.scale((2.0 * q.w));
+ uuv.scale(2.0);
+
+ retVec.add(uv);
+ retVec.add(uuv);
+ return retVec;
+ };
+})(cc);
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/cocos2d/kazmath/ray2.js b/cocos2d/kazmath/ray2.js
new file mode 100644
index 0000000000..5a29794e88
--- /dev/null
+++ b/cocos2d/kazmath/ray2.js
@@ -0,0 +1,140 @@
+/**
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2008, Luke Benstead.
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without modification,
+ are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+(function(cc){
+ cc.math.Ray2 = function (start, dir) { // = cc.kmRay2
+ this.start = start || new cc.math.Vec2();
+ this.dir = dir || new cc.math.Vec2();
+ };
+
+ cc.math.Ray2.prototype.fill = function (px, py, vx, vy) { // = cc.kmRay2Fill
+ this.start.x = px;
+ this.start.y = py;
+ this.dir.x = vx;
+ this.dir.y = vy;
+ };
+
+ cc.math.Ray2.prototype.intersectLineSegment = function (p1, p2, intersection) { // = cc.kmRay2IntersectLineSegment
+ var x1 = this.start.x, y1 = this.start.y;
+ var x2 = this.start.x + this.dir.x, y2 = this.start.y + this.dir.y;
+ var x3 = p1.x, y3 = p1.y;
+ var x4 = p2.x, y4 = p2.y;
+
+ var denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1);
+ var ua, x, y;
+ //If denom is zero, the lines are parallel
+ if (denom > -cc.math.EPSILON && denom < cc.math.EPSILON)
+ return false;
+
+ ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / denom;
+ //var ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / denom;
+
+ x = x1 + ua * (x2 - x1);
+ y = y1 + ua * (y2 - y1);
+
+ if (x < Math.min(p1.x, p2.x) - cc.math.EPSILON ||
+ x > Math.max(p1.x, p2.x) + cc.math.EPSILON ||
+ y < Math.min(p1.y, p2.y) - cc.math.EPSILON ||
+ y > Math.max(p1.y, p2.y) + cc.math.EPSILON) {
+ //Outside of line
+ //printf("Outside of line, %f %f (%f %f)(%f, %f)\n", x, y, p1.x, p1.y, p2.x, p2.y);
+ return false;
+ }
+
+ if (x < Math.min(x1, x2) - cc.math.EPSILON ||
+ x > Math.max(x1, x2) + cc.math.EPSILON ||
+ y < Math.min(y1, y2) - cc.math.EPSILON ||
+ y > Math.max(y1, y2) + cc.math.EPSILON) {
+ //printf("Outside of ray, %f %f (%f %f)(%f, %f)\n", x, y, x1, y1, x2, y2);
+ return false;
+ }
+
+ intersection.x = x;
+ intersection.y = y;
+ return true;
+ };
+
+ function calculate_line_normal(p1, p2, normalOut){
+ var tmp = new cc.math.Vec2(p2);
+ tmp.subtract(p1);
+
+ normalOut.x = -tmp.y;
+ normalOut.y = tmp.x;
+ normalOut.normalize();
+ //TODO: should check that the normal is pointing out of the triangle
+ }
+
+ cc.math.Ray2.prototype.intersectTriangle = function(p1, p2, p3, intersection, normal_out){
+ var intersect = new cc.math.Vec2(), final_intersect = new cc.math.Vec2();
+ var normal = new cc.math.Vec2(), distance = 10000.0, intersected = false;
+ var this_distance;
+
+ if(this.intersectLineSegment(p1, p2, intersect)) {
+ intersected = true;
+ this_distance = intersect.subtract(this.start).length();
+ if(this_distance < distance) {
+ final_intersect.x = intersect.x;
+ final_intersect.y = intersect.y;
+ distance = this_distance;
+ calculate_line_normal(p1, p2, normal);
+ }
+ }
+
+ if(this.intersectLineSegment(p2, p3, intersect)) {
+ intersected = true;
+ this_distance = intersect.subtract(this.start).length();
+ if(this_distance < distance) {
+ final_intersect.x = intersect.x;
+ final_intersect.y = intersect.y;
+ distance = this_distance;
+ calculate_line_normal(p2, p3, normal);
+ }
+ }
+
+ if(this.intersectLineSegment(p3, p1, intersect)) {
+ intersected = true;
+ this_distance = intersect.subtract(this.start).length();
+ if(this_distance < distance) {
+ final_intersect.x = intersect.x;
+ final_intersect.y = intersect.y;
+ distance = this_distance;
+ calculate_line_normal(p3, p1, normal);
+ }
+ }
+
+ if(intersected) {
+ intersection.x = final_intersect.x;
+ intersection.y = final_intersect.y;
+ if(normal_out) {
+ normal_out.x = normal.x;
+ normal_out.y = normal.y;
+ }
+ }
+ return intersected;
+ };
+})(cc);
diff --git a/cocos2d/kazmath/simd_benchmark/base.js b/cocos2d/kazmath/simd_benchmark/base.js
new file mode 100644
index 0000000000..7bbb84533e
--- /dev/null
+++ b/cocos2d/kazmath/simd_benchmark/base.js
@@ -0,0 +1,139 @@
+// SIMD Kernel Benchmark Harness
+// Author: Peter Jensen
+
+function Benchmark (config) {
+ this.config = config;
+ this.initOk = true; // Initialize all properties used on a Benchmark object
+ this.cleanupOk = true;
+ this.useAutoIterations = true;
+ this.autoIterations = 0;
+ this.actualIterations = 0;
+ this.simdTime = 0;
+ this.nonSimdTime = 0;
+}
+
+function Benchmarks () {
+ this.benchmarks = [];
+}
+
+Benchmarks.prototype.add = function (benchmark) {
+ this.benchmarks.push (benchmark);
+ return this.benchmarks.length - 1;
+};
+
+Benchmarks.prototype.runOne = function (benchmark) {
+
+ function timeKernel(kernel, iterations) {
+ var start, stop;
+ start = Date.now();
+ kernel(iterations);
+ stop = Date.now();
+ return stop - start;
+ }
+
+ function computeIterations() {
+ var desiredRuntime = 1000; // milliseconds for longest running kernel
+ var testIterations = 10; // iterations used to determine time for desiredRuntime
+
+ // Make the slowest kernel run for at least 500ms
+ var simdTime = timeKernel(benchmark.config.kernelSimd, testIterations);
+ var nonSimdTime = timeKernel(benchmark.config.kernelNonSimd, testIterations);
+ var maxTime = simdTime > nonSimdTime ? simdTime : nonSimdTime;
+ while (maxTime < 500) {
+ testIterations *= 2;
+ simdTime = timeKernel(benchmark.config.kernelSimd, testIterations);
+ nonSimdTime = timeKernel(benchmark.config.kernelNonSimd, testIterations);
+ maxTime = simdTime > nonSimdTime ? simdTime : nonSimdTime;
+ }
+ maxTime = simdTime > nonSimdTime ? simdTime : nonSimdTime;
+
+ // Compute iteration count for 1 second run of slowest kernel
+ var iterations = Math.ceil(desiredRuntime * testIterations / maxTime);
+ return iterations;
+ }
+
+ // Initialize the kernels and check the correctness status
+ if (!benchmark.config.kernelInit()) {
+ benchmark.initOk = false;
+ return false;
+ }
+
+ // Determine how many iterations to use.
+ if (benchmark.useAutoIterations) {
+ benchmark.autoIterations = computeIterations();
+ benchmark.actualIterations = benchmark.autoIterations;
+ }
+ else {
+ benchmark.actualIterations = benchmark.config.kernelIterations;
+ }
+
+ // Run the SIMD kernel
+ benchmark.simdTime = timeKernel(benchmark.config.kernelSimd, benchmark.actualIterations);
+
+ // Run the non-SIMD kernel
+ benchmark.nonSimdTime = timeKernel(benchmark.config.kernelNonSimd, benchmark.actualIterations);
+
+ // Do the final sanity check
+ if (!benchmark.config.kernelCleanup()) {
+ benchmark.cleanupOk = false;
+ return false;
+ }
+
+ return true;
+};
+
+Benchmarks.prototype.report = function (benchmark, outputFunctions) {
+
+ function fillRight(str, width) {
+ str += ""; // make sure it's a string
+ while (str.length < width) {
+ str += " ";
+ }
+ return str;
+ }
+
+ function fillLeft(str, width) {
+ str += ""; // make sure it's a string
+ while (str.length < width) {
+ str = " " + str;
+ }
+ return str;
+ }
+
+ if (!benchmark.initOk) {
+ outputFunctions.notifyError(fillRight(benchmark.config.kernelName + ": ", 23) + "FAILED INIT");
+ return;
+ }
+ if (!benchmark.cleanupOk) {
+ outputFunctions.notifyError(fillRight(benchmark.config.kernelName + ": ", 23) + "FAILED CLEANUP");
+ return;
+ }
+
+ var ratio = benchmark.nonSimdTime / benchmark.simdTime;
+ ratio = ratio.toFixed(2);
+ outputFunctions.notifyResult(
+ fillRight(benchmark.config.kernelName + ": ", 23) +
+ "Iterations(" + fillLeft(benchmark.actualIterations, 10) + ")" +
+ ", SIMD(" + fillLeft(benchmark.simdTime + "ms)", 8) +
+ ", Non-SIMD(" + fillLeft(benchmark.nonSimdTime + "ms)", 8) +
+ ", Speedup(" + ratio + ")");
+ outputFunctions.timeData.labels.push(benchmark.config.kernelName);
+ outputFunctions.timeData.datasets[0].data.push(benchmark.simdTime);
+ outputFunctions.timeData.datasets[1].data.push(benchmark.nonSimdTime);
+ outputFunctions.speedupData.labels.push(benchmark.config.kernelName);
+ outputFunctions.speedupData.datasets[0].data.push(ratio);
+};
+
+Benchmarks.prototype.runAll = function (outputFunctions, useAutoIterations) {
+ if (typeof useAutoIterations === "undefined") {
+ useAutoIterations = false;
+ }
+ for (var i = 0, n = this.benchmarks.length; i < n; ++i) {
+ var benchmark = this.benchmarks[i];
+ benchmark.useAutoIterations = useAutoIterations;
+ this.runOne(benchmark);
+ this.report(benchmark, outputFunctions);
+ }
+};
+
+var benchmarks = new Benchmarks ();
diff --git a/cocos2d/kazmath/simd_benchmark/index.html b/cocos2d/kazmath/simd_benchmark/index.html
new file mode 100644
index 0000000000..5b115d91c9
--- /dev/null
+++ b/cocos2d/kazmath/simd_benchmark/index.html
@@ -0,0 +1,44 @@
+
+
+
+
+ Kazmath SIMD benchmarks
+
+
+
+ Running benchmarks...
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/cocos2d/kazmath/simd_benchmark/kernel-template.js b/cocos2d/kazmath/simd_benchmark/kernel-template.js
new file mode 100644
index 0000000000..d7c377585d
--- /dev/null
+++ b/cocos2d/kazmath/simd_benchmark/kernel-template.js
@@ -0,0 +1,64 @@
+// Kernel template
+// Author: Peter Jensen
+(function () {
+
+ // Kernel configuration
+ var kernelConfig = {
+ kernelName: "Test",
+ kernelInit: init,
+ kernelCleanup: cleanup,
+ kernelSimd: simd,
+ kernelNonSimd: nonSimd,
+ kernelIterations: 100000000
+ };
+
+ // Hook up to the harness
+ benchmarks.add (new Benchmark (kernelConfig));
+
+ // Kernel Initializer
+ function init () {
+ // Do initial sanity check and initialize data for the kernels.
+ // The sanity check should verify that the simd and nonSimd results
+ // are the same.
+ // It is recommended to do minimal object creation in the kernels
+ // themselves. If global data needs to be initialized, here would
+ // be the place to do it.
+ // If the sanity checks fails the kernels will not be executed
+ // Returns:
+ // true: First run (unoptimized) of the kernels passed
+ // false: First run (unoptimized) of the kernels failed
+ return simd (1) === nonSimd (1);
+ }
+
+ // Kernel Cleanup
+ function cleanup () {
+ // Do final sanity check and perform cleanup.
+ // This function is called when all the kernel iterations have been
+ // executed, so they should be in their final optimized version. The
+ // sanity check done during initialization will probably be of the
+ // initial unoptimized version.
+ // Returns:
+ // true: Last run (optimized) of the kernels passed
+ // false: last run (optimized) of the kernels failed
+ return simd (1) === nonSimd (1);
+ }
+
+ // SIMD version of the kernel
+ function simd (n) {
+ var s = 0;
+ for (var i = 0; i < n; ++i) {
+ s += i;
+ }
+ return s;
+ }
+
+ // Non SIMD version of the kernel
+ function nonSimd (n) {
+ var s = 0;
+ for (var i = 0; i < n; ++i) {
+ s += i;
+ }
+ return s;
+ }
+
+} ());
diff --git a/cocos2d/kazmath/simd_benchmark/kmMat4AreEqual.js b/cocos2d/kazmath/simd_benchmark/kmMat4AreEqual.js
new file mode 100644
index 0000000000..a3dee727ac
--- /dev/null
+++ b/cocos2d/kazmath/simd_benchmark/kmMat4AreEqual.js
@@ -0,0 +1,77 @@
+// kmMat4AreEqual
+
+(function () {
+
+ // Kernel configuration
+ var kernelConfig = {
+ kernelName: "kmMat4AreEqual",
+ kernelInit: init,
+ kernelCleanup: cleanup,
+ kernelSimd: simd,
+ kernelNonSimd: nonSimd,
+ kernelIterations: 10000
+ };
+
+ // Hook up to the harness
+ benchmarks.add(new Benchmark(kernelConfig));
+
+ // Benchmark data, initialization and kernel functions
+ var T1 = new cc.kmMat4();
+ var T2 = new cc.kmMat4();
+ var T1x4 = new cc.kmMat4();
+ var T2x4 = new cc.kmMat4();
+ var areEqual, areEqualSIMD;
+
+ function equals(A, B) {
+ for (var i = 0; i < 16; ++i) {
+ if (A[i] != B[i])
+ return false;
+ }
+ return true;
+ }
+
+ function init() {
+ T1.mat[0] = 1.0;
+ T1.mat[5] = 1.0;
+ T1.mat[10] = 1.0;
+ T1.mat[15] = 1.0;
+
+ T2.mat[0] = 1.0;
+ T2.mat[5] = 1.0;
+ T2.mat[10] = 1.0;
+ T2.mat[15] = 1.0;
+
+ T1x4.mat[0] = 1.0;
+ T1x4.mat[5] = 1.0;
+ T1x4.mat[10] = 1.0;
+ T1x4.mat[15] = 1.0;
+
+ T2x4.mat[0] = 1.0;
+ T2x4.mat[5] = 1.0;
+ T2x4.mat[10] = 1.0;
+ T2x4.mat[15] = 1.0;
+
+ nonSimd(1);
+ simd(1);
+
+ return equals(T1.mat, T1x4.mat) && equals(T2.mat, T2x4.mat) && (areEqual === areEqualSIMD);
+
+ }
+
+ function cleanup() {
+ return init(); // Sanity checking before and after are the same
+ }
+
+ function nonSimd(n) {
+ for (var i = 0; i < n; i++) {
+ areEqual = T1.equals(T2);
+ }
+ }
+
+ function simd(n) {
+ for (var i = 0; i < n; i++) {
+ areEqualSIMD = T1x4.equalsSIMD(T2x4);
+ }
+ }
+
+} ());
diff --git a/cocos2d/kazmath/simd_benchmark/kmMat4Assign.js b/cocos2d/kazmath/simd_benchmark/kmMat4Assign.js
new file mode 100644
index 0000000000..e8e386f781
--- /dev/null
+++ b/cocos2d/kazmath/simd_benchmark/kmMat4Assign.js
@@ -0,0 +1,68 @@
+// kmMat4Assign
+
+(function () {
+
+ // Kernel configuration
+ var kernelConfig = {
+ kernelName: "kmMat4Assign",
+ kernelInit: init,
+ kernelCleanup: cleanup,
+ kernelSimd: simd,
+ kernelNonSimd: nonSimd,
+ kernelIterations: 10000
+ };
+
+ // Hook up to the harness
+ benchmarks.add(new Benchmark(kernelConfig));
+
+ // Benchmark data, initialization and kernel functions
+ var T1 = new cc.kmMat4();
+ var T2 = new cc.kmMat4();
+ var T1x4 = new cc.kmMat4();
+ var T2x4 = new cc.kmMat4();
+
+ function equals(A, B) {
+ for (var i = 0; i < 16; ++i) {
+ if (A[i] != B[i])
+ return false;
+ }
+ return true;
+ }
+
+ function init() {
+ T1.mat[0] = 1.0;
+ T1.mat[5] = 1.0;
+ T1.mat[10] = 1.0;
+ T1.mat[15] = 1.0;
+
+ T1x4.mat[0] = 1.0;
+ T1x4.mat[5] = 1.0;
+ T1x4.mat[10] = 1.0;
+ T1x4.mat[15] = 1.0;
+
+ nonSimd(1);
+ simd(1);
+
+ return equals(T1.mat, T1x4.mat) && equals(T2.mat, T2x4.mat);
+
+ }
+
+ function cleanup() {
+ return init(); // Sanity checking before and after are the same
+ }
+
+ function nonSimd(n) {
+ for (var i = 0; i < n; i++) {
+ //cc.kmMat4Assign(T2, T1);
+ T2.assignFrom(T1);
+ }
+ }
+
+ function simd(n) {
+ for (var i = 0; i < n; i++) {
+ //cc.kmMat4AssignSIMD(T2x4, T1x4);
+ T2x4.assignFromSIMD(T1x4);
+ }
+ }
+
+} ());
diff --git a/cocos2d/kazmath/simd_benchmark/kmMat4Inverse.js b/cocos2d/kazmath/simd_benchmark/kmMat4Inverse.js
new file mode 100644
index 0000000000..212dff1af1
--- /dev/null
+++ b/cocos2d/kazmath/simd_benchmark/kmMat4Inverse.js
@@ -0,0 +1,116 @@
+// kmMat4Inverse
+
+(function () {
+
+ // Kernel configuration
+ var kernelConfig = {
+ kernelName: "kmMat4Inverse",
+ kernelInit: init,
+ kernelCleanup: cleanup,
+ kernelSimd: simd,
+ kernelNonSimd: nonSimd,
+ kernelIterations: 10000
+ };
+
+ // Hook up to the harness
+ benchmarks.add(new Benchmark(kernelConfig));
+
+ // Benchmark data, initialization and kernel functions
+ var src = new cc.kmMat4();
+ var dst = new cc.kmMat4();
+ var srcx4 = new cc.kmMat4();
+ var dstx4 = new cc.kmMat4();
+ var ident = new Float32Array(
+ [1,0,0,0,
+ 0,1,0,0,
+ 0,0,1,0,
+ 0,0,0,1]);
+
+ function equals(A, B) {
+ for (var i = 0; i < 16; ++i) {
+ if (Math.abs (A[i] - B[i]) > 5)
+ return false;
+ }
+ return true;
+ }
+
+ function initMatrix(matrix) {
+ // These values were chosen somewhat randomly, but they will at least yield a solution.
+ matrix [0] = 0; matrix[1] = 1; matrix[2] = 2; matrix[3] = 3;
+ matrix [4] = -1; matrix[5] = -2; matrix[6] = -3; matrix[7] = -4;
+ matrix [8] = 0; matrix[9] = 0; matrix[10] = 2; matrix[11] = 3;
+ matrix [12] = -1; matrix[13] = -2; matrix[14] = 0; matrix[15] = -4;
+ }
+
+ function mulMatrix(dst, op1, op2) {
+ for (var r = 0; r < 4; ++r) {
+ for (var c = 0; c < 4; ++c) {
+ var ri = 4*r;
+ dst[ri + c] = op1[ri]*op2[c] + op1[ri+1]*op2[c+4] + op1[ri+2]*op2[c+8] + op1[ri+3]*op2[c+12];
+ }
+ }
+ }
+
+ function printMatrix(matrix, str) {
+ print('--------matrix ' + str + '----------');
+ for (var r = 0; r < 4; ++r) {
+ var str = "";
+ var ri = r*4;
+ for (var c = 0; c < 4; ++c) {
+ var value = matrix[ri + c];
+ str += " " + value.toFixed(2);
+ }
+ print(str);
+ }
+ }
+
+ function checkMatrix(src, dst) {
+ // when multiplied with the src matrix it should yield the identity matrix
+ var tmp = new Float32Array(16);
+ mulMatrix(tmp, src, dst);
+ for (var i = 0; i < 16; ++i) {
+ if (Math.abs (tmp[i] - ident[i]) > 0.00001) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ function init() {
+ initMatrix(src.mat);
+ // printMatrix(src);
+ nonSimd(1);
+ // printMatrix(dst);
+ if (!checkMatrix(src.mat, dst.mat)) {
+ return false;
+ }
+
+ initMatrix(srcx4.mat);
+ simd(1);
+ // printMatrix(dst);
+ if (!checkMatrix(srcx4.mat, dstx4.mat)) {
+ return false;
+ }
+
+ return true;
+ }
+
+ function cleanup() {
+ return init(); // Sanity checking before and after are the same
+ }
+
+ function nonSimd(n) {
+ for (var i = 0; i < n; i++) {
+ //cc.kmMat4Inverse(dst, src);
+ dst = src.inverse();
+ }
+ }
+
+ function simd(n) {
+ for (var i = 0; i < n; i++) {
+ //cc.kmMat4InverseSIMD(dstx4, srcx4);
+ dstx4 = srcx4.inverseSIMD();
+ }
+ }
+
+} ());
diff --git a/cocos2d/kazmath/simd_benchmark/kmMat4IsIdentity.js b/cocos2d/kazmath/simd_benchmark/kmMat4IsIdentity.js
new file mode 100644
index 0000000000..9ab17ac744
--- /dev/null
+++ b/cocos2d/kazmath/simd_benchmark/kmMat4IsIdentity.js
@@ -0,0 +1,65 @@
+// kmMat4IsIdentity
+
+(function () {
+
+ // Kernel configuration
+ var kernelConfig = {
+ kernelName: "kmMat4IsIdentity",
+ kernelInit: init,
+ kernelCleanup: cleanup,
+ kernelSimd: simd,
+ kernelNonSimd: nonSimd,
+ kernelIterations: 10000
+ };
+
+ // Hook up to the harness
+ benchmarks.add(new Benchmark(kernelConfig));
+
+ // Benchmark data, initialization and kernel functions
+ var T1 = new cc.kmMat4();
+ var T1x4 = new cc.kmMat4();
+ var isIdentity, isIdentitySIMD;
+
+ function equals(A, B) {
+ for (var i = 0; i < 16; ++i) {
+ if (A[i] != B[i])
+ return false;
+ }
+ return true;
+ }
+
+ function init() {
+ T1.mat[0] = 1.0;
+ T1.mat[5] = 1.0;
+ T1.mat[10] = 1.0;
+ T1.mat[15] = 1.0;
+
+ T1x4.mat[0] = 1.0;
+ T1x4.mat[5] = 1.0;
+ T1x4.mat[10] = 1.0;
+ T1x4.mat[15] = 1.0;
+
+ nonSimd(1);
+ simd(1);
+
+ return equals(T1.mat, T1x4.mat) && (isIdentity === isIdentitySIMD);
+
+ }
+
+ function cleanup() {
+ return init(); // Sanity checking before and after are the same
+ }
+
+ function nonSimd(n) {
+ for (var i = 0; i < n; i++) {
+ isIdentity = T1.isIdentity();
+ }
+ }
+
+ function simd(n) {
+ for (var i = 0; i < n; i++) {
+ isIdentitySIMD = T1x4.isIdentitySIMD();
+ }
+ }
+
+} ());
diff --git a/cocos2d/kazmath/simd_benchmark/kmMat4LookAt.js b/cocos2d/kazmath/simd_benchmark/kmMat4LookAt.js
new file mode 100644
index 0000000000..1015ad14eb
--- /dev/null
+++ b/cocos2d/kazmath/simd_benchmark/kmMat4LookAt.js
@@ -0,0 +1,94 @@
+// kmMat4LookAt
+
+(function () {
+
+ // Kernel configuration
+ var kernelConfig = {
+ kernelName: "kmMat4LookAt",
+ kernelInit: init,
+ kernelCleanup: cleanup,
+ kernelSimd: simd,
+ kernelNonSimd: nonSimd,
+ kernelIterations: 10000
+ };
+
+ // Hook up to the harness
+ benchmarks.add(new Benchmark(kernelConfig));
+
+ // Benchmark data, initialization and kernel functions
+ var eye = new cc.kmVec3(), center = new cc.kmVec3(), up = new cc.kmVec3();
+ var T1 = new cc.kmMat4();
+ var eye1 = new cc.kmVec3(), center1 = new cc.kmVec3(), up1 = new cc.kmVec3();
+ var T1x4 = new cc.kmMat4();
+
+ function printMatrix(matrix) {
+ print('--------matrix----------');
+ for (var r = 0; r < 4; ++r) {
+ var str = "";
+ var ri = r*4;
+ for (var c = 0; c < 4; ++c) {
+ var value = matrix[ri + c];
+ str += " " + value.toFixed(2);
+ }
+ print(str);
+ }
+ }
+
+ function equals(A, B) {
+ for (var i = 0; i < 16; ++i) {
+ if (Math.abs (A[i] - B[i]) > 0.001) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ function init() {
+
+ eye.fill(0, 1, 2);
+ center.fill(2, 1, 0);
+ up.fill(1, 1, 1);
+
+ eye1.fill(0, 1, 2);
+ center1.fill(2, 1, 0);
+ up1.fill(1, 1, 1);
+ /*
+ eye1.data[0] = 0;
+ eye1.data[1] = 1;
+ eye1.data[2] = 2;
+
+ center1.data[0] = 2;
+ center1.data[1] = 1;
+ center1.data[2] = 0;
+
+ up1.data[0] = 1;
+ up1.data[1] = 1;
+ up1.data[2] = 1;
+ */
+ nonSimd(1);
+ //printMatrix(T1.mat);
+ simd(1);
+ //printMatrix(T1x4.mat);
+
+ return equals(T1.mat, T1x4.mat);
+ }
+
+ function cleanup() {
+ return init(); // Sanity checking before and after are the same
+ }
+
+ function nonSimd(n) {
+ for (var i = 0; i < n; i++) {
+ //cc.kmMat4LookAt(T1, eye, center, up);
+ T1.lookAt(eye, center, up);
+ }
+ }
+
+ function simd(n) {
+ for (var i = 0; i < n; i++) {
+ //cc.kmMat4LookAtSIMD(T1x4, eye1, center1, up1);
+ T1x4.lookAtSIMD(eye1, center1, up1);
+ }
+ }
+
+} ());
diff --git a/cocos2d/kazmath/simd_benchmark/kmMat4Multiply.js b/cocos2d/kazmath/simd_benchmark/kmMat4Multiply.js
new file mode 100644
index 0000000000..325b6f95bf
--- /dev/null
+++ b/cocos2d/kazmath/simd_benchmark/kmMat4Multiply.js
@@ -0,0 +1,74 @@
+// kmMat4Multiply
+
+(function () {
+
+ // Kernel configuration
+ var kernelConfig = {
+ kernelName: "kmMat4Multiply",
+ kernelInit: init,
+ kernelCleanup: cleanup,
+ kernelSimd: simd,
+ kernelNonSimd: nonSimd,
+ kernelIterations: 10000
+ };
+
+ // Hook up to the harness
+ benchmarks.add(new Benchmark(kernelConfig));
+
+ // Benchmark data, initialization and kernel functions
+ var T1 = new cc.kmMat4();
+ var T2 = new cc.kmMat4();
+ var T1x4 = new cc.kmMat4();
+ var T2x4 = new cc.kmMat4();
+
+ function equals(A, B) {
+ for (var i = 0; i < 16; ++i) {
+ if (A[i] != B[i])
+ return false;
+ }
+ return true;
+ }
+
+ function init() {
+ T1.mat[0] = 1.0;
+ T1.mat[5] = 1.0;
+ T1.mat[10] = 1.0;
+ T1.mat[15] = 1.0;
+
+ T2.mat[0] = 1.0;
+ T2.mat[5] = 1.0;
+ T2.mat[10] = 1.0;
+ T2.mat[15] = 1.0;
+
+ T1x4.mat[0] = 1.0;
+ T1x4.mat[5] = 1.0;
+ T1x4.mat[10] = 1.0;
+ T1x4.mat[15] = 1.0;
+
+ T2x4.mat[0] = 1.0;
+ T2x4.mat[5] = 1.0;
+ T2x4.mat[10] = 1.0;
+ T2x4.mat[15] = 1.0;
+
+ nonSimd(1);
+ simd(1);
+ return equals(T1.mat, T1x4.mat) && equals(T2.mat, T2x4.mat);
+ }
+
+ function cleanup() {
+ return init(); // Sanity checking before and after are the same
+ }
+
+ function nonSimd(n) {
+ for (var i = 0; i < n; i++) {
+ T1.multiply(T2);
+ }
+ }
+
+ function simd(n) {
+ for (var i = 0; i < n; i++) {
+ T1x4.multiplySIMD(T2x4);
+ }
+ }
+
+} ());
diff --git a/cocos2d/kazmath/simd_benchmark/kmMat4Transpose.js b/cocos2d/kazmath/simd_benchmark/kmMat4Transpose.js
new file mode 100644
index 0000000000..cd1b776bf0
--- /dev/null
+++ b/cocos2d/kazmath/simd_benchmark/kmMat4Transpose.js
@@ -0,0 +1,82 @@
+// kmMat4Transpose
+
+(function () {
+
+ // Kernel configuration
+ var kernelConfig = {
+ kernelName: "kmMat4Transpose",
+ kernelInit: init,
+ kernelCleanup: cleanup,
+ kernelSimd: simd,
+ kernelNonSimd: nonSimd,
+ kernelIterations: 10000
+ };
+
+ // Hook up to the harness
+ benchmarks.add(new Benchmark(kernelConfig));
+
+ // Benchmark data, initialization and kernel functions
+ var T1 = new cc.kmMat4();
+ var T2 = new cc.kmMat4();
+ var T1x4 = new cc.kmMat4();
+ var T2x4 = new cc.kmMat4();
+
+ function equals(A, B) {
+ for (var i = 0; i < 16; ++i) {
+ if (A[i] != B[i])
+ return false;
+ }
+ return true;
+ }
+
+ function printMatrix(matrix) {
+ print('--------matrix----------');
+ for (var r = 0; r < 4; ++r) {
+ var str = "";
+ var ri = r*4;
+ for (var c = 0; c < 4; ++c) {
+ var value = matrix[ri + c];
+ str += " " + value.toFixed(2);
+ }
+ print(str);
+ }
+ }
+
+ function init() {
+ T1.mat [0] = 0; T1.mat[1] = 1; T1.mat[2] = 2; T1.mat[3] = 3;
+ T1.mat [4] = -1; T1.mat[5] = -2; T1.mat[6] = -3; T1.mat[7] = -4;
+ T1.mat [8] = 0; T1.mat[9] = 0; T1.mat[10] = 2; T1.mat[11] = 3;
+ T1.mat [12] = -1; T1.mat[13] = -2; T1.mat[14] = 0; T1.mat[15] = -4;
+
+ T1x4.mat [0] = 0; T1x4.mat[1] = 1; T1x4.mat[2] = 2; T1x4.mat[3] = 3;
+ T1x4.mat [4] = -1; T1x4.mat[5] = -2; T1x4.mat[6] = -3; T1x4.mat[7] = -4;
+ T1x4.mat [8] = 0; T1x4.mat[9] = 0; T1x4.mat[10] = 2; T1x4.mat[11] = 3;
+ T1x4.mat [12] = -1; T1x4.mat[13] = -2; T1x4.mat[14] = 0; T1x4.mat[15] = -4;
+
+ nonSimd(1);
+ //printMatrix(T2.mat);
+ simd(1);
+ //printMatrix(T2x4.mat);
+ return equals(T1.mat, T1x4.mat) && equals(T2.mat, T2x4.mat);
+
+ }
+
+ function cleanup() {
+ return init(); // Sanity checking before and after are the same
+ }
+
+ function nonSimd(n) {
+ for (var i = 0; i < n; i++) {
+ T2 = T1.transpose();
+ //T1.transpose();
+ }
+ }
+
+ function simd(n) {
+ for (var i = 0; i < n; i++) {
+ T2x4 = T1x4.transposeSIMD();
+ //T1x4.transposeSIMD();
+ }
+ }
+
+} ());
diff --git a/cocos2d/kazmath/simd_benchmark/kmVec3TransformCoord.js b/cocos2d/kazmath/simd_benchmark/kmVec3TransformCoord.js
new file mode 100644
index 0000000000..541a926c9d
--- /dev/null
+++ b/cocos2d/kazmath/simd_benchmark/kmVec3TransformCoord.js
@@ -0,0 +1,65 @@
+// kmVec3TransformCoord
+
+(function () {
+
+ // Kernel configuration
+ var kernelConfig = {
+ kernelName: "kmVec3TransformCoord",
+ kernelInit: init,
+ kernelCleanup: cleanup,
+ kernelSimd: simd,
+ kernelNonSimd: nonSimd,
+ kernelIterations: 10000
+ };
+
+ // Hook up to the harness
+ benchmarks.add(new Benchmark(kernelConfig));
+
+ // Benchmark data, initialization and kernel functions
+ var V = new cc.kmVec3();
+ var T = new cc.kmMat4();
+ var Out = new cc.kmVec3();
+ var Vx4 = new cc.kmVec3();
+ var Tx4 = new cc.kmMat4();
+ var Outx4 = new cc.kmVec3();
+
+ function init() {
+ T.mat[0] = 1.0;
+ T.mat[5] = 1.0;
+ T.mat[10] = 1.0;
+ T.mat[15] = 1.0;
+
+ V.fill(0.0, 1.0, 0.0);
+
+ Tx4.mat[0] = 1.0;
+ Tx4.mat[5] = 1.0;
+ Tx4.mat[10] = 1.0;
+ Tx4.mat[15] = 1.0;
+
+ Vx4.fill(0.0, 1.0, 0.0);
+
+ nonSimd(1);
+ simd(1);
+ //console.log(V);
+ //console.log(Vx4);
+ return V.equals(Vx4);
+
+ }
+
+ function cleanup() {
+ return init(); // Sanity checking before and after are the same
+ }
+
+ function nonSimd(n) {
+ for (var i = 0; i < n; i++) {
+ V.transformCoord(T);
+ }
+ }
+
+ function simd(n) {
+ for (var i = 0; i < n; i++) {
+ Vx4.transformCoordSIMD(Tx4);
+ }
+ }
+
+} ());
diff --git a/cocos2d/kazmath/simd_benchmark/run.js b/cocos2d/kazmath/simd_benchmark/run.js
new file mode 100644
index 0000000000..693b17f704
--- /dev/null
+++ b/cocos2d/kazmath/simd_benchmark/run.js
@@ -0,0 +1,40 @@
+"use strict";
+
+var cc = {};
+
+load ('base.js');
+
+load ('../utility.js');
+load ('../vec3.js');
+load ('../vec4.js');
+load ('../mat4.js');
+load ('../vec3SIMD.js');
+load ('../mat4SIMD.js');
+
+// load individual benchmarks
+load ('kernel-template.js');
+load ('kmMat4Multiply.js');
+load ('kmMat4Assign.js');
+load ('kmMat4AreEqual.js');
+load ('kmMat4Inverse.js');
+load ('kmMat4IsIdentity.js');
+load ('kmMat4Transpose.js');
+load ('kmMat4LookAt.js');
+load ('kmVec3TransformCoord.js');
+
+function printResult (str) {
+ print (str);
+}
+
+function printError (str) {
+ print (str);
+}
+
+function printScore (str) {
+ print (str);
+}
+
+benchmarks.runAll ({notifyResult: printResult,
+ notifyError: printError,
+ notifyScore: printScore},
+ true);
diff --git a/cocos2d/kazmath/simd_benchmark/run_browser.js b/cocos2d/kazmath/simd_benchmark/run_browser.js
new file mode 100644
index 0000000000..5d2d0cdd74
--- /dev/null
+++ b/cocos2d/kazmath/simd_benchmark/run_browser.js
@@ -0,0 +1,80 @@
+var echo = document.getElementById('echo');
+
+function printResult(str) {
+ console.log(str);
+ echo.innerHTML += str + ' ';
+}
+
+function printError(str) {
+ console.log(str);
+ echo.innerHTML += str + ' ';
+}
+
+function printScore(str) {
+ console.log(str);
+ echo.innerHTML += str + ' ';
+}
+
+var timeData = {
+ labels: [],
+ datasets: [
+ {
+ labels: 'Non-SIMD',
+ fillColor: "rgba(220,220,220,0.5)",
+ strokeColor: "rgba(220,220,220,0.8)",
+ highlightFill: "rgba(220,220,220,0.75)",
+ highlightStroke: "rgba(220,220,220,1)",
+ data: []
+ },
+ {
+ labels: 'SIMD',
+ fillColor: "rgba(151,187,205,0.5)",
+ strokeColor: "rgba(151,187,205,0.8)",
+ highlightFill: "rgba(151,187,205,0.75)",
+ highlightStroke: "rgba(151,187,205,1)",
+ data: []
+ }
+ ]
+};
+
+var speedupData ={
+ labels: [],
+ datasets: [
+ {
+ labels: 'SIMD',
+ fillColor: "rgba(151,187,205,0.5)",
+ strokeColor: "rgba(151,187,205,0.8)",
+ highlightFill: "rgba(151,187,205,0.75)",
+ highlightStroke: "rgba(151,187,205,1)",
+ data: []
+ }
+ ]
+};
+
+window.onload = function() {
+ if (typeof(SIMD) === 'undefined') {
+ var head = document.getElementById('head');
+ head.innerHTML = 'SIMD is not implemented in your browser, stops.';
+ return;
+ }
+ console.log('Running benchmarks.');
+ benchmarks.runAll({notifyResult: printResult,
+ notifyError: printError,
+ notifyScore: printScore,
+ timeData: timeData,
+ speedupData: speedupData}, true);
+ document.getElementById('head').innerHTML = 'Results';
+ document.getElementById('time').innerHTML = 'Time';
+ document.getElementById('speedup').innerHTML = 'Speedup';
+ var ctx1 = document.getElementById("canvasTime").getContext("2d");
+ window.Bar1 = new Chart(ctx1).Bar(timeData, {
+ scaleLabel: "<%=value%>ms",
+ responsive: true
+ });
+ var ctx2 = document.getElementById("canvasSpeedup").getContext("2d");
+ window.Bar2 = new Chart(ctx2).Bar(speedupData, {
+ scaleLabel: " <%=value%>",
+ responsive: true
+ });
+ console.log('Benchmarks completed.');
+};
diff --git a/cocos2d/kazmath/utility.js b/cocos2d/kazmath/utility.js
new file mode 100644
index 0000000000..9cd3fb4c71
--- /dev/null
+++ b/cocos2d/kazmath/utility.js
@@ -0,0 +1,54 @@
+/**
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2008, Luke Benstead.
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without modification,
+ are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+
+/**
+ * The main namespace of Cocos2d-html5's math library,
+ * all math core classes, functions, properties and constants are defined in this namespace
+ * @namespace
+ * @name cc.math
+ */
+cc.math = cc.math || {};
+
+//cc.kmPIOver180 = 0.017453; please use cc.RAD
+
+//cc.kmPIUnder180 = 57.295779; please use cc.DEG
+
+cc.math.EPSILON = 1.0 / 64.0; //cc.kmEpsilon
+
+/**
+ * Returns the square of s (e.g. s*s)
+ * @param {Number} s
+ */
+cc.math.square = function(s){
+ return s*s;
+};
+
+cc.math.almostEqual = function(lhs,rhs){
+ return (lhs + cc.math.EPSILON > rhs && lhs - cc.math.EPSILON < rhs);
+};
diff --git a/cocos2d/kazmath/vec2.js b/cocos2d/kazmath/vec2.js
new file mode 100644
index 0000000000..a682bc4853
--- /dev/null
+++ b/cocos2d/kazmath/vec2.js
@@ -0,0 +1,113 @@
+/**
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2008, Luke Benstead.
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without modification,
+ are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+(function(cc){
+ cc.math.Vec2 = function (x, y) {
+ if(y === undefined){
+ this.x = x.x;
+ this.y = x.y;
+ }else{
+ this.x = x || 0;
+ this.y = y || 0;
+ }
+ };
+
+ var proto = cc.math.Vec2.prototype;
+ proto.fill = function(x, y){ // = cc.kmVec2Fill
+ this.x = x;
+ this.y = y;
+ };
+
+ proto.length = function(){ // = cc.kmVec2Length
+ return Math.sqrt(cc.math.square(this.x) + cc.math.square(this.y));
+ };
+
+ proto.lengthSq = function(){ // = cc.kmVec2LengthSq
+ return cc.math.square(this.x) + cc.math.square(this.y);
+ };
+
+ proto.normalize = function(){ // = cc.kmVec2Normalize
+ var l = 1.0 / this.length();
+ this.x *= l;
+ this.y *= l;
+ return this;
+ };
+
+ cc.math.Vec2.add = function (pOut, pV1, pV2) { // = cc.kmVec2Add
+ pOut.x = pV1.x + pV2.x;
+ pOut.y = pV1.y + pV2.y;
+ return pOut
+ };
+
+ proto.add = function(vec){ // = cc.kmVec2Add
+ this.x += vec.x;
+ this.y += vec.y;
+ return this;
+ };
+
+ proto.dot = function (vec) { //cc.kmVec2Dot
+ return this.x * vec.x + this.y * vec.y;
+ };
+
+ cc.math.Vec2.subtract = function (pOut, pV1, pV2) { // = cc.kmVec2Subtract
+ pOut.x = pV1.x - pV2.x;
+ pOut.y = pV1.y - pV2.y;
+ return pOut;
+ };
+
+ proto.subtract = function(vec){ // = cc.kmVec2Subtract
+ this.x -= vec.x;
+ this.y -= vec.y;
+ return this;
+ };
+
+ proto.transform = function (mat3) { // = cc.kmVec2Transform
+ var x = this.x, y = this.y;
+ this.x = x * mat3.mat[0] + y * mat3.mat[3] + mat3.mat[6];
+ this.y = x * mat3.mat[1] + y * mat3.mat[4] + mat3.mat[7];
+ return this;
+ };
+
+ cc.math.Vec2.scale = function (pOut, pIn, s) { // = cc.kmVec2Scale
+ pOut.x = pIn.x * s;
+ pOut.y = pIn.y * s;
+ return pOut;
+ };
+
+ proto.scale = function(s) { // = cc.kmVec2Scale
+ this.x *= s;
+ this.y *= s;
+ return this;
+ };
+
+ proto.equals = function (vec) { // = cc.kmVec2AreEqual
+ return (this.x < vec.x + cc.math.EPSILON && this.x > vec.x - cc.math.EPSILON) &&
+ (this.y < vec.y + cc.math.EPSILON && this.y > vec.y - cc.math.EPSILON);
+ };
+})(cc);
+
diff --git a/cocos2d/kazmath/vec3.js b/cocos2d/kazmath/vec3.js
new file mode 100644
index 0000000000..282b34aaae
--- /dev/null
+++ b/cocos2d/kazmath/vec3.js
@@ -0,0 +1,201 @@
+/**
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2008, Luke Benstead.
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without modification,
+ are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+(function(cc) {
+ cc.kmVec3 = cc.math.Vec3 = function (x, y, z) {
+ if(x && y === undefined){
+ this.x = x.x;
+ this.y = x.y;
+ this.z = x.z;
+ } else {
+ this.x = x || 0;
+ this.y = y || 0;
+ this.z = z || 0;
+ }
+ };
+
+ cc.math.vec3 = function(x, y, z){
+ return new cc.math.Vec3(x, y, z);
+ };
+
+ var proto = cc.math.Vec3.prototype;
+
+ proto.fill = function (x, y, z) { // =cc.kmVec3Fill
+ if (x && y === undefined) {
+ this.x = x.x;
+ this.y = x.y;
+ this.z = x.z;
+ } else {
+ this.x = x;
+ this.y = y;
+ this.z = z;
+ }
+ return this;
+ };
+
+ proto.length = function () { //=cc.kmVec3Length
+ return Math.sqrt(cc.math.square(this.x) + cc.math.square(this.y) + cc.math.square(this.z));
+ };
+
+ proto.lengthSq = function () { //=cc.kmVec3LengthSq
+ return cc.math.square(this.x) + cc.math.square(this.y) + cc.math.square(this.z)
+ };
+
+ proto.normalize = function () { //= cc.kmVec3Normalize
+ var l = 1.0 / this.length();
+ this.x *= l;
+ this.y *= l;
+ this.z *= l;
+ return this;
+ };
+
+ proto.cross = function (vec3) { //= cc.kmVec3Cross
+ var x = this.x, y = this.y, z = this.z;
+ this.x = (y * vec3.z) - (z * vec3.y);
+ this.y = (z * vec3.x) - (x * vec3.z);
+ this.z = (x * vec3.y) - (y * vec3.x);
+ return this;
+ };
+
+ proto.dot = function (vec) { //= cc.kmVec3Dot
+ return ( this.x * vec.x + this.y * vec.y + this.z * vec.z );
+ };
+
+ proto.add = function(vec){ //= cc.kmVec3Add
+ this.x += vec.x;
+ this.y += vec.y;
+ this.z += vec.z;
+ return this;
+ };
+
+ proto.subtract = function (vec) { // = cc.kmVec3Subtract
+ this.x -= vec.x;
+ this.y -= vec.y;
+ this.z -= vec.z;
+ return this;
+ };
+
+ proto.transform = function (mat4) { // = cc.kmVec3Transform
+ var x = this.x, y = this.y, z = this.z, mat = mat4.mat;
+ this.x = x * mat[0] + y * mat[4] + z * mat[8] + mat[12];
+ this.y = x * mat[1] + y * mat[5] + z * mat[9] + mat[13];
+ this.z = x * mat[2] + y * mat[6] + z * mat[10] + mat[14];
+ return this;
+ };
+
+ proto.transformNormal = function(mat4){
+ /*
+ a = (Vx, Vy, Vz, 0)
+ b = (aĂM)T
+ Out = (bx, by, bz)
+ */
+ //Omits the translation, only scaling + rotating
+ var x = this.x, y = this.y, z = this.z, mat = mat4.mat;
+ this.x = x * mat[0] + y * mat[4] + z * mat[8];
+ this.y = x * mat[1] + y * mat[5] + z * mat[9];
+ this.z = x * mat[2] + y * mat[6] + z * mat[10];
+ return this;
+ };
+
+ proto.transformCoord = function(mat4){ // = cc.kmVec3TransformCoord
+ /*
+ a = (Vx, Vy, Vz, 1)
+ b = (aĂM)T
+ Out = 1âbw(bx, by, bz)
+ */
+ var v = new cc.math.Vec4(this.x, this.y, this.z, 1.0);
+ v.transform(mat4);
+ this.x = v.x / v.w;
+ this.y = v.y / v.w;
+ this.z = v.z / v.w;
+ return this;
+ };
+
+ proto.scale = function(scale){ // = cc.kmVec3Scale
+ this.x *= scale;
+ this.y *= scale;
+ this.z *= scale;
+ return this;
+ };
+
+ proto.equals = function(vec){ // = cc.kmVec3AreEqual
+ var EPSILON = cc.math.EPSILON;
+ return (this.x < (vec.x + EPSILON) && this.x > (vec.x - EPSILON)) &&
+ (this.y < (vec.y + EPSILON) && this.y > (vec.y - EPSILON)) &&
+ (this.z < (vec.z + EPSILON) && this.z > (vec.z - EPSILON));
+ };
+
+ proto.inverseTransform = function(mat4){ //= cc.kmVec3InverseTransform
+ var mat = mat4.mat;
+ var v1 = new cc.math.Vec3(this.x - mat[12], this.y - mat[13], this.z - mat[14]);
+ this.x = v1.x * mat[0] + v1.y * mat[1] + v1.z * mat[2];
+ this.y = v1.x * mat[4] + v1.y * mat[5] + v1.z * mat[6];
+ this.z = v1.x * mat[8] + v1.y * mat[9] + v1.z * mat[10];
+ return this;
+ };
+
+ proto.inverseTransformNormal = function(mat4){ // = cc.kmVec3InverseTransformNormal
+ var x = this.x, y = this.y, z = this.z, mat = mat4.mat;
+ this.x = x * mat[0] + y * mat[1] + z * mat[2];
+ this.y = x * mat[4] + y * mat[5] + z * mat[6];
+ this.z = x * mat[8] + y * mat[9] + z * mat[10];
+ return this;
+ };
+
+ proto.assignFrom = function(vec){
+ if(!vec)
+ return this;
+ this.x = vec.x;
+ this.y = vec.y;
+ this.z = vec.z;
+ return this;
+ };
+
+ cc.math.Vec3.zero = function(vec){ // = cc.kmVec3Zero
+ vec.x = vec.y = vec.z = 0.0;
+ return vec;
+ };
+
+ proto.toTypeArray = function(){ //cc.kmVec3ToTypeArray
+ var tyArr = new Float32Array(3);
+ tyArr[0] = this.x;
+ tyArr[1] = this.y;
+ tyArr[2] = this.z;
+ return tyArr;
+ };
+})(cc);
+
+
+
+
+
+
+
+
+
+
diff --git a/cocos2d/kazmath/vec3SIMD.js b/cocos2d/kazmath/vec3SIMD.js
new file mode 100644
index 0000000000..0bf4ff4b87
--- /dev/null
+++ b/cocos2d/kazmath/vec3SIMD.js
@@ -0,0 +1,51 @@
+/**
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2008, Luke Benstead.
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without modification,
+ are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+ (function(cc) {
+ var proto = cc.math.Vec3.prototype;
+
+ proto.transformCoordSIMD = function(mat4){
+ var vec = SIMD.float32x4(this.x, this.y, this.z, 0.0);
+ var mat0 = SIMD.float32x4.load(mat4.mat, 0);
+ var mat1 = SIMD.float32x4.load(mat4.mat, 4);
+ var mat2 = SIMD.float32x4.load(mat4.mat, 8);
+ var mat3 = SIMD.float32x4.load(mat4.mat, 12);
+
+ //cc.kmVec4Transform(v, inV,pM);
+ var out = SIMD.float32x4.add(
+ SIMD.float32x4.add(SIMD.float32x4.mul(mat0, SIMD.float32x4.swizzle(vec, 0, 0, 0, 0)),
+ SIMD.float32x4.mul(mat1, SIMD.float32x4.swizzle(vec, 1, 1, 1, 1))),
+ SIMD.float32x4.add(SIMD.float32x4.mul(mat2, SIMD.float32x4.swizzle(vec, 2, 2, 2, 2)),
+ mat3));
+
+ out = SIMD.float32x4.div(out, SIMD.float32x4.swizzle(out, 3, 3, 3, 3));
+ this.fill(out);
+
+ return this;
+ };
+})(cc);
diff --git a/cocos2d/kazmath/vec4.js b/cocos2d/kazmath/vec4.js
new file mode 100644
index 0000000000..fb2e376380
--- /dev/null
+++ b/cocos2d/kazmath/vec4.js
@@ -0,0 +1,158 @@
+/**
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2008, Luke Benstead.
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without modification,
+ are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+(function(cc) {
+ cc.math.Vec4 = function (x, y, z, w) {
+ if (x && y === undefined) {
+ this.x = x.x;
+ this.y = x.y;
+ this.z = x.z;
+ this.w = x.w;
+ } else {
+ this.x = x || 0;
+ this.y = y || 0;
+ this.z = z || 0;
+ this.w = w || 0;
+ }
+ };
+ cc.kmVec4 = cc.math.Vec4;
+ var proto = cc.math.Vec4.prototype;
+
+ proto.fill = function (x, y, z, w) { //=cc.kmVec4Fill
+ if (x && y === undefined) {
+ this.x = x.x;
+ this.y = x.y;
+ this.z = x.z;
+ this.w = x.w;
+ } else {
+ this.x = x;
+ this.y = y;
+ this.z = z;
+ this.w = w;
+ }
+ };
+
+ proto.add = function(vec) { //cc.kmVec4Add
+ if(!vec)
+ return this;
+ this.x += vec.x;
+ this.y += vec.y;
+ this.z += vec.z;
+ this.w += vec.w;
+ return this;
+ };
+
+ proto.dot = function(vec){ //cc.kmVec4Dot
+ return ( this.x * vec.x + this.y * vec.y + this.z * vec.z + this.w * vec.w );
+ };
+
+ proto.length = function(){ //=cc.kmVec4Length
+ return Math.sqrt(cc.math.square(this.x) + cc.math.square(this.y) + cc.math.square(this.z) + cc.math.square(this.w));
+ };
+
+ proto.lengthSq = function(){ //=cc.kmVec4LengthSq
+ return cc.math.square(this.x) + cc.math.square(this.y) + cc.math.square(this.z) + cc.math.square(this.w);
+ };
+
+ proto.lerp = function(vec, t){ //= cc.kmVec4Lerp
+ //not implemented
+ return this;
+ };
+
+ proto.normalize = function() { // cc.kmVec4Normalize
+ var l = 1.0 / this.length();
+ this.x *= l;
+ this.y *= l;
+ this.z *= l;
+ this.w *= l;
+ return this;
+ };
+
+ proto.scale = function(scale){ //= cc.kmVec4Scale
+ /// Scales a vector to the required length. This performs a Normalize before multiplying by S.
+ this.normalize();
+ this.x *= scale;
+ this.y *= scale;
+ this.z *= scale;
+ this.w *= scale;
+ return this;
+ };
+
+ proto.subtract = function(vec) {
+ this.x -= vec.x;
+ this.y -= vec.y;
+ this.z -= vec.z;
+ this.w -= vec.w;
+ };
+
+ proto.transform = function(mat4) {
+ var x = this.x, y = this.y, z = this.z, w = this.w, mat = mat4.mat;
+ this.x = x * mat[0] + y * mat[4] + z * mat[8] + w * mat[12];
+ this.y = x * mat[1] + y * mat[5] + z * mat[9] + w * mat[13];
+ this.z = x * mat[2] + y * mat[6] + z * mat[10] + w * mat[14];
+ this.w = x * mat[3] + y * mat[7] + z * mat[11] + w * mat[15];
+ return this;
+ };
+
+ cc.math.Vec4.transformArray = function(vecArray, mat4){
+ var retArray = [];
+ for (var i = 0; i < vecArray.length; i++) {
+ var selVec = new cc.math.Vec4(vecArray[i]);
+ selVec.transform(mat4);
+ retArray.push(selVec);
+ }
+ return retArray;
+ };
+
+ proto.equals = function(vec){ //=cc.kmVec4AreEqual
+ var EPSILON = cc.math.EPSILON;
+ return (this.x < vec.x + EPSILON && this.x > vec.x - EPSILON) &&
+ (this.y < vec.y + EPSILON && this.y > vec.y - EPSILON) &&
+ (this.z < vec.z + EPSILON && this.z > vec.z - EPSILON) &&
+ (this.w < vec.w + EPSILON && this.w > vec.w - EPSILON);
+ };
+
+ proto.assignFrom = function(vec) { //= cc.kmVec4Assign
+ this.x = vec.x;
+ this.y = vec.y;
+ this.z = vec.z;
+ this.w = vec.w;
+ return this;
+ };
+
+ proto.toTypeArray = function(){ //cc.kmVec4ToTypeArray
+ var tyArr = new Float32Array(4);
+ tyArr[0] = this.x;
+ tyArr[1] = this.y;
+ tyArr[2] = this.z;
+ tyArr[3] = this.w;
+ return tyArr;
+ };
+})(cc);
+
+
diff --git a/cocos2d/labels/CCLabel.js b/cocos2d/labels/CCLabel.js
new file mode 100644
index 0000000000..340f262c69
--- /dev/null
+++ b/cocos2d/labels/CCLabel.js
@@ -0,0 +1,251 @@
+/*global cc */
+
+/****************************************************************************
+ Copyright (c) 2015 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+var EventTarget = require("../cocos2d/core/event/event-target");
+
+cc.Label = cc.Node.extend({
+ _hAlign: cc.TextAlignment.LEFT,
+ _vAlign: cc.VerticalTextAlignment.BOTTOM,
+ _string: "",
+ _fontSize: 20,
+ _overFlow: 0, //0 clamp, 1 shrink 2, resize to content
+ _isWrapText: true,
+ _spacingX: 0,
+ _spacingY: 0,
+ _blendFunc: null,
+ _labelSkinDirty: true,
+ _labelIsTTF: true,
+ _fontHandle: "",
+
+ //fontHandle it is a font name or bmfont file.
+ ctor: function(fontHandle) {
+ this.setFontFileOrFamily(fontHandle);
+ cc.Node.prototype.ctor.call(this);
+ this.setContentSize(cc.size(128, 128));
+ this._blendFunc = cc.BlendFunc._alphaNonPremultiplied();
+ },
+
+ setHorizontalAlign: function(align) {
+ if (this._hAlign === align) return;
+ this._hAlign = align;
+ this._notifyLabelSkinDirty();
+ },
+
+ getHorizontalAlign: function() {
+ return this._hAlign;
+ },
+
+ setVerticalAlign: function(align) {
+ if (this._vAlign === align) return;
+ this._vAlign = align;
+ this._notifyLabelSkinDirty();
+ },
+
+ getVerticalAlign: function() {
+ return this._vAlign;
+ },
+
+ setString: function(string) {
+ if (this._string === string) return;
+ this._string = string;
+ this._notifyLabelSkinDirty();
+ },
+
+ getString: function() {
+ return this._string;
+ },
+
+ enableWrapText: function(enabled) {
+ if (this._isWrapText === enabled) return;
+ this._isWrapText = enabled;
+ this._notifyLabelSkinDirty();
+ },
+
+ isWrapTextEnabled: function() {
+ return this._isWrapText;
+ },
+
+ setFontSize: function(fntSize) {
+ if (this._fontSize === fntSize) return;
+ this._fontSize = fntSize;
+ this._notifyLabelSkinDirty();
+ },
+
+ getFontSize: function() {
+ return this._fontSize;
+ },
+
+ setOverflow: function(overflow) {
+ if (this._overFlow === overflow) return;
+ this._overFlow = overflow;
+ this._notifyLabelSkinDirty();
+ },
+
+ getOverflow: function() {
+ return this._overFlow;
+ },
+
+ setSpacingX: function(spacing) {
+ if (this._spacingX === spacing) return;
+ this._spacingX = spacing;
+ if(this._labelIsTTF === false)
+ this._notifyLabelSkinDirty();
+ },
+
+ setLineHeight: function(spacing) {
+ if (this._spacingY === spacing) return;
+ this._spacingY = spacing;
+ this._notifyLabelSkinDirty();
+ },
+
+ getSpacingX: function() {
+ return this._spacingX;
+ },
+
+ getLineHeight: function() {
+ return this._spacingY;
+ },
+
+ setFontFileOrFamily: function( fontHandle ) {
+ fontHandle = fontHandle || "";
+ var extName = cc.path.extname(fontHandle);
+
+ //specify font family name directly
+ if( extName === null) {
+ this._fontHandle = fontHandle;
+ this._labelIsTTF = true;
+ this._notifyLabelSkinDirty();
+ return;
+ }
+ //add resource path
+ fontHandle = cc.path.join(cc.loader.resPath, fontHandle);
+
+ if(extName === ".ttf") {
+ this._labelIsTTF = true;
+ this._fontHandle = this._loadTTFFont(fontHandle);
+ }
+ else {
+ //todo add bmfont here
+ this._fontHandle = fontHandle;
+ this._labelIsTTF = false;
+ this._notifyLabelSkinDirty();
+ }
+ },
+
+ _loadTTFFont : function(fontHandle){
+ var ttfIndex = fontHandle.lastIndexOf(".ttf");
+ if(ttfIndex === -1) return fontHandle;
+ var slashPos = fontHandle.lastIndexOf("/");
+ var fontFamilyName;
+ if(slashPos === -1) fontFamilyName = fontHandle.substring(0,ttfIndex ) + "_LABEL";
+ else fontFamilyName = fontHandle.substring(slashPos + 1, ttfIndex) + "_LABEL";
+ var self = this;
+ if(FontFace) {
+ var fontFace = new FontFace(fontFamilyName, "url('" + fontHandle + "')");
+ fontFace.load().then( function (loadedFace) {
+ document.fonts.add(loadedFace);
+ self._notifyLabelSkinDirty();
+ });
+ } else {
+ //fall back implementations
+ var doc = document, fontStyle = document.createElement("style");
+ fontStyle.type = "text/css";
+ doc.body.appendChild(fontStyle);
+
+ var fontStr = "";
+ if(isNaN(fontFamilyName - 0))
+ fontStr += "@font-face { font-family:" + fontFamilyName + "; src:";
+ else
+ fontStr += "@font-face { font-family:'" + fontFamilyName + "'; src:";
+
+ fontStr += "url('" + fontHandle + "');";
+
+ fontStyle.textContent = fontStr + "}";
+
+ //.
+ var preloadDiv = document.createElement("div");
+ var _divStyle = preloadDiv.style;
+ _divStyle.fontFamily = name;
+ preloadDiv.innerHTML = ".";
+ _divStyle.position = "absolute";
+ _divStyle.left = "-100px";
+ _divStyle.top = "-100px";
+ doc.body.appendChild(preloadDiv);
+ self.scheduleOnce(self._notifyLabelSkinDirty,2);
+ }
+
+ return fontFamilyName;
+ },
+
+ setContentSize: function(size, height) {
+ var oldWidth = this._contentSize.width;
+ var oldHeight = this._contentSize.height;
+ cc.Node.prototype.setContentSize.call(this, size,height);
+ if (oldWidth === this._contentSize.width && oldHeight === this._contentSize.height) {
+ return;
+ }
+ this._notifyLabelSkinDirty();
+ },
+
+ setBlendFunc: function (src, dst) {
+ var locBlendFunc = this._blendFunc;
+ if (dst === undefined) {
+ locBlendFunc.src = src.src;
+ locBlendFunc.dst = src.dst;
+ } else {
+ locBlendFunc.src = src;
+ locBlendFunc.dst = dst;
+ }
+ },
+
+
+ getBlendFunc: function() {
+ return new cc.BlendFunc(this._blendFunc.src, this._blendFunc.dst);
+ },
+
+ _notifyLabelSkinDirty: function() {
+ this._labelSkinDirty = true;
+ if(this._renderCmd)
+ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.textDirty);
+ },
+ _createRenderCmd: function() {
+
+ if (this._labelIsTTF) {
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ return new cc.Label.TTFWebGLRenderCmd(this);
+ else
+ return new cc.Label.TTFCanvasRenderCmd(this);
+ } else {
+ //todo:add label bmfont here
+ }
+ }
+});
+
+cc.Label.Overflow = cc.Enum({
+ CLAMP: 0,
+ SHRINK: 1,
+ RESIZE: 2
+});
diff --git a/cocos2d/labels/CCLabelAtlas.js b/cocos2d/labels/CCLabelAtlas.js
new file mode 100644
index 0000000000..0c45e96f55
--- /dev/null
+++ b/cocos2d/labels/CCLabelAtlas.js
@@ -0,0 +1,240 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+/**
+ * using image file to print text label on the screen, might be a bit slower than cc.Label, similar to cc.LabelBMFont
+ * @class
+ * @extends cc.AtlasNode
+ *
+ * @property {String} string - Content string of label
+ *
+ * @param {String} strText
+ * @param {String} charMapFile charMapFile or fntFile
+ * @param {Number} [itemWidth=0]
+ * @param {Number} [itemHeight=0]
+ * @param {Number} [startCharMap=""]
+ * @example
+ * //creates the cc.LabelAtlas with a string, a char map file(the atlas), the width and height of each element and the starting char of the atlas
+ * var myLabel = new cc.LabelAtlas('Text to display', 'CharMapfile.png', 12, 20, ' ')
+ *
+ * //creates the cc.LabelAtlas with a string, a fnt file
+ * var myLabel = new cc.LabelAtlas('Text to display', 'CharMapFile.plistâ);
+ */
+cc.LabelAtlas = cc.AtlasNode.extend(/** @lends cc.LabelAtlas# */{
+ //property String is Getter and Setter
+ // string to render
+ _string: null,
+ // the first char in the charmap
+ _mapStartChar: null,
+
+ _textureLoaded: false,
+ _className: "LabelAtlas",
+
+ /**
+ *
+ * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
+ * Create a label atlas.
+ * It accepts two groups of parameters:
+ * a) string, fntFile
+ * b) label, textureFilename, width, height, startChar
+ *
+ * @param {String} strText
+ * @param {String} charMapFile charMapFile or fntFile
+ * @param {Number} [itemWidth=0]
+ * @param {Number} [itemHeight=0]
+ * @param {Number} [startCharMap=""]
+ */
+ ctor: function (strText, charMapFile, itemWidth, itemHeight, startCharMap) {
+ cc.AtlasNode.prototype.ctor.call(this);
+
+ this._renderCmd.setCascade();
+ charMapFile && cc.LabelAtlas.prototype.initWithString.call(this, strText, charMapFile, itemWidth, itemHeight, startCharMap);
+ },
+
+ _createRenderCmd: function(){
+ if(cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ return new cc.LabelAtlas.WebGLRenderCmd(this);
+ else
+ return new cc.LabelAtlas.CanvasRenderCmd(this);
+ },
+
+ /**
+ * Return texture is loaded.
+ * @returns {boolean}
+ */
+ textureLoaded: function () {
+ return this._textureLoaded;
+ },
+
+ /**
+ * Add texture loaded event listener.
+ * @param {Function} callback
+ * @param {cc.Node} target
+ * @deprecated since 3.1, please use EventTarget API instead
+ */
+ addLoadedEventListener: function (callback, target) {
+ this.once("load", callback, target);
+ },
+
+ /**
+ *
+ * initializes the cc.LabelAtlas with a string, a char map file(the atlas),
+ * the width and height of each element and the starting char of the atlas
+ * It accepts two groups of parameters:
+ * a) string, fntFile
+ * b) label, textureFilename, width, height, startChar
+ *
+ * @param {String} strText
+ * @param {String|cc.Texture2D} charMapFile charMapFile or fntFile or texture file
+ * @param {Number} [itemWidth=0]
+ * @param {Number} [itemHeight=0]
+ * @param {Number} [startCharMap=""]
+ * @return {Boolean} returns true on success
+ */
+ initWithString: function (strText, charMapFile, itemWidth, itemHeight, startCharMap) {
+ var label = strText + "", textureFilename, width, height, startChar;
+ if (itemWidth === undefined) {
+ var dict = cc.loader.getRes(charMapFile);
+ if (parseInt(dict["version"], 10) !== 1) {
+ cc.log("cc.LabelAtlas.initWithString(): Unsupported version. Upgrade cocos2d version");
+ return false;
+ }
+
+ textureFilename = cc.path.changeBasename(charMapFile, dict["textureFilename"]);
+ var locScaleFactor = cc.contentScaleFactor();
+ width = parseInt(dict["itemWidth"], 10) / locScaleFactor;
+ height = parseInt(dict["itemHeight"], 10) / locScaleFactor;
+ startChar = String.fromCharCode(parseInt(dict["firstChar"], 10));
+ } else {
+ textureFilename = charMapFile;
+ width = itemWidth || 0;
+ height = itemHeight || 0;
+ startChar = startCharMap || " ";
+ }
+
+ var texture = null;
+ if (textureFilename instanceof cc.Texture2D)
+ texture = textureFilename;
+ else
+ texture = cc.textureCache.addImage(textureFilename);
+ var locLoaded = texture.isLoaded();
+ this._textureLoaded = locLoaded;
+ if (!locLoaded) {
+ this._string = label;
+ texture.once("load", function (event) {
+ this.initWithTexture(texture, width, height, label.length);
+ this.string = this._string;
+ this.setColor(this._renderCmd._displayedColor);
+ this.emit("load");
+ }, this);
+ }
+ if (this.initWithTexture(texture, width, height, label.length)) {
+ this._mapStartChar = startChar;
+ this.string = label;
+ return true;
+ }
+ return false;
+ },
+
+ /**
+ * Set the color.
+ * @param {cc.Color} color3
+ */
+ setColor: function (color3) {
+ cc.AtlasNode.prototype.setColor.call(this, color3);
+ this._renderCmd.updateAtlasValues();
+ },
+
+ /**
+ * return the text of this label
+ * @return {String}
+ */
+ getString: function () {
+ return this._string;
+ },
+
+ addChild: function(child, localZOrder, tag){
+ this._renderCmd._addChild(child);
+ cc.Node.prototype.addChild.call(this, child, localZOrder, tag);
+ },
+
+ /**
+ * Atlas generation
+ * @function
+ */
+ updateAtlasValues: function(){
+ this._renderCmd.updateAtlasValues();
+ },
+
+ /**
+ * set the display string
+ * @function
+ * @param {String} label
+ */
+ setString: function(label){
+ label = String(label);
+ var len = label.length;
+ this._string = label;
+ this.setContentSize(len * this._itemWidth, this._itemHeight);
+ this._renderCmd.setString(label);
+
+ this._renderCmd.updateAtlasValues();
+ this.quadsToDraw = len;
+ }
+});
+
+(function(){
+ var proto = cc.LabelAtlas.prototype;
+ // Override properties
+ cc.defineGetterSetter(proto, "opacity", proto.getOpacity, proto.setOpacity);
+ cc.defineGetterSetter(proto, "color", proto.getColor, proto.setColor);
+
+ // Extended properties
+ /** @expose */
+ proto.string;
+ cc.defineGetterSetter(proto, "string", proto.getString, proto.setString);
+})();
+
+/**
+ *
+ * Please use new cc.LabelAtlas instead.
+ * Create a label atlas.
+ * It accepts two groups of parameters:
+ * a) string, fntFile
+ * b) label, textureFilename, width, height, startChar
+ *
+ * @deprecated since v3.0 please use new cc.LabelAtlas
+ * @param {String} strText
+ * @param {String} charMapFile charMapFile or fntFile
+ * @param {Number} [itemWidth=0]
+ * @param {Number} [itemHeight=0]
+ * @param {Number} [startCharMap=""]
+ * @return {cc.LabelAtlas} returns the LabelAtlas object on success
+ */
+cc.LabelAtlas.create = function (strText, charMapFile, itemWidth, itemHeight, startCharMap) {
+ return new cc.LabelAtlas(strText, charMapFile, itemWidth, itemHeight, startCharMap);
+};
+
diff --git a/cocos2d/labels/CCLabelAtlasCanvasRenderCmd.js b/cocos2d/labels/CCLabelAtlasCanvasRenderCmd.js
new file mode 100644
index 0000000000..890c98be25
--- /dev/null
+++ b/cocos2d/labels/CCLabelAtlasCanvasRenderCmd.js
@@ -0,0 +1,110 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+(function(){
+ cc.LabelAtlas.CanvasRenderCmd = function(renderableObject){
+ cc.AtlasNode.CanvasRenderCmd.call(this, renderableObject);
+ this._needDraw = false;
+ };
+
+ var proto = cc.LabelAtlas.CanvasRenderCmd.prototype = Object.create(cc.AtlasNode.CanvasRenderCmd.prototype);
+ proto.constructor = cc.LabelAtlas.CanvasRenderCmd;
+
+ proto.setCascade = function(){
+ var node = this._node;
+ node._cascadeOpacityEnabled = true;
+ node._cascadeColorEnabled = false;
+ };
+
+ proto.updateAtlasValues = function(){
+ var node = this._node;
+ var locString = node._string || "";
+ var n = locString.length;
+ var texture = this._textureToRender;
+ var locItemWidth = node._itemWidth , locItemHeight = node._itemHeight; //needn't multiply cc.contentScaleFactor(), because sprite's draw will do this
+
+ for (var i = 0, cr = -1; i < n; i++) {
+ var a = locString.charCodeAt(i) - node._mapStartChar.charCodeAt(0);
+ var row = parseInt(a % node._itemsPerRow, 10);
+ var col = parseInt(a / node._itemsPerRow, 10);
+ if(row < 0 || col < 0)
+ continue;
+ var rect = cc.rect(row * locItemWidth, col * locItemHeight, locItemWidth, locItemHeight);
+ var textureContent = texture._contentSize;
+ if(rect.x < 0 || rect.y < 0 || rect.x + rect.width > textureContent.width || rect.y + rect.height > textureContent.height)
+ continue;
+
+ cr++;
+ var c = locString.charCodeAt(i);
+ var fontChar = node.getChildByTag(i);
+ if (!fontChar) {
+ fontChar = new cc.Sprite();
+ if (c === 32) {
+ fontChar.init();
+ fontChar.setTextureRect(cc.rect(0, 0, 10, 10), false, cc.size(0, 0));
+ } else
+ fontChar.initWithTexture(texture, rect);
+
+ cc.Node.prototype.addChild.call(node, fontChar, 0, i);
+ } else {
+ if (c === 32) {
+ fontChar.init();
+ fontChar.setTextureRect(cc.rect(0, 0, 10, 10), false, cc.size(0, 0));
+ } else {
+ // reusing fonts
+ fontChar.initWithTexture(texture, rect);
+ // restore to default in case they were modified
+ fontChar.visible = true;
+ }
+ }
+ fontChar.setPosition(cr * locItemWidth + locItemWidth / 2, locItemHeight / 2);
+ }
+ this.updateContentSize(i, cr+1);
+ };
+
+ proto.updateContentSize = function(i, cr){
+ var node = this._node,
+ contentSize = node._contentSize;
+ if(i !== cr && i*node._itemWidth === contentSize.width && node._itemHeight === contentSize.height){
+ node.setContentSize(cr * node._itemWidth, node._itemHeight);
+ }
+ };
+
+ proto.setString = function(label){
+ var node = this._node;
+ if (node._children) {
+ var locChildren = node._children;
+ var len = locChildren.length;
+ for (var i = 0; i < len; i++) {
+ var child = locChildren[i];
+ if (child && !child._lateChild)
+ child.visible = false;
+ }
+ }
+ };
+
+ proto._addChild = function(){
+ child._lateChild = true;
+ };
+})();
\ No newline at end of file
diff --git a/cocos2d/labels/CCLabelAtlasWebGLRenderCmd.js b/cocos2d/labels/CCLabelAtlasWebGLRenderCmd.js
new file mode 100644
index 0000000000..87e9fa79f5
--- /dev/null
+++ b/cocos2d/labels/CCLabelAtlasWebGLRenderCmd.js
@@ -0,0 +1,153 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+(function(){
+ cc.LabelAtlas.WebGLRenderCmd = function(renderable){
+ cc.AtlasNode.WebGLRenderCmd.call(this, renderable);
+ this._needDraw = true;
+ };
+
+ var proto = cc.LabelAtlas.WebGLRenderCmd.prototype = Object.create(cc.AtlasNode.WebGLRenderCmd.prototype);
+ proto.constructor = cc.LabelAtlas.WebGLRenderCmd;
+
+ proto.setCascade = function(){
+ var node = this._node;
+ node._cascadeOpacityEnabled = true;
+ node._cascadeColorEnabled = true;
+ };
+
+ proto.rendering = function(ctx){
+ cc.AtlasNode.WebGLRenderCmd.prototype.rendering.call(this, ctx);
+ if (cc.LABELATLAS_DEBUG_DRAW) {
+ var node = this._node;
+ var s = node.getContentSize();
+ var locRect = node.getBoundingBoxToWorld();
+ var posX = locRect.x,
+ posY = locRect.y;
+ s.width = locRect.width;
+ s.height = locRect.height;
+ var vertices = [cc.p(posX, posY), cc.p(posX+ s.width, posY),
+ cc.p(s.width+posX, s.height+posY), cc.p(posX, posY+s.height)];
+ cc._drawingUtil.drawPoly(vertices, 4, true);
+ }
+ };
+
+ proto.updateAtlasValues = function(){
+ var node = this._node;
+ var locString = node._string;
+ var n = locString.length;
+ var locTextureAtlas = this._textureAtlas;
+
+ var texture = locTextureAtlas.texture;
+ var textureWide = texture.getPixelWidth();
+ var textureHigh = texture.getPixelHeight();
+ var itemWidthInPixels = node._itemWidth;
+ var itemHeightInPixels = node._itemHeight;
+ if (!node._ignoreContentScaleFactor) {
+ itemWidthInPixels = node._itemWidth * cc.contentScaleFactor();
+ itemHeightInPixels = node._itemHeight * cc.contentScaleFactor();
+ }
+ if (n > locTextureAtlas.getCapacity())
+ cc.log("cc.LabelAtlas._updateAtlasValues(): Invalid String length");
+ var quads = locTextureAtlas.quads;
+ var locDisplayedColor = this._displayedColor;
+ var curColor = {r: locDisplayedColor.r, g: locDisplayedColor.g, b: locDisplayedColor.b, a: node._displayedOpacity};
+ var locItemWidth = node._itemWidth;
+ var locItemHeight = node._itemHeight;
+ for (var i = 0, cr = -1; i < n; i++) {
+ var a = locString.charCodeAt(i) - node._mapStartChar.charCodeAt(0);
+ var row = a % node._itemsPerRow;
+ var col = 0 | (a / node._itemsPerRow);
+ if(row < 0 || col < 0)
+ continue;
+ if(row*locItemWidth + locItemWidth > textureWide || col*locItemHeight + locItemHeight > textureHigh)
+ continue;
+
+ cr++;
+ var left, right, top, bottom;
+ if (cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL) {
+ // Issue #938. Don't use texStepX & texStepY
+ left = (2 * row * itemWidthInPixels + 1) / (2 * textureWide);
+ right = left + (itemWidthInPixels * 2 - 2) / (2 * textureWide);
+ top = (2 * col * itemHeightInPixels + 1) / (2 * textureHigh);
+ bottom = top + (itemHeightInPixels * 2 - 2) / (2 * textureHigh);
+ } else {
+ left = row * itemWidthInPixels / textureWide;
+ right = left + itemWidthInPixels / textureWide;
+ top = col * itemHeightInPixels / textureHigh;
+ bottom = top + itemHeightInPixels / textureHigh;
+ }
+ var quad = quads[i];
+ var locQuadTL = quad.tl, locQuadTR = quad.tr, locQuadBL = quad.bl, locQuadBR = quad.br;
+ locQuadTL.texCoords.u = left;
+ locQuadTL.texCoords.v = top;
+ locQuadTR.texCoords.u = right;
+ locQuadTR.texCoords.v = top;
+ locQuadBL.texCoords.u = left;
+ locQuadBL.texCoords.v = bottom;
+ locQuadBR.texCoords.u = right;
+ locQuadBR.texCoords.v = bottom;
+
+ locQuadBL.vertices.x = (cr * locItemWidth);
+ locQuadBL.vertices.y = 0;
+ locQuadBL.vertices.z = 0.0;
+ locQuadBR.vertices.x = (cr * locItemWidth + locItemWidth);
+ locQuadBR.vertices.y = 0;
+ locQuadBR.vertices.z = 0.0;
+ locQuadTL.vertices.x = cr * locItemWidth;
+ locQuadTL.vertices.y = node._itemHeight;
+ locQuadTL.vertices.z = 0.0;
+ locQuadTR.vertices.x = cr * locItemWidth + locItemWidth;
+ locQuadTR.vertices.y = node._itemHeight;
+ locQuadTR.vertices.z = 0.0;
+ locQuadTL.colors = curColor;
+ locQuadTR.colors = curColor;
+ locQuadBL.colors = curColor;
+ locQuadBR.colors = curColor;
+ }
+ this.updateContentSize(i, cr+1);
+ if (n > 0) {
+ locTextureAtlas.dirty = true;
+ var totalQuads = locTextureAtlas.totalQuads;
+ if (n > totalQuads)
+ locTextureAtlas.increaseTotalQuadsWith(n - totalQuads);
+ }
+ };
+
+ proto.updateContentSize = function(i, cr){
+ var node = this._node,
+ contentSize = node._contentSize;
+ if(i !== cr && i*node._itemWidth === contentSize.width && node._itemHeight === contentSize.height){
+ node.setContentSize(cr * node._itemWidth, node._itemHeight);
+ }
+ };
+
+ proto.setString = function(label){
+ var len = label.length;
+ if (len > this._textureAtlas.totalQuads)
+ this._textureAtlas.resizeCapacity(len);
+ };
+
+ proto._addChild = function(){};
+})();
\ No newline at end of file
diff --git a/cocos2d/labels/CCLabelBMFont.js b/cocos2d/labels/CCLabelBMFont.js
new file mode 100644
index 0000000000..898a5bcdfa
--- /dev/null
+++ b/cocos2d/labels/CCLabelBMFont.js
@@ -0,0 +1,971 @@
+/****************************************************************************
+ 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.
+
+ Use any of these editors to generate BMFonts:
+ http://glyphdesigner.71squared.com/ (Commercial, Mac OS X)
+ http://www.n4te.com/hiero/hiero.jnlp (Free, Java)
+ http://slick.cokeandcode.com/demos/hiero.jnlp (Free, Java)
+ http://www.angelcode.com/products/bmfont/ (Free, Windows only)
+ ****************************************************************************/
+
+EventTarget = require("../cocos2d/core/event/event-target");
+
+/**
+ * @constant
+ * @type Number
+ */
+cc.LABEL_AUTOMATIC_WIDTH = -1;
+
+/**
+ * cc.LabelBMFont is a subclass of cc.SpriteBatchNode.
+ *
+ * Features:
+ *
- Treats each character like a cc.Sprite. This means that each individual character can be:
+ * - rotated
+ * - scaled
+ * - translated
+ * - tinted
+ * - change the opacity
+ * - It can be used as part of a menu item.
+ * - anchorPoint can be used to align the "label"
+ * - Supports AngelCode text format
+ *
+ * Limitations:
+ * - All inner characters are using an anchorPoint of (0.5, 0.5) and it is not recommend to change it
+ * because it might affect the rendering
+ *
+ * cc.LabelBMFont implements the protocol cc.LabelProtocol, like cc.Label and cc.LabelAtlas.
+ * cc.LabelBMFont has the flexibility of cc.Label, the speed of cc.LabelAtlas and all the features of cc.Sprite.
+ * If in doubt, use cc.LabelBMFont instead of cc.LabelAtlas / cc.Label.
+ *
+ * Supported editors:
+ * http://glyphdesigner.71squared.com/ (Commercial, Mac OS X)
+ * http://www.n4te.com/hiero/hiero.jnlp (Free, Java)
+ * http://slick.cokeandcode.com/demos/hiero.jnlp (Free, Java)
+ * http://www.angelcode.com/products/bmfont/ (Free, Windows only)
+ * @class
+ * @extends cc.SpriteBatchNode
+ *
+ * @property {String} string - Content string of label
+ * @property {cc.TextAlignment} textAlign - Horizontal Alignment of label
+ * @property {Number} boundingWidth - Width of the bounding box of label, the real content width is limited by boundingWidth
+ *
+ * @param {String} str
+ * @param {String} fntFile
+ * @param {Number} [width=-1]
+ * @param {cc.TextAlignment} [alignment=cc.TextAlignment.LEFT]
+ * @param {cc.Vec2} [imageOffset=cc.p(0,0)]
+ *
+ * @example
+ * // Example 01
+ * var label1 = new cc.LabelBMFont("Test case", "test.fnt");
+ *
+ * // Example 02
+ * var label2 = new cc.LabelBMFont("test case", "test.fnt", 200, cc.TextAlignment.LEFT);
+ *
+ * // Example 03
+ * var label3 = new cc.LabelBMFont("This is a \n test case", "test.fnt", 200, cc.TextAlignment.LEFT, cc.p(0,0));
+ */
+cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
+ //property string is Getter and Setter.
+ //property textAlign is Getter and Setter.
+ //property boundingWidth is Getter and Setter.
+ _opacityModifyRGB: false,
+
+ _string: "",
+ _config: null,
+
+ // name of fntFile
+ _fntFile: "",
+
+ // initial string without line breaks
+ _initialString: "",
+
+ // alignment of all lines
+ _alignment: cc.TextAlignment.CENTER,
+
+ // max width until a line break is added
+ _width: -1,
+ _lineBreakWithoutSpaces: false,
+ _imageOffset: null,
+
+ _reusedChar: null,
+
+ _textureLoaded: false,
+ _className: "LabelBMFont",
+
+ _createRenderCmd: function(){
+ if(cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ return new cc.LabelBMFont.WebGLRenderCmd(this);
+ else
+ return new cc.LabelBMFont.CanvasRenderCmd(this);
+ },
+
+ _setString: function (newString, needUpdateLabel) {
+ if (!needUpdateLabel) {
+ this._string = newString;
+ } else {
+ this._initialString = newString;
+ }
+ var locChildren = this._children;
+ if (locChildren) {
+ for (var i = 0; i < locChildren.length; i++) {
+ var selNode = locChildren[i];
+ if (selNode)
+ selNode.setVisible(false);
+ }
+ }
+ if (this._textureLoaded) {
+ this.createFontChars();
+ if (needUpdateLabel)
+ this.updateLabel();
+ }
+ },
+
+ /**
+ * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
+ * creates a bitmap font atlas with an initial string and the FNT file.
+ * @param {String} str
+ * @param {String} fntFile
+ * @param {Number} [width=-1]
+ * @param {cc.TextAlignment} [alignment=cc.TextAlignment.LEFT]
+ * @param {cc.Vec2} [imageOffset=cc.p(0,0)]
+ */
+ ctor: function (str, fntFile, width, alignment, imageOffset) {
+ cc.SpriteBatchNode.prototype.ctor.call(this);
+ this._imageOffset = cc.p(0, 0);
+ this._reusedChar = [];
+ this._cascadeColorEnabled = true;
+ this._cascadeOpacityEnabled = true;
+ this.initWithString(str, fntFile, width, alignment, imageOffset);
+ },
+
+ /**
+ * return texture is loaded
+ * @returns {boolean}
+ */
+ textureLoaded: function () {
+ return this._textureLoaded;
+ },
+
+ /**
+ * add texture loaded event listener.
+ * Will execute the callback in the loaded.
+ * @param {Function} callback
+ * @param {Object} target
+ * @deprecated since 3.1, please use EventTarget API instead
+ */
+ addLoadedEventListener: function (callback, target) {
+ this.once("load", callback, target);
+ },
+
+ /**
+ * Conforms to cc.RGBAProtocol protocol.
+ * @return {Boolean}
+ */
+ isOpacityModifyRGB: function () {
+ return this._opacityModifyRGB;
+ },
+
+ /**
+ * Set whether to support cc.RGBAProtocol protocol
+ * @param {Boolean} opacityModifyRGB
+ */
+ setOpacityModifyRGB: function (opacityModifyRGB) {
+ this._opacityModifyRGB = opacityModifyRGB;
+ var locChildren = this._children;
+ if (locChildren) {
+ for (var i = 0; i < locChildren.length; i++) {
+ var node = locChildren[i];
+ if (node)
+ node.opacityModifyRGB = this._opacityModifyRGB;
+ }
+ }
+ },
+
+ _changeTextureColor: function () {
+ this._renderCmd._changeTextureColor();
+ },
+
+ /**
+ * Initialization of the node, please do not call this function by yourself, you should pass the parameters to constructor to initialize it.
+ */
+ init: function () {
+ return this.initWithString(null, null, null, null, null);
+ },
+
+ /**
+ * init a bitmap font atlas with an initial string and the FNT file
+ * @param {String} str
+ * @param {String} fntFile
+ * @param {Number} [width=-1]
+ * @param {cc.TextAlignment} [alignment=cc.TextAlignment.LEFT]
+ * @param {cc.Vec2} [imageOffset=cc.p(0,0)]
+ * @return {Boolean}
+ */
+ initWithString: function (str, fntFile, width, alignment, imageOffset) {
+ var self = this, theString = str || "";
+ var cmd = this._renderCmd;
+
+ if (self._config)
+ cc.log("cc.LabelBMFont.initWithString(): re-init is no longer supported");
+
+ var texture;
+ if (fntFile) {
+ var newConf = cc.loader.getRes(fntFile);
+ if (!newConf) {
+ cc.log("cc.LabelBMFont.initWithString(): Impossible to create font. Please check file");
+ return false;
+ }
+
+ self._config = newConf;
+ self._fntFile = fntFile;
+ texture = cc.textureCache.addImage(newConf.atlasName);
+ var locIsLoaded = texture.isLoaded();
+ self._textureLoaded = locIsLoaded;
+ if (!locIsLoaded) {
+ texture.once("load", function (event) {
+ var self1 = this;
+ self1._textureLoaded = true;
+ //reset the LabelBMFont
+ self1.initWithTexture(texture, self1._initialString.length);
+ self1.setString(self1._initialString, true);
+ self1.emit("load");
+ }, self);
+ }
+ } else {
+ texture = new cc.Texture2D();
+ var image = new Image();
+ texture.initWithElement(image);
+ self._textureLoaded = false;
+ }
+
+ if (self.initWithTexture(texture, theString.length)) {
+ self._alignment = alignment || cc.TextAlignment.LEFT;
+ self._imageOffset = imageOffset || cc.p(0, 0);
+ self._width = (width == null) ? -1 : width;
+
+ self._realOpacity = 255;
+ self._realColor = cc.color(255, 255, 255, 255);
+
+ self._contentSize.width = 0;
+ self._contentSize.height = 0;
+
+ self.setAnchorPoint(0.5, 0.5);
+
+ this._renderCmd._initBatchTexture();
+
+ self.setString(theString, true);
+ return true;
+ }
+ return false;
+ },
+
+ /**
+ * updates the font chars based on the string to render
+ */
+ createFontChars: function () {
+ var self = this;
+ var cmd = this._renderCmd;
+ var locTexture = cmd._texture || self.textureAtlas.texture;
+
+ var nextFontPositionX = 0;
+
+ var tmpSize = cc.size(0, 0);
+
+ var longestLine = 0;
+
+ var quantityOfLines = 1;
+
+ var locStr = self._string;
+ var stringLen = locStr ? locStr.length : 0;
+
+ if (stringLen === 0)
+ return;
+
+ var i, locCfg = self._config, locKerningDict = locCfg.kerningDict,
+ locCommonH = locCfg.commonHeight, locFontDict = locCfg.fontDefDictionary;
+ for (i = 0; i < stringLen - 1; i++) {
+ if (locStr.charCodeAt(i) === 10) quantityOfLines++;
+ }
+
+ var totalHeight = locCommonH * quantityOfLines;
+ var nextFontPositionY = -(locCommonH - locCommonH * quantityOfLines);
+
+ var prev = -1;
+ for (i = 0; i < stringLen; i++) {
+ var key = locStr.charCodeAt(i);
+ if (key === 0) continue;
+
+ if (key === 10) {
+ //new line
+ nextFontPositionX = 0;
+ nextFontPositionY -= locCfg.commonHeight;
+ continue;
+ }
+
+ var kerningAmount = locKerningDict[(prev << 16) | (key & 0xffff)] || 0;
+ var fontDef = locFontDict[key];
+ if (!fontDef) {
+ cc.log("cocos2d: LabelBMFont: character not found " + locStr[i]);
+
+ fontDef = {
+ rect: {
+ x: 0,
+ y: 0,
+ width: 0,
+ height: 0
+ },
+ xOffset: 0,
+ yOffset: 0,
+ xAdvance: 0
+ };
+ }
+
+ var rect = cc.rect(fontDef.rect.x, fontDef.rect.y, fontDef.rect.width, fontDef.rect.height);
+ rect = cc.rectPixelsToPoints(rect);
+ rect.x += self._imageOffset.x;
+ rect.y += self._imageOffset.y;
+
+ var fontChar = self.getChildByTag(i);
+
+ if(!fontChar){
+ fontChar = new cc.Sprite();
+ fontChar.initWithTexture(locTexture, rect, false);
+ fontChar._newTextureWhenChangeColor = true;
+ this.addChild(fontChar, 0, i);
+ }else{
+ this._renderCmd._updateCharTexture(fontChar, rect, key);
+ }
+
+ // Apply label properties
+ fontChar.opacityModifyRGB = this._opacityModifyRGB;
+ this._renderCmd._updateCharColorAndOpacity(fontChar);
+
+ var yOffset = locCfg.commonHeight - fontDef.yOffset;
+ var fontPos = cc.p(nextFontPositionX + fontDef.xOffset + fontDef.rect.width * 0.5 + kerningAmount,
+ nextFontPositionY + yOffset - rect.height * 0.5 * cc.contentScaleFactor());
+ fontChar.setPosition(cc.pointPixelsToPoints(fontPos));
+
+ // update kerning
+ nextFontPositionX += fontDef.xAdvance + kerningAmount;
+ prev = key;
+
+ if (longestLine < nextFontPositionX)
+ longestLine = nextFontPositionX;
+ }
+
+ //If the last character processed has an xAdvance which is less that the width of the characters image, then we need
+ // to adjust the width of the string to take this into account, or the character will overlap the end of the bounding box
+ if(fontDef && fontDef.xAdvance < fontDef.rect.width)
+ tmpSize.width = longestLine - fontDef.xAdvance + fontDef.rect.width;
+ else
+ tmpSize.width = longestLine;
+ tmpSize.height = totalHeight;
+ self.setContentSize(cc.sizePixelsToPoints(tmpSize));
+ },
+
+ /**
+ * Update String.
+ * Only update this label display string.
+ * @param {Boolean} fromUpdate
+ */
+ updateString: function (fromUpdate) {
+ var self = this;
+ var locChildren = self._children;
+ if (locChildren) {
+ for (var i = 0, li = locChildren.length; i < li; i++) {
+ var node = locChildren[i];
+ if (node) node.visible = false;
+ }
+ }
+ if (self._config)
+ self.createFontChars();
+
+ if (!fromUpdate)
+ self.updateLabel();
+ },
+
+ /**
+ * Gets the text of this label
+ * @return {String}
+ */
+ getString: function () {
+ return this._initialString;
+ },
+
+ /**
+ * Set the text
+ * @param {String} newString
+ * @param {Boolean|null} needUpdateLabel
+ */
+ setString: function (newString, needUpdateLabel) {
+ newString = String(newString);
+ if (needUpdateLabel == null)
+ needUpdateLabel = true;
+ if (newString == null || !cc.js.isString(newString))
+ newString = newString + "";
+
+ this._initialString = newString;
+ this._setString(newString, needUpdateLabel);
+ },
+
+ _setStringForSetter: function (newString) {
+ this.setString(newString, false);
+ },
+
+ /**
+ * Set the text.
+ * Change this Label display string.
+ * @deprecated since v3.0 please use .setString
+ * @param label
+ */
+ setCString: function (label) {
+ this.setString(label, true);
+ },
+
+ // calc the text all with in a line
+ _getCharsWidth:function (startIndex, endIndex) {
+ if (endIndex <= 0)
+ {
+ return 0;
+ }
+ var curTextFirstSprite = this.getChildByTag(startIndex);
+ var curTextLastSprite = this.getChildByTag(startIndex + endIndex);
+ return this._getLetterPosXLeft(curTextLastSprite) - this._getLetterPosXLeft(curTextFirstSprite);
+ },
+
+ _checkWarp:function (strArr, i, maxWidth, initStringWrapNum) {
+ var self = this;
+ var text = strArr[i];
+ var curLength = 0;
+ for (var strArrIndex = 0; strArrIndex < i; strArrIndex++)
+ {
+ curLength += strArr[strArrIndex].length;
+ }
+
+ curLength = curLength + i - initStringWrapNum; // add the wrap line num
+
+ var allWidth = self._getCharsWidth(curLength, strArr[i].length - 1);
+
+ if (allWidth > maxWidth && text.length > 1) {
+ var fuzzyLen = text.length * ( maxWidth / allWidth ) | 0;
+ var tmpText = text.substr(fuzzyLen);
+ var width = allWidth - this._getCharsWidth(curLength + fuzzyLen, tmpText.length - 1);
+ var sLine;
+ var pushNum = 0;
+
+ //Increased while cycle maximum ceiling. default 100 time
+ var checkWhile = 0;
+
+ //Exceeded the size
+ while (width > maxWidth && checkWhile++ < 100) {
+ fuzzyLen *= maxWidth / width;
+ fuzzyLen = fuzzyLen | 0;
+ tmpText = text.substr(fuzzyLen);
+ width = allWidth - this._getCharsWidth(curLength + fuzzyLen, tmpText.length - 1);
+ }
+
+ checkWhile = 0;
+
+ //Find the truncation point
+ while (width < maxWidth && checkWhile++ < 100) {
+ if (tmpText) {
+ var exec = cc.LabelTTF._wordRex.exec(tmpText);
+ pushNum = exec ? exec[0].length : 1;
+ sLine = tmpText;
+ }
+ if (self._lineBreakWithoutSpaces) {
+ pushNum = 0;
+ }
+ fuzzyLen = fuzzyLen + pushNum;
+ tmpText = text.substr(fuzzyLen);
+ width = allWidth - this._getCharsWidth(curLength + fuzzyLen, tmpText.length - 1);
+ }
+
+ fuzzyLen -= pushNum;
+ if (fuzzyLen === 0) {
+ fuzzyLen = 1;
+ sLine = sLine.substr(1);
+ }
+
+ var sText = text.substr(0, fuzzyLen), result;
+
+ //symbol in the first
+ if (cc.LabelTTF.wrapInspection) {
+ if (cc.LabelTTF._symbolRex.test(sLine || tmpText)) {
+ result = cc.LabelTTF._lastWordRex.exec(sText);
+ pushNum = result ? result[0].length : 0;
+ if (self._lineBreakWithoutSpaces) {
+ pushNum = 0;
+ }
+ fuzzyLen -= pushNum;
+
+ sLine = text.substr(fuzzyLen);
+ sText = text.substr(0, fuzzyLen);
+ }
+ }
+
+ //To judge whether a English words are truncated
+ if (cc.LabelTTF._firsrEnglish.test(sLine)) {
+ result = cc.LabelTTF._lastEnglish.exec(sText);
+ if (result && sText !== result[0]) {
+ pushNum = result[0].length;
+ if (self._lineBreakWithoutSpaces) {
+ pushNum = 0;
+ }
+ fuzzyLen -= pushNum;
+ sLine = text.substr(fuzzyLen);
+ sText = text.substr(0, fuzzyLen);
+ }
+ }
+ strArr[i] = sLine || tmpText;
+ strArr.splice(i, 0, sText);
+ }
+ },
+
+ /**
+ * Update Label.
+ * Update this Label display string and more...
+ */
+ updateLabel: function () {
+ var self = this;
+ self.string = self._initialString;
+ var i, j, characterSprite;
+ // process string
+ // Step 1: Make multiline
+ if (self._width > 0) {
+ var stringArr = self.string.split('\n');
+ var wrapString = "";
+ var newWrapNum = 0;
+ var oldArrLength = 0;
+ for (i = 0; i < stringArr.length; i++) {
+ oldArrLength = stringArr.length;
+ this._checkWarp(stringArr, i, self._width * this._scaleX, newWrapNum);
+ if (oldArrLength < stringArr.length) {
+ newWrapNum++;
+ }
+ if (i > 0)
+ {
+ wrapString += "\n";
+ }
+ wrapString += stringArr[i];
+ }
+ wrapString = wrapString + String.fromCharCode(0);
+ self._setString(wrapString, false);
+ }
+
+ // Step 2: Make alignment
+ if (self._alignment !== cc.TextAlignment.LEFT) {
+ i = 0;
+
+ var lineNumber = 0;
+ var strlen = self._string.length;
+ var last_line = [];
+
+ for (var ctr = 0; ctr < strlen; ctr++) {
+ if (self._string[ctr].charCodeAt(0) === 10 || self._string[ctr].charCodeAt(0) === 0) {
+ var lineWidth = 0;
+ var line_length = last_line.length;
+ // if last line is empty we must just increase lineNumber and work with next line
+ if (line_length === 0) {
+ lineNumber++;
+ continue;
+ }
+ var index = i + line_length - 1 + lineNumber;
+ if (index < 0) continue;
+
+ var lastChar = self.getChildByTag(index);
+ if (lastChar == null)
+ continue;
+ lineWidth = lastChar.getPositionX() + lastChar._getWidth() / 2;
+
+ var shift = 0;
+ switch (self._alignment) {
+ case cc.TextAlignment.CENTER:
+ shift = self.width / 2 - lineWidth / 2;
+ break;
+ case cc.TextAlignment.RIGHT:
+ shift = self.width - lineWidth;
+ break;
+ default:
+ break;
+ }
+
+ if (shift !== 0) {
+ for (j = 0; j < line_length; j++) {
+ index = i + j + lineNumber;
+ if (index < 0) continue;
+ characterSprite = self.getChildByTag(index);
+ if (characterSprite)
+ characterSprite.x += shift;
+ }
+ }
+
+ i += line_length;
+ lineNumber++;
+
+ last_line.length = 0;
+ continue;
+ }
+ last_line.push(self._string[i]);
+ }
+ }
+ },
+
+ /**
+ * Set text alignment.
+ * @param {Number} alignment
+ */
+ setAlignment: function (alignment) {
+ this._alignment = alignment;
+ this.updateLabel();
+ },
+
+ _getAlignment: function () {
+ return this._alignment;
+ },
+
+ /**
+ * Set the bounding width.
+ * max with display width. The exceeding string will be wrapping.
+ * @param {Number} width
+ */
+ setBoundingWidth: function (width) {
+ this._width = width;
+ this.updateLabel();
+ },
+
+ _getBoundingWidth: function () {
+ return this._width;
+ },
+
+ /**
+ * Set the param to change English word warp according to whether the space.
+ * default is false.
+ * @param {Boolean} breakWithoutSpace
+ */
+ setLineBreakWithoutSpace: function (breakWithoutSpace) {
+ this._lineBreakWithoutSpaces = breakWithoutSpace;
+ this.updateLabel();
+ },
+
+ /**
+ * Set scale.
+ * Input a number, will be decrease or increase the font size.
+ * @param {Number} scale
+ * @param {Number} [scaleY=null] default is scale
+ */
+ setScale: function (scale, scaleY) {
+ cc.Node.prototype.setScale.call(this, scale, scaleY);
+ this.updateLabel();
+ },
+
+ /**
+ * Set scale of x.
+ * Input a number, will be decrease or increase the font size.
+ * Horizontal scale.
+ * @param {Number} scaleX
+ */
+ setScaleX: function (scaleX) {
+ cc.Node.prototype.setScaleX.call(this, scaleX);
+ this.updateLabel();
+ },
+
+ /**
+ * Set scale of x.
+ * Input a number, will be decrease or increase the font size.
+ * Longitudinal scale.
+ * @param {Number} scaleY
+ */
+ setScaleY: function (scaleY) {
+ cc.Node.prototype.setScaleY.call(this, scaleY);
+ this.updateLabel();
+ },
+
+ /**
+ * set fnt file path.
+ * Change the fnt file path.
+ * @param {String} fntFile
+ */
+ setFntFile: function (fntFile) {
+ var self = this;
+ if (fntFile != null && fntFile !== self._fntFile) {
+ var newConf = cc.loader.getRes(fntFile);
+
+ if (!newConf) {
+ cc.log("cc.LabelBMFont.setFntFile() : Impossible to create font. Please check file");
+ return;
+ }
+
+ self._fntFile = fntFile;
+ self._config = newConf;
+
+ var texture = cc.textureCache.addImage(newConf.atlasName);
+ var locIsLoaded = texture.isLoaded();
+ self._textureLoaded = locIsLoaded;
+ self.texture = texture;
+ if (!locIsLoaded) {
+ texture.once("load", function (event) {
+ var self1 = this;
+ self1._textureLoaded = true;
+ self1.texture = texture;
+ self1.createFontChars();
+ self1._changeTextureColor();
+ self1.updateLabel();
+
+ self1.emit("load");
+ }, self);
+ } else {
+ self.createFontChars();
+ }
+ }
+ },
+
+ /**
+ * Return the fnt file path.
+ * @return {String}
+ */
+ getFntFile: function () {
+ return this._fntFile;
+ },
+
+ setTexture: function(texture){
+ this._renderCmd.setTexture(texture);
+ },
+
+ /**
+ * Set the AnchorPoint of the labelBMFont.
+ * In order to change the location of label.
+ * @override
+ * @param {cc.Vec2|Number} point The anchor point of labelBMFont or The anchor point.x of labelBMFont.
+ * @param {Number} [y] The anchor point.y of labelBMFont.
+ */
+ setAnchorPoint: function (point, y) {
+ cc.Node.prototype.setAnchorPoint.call(this, point, y);
+ this.updateLabel();
+ },
+
+ _setAnchorX: function (x) {
+ cc.Node.prototype._setAnchorX.call(this, x);
+ this.updateLabel();
+ },
+
+ _setAnchorY: function (y) {
+ cc.Node.prototype._setAnchorY.call(this, y);
+ this.updateLabel();
+ },
+
+ _atlasNameFromFntFile: function (fntFile) {},
+
+ _kerningAmountForFirst: function (first, second) {
+ var ret = 0;
+ var key = (first << 16) | (second & 0xffff);
+ if (this._configuration.kerningDictionary) {
+ var element = this._configuration.kerningDictionary[key.toString()];
+ if (element)
+ ret = element.amount;
+ }
+ return ret;
+ },
+
+ _getLetterPosXLeft: function (sp) {
+ return sp.getPositionX() * this._scaleX - (sp._getWidth() * this._scaleX * sp._getAnchorX());
+ },
+
+ _getLetterPosXRight: function (sp) {
+ return sp.getPositionX() * this._scaleX + (sp._getWidth() * this._scaleX * sp._getAnchorX());
+ },
+
+ //Checking whether the character is a whitespace
+ _isspace_unicode: function(ch){
+ ch = ch.charCodeAt(0);
+ return ((ch >= 9 && ch <= 13) || ch === 32 || ch === 133 || ch === 160 || ch === 5760
+ || (ch >= 8192 && ch <= 8202) || ch === 8232 || ch === 8233 || ch === 8239
+ || ch === 8287 || ch === 12288)
+ },
+
+ _utf8_trim_ws: function(str){
+ var len = str.length;
+
+ if (len <= 0)
+ return;
+
+ var last_index = len - 1;
+
+ // Only start trimming if the last character is whitespace..
+ if (this._isspace_unicode(str[last_index])) {
+ for (var i = last_index - 1; i >= 0; --i) {
+ if (this._isspace_unicode(str[i])) {
+ last_index = i;
+ }
+ else {
+ break;
+ }
+ }
+ this._utf8_trim_from(str, last_index);
+ }
+ },
+
+ //Trims str st str=[0, index) after the operation.
+ //Return value: the trimmed string.
+ _utf8_trim_from: function(str, index){
+ var len = str.length;
+ if (index >= len || index < 0)
+ return;
+ str.splice(index, len);
+ }
+});
+
+(function(){
+ var p = cc.LabelBMFont.prototype;
+ EventTarget.polyfill(p);
+
+ /** @expose */
+ p.string;
+ cc.defineGetterSetter(p, "string", p.getString, p._setStringForSetter);
+ /** @expose */
+ p.boundingWidth;
+ cc.defineGetterSetter(p, "boundingWidth", p._getBoundingWidth, p.setBoundingWidth);
+ /** @expose */
+ p.textAlign;
+ cc.defineGetterSetter(p, "textAlign", p._getAlignment, p.setAlignment);
+})();
+
+/**
+ * creates a bitmap font atlas with an initial string and the FNT file
+ * @deprecated since v3.0 please use new cc.LabelBMFont
+ * @param {String} str
+ * @param {String} fntFile
+ * @param {Number} [width=-1]
+ * @param {cc.TextAlignment} [alignment=cc.TextAlignment.LEFT]
+ * @param {cc.Vec2} [imageOffset=cc.p(0,0)]
+ * @return {cc.LabelBMFont|Null}
+ */
+cc.LabelBMFont.create = function (str, fntFile, width, alignment, imageOffset) {
+ return new cc.LabelBMFont(str, fntFile, width, alignment, imageOffset);
+};
+
+cc._fntLoader = {
+ INFO_EXP: /info [^\n]*(\n|$)/gi,
+ COMMON_EXP: /common [^\n]*(\n|$)/gi,
+ PAGE_EXP: /page [^\n]*(\n|$)/gi,
+ CHAR_EXP: /char [^\n]*(\n|$)/gi,
+ KERNING_EXP: /kerning [^\n]*(\n|$)/gi,
+ ITEM_EXP: /\w+=[^ \r\n]+/gi,
+ INT_EXP: /^[\-]?\d+$/,
+
+ _parseStrToObj: function (str) {
+ var arr = str.match(this.ITEM_EXP);
+ var obj = {};
+ if (arr) {
+ for (var i = 0, li = arr.length; i < li; i++) {
+ var tempStr = arr[i];
+ var index = tempStr.indexOf("=");
+ var key = tempStr.substring(0, index);
+ var value = tempStr.substring(index + 1);
+ if (value.match(this.INT_EXP)) value = parseInt(value);
+ else if (value[0] === '"') value = value.substring(1, value.length - 1);
+ obj[key] = value;
+ }
+ }
+ return obj;
+ },
+
+ /**
+ * Parse Fnt string.
+ * @param fntStr
+ * @param url
+ * @returns {{}}
+ */
+ parseFnt: function (fntStr, url) {
+ var self = this, fnt = {};
+ //padding
+ var infoObj = self._parseStrToObj(fntStr.match(self.INFO_EXP)[0]);
+ var paddingArr = infoObj["padding"].split(",");
+ var padding = {
+ left: parseInt(paddingArr[0]),
+ top: parseInt(paddingArr[1]),
+ right: parseInt(paddingArr[2]),
+ bottom: parseInt(paddingArr[3])
+ };
+
+ //common
+ var commonObj = self._parseStrToObj(fntStr.match(self.COMMON_EXP)[0]);
+ fnt.commonHeight = commonObj["lineHeight"];
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
+ var texSize = cc.configuration.getMaxTextureSize();
+ if (commonObj["scaleW"] > texSize.width || commonObj["scaleH"] > texSize.height)
+ cc.log("cc.LabelBMFont._parseCommonArguments(): page can't be larger than supported");
+ }
+ if (commonObj["pages"] !== 1) cc.log("cc.LabelBMFont._parseCommonArguments(): only supports 1 page");
+
+ //page
+ var pageObj = self._parseStrToObj(fntStr.match(self.PAGE_EXP)[0]);
+ if (pageObj["id"] !== 0) cc.log("cc.LabelBMFont._parseImageFileName() : file could not be found");
+ fnt.atlasName = cc.path.changeBasename(url, pageObj["file"]);
+
+ //char
+ var charLines = fntStr.match(self.CHAR_EXP);
+ var fontDefDictionary = fnt.fontDefDictionary = {};
+ for (var i = 0, li = charLines.length; i < li; i++) {
+ var charObj = self._parseStrToObj(charLines[i]);
+ var charId = charObj["id"];
+ fontDefDictionary[charId] = {
+ rect: {x: charObj["x"], y: charObj["y"], width: charObj["width"], height: charObj["height"]},
+ xOffset: charObj["xoffset"],
+ yOffset: charObj["yoffset"],
+ xAdvance: charObj["xadvance"]
+ };
+ }
+
+ //kerning
+ var kerningDict = fnt.kerningDict = {};
+ var kerningLines = fntStr.match(self.KERNING_EXP);
+ if (kerningLines) {
+ for (var i = 0, li = kerningLines.length; i < li; i++) {
+ var kerningObj = self._parseStrToObj(kerningLines[i]);
+ kerningDict[(kerningObj["first"] << 16) | (kerningObj["second"] & 0xffff)] = kerningObj["amount"];
+ }
+ }
+ return fnt;
+ },
+
+ /**
+ * load the fnt
+ * @param realUrl
+ * @param url
+ * @param res
+ * @param cb
+ */
+ load: function (realUrl, url, res, cb) {
+ var self = this;
+ cc.loader.loadTxt(realUrl, function (err, txt) {
+ if (err) return cb(err);
+ cb(null, self.parseFnt(txt, url));
+ });
+ }
+};
+cc.loader.register(["fnt"], cc._fntLoader);
diff --git a/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js b/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js
new file mode 100644
index 0000000000..1d43842993
--- /dev/null
+++ b/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js
@@ -0,0 +1,107 @@
+/****************************************************************************
+ 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.
+
+ Use any of these editors to generate BMFonts:
+ http://glyphdesigner.71squared.com/ (Commercial, Mac OS X)
+ http://www.n4te.com/hiero/hiero.jnlp (Free, Java)
+ http://slick.cokeandcode.com/demos/hiero.jnlp (Free, Java)
+ http://www.angelcode.com/products/bmfont/ (Free, Windows only)
+ ****************************************************************************/
+
+(function(){
+ cc.LabelBMFont.CanvasRenderCmd = function(renderableObject){
+ cc.SpriteBatchNode.CanvasRenderCmd.call(this, renderableObject);
+ this._needDraw = true;
+ };
+
+ var proto = cc.LabelBMFont.CanvasRenderCmd.prototype = Object.create(cc.SpriteBatchNode.CanvasRenderCmd.prototype);
+ proto.constructor = cc.LabelBMFont.CanvasRenderCmd;
+
+ proto.rendering = function(){
+ void 0;
+ };
+
+ proto._updateCharTexture = function(fontChar, rect, key){
+ if (key === 32) {
+ fontChar.setTextureRect(rect, false, cc.size(0, 0));
+ } else {
+ // updating previous sprite
+ fontChar.setTextureRect(rect, false);
+ // restore to default in case they were modified
+ fontChar.visible = true;
+ }
+ };
+
+ proto._updateCharColorAndOpacity = function(fontChar){
+ // Color MUST be set before opacity, since opacity might change color if OpacityModifyRGB is on
+ fontChar._displayedColor = this._displayedColor;
+ fontChar._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty);
+ fontChar._displayedOpacity = this._displayedOpacity;
+ fontChar._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.opacityDirty);
+ };
+
+ proto.setTexture = function (texture) {
+ var node = this._node;
+ var locChildren = node._children;
+ var locDisplayedColor = this._displayedColor;
+ for (var i = 0; i < locChildren.length; i++) {
+ var selChild = locChildren[i];
+ var cm = selChild._renderCmd;
+ var childDColor = cm._displayedColor;
+ if (this._texture !== cm._texture && (childDColor.r !== locDisplayedColor.r ||
+ childDColor.g !== locDisplayedColor.g || childDColor.b !== locDisplayedColor.b))
+ continue;
+ selChild.texture = texture;
+ }
+ this._texture = texture;
+ };
+
+ proto._changeTextureColor = function(){
+ var node = this._node;
+ var texture = this._textureToRender,
+ contentSize = texture.getContentSize();
+
+ var oTexture = node._texture,
+ oElement = oTexture.getHtmlElementObj();
+ var disColor = this._displayedColor;
+ var textureRect = cc.rect(0, 0, oElement.width, oElement.height);
+ if(texture && contentSize.width > 0){
+ if(!oElement)
+ return;
+ this._textureToRender = oTexture._generateColorTexture(disColor.r, disColor.g, disColor.b, textureRect);
+ }
+ };
+
+ proto._updateChildrenDisplayedOpacity = function(locChild){
+ cc.Node.prototype.updateDisplayedOpacity.call(locChild, this._displayedOpacity);
+ };
+
+ proto._updateChildrenDisplayedColor = function(locChild){
+ cc.Node.prototype.updateDisplayedColor.call(locChild, this._displayedColor);
+ };
+
+ proto._initBatchTexture = function(){};
+
+})();
\ No newline at end of file
diff --git a/cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js b/cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js
new file mode 100644
index 0000000000..69c126cf6d
--- /dev/null
+++ b/cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js
@@ -0,0 +1,84 @@
+/****************************************************************************
+ 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.
+
+ Use any of these editors to generate BMFonts:
+ http://glyphdesigner.71squared.com/ (Commercial, Mac OS X)
+ http://www.n4te.com/hiero/hiero.jnlp (Free, Java)
+ http://slick.cokeandcode.com/demos/hiero.jnlp (Free, Java)
+ http://www.angelcode.com/products/bmfont/ (Free, Windows only)
+ ****************************************************************************/
+
+(function(){
+ cc.LabelBMFont.WebGLRenderCmd = function(renderableObject){
+ cc.SpriteBatchNode.WebGLRenderCmd.call(this, renderableObject);
+ this._needDraw = true;
+ };
+
+ var proto = cc.LabelBMFont.WebGLRenderCmd.prototype = Object.create(cc.SpriteBatchNode.WebGLRenderCmd.prototype);
+ proto.constructor = cc.LabelBMFont.WebGLRenderCmd;
+
+ proto._updateCharTexture = function(fontChar, rect, key){
+ // updating previous sprite
+ fontChar.setTextureRect(rect, false);
+ // restore to default in case they were modified
+ fontChar.visible = true;
+ };
+
+ proto._changeTextureColor = function(){};
+
+ proto._updateChildrenDisplayedOpacity = function(locChild){
+ locChild.updateDisplayedOpacity(this._displayedOpacity);
+ };
+
+ proto._updateChildrenDisplayedColor = function(locChild){
+ locChild.updateDisplayedColor(this._displayedColor);
+ };
+
+ proto._initBatchTexture = function(){
+ var node = this._node;
+ var locTexture = node.textureAtlas.texture;
+ node._opacityModifyRGB = locTexture.hasPremultipliedAlpha();
+
+ var reusedChar = node._reusedChar = new cc.Sprite();
+ reusedChar.initWithTexture(locTexture, cc.rect(0, 0, 0, 0), false);
+ reusedChar.batchNode = node;
+ };
+
+ proto.rendering = function(ctx){
+ cc.SpriteBatchNode.WebGLRenderCmd.prototype.rendering.call(this, ctx);
+
+ var node = this._node;
+ //LabelBMFont - Debug draw
+ if (cc.LABELBMFONT_DEBUG_DRAW) {
+ var size = node.getContentSize();
+ var pos = cc.p(0 | ( -this._anchorPointInPoints.x), 0 | ( -this._anchorPointInPoints.y));
+ var vertices = [cc.p(pos.x, pos.y), cc.p(pos.x + size.width, pos.y), cc.p(pos.x + size.width, pos.y + size.height), cc.p(pos.x, pos.y + size.height)];
+ cc._drawingUtil.setDrawColor(0, 255, 0, 255);
+ cc._drawingUtil.drawPoly(vertices, 4, true);
+ }
+ };
+
+ proto._updateCharColorAndOpacity = function(){};
+})();
\ No newline at end of file
diff --git a/cocos2d/labels/CCLabelCanvasRenderCmd.js b/cocos2d/labels/CCLabelCanvasRenderCmd.js
new file mode 100644
index 0000000000..c692ba6475
--- /dev/null
+++ b/cocos2d/labels/CCLabelCanvasRenderCmd.js
@@ -0,0 +1,338 @@
+/****************************************************************************
+ 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.
+
+ Use any of these editors to generate BMFonts:
+ http://glyphdesigner.71squared.com/ (Commercial, Mac OS X)
+ http://www.n4te.com/hiero/hiero.jnlp (Free, Java)
+ http://slick.cokeandcode.com/demos/hiero.jnlp (Free, Java)
+ http://www.angelcode.com/products/bmfont/ (Free, Windows only)
+ ****************************************************************************/
+(function() {
+ cc.Label.TTFLabelBaker = function() {
+
+ };
+ var proto = cc.Label.TTFLabelBaker.prototype = Object.create(Object.prototype);
+ proto._getLineHeight = function() {
+ //todo refine it
+ var nodeSpacingY = this._node._spacingY;
+ if(nodeSpacingY === 0) nodeSpacingY = this._drawFontsize;
+ else { nodeSpacingY = nodeSpacingY * this._drawFontsize / this._node._fontSize;}
+ return nodeSpacingY | 0;
+ };
+
+ proto._prepareQuad = function() {
+ var quad = this._quad;
+ var white = cc.color(255,255,255,this._displayedOpacity);
+ var width = this._node._contentSize.width;
+ var height = this._node._contentSize.height;
+ quad._bl.colors = white;
+ quad._br.colors = white;
+ quad._tl.colors = white;
+ quad._tr.colors = white;
+
+ quad._bl.vertices = new cc.Vertex3F(0,0,0);
+ quad._br.vertices = new cc.Vertex3F(width,0,0);
+ quad._tl.vertices = new cc.Vertex3F(0,height,0);
+ quad._tr.vertices = new cc.Vertex3F(width,height,0);
+
+ //texture coordinate should be y-flipped
+ quad._bl.texCoords = new cc.Tex2F(0,1);
+ quad._br.texCoords = new cc.Tex2F(1,1);
+ quad._tl.texCoords = new cc.Tex2F(0,0);
+ quad._tr.texCoords = new cc.Tex2F(1,0);
+
+ this._quadDirty = true;
+ };
+
+ proto._fragmentText = function fragmentText(text, maxWidth, ctx) {
+ var words = text.split(' '),
+ lines = [],
+ line = "";
+ if (ctx.measureText(text).width < maxWidth) {
+ return [text];
+ }
+ while (words.length > 0) {
+ while (ctx.measureText(words[0]).width >= maxWidth && words[0].length > 1) {
+ var tmp = words[0];
+ words[0] = tmp.slice(0, -1);
+ if (words.length > 1) {
+ words[1] = tmp.slice(-1) + words[1];
+ } else {
+ words.push(tmp.slice(-1));
+ }
+ }
+ if (ctx.measureText(line + words[0]).width < maxWidth) {
+ line += words.shift() + " ";
+ } else if(line.length === 0 && words[0].length === 1){
+ lines.push(words.shift());
+ } else {
+ lines.push(line.slice(0,-1));
+ line = "";
+ }
+ if (words.length === 0 && line.length > 0) {
+ lines.push(line);
+ }
+ }
+ return lines;
+ };
+ proto._updateDisplayOpacity = function(parentOpacity) {
+ cc.Node.RenderCmd.prototype._updateDisplayOpacity.call(this, parentOpacity);
+ //specify opacity to quad
+ var color = cc.color(255,255,255,this._displayedOpacity);
+ var quad = this._quad;
+ quad._bl.colors = color;
+ quad._br.colors = color;
+ quad._tl.colors = color;
+ quad._tr.colors = color;
+ this._quadDirty = true;
+ };
+ proto.updateStatus = function () {
+ cc.Node.RenderCmd.prototype.updateStatus.call(this);
+
+ var textDirty = this._dirtyFlag & cc.Node._dirtyFlags.textDirty;
+ if(textDirty) {
+ this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.textDirty ^ this._dirtyFlag;
+ }
+ };
+ proto._bakeLabel = function() {
+ var node = this._node;
+ this._drawFontsize = node._fontSize;
+ var ctx = this._labelContext;
+ var canvasSizeX = node._contentSize.width;
+ var canvasSizeY = node._contentSize.height;
+ if(canvasSizeX <=0) canvasSizeX = 1;
+ if(canvasSizeY <=0) canvasSizeY = 1;
+ var paragraphedStrings = node._string.split("\n");
+ var paragraphLength = [];
+ this._drawFontsize = node._fontSize;
+ var fontDesc = this._drawFontsize.toString() + "px ";
+ var fontFamily = node._fontHandle.length === 0? "serif" : node._fontHandle;
+ fontDesc = fontDesc + fontFamily;
+ this._labelContext.font = fontDesc;
+ for(var i = 0; i < paragraphedStrings.length; ++i) {
+ var textMetric = ctx.measureText(paragraphedStrings[i]);
+ paragraphLength.push(textMetric.width);
+ }
+
+ if(cc.Label.Overflow.CLAMP == node._overFlow) {
+ if(node._isWrapText) {
+ this._splitedStrings = [];
+ for(var i = 0; i < paragraphedStrings.length; ++i) {
+ this._splitedStrings = this._splitedStrings.concat(this._fragmentText(paragraphedStrings[i], canvasSizeX, ctx));
+ }
+ }
+ else {
+ this._splitedStrings = paragraphedStrings;
+ }
+ }
+ else if(cc.Label.Overflow.RESIZE == node._overFlow) {
+ //todo fix it
+ if(node._isWrapText) {
+ this._splitedStrings = [];
+ for(var i = 0; i < paragraphedStrings.length; ++i) {
+ this._splitedStrings = this._splitedStrings.concat(this._fragmentText(paragraphedStrings[i], canvasSizeX, ctx));
+ }
+ canvasSizeY = this._splitedStrings.length * this._getLineHeight();
+ node.setContentSize(cc.size(canvasSizeX,canvasSizeY));
+ }
+ else {
+ this._splitedStrings = paragraphedStrings;
+ canvasSizeY = this._splitedStrings.length * this._getLineHeight();
+ node.setContentSize(cc.size(canvasSizeX,canvasSizeY));
+ }
+ }
+ else {
+ this._splitedStrings = paragraphedStrings;
+ //shrink
+ if(node._isWrapText) {
+ var totalLength = 0;
+ for(var i = 0; i < paragraphedStrings.length; ++i) { totalLength += ((paragraphLength[i]/canvasSizeX + 1) | 0) * canvasSizeX; }
+ var scale = canvasSizeX * ((canvasSizeY/this._getLineHeight())|0)/totalLength;
+ this._drawFontsize = (this._drawFontsize * Math.min(Math.sqrt(scale),1) ) | 0;
+ fontDesc = this._drawFontsize.toString() + "px " + fontFamily;
+ this._labelContext.font = fontDesc;
+ //
+ this._splitedStrings = [];
+ for(var i = 0; i < paragraphedStrings.length; ++i) {
+ this._splitedStrings = this._splitedStrings.concat(this._fragmentText(paragraphedStrings[i], canvasSizeX, ctx));
+ }
+ }
+ else {
+ var maxLength = 0;
+ var totalHeight = paragraphedStrings.length * this._getLineHeight();
+ for(var i = 0; i < paragraphedStrings.length; ++i) {
+ if(maxLength < paragraphLength[i]) maxLength = paragraphLength[i];
+ }
+ var scaleX = canvasSizeX/maxLength;
+ var scaleY = canvasSizeY/totalHeight;
+
+ this._drawFontsize = (this._drawFontsize * Math.min(1, scaleX, scaleY)) | 0;
+ fontDesc = this._drawFontsize.toString() + "px " + fontFamily;
+ this._splitedStrings = paragraphedStrings;
+ }
+
+ }
+
+ this._labelCanvas.width = canvasSizeX;
+ this._labelCanvas.height = canvasSizeY;
+ this._labelContext.clearRect(0,0,this._labelCanvas.width,this._labelCanvas.height);
+ //this._labelContext.fillStyle = "rgb(128,128,128)";
+ //this._labelContext.fillRect(0,0,this._labelCanvas.width,this._labelCanvas.height);
+ var color = this._displayedColor;
+ this._labelContext.fillStyle = "rgb(" + color.r + "," + color.g + "," +
+ color.b + ")";
+
+ var lineHeight = this._getLineHeight();
+ var lineCount = this._splitedStrings.length;
+ var labelX; var firstLinelabelY;
+ var hAlign; var vAlign;
+ //apply align
+ {
+ if(cc.TextAlignment.RIGHT === node._hAlign) {
+ hAlign = "right";
+ labelX = canvasSizeX;
+ }
+ else if(cc.TextAlignment.CENTER === node._hAlign) {
+ hAlign = "center";
+ labelX = canvasSizeX/2;
+ }
+ else {
+ hAlign = "left";
+ labelX = 0;
+ }
+
+ this._labelContext.textAlign = hAlign;
+ if(cc.VerticalTextAlignment.TOP === node._vAlign) {
+ vAlign = "top";
+ firstLinelabelY = 0;
+ }
+ else if(cc.VerticalTextAlignment.CENTER === node._vAlign) {
+ vAlign = "middle";
+ firstLinelabelY = canvasSizeY/2 - lineHeight * (lineCount -1 ) / 2;
+ }
+ else {
+ vAlign = "bottom";
+ firstLinelabelY = canvasSizeY - lineHeight * (lineCount -1 );
+ }
+ this._labelContext.textBaseline = vAlign;
+ }
+
+ this._labelContext.font = fontDesc;
+
+ //do real rendering
+ for(var i = 0; i < this._splitedStrings.length; ++i) {
+ this._labelContext.fillText(this._splitedStrings[i],labelX,firstLinelabelY + i * lineHeight);
+ }
+
+ this._labelTexture._textureLoaded = false;
+ this._labelTexture.handleLoadedTexture();
+ };
+
+ proto._rebuildLabelSkin = function() {
+ if(this._node._labelSkinDirty) {
+ this._bakeLabel();
+ this._prepareQuad();
+ this._node._labelSkinDirty = false;
+ }
+ };
+})();
+
+(function(){
+ cc.Label.TTFCanvasRenderCmd = function(renderableObject){
+ cc.Node.CanvasRenderCmd.call(this, renderableObject);
+ this._needDraw = true;
+ this._labelTexture = new cc.Texture2D();
+ this._labelCanvas = document.createElement("canvas");
+ this._labelCanvas.width = 1;
+ this._labelCanvas.height = 1;
+ this._labelContext = this._labelCanvas.getContext("2d");
+ this._labelTexture.initWithElement(this._labelCanvas);
+ this._quad = new cc.V3F_C4B_T2F_Quad();
+ this._quadDirty = true;
+ this._splitedStrings = null;
+ this._drawFontsize = 0;
+ };
+
+ var proto = cc.Label.TTFCanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
+ cc.js.mixin(proto, cc.Label.TTFLabelBaker.prototype);
+
+ proto.constructor = cc.Label.TTFCanvasRenderCmd;
+
+ proto.rendering = function (ctx, scaleX, scaleY) {
+ this._rebuildLabelSkin();
+ var node = this._node;
+ var locDisplayOpacity = this._displayedOpacity;
+ var alpha = locDisplayOpacity/ 255;
+ //var locTexture = this._labelTexture;
+ if (locDisplayOpacity === 0)
+ return;
+
+ var wrapper = ctx || cc._renderContext, context = wrapper.getContext();
+ wrapper.setTransform(this._worldTransform, scaleX, scaleY);
+ wrapper.setCompositeOperation(cc.Node.CanvasRenderCmd._getCompositeOperationByBlendFunc(node._blendFunc));
+ wrapper.setGlobalAlpha(alpha);
+
+ if(this._labelTexture) {
+
+ var quad = this._quad;
+ {
+ var sx,sy,sw,sh;
+ var x, y, w,h;
+
+ x = quad._bl.vertices.x;
+ y = quad._bl.vertices.y;
+ w = quad._tr.vertices.x - quad._bl.vertices.x;
+ h = quad._tr.vertices.y - quad._bl.vertices.y;
+ y = - y - h;
+
+ var textureWidth = this._labelTexture.getPixelWidth();
+ var textureHeight = this._labelTexture.getPixelHeight();
+
+ sx = quad._bl.texCoords.u * textureWidth;
+ sy = quad._bl.texCoords.v * textureHeight;
+ sw = (quad._tr.texCoords.u - quad._bl.texCoords.u) * textureWidth;
+ sh = (quad._tr.texCoords.v - quad._bl.texCoords.v) * textureHeight;
+
+ x = x * scaleX;
+ y = y * scaleY;
+ w = w * scaleX;
+ h = h * scaleY;
+
+ var image = this._labelTexture._htmlElementObj;
+ if (this._labelTexture._pattern !== "") {
+ wrapper.setFillStyle(context.createPattern(image, this._labelTexture._pattern));
+ context.fillRect(x, y, w, h);
+ } else {
+ context.drawImage(image,
+ sx, sy, sw, sh,
+ x, y, w, h);
+ }
+ }
+
+ }
+ cc.g_NumberOfDraws = cc.g_NumberOfDraws + 1;
+ };
+
+})();
\ No newline at end of file
diff --git a/cocos2d/labels/CCLabelWebGLRenderCmd.js b/cocos2d/labels/CCLabelWebGLRenderCmd.js
new file mode 100644
index 0000000000..ad4726afd0
--- /dev/null
+++ b/cocos2d/labels/CCLabelWebGLRenderCmd.js
@@ -0,0 +1,78 @@
+/****************************************************************************
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ 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.
+
+ Use any of these editors to generate BMFonts:
+ http://glyphdesigner.71squared.com/ (Commercial, Mac OS X)
+ http://www.n4te.com/hiero/hiero.jnlp (Free, Java)
+ http://slick.cokeandcode.com/demos/hiero.jnlp (Free, Java)
+ http://www.angelcode.com/products/bmfont/ (Free, Windows only)
+ ****************************************************************************/
+
+(function(){
+ cc.Label.TTFWebGLRenderCmd = function(renderableObject){
+ cc.Node.WebGLRenderCmd.call(this, renderableObject);
+ this._needDraw = true;
+ this._labelTexture = new cc.Texture2D();
+ this._labelCanvas = document.createElement("canvas");
+ this._labelCanvas.width = 1;
+ this._labelCanvas.height = 1;
+ this._labelContext = this._labelCanvas.getContext("2d");
+ this._labelTexture.initWithElement(this._labelCanvas);
+ this._quad = new cc.V3F_C4B_T2F_Quad();
+ this._quadDirty = true;
+ this._quadWebBuffer = cc._renderContext.createBuffer();
+ this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURECOLOR);
+ this._splitedStrings = null;
+ this._drawFontsize = 0;
+ };
+
+ var proto = cc.Label.TTFWebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
+ cc.js.mixin(proto, cc.Label.TTFLabelBaker.prototype);
+
+ proto.constructor = cc.Label.TTFWebGLRenderCmd;
+
+ proto.rendering = function (ctx) {
+ var node = this._node;
+ this._rebuildLabelSkin();
+
+ var gl = ctx || cc._renderContext ;
+ this._shaderProgram.use();
+ this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix);
+ cc.glBlendFunc(node._blendFunc.src,node._blendFunc.dst);
+ cc.glBindTexture2DN(0,this._labelTexture);
+ cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POS_COLOR_TEX);
+
+ gl.bindBuffer(gl.ARRAY_BUFFER, this._quadWebBuffer);
+ if (this._quadDirty) {
+ gl.bufferData(gl.ARRAY_BUFFER, this._quad.arrayBuffer, gl.DYNAMIC_DRAW);
+ this._quadDirty = false;
+ }
+ gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 24, 0); //cc.VERTEX_ATTRIB_POSITION
+ gl.vertexAttribPointer(1, 4, gl.UNSIGNED_BYTE, true, 24, 12); //cc.VERTEX_ATTRIB_COLOR
+ gl.vertexAttribPointer(2, 2, gl.FLOAT, false, 24, 16); //cc.VERTEX_ATTRIB_TEX_COORDS
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
+ };
+
+})();
\ No newline at end of file
diff --git a/cocos2d/menus/CCMenu.js b/cocos2d/menus/CCMenu.js
new file mode 100644
index 0000000000..9a92b8cc43
--- /dev/null
+++ b/cocos2d/menus/CCMenu.js
@@ -0,0 +1,600 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+/**
+ * @constant
+ * @type Number
+ */
+cc.MENU_STATE_WAITING = 0;
+/**
+ * @constant
+ * @type Number
+ */
+cc.MENU_STATE_TRACKING_TOUCH = 1;
+/**
+ * @constant
+ * @type Number
+ */
+cc.MENU_HANDLER_PRIORITY = -128;
+/**
+ * @constant
+ * @type Number
+ */
+cc.DEFAULT_PADDING = 5;
+
+/**
+ * Features and Limitation:
+ * - You can add MenuItem objects in runtime using addChild:
+ * - But the only accepted children are MenuItem objects
+ * @class
+ * @extends cc.Layer
+ * @param {...cc.MenuItem|null} menuItems}
+ * @example
+ * var layer = new cc.Menu(menuitem1, menuitem2, menuitem3);
+ */
+cc.Menu = cc.Layer.extend(/** @lends cc.Menu# */{
+ enabled: false,
+
+ _selectedItem: null,
+ _state: -1,
+ _touchListener: null,
+ _className: "Menu",
+
+ /**
+ * Constructor of cc.Menu override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
+ * @param {...cc.MenuItem|null} menuItems
+ */
+ ctor: function (menuItems) {
+ cc.Layer.prototype.ctor.call(this);
+ this._color = cc.Color.WHITE;
+ this.enabled = false;
+ this._opacity = 255;
+ this._selectedItem = null;
+ this._state = -1;
+
+ this._touchListener = cc.EventListener.create({
+ event: cc.EventListener.TOUCH_ONE_BY_ONE,
+ swallowTouches: true,
+ onTouchBegan: this._onTouchBegan,
+ onTouchMoved: this._onTouchMoved,
+ onTouchEnded: this._onTouchEnded,
+ onTouchCancelled: this._onTouchCancelled
+ });
+
+ if ((arguments.length > 0) && (arguments[arguments.length - 1] == null))
+ cc.log("parameters should not be ending with null in Javascript");
+
+ var argc = arguments.length, items;
+ if (argc === 0) {
+ items = [];
+ } else if (argc === 1) {
+ if (menuItems instanceof Array) {
+ items = menuItems;
+ }
+ else items = [menuItems];
+ }
+ else if (argc > 1) {
+ items = [];
+ for (var i = 0; i < argc; i++) {
+ if (arguments[i])
+ items.push(arguments[i]);
+ }
+ }
+ this.initWithArray(items);
+ },
+ /**
+ *
+ * Event callback that is invoked every time when CCMenu enters the 'stage'.
+ * If the CCMenu enters the 'stage' with a transition, this event is called when the transition starts.
+ * During onEnter you can't access a "sister/brother" node.
+ * If you override onEnter, you must call its parent's onEnter function with this._super().
+ *
+ */
+ onEnter: function () {
+ var locListener = this._touchListener;
+ if (!locListener._isRegistered())
+ cc.eventManager.addListener(locListener, this);
+ cc.Node.prototype.onEnter.call(this);
+ },
+
+ /**
+ * return whether or not the menu will receive events
+ * @return {Boolean}
+ */
+ isEnabled: function () {
+ return this.enabled;
+ },
+
+ /**
+ * set whether or not the menu will receive events
+ * @param {Boolean} enabled
+ */
+ setEnabled: function (enabled) {
+ this.enabled = enabled;
+ },
+
+ /**
+ * initializes a cc.Menu with it's items
+ * @param {Array} args
+ * @return {Boolean}
+ */
+ initWithItems: function (args) {
+ var pArray = [];
+ if (args) {
+ for (var i = 0; i < args.length; i++) {
+ if (args[i])
+ pArray.push(args[i]);
+ }
+ }
+
+ return this.initWithArray(pArray);
+ },
+
+ /**
+ * initializes a cc.Menu with a Array of cc.MenuItem objects
+ * @param {Array} arrayOfItems array Of cc.MenuItem Items
+ * @return {Boolean}
+ */
+ initWithArray: function (arrayOfItems) {
+ if (cc.Layer.prototype.init.call(this)) {
+ this.enabled = true;
+
+ // menu in the center of the screen
+ var winSize = cc.winSize;
+ this.setPosition(winSize.width / 2, winSize.height / 2);
+ this.setContentSize(winSize);
+ this.setAnchorPoint(0.5, 0.5);
+ this.ignoreAnchorPointForPosition(true);
+
+ if (arrayOfItems) {
+ for (var i = 0; i < arrayOfItems.length; i++)
+ this.addChild(arrayOfItems[i], i);
+ }
+
+ this._selectedItem = null;
+ this._state = cc.MENU_STATE_WAITING;
+
+ // enable cascade color and opacity on menus
+ this.cascadeColor = true;
+ this.cascadeOpacity = true;
+
+ return true;
+ }
+ return false;
+ },
+
+ /**
+ * add a child for cc.Menu
+ * @param {cc.Node} child
+ * @param {Number|Null} [zOrder=] zOrder for the child
+ * @param {Number|Null} [tag=] tag for the child
+ */
+ addChild: function (child, zOrder, tag) {
+ if (!(child instanceof cc.MenuItem))
+ throw new Error("cc.Menu.addChild() : Menu only supports MenuItem objects as children");
+ cc.Layer.prototype.addChild.call(this, child, zOrder, tag);
+ },
+
+ /**
+ * align items vertically with default padding
+ */
+ alignItemsVertically: function () {
+ this.alignItemsVerticallyWithPadding(cc.DEFAULT_PADDING);
+ },
+
+ /**
+ * align items vertically with specified padding
+ * @param {Number} padding
+ */
+ alignItemsVerticallyWithPadding: function (padding) {
+ var height = -padding, locChildren = this._children, len, i, locScaleY, locHeight, locChild;
+ if (locChildren && locChildren.length > 0) {
+ for (i = 0, len = locChildren.length; i < len; i++)
+ height += locChildren[i].height * locChildren[i].scaleY + padding;
+
+ var y = height / 2.0;
+
+ for (i = 0, len = locChildren.length; i < len; i++) {
+ locChild = locChildren[i];
+ locHeight = locChild.height;
+ locScaleY = locChild.scaleY;
+ locChild.setPosition(0, y - locHeight * locScaleY / 2);
+ y -= locHeight * locScaleY + padding;
+ }
+ }
+ },
+
+ /**
+ * align items horizontally with default padding
+ */
+ alignItemsHorizontally: function () {
+ this.alignItemsHorizontallyWithPadding(cc.DEFAULT_PADDING);
+ },
+
+ /**
+ * align items horizontally with specified padding
+ * @param {Number} padding
+ */
+ alignItemsHorizontallyWithPadding: function (padding) {
+ var width = -padding, locChildren = this._children, i, len, locScaleX, locWidth, locChild;
+ if (locChildren && locChildren.length > 0) {
+ for (i = 0, len = locChildren.length; i < len; i++)
+ width += locChildren[i].width * locChildren[i].scaleX + padding;
+
+ var x = -width / 2.0;
+
+ for (i = 0, len = locChildren.length; i < len; i++) {
+ locChild = locChildren[i];
+ locScaleX = locChild.scaleX;
+ locWidth = locChildren[i].width;
+ locChild.setPosition(x + locWidth * locScaleX / 2, 0);
+ x += locWidth * locScaleX + padding;
+ }
+ }
+ },
+
+ /**
+ * align items in columns
+ * @example
+ * // Example
+ * menu.alignItemsInColumns(3,2,3)// this will create 3 columns, with 3 items for first column, 2 items for second and 3 for third
+ *
+ * menu.alignItemsInColumns(3,3)//this creates 2 columns, each have 3 items
+ */
+ alignItemsInColumns: function (/*Multiple Arguments*/) {
+ if ((arguments.length > 0) && (arguments[arguments.length - 1] == null))
+ cc.log("parameters should not be ending with null in Javascript");
+
+ var rows = [];
+ for (var i = 0; i < arguments.length; i++) {
+ rows.push(arguments[i]);
+ }
+ var height = -5;
+ var row = 0;
+ var rowHeight = 0;
+ var columnsOccupied = 0;
+ var rowColumns, tmp, len;
+ var locChildren = this._children;
+ if (locChildren && locChildren.length > 0) {
+ for (i = 0, len = locChildren.length; i < len; i++) {
+ if (row >= rows.length)
+ continue;
+
+ rowColumns = rows[row];
+ // can not have zero columns on a row
+ if (!rowColumns)
+ continue;
+
+ tmp = locChildren[i].height;
+ rowHeight = ((rowHeight >= tmp || isNaN(tmp)) ? rowHeight : tmp);
+
+ ++columnsOccupied;
+ if (columnsOccupied >= rowColumns) {
+ height += rowHeight + 5;
+
+ columnsOccupied = 0;
+ rowHeight = 0;
+ ++row;
+ }
+ }
+ }
+ // check if too many rows/columns for available menu items
+ //cc.assert(!columnsOccupied, ""); //?
+ var winSize = cc.director.getWinSize();
+
+ row = 0;
+ rowHeight = 0;
+ rowColumns = 0;
+ var w = 0.0;
+ var x = 0.0;
+ var y = (height / 2);
+
+ if (locChildren && locChildren.length > 0) {
+ for (i = 0, len = locChildren.length; i < len; i++) {
+ var child = locChildren[i];
+ if (rowColumns === 0) {
+ rowColumns = rows[row];
+ w = winSize.width / (1 + rowColumns);
+ x = w;
+ }
+
+ tmp = child._getHeight();
+ rowHeight = ((rowHeight >= tmp || isNaN(tmp)) ? rowHeight : tmp);
+ child.setPosition(x - winSize.width / 2, y - tmp / 2);
+
+ x += w;
+ ++columnsOccupied;
+
+ if (columnsOccupied >= rowColumns) {
+ y -= rowHeight + 5;
+ columnsOccupied = 0;
+ rowColumns = 0;
+ rowHeight = 0;
+ ++row;
+ }
+ }
+ }
+ },
+ /**
+ * align menu items in rows
+ * @param {Number}
+ * @example
+ * // Example
+ * menu.alignItemsInRows(5,3)//this will align items to 2 rows, first row with 5 items, second row with 3
+ *
+ * menu.alignItemsInRows(4,4,4,4)//this creates 4 rows each have 4 items
+ */
+ alignItemsInRows: function (/*Multiple arguments*/) {
+ if ((arguments.length > 0) && (arguments[arguments.length - 1] == null))
+ cc.log("parameters should not be ending with null in Javascript");
+ var columns = [], i;
+ for (i = 0; i < arguments.length; i++) {
+ columns.push(arguments[i]);
+ }
+ var columnWidths = [];
+ var columnHeights = [];
+
+ var width = -10;
+ var columnHeight = -5;
+ var column = 0;
+ var columnWidth = 0;
+ var rowsOccupied = 0;
+ var columnRows, child, len, tmp;
+
+ var locChildren = this._children;
+ if (locChildren && locChildren.length > 0) {
+ for (i = 0, len = locChildren.length; i < len; i++) {
+ child = locChildren[i];
+ // check if too many menu items for the amount of rows/columns
+ if (column >= columns.length)
+ continue;
+
+ columnRows = columns[column];
+ // can't have zero rows on a column
+ if (!columnRows)
+ continue;
+
+ // columnWidth = fmaxf(columnWidth, [item contentSize].width);
+ tmp = child.width;
+ columnWidth = ((columnWidth >= tmp || isNaN(tmp)) ? columnWidth : tmp);
+
+ columnHeight += (child.height + 5);
+ ++rowsOccupied;
+
+ if (rowsOccupied >= columnRows) {
+ columnWidths.push(columnWidth);
+ columnHeights.push(columnHeight);
+ width += columnWidth + 10;
+
+ rowsOccupied = 0;
+ columnWidth = 0;
+ columnHeight = -5;
+ ++column;
+ }
+ }
+ }
+ // check if too many rows/columns for available menu items.
+ //cc.assert(!rowsOccupied, "");
+ var winSize = cc.director.getWinSize();
+
+ column = 0;
+ columnWidth = 0;
+ columnRows = 0;
+ var x = -width / 2;
+ var y = 0.0;
+
+ if (locChildren && locChildren.length > 0) {
+ for (i = 0, len = locChildren.length; i < len; i++) {
+ child = locChildren[i];
+ if (columnRows === 0) {
+ columnRows = columns[column];
+ y = columnHeights[column];
+ }
+
+ // columnWidth = fmaxf(columnWidth, [item contentSize].width);
+ tmp = child._getWidth();
+ columnWidth = ((columnWidth >= tmp || isNaN(tmp)) ? columnWidth : tmp);
+
+ child.setPosition(x + columnWidths[column] / 2, y - winSize.height / 2);
+
+ y -= child.height + 10;
+ ++rowsOccupied;
+
+ if (rowsOccupied >= columnRows) {
+ x += columnWidth + 5;
+ rowsOccupied = 0;
+ columnRows = 0;
+ columnWidth = 0;
+ ++column;
+ }
+ }
+ }
+ },
+
+ /**
+ * remove a child from cc.Menu
+ * @param {cc.Node} child the child you want to remove
+ * @param {boolean} cleanup whether to cleanup
+ */
+ removeChild: function (child, cleanup) {
+ if (child == null)
+ return;
+ if (!(child instanceof cc.MenuItem)) {
+ cc.log("cc.Menu.removeChild():Menu only supports MenuItem objects as children");
+ return;
+ }
+
+ if (this._selectedItem === child)
+ this._selectedItem = null;
+ cc.Node.prototype.removeChild.call(this, child, cleanup);
+ },
+
+ _onTouchBegan: function (touch, event) {
+ var target = event.getCurrentTarget();
+ if (target._state !== cc.MENU_STATE_WAITING || !target._visible || !target.enabled)
+ return false;
+
+ for (var c = target.parent; c != null; c = c.parent) {
+ if (!c.isVisible())
+ return false;
+ }
+
+ target._selectedItem = target._itemForTouch(touch);
+ if (target._selectedItem) {
+ target._state = cc.MENU_STATE_TRACKING_TOUCH;
+ target._selectedItem.selected();
+ target._selectedItem.setNodeDirty();
+ return true;
+ }
+ return false;
+ },
+
+ _onTouchEnded: function (touch, event) {
+ var target = event.getCurrentTarget();
+ if (target._state !== cc.MENU_STATE_TRACKING_TOUCH) {
+ cc.log("cc.Menu.onTouchEnded(): invalid state");
+ return;
+ }
+ if (target._selectedItem) {
+ target._selectedItem.unselected();
+ target._selectedItem.setNodeDirty();
+ target._selectedItem.activate();
+ }
+ target._state = cc.MENU_STATE_WAITING;
+ },
+
+ _onTouchCancelled: function (touch, event) {
+ var target = event.getCurrentTarget();
+ if (target._state !== cc.MENU_STATE_TRACKING_TOUCH) {
+ cc.log("cc.Menu.onTouchCancelled(): invalid state");
+ return;
+ }
+ if (target._selectedItem) {
+ target._selectedItem.unselected();
+ target._selectedItem.setNodeDirty();
+ }
+ target._state = cc.MENU_STATE_WAITING;
+ },
+
+ _onTouchMoved: function (touch, event) {
+ var target = event.getCurrentTarget();
+ if (target._state !== cc.MENU_STATE_TRACKING_TOUCH) {
+ cc.log("cc.Menu.onTouchMoved(): invalid state");
+ return;
+ }
+ var currentItem = target._itemForTouch(touch);
+ if (currentItem !== target._selectedItem) {
+ if (target._selectedItem) {
+ target._selectedItem.unselected();
+ target._selectedItem.setNodeDirty();
+ }
+ target._selectedItem = currentItem;
+ if (target._selectedItem) {
+ target._selectedItem.selected();
+ target._selectedItem.setNodeDirty();
+ }
+ }
+ },
+
+ /**
+ *
+ * callback that is called every time the cc.Menu leaves the 'stage'.
+ * If the cc.Menu leaves the 'stage' with a transition, this callback is called when the transition finishes.
+ * During onExit you can't access a sibling node.
+ * If you override onExit, you shall call its parent's onExit with this._super().
+ *
+ */
+ onExit: function () {
+ if (this._state === cc.MENU_STATE_TRACKING_TOUCH) {
+ if (this._selectedItem) {
+ this._selectedItem.unselected();
+ this._selectedItem = null;
+ }
+ this._state = cc.MENU_STATE_WAITING;
+ }
+ cc.Node.prototype.onExit.call(this);
+ },
+ /**
+ * only use for jsbinding
+ * @param value
+ */
+ setOpacityModifyRGB: function (value) {
+ },
+ /**
+ * only use for jsbinding
+ * @returns {boolean}
+ */
+ isOpacityModifyRGB: function () {
+ return false;
+ },
+
+ _itemForTouch: function (touch) {
+ var touchLocation = touch.getLocation();
+ var itemChildren = this._children, locItemChild;
+ if (itemChildren && itemChildren.length > 0) {
+ for (var i = itemChildren.length - 1; i >= 0; i--) {
+ locItemChild = itemChildren[i];
+ if (locItemChild.isVisible() && locItemChild.isEnabled()) {
+ var local = locItemChild.convertToNodeSpace(touchLocation);
+ var r = locItemChild.rect();
+ r.x = 0;
+ r.y = 0;
+ if (cc.rectContainsPoint(r, local))
+ return locItemChild;
+ }
+ }
+ }
+ return null;
+ }
+});
+
+var _p = cc.Menu.prototype;
+
+// Extended properties
+/** @expose */
+_p.enabled;
+
+/**
+ * create a new menu
+ * @deprecated since v3.0, please use new cc.Menu(menuitem1, menuitem2, menuitem3) to create a new menu
+ * @param {...cc.MenuItem|null} menuItems
+ * todo: need to use new
+ * @return {cc.Menu}
+ */
+cc.Menu.create = function (menuItems) {
+ var argc = arguments.length;
+ if ((argc > 0) && (arguments[argc - 1] == null))
+ cc.log("parameters should not be ending with null in Javascript");
+
+ var ret;
+ if (argc === 0)
+ ret = new cc.Menu();
+ else if (argc === 1)
+ ret = new cc.Menu(menuItems);
+ else
+ ret = new cc.Menu(Array.prototype.slice.call(arguments, 0));
+ return ret;
+};
diff --git a/cocos2d/menus/CCMenuItem.js b/cocos2d/menus/CCMenuItem.js
new file mode 100644
index 0000000000..3fbe6559c4
--- /dev/null
+++ b/cocos2d/menus/CCMenuItem.js
@@ -0,0 +1,1349 @@
+/****************************************************************************
+ 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._globalFontSize = cc.ITEM_SIZE;
+cc._globalFontName = "Arial";
+cc._globalFontNameRelease = false;
+
+/**
+ * Subclass cc.MenuItem (or any subclass) to create your custom cc.MenuItem objects.
+ * @class
+ * @extends cc.Node
+ * @param {function|String} callback
+ * @param {cc.Node} target
+ */
+cc.MenuItem = cc.Node.extend(/** @lends cc.MenuItem# */{
+ _enabled: false,
+ _target: null,
+ _callback: null,
+ _isSelected: false,
+ _className: "MenuItem",
+
+ /**
+ * Constructor of cc.MenuItem
+ * @param {function|String} callback
+ * @param {cc.Node} target
+ */
+ ctor: function (callback, target) {
+ var nodeP = cc.Node.prototype;
+ nodeP.ctor.call(this);
+ this._target = null;
+ this._callback = null;
+ this._isSelected = false;
+ this._enabled = false;
+
+ nodeP.setAnchorPoint.call(this, 0.5, 0.5);
+ this._target = target || null;
+ this._callback = callback || null;
+ if (this._callback) {
+ this._enabled = true;
+ }
+ },
+
+ /**
+ * return whether MenuItem is selected
+ * @return {Boolean}
+ */
+ isSelected: function () {
+ return this._isSelected;
+ },
+ /**
+ * only use for jsbinding
+ * @param value
+ */
+ setOpacityModifyRGB: function (value) {
+ },
+ /**
+ * only use for jsbinding
+ * @returns {boolean}
+ */
+ isOpacityModifyRGB: function () {
+ return false;
+ },
+
+ /**
+ * set the target/selector of the menu item
+ * @param {function|String} selector
+ * @param {cc.Node} rec
+ * @deprecated since v3.0
+ */
+ setTarget: function (selector, rec) {
+ this._target = rec;
+ this._callback = selector;
+ },
+
+ /**
+ * return whether MenuItem is Enabled
+ * @return {Boolean}
+ */
+ isEnabled: function () {
+ return this._enabled;
+ },
+
+ /**
+ * set enable value of MenuItem
+ * @param {Boolean} enable
+ */
+ setEnabled: function (enable) {
+ this._enabled = enable;
+ },
+
+ /**
+ * initializes a cc.MenuItem with callback
+ * @param {function|String} callback
+ * @param {cc.Node} target
+ * @return {Boolean}
+ */
+ initWithCallback: function (callback, target) {
+ this.anchorX = 0.5;
+ this.anchorY = 0.5;
+ this._target = target;
+ this._callback = callback;
+ this._enabled = true;
+ this._isSelected = false;
+ return true;
+ },
+
+ /**
+ * return rect value of cc.MenuItem
+ * @return {cc.Rect}
+ */
+ rect: function () {
+ var locPosition = this._position, locContentSize = this._contentSize, locAnchorPoint = this._anchorPoint;
+ return cc.rect(locPosition.x - locContentSize.width * locAnchorPoint.x,
+ locPosition.y - locContentSize.height * locAnchorPoint.y,
+ locContentSize.width, locContentSize.height);
+ },
+
+ /**
+ * set the cc.MenuItem selected same as setIsSelected(true)
+ */
+ selected: function () {
+ this._isSelected = true;
+ },
+
+ /**
+ * set the cc.MenuItem unselected same as setIsSelected(false)
+ */
+ unselected: function () {
+ this._isSelected = false;
+ },
+
+ /**
+ * set the callback to the menu item
+ * @param {function|String} callback
+ * @param {cc.Node} target
+ */
+ setCallback: function (callback, target) {
+ this._target = target;
+ this._callback = callback;
+ },
+
+ /**
+ * call the selector with target
+ */
+ activate: function () {
+ if (this._enabled) {
+ var locTarget = this._target, locCallback = this._callback;
+ if (!locCallback)
+ return;
+ if (locTarget && cc.js.isString(locCallback)) {
+ locTarget[locCallback](this);
+ } else if (locTarget && cc.js.isFunction(locCallback)) {
+ locCallback.call(locTarget, this);
+ } else
+ locCallback(this);
+ }
+ }
+});
+
+var _p = cc.MenuItem.prototype;
+
+// Extended properties
+/** @expose */
+_p.enabled;
+cc.defineGetterSetter(_p, "enabled", _p.isEnabled, _p.setEnabled);
+
+/**
+ * creates an empty menu item with target and callback
+ * Not recommended to use the base class, should use more defined menu item classes
+ * @deprecated since v3.0, please use new cc.MenuItem(callback,target) instead
+ * @param {function|String} callback callback
+ * @param {cc.Node} target
+ * @return {cc.MenuItem}
+ */
+cc.MenuItem.create = function (callback, target) {
+ return new cc.MenuItem(callback, target);
+};
+
+/**
+ * Any cc.Node that supports the cc.LabelProtocol protocol can be added.
+ * Supported nodes:
+ * - cc.BitmapFontAtlas
+ * - cc.LabelAtlas
+ * - cc.LabelTTF
+ * @class
+ * @extends cc.MenuItem
+ * @param {cc.Node} label
+ * @param {function|String} selector
+ * @param {cc.Node} target
+ * @example
+ * var menuitemLabel = new cc.MenuItemLabel(label,selector,target);
+ *
+ * @property {String} string - Content string of label item
+ * @property {cc.Node} label - Label of label item
+ * @property {cc.Color} disabledColor - Color of label when it's disabled
+ */
+cc.MenuItemLabel = cc.MenuItem.extend(/** @lends cc.MenuItemLabel# */{
+ _disabledColor: null,
+ _label: null,
+ _originalScale: 0,
+ _colorBackup: null,
+
+ /**
+ * Constructor of cc.MenuItemLabel
+ * @param {cc.Node} label
+ * @param {function|String} selector
+ * @param {cc.Node} target
+ */
+ ctor: function (label, selector, target) {
+ cc.MenuItem.prototype.ctor.call(this, selector, target);
+ this._disabledColor = null;
+ this._label = null;
+ this._colorBackup = null;
+
+ if (label) {
+ this._originalScale = 1.0;
+ this._colorBackup = cc.Color.WHITE;
+ this._disabledColor = cc.color(126, 126, 126);
+ this.setLabel(label);
+
+ this.setCascadeColorEnabled(true);
+ this.setCascadeOpacityEnabled(true);
+ }
+ },
+
+ /**
+ * return the disable color for this cc.MenuItemLabel
+ * @return {cc.Color}
+ */
+ getDisabledColor: function () {
+ return this._disabledColor;
+ },
+
+ /**
+ * set the disable color for this cc.MenuItemLabel
+ * @param {cc.Color} color
+ */
+ setDisabledColor: function (color) {
+ this._disabledColor = color;
+ },
+
+ /**
+ * return label of cc.MenuItemLabel
+ * @return {cc.Node}
+ */
+ getLabel: function () {
+ return this._label;
+ },
+
+ /**
+ * set a label for cc.MenuItemLabel
+ * @param {cc.Node} label
+ */
+ setLabel: function (label) {
+ if (label) {
+ this.addChild(label);
+ label.anchorX = 0;
+ label.anchorY = 0;
+ this.width = label.width;
+ this.height = label.height;
+ label.setCascadeColorEnabled(true);
+ }
+
+ if (this._label) {
+ this.removeChild(this._label, true);
+ }
+
+ this._label = label;
+ },
+
+ /**
+ * set enable value to cc.MenuItemLabel
+ * @param {Boolean} enabled
+ */
+ setEnabled: function (enabled) {
+ if (this._enabled !== enabled) {
+ if (!enabled) {
+ this._colorBackup = this.color;
+ this.setColor(this._disabledColor);
+ } else {
+ this.setColor(this._colorBackup);
+ }
+ }
+ cc.MenuItem.prototype.setEnabled.call(this, enabled);
+ },
+
+ /**
+ * initializes a cc.MenuItemLabel with a label
+ * @param {cc.Node} label
+ * @param {function|String} selector
+ * @param {cc.Node} target
+ * @return {Boolean}
+ */
+ initWithLabel: function (label, selector, target) {
+ this.initWithCallback(selector, target);
+ this._originalScale = 1.0;
+ this._colorBackup = cc.Color.WHITE;
+ this._disabledColor = cc.color(126, 126, 126);
+ this.setLabel(label);
+
+ this.setCascadeColorEnabled(true);
+ this.setCascadeOpacityEnabled(true);
+
+ return true;
+ },
+
+ /**
+ * set the string for cc.MenuItemLabel
+ * @param {String} label
+ */
+ setString: function (label) {
+ this._label.string = label;
+ this.width = this._label.width;
+ this.height = this._label.height;
+ },
+ /**
+ * return the string of cc.MenuItemLabel
+ * @returns {*|string|_p.string|ret.string|q.string|String}
+ */
+ getString: function () {
+ return this._label.string;
+ },
+
+ /**
+ * activate the menu item
+ */
+ activate: function () {
+ if (this._enabled) {
+ this.stopAllActions();
+ this.scale = this._originalScale;
+ cc.MenuItem.prototype.activate.call(this);
+ }
+ },
+
+ /**
+ * menu item is selected (runs callback)
+ */
+ selected: function () {
+ if (this._enabled) {
+ cc.MenuItem.prototype.selected.call(this);
+
+ var action = this.getActionByTag(cc.ZOOM_ACTION_TAG);
+ if (action)
+ this.stopAction(action);
+ else
+ this._originalScale = this.scale;
+
+ var zoomAction = cc.scaleTo(0.1, this._originalScale * 1.2);
+ zoomAction.setTag(cc.ZOOM_ACTION_TAG);
+ this.runAction(zoomAction);
+ }
+ },
+
+ /**
+ * menu item goes back to unselected state
+ */
+ unselected: function () {
+ if (this._enabled) {
+ cc.MenuItem.prototype.unselected.call(this);
+ this.stopActionByTag(cc.ZOOM_ACTION_TAG);
+ var zoomAction = cc.scaleTo(0.1, this._originalScale);
+ zoomAction.setTag(cc.ZOOM_ACTION_TAG);
+ this.runAction(zoomAction);
+ }
+ }
+});
+
+var _p = cc.MenuItemLabel.prototype;
+
+// Extended properties
+/** @expose */
+_p.string;
+cc.defineGetterSetter(_p, "string", _p.getString, _p.setString);
+/** @expose */
+_p.disabledColor;
+cc.defineGetterSetter(_p, "disabledColor", _p.getDisabledColor, _p.setDisabledColor);
+/** @expose */
+_p.label;
+cc.defineGetterSetter(_p, "label", _p.getLabel, _p.setLabel);
+
+
+/**
+ * @deprecated since v3.0 ,please use new cc.MenuItemLabel(label,selector,target) instead
+ * @param {cc.Node} label
+ * @param {function|String|Null} [selector=]
+ * @param {cc.Node|Null} [target=]
+ * @return {cc.MenuItemLabel}
+ */
+cc.MenuItemLabel.create = function (label, selector, target) {
+ return new cc.MenuItemLabel(label, selector, target);
+};
+
+/**
+ * Helper class that creates a MenuItemLabel class with a LabelAtlas
+ * @class
+ * @extends cc.MenuItemLabel
+ * @param {String} value
+ * @param {String} charMapFile
+ * @param {Number} itemWidth
+ * @param {Number} itemHeight
+ * @param {String} startCharMap a single character
+ * @param {function|String|Null} callback
+ * @param {cc.Node|Null} target
+ * @example
+ * var menuItem = new cc.MenuItemAtlasFont(param1,param2...);
+ */
+cc.MenuItemAtlasFont = cc.MenuItemLabel.extend(/** @lends cc.MenuItemAtlasFont# */{
+
+ /**
+ * the contructor of cc.MenuItemAtlasFont
+ * @param {String} value
+ * @param {String} charMapFile
+ * @param {Number} itemWidth
+ * @param {Number} itemHeight
+ * @param {String} startCharMap a single character
+ * @param {function|String|Null} callback
+ * @param {cc.Node|Null} target
+ */
+ ctor: function (value, charMapFile, itemWidth, itemHeight, startCharMap, callback, target) {
+ var label;
+ if (value && value.length > 0) {
+ label = new cc.LabelAtlas(value, charMapFile, itemWidth, itemHeight, startCharMap);
+ }
+
+ cc.MenuItemLabel.prototype.ctor.call(this, label, callback, target);
+ },
+
+ /**
+ * initializes a cc.MenuItemAtlasFont with string
+ * @param {String} value
+ * @param {String} charMapFile
+ * @param {Number} itemWidth
+ * @param {Number} itemHeight
+ * @param {String} startCharMap a single character
+ * @param {function|String|Null} callback
+ * @param {cc.Node|Null} target
+ * @return {Boolean}
+ */
+ initWithString: function (value, charMapFile, itemWidth, itemHeight, startCharMap, callback, target) {
+ if (!value || value.length === 0)
+ throw new Error("cc.MenuItemAtlasFont.initWithString(): value should be non-null and its length should be greater than 0");
+
+ var label = new cc.LabelAtlas();
+ label.initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap);
+ if (this.initWithLabel(label, callback, target)) {
+ // do something ?
+ }
+ return true;
+ }
+});
+
+/**
+ * create menu item from string with font
+ * @deprecated since v3.0 ,please use new cc.MenuItemAtlasFont() instead.
+ * @param {String} value the text to display
+ * @param {String} charMapFile the character map file
+ * @param {Number} itemWidth
+ * @param {Number} itemHeight
+ * @param {String} startCharMap a single character
+ * @param {function|String|Null} [callback=null]
+ * @param {cc.Node|Null} [target=]
+ * @return {cc.MenuItemAtlasFont}
+ */
+cc.MenuItemAtlasFont.create = function (value, charMapFile, itemWidth, itemHeight, startCharMap, callback, target) {
+ return new cc.MenuItemAtlasFont(value, charMapFile, itemWidth, itemHeight, startCharMap, callback, target);
+};
+
+/**
+ * Helper class that creates a CCMenuItemLabel class with a Label
+ * @class
+ * @extends cc.MenuItemLabel
+ * @param {String} value text for the menu item
+ * @param {function|String} callback
+ * @param {cc.Node} target
+ * @example
+ * var menuItem = new cc.MenuItemFont(value, callback, target);
+ *
+ * @property {Number} fontSize - Font size of font item
+ * @property {String} fontName - Font name of font item
+ */
+cc.MenuItemFont = cc.MenuItemLabel.extend(/** @lends cc.MenuItemFont# */{
+ _fontSize: null,
+ _fontName: null,
+
+ /**
+ * Constructor of cc.MenuItemFont
+ * @param {String} value text for the menu item
+ * @param {function|String} callback
+ * @param {cc.Node} target
+ */
+ ctor: function (value, callback, target) {
+ var label;
+ if (value && value.length > 0) {
+ this._fontName = cc._globalFontName;
+ this._fontSize = cc._globalFontSize;
+ label = new cc.LabelTTF(value, this._fontName, this._fontSize);
+ }
+ else {
+ this._fontSize = 0;
+ this._fontName = "";
+ }
+
+ cc.MenuItemLabel.prototype.ctor.call(this, label, callback, target);
+ },
+
+ /**
+ * initializes cc.MenuItemFont with string
+ * @param {String} value text for the menu item
+ * @param {function|String} callback
+ * @param {cc.Node} target
+ * @return {Boolean}
+ */
+ initWithString: function (value, callback, target) {
+ if (!value || value.length === 0)
+ throw new Error("Value should be non-null and its length should be greater than 0");
+
+ this._fontName = cc._globalFontName;
+ this._fontSize = cc._globalFontSize;
+
+ var label = new cc.LabelTTF(value, this._fontName, this._fontSize);
+ if (this.initWithLabel(label, callback, target)) {
+ // do something ?
+ }
+ return true;
+ },
+
+ /**
+ * set the font size for cc.MenuItemFont
+ * @param {Number} s
+ */
+ setFontSize: function (s) {
+ this._fontSize = s;
+ this._recreateLabel();
+ },
+
+ /**
+ *return the font size of cc.MenuItemFont
+ * @return {Number}
+ */
+ getFontSize: function () {
+ return this._fontSize;
+ },
+
+ /**
+ * set the font name for cc.MenuItemFont
+ * @param {String} name
+ */
+ setFontName: function (name) {
+ this._fontName = name;
+ this._recreateLabel();
+ },
+
+ /**
+ * return the font name for cc.MenuItemFont
+ * @return {String}
+ */
+ getFontName: function () {
+ return this._fontName;
+ },
+
+ _recreateLabel: function () {
+ var label = new cc.LabelTTF(this._label.string, this._fontName, this._fontSize);
+ this.setLabel(label);
+ }
+});
+
+/**
+ * a shared function to set the fontSize for menuitem font
+ * @param {Number} fontSize
+ */
+cc.MenuItemFont.setFontSize = function (fontSize) {
+ cc._globalFontSize = fontSize;
+};
+
+/**
+ * a shared function to get the font size for menuitem font
+ * @return {Number}
+ */
+cc.MenuItemFont.fontSize = function () {
+ return cc._globalFontSize;
+};
+
+/**
+ * a shared function to set the fontsize for menuitem font
+ * @param name
+ */
+cc.MenuItemFont.setFontName = function (name) {
+ if (cc._globalFontNameRelease) {
+ cc._globalFontName = '';
+ }
+ cc._globalFontName = name;
+ cc._globalFontNameRelease = true;
+};
+
+var _p = cc.MenuItemFont.prototype;
+
+// Extended properties
+/** @expose */
+_p.fontSize;
+cc.defineGetterSetter(_p, "fontSize", _p.getFontSize, _p.setFontSize);
+/** @expose */
+_p.fontName;
+cc.defineGetterSetter(_p, "fontName", _p.getFontName, _p.setFontName);
+
+
+/**
+ * a shared function to get the font name for menuitem font
+ * @return {String}
+ */
+cc.MenuItemFont.fontName = function () {
+ return cc._globalFontName;
+};
+
+/**
+ * create a menu item from string
+ * @deprecated since v3.0, please use new construction instead
+ * @param {String} value the text to display
+ * @param {String|function|Null} callback the callback to run, either in function name or pass in the actual function
+ * @param {cc.Node|Null} target the target to run callback
+ * @return {cc.MenuItemFont}
+ */
+cc.MenuItemFont.create = function (value, callback, target) {
+ return new cc.MenuItemFont(value, callback, target);
+};
+
+
+/**
+ * CCMenuItemSprite accepts CCNode objects as items.
+ * The images has 3 different states:
+ * - unselected image
+ * - selected image
+ * - disabled image
+ * @class
+ * @extends cc.MenuItem
+ * @param {Image|Null} normalSprite normal state image
+ * @param {Image|Null} selectedSprite selected state image
+ * @param {Image|cc.Node|Null} three disabled state image OR target node
+ * @param {String|function|cc.Node|Null} four callback function name in string or actual function, OR target Node
+ * @param {String|function|Null} five callback function name in string or actual function
+ *
+ * @example
+ * var item = new cc.MenuItemSprite(normalImage)//create a menu item from a sprite with no functionality
+ * var item = new cc.MenuItemSprite(normalImage, selectedImage)//create a menu Item, nothing will happen when clicked
+ * var item = new cc.MenuItemSprite(normalImage, SelectedImage, disabledImage)//same above, but with disabled state image
+ * var item = new cc.MenuItemSprite(normalImage, SelectedImage, 'callback', targetNode)//create a menu item, when clicked runs targetNode.callback()
+ * var item = new cc.MenuItemSprite(normalImage, SelectedImage, disabledImage, targetNode.callback, targetNode)
+ * //same as above, but with disabled image, and passing in callback function
+ *
+ * @property {cc.Sprite} normalImage - Sprite in normal state
+ * @property {cc.Sprite} selectedImage - Sprite in selected state
+ * @property {cc.Sprite} disabledImage - Sprite in disabled state
+ */
+cc.MenuItemSprite = cc.MenuItem.extend(/** @lends cc.MenuItemSprite# */{
+ _normalImage: null,
+ _selectedImage: null,
+ _disabledImage: null,
+
+ /**
+ * Constructor of cc.MenuItemSprite
+ * @param {Image|Null} normalSprite normal state image
+ * @param {Image|Null} selectedSprite selected state image
+ * @param {Image|cc.Node|Null} three disabled state image OR target node
+ * @param {String|function|cc.Node|Null} four callback function name in string or actual function, OR target Node
+ * @param {String|function|Null} five callback function name in string or actual function
+ */
+ ctor: function (normalSprite, selectedSprite, three, four, five) {
+ cc.MenuItem.prototype.ctor.call(this);
+ this._normalImage = null;
+ this._selectedImage = null;
+ this._disabledImage = null;
+
+ if (selectedSprite !== undefined) {
+ //normalSprite = normalSprite;
+ //selectedSprite = selectedSprite;
+ var disabledImage, target, callback;
+ //when you send 4 arguments, five is undefined
+ if (five !== undefined) {
+ disabledImage = three;
+ callback = four;
+ target = five;
+ } else if (four !== undefined && cc.js.isFunction(four)) {
+ disabledImage = three;
+ callback = four;
+ } else if (four !== undefined && cc.js.isFunction(three)) {
+ target = four;
+ callback = three;
+ disabledImage = null;
+ } else if (three === undefined) {
+ disabledImage = null;
+ }
+ this.initWithNormalSprite(normalSprite, selectedSprite, disabledImage, callback, target);
+ }
+ },
+
+ /**
+ * return the normal status image(cc.Sprite)
+ * @return {cc.Sprite}
+ */
+ getNormalImage: function () {
+ return this._normalImage;
+ },
+
+ /**
+ * set the normal status image(cc.Sprite)
+ * @param {cc.Sprite} normalImage
+ */
+ setNormalImage: function (normalImage) {
+ if (this._normalImage === normalImage) {
+ return;
+ }
+ if (normalImage) {
+ this.addChild(normalImage, 0, cc.NORMAL_TAG);
+ normalImage.anchorX = 0;
+ normalImage.anchorY = 0;
+ }
+ if (this._normalImage) {
+ this.removeChild(this._normalImage, true);
+ }
+
+ this._normalImage = normalImage;
+ if(!this._normalImage)
+ return;
+
+ this.width = this._normalImage.width;
+ this.height = this._normalImage.height;
+ this._updateImagesVisibility();
+
+ if (normalImage.textureLoaded && !normalImage.textureLoaded()) {
+ normalImage.once("load", function (event) {
+ this.width = normalImage.width;
+ this.height = normalImage.height;
+ }, this);
+ }
+ },
+
+ /**
+ * return the selected status image(cc.Sprite) of cc.MenuItemSprite
+ * @return {cc.Sprite}
+ */
+ getSelectedImage: function () {
+ return this._selectedImage;
+ },
+
+ /**
+ * set the selected status image(cc.Sprite)
+ * @param {cc.Sprite} selectedImage
+ */
+ setSelectedImage: function (selectedImage) {
+ if (this._selectedImage === selectedImage)
+ return;
+
+ if (selectedImage) {
+ this.addChild(selectedImage, 0, cc.SELECTED_TAG);
+ selectedImage.anchorX = 0;
+ selectedImage.anchorY = 0;
+ }
+
+ if (this._selectedImage) {
+ this.removeChild(this._selectedImage, true);
+ }
+
+ this._selectedImage = selectedImage;
+ this._updateImagesVisibility();
+ },
+
+ /**
+ * return the disabled status of cc.MenuItemSprite
+ * @return {cc.Sprite}
+ */
+ getDisabledImage: function () {
+ return this._disabledImage;
+ },
+
+ /**
+ * set the disabled status image(cc.Sprite)
+ * @param {cc.Sprite} disabledImage
+ */
+ setDisabledImage: function (disabledImage) {
+ if (this._disabledImage === disabledImage)
+ return;
+
+ if (disabledImage) {
+ this.addChild(disabledImage, 0, cc.DISABLE_TAG);
+ disabledImage.anchorX = 0;
+ disabledImage.anchorY = 0;
+ }
+
+ if (this._disabledImage)
+ this.removeChild(this._disabledImage, true);
+
+ this._disabledImage = disabledImage;
+ this._updateImagesVisibility();
+ },
+
+ /**
+ * initializes cc.MenuItemSprite with a cc.Sprite
+ * @param {cc.Node} normalSprite
+ * @param {cc.Node} selectedSprite
+ * @param {cc.Node} disabledSprite
+ * @param {function|String} callback
+ * @param {cc.Node} target
+ * @return {Boolean}
+ */
+ initWithNormalSprite: function (normalSprite, selectedSprite, disabledSprite, callback, target) {
+ this.initWithCallback(callback, target);
+ this.setNormalImage(normalSprite);
+ this.setSelectedImage(selectedSprite);
+ this.setDisabledImage(disabledSprite);
+ var locNormalImage = this._normalImage;
+ if (locNormalImage) {
+ this.width = locNormalImage.width;
+ this.height = locNormalImage.height;
+
+ if (locNormalImage.textureLoaded && !locNormalImage.textureLoaded()) {
+ locNormalImage.once("load", function (event) {
+ this.width = locNormalImage.width;
+ this.height = locNormalImage.height;
+ this.setCascadeColorEnabled(true);
+ this.setCascadeOpacityEnabled(true);
+ }, this);
+ }
+ }
+ this.setCascadeColorEnabled(true);
+ this.setCascadeOpacityEnabled(true);
+ return true;
+ },
+
+ /**
+ * menu item is selected (runs callback)
+ */
+ selected: function () {
+ cc.MenuItem.prototype.selected.call(this);
+ if (this._normalImage) {
+ if (this._disabledImage)
+ this._disabledImage.visible = false;
+
+ if (this._selectedImage) {
+ this._normalImage.visible = false;
+ this._selectedImage.visible = true;
+ } else
+ this._normalImage.visible = true;
+ }
+ },
+
+ /**
+ * menu item goes back to unselected state
+ */
+ unselected: function () {
+ cc.MenuItem.prototype.unselected.call(this);
+ if (this._normalImage) {
+ this._normalImage.visible = true;
+
+ if (this._selectedImage)
+ this._selectedImage.visible = false;
+
+ if (this._disabledImage)
+ this._disabledImage.visible = false;
+ }
+ },
+
+ /**
+ * set cc.MenuItemSprite enable to receive the touch event
+ * @param {Boolean} bEnabled
+ */
+ setEnabled: function (bEnabled) {
+ if (this._enabled !== bEnabled) {
+ cc.MenuItem.prototype.setEnabled.call(this, bEnabled);
+ this._updateImagesVisibility();
+ }
+ },
+
+ _updateImagesVisibility: function () {
+ var locNormalImage = this._normalImage, locSelImage = this._selectedImage, locDisImage = this._disabledImage;
+ if (this._enabled) {
+ if (locNormalImage)
+ locNormalImage.visible = true;
+ if (locSelImage)
+ locSelImage.visible = false;
+ if (locDisImage)
+ locDisImage.visible = false;
+ } else {
+ if (locDisImage) {
+ if (locNormalImage)
+ locNormalImage.visible = false;
+ if (locSelImage)
+ locSelImage.visible = false;
+ if (locDisImage)
+ locDisImage.visible = true;
+ } else {
+ if (locNormalImage)
+ locNormalImage.visible = true;
+ if (locSelImage)
+ locSelImage.visible = false;
+ }
+ }
+ }
+});
+
+var _p = cc.MenuItemSprite.prototype;
+
+// Extended properties
+/** @expose */
+_p.normalImage;
+cc.defineGetterSetter(_p, "normalImage", _p.getNormalImage, _p.setNormalImage);
+/** @expose */
+_p.selectedImage;
+cc.defineGetterSetter(_p, "selectedImage", _p.getSelectedImage, _p.setSelectedImage);
+/** @expose */
+_p.disabledImage;
+cc.defineGetterSetter(_p, "disabledImage", _p.getDisabledImage, _p.setDisabledImage);
+
+/**
+ * create a menu item from sprite
+ * @deprecated since v3.0 please use new cc.MenuItemSprite(normalSprite, selectedSprite, three, four, five) instead
+ * @param {Image} normalSprite normal state image
+ * @param {Image|Null} selectedSprite selected state image
+ * @param {Image|cc.Node|Null} three disabled state image OR target node
+ * @param {String|function|cc.Node|Null} four callback function name in string or actual function, OR target Node
+ * @param {String|function|Null} five callback function name in string or actual function
+ * @return {cc.MenuItemSprite}
+ */
+cc.MenuItemSprite.create = function (normalSprite, selectedSprite, three, four, five) {
+ return new cc.MenuItemSprite(normalSprite, selectedSprite, three, four, five || undefined);
+};
+
+/**
+ * cc.MenuItemImage accepts images as items.
+ * The images has 3 different states:
+ * - unselected image
+ * - selected image
+ * - disabled image
+ *
+ * For best results try that all images are of the same size
+ * @class
+ * @extends cc.MenuItemSprite
+ * @param {string|null} normalImage
+ * @param {string|null} selectedImage
+ * @param {string|null} disabledImage
+ * @param {function|string|null} callback
+ * @param {cc.Node|null} target
+ * @example
+ * var menuItem = new cc.MenuItemImage(normalImage, selectedImage, three, four, five);
+ */
+cc.MenuItemImage = cc.MenuItemSprite.extend(/** @lends cc.MenuItemImage# */{
+
+ /**
+ * Constructor of cc.MenuItemImage
+ * @param {string|null} normalImage
+ * @param {string|null} selectedImage
+ * @param {string|null} disabledImage
+ * @param {function|string|null} callback
+ * @param {cc.Node|null} target
+ */
+ ctor: function (normalImage, selectedImage, three, four, five) {
+ var normalSprite = null,
+ selectedSprite = null,
+ disabledSprite = null,
+ callback = null,
+ target = null;
+
+ if (normalImage === undefined || normalImage === null) {
+ cc.MenuItemSprite.prototype.ctor.call(this);
+ }
+ else {
+ normalSprite = new cc.Sprite(normalImage);
+ selectedImage &&
+ (selectedSprite = new cc.Sprite(selectedImage));
+ if (four === undefined) {
+ callback = three;
+ }
+ else if (five === undefined) {
+ callback = three;
+ target = four;
+ }
+ else if (five) {
+ disabledSprite = new cc.Sprite(three);
+ callback = four;
+ target = five;
+ }
+ cc.MenuItemSprite.prototype.ctor.call(this, normalSprite, selectedSprite, disabledSprite, callback, target);
+ }
+ },
+
+ /**
+ * sets the sprite frame for the normal image
+ * @param {cc.SpriteFrame} frame
+ */
+ setNormalSpriteFrame: function (frame) {
+ this.setNormalImage(new cc.Sprite(frame));
+ },
+
+ /**
+ * sets the sprite frame for the selected image
+ * @param {cc.SpriteFrame} frame
+ */
+ setSelectedSpriteFrame: function (frame) {
+ this.setSelectedImage(new cc.Sprite(frame));
+ },
+
+ /**
+ * sets the sprite frame for the disabled image
+ * @param {cc.SpriteFrame} frame
+ */
+ setDisabledSpriteFrame: function (frame) {
+ this.setDisabledImage(new cc.Sprite(frame));
+ },
+
+ /**
+ * initializes a cc.MenuItemImage
+ * @param {string|null} normalImage
+ * @param {string|null} selectedImage
+ * @param {string|null} disabledImage
+ * @param {function|string|null} callback
+ * @param {cc.Node|null} target
+ * @returns {boolean}
+ */
+ initWithNormalImage: function (normalImage, selectedImage, disabledImage, callback, target) {
+ var normalSprite = null;
+ var selectedSprite = null;
+ var disabledSprite = null;
+
+ if (normalImage) {
+ normalSprite = new cc.Sprite(normalImage);
+ }
+ if (selectedImage) {
+ selectedSprite = new cc.Sprite(selectedImage);
+ }
+ if (disabledImage) {
+ disabledSprite = new cc.Sprite(disabledImage);
+ }
+ return this.initWithNormalSprite(normalSprite, selectedSprite, disabledSprite, callback, target);
+ }
+});
+
+/**
+ * creates a new menu item image
+ * @deprecated since v3.0, please use new cc.MenuItemImage(normalImage, selectedImage, three, four, five) instead.
+ * @param {String} normalImage file name for normal state
+ * @param {String} selectedImage image for selected state
+ * @param {String|cc.Node} three Disabled image OR callback function
+ * @param {String|function|Null} [four] callback function, either name in string or pass the whole function OR the target
+ * @param {cc.Node|String|function|Null} [five] cc.Node target to run callback when clicked
+ * @return {cc.MenuItemImage}
+ */
+cc.MenuItemImage.create = function (normalImage, selectedImage, three, four, five) {
+ return new cc.MenuItemImage(normalImage, selectedImage, three, four, five);
+};
+
+
+/**
+ * A simple container class that "toggles" it's inner items
+ * The inner items can be any MenuItem
+ * @class
+ * @extends cc.MenuItem
+ *
+ * @property {Array} subItems - Sub items
+ * @property {Number} selectedIndex - Index of selected sub item
+ *
+ *@example
+ * // Example
+ * //create a toggle item with 2 menu items (which you can then toggle between them later)
+ * var toggler = new cc.MenuItemToggle( new cc.MenuItemFont("On"), new cc.MenuItemFont("Off"), this.callback, this)
+ * //Note: the first param is the target, the second is the callback function, afterwards, you can pass in any number of menuitems
+ *
+ * //if you pass only 1 variable, then it must be a cc.MenuItem
+ * var notYetToggler = new cc.MenuItemToggle(cc.MenuItemFont("On"));//it is useless right now, until you add more stuff to it
+ * notYetToggler.addSubItem(new cc.MenuItemFont("Off"));
+ * //this is useful for constructing a toggler without a callback function (you wish to control the behavior from somewhere else)
+ */
+cc.MenuItemToggle = cc.MenuItem.extend(/** @lends cc.MenuItemToggle# */{
+ subItems: null,
+
+ _selectedIndex: 0,
+ _opacity: null,
+ _color: null,
+
+ /**
+ * Constructor of cc.MenuItemToggle
+ */
+ ctor: function (/*Multiple arguments follow*/) {
+
+ cc.MenuItem.prototype.ctor.call(this);
+ this._selectedIndex = 0;
+ this.subItems = [];
+ this._opacity = 0;
+ this._color = cc.Color.WHITE;
+
+ if(arguments.length > 0)
+ this.initWithItems(Array.prototype.slice.apply(arguments));
+
+ },
+
+ /**
+ * return the opacity of cc.MenuItemToggle
+ * @return {Number}
+ */
+ getOpacity: function () {
+ return this._opacity;
+ },
+
+ /**
+ * set the opacity for cc.MenuItemToggle
+ * @param {Number} opacity
+ */
+ setOpacity: function (opacity) {
+ this._opacity = opacity;
+ if (this.subItems && this.subItems.length > 0) {
+ for (var it = 0; it < this.subItems.length; it++) {
+ this.subItems[it].opacity = opacity;
+ }
+ }
+ this._color.a = opacity;
+ },
+
+ /**
+ * return the color of cc.MenuItemToggle
+ * @return {cc.Color}
+ */
+ getColor: function () {
+ var locColor = this._color;
+ return cc.color(locColor.r, locColor.g, locColor.b, locColor.a);
+ },
+
+ /**
+ * set the color for cc.MenuItemToggle
+ * @param {cc.Color} Color
+ */
+ setColor: function (color) {
+ var locColor = this._color;
+ locColor.r = color.r;
+ locColor.g = color.g;
+ locColor.b = color.b;
+
+ if (this.subItems && this.subItems.length > 0) {
+ for (var it = 0; it < this.subItems.length; it++) {
+ this.subItems[it].setColor(color);
+ }
+ }
+
+ if (color.a !== undefined && !color.a_undefined) {
+ this.setOpacity(color.a);
+ }
+ },
+
+ /**
+ * return the index of selected
+ * @return {Number}
+ */
+ getSelectedIndex: function () {
+ return this._selectedIndex;
+ },
+
+ /**
+ * set the seleceted index for cc.MenuItemToggle
+ * @param {Number} SelectedIndex
+ */
+ setSelectedIndex: function (SelectedIndex) {
+ if (SelectedIndex !== this._selectedIndex) {
+ this._selectedIndex = SelectedIndex;
+ var currItem = this.getChildByTag(cc.CURRENT_ITEM);
+ if (currItem)
+ currItem.removeFromParent(false);
+
+ var item = this.subItems[this._selectedIndex];
+ this.addChild(item, 0, cc.CURRENT_ITEM);
+ var w = item.width, h = item.height;
+ this.width = w;
+ this.height = h;
+ item.setPosition(w / 2, h / 2);
+ }
+ },
+
+ /**
+ * similar to get children,return the sumItem array.
+ * @return {Array}
+ */
+ getSubItems: function () {
+ return this.subItems;
+ },
+
+ /**
+ * set the subitem for cc.MenuItemToggle
+ * @param {cc.MenuItem} subItems
+ */
+ setSubItems: function (subItems) {
+ this.subItems = subItems;
+ },
+
+ /**
+ * initializes a cc.MenuItemToggle with items
+ * @param {cc.MenuItem} args[0...last-2] the rest in the array are cc.MenuItems
+ * @param {function|String} args[last-1] the second item in the args array is the callback
+ * @param {cc.Node} args[last] the first item in the args array is a target
+ * @return {Boolean}
+ */
+ initWithItems: function (args) {
+ var l = args.length;
+ // passing callback.
+ if (cc.js.isFunction(args[args.length - 2])) {
+ this.initWithCallback(args[args.length - 2], args[args.length - 1]);
+ l = l - 2;
+ } else if (cc.js.isFunction(args[args.length - 1])) {
+ this.initWithCallback(args[args.length - 1], null);
+ l = l - 1;
+ } else {
+ this.initWithCallback(null, null);
+ }
+
+ var locSubItems = this.subItems;
+ locSubItems.length = 0;
+ for (var i = 0; i < l; i++) {
+ if (args[i])
+ locSubItems.push(args[i]);
+ }
+ this._selectedIndex = cc.UINT_MAX;
+ this.setSelectedIndex(0);
+
+ this.setCascadeColorEnabled(true);
+ this.setCascadeOpacityEnabled(true);
+
+ return true;
+ },
+
+ /**
+ * add the subitem for cc.MenuItemToggle
+ * @param {cc.MenuItem} item
+ */
+ addSubItem: function (item) {
+ this.subItems.push(item);
+ },
+
+ /**
+ * activate the menu item
+ */
+ activate: function () {
+ // update index
+ if (this._enabled) {
+ var newIndex = (this._selectedIndex + 1) % this.subItems.length;
+ this.setSelectedIndex(newIndex);
+ }
+ cc.MenuItem.prototype.activate.call(this);
+ },
+
+ /**
+ * menu item is selected (runs callback)
+ */
+ selected: function () {
+ cc.MenuItem.prototype.selected.call(this);
+ this.subItems[this._selectedIndex].selected();
+ },
+
+ /**
+ * menu item goes back to unselected state
+ */
+ unselected: function () {
+ cc.MenuItem.prototype.unselected.call(this);
+ this.subItems[this._selectedIndex].unselected();
+ },
+
+ /**
+ * set the enable status for cc.MenuItemToggle
+ * @param {Boolean} enabled
+ */
+ setEnabled: function (enabled) {
+ if (this._enabled !== enabled) {
+ cc.MenuItem.prototype.setEnabled.call(this, enabled);
+ var locItems = this.subItems;
+ if (locItems && locItems.length > 0) {
+ for (var it = 0; it < locItems.length; it++)
+ locItems[it].enabled = enabled;
+ }
+ }
+ },
+
+ /**
+ * returns the selected item (deprecated in -x, please use getSelectedItem instead.)
+ * @return {cc.MenuItem}
+ */
+ selectedItem: function () {
+ return this.subItems[this._selectedIndex];
+ },
+
+ /**
+ * returns the selected item.
+ * @return {cc.MenuItem}
+ */
+ getSelectedItem: function() {
+ return this.subItems[this._selectedIndex];
+ },
+
+ /**
+ * *
+ * Event callback that is invoked every time when cc.MenuItemToggle enters the 'stage'.
+ * If the cc.MenuItemToggle enters the 'stage' with a transition, this event is called when the transition starts.
+ * During onEnter you can't access a "sister/brother" node.
+ * If you override onEnter, you must call its parent's onEnter function with this._super().
+ *
+ */
+ onEnter: function () {
+ cc.Node.prototype.onEnter.call(this);
+ this.setSelectedIndex(this._selectedIndex);
+ }
+});
+
+var _p = cc.MenuItemToggle.prototype;
+
+// Extended properties
+/** @expose */
+_p.selectedIndex;
+cc.defineGetterSetter(_p, "selectedIndex", _p.getSelectedIndex, _p.setSelectedIndex);
+
+
+/**
+ * create a simple container class that "toggles" it's inner items
+ * The inner items can be any MenuItem
+ * @deprecated since v3.0 please use new cc.MenuItemToggle(params) instead
+ * @return {cc.MenuItemToggle}
+ * @example
+ */
+cc.MenuItemToggle.create = function (/*Multiple arguments follow*/) {
+ if ((arguments.length > 0) && (arguments[arguments.length - 1] == null))
+ cc.log("parameters should not be ending with null in Javascript");
+ var ret = new cc.MenuItemToggle();
+ ret.initWithItems(Array.prototype.slice.apply(arguments));
+ return ret;
+};
diff --git a/cocos2d/motion-streak/CCMotionStreak.js b/cocos2d/motion-streak/CCMotionStreak.js
new file mode 100644
index 0000000000..78fae3e0a4
--- /dev/null
+++ b/cocos2d/motion-streak/CCMotionStreak.js
@@ -0,0 +1,533 @@
+/****************************************************************************
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2008-2009 Jason Booth
+
+ 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.MotionStreak manages a Ribbon based on it's motion in absolute space.
+ * You construct it with a fadeTime, minimum segment size, texture path, texture
+ * length and color. The fadeTime controls how long it takes each vertex in
+ * the streak to fade out, the minimum segment size it how many pixels the
+ * streak will move before adding a new ribbon segment, and the texture
+ * length is the how many pixels the texture is stretched across. The texture
+ * is vertically aligned along the streak segment.
+ * @class
+ * @extends cc.Node
+ *
+ * @property {cc.Texture2D} texture - Texture used for the motion streak.
+ * @property {Boolean} fastMode - Indicate whether use fast mode.
+ * @property {Boolean} startingPositionInitialized - Indicate whether starting position initialized.
+ * @example
+ * //example
+ * new cc.MotionStreak(2, 3, 32, cc.Color.GREEN, s_streak);
+ */
+cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
+ texture:null,
+ fastMode:false,
+ startingPositionInitialized:false,
+
+ _blendFunc:null,
+
+ _stroke:0,
+ _fadeDelta:0,
+ _minSeg:0,
+
+ _maxPoints:0,
+ _nuPoints:0,
+ _previousNuPoints:0,
+
+ /* Pointers */
+ _pointVertexes:null,
+ _pointState:null,
+
+ // webgl
+ _vertices:null,
+ _colorPointer:null,
+ _texCoords:null,
+
+ _verticesBuffer:null,
+ _colorPointerBuffer:null,
+ _texCoordsBuffer:null,
+ _className:"MotionStreak",
+
+ /**
+ * creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture filename or texture
+ * Constructor of cc.MotionStreak
+ * @param {Number} fade time to fade
+ * @param {Number} minSeg minimum segment size
+ * @param {Number} stroke stroke's width
+ * @param {Number} color
+ * @param {string|cc.Texture2D} texture texture filename or texture
+ */
+ ctor: function (fade, minSeg, stroke, color, texture) {
+ cc.Node.prototype.ctor.call(this);
+ this._positionR = cc.p(0, 0);
+ this._blendFunc = new cc.BlendFunc(cc.SRC_ALPHA, cc.ONE_MINUS_SRC_ALPHA);
+
+ this.fastMode = false;
+ this.startingPositionInitialized = false;
+
+ this.texture = null;
+
+ this._stroke = 0;
+ this._fadeDelta = 0;
+ this._minSeg = 0;
+
+ this._maxPoints = 0;
+ this._nuPoints = 0;
+ this._previousNuPoints = 0;
+
+ /** Pointers */
+ this._pointVertexes = null;
+ this._pointState = null;
+
+ // webgl
+ this._vertices = null;
+ this._colorPointer = null;
+ this._texCoords = null;
+
+ this._verticesBuffer = null;
+ this._colorPointerBuffer = null;
+ this._texCoordsBuffer = null;
+
+ if(texture !== undefined)
+ this.initWithFade(fade, minSeg, stroke, color, texture);
+ },
+
+ /**
+ * Gets the texture.
+ * @return {cc.Texture2D}
+ */
+ getTexture:function () {
+ return this.texture;
+ },
+
+ /**
+ * Set the texture.
+ * @param {cc.Texture2D} texture
+ */
+ setTexture:function (texture) {
+ if (this.texture !== texture)
+ this.texture = texture;
+ },
+
+ /**
+ * Gets the blend func.
+ * @return {cc.BlendFunc}
+ */
+ getBlendFunc:function () {
+ return this._blendFunc;
+ },
+
+ /**
+ * Set the blend func.
+ * @param {Number} src
+ * @param {Number} dst
+ */
+ setBlendFunc:function (src, dst) {
+ if (dst === undefined) {
+ this._blendFunc = src;
+ } else {
+ this._blendFunc.src = src;
+ this._blendFunc.dst = dst;
+ }
+ },
+
+ /**
+ * Gets opacity.
+ * @warning cc.MotionStreak.getOpacity has not been supported.
+ * @returns {number}
+ */
+ getOpacity:function () {
+ cc.log("cc.MotionStreak.getOpacity has not been supported.");
+ return 0;
+ },
+
+ /**
+ * Set opacity.
+ * @warning cc.MotionStreak.setOpacity has not been supported.
+ * @param opacity
+ */
+ setOpacity:function (opacity) {
+ cc.log("cc.MotionStreak.setOpacity has not been supported.");
+ },
+
+ /**
+ * set opacity modify RGB.
+ * @warning cc.MotionStreak.setOpacityModifyRGB has not been supported.
+ * @param value
+ */
+ setOpacityModifyRGB:function (value) {
+ },
+
+ /**
+ * Checking OpacityModifyRGB.
+ * @returns {boolean}
+ */
+ isOpacityModifyRGB:function () {
+ return false;
+ },
+
+ /**
+ * Checking fast mode.
+ * @returns {boolean}
+ */
+ isFastMode:function () {
+ return this.fastMode;
+ },
+
+ /**
+ * set fast mode
+ * @param {Boolean} fastMode
+ */
+ setFastMode:function (fastMode) {
+ this.fastMode = fastMode;
+ },
+
+ /**
+ * Checking starting position initialized.
+ * @returns {boolean}
+ */
+ isStartingPositionInitialized:function () {
+ return this.startingPositionInitialized;
+ },
+
+ /**
+ * Set Starting Position Initialized.
+ * @param {Boolean} startingPositionInitialized
+ */
+ setStartingPositionInitialized:function (startingPositionInitialized) {
+ this.startingPositionInitialized = startingPositionInitialized;
+ },
+
+ /**
+ * Get stroke.
+ * @returns {Number} stroke
+ */
+ getStroke:function () {
+ return this._stroke;
+ },
+
+ /**
+ * Set stroke.
+ * @param {Number} stroke
+ */
+ setStroke:function (stroke) {
+ this._stroke = stroke;
+ },
+
+ /**
+ * initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture filename or texture
+ * @param {Number} fade time to fade
+ * @param {Number} minSeg minimum segment size
+ * @param {Number} stroke stroke's width
+ * @param {Number} color
+ * @param {string|cc.Texture2D} texture texture filename or texture
+ * @return {Boolean}
+ */
+ initWithFade:function (fade, minSeg, stroke, color, texture) {
+ if(!texture)
+ throw new Error("cc.MotionStreak.initWithFade(): Invalid filename or texture");
+
+ if (cc.js.isString(texture))
+ texture = cc.textureCache.addImage(texture);
+
+ cc.Node.prototype.setPosition.call(this, cc.p(0,0));
+ this.anchorX = 0;
+ this.anchorY = 0;
+ this.ignoreAnchor = true;
+ this.startingPositionInitialized = false;
+
+ this.fastMode = true;
+ this._minSeg = (minSeg === -1.0) ? (stroke / 5.0) : minSeg;
+ this._minSeg *= this._minSeg;
+
+ this._stroke = stroke;
+ this._fadeDelta = 1.0 / fade;
+
+ var locMaxPoints = (0 | (fade * 60)) + 2;
+ this._maxPoints = locMaxPoints;
+ this._nuPoints = 0;
+ this._pointState = new Float32Array(locMaxPoints);
+ this._pointVertexes = new Float32Array(locMaxPoints * 2);
+
+ this._vertices = new Float32Array(locMaxPoints * 4);
+ this._texCoords = new Float32Array(locMaxPoints * 4);
+ this._colorPointer = new Uint8Array(locMaxPoints * 8);
+
+ this._verticesBuffer = gl.createBuffer();
+ this._texCoordsBuffer = gl.createBuffer();
+ this._colorPointerBuffer = gl.createBuffer();
+
+ // Set blend mode
+ this._blendFunc.src = gl.SRC_ALPHA;
+ this._blendFunc.dst = gl.ONE_MINUS_SRC_ALPHA;
+
+ this.texture = texture;
+ this.color = color;
+ this.scheduleUpdate();
+
+ //bind buffer
+ gl.bindBuffer(gl.ARRAY_BUFFER, this._verticesBuffer);
+ gl.bufferData(gl.ARRAY_BUFFER, this._vertices, gl.DYNAMIC_DRAW);
+ gl.bindBuffer(gl.ARRAY_BUFFER, this._texCoordsBuffer);
+ gl.bufferData(gl.ARRAY_BUFFER, this._texCoords, gl.DYNAMIC_DRAW);
+ gl.bindBuffer(gl.ARRAY_BUFFER, this._colorPointerBuffer);
+ gl.bufferData(gl.ARRAY_BUFFER, this._colorPointer, gl.DYNAMIC_DRAW);
+
+ return true;
+ },
+
+ /**
+ * color used for the tint
+ * @param {cc.Color} color
+ */
+ tintWithColor:function (color) {
+ this.color = color;
+
+ // Fast assignation
+ var locColorPointer = this._colorPointer;
+ for (var i = 0, len = this._nuPoints * 2; i < len; i++) {
+ locColorPointer[i * 4] = color.r;
+ locColorPointer[i * 4 + 1] = color.g;
+ locColorPointer[i * 4 + 2] = color.b;
+ }
+ },
+
+ /**
+ * Remove all living segments of the ribbon
+ */
+ reset:function () {
+ this._nuPoints = 0;
+ },
+
+ /**
+ * Set the position.
+ *
+ * @param {cc.Vec2|Number} position
+ * @param {Number} [yValue=undefined] If not exists, the first parameter must be cc.Vec2.
+ */
+ setPosition:function (position, yValue) {
+ this.startingPositionInitialized = true;
+ if(yValue === undefined){
+ this._positionR.x = position.x;
+ this._positionR.y = position.y;
+ } else {
+ this._positionR.x = position;
+ this._positionR.y = yValue;
+ }
+ },
+
+ /**
+ * Gets the position.x
+ * @return {Number}
+ */
+ getPositionX:function () {
+ return this._positionR.x;
+ },
+
+ /**
+ * Set the position.x
+ * @param {Number} x
+ */
+ setPositionX:function (x) {
+ this._positionR.x = x;
+ if(!this.startingPositionInitialized)
+ this.startingPositionInitialized = true;
+ },
+
+ /**
+ * Gets the position.y
+ * @return {Number}
+ */
+ getPositionY:function () {
+ return this._positionR.y;
+ },
+
+ /**
+ * Set the position.y
+ * @param {Number} y
+ */
+ setPositionY:function (y) {
+ this._positionR.y = y;
+ if(!this.startingPositionInitialized)
+ this.startingPositionInitialized = true;
+ },
+
+ /**
+ * schedules the "update" method.
+ * It will use the order number 0. This method will be called every frame.
+ * Scheduled methods with a lower order value will be called before the ones that have a higher order value.
+ * Only one "update" method could be scheduled per node.
+ * @param {Number} delta
+ */
+ update:function (delta) {
+ if (!this.startingPositionInitialized)
+ return;
+
+ //TODO update the color (need move to render cmd)
+ this._renderCmd._updateDisplayColor();
+
+ delta *= this._fadeDelta;
+
+ var newIdx, newIdx2, i, i2;
+ var mov = 0;
+
+ // Update current points
+ var locNuPoints = this._nuPoints;
+ var locPointState = this._pointState, locPointVertexes = this._pointVertexes, locVertices = this._vertices;
+ var locColorPointer = this._colorPointer;
+
+ for (i = 0; i < locNuPoints; i++) {
+ locPointState[i] -= delta;
+
+ if (locPointState[i] <= 0)
+ mov++;
+ else {
+ newIdx = i - mov;
+ if (mov > 0) {
+ // Move data
+ locPointState[newIdx] = locPointState[i];
+ // Move point
+ locPointVertexes[newIdx * 2] = locPointVertexes[i * 2];
+ locPointVertexes[newIdx * 2 + 1] = locPointVertexes[i * 2 + 1];
+
+ // Move vertices
+ i2 = i * 2;
+ newIdx2 = newIdx * 2;
+ locVertices[newIdx2 * 2] = locVertices[i2 * 2];
+ locVertices[newIdx2 * 2 + 1] = locVertices[i2 * 2 + 1];
+ locVertices[(newIdx2 + 1) * 2] = locVertices[(i2 + 1) * 2];
+ locVertices[(newIdx2 + 1) * 2 + 1] = locVertices[(i2 + 1) * 2 + 1];
+
+ // Move color
+ i2 *= 4;
+ newIdx2 *= 4;
+ locColorPointer[newIdx2 + 0] = locColorPointer[i2 + 0];
+ locColorPointer[newIdx2 + 1] = locColorPointer[i2 + 1];
+ locColorPointer[newIdx2 + 2] = locColorPointer[i2 + 2];
+ locColorPointer[newIdx2 + 4] = locColorPointer[i2 + 4];
+ locColorPointer[newIdx2 + 5] = locColorPointer[i2 + 5];
+ locColorPointer[newIdx2 + 6] = locColorPointer[i2 + 6];
+ } else
+ newIdx2 = newIdx * 8;
+
+ var op = locPointState[newIdx] * 255.0;
+ locColorPointer[newIdx2 + 3] = op;
+ locColorPointer[newIdx2 + 7] = op;
+ }
+ }
+ locNuPoints -= mov;
+
+ // Append new point
+ var appendNewPoint = true;
+ if (locNuPoints >= this._maxPoints)
+ appendNewPoint = false;
+ else if (locNuPoints > 0) {
+ var a1 = cc.pDistanceSQ(cc.p(locPointVertexes[(locNuPoints - 1) * 2], locPointVertexes[(locNuPoints - 1) * 2 + 1]),
+ this._positionR) < this._minSeg;
+ var a2 = (locNuPoints === 1) ? false : (cc.pDistanceSQ(
+ cc.p(locPointVertexes[(locNuPoints - 2) * 2], locPointVertexes[(locNuPoints - 2) * 2 + 1]), this._positionR) < (this._minSeg * 2.0));
+ if (a1 || a2)
+ appendNewPoint = false;
+ }
+
+ if (appendNewPoint) {
+ locPointVertexes[locNuPoints * 2] = this._positionR.x;
+ locPointVertexes[locNuPoints * 2 + 1] = this._positionR.y;
+ locPointState[locNuPoints] = 1.0;
+
+ // Color assignment
+ var offset = locNuPoints * 8;
+
+ var locDisplayedColor = this.getDisplayedColor();
+ locColorPointer[offset] = locDisplayedColor.r;
+ locColorPointer[offset + 1] = locDisplayedColor.g;
+ locColorPointer[offset + 2] = locDisplayedColor.b;
+ //*((ccColor3B*)(m_pColorPointer + offset+4)) = this._color;
+ locColorPointer[offset + 4] = locDisplayedColor.r;
+ locColorPointer[offset + 5] = locDisplayedColor.g;
+ locColorPointer[offset + 6] = locDisplayedColor.b;
+
+ // Opacity
+ locColorPointer[offset + 3] = 255;
+ locColorPointer[offset + 7] = 255;
+
+ // Generate polygon
+ if (locNuPoints > 0 && this.fastMode) {
+ if (locNuPoints > 1)
+ cc.vertexLineToPolygon(locPointVertexes, this._stroke, this._vertices, locNuPoints, 1);
+ else
+ cc.vertexLineToPolygon(locPointVertexes, this._stroke, this._vertices, 0, 2);
+ }
+ locNuPoints++;
+ }
+
+ if (!this.fastMode)
+ cc.vertexLineToPolygon(locPointVertexes, this._stroke, this._vertices, 0, locNuPoints);
+
+ // Updated Tex Coords only if they are different than previous step
+ if (locNuPoints && this._previousNuPoints !== locNuPoints) {
+ var texDelta = 1.0 / locNuPoints;
+ var locTexCoords = this._texCoords;
+ for (i = 0; i < locNuPoints; i++) {
+ locTexCoords[i * 4] = 0;
+ locTexCoords[i * 4 + 1] = texDelta * i;
+
+ locTexCoords[(i * 2 + 1) * 2] = 1;
+ locTexCoords[(i * 2 + 1) * 2 + 1] = texDelta * i;
+ }
+
+ this._previousNuPoints = locNuPoints;
+ }
+
+ this._nuPoints = locNuPoints;
+ },
+
+ _createRenderCmd: function(){
+ if(cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ return new cc.MotionStreak.WebGLRenderCmd(this);
+ else
+ return null; //MotionStreak doesn't support Canvas mode
+ }
+});
+
+/**
+ * Please use new cc.MotionStreak instead.
+ * Creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture filename or texture
+ * @deprecated since v3.0 please use new cc.MotionStreak instead.
+ * @param {Number} fade time to fade
+ * @param {Number} minSeg minimum segment size
+ * @param {Number} stroke stroke's width
+ * @param {Number} color
+ * @param {string|cc.Texture2D} texture texture filename or texture
+ * @return {cc.MotionStreak}
+ * @example
+ * //example
+ * new cc.MotionStreak(2, 3, 32, cc.Color.GREEN, s_streak);
+ */
+cc.MotionStreak.create = function (fade, minSeg, stroke, color, texture) {
+ return new cc.MotionStreak(fade, minSeg, stroke, color, texture);
+};
diff --git a/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js b/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js
new file mode 100644
index 0000000000..45ab07cafd
--- /dev/null
+++ b/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js
@@ -0,0 +1,66 @@
+/****************************************************************************
+ 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.MotionStreak.WebGLRenderCmd = function(renderableObject){
+ cc.Node.WebGLRenderCmd.call(this, renderableObject);
+ this._needDraw = true;
+ this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURECOLOR);
+};
+
+cc.MotionStreak.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
+cc.MotionStreak.WebGLRenderCmd.prototype.constructor = cc.Sprite.WebGLRenderCmd;
+
+cc.MotionStreak.WebGLRenderCmd.prototype.rendering = function(ctx){
+ var node = this._node;
+ if (node._nuPoints <= 1)
+ return;
+
+ if (node.texture && node.texture.isLoaded()) {
+ ctx = ctx || cc._renderContext;
+ this._shaderProgram.use();
+ this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix);
+ cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POS_COLOR_TEX);
+ cc.glBlendFunc(node._blendFunc.src, node._blendFunc.dst);
+
+ cc.glBindTexture2D(node.texture);
+
+ //position
+ ctx.bindBuffer(ctx.ARRAY_BUFFER, node._verticesBuffer);
+ ctx.bufferData(ctx.ARRAY_BUFFER, node._vertices, ctx.DYNAMIC_DRAW);
+ ctx.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, ctx.FLOAT, false, 0, 0);
+
+ //texcoords
+ ctx.bindBuffer(ctx.ARRAY_BUFFER, node._texCoordsBuffer);
+ ctx.bufferData(ctx.ARRAY_BUFFER, node._texCoords, ctx.DYNAMIC_DRAW);
+ ctx.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, ctx.FLOAT, false, 0, 0);
+
+ //colors
+ ctx.bindBuffer(ctx.ARRAY_BUFFER, node._colorPointerBuffer);
+ ctx.bufferData(ctx.ARRAY_BUFFER, node._colorPointer, ctx.DYNAMIC_DRAW);
+ ctx.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, ctx.UNSIGNED_BYTE, true, 0, 0);
+
+ ctx.drawArrays(ctx.TRIANGLE_STRIP, 0, node._nuPoints * 2);
+ cc.g_NumberOfDraws++;
+ }
+};
\ No newline at end of file
diff --git a/cocos2d/node-grid/CCNodeGrid.js b/cocos2d/node-grid/CCNodeGrid.js
new file mode 100644
index 0000000000..f1cb9b4658
--- /dev/null
+++ b/cocos2d/node-grid/CCNodeGrid.js
@@ -0,0 +1,150 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+/**
+ * NodeGrid class is a class serves as a decorator of cc.Node,
+ * Grid node can run grid actions over all its children (WebGL only)
+ *
+ * @type {Class}
+ *
+ * @property {cc.GridBase} grid - Grid object that is used when applying effects
+ * @property {cc.Node} target - <@writeonly>Target
+ */
+cc.NodeGrid = cc.Node.extend({
+ grid: null,
+ _target: null,
+ _gridRect:null,
+
+ ctor: function (rect) {
+ cc.Node.prototype.ctor.call(this);
+ if(rect === undefined) rect = cc.rect();
+ this._gridRect = rect;
+ },
+ /**
+ * Gets the grid object.
+ * @returns {cc.GridBase}
+ */
+ getGrid: function () {
+ return this.grid;
+ },
+
+ /**
+ * Set the grid object.
+ * @param {cc.GridBase} grid
+ */
+ setGrid: function (grid) {
+ this.grid = grid;
+ },
+
+ /**
+ * @brief Set the effect grid rect.
+ * @param {cc.rect} rect.
+ */
+ setGridRect: function (rect) {
+ this._gridRect = rect;
+ },
+ /**
+ * @brief Get the effect grid rect.
+ * @return {cc.rect} rect.
+ */
+ getGridRect: function () {
+ return this._gridRect;
+ },
+
+ /**
+ * Set the target
+ * @param {cc.Node} target
+ */
+ setTarget: function (target) {
+ this._target = target;
+ },
+
+ _transformForWebGL: function () {
+ //optimize performance for javascript
+ var t4x4 = this._transform4x4, topMat4 = cc.current_stack.top;
+
+ // Convert 3x3 into 4x4 matrix
+ var trans = this.getNodeToParentTransform();
+ var t4x4Mat = t4x4.mat;
+ t4x4Mat[0] = trans.a;
+ t4x4Mat[4] = trans.c;
+ t4x4Mat[12] = trans.tx;
+ t4x4Mat[1] = trans.b;
+ t4x4Mat[5] = trans.d;
+ t4x4Mat[13] = trans.ty;
+
+ // Update Z vertex manually
+ //this._transform4x4.mat[14] = this._vertexZ;
+ t4x4Mat[14] = this._vertexZ;
+
+ //optimize performance for Javascript
+ topMat4.multiply(t4x4) ; // = cc.kmGLMultMatrix(this._transform4x4);
+
+ // XXX: Expensive calls. Camera should be integrated into the cached affine matrix
+ if (this._camera !== null && !(this.grid && this.grid.isActive())) {
+ var app = this._renderCmd._anchorPointInPoints,
+ apx = app.x, apy = app.y,
+ translate = (apx !== 0.0 || apy !== 0.0);
+ if (translate) {
+ if(!cc.SPRITEBATCHNODE_RENDER_SUBPIXEL) {
+ apx = 0 | apx;
+ apy = 0 | apy;
+ }
+ cc.kmGLTranslatef(apx, apy, 0);
+ this._camera.locate();
+ cc.kmGLTranslatef(-apx, -apy, 0);
+ } else {
+ this._camera.locate();
+ }
+ }
+ },
+
+ _createRenderCmd: function(){
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ return new cc.NodeGrid.WebGLRenderCmd(this);
+ else
+ return new cc.Node.CanvasRenderCmd(this); // cc.NodeGrid doesn't support Canvas mode.
+ }
+});
+
+var _p = cc.NodeGrid.prototype;
+// Extended property
+/** @expose */
+_p.grid;
+/** @expose */
+_p.target;
+cc.defineGetterSetter(_p, "target", null, _p.setTarget);
+
+
+/**
+ * Creates a NodeGrid.
+ * Implementation cc.NodeGrid
+ * @deprecated since v3.0 please new cc.NodeGrid instead.
+ * @return {cc.NodeGrid}
+ */
+cc.NodeGrid.create = function () {
+ return new cc.NodeGrid();
+};
\ No newline at end of file
diff --git a/cocos2d/node-grid/CCNodeGridWebGLRenderCmd.js b/cocos2d/node-grid/CCNodeGridWebGLRenderCmd.js
new file mode 100644
index 0000000000..8c45377dfe
--- /dev/null
+++ b/cocos2d/node-grid/CCNodeGridWebGLRenderCmd.js
@@ -0,0 +1,98 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+(function(){
+ cc.NodeGrid.WebGLRenderCmd = function(renderable){
+ cc.Node.WebGLRenderCmd.call(this, renderable);
+ this._needDraw = false;
+ this._gridBeginCommand = new cc.CustomRenderCmd(this, this.onGridBeginDraw);
+ this._gridEndCommand = new cc.CustomRenderCmd(this, this.onGridEndDraw);
+ };
+
+ var proto = cc.NodeGrid.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
+ proto.constructor = cc.NodeGrid.WebGLRenderCmd;
+
+ proto.visit = function(parentCmd) {
+ var node = this._node;
+ // quick return if not visible
+ if (!node._visible)
+ return;
+
+ parentCmd = parentCmd || this.getParentRenderCmd();
+ if (node._parent && node._parent._renderCmd)
+ this._curLevel = node._parent._renderCmd._curLevel + 1;
+
+ var currentStack = cc.current_stack;
+ currentStack.stack.push(currentStack.top);
+ this._syncStatus(parentCmd);
+ currentStack.top = this._stackMatrix;
+
+ /*var beforeProjectionType = cc.director.PROJECTION_DEFAULT;
+ if (locGrid && locGrid._active) {
+ //var backMatrix = new cc.kmMat4();
+ //cc.kmMat4Assign(backMatrix, this._stackMatrix);
+
+ beforeProjectionType = cc.director.getProjection();
+ //locGrid.set2DProjection();
+
+ //reset this._stackMatrix to current_stack.top
+ //cc.kmMat4Assign(currentStack.top, backMatrix);
+ }*/
+ cc.renderer.pushRenderCommand(this._gridBeginCommand);
+
+ if (node._target)
+ node._target.visit();
+
+ var locChildren = node._children;
+ if (locChildren && locChildren.length > 0) {
+ var childLen = locChildren.length;
+ node.sortAllChildren();
+ // draw children
+ for (var i = 0; i < childLen; i++) {
+ var child = locChildren[i];
+ child && child.visit();
+ }
+ }
+
+ //if (locGrid && locGrid._active) {
+ //cc.director.setProjection(beforeProjectionType);
+ //}
+ cc.renderer.pushRenderCommand(this._gridEndCommand);
+
+ this._dirtyFlag = 0;
+ currentStack.top = currentStack.stack.pop();
+ };
+
+ proto.onGridBeginDraw = function(){
+ var locGrid = this._node.grid;
+ if (locGrid && locGrid._active)
+ locGrid.beforeDraw();
+ };
+
+ proto.onGridEndDraw = function(){
+ var locGrid = this._node.grid;
+ if (locGrid && locGrid._active)
+ locGrid.afterDraw(this._node);
+ };
+})();
diff --git a/cocos2d/parallax/CCParallaxNode.js b/cocos2d/parallax/CCParallaxNode.js
new file mode 100644
index 0000000000..afa8e214e0
--- /dev/null
+++ b/cocos2d/parallax/CCParallaxNode.js
@@ -0,0 +1,252 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+/**
+ * Parallax Object.
+ * Parallax required attributes are stored.
+ * @class
+ * @extends cc._Class
+ */
+cc.PointObject = cc._Class.extend(/** @lends cc.PointObject# */{
+ _ratio:null,
+ _offset:null,
+ _child:null,
+
+ ctor: function(ratio, offset){
+ this.initWithCCPoint(ratio, offset);
+ },
+
+ /**
+ * Gets the ratio.
+ * @return {cc.Vec2} Not point, this is ratio.
+ */
+ getRatio:function () {
+ return this._ratio;
+ },
+
+ /**
+ * Set the ratio.
+ * @param {cc.Vec2} value
+ */
+ setRatio:function (value) {
+ this._ratio = value;
+ },
+
+ /**
+ * Gets the offset.
+ * @return {cc.Vec2}
+ */
+ getOffset:function () {
+ return this._offset;
+ },
+
+ /**
+ * Set the offset.
+ * @param {cc.Vec2} value
+ */
+ setOffset:function (value) {
+ this._offset = value;
+ },
+
+ /**
+ * Gets the child.
+ * @return {cc.Node}
+ */
+ getChild:function () {
+ return this._child;
+ },
+
+ /**
+ * Set the child.
+ * @param {cc.Node} value
+ */
+ setChild:function (value) {
+ this._child = value;
+ },
+
+ /**
+ * initializes cc.PointObject
+ * @param {cc.Vec2} ratio Not point, this is a ratio.
+ * @param {cc.Vec2} offset
+ * @return {Boolean}
+ */
+ initWithCCPoint:function (ratio, offset) {
+ this._ratio = ratio;
+ this._offset = offset;
+ this._child = null;
+ return true;
+ }
+});
+
+/**
+ * Create a object to stored parallax data.
+ * @param {cc.Vec2} ratio
+ * @param {cc.Vec2} offset
+ * @return {cc.PointObject}
+ * @deprecated since v3.0 please use new cc.PointObject() instead.
+ */
+cc.PointObject.create = function (ratio, offset) {
+ return new cc.PointObject(ratio, offset);
+};
+
+/**
+ * cc.ParallaxNode: A node that simulates a parallax scroller
+ * The children will be moved faster / slower than the parent according the the parallax ratio.
+ * @class
+ * @extends cc.Node
+ *
+ * @property {Array} parallaxArray - Parallax nodes array
+ */
+cc.ParallaxNode = cc.Node.extend(/** @lends cc.ParallaxNode# */{
+ parallaxArray:null,
+
+ _lastPosition:null,
+ _className:"ParallaxNode",
+
+ /**
+ * Gets the parallax array.
+ * @return {Array}
+ */
+ getParallaxArray:function () {
+ return this.parallaxArray;
+ },
+
+ /**
+ * Set parallax array.
+ * @param {Array} value
+ */
+ setParallaxArray:function (value) {
+ this.parallaxArray = value;
+ },
+
+ /**
+ * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
+ */
+ ctor:function () {
+ cc.Node.prototype.ctor.call(this);
+ this.parallaxArray = [];
+ this._lastPosition = cc.p(-100, -100);
+ },
+
+ /**
+ * Adds a child to the container with a z-order, a parallax ratio and a position offset
+ * It returns self, so you can chain several addChilds.
+ * @param {cc.Node} child
+ * @param {Number} z
+ * @param {cc.Vec2} ratio
+ * @param {cc.Vec2} offset
+ * @example
+ * //example
+ * voidNode.addChild(background, -1, cc.p(0.4, 0.5), cc.p(0,0));
+ */
+ addChild:function (child, z, ratio, offset) {
+ if (arguments.length === 3) {
+ cc.log("ParallaxNode: use addChild(child, z, ratio, offset) instead");
+ return;
+ }
+ if(!child)
+ throw new Error("cc.ParallaxNode.addChild(): child should be non-null");
+ var obj = new cc.PointObject(ratio, offset);
+ obj.setChild(child);
+ this.parallaxArray.push(obj);
+
+ child.setPosition(this._position.x * ratio.x + offset.x, this._position.y * ratio.y + offset.y);
+
+ cc.Node.prototype.addChild.call(this, child, z, child.tag);
+ },
+
+ /**
+ * Remove Child
+ * @param {cc.Node} child
+ * @param {Boolean} cleanup
+ * @example
+ * //example
+ * voidNode.removeChild(background,true);
+ */
+ removeChild:function (child, cleanup) {
+ var locParallaxArray = this.parallaxArray;
+ for (var i = 0; i < locParallaxArray.length; i++) {
+ var point = locParallaxArray[i];
+ if (point.getChild() === child) {
+ locParallaxArray.splice(i, 1);
+ break;
+ }
+ }
+ cc.Node.prototype.removeChild.call(this, child, cleanup);
+ },
+
+ /**
+ * Remove all children with cleanup
+ * @param {Boolean} cleanup
+ */
+ removeAllChildren:function (cleanup) {
+ this.parallaxArray.length = 0;
+ cc.Node.prototype.removeAllChildren.call(this, cleanup);
+ },
+
+ _updateParallaxPosition: function(){
+ var pos = this._absolutePosition();
+ if (!cc.pointEqualToPoint(pos, this._lastPosition)) {
+ var locParallaxArray = this.parallaxArray;
+ for (var i = 0, len = locParallaxArray.length; i < len; i++) {
+ var point = locParallaxArray[i];
+ var child = point.getChild();
+ child.setPosition(-pos.x + pos.x * point.getRatio().x + point.getOffset().x,
+ -pos.y + pos.y * point.getRatio().y + point.getOffset().y);
+ }
+ this._lastPosition = pos;
+ }
+ },
+
+ _absolutePosition:function () {
+ var ret = this._position;
+ var cn = this;
+ while (cn.parent !== null) {
+ cn = cn.parent;
+ ret = cc.pAdd(ret, cn.getPosition());
+ }
+ return ret;
+ },
+
+ _createRenderCmd: function(){
+ if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ return new cc.ParallaxNode.CanvasRenderCmd(this);
+ else
+ return new cc.ParallaxNode.WebGLRenderCmd(this);
+ }
+});
+
+/**
+ * Create new parallax node.
+ * @deprecated since v3.0 please use new cc.ParallaxNode() instead.
+ * @return {cc.ParallaxNode}
+ * @example
+ * //example
+ * var voidNode = new cc.ParallaxNode();
+ */
+cc.ParallaxNode.create = function () {
+ return new cc.ParallaxNode();
+};
diff --git a/cocos2d/parallax/CCParallaxNodeRenderCmd.js b/cocos2d/parallax/CCParallaxNodeRenderCmd.js
new file mode 100644
index 0000000000..985e7d0d31
--- /dev/null
+++ b/cocos2d/parallax/CCParallaxNodeRenderCmd.js
@@ -0,0 +1,69 @@
+/****************************************************************************
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+//TODO find a way to simple these code.
+
+(function(){
+ cc.ParallaxNode.CanvasRenderCmd = function(renderable){
+ cc.Node.CanvasRenderCmd.call(this, renderable);
+ this._needDraw = false;
+ };
+
+ var proto = cc.ParallaxNode.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
+ proto.constructor = cc.ParallaxNode.CanvasRenderCmd;
+
+ proto.updateStatus = function(){
+ this._node._updateParallaxPosition();
+ cc.Node.CanvasRenderCmd.prototype.updateStatus.call(this);
+ };
+
+ proto._syncStatus = function(parentCmd){
+ this._node._updateParallaxPosition();
+ cc.Node.CanvasRenderCmd.prototype._syncStatus.call(this, parentCmd);
+ }
+})();
+
+cc.game.once(cc.game.EVENT_RENDERER_INITED, function () {
+ if(cc._renderType !== cc.game.RENDER_TYPE_WEBGL)
+ return;
+
+ cc.ParallaxNode.WebGLRenderCmd = function(renderable){
+ cc.Node.WebGLRenderCmd.call(this, renderable);
+ this._needDraw = false;
+ };
+
+ var proto = cc.ParallaxNode.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
+ proto.constructor = cc.ParallaxNode.WebGLRenderCmd;
+
+ proto.updateStatus = function(){
+ this._node._updateParallaxPosition();
+ cc.Node.WebGLRenderCmd.prototype.updateStatus.call(this);
+ };
+
+ proto._syncStatus = function(parentCmd){
+ this._node._updateParallaxPosition();
+ cc.Node.WebGLRenderCmd.prototype._syncStatus.call(this, parentCmd);
+ }
+});
+
diff --git a/cocos2d/particle/CCEParticleSystem.js b/cocos2d/particle/CCEParticleSystem.js
new file mode 100644
index 0000000000..04abe4bc77
--- /dev/null
+++ b/cocos2d/particle/CCEParticleSystem.js
@@ -0,0 +1,830 @@
+/****************************************************************************
+ Copyright (c) 2015 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.
+ ****************************************************************************/
+
+/**
+ * Enum for emitter modes
+ * @enum EmitterMode
+ * @namespace EParticleSystem
+ */
+var EmitterMode = cc.Enum({
+ /**
+ * @property {Number} GRAVITY - Uses gravity, speed, radial and tangential acceleration.
+ */
+ GRAVITY: 0,
+ /**
+ * @property {Number} RADIUS - Uses radius movement + rotation.
+ */
+ RADIUS: 1
+});
+
+/**
+ * Enum for particles movement type
+ * @enum PositionType
+ * @namespace EParticleSystem
+ */
+var PositionType = cc.Enum({
+ /**
+ * Living particles are attached to the world and are unaffected by emitter repositioning.
+ * @property {Number} FREE
+ */
+ FREE: 0,
+
+ /**
+ * Living particles are attached to the world but will follow the emitter repositioning.
+ * Use case: Attach an emitter to an sprite, and you want that the emitter follows the sprite.
+ * @property {Number} RELATIVE
+ */
+ RELATIVE: 1,
+
+ /**
+ * Living particles are attached to the emitter and are translated along with it.
+ * @property {Number} GROUPED
+ */
+ GROUPED: 2
+});
+
+var properties = {
+
+ /**
+ * Play particle in edit mode.
+ * @property {Boolean} preview
+ * @default false
+ */
+ preview: {
+ default: true,
+ editorOnly: true,
+ notify: CC_EDITOR && function () {
+ if (this._sgNode) {
+ this._sgNode.resetSystem();
+ if ( !this.preview ) {
+ this._sgNode.stopSystem();
+ }
+ cc.engine.repaintInEditMode();
+ }
+ }
+ },
+
+ /**
+ * If set custom to true, then use custom properties insteadof read particle file.
+ * @property {Boolean} custom
+ * @default false
+ */
+ _custom: false,
+ custom: {
+ get: function () {
+ return this._custom;
+ },
+ set: function (value) {
+ if (CC_EDITOR && !value && !this._file) {
+ return cc.warn('Custom should not be false if file is not specified.');
+ }
+ if (this._custom !== value) {
+ this._custom = value;
+ if (this._sgNode) {
+ if (value) {
+ this._applyCustoms();
+ }
+ else {
+ this._applyFile();
+ }
+ cc.engine.repaintInEditMode();
+ //if (CC_EDITOR) {
+ // self.preview = self.preview;
+ //}
+ }
+ }
+ },
+ },
+
+ /**
+ * The plist file.
+ * @property {string} file
+ * @default ""
+ */
+ _file: {
+ default: '',
+ url: cc.ParticleAsset
+ },
+ file: {
+ get: function () {
+ return this._file;
+ },
+ set: function (value, force) {
+ if (this._file !== value || (CC_EDITOR && force)) {
+ this._file = value;
+ if (this._sgNode && value) {
+ this._applyFile();
+ cc.engine.repaintInEditMode();
+ //if (CC_EDITOR) {
+ // self.preview = self.preview;
+ //}
+ }
+ else {
+ this.custom = true;
+ }
+ }
+ },
+ url: cc.ParticleAsset
+ },
+
+ /**
+ * @property {Texture2D} texture - Texture of Particle System.
+ */
+ _texture: {
+ default: '',
+ url: cc.Texture2D
+ },
+ texture: {
+ get: function () {
+ return this._texture;
+ },
+ set: function (value) {
+ this._texture = value;
+
+ if (this._sgNode) {
+ this._sgNode.texture = value ? cc.textureCache.addImage( value ) : null;
+ }
+ },
+ url: cc.Texture2D
+ },
+
+ /**
+ * @property {Number} particleCount - Current quantity of particles that are being simulated.
+ */
+ particleCount: {
+ get: function () {
+ return this._sgNode ? this._sgNode.particleCount : 0;
+ },
+ set: function (value) {
+ if (this._sgNode) {
+ this._sgNode.particleCount = value;
+ }
+ },
+ visible: false
+ },
+
+ /**
+ * !#en If set to true, the particle system will automatically start playing on onLoad.
+ * !#zh ćŠæèźŸçœźäžștrue èżèĄæ¶äŒèȘćšćć°çČć
+ * @property playOnLoad
+ * @type {boolean}
+ * @default true
+ */
+ playOnLoad: true,
+
+ /**
+ * @property {Boolean} autoRemoveOnFinish - Indicate whether the owner node will be auto-removed when it has no particles left.
+ */
+ _autoRemoveOnFinish: false,
+ autoRemoveOnFinish: {
+ get: function () {
+ return this._autoRemoveOnFinish;
+ },
+ set: function (value) {
+ if (this._autoRemoveOnFinish !== value) {
+ this._autoRemoveOnFinish = value;
+ if (CC_EDITOR && !cc.engine.isPlaying) {
+ return;
+ }
+ this._applyAutoRemove();
+ }
+ },
+ },
+
+ /**
+ * Indicate whether the particle system is activated.
+ * @property {Boolean} active
+ * @readonly
+ */
+ active: {
+ get: function () {
+ return this._sgNode ? this._sgNode.isActive() : false;
+ },
+ visible: false
+ }
+};
+
+/**
+ * @class EParticleSystem
+ */
+var CustomProps = (function () {
+ var DefaultValues = {
+ /**
+ * @property {Number} totalParticles - Maximum particles of the system.
+ * @default 150
+ */
+ totalParticles: 150,
+ /**
+ * @property {Number} duration - How many seconds the emitter wil run. -1 means 'forever'
+ * @default EParticleSystem.DURATION_INFINITY
+ */
+ duration: -1,
+ /**
+ * @property {Number} emissionRate - Emission rate of the particles.
+ * @default 10
+ */
+ emissionRate: 10,
+ /**
+ * @property {Number} life - Life of each particle setter.
+ * @default 1
+ */
+ life: 1,
+ /**
+ * @property {Number} lifeVar - Variation of life.
+ * @default 0
+ */
+ lifeVar: 0,
+
+ /**
+ * @property {Color} startColor - Start color of each particle.
+ * @default cc.Color.WHITE
+ */
+ startColor: cc.Color.WHITE,
+ /**
+ * @property {Color} startColorVar - Variation of the start color.
+ * @default cc.Color.BLACK
+ */
+ startColorVar: cc.Color.BLACK,
+ /**
+ * @property {Color} endColor - Ending color of each particle.
+ * @default new cc.Color(255, 255, 255, 0)
+ */
+ endColor: cc.color(255, 255, 255, 0),
+ /**
+ * @property {Color} endColorVar - Variation of the end color.
+ * @default Color.TRANSPARENT
+ */
+ endColorVar: cc.color(0, 0, 0, 0),
+
+ /**
+ * @property {Number} angle - Angle of each particle setter.
+ * @default 90
+ */
+ angle: 90,
+ /**
+ * @property {Number} angleVar - Variation of angle of each particle setter.
+ * @default 20
+ */
+ angleVar: 20,
+ /**
+ * @property {Number} startSize - Start size in pixels of each particle.
+ * @default 50
+ */
+ startSize: 50,
+ /**
+ * @property {Number} startSizeVar - Variation of start size in pixels.
+ * @default 0
+ */
+ startSizeVar: 0,
+ /**
+ * @property {Number} endSize - End size in pixels of each particle.
+ * @default 0
+ */
+ endSize: 0,
+ /**
+ * @property {Number} endSizeVar - Variation of end size in pixels.
+ * @default 0
+ */
+ endSizeVar: 0,
+ /**
+ * @property {Number} startSpin - Start angle of each particle.
+ * @default 0
+ */
+ startSpin: 0,
+ /**
+ * @property {Number} startSpinVar - Variation of start angle.
+ * @default 0
+ */
+ startSpinVar: 0,
+ /**
+ * @property {Number} endSpin - End angle of each particle.
+ * @default 0
+ */
+ endSpin: 0,
+ /**
+ * @property {Number} endSpinVar - Variation of end angle.
+ * @default 0
+ */
+ endSpinVar: 0,
+
+ /**
+ * @property {Vec2} sourcePos - Source position of the emitter.
+ * @default cc.Vec2.ZERO
+ */
+ sourcePos: cc.p(0, 0),
+
+ /**
+ * @property {Vec2} posVar - Variation of source position.
+ * @default cc.Vec2.ZERO
+ */
+ posVar: cc.p(0, 0),
+
+ /**
+ * Particles movement type.
+ * @property {EParticleSystem.PositionType} positionType
+ * @default EParticleSystem.PositionType.FREE
+ */
+ positionType: PositionType.FREE,
+ /**
+ * Particles emitter modes.
+ * @property {EParticleSystem.EmitterMode} emitterMode
+ * @default EParticleSystem.EmitterMode.GRAVITY
+ */
+ emitterMode: EmitterMode.GRAVITY,
+
+ // GRAVITY MODE
+
+ /**
+ * @property {Vec2} gravity - Gravity of the emitter.
+ * @default cc.Vec2.ZERO
+ */
+ gravity: cc.p(0, 0),
+ /**
+ * @property {Number} speed - Speed of the emitter.
+ * @default 180
+ */
+ speed: 180,
+ /**
+ * @property {Number} speedVar - Variation of the speed.
+ * @default 50
+ */
+ speedVar: 50,
+ /**
+ * @property {Number} tangentialAccel - Tangential acceleration of each particle. Only available in 'Gravity' mode.
+ * @default 80
+ */
+ tangentialAccel: 80,
+ /**
+ * @property {Number} tangentialAccelVar - Variation of the tangential acceleration.
+ * @default 0
+ */
+ tangentialAccelVar: 0,
+ /**
+ * @property {Number} radialAccel - Radial acceleration of each particle. Only available in 'Gravity' mode.
+ * @default 0
+ */
+ radialAccel: 0,
+ /**
+ * @property {Number} radialAccelVar - Variation of the radial acceleration.
+ * @default 0
+ */
+ radialAccelVar: 0,
+
+ /**
+ * @property {Boolean} rotationIsDir - Indicate whether the rotation of each particle equals to its direction. Only available in 'Gravity' mode.
+ * @default false
+ */
+ rotationIsDir: false,
+
+ // RADIUS MODE
+
+ /**
+ * @property {Number} startRadius - Starting radius of the particles. Only available in 'Radius' mode.
+ * @default 0
+ */
+ startRadius: 0,
+ /**
+ * @property {Number} startRadiusVar - Variation of the starting radius.
+ * @default 0
+ */
+ startRadiusVar: 0,
+ /**
+ * @property {Number} endRadius - Ending radius of the particles. Only available in 'Radius' mode.
+ * @default 0
+ */
+ endRadius: 0,
+ /**
+ * @property {Number} endRadiusVar - Variation of the ending radius.
+ * @default 0
+ */
+ endRadiusVar: 0,
+ /**
+ * @property {Number} rotatePerS - Number of degress to rotate a particle around the source pos per second. Only available in 'Radius' mode.
+ * @default 0
+ */
+ rotatePerS: 0,
+ /**
+ * @property {Number} rotatePerSVar - Variation of the degress to rotate a particle around the source pos per second.
+ * @default 0
+ */
+ rotatePerSVar: 0
+ };
+ var props = Object.keys(DefaultValues);
+
+ for (var i = 0; i < props.length; ++i) {
+ var prop = props[i];
+ (function (prop, defaultValue) {
+ var internalProp = '_' + prop;
+ properties[internalProp] = defaultValue;
+
+ var type = defaultValue.constructor;
+ var propDef = properties[prop] = {};
+
+ if (cc.isChildClassOf(type, cc.ValueType)) {
+ propDef.get = function () {
+ return new type(this[internalProp]);
+ };
+ propDef.type = type;
+ }
+ else {
+ propDef.get = function () {
+ return this[internalProp];
+ };
+ }
+
+ if (cc.isChildClassOf(type, cc.ValueType)) {
+ propDef.set = function (value) {
+ this[internalProp] = new type(value);
+ if (this._sgNode) {
+ this._sgNode[prop] = value;
+ }
+ };
+ }
+ else if (CC_EDITOR && typeof defaultValue === "number") {
+ propDef.set = function (value) {
+ this[internalProp] = value;
+ if (!isNaN(value)) {
+ if (this._sgNode) {
+ this._sgNode[prop] = value;
+ }
+ }
+ else {
+ cc.error('The new %s must not be NaN', prop);
+ }
+ };
+ }
+ else {
+ propDef.set = function (value) {
+ this[internalProp] = value;
+ if (this._sgNode) {
+ this._sgNode[prop] = value;
+ }
+ };
+ }
+ })(prop, DefaultValues[prop]);
+ }
+ return props;
+})();
+
+properties.positionType.type = PositionType;
+properties.emitterMode.type = EmitterMode;
+
+/**
+ *
+ * Particle System base class.
+ * Attributes of a Particle System:
+ * - emmision rate of the particles
+ * - Gravity Mode (Mode A):
+ * - gravity
+ * - direction
+ * - speed +- variance
+ * - tangential acceleration +- variance
+ * - radial acceleration +- variance
+ * - Radius Mode (Mode B):
+ * - startRadius +- variance
+ * - endRadius +- variance
+ * - rotate +- variance
+ * - Properties common to all modes:
+ * - life +- life variance
+ * - start spin +- variance
+ * - end spin +- variance
+ * - start size +- variance
+ * - end size +- variance
+ * - start color +- variance
+ * - end color +- variance
+ * - life +- variance
+ * - blending function
+ * - texture
+ *
+ * cocos2d also supports particles generated by Particle Designer (http://particledesigner.71squared.com/).
+ * 'Radius Mode' in Particle Designer uses a fixed emit rate of 30 hz. Since that can't be guarateed in cocos2d,
+ * cocos2d uses a another approach, but the results are almost identical.
+ * cocos2d supports all the variables used by Particle Designer plus a bit more:
+ * - spinning particles (supported when using ParticleSystem)
+ * - tangential acceleration (Gravity mode)
+ * - radial acceleration (Gravity mode)
+ * - radius direction (Radius mode) (Particle Designer supports outwards to inwards direction only)
+ * It is possible to customize any of the above mentioned properties in runtime. Example:
+ *
+ * @class EParticleSystem
+ * @extends cc._ComponentInSG
+ */
+var ParticleSystem = cc.Class({
+ name: 'cc.ParticleSystem',
+ extends: cc._ComponentInSG,
+ editor: CC_EDITOR && {
+ menu: 'ParticleSystem',
+ inspector: 'app://editor/page/inspector/particle-system/index.html',
+ playOnFocus: true,
+ },
+
+ ctor: function () {
+ this._previewTimer = null;
+ this._focused = false;
+ this._willStart = false;
+ },
+
+ properties: properties,
+
+ statics: {
+
+ /**
+ * The Particle emitter lives forever
+ * @property {Number} DURATION_INFINITY
+ * @default -1
+ * @static
+ * @readonly
+ */
+ DURATION_INFINITY: -1,
+
+ /**
+ * The starting size of the particle is equal to the ending size
+ * @property {Number} START_SIZE_EQUAL_TO_END_SIZE
+ * @default -1
+ * @static
+ * @readonly
+ */
+ START_SIZE_EQUAL_TO_END_SIZE: -1,
+
+ /**
+ * The starting radius of the particle is equal to the ending radius
+ * @property {Number} START_RADIUS_EQUAL_TO_END_RADIUS
+ * @default -1
+ * @static
+ * @readonly
+ */
+ START_RADIUS_EQUAL_TO_END_RADIUS: -1,
+
+ EmitterMode: EmitterMode,
+ PositionType: PositionType,
+ },
+
+ // LIFE-CYCLE METHODS
+ onLoad: function () {
+ this._super();
+ // auto play
+ if (CC_EDITOR && !cc.engine.isPlaying) {
+ if (this.preview) {
+ this.resetSystem();
+ }
+ }
+ else {
+ if (this.playOnLoad) {
+ this.resetSystem();
+ }
+ this._applyAutoRemove();
+ }
+ },
+ //onEnable: function () {
+ // this._super();
+ //},
+ //onDisable: function () {
+ // this._super();
+ //},
+ onDestroy: function () {
+ if (this._autoRemoveOnFinish) {
+ this.autoRemoveOnFinish = false; // already removed
+ }
+ this._super();
+ },
+
+ onFocusInEditor: CC_EDITOR && function () {
+ this._focused = true;
+ if (this.preview && this._sgNode) {
+ this._sgNode.resetSystem();
+
+ var self = this;
+ this._previewTimer = setInterval(function () {
+ // attemptToReplay
+ if (self.particleCount === 0 && !self._willStart) {
+ self._willStart = true;
+ setTimeout(function () {
+ self._willStart = false;
+ if (self.preview && self._focused && !self.active && !cc.engine.isPlaying) {
+ self.resetSystem();
+ }
+ }, 600);
+ }
+ }, 100);
+ }
+ },
+
+ onLostFocusInEditor: CC_EDITOR && function () {
+ this._focused = false;
+ if (this.preview && this._sgNode) {
+ this._sgNode.resetSystem();
+ this._sgNode.stopSystem();
+ this._sgNode.update();
+ cc.engine.repaintInEditMode();
+ }
+ if (this._previewTimer) {
+ clearInterval(this._previewTimer);
+ }
+ },
+
+ // OVERRIDE METHODS
+
+ _createSgNode: function () {
+ var sgNode = this._sgNode = new cc.ParticleSystem();
+
+ var loadCustomAfterFile = false;
+ if (this._file) {
+ var missCustomTexture = this._custom && !this._texture;
+ loadCustomAfterFile = missCustomTexture;
+ this._applyFile(loadCustomAfterFile && this._applyCustoms.bind(this));
+ }
+ if (this._custom && !loadCustomAfterFile) {
+ this._applyCustoms();
+ }
+
+ // stop by default
+ sgNode.stopSystem();
+ return sgNode;
+ },
+
+ // APIS
+
+ /**
+ * Add a particle to the emitter
+ * @method addParticle
+ * @return {Boolean}
+ */
+ addParticle: function () {
+ if (this._sgNode) {
+ return this._sgNode.addParticle();
+ }
+ else {
+ return false;
+ }
+ },
+
+ /**
+ * stop emitting particles. Running particles will continue to run until they die
+ * @method stopSystem
+ */
+ stopSystem: function () {
+ if (this._sgNode) {
+ this._sgNode.stopSystem();
+ }
+ },
+
+ /**
+ * Kill all living particles.
+ * @method resetSystem
+ */
+ resetSystem: function () {
+ if (this._sgNode) {
+ this._sgNode.resetSystem();
+ }
+ },
+
+ /**
+ * whether or not the system is full
+ * @method isFull
+ * @return {Boolean}
+ */
+ isFull: function () {
+ return (this.particleCount >= this._totalParticles);
+ },
+
+ /**
+ * Sets a new CCSpriteFrame as particle.
+ * WARNING: this method is experimental. Use setTextureWithRect instead.
+ *
+ * @method setDisplayFrame
+ * @param {SpriteFrame} spriteFrame
+ */
+ setDisplayFrame: function (spriteFrame) {
+ if (!spriteFrame)
+ return;
+
+ var texture = spriteFrame.getTexture();
+ if (texture) {
+ this._texture = texture.url;
+ }
+ if (this._sgNode) {
+ this._sgNode.setDisplayFrame(spriteFrame);
+ }
+ },
+
+ /**
+ * Sets a new texture with a rect. The rect is in Points.
+ * @method setTextureWithRect
+ * @param {Texture2D} texture
+ * @param {Rect} rect
+ */
+ setTextureWithRect: function (texture, rect) {
+ if (texture instanceof cc.Texture2D) {
+ this._texture = texture.url;
+ }
+ if (this._sgNode) {
+ this._sgNode.setTextureWithRect(texture, rect);
+ }
+ },
+
+ // PRIVATE METHODS
+
+ _applyFile: function (done) {
+ var node = this._sgNode;
+ if (!node) {
+ return;
+ }
+ var file = this._file;
+ if (file) {
+ var self = this;
+ cc.loader.load(file, function (err, results) {
+ if (err) throw err;
+
+ node.particleCount = 0;
+
+ var active = node.isActive();
+ node.initWithFile(file);
+
+ // recover sgNode properties
+
+ if (!active) {
+ node.stopSystem();
+ }
+
+ var sourcePos = node.getPosition();
+ if (CC_EDITOR && (sourcePos.x !== 0 || sourcePos.y !== 0)) {
+ cc.log('Discard sourcePosition: %s from "%s", you can set position in the node directly.', sourcePos, cc.path.basename(file));
+ }
+ node.setPosition(0, 0);
+
+ node.autoRemoveOnFinish = self._autoRemoveOnFinish;
+
+ //
+
+ if (done) {
+ done();
+ }
+ });
+ }
+ },
+
+ _applyCustoms: function () {
+ var node = this._sgNode;
+ if (!node) {
+ return;
+ }
+
+ var active = node.isActive();
+
+ for (var i = 0; i < CustomProps.length; i++) {
+ var prop = CustomProps[i];
+ node[prop] = this['_' + prop];
+ }
+ if (this._texture) {
+ node.texture = cc.textureCache.addImage(this._texture);
+ }
+
+ // recover sgNode properties
+ if (!active) {
+ node.stopSystem();
+ }
+ node.autoRemoveOnFinish = this._autoRemoveOnFinish;
+ },
+
+ _applyAutoRemove: function () {
+ var sgNode = this._sgNode;
+ if (sgNode) {
+ var autoRemove = this._autoRemoveOnFinish;
+ sgNode.autoRemoveOnFinish = autoRemove;
+ if (autoRemove) {
+ cc.assert(!sgNode.onExit);
+ var self = this;
+ sgNode.onExit = function () {
+ cc.Node.prototype.onExit.call(this);
+ self.node.destroy();
+ };
+ }
+ else {
+ sgNode.onExit = null;
+ }
+ }
+ }
+});
+
+cc.EParticleSystem = module.exports = ParticleSystem;
diff --git a/cocos2d/particle/CCPNGReader.js b/cocos2d/particle/CCPNGReader.js
new file mode 100644
index 0000000000..44cde5b4f8
--- /dev/null
+++ b/cocos2d/particle/CCPNGReader.js
@@ -0,0 +1,330 @@
+/****************************************************************************
+ Copyright (c) 2011 Devon Govett
+ 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 png file reader
+ * @name cc.tiffReader
+ */
+cc.PNGReader = cc._Class.extend({
+ ctor:function(data){
+ var chunkSize, colors, delayDen, delayNum, frame, i, index, key, section, ccshort, text, _i, _j, _ref;
+ this.data = data;
+ this.pos = 8;
+ this.palette = [];
+ this.imgData = [];
+ this.transparency = {};
+ this.animation = null;
+ this.text = {};
+ frame = null;
+ while (true) {
+ chunkSize = this.readUInt32();
+ section = ((function() {
+ var _i, _results;
+ _results = [];
+ for (i = _i = 0; _i < 4; i = ++_i) {
+ _results.push(String.fromCharCode(this.data[this.pos++]));
+ }
+ return _results;
+ }).call(this)).join('');
+ switch (section) {
+ case 'IHDR':
+ this.width = this.readUInt32();
+ this.height = this.readUInt32();
+ this.bits = this.data[this.pos++];
+ this.colorType = this.data[this.pos++];
+ this.compressionMethod = this.data[this.pos++];
+ this.filterMethod = this.data[this.pos++];
+ this.interlaceMethod = this.data[this.pos++];
+ break;
+ case 'acTL':
+ this.animation = {
+ numFrames: this.readUInt32(),
+ numPlays: this.readUInt32() || Infinity,
+ frames: []
+ };
+ break;
+ case 'PLTE':
+ this.palette = this.read(chunkSize);
+ break;
+ case 'fcTL':
+ if (frame) {
+ this.animation.frames.push(frame);
+ }
+ this.pos += 4;
+ frame = {
+ width: this.readUInt32(),
+ height: this.readUInt32(),
+ xOffset: this.readUInt32(),
+ yOffset: this.readUInt32()
+ };
+ delayNum = this.readUInt16();
+ delayDen = this.readUInt16() || 100;
+ frame.delay = 1000 * delayNum / delayDen;
+ frame.disposeOp = this.data[this.pos++];
+ frame.blendOp = this.data[this.pos++];
+ frame.data = [];
+ break;
+ case 'IDAT':
+ case 'fdAT':
+ if (section === 'fdAT') {
+ this.pos += 4;
+ chunkSize -= 4;
+ }
+ data = (frame != null ? frame.data : void 0) || this.imgData;
+ for (i = _i = 0; 0 <= chunkSize ? _i < chunkSize : _i > chunkSize; i = 0 <= chunkSize ? ++_i : --_i) {
+ data.push(this.data[this.pos++]);
+ }
+ break;
+ case 'tRNS':
+ this.transparency = {};
+ switch (this.colorType) {
+ case 3:
+ this.transparency.indexed = this.read(chunkSize);
+ ccshort = 255 - this.transparency.indexed.length;
+ if (ccshort > 0) {
+ for (i = _j = 0; 0 <= ccshort ? _j < ccshort : _j > ccshort; i = 0 <= ccshort ? ++_j : --_j) {
+ this.transparency.indexed.push(255);
+ }
+ }
+ break;
+ case 0:
+ this.transparency.grayscale = this.read(chunkSize)[0];
+ break;
+ case 2:
+ this.transparency.rgb = this.read(chunkSize);
+ }
+ break;
+ case 'tEXt':
+ text = this.read(chunkSize);
+ index = text.indexOf(0);
+ key = String.fromCharCode.apply(String, text.slice(0, index));
+ this.text[key] = String.fromCharCode.apply(String, text.slice(index + 1));
+ break;
+ case 'IEND':
+ if (frame) {
+ this.animation.frames.push(frame);
+ }
+ this.colors = (function() {
+ switch (this.colorType) {
+ case 0:
+ case 3:
+ case 4:
+ return 1;
+ case 2:
+ case 6:
+ return 3;
+ }
+ }).call(this);
+ this.hasAlphaChannel = (_ref = this.colorType) === 4 || _ref === 6;
+ colors = this.colors + (this.hasAlphaChannel ? 1 : 0);
+ this.pixelBitlength = this.bits * colors;
+ this.colorSpace = (function() {
+ switch (this.colors) {
+ case 1:
+ return 'DeviceGray';
+ case 3:
+ return 'DeviceRGB';
+ }
+ }).call(this);
+ if(Uint8Array != Array)
+ this.imgData = new Uint8Array(this.imgData);
+ return;
+ default:
+ this.pos += chunkSize;
+ }
+ this.pos += 4;
+ if (this.pos > this.data.length) {
+ throw new Error("Incomplete or corrupt PNG file");
+ }
+ }
+ },
+ read:function(bytes){
+ var i, _i, _results;
+ _results = [];
+ for (i = _i = 0; 0 <= bytes ? _i < bytes : _i > bytes; i = 0 <= bytes ? ++_i : --_i) {
+ _results.push(this.data[this.pos++]);
+ }
+ return _results;
+ },
+ readUInt32:function(){
+ var b1, b2, b3, b4;
+ b1 = this.data[this.pos++] << 24;
+ b2 = this.data[this.pos++] << 16;
+ b3 = this.data[this.pos++] << 8;
+ b4 = this.data[this.pos++];
+ return b1 | b2 | b3 | b4;
+ },
+ readUInt16:function(){
+ var b1, b2;
+ b1 = this.data[this.pos++] << 8;
+ b2 = this.data[this.pos++];
+ return b1 | b2;
+ },
+ decodePixels:function(data){
+ var ccbyte, c, col, i, left, length, p, pa, paeth, pb, pc, pixelBytes, pixels, pos, row, scanlineLength, upper, upperLeft, _i, _j, _k, _l, _m;
+ if (data == null) {
+ data = this.imgData;
+ }
+ if (data.length === 0) {
+ return new Uint8Array(0);
+ }
+ var inflate = new Zlib.Inflate(data,{index:0, verify:false});
+ data = inflate.decompress();
+
+ pixelBytes = this.pixelBitlength / 8;
+ scanlineLength = pixelBytes * this.width;
+ pixels = new Uint8Array(scanlineLength * this.height);
+ length = data.length;
+ row = 0;
+ pos = 0;
+ c = 0;
+ while (pos < length) {
+ switch (data[pos++]) {
+ case 0:
+ for (i = _i = 0; _i < scanlineLength; i = _i += 1) {
+ pixels[c++] = data[pos++];
+ }
+ break;
+ case 1:
+ for (i = _j = 0; _j < scanlineLength; i = _j += 1) {
+ ccbyte = data[pos++];
+ left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
+ pixels[c++] = (ccbyte + left) % 256;
+ }
+ break;
+ case 2:
+ for (i = _k = 0; _k < scanlineLength; i = _k += 1) {
+ ccbyte = data[pos++];
+ col = (i - (i % pixelBytes)) / pixelBytes;
+ upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
+ pixels[c++] = (upper + ccbyte) % 256;
+ }
+ break;
+ case 3:
+ for (i = _l = 0; _l < scanlineLength; i = _l += 1) {
+ ccbyte = data[pos++];
+ col = (i - (i % pixelBytes)) / pixelBytes;
+ left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
+ upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
+ pixels[c++] = (ccbyte + Math.floor((left + upper) / 2)) % 256;
+ }
+ break;
+ case 4:
+ for (i = _m = 0; _m < scanlineLength; i = _m += 1) {
+ ccbyte = data[pos++];
+ col = (i - (i % pixelBytes)) / pixelBytes;
+ left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
+ if (row === 0) {
+ upper = upperLeft = 0;
+ } else {
+ upper = pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
+ upperLeft = col && pixels[(row - 1) * scanlineLength + (col - 1) * pixelBytes + (i % pixelBytes)];
+ }
+ p = left + upper - upperLeft;
+ pa = Math.abs(p - left);
+ pb = Math.abs(p - upper);
+ pc = Math.abs(p - upperLeft);
+ if (pa <= pb && pa <= pc) {
+ paeth = left;
+ } else if (pb <= pc) {
+ paeth = upper;
+ } else {
+ paeth = upperLeft;
+ }
+ pixels[c++] = (ccbyte + paeth) % 256;
+ }
+ break;
+ default:
+ throw new Error("Invalid filter algorithm: " + data[pos - 1]);
+ }
+ row++;
+ }
+ return pixels;
+ },
+ copyToImageData:function(imageData,pixels){
+ var alpha, colors, data, i, input, j, k, length, palette, v, _ref;
+ colors = this.colors;
+ palette = null;
+ alpha = this.hasAlphaChannel;
+ if (this.palette.length) {
+ palette = (_ref = this._decodedPalette) != null ? _ref : this._decodedPalette = this.decodePalette();
+ colors = 4;
+ alpha = true;
+ }
+ data = imageData.data || imageData;
+ length = data.length;
+ input = palette || pixels;
+ i = j = 0;
+ if (colors === 1) {
+ while (i < length) {
+ k = palette ? pixels[i / 4] * 4 : j;
+ v = input[k++];
+ data[i++] = v;
+ data[i++] = v;
+ data[i++] = v;
+ data[i++] = alpha ? input[k++] : 255;
+ j = k;
+ }
+ } else {
+ while (i < length) {
+ k = palette ? pixels[i / 4] * 4 : j;
+ data[i++] = input[k++];
+ data[i++] = input[k++];
+ data[i++] = input[k++];
+ data[i++] = alpha ? input[k++] : 255;
+ j = k;
+ }
+ }
+ },
+ decodePalette:function(){
+ var c, i, palette, pos, ret, transparency, _i, _ref, _ref1;
+ palette = this.palette;
+ transparency = this.transparency.indexed || [];
+ ret = new Uint8Array((transparency.length || 0) + palette.length);
+ pos = 0;
+ c = 0;
+ for (i = _i = 0, _ref = palette.length; _i < _ref; i = _i += 3) {
+ ret[pos++] = palette[i];
+ ret[pos++] = palette[i + 1];
+ ret[pos++] = palette[i + 2];
+ ret[pos++] = (_ref1 = transparency[c++]) != null ? _ref1 : 255;
+ }
+ return ret;
+ },
+ render: function (canvas) {
+ var ctx, data;
+ canvas.width = this.width;
+ canvas.height = this.height;
+ ctx = canvas.getContext("2d");
+ data = ctx.createImageData(this.width, this.height);
+ this.copyToImageData(data, this.decodePixels());
+ return ctx.putImageData(data, 0, 0);
+
+ }
+});
+
diff --git a/cocos2d/particle/CCParticleAsset.js b/cocos2d/particle/CCParticleAsset.js
new file mode 100644
index 0000000000..da960e75e5
--- /dev/null
+++ b/cocos2d/particle/CCParticleAsset.js
@@ -0,0 +1,12 @@
+/**
+ * Class for particle asset handling.
+ * @class ParticleAsset
+ * @extends RawAsset
+ * @constructor
+ */
+var ParticleAsset = cc.Class({
+ name: 'cc.ParticleAsset',
+ extends: cc.RawAsset,
+});
+
+cc.ParticleAsset = module.exports = ParticleAsset;
diff --git a/cocos2d/particle/CCParticleBatchNode.js b/cocos2d/particle/CCParticleBatchNode.js
new file mode 100644
index 0000000000..c63fcb658e
--- /dev/null
+++ b/cocos2d/particle/CCParticleBatchNode.js
@@ -0,0 +1,527 @@
+/**
+ * Copyright (c) 2008-2010 Ricardo Quesada
+ * Copyright (c) 2011-2012 cocos2d-x.org
+ * Copyright (c) 2013-2014 Chukong Technologies Inc.
+ * Copyright (C) 2009 Matt Oswald
+ * Copyright (c) 2011 Marco Tillemans
+ *
+ * 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.
+ *
+ */
+
+/**
+ * paticle default capacity
+ * @constant
+ * @type Number
+ */
+cc.PARTICLE_DEFAULT_CAPACITY = 500;
+
+/**
+ *
+ * cc.ParticleBatchNode is like a batch node: if it contains children, it will draw them in 1 single OpenGL call
+ * (often known as "batch draw").
+ *
+ * A cc.ParticleBatchNode can reference one and only one texture (one image file, one texture atlas).
+ * Only the cc.ParticleSystems that are contained in that texture can be added to the cc.SpriteBatchNode.
+ * All cc.ParticleSystems added to a cc.SpriteBatchNode are drawn in one OpenGL ES draw call.
+ * If the cc.ParticleSystems are not added to a cc.ParticleBatchNode then an OpenGL ES draw call will be needed for each one, which is less efficient.
+ *
+ * Limitations:
+ * - At the moment only cc.ParticleSystem is supported
+ * - All systems need to be drawn with the same parameters, blend function, aliasing, texture
+ *
+ * Most efficient usage
+ * - Initialize the ParticleBatchNode with the texture and enough capacity for all the particle systems
+ * - Initialize all particle systems and add them as child to the batch node
+ *
+ * @class
+ * @extends cc.ParticleSystem
+ * @param {String|cc.Texture2D} fileImage
+ * @param {Number} capacity
+ *
+ * @property {cc.Texture2D|HTMLImageElement|HTMLCanvasElement} texture - The used texture
+ * @property {cc.TextureAtlas} textureAtlas - The texture atlas used for drawing the quads
+ *
+ * @example
+ * 1.
+ * //Create a cc.ParticleBatchNode with image path and capacity
+ * var particleBatchNode = new cc.ParticleBatchNode("res/grossini_dance.png",30);
+ *
+ * 2.
+ * //Create a cc.ParticleBatchNode with a texture and capacity
+ * var texture = cc.TextureCache.getInstance().addImage("res/grossini_dance.png");
+ * var particleBatchNode = new cc.ParticleBatchNode(texture, 30);
+ */
+cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
+ textureAtlas:null,
+ //the blend function used for drawing the quads
+ _blendFunc:null,
+ _className:"ParticleBatchNode",
+
+ /**
+ * initializes the particle system with the name of a file on disk (for a list of supported formats look at the cc.Texture2D class), a capacity of particles
+ * Constructor of cc.ParticleBatchNode
+ * @param {String|cc.Texture2D} fileImage
+ * @param {Number} capacity
+ * @example
+ * 1.
+ * //Create a cc.ParticleBatchNode with image path and capacity
+ * var particleBatchNode = new cc.ParticleBatchNode("res/grossini_dance.png",30);
+ *
+ * 2.
+ * //Create a cc.ParticleBatchNode with a texture and capacity
+ * var texture = cc.TextureCache.getInstance().addImage("res/grossini_dance.png");
+ * var particleBatchNode = new cc.ParticleBatchNode(texture, 30);
+ */
+ ctor:function (fileImage, capacity) {
+ cc.Node.prototype.ctor.call(this);
+ this._blendFunc = {src:cc.BLEND_SRC, dst:cc.BLEND_DST};
+ if (cc.js.isString(fileImage)) {
+ this.init(fileImage, capacity);
+ } else if (fileImage instanceof cc.Texture2D) {
+ this.initWithTexture(fileImage, capacity);
+ }
+ },
+
+ _createRenderCmd: function(){
+ if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ return new cc.ParticleBatchNode.CanvasRenderCmd(this);
+ else
+ return new cc.ParticleBatchNode.WebGLRenderCmd(this);
+ },
+
+ /**
+ * initializes the particle system with cc.Texture2D, a capacity of particles
+ * @param {cc.Texture2D|HTMLImageElement|HTMLCanvasElement} texture
+ * @param {Number} capacity
+ * @return {Boolean}
+ */
+ initWithTexture:function (texture, capacity) {
+ this.textureAtlas = new cc.TextureAtlas();
+ this.textureAtlas.initWithTexture(texture, capacity);
+
+ // no lazy alloc in this node
+ this._children.length = 0;
+
+ this._renderCmd._initWithTexture();
+ return true;
+ },
+
+ /**
+ * initializes the particle system with the name of a file on disk (for a list of supported formats look at the cc.Texture2D class), a capacity of particles
+ * @param {String} fileImage
+ * @param {Number} capacity
+ * @return {Boolean}
+ */
+ initWithFile:function (fileImage, capacity) {
+ var tex = cc.textureCache.addImage(fileImage);
+ return this.initWithTexture(tex, capacity);
+ },
+
+ /**
+ * initializes the particle system with the name of a file on disk (for a list of supported formats look at the cc.Texture2D class), a capacity of particles
+ * @param {String} fileImage
+ * @param {Number} capacity
+ * @return {Boolean}
+ */
+ init:function (fileImage, capacity) {
+ var tex = cc.textureCache.addImage(fileImage);
+ return this.initWithTexture(tex, capacity);
+ },
+
+ /**
+ * Add a child into the cc.ParticleBatchNode
+ * @param {cc.ParticleSystem} child
+ * @param {Number} zOrder
+ * @param {Number} tag
+ */
+ addChild:function (child, zOrder, tag) {
+ if(!child)
+ throw new Error("cc.ParticleBatchNode.addChild() : child should be non-null");
+ if(!(child instanceof cc.ParticleSystem))
+ throw new Error("cc.ParticleBatchNode.addChild() : only supports cc.ParticleSystem as children");
+ zOrder = (zOrder == null) ? child.zIndex : zOrder;
+ tag = (tag == null) ? child.tag : tag;
+
+ if(child.getTexture() !== this.textureAtlas.texture)
+ throw new Error("cc.ParticleSystem.addChild() : the child is not using the same texture id");
+
+ // If this is the 1st children, then copy blending function
+ var childBlendFunc = child.getBlendFunc();
+ if (this._children.length === 0)
+ this.setBlendFunc(childBlendFunc);
+ else{
+ if((childBlendFunc.src !== this._blendFunc.src) || (childBlendFunc.dst !== this._blendFunc.dst)){
+ cc.log("cc.ParticleSystem.addChild() : Can't add a ParticleSystem that uses a different blending function");
+ return;
+ }
+ }
+
+ //no lazy sorting, so don't call super addChild, call helper instead
+ var pos = this._addChildHelper(child, zOrder, tag);
+
+ //get new atlasIndex
+ var atlasIndex = 0;
+
+ if (pos !== 0) {
+ var p = this._children[pos - 1];
+ atlasIndex = p.getAtlasIndex() + p.getTotalParticles();
+ } else
+ atlasIndex = 0;
+
+ this.insertChild(child, atlasIndex);
+
+ // update quad info
+ child.setBatchNode(this);
+ },
+
+ /**
+ * Inserts a child into the cc.ParticleBatchNode
+ * @param {cc.ParticleSystem} pSystem
+ * @param {Number} index
+ */
+ insertChild:function (pSystem, index) {
+ var totalParticles = pSystem.getTotalParticles();
+ var locTextureAtlas = this.textureAtlas;
+ var totalQuads = locTextureAtlas.totalQuads;
+ pSystem.setAtlasIndex(index);
+ if (totalQuads + totalParticles > locTextureAtlas.getCapacity()) {
+ this._increaseAtlasCapacityTo(totalQuads + totalParticles);
+ // after a realloc empty quads of textureAtlas can be filled with gibberish (realloc doesn't perform calloc), insert empty quads to prevent it
+ locTextureAtlas.fillWithEmptyQuadsFromIndex(locTextureAtlas.getCapacity() - totalParticles, totalParticles);
+ }
+
+ // make room for quads, not necessary for last child
+ if (pSystem.getAtlasIndex() + totalParticles !== totalQuads)
+ locTextureAtlas.moveQuadsFromIndex(index, index + totalParticles);
+
+ // increase totalParticles here for new particles, update method of particlesystem will fill the quads
+ locTextureAtlas.increaseTotalQuadsWith(totalParticles);
+ this._updateAllAtlasIndexes();
+ },
+
+ /**
+ * @param {cc.ParticleSystem} child
+ * @param {Boolean} cleanup
+ */
+ removeChild:function (child, cleanup) {
+ // explicit nil handling
+ if (child == null)
+ return;
+
+ if(!(child instanceof cc.ParticleSystem))
+ throw new Error("cc.ParticleBatchNode.removeChild(): only supports cc.ParticleSystem as children");
+ if(this._children.indexOf(child) === -1){
+ cc.log("cc.ParticleBatchNode.removeChild(): doesn't contain the sprite. Can't remove it");
+ return;
+ }
+
+ cc.Node.prototype.removeChild.call(this, child, cleanup);
+
+ var locTextureAtlas = this.textureAtlas;
+ // remove child helper
+ locTextureAtlas.removeQuadsAtIndex(child.getAtlasIndex(), child.getTotalParticles());
+
+ // after memmove of data, empty the quads at the end of array
+ locTextureAtlas.fillWithEmptyQuadsFromIndex(locTextureAtlas.totalQuads, child.getTotalParticles());
+
+ // paticle could be reused for self rendering
+ child.setBatchNode(null);
+
+ this._updateAllAtlasIndexes();
+ },
+
+ /**
+ * Reorder will be done in this function, no "lazy" reorder to particles
+ * @param {cc.ParticleSystem} child
+ * @param {Number} zOrder
+ */
+ reorderChild:function (child, zOrder) {
+ if(!child)
+ throw new Error("cc.ParticleBatchNode.reorderChild(): child should be non-null");
+ if(!(child instanceof cc.ParticleSystem))
+ throw new Error("cc.ParticleBatchNode.reorderChild(): only supports cc.QuadParticleSystems as children");
+ if(this._children.indexOf(child) === -1){
+ cc.log("cc.ParticleBatchNode.reorderChild(): Child doesn't belong to batch");
+ return;
+ }
+
+ if (zOrder === child.zIndex)
+ return;
+
+ // no reordering if only 1 child
+ if (this._children.length > 1) {
+ var getIndexes = this._getCurrentIndex(child, zOrder);
+
+ if (getIndexes.oldIndex !== getIndexes.newIndex) {
+ // reorder m_pChildren.array
+ this._children.splice(getIndexes.oldIndex, 1)
+ this._children.splice(getIndexes.newIndex, 0, child);
+
+ // save old altasIndex
+ var oldAtlasIndex = child.getAtlasIndex();
+
+ // update atlas index
+ this._updateAllAtlasIndexes();
+
+ // Find new AtlasIndex
+ var newAtlasIndex = 0;
+ var locChildren = this._children;
+ for (var i = 0; i < locChildren.length; i++) {
+ var pNode = locChildren[i];
+ if (pNode === child) {
+ newAtlasIndex = child.getAtlasIndex();
+ break;
+ }
+ }
+
+ // reorder textureAtlas quads
+ this.textureAtlas.moveQuadsFromIndex(oldAtlasIndex, child.getTotalParticles(), newAtlasIndex);
+
+ child.updateWithNoTime();
+ }
+ }
+ child._setLocalZOrder(zOrder);
+ },
+
+ /**
+ * @param {Number} index
+ * @param {Boolean} doCleanup
+ */
+ removeChildAtIndex:function (index, doCleanup) {
+ this.removeChild(this._children[i], doCleanup);
+ },
+
+ /**
+ * @param {Boolean} doCleanup
+ */
+ removeAllChildren:function (doCleanup) {
+ var locChildren = this._children;
+ for (var i = 0; i < locChildren.length; i++) {
+ locChildren[i].setBatchNode(null);
+ }
+ cc.Node.prototype.removeAllChildren.call(this, doCleanup);
+ this.textureAtlas.removeAllQuads();
+ },
+
+ /**
+ * disables a particle by inserting a 0'd quad into the texture atlas
+ * @param {Number} particleIndex
+ */
+ disableParticle:function (particleIndex) {
+ var quad = this.textureAtlas.quads[particleIndex];
+ quad.br.vertices.x = quad.br.vertices.y = quad.tr.vertices.x = quad.tr.vertices.y =
+ quad.tl.vertices.x = quad.tl.vertices.y = quad.bl.vertices.x = quad.bl.vertices.y = 0.0;
+ this.textureAtlas._setDirty(true);
+ },
+
+ /**
+ * returns the used texture
+ * @return {cc.Texture2D}
+ */
+ getTexture:function () {
+ return this.textureAtlas.texture;
+ },
+
+ /**
+ * sets a new texture. it will be retained
+ * @param {cc.Texture2D} texture
+ */
+ setTexture:function (texture) {
+ this.textureAtlas.texture = texture;
+
+ // If the new texture has No premultiplied alpha, AND the blendFunc hasn't been changed, then update it
+ var locBlendFunc = this._blendFunc;
+ if (texture && !texture.hasPremultipliedAlpha() && ( locBlendFunc.src === cc.BLEND_SRC && locBlendFunc.dst === cc.BLEND_DST )) {
+ locBlendFunc.src = cc.SRC_ALPHA;
+ locBlendFunc.dst = cc.ONE_MINUS_SRC_ALPHA;
+ }
+ },
+
+ /**
+ * set the blending function used for the texture
+ * @param {Number|Object} src
+ * @param {Number} dst
+ */
+ setBlendFunc:function (src, dst) {
+ if (dst === undefined){
+ this._blendFunc.src = src.src;
+ this._blendFunc.dst = src.dst;
+ } else{
+ this._blendFunc.src = src;
+ this._blendFunc.src = dst;
+ }
+ },
+
+ /**
+ * returns the blending function used for the texture
+ * @return {cc.BlendFunc}
+ */
+ getBlendFunc:function () {
+ return new cc.BlendFunc(this._blendFunc.src, this._blendFunc.dst);
+ },
+
+ _updateAllAtlasIndexes:function () {
+ var index = 0;
+ var locChildren = this._children;
+ for (var i = 0; i < locChildren.length; i++) {
+ var child = locChildren[i];
+ child.setAtlasIndex(index);
+ index += child.getTotalParticles();
+ }
+ },
+
+ _increaseAtlasCapacityTo:function (quantity) {
+ cc.log("cocos2d: cc.ParticleBatchNode: resizing TextureAtlas capacity from [" + this.textureAtlas.getCapacity()
+ + "] to [" + quantity + "].");
+
+ if (!this.textureAtlas.resizeCapacity(quantity)) {
+ // serious problems
+ cc.log("cc.ParticleBatchNode._increaseAtlasCapacityTo() : WARNING: Not enough memory to resize the atlas");
+ }
+ },
+
+ _searchNewPositionInChildrenForZ:function (z) {
+ var locChildren = this._children;
+ var count = locChildren.length;
+ for (var i = 0; i < count; i++) {
+ if (locChildren[i].zIndex > z)
+ return i;
+ }
+ return count;
+ },
+
+ _getCurrentIndex:function (child, z) {
+ var foundCurrentIdx = false;
+ var foundNewIdx = false;
+
+ var newIndex = 0;
+ var oldIndex = 0;
+
+ var minusOne = 0, locChildren = this._children;
+ var count = locChildren.length;
+ for (var i = 0; i < count; i++) {
+ var pNode = locChildren[i];
+ // new index
+ if (pNode.zIndex > z && !foundNewIdx) {
+ newIndex = i;
+ foundNewIdx = true;
+
+ if (foundCurrentIdx && foundNewIdx)
+ break;
+ }
+ // current index
+ if (child === pNode) {
+ oldIndex = i;
+ foundCurrentIdx = true;
+ if (!foundNewIdx)
+ minusOne = -1;
+ if (foundCurrentIdx && foundNewIdx)
+ break;
+ }
+ }
+ if (!foundNewIdx)
+ newIndex = count;
+ newIndex += minusOne;
+ return {newIndex:newIndex, oldIndex:oldIndex};
+ },
+
+ //
+ //
+ // don't use lazy sorting, reordering the particle systems quads afterwards would be too complex
+ // XXX research whether lazy sorting + freeing current quads and calloc a new block with size of capacity would be faster
+ // XXX or possibly using vertexZ for reordering, that would be fastest
+ // this helper is almost equivalent to CCNode's addChild, but doesn't make use of the lazy sorting
+ //
+ // @param {cc.ParticleSystem} child
+ // @param {Number} z
+ // @param {Number} aTag
+ // @return {Number}
+ // @private
+ //
+ _addChildHelper:function (child, z, aTag) {
+ if(!child)
+ throw new Error("cc.ParticleBatchNode._addChildHelper(): child should be non-null");
+ if(child.parent){
+ cc.log("cc.ParticleBatchNode._addChildHelper(): child already added. It can't be added again");
+ return null;
+ }
+
+
+ if (!this._children)
+ this._children = [];
+
+ //don't use a lazy insert
+ var pos = this._searchNewPositionInChildrenForZ(z);
+
+ this._children.splice(pos, 0, child);
+ child.tag = aTag;
+ child._setLocalZOrder(z);
+ child.parent = this;
+ if (this._running) {
+ child.onEnter();
+ child.onEnterTransitionDidFinish();
+ }
+ return pos;
+ },
+
+ _updateBlendFunc:function () {
+ if (!this.textureAtlas.texture.hasPremultipliedAlpha()) {
+ this._blendFunc.src = cc.SRC_ALPHA;
+ this._blendFunc.dst = cc.ONE_MINUS_SRC_ALPHA;
+ }
+ },
+
+ /**
+ * return the texture atlas used for drawing the quads
+ * @return {cc.TextureAtlas}
+ */
+ getTextureAtlas:function () {
+ return this.textureAtlas;
+ },
+
+ /**
+ * set the texture atlas used for drawing the quads
+ * @param {cc.TextureAtlas} textureAtlas
+ */
+ setTextureAtlas:function (textureAtlas) {
+ this.textureAtlas = textureAtlas;
+ }
+});
+
+var _p = cc.ParticleBatchNode.prototype;
+
+// Extended properties
+/** @expose */
+_p.texture;
+cc.defineGetterSetter(_p, "texture", _p.getTexture, _p.setTexture);
+
+
+/**
+ * initializes the particle system with the name of a file on disk (for a list of supported formats look at the cc.Texture2D class), a capacity of particles
+ * @deprecated since v3.0 please use new cc.ParticleBatchNode(filename, capacity) instead.
+ * @param {String|cc.Texture2D} fileImage
+ * @param {Number} capacity
+ * @return {cc.ParticleBatchNode}
+ */
+cc.ParticleBatchNode.create = function (fileImage, capacity) {
+ return new cc.ParticleBatchNode(fileImage, capacity);
+};
diff --git a/cocos2d/particle/CCParticleBatchNodeCanvasRenderCmd.js b/cocos2d/particle/CCParticleBatchNodeCanvasRenderCmd.js
new file mode 100644
index 0000000000..36da185ecb
--- /dev/null
+++ b/cocos2d/particle/CCParticleBatchNodeCanvasRenderCmd.js
@@ -0,0 +1,38 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+(function(){
+ /**
+ * cc.ParticleBatchNode's rendering objects of Canvas
+ */
+ cc.ParticleBatchNode.CanvasRenderCmd = function(renderable){
+ cc.Node.CanvasRenderCmd.call(this, renderable);
+ this._needDraw = false;
+ };
+
+ var proto = cc.ParticleBatchNode.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
+ proto.constructor = cc.ParticleBatchNode.CanvasRenderCmd;
+
+ proto._initWithTexture = function(){};
+})();
diff --git a/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js b/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js
new file mode 100644
index 0000000000..16da24b496
--- /dev/null
+++ b/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js
@@ -0,0 +1,74 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+(function(){
+ /**
+ * cc.ParticleBatchNode's rendering objects of WebGL
+ */
+ cc.ParticleBatchNode.WebGLRenderCmd = function(renderable){
+ cc.Node.WebGLRenderCmd.call(this, renderable);
+ this._needDraw = true;
+ };
+
+ var proto = cc.ParticleBatchNode.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
+ proto.constructor = cc.ParticleBatchNode.WebGLRenderCmd;
+
+ proto.rendering = function (ctx) {
+ var _t = this._node;
+ if (_t.textureAtlas.totalQuads === 0)
+ return;
+
+ this._shaderProgram.use();
+ this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix);
+ cc.glBlendFuncForParticle(_t._blendFunc.src, _t._blendFunc.dst);
+ _t.textureAtlas.drawQuads();
+ };
+
+ proto._initWithTexture = function(){
+ this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURECOLOR);
+ };
+
+ proto.visit = function(parentCmd){
+ var node = this._node;
+ // CAREFUL:
+ // This visit is almost identical to cc.Node#visit
+ // with the exception that it doesn't call visit on it's children
+ //
+ // The alternative is to have a void cc.Sprite#visit, but
+ // although this is less mantainable, is faster
+ //
+ if (!node._visible)
+ return;
+
+ var currentStack = cc.current_stack;
+ currentStack.stack.push(currentStack.top);
+ this._syncStatus(parentCmd);
+ currentStack.top = this._stackMatrix;
+ //this.draw(ctx);
+ cc.renderer.pushRenderCommand(this);
+
+ this._dirtyFlag = 0;
+ cc.kmGLPopMatrix();
+ };
+})();
\ No newline at end of file
diff --git a/cocos2d/particle/CCParticleExamples.js b/cocos2d/particle/CCParticleExamples.js
new file mode 100644
index 0000000000..49d603e568
--- /dev/null
+++ b/cocos2d/particle/CCParticleExamples.js
@@ -0,0 +1,1006 @@
+/****************************************************************************
+ 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 fire particle system
+ * @class
+ * @extends cc.ParticleSystem
+ *
+ * @example
+ * var emitter = new cc.ParticleFire();
+ */
+cc.ParticleFire = cc.ParticleSystem.extend(/** @lends cc.ParticleFire# */{
+ /**
+ * The cc.ParticleFire's constructor.
+ * This function will automatically be invoked when you create a node using new construction: "var node = new cc.ParticleFire()".
+ * Override it to extend its behavior, remember to call "this._super()" in the extended "ctor" function.
+ */
+ ctor:function () {
+ cc.ParticleSystem.prototype.ctor.call(this, (cc._renderType === cc.game.RENDER_TYPE_WEBGL) ? 300 : 150);
+ },
+
+ /**
+ * initialize a fire particle system with number Of Particles
+ * @param {Number} numberOfParticles
+ * @return {Boolean}
+ */
+ initWithTotalParticles:function (numberOfParticles) {
+ if (cc.ParticleSystem.prototype.initWithTotalParticles.call(this, numberOfParticles)) {
+ // duration
+ this.setDuration(cc.ParticleSystem.DURATION_INFINITY);
+
+ // Gravity Mode
+ this.setEmitterMode(cc.ParticleSystem.Mode.GRAVITY);
+
+
+ // Gravity Mode: gravity
+ this.setGravity(cc.p(0, 0));
+
+ // Gravity Mode: radial acceleration
+ this.setRadialAccel(0);
+ this.setRadialAccelVar(0);
+
+ // Gravity Mode: speed of particles
+ this.setSpeed(60);
+ this.setSpeedVar(20);
+
+ // starting angle
+ this.setAngle(90);
+ this.setAngleVar(10);
+
+ // emitter position
+ var winSize = cc.director.getWinSize();
+ this.setPosition(winSize.width / 2, 60);
+ this.setPosVar(cc.p(40, 20));
+
+ // life of particles
+ this.setLife(3);
+ this.setLifeVar(0.25);
+
+
+ // size, in pixels
+ this.setStartSize(54.0);
+ this.setStartSizeVar(10.0);
+ this.setEndSize(cc.ParticleSystem.START_SIZE_EQUAL_TO_END_SIZE);
+
+ // emits per frame
+ this.setEmissionRate(this.getTotalParticles() / this.getLife());
+
+ // color of particles
+ this.setStartColor(cc.color(194,64,31,255));
+ this.setStartColorVar(cc.color(0,0,0,0));
+ this.setEndColor(cc.color(0,0,0,255));
+ this.setEndColorVar(cc.color(0,0,0,0));
+
+ // additive
+ this.setBlendAdditive(true);
+ return true;
+ }
+ return false;
+ }
+});
+
+/**
+ * Create a fire particle system
+ * @deprecated since v3.0 please use new cc.ParticleFire() instead
+ * @return {cc.ParticleFire}
+ */
+cc.ParticleFire.create = function () {
+ return new cc.ParticleFire();
+};
+
+/**
+ * A fireworks particle system
+ * @class
+ * @extends cc.ParticleSystem
+ *
+ * @example
+ * var emitter = new cc.ParticleFireworks();
+ */
+cc.ParticleFireworks = cc.ParticleSystem.extend(/** @lends cc.ParticleFireworks# */{
+ /**
+ * The cc.ParticleFireworks's constructor.
+ * This function will automatically be invoked when you create a node using new construction: "var node = new cc.ParticleFireworks()".
+ * Override it to extend its behavior, remember to call "this._super()" in the extended "ctor" function.
+ */
+ ctor:function () {
+ cc.ParticleSystem.prototype.ctor.call(this, (cc._renderType === cc.game.RENDER_TYPE_WEBGL) ? 1500 : 150);
+ },
+
+ /**
+ * initialize a fireworks particle system with number Of Particles
+ * @param {Number} numberOfParticles
+ * @return {Boolean}
+ */
+ initWithTotalParticles:function (numberOfParticles) {
+ if (cc.ParticleSystem.prototype.initWithTotalParticles.call(this, numberOfParticles)) {
+ // duration
+ this.setDuration(cc.ParticleSystem.DURATION_INFINITY);
+
+ // Gravity Mode
+ this.setEmitterMode(cc.ParticleSystem.Mode.GRAVITY);
+
+ // Gravity Mode: gravity
+ this.setGravity(cc.p(0, -90));
+
+ // Gravity Mode: radial
+ this.setRadialAccel(0);
+ this.setRadialAccelVar(0);
+
+ // Gravity Mode: speed of particles
+ this.setSpeed(180);
+ this.setSpeedVar(50);
+
+ // emitter position
+ var winSize = cc.director.getWinSize();
+ this.setPosition(winSize.width / 2, winSize.height / 2);
+
+ // angle
+ this.setAngle(90);
+ this.setAngleVar(20);
+
+ // life of particles
+ this.setLife(3.5);
+ this.setLifeVar(1);
+
+ // emits per frame
+ this.setEmissionRate(this.getTotalParticles() / this.getLife());
+
+ // color of particles
+ this.setStartColor(cc.color(128,128,128,255));
+ this.setStartColorVar(cc.color(128,128,128,255));
+ this.setEndColor(cc.color(26,26,26,51));
+ this.setEndColorVar(cc.color(26,26,26,51));
+
+ // size, in pixels
+ this.setStartSize(8.0);
+ this.setStartSizeVar(2.0);
+ this.setEndSize(cc.ParticleSystem.START_SIZE_EQUAL_TO_END_SIZE);
+
+ // additive
+ this.setBlendAdditive(false);
+ return true;
+ }
+ return false;
+ }
+});
+
+/**
+ * Create a fireworks particle system
+ * @deprecated since v3.0 please use new cc.ParticleFireworks() instead.
+ * @return {cc.ParticleFireworks}
+ */
+cc.ParticleFireworks.create = function () {
+ return new cc.ParticleFireworks();
+};
+
+/**
+ * A sun particle system
+ * @class
+ * @extends cc.ParticleSystem
+ *
+ * @example
+ * var emitter = new cc.ParticleSun();
+ */
+cc.ParticleSun = cc.ParticleSystem.extend(/** @lends cc.ParticleSun# */{
+ /**
+ * The cc.ParticleSun's constructor.
+ * This function will automatically be invoked when you create a node using new construction: "var node = new cc.ParticleSun()".
+ * Override it to extend its behavior, remember to call "this._super()" in the extended "ctor" function.
+ */
+ ctor:function () {
+ cc.ParticleSystem.prototype.ctor.call(this, (cc._renderType === cc.game.RENDER_TYPE_WEBGL) ? 350 : 150);
+ },
+
+ /**
+ * initialize a sun particle system with number Of Particles
+ * @param {Number} numberOfParticles
+ * @return {Boolean}
+ */
+ initWithTotalParticles:function (numberOfParticles) {
+ if (cc.ParticleSystem.prototype.initWithTotalParticles.call(this, numberOfParticles)) {
+ // additive
+ this.setBlendAdditive(true);
+
+ // duration
+ this.setDuration(cc.ParticleSystem.DURATION_INFINITY);
+
+ // Gravity Mode
+ this.setEmitterMode(cc.ParticleSystem.Mode.GRAVITY);
+
+ // Gravity Mode: gravity
+ this.setGravity(cc.p(0, 0));
+
+ // Gravity mode: radial acceleration
+ this.setRadialAccel(0);
+ this.setRadialAccelVar(0);
+
+ // Gravity mode: speed of particles
+ this.setSpeed(20);
+ this.setSpeedVar(5);
+
+ // angle
+ this.setAngle(90);
+ this.setAngleVar(360);
+
+ // emitter position
+ var winSize = cc.director.getWinSize();
+ this.setPosition(winSize.width / 2, winSize.height / 2);
+ this.setPosVar(cc.p(0,0));
+
+ // life of particles
+ this.setLife(1);
+ this.setLifeVar(0.5);
+
+ // size, in pixels
+ this.setStartSize(30.0);
+ this.setStartSizeVar(10.0);
+ this.setEndSize(cc.ParticleSystem.START_SIZE_EQUAL_TO_END_SIZE);
+
+ // emits per seconds
+ this.setEmissionRate(this.getTotalParticles() / this.getLife());
+
+ // color of particles
+ this.setStartColor(cc.color(194, 64, 31, 255));
+ this.setStartColorVar(cc.color(0, 0, 0, 0));
+ this.setEndColor(cc.color(0, 0, 0, 255));
+ this.setEndColorVar(cc.color(0, 0, 0, 0));
+
+ return true;
+ }
+ return false;
+ }
+});
+
+/**
+ * Create a sun particle system
+ * @deprecated since v3.0 please use new cc.ParticleSun() instead.
+ * @return {cc.ParticleSun}
+ */
+cc.ParticleSun.create = function () {
+ return new cc.ParticleSun();
+};
+
+//! @brief A particle system
+/**
+ * A galaxy particle system
+ * @class
+ * @extends cc.ParticleSystem
+ *
+ * @example
+ * var emitter = new cc.ParticleGalaxy();
+ */
+cc.ParticleGalaxy = cc.ParticleSystem.extend(/** @lends cc.ParticleGalaxy# */{
+ /**
+ * The cc.ParticleGalaxy's constructor.
+ * This function will automatically be invoked when you create a node using new construction: "var node = new cc.ParticleGalaxy()".
+ * Override it to extend its behavior, remember to call "this._super()" in the extended "ctor" function.
+ */
+ ctor:function () {
+ cc.ParticleSystem.prototype.ctor.call(this, (cc._renderType === cc.game.RENDER_TYPE_WEBGL) ? 200 : 100);
+ },
+
+ /**
+ * initialize a galaxy particle system with number Of Particles
+ * @param {Number} numberOfParticles
+ * @return {Boolean}
+ */
+ initWithTotalParticles:function (numberOfParticles) {
+ if (cc.ParticleSystem.prototype.initWithTotalParticles.call(this, numberOfParticles)) {
+ // duration
+ this.setDuration(cc.ParticleSystem.DURATION_INFINITY);
+
+ // Gravity Mode
+ this.setEmitterMode(cc.ParticleSystem.Mode.GRAVITY);
+
+ // Gravity Mode: gravity
+ this.setGravity(cc.p(0, 0));
+
+ // Gravity Mode: speed of particles
+ this.setSpeed(60);
+ this.setSpeedVar(10);
+
+ // Gravity Mode: radial
+ this.setRadialAccel(-80);
+ this.setRadialAccelVar(0);
+
+ // Gravity Mode: tangential
+ this.setTangentialAccel(80);
+ this.setTangentialAccelVar(0);
+
+ // angle
+ this.setAngle(90);
+ this.setAngleVar(360);
+
+ // emitter position
+ var winSize = cc.director.getWinSize();
+ this.setPosition(winSize.width / 2, winSize.height / 2);
+ this.setPosVar(cc.p(0,0));
+
+ // life of particles
+ this.setLife(4);
+ this.setLifeVar(1);
+
+ // size, in pixels
+ this.setStartSize(37.0);
+ this.setStartSizeVar(10.0);
+ this.setEndSize(cc.ParticleSystem.START_SIZE_EQUAL_TO_END_SIZE);
+
+ // emits per second
+ this.setEmissionRate(this.getTotalParticles() / this.getLife());
+
+ // color of particles
+ this.setStartColor(cc.color(31, 64, 194, 255));
+ this.setStartColorVar(cc.color(0, 0, 0, 0));
+ this.setEndColor(cc.color(0, 0, 0, 255));
+ this.setEndColorVar(cc.color(0, 0, 0, 0));
+
+ // additive
+ this.setBlendAdditive(true);
+ return true;
+ }
+ return false;
+ }
+});
+/**
+ * Create a galaxy particle system
+ * @deprecated since v3.0 please use new cc.OarticleGalaxy() instead.
+ * @return {cc.ParticleGalaxy}
+ */
+cc.ParticleGalaxy.create = function () {
+ return new cc.ParticleGalaxy();
+};
+
+/**
+ * A flower particle system
+ * @class
+ * @extends cc.ParticleSystem
+ *
+ * @example
+ * var emitter = new cc.ParticleFlower();
+ */
+cc.ParticleFlower = cc.ParticleSystem.extend(/** @lends cc.ParticleFlower# */{
+ /**
+ * The cc.ParticleFlower's constructor.
+ * This function will automatically be invoked when you create a node using new construction: "var node = new cc.ParticleFlower()".
+ * Override it to extend its behavior, remember to call "this._super()" in the extended "ctor" function.
+ */
+ ctor : function () {
+ cc.ParticleSystem.prototype.ctor.call(this, (cc._renderType === cc.game.RENDER_TYPE_WEBGL) ? 250 : 100);
+ },
+
+ /**
+ * initialize a flower particle system with number Of Particles
+ * @param {Number} numberOfParticles
+ * @return {Boolean}
+ */
+ initWithTotalParticles:function (numberOfParticles) {
+ if (cc.ParticleSystem.prototype.initWithTotalParticles.call(this, numberOfParticles)) {
+ // duration
+ this.setDuration(cc.ParticleSystem.DURATION_INFINITY);
+
+ // Gravity Mode
+ this.setEmitterMode(cc.ParticleSystem.Mode.GRAVITY);
+
+ // Gravity Mode: gravity
+ this.setGravity(cc.p(0, 0));
+
+ // Gravity Mode: speed of particles
+ this.setSpeed(80);
+ this.setSpeedVar(10);
+
+ // Gravity Mode: radial
+ this.setRadialAccel(-60);
+ this.setRadialAccelVar(0);
+
+ // Gravity Mode: tangential
+ this.setTangentialAccel(15);
+ this.setTangentialAccelVar(0);
+
+ // angle
+ this.setAngle(90);
+ this.setAngleVar(360);
+
+ // emitter position
+ var winSize = cc.director.getWinSize();
+ this.setPosition(winSize.width / 2, winSize.height / 2);
+ this.setPosVar(cc.p(0,0));
+
+ // life of particles
+ this.setLife(4);
+ this.setLifeVar(1);
+
+ // size, in pixels
+ this.setStartSize(30.0);
+ this.setStartSizeVar(10.0);
+ this.setEndSize(cc.ParticleSystem.START_SIZE_EQUAL_TO_END_SIZE);
+
+ // emits per second
+ this.setEmissionRate(this.getTotalParticles() / this.getLife());
+
+ // color of particles
+ this.setStartColor(cc.color(128, 128, 128, 255));
+ this.setStartColorVar(cc.color(128, 128, 128, 128));
+ this.setEndColor(cc.color(0, 0, 0, 255));
+ this.setEndColorVar(cc.color(0, 0, 0, 0));
+
+ // additive
+ this.setBlendAdditive(true);
+ return true;
+ }
+ return false;
+ }
+});
+
+/**
+ * Create a flower particle system
+ * @deprecated since v3.0 please use new cc.ParticleFlower() instead.
+ * @return {cc.ParticleFlower}
+ */
+cc.ParticleFlower.create = function () {
+ return new cc.ParticleFlower();
+};
+
+//! @brief A meteor particle system
+/**
+ * A meteor particle system
+ * @class
+ * @extends cc.ParticleSystem
+ *
+ * @example
+ * var emitter = new cc.ParticleMeteor();
+ */
+cc.ParticleMeteor = cc.ParticleSystem.extend(/** @lends cc.ParticleMeteor# */{
+ /**
+ * The cc.ParticleMeteor's constructor.
+ * This function will automatically be invoked when you create a node using new construction: "var node = new cc.ParticleMeteor()".
+ * Override it to extend its behavior, remember to call "this._super()" in the extended "ctor" function.
+ */
+ ctor:function () {
+ cc.ParticleSystem.prototype.ctor.call(this, (cc._renderType === cc.game.RENDER_TYPE_WEBGL) ? 150 : 100);
+ },
+
+ /**
+ * initialize a meteor particle system with number Of Particles
+ * @param {Number} numberOfParticles
+ * @return {Boolean}
+ */
+ initWithTotalParticles:function (numberOfParticles) {
+ if (cc.ParticleSystem.prototype.initWithTotalParticles.call(this, numberOfParticles)) {
+ // duration
+ this.setDuration(cc.ParticleSystem.DURATION_INFINITY);
+
+ // Gravity Mode
+ this.setEmitterMode(cc.ParticleSystem.Mode.GRAVITY);
+
+ // Gravity Mode: gravity
+ this.setGravity(cc.p(-200, 200));
+
+ // Gravity Mode: speed of particles
+ this.setSpeed(15);
+ this.setSpeedVar(5);
+
+ // Gravity Mode: radial
+ this.setRadialAccel(0);
+ this.setRadialAccelVar(0);
+
+ // Gravity Mode: tangential
+ this.setTangentialAccel(0);
+ this.setTangentialAccelVar(0);
+
+ // angle
+ this.setAngle(90);
+ this.setAngleVar(360);
+
+ // emitter position
+ var winSize = cc.director.getWinSize();
+ this.setPosition(winSize.width / 2, winSize.height / 2);
+ this.setPosVar(cc.p(0,0));
+
+ // life of particles
+ this.setLife(2);
+ this.setLifeVar(1);
+
+ // size, in pixels
+ this.setStartSize(60.0);
+ this.setStartSizeVar(10.0);
+ this.setEndSize(cc.ParticleSystem.START_SIZE_EQUAL_TO_END_SIZE);
+
+ // emits per second
+ this.setEmissionRate(this.getTotalParticles() / this.getLife());
+
+ // color of particles
+ this.setStartColor(cc.color(51, 102, 179));
+ this.setStartColorVar(cc.color(0, 0, 51, 26));
+ this.setEndColor(cc.color(0, 0, 0, 255));
+ this.setEndColorVar(cc.color(0, 0, 0, 0));
+
+ // additive
+ this.setBlendAdditive(true);
+ return true;
+ }
+ return false;
+ }
+});
+
+/**
+ * Create a meteor particle system
+ * @deprecated since v3.0 please use new cc.ParticleMeteor() instead.
+ * @return {cc.ParticleMeteor}
+ */
+cc.ParticleMeteor.create = function () {
+ return new cc.ParticleMeteor();
+};
+
+/**
+ * A spiral particle system
+ * @class
+ * @extends cc.ParticleSystem
+ *
+ * @example
+ * var emitter = new cc.ParticleSpiral();
+ */
+cc.ParticleSpiral = cc.ParticleSystem.extend(/** @lends cc.ParticleSpiral# */{
+
+ /**
+ * The cc.ParticleSpiral's constructor.
+ * This function will automatically be invoked when you create a node using new construction: "var node = new cc.ParticleSpiral()".
+ * Override it to extend its behavior, remember to call "this._super()" in the extended "ctor" function.
+ */
+ ctor:function() {
+ cc.ParticleSystem.prototype.ctor.call(this,(cc._renderType === cc.game.RENDER_TYPE_WEBGL) ? 500 : 100);
+ },
+
+ /**
+ * initialize a spiral particle system with number Of Particles
+ * @param {Number} numberOfParticles
+ * @return {Boolean}
+ */
+ initWithTotalParticles:function (numberOfParticles) {
+ if (cc.ParticleSystem.prototype.initWithTotalParticles.call(this, numberOfParticles)) {
+ // duration
+ this.setDuration(cc.ParticleSystem.DURATION_INFINITY);
+
+ // Gravity Mode
+ this.setEmitterMode(cc.ParticleSystem.Mode.GRAVITY);
+
+ // Gravity Mode: gravity
+ this.setGravity(cc.p(0, 0));
+
+ // Gravity Mode: speed of particles
+ this.setSpeed(150);
+ this.setSpeedVar(0);
+
+ // Gravity Mode: radial
+ this.setRadialAccel(-380);
+ this.setRadialAccelVar(0);
+
+ // Gravity Mode: tangential
+ this.setTangentialAccel(45);
+ this.setTangentialAccelVar(0);
+
+ // angle
+ this.setAngle(90);
+ this.setAngleVar(0);
+
+ // emitter position
+ var winSize = cc.director.getWinSize();
+ this.setPosition(winSize.width / 2, winSize.height / 2);
+ this.setPosVar(cc.p(0,0));
+
+ // life of particles
+ this.setLife(12);
+ this.setLifeVar(0);
+
+ // size, in pixels
+ this.setStartSize(20.0);
+ this.setStartSizeVar(0.0);
+ this.setEndSize(cc.ParticleSystem.START_SIZE_EQUAL_TO_END_SIZE);
+
+ // emits per second
+ this.setEmissionRate(this.getTotalParticles() / this.getLife());
+
+ // color of particles
+ this.setStartColor(cc.color(128,128,128,255));
+ this.setStartColorVar(cc.color(128,128,128,0));
+ this.setEndColor(cc.color(128,128,128,255));
+ this.setEndColorVar(cc.color(128,128,128,0));
+
+ // additive
+ this.setBlendAdditive(false);
+ return true;
+ }
+ return false;
+ }
+});
+
+/**
+ * Create a spiral particle system
+ * @deprecated since v3.0 please use new cc.ParticleSpiral() instead.
+ * @return {cc.ParticleSpiral}
+ */
+cc.ParticleSpiral.create = function () {
+ return new cc.ParticleSpiral();
+};
+
+/**
+ * An explosion particle system
+ * @class
+ * @extends cc.ParticleSystem
+ *
+ * @example
+ * var emitter = new cc.ParticleExplosion();
+ */
+cc.ParticleExplosion = cc.ParticleSystem.extend(/** @lends cc.ParticleExplosion# */{
+ /**
+ * The cc.ParticleExplosion's constructor.
+ * This function will automatically be invoked when you create a node using new construction: "var node = new cc.ParticleExplosion()".
+ * Override it to extend its behavior, remember to call "this._super()" in the extended "ctor" function.
+ */
+ ctor:function () {
+ cc.ParticleSystem.prototype.ctor.call(this, (cc._renderType === cc.game.RENDER_TYPE_WEBGL) ? 700 : 300);
+ },
+
+ /**
+ * initialize an explosion particle system with number Of Particles
+ * @param {Number} numberOfParticles
+ * @return {Boolean}
+ */
+ initWithTotalParticles:function (numberOfParticles) {
+ if (cc.ParticleSystem.prototype.initWithTotalParticles.call(this, numberOfParticles)) {
+ // duration
+ this.setDuration(0.1);
+
+ this.setEmitterMode(cc.ParticleSystem.Mode.GRAVITY);
+
+ // Gravity Mode: gravity
+ this.setGravity(cc.p(0, 0));
+
+ // Gravity Mode: speed of particles
+ this.setSpeed(70);
+ this.setSpeedVar(40);
+
+ // Gravity Mode: radial
+ this.setRadialAccel(0);
+ this.setRadialAccelVar(0);
+
+ // Gravity Mode: tangential
+ this.setTangentialAccel(0);
+ this.setTangentialAccelVar(0);
+
+ // angle
+ this.setAngle(90);
+ this.setAngleVar(360);
+
+ // emitter position
+ var winSize = cc.director.getWinSize();
+ this.setPosition(winSize.width / 2, winSize.height / 2);
+ this.setPosVar(cc.p(0,0));
+
+ // life of particles
+ this.setLife(5.0);
+ this.setLifeVar(2);
+
+ // size, in pixels
+ this.setStartSize(15.0);
+ this.setStartSizeVar(10.0);
+ this.setEndSize(cc.ParticleSystem.START_SIZE_EQUAL_TO_END_SIZE);
+
+ // emits per second
+ this.setEmissionRate(this.getTotalParticles() / this.getDuration());
+
+ // color of particles
+ this.setStartColor(cc.color(179, 26, 51, 255));
+ this.setStartColorVar(cc.color(128, 128, 128, 0));
+ this.setEndColor(cc.color(128, 128, 128, 0));
+ this.setEndColorVar(cc.color(128, 128, 128, 0));
+
+ // additive
+ this.setBlendAdditive(false);
+ return true;
+ }
+ return false;
+ }
+});
+
+/**
+ * Create an explosion particle system
+ * @deprecated since v3.0 please use new cc.ParticleExplosion() instead.
+ * @return {cc.ParticleExplosion}
+ */
+cc.ParticleExplosion.create = function () {
+ return new cc.ParticleExplosion();
+};
+
+/**
+ * A smoke particle system
+ * @class
+ * @extends cc.ParticleSystem
+ *
+ * @example
+ * var emitter = new cc.ParticleSmoke();
+ */
+cc.ParticleSmoke = cc.ParticleSystem.extend(/** @lends cc.ParticleSmoke# */{
+
+ /**
+ * The cc.ParticleSmoke's constructor.
+ * This function will automatically be invoked when you create a node using new construction: "var node = new cc.ParticleSmoke()".
+ * Override it to extend its behavior, remember to call "this._super()" in the extended "ctor" function.
+ */
+ ctor:function () {
+ cc.ParticleSystem.prototype.ctor.call(this, (cc._renderType === cc.game.RENDER_TYPE_WEBGL) ? 200 : 100);
+ },
+
+ /**
+ * initialize a smoke particle system with number Of Particles
+ * @param {Number} numberOfParticles
+ * @return {Boolean}
+ */
+ initWithTotalParticles:function (numberOfParticles) {
+ if (cc.ParticleSystem.prototype.initWithTotalParticles.call(this, numberOfParticles)) {
+ // duration
+ this.setDuration(cc.ParticleSystem.DURATION_INFINITY);
+
+ // Emitter mode: Gravity Mode
+ this.setEmitterMode(cc.ParticleSystem.Mode.GRAVITY);
+
+ // Gravity Mode: gravity
+ this.setGravity(cc.p(0, 0));
+
+ // Gravity Mode: radial acceleration
+ this.setRadialAccel(0);
+ this.setRadialAccelVar(0);
+
+ // Gravity Mode: speed of particles
+ this.setSpeed(25);
+ this.setSpeedVar(10);
+
+ // angle
+ this.setAngle(90);
+ this.setAngleVar(5);
+
+ // emitter position
+ var winSize = cc.director.getWinSize();
+ this.setPosition(winSize.width / 2, 0);
+ this.setPosVar(cc.p(20, 0));
+
+ // life of particles
+ this.setLife(4);
+ this.setLifeVar(1);
+
+ // size, in pixels
+ this.setStartSize(60.0);
+ this.setStartSizeVar(10.0);
+ this.setEndSize(cc.ParticleSystem.START_SIZE_EQUAL_TO_END_SIZE);
+
+ // emits per frame
+ this.setEmissionRate(this.getTotalParticles() / this.getLife());
+
+ // color of particles
+ this.setStartColor(cc.color(204, 204, 204, 255));
+ this.setStartColorVar(cc.color(5, 5, 5, 0));
+ this.setEndColor(cc.color(0, 0, 0, 255));
+ this.setEndColorVar(cc.color(0, 0, 0, 0));
+
+ // additive
+ this.setBlendAdditive(false);
+ return true;
+ }
+ return false;
+ }
+});
+
+/**
+ * Create a smoke particle system
+ * @deprecated since v3.0 please use new cc.ParticleSmoke() instead.
+ * @return {cc.ParticleSmoke}
+ */
+cc.ParticleSmoke.create = function () {
+ return new cc.ParticleSmoke();
+};
+
+/**
+ * A snow particle system
+ * @class
+ * @extends cc.ParticleSystem
+ *
+ * @example
+ * var emitter = new cc.ParticleSnow();
+ */
+cc.ParticleSnow = cc.ParticleSystem.extend(/** @lends cc.ParticleSnow# */{
+
+ /**
+ * The cc.ParticleSnow's constructor.
+ * This function will automatically be invoked when you create a node using new construction: "var node = new cc.ParticleSnow()".
+ * Override it to extend its behavior, remember to call "this._super()" in the extended "ctor" function.
+ */
+ ctor:function () {
+ cc.ParticleSystem.prototype.ctor.call(this, (cc._renderType === cc.game.RENDER_TYPE_WEBGL) ? 700 : 250);
+ },
+
+ /**
+ * initialize a snow particle system with number Of Particles
+ * @param {Number} numberOfParticles
+ * @return {Boolean}
+ */
+ initWithTotalParticles:function (numberOfParticles) {
+ if (cc.ParticleSystem.prototype.initWithTotalParticles.call(this, numberOfParticles)) {
+ // duration
+ this.setDuration(cc.ParticleSystem.DURATION_INFINITY);
+
+ // set gravity mode.
+ this.setEmitterMode(cc.ParticleSystem.Mode.GRAVITY);
+
+ // Gravity Mode: gravity
+ this.setGravity(cc.p(0, -1));
+
+ // Gravity Mode: speed of particles
+ this.setSpeed(5);
+ this.setSpeedVar(1);
+
+ // Gravity Mode: radial
+ this.setRadialAccel(0);
+ this.setRadialAccelVar(1);
+
+ // Gravity mode: tangential
+ this.setTangentialAccel(0);
+ this.setTangentialAccelVar(1);
+
+ // emitter position
+ var winSize = cc.director.getWinSize();
+ this.setPosition(winSize.width / 2, winSize.height + 10);
+ this.setPosVar(cc.p(winSize.width / 2, 0));
+
+ // angle
+ this.setAngle(-90);
+ this.setAngleVar(5);
+
+ // life of particles
+ this.setLife(45);
+ this.setLifeVar(15);
+
+ // size, in pixels
+ this.setStartSize(10.0);
+ this.setStartSizeVar(5.0);
+ this.setEndSize(cc.ParticleSystem.START_SIZE_EQUAL_TO_END_SIZE);
+
+ // emits per second
+ this.setEmissionRate(10);
+
+ // color of particles
+ this.setStartColor(cc.color(255, 255, 255, 255));
+ this.setStartColorVar(cc.color(0, 0, 0, 0));
+ this.setEndColor(cc.color(255, 255, 255, 0));
+ this.setEndColorVar(cc.color(0, 0, 0, 0));
+
+ // additive
+ this.setBlendAdditive(false);
+ return true;
+ }
+ return false;
+ }
+});
+
+/**
+ * Create a snow particle system
+ * @deprecated since v3.0 please use new cc.ParticleSnow() instead.
+ * @return {cc.ParticleSnow}
+ */
+cc.ParticleSnow.create = function () {
+ return new cc.ParticleSnow();
+};
+
+//! @brief A rain particle system
+/**
+ * A rain particle system
+ * @class
+ * @extends cc.ParticleSystem
+ *
+ * @example
+ * var emitter = new cc.ParticleRain();
+ */
+cc.ParticleRain = cc.ParticleSystem.extend(/** @lends cc.ParticleRain# */{
+
+ /**
+ * The cc.ParticleRain's constructor.
+ * This function will automatically be invoked when you create a node using new construction: "var node = new cc.ParticleRain()".
+ * Override it to extend its behavior, remember to call "this._super()" in the extended "ctor" function.
+ */
+ ctor:function () {
+ cc.ParticleSystem.prototype.ctor.call(this, (cc._renderType === cc.game.RENDER_TYPE_WEBGL) ? 1000 : 300);
+ },
+
+ /**
+ * initialize a rain particle system with number Of Particles
+ * @param {Number} numberOfParticles
+ * @return {Boolean}
+ */
+ initWithTotalParticles:function (numberOfParticles) {
+ if (cc.ParticleSystem.prototype.initWithTotalParticles.call(this, numberOfParticles)) {
+ // duration
+ this.setDuration(cc.ParticleSystem.DURATION_INFINITY);
+
+ this.setEmitterMode(cc.ParticleSystem.Mode.GRAVITY);
+
+ // Gravity Mode: gravity
+ this.setGravity(cc.p(10, -10));
+
+ // Gravity Mode: radial
+ this.setRadialAccel(0);
+ this.setRadialAccelVar(1);
+
+ // Gravity Mode: tangential
+ this.setTangentialAccel(0);
+ this.setTangentialAccelVar(1);
+
+ // Gravity Mode: speed of particles
+ this.setSpeed(130);
+ this.setSpeedVar(30);
+
+ // angle
+ this.setAngle(-90);
+ this.setAngleVar(5);
+
+
+ // emitter position
+ var winSize = cc.director.getWinSize();
+ this.setPosition(winSize.width / 2, winSize.height);
+ this.setPosVar(cc.p(winSize.width / 2, 0));
+
+ // life of particles
+ this.setLife(4.5);
+ this.setLifeVar(0);
+
+ // size, in pixels
+ this.setStartSize(4.0);
+ this.setStartSizeVar(2.0);
+ this.setEndSize(cc.ParticleSystem.START_SIZE_EQUAL_TO_END_SIZE);
+
+ // emits per second
+ this.setEmissionRate(20);
+
+ // color of particles
+ this.setStartColor(cc.color(179, 204, 255, 255));
+ this.setStartColorVar(cc.color(0, 0, 0, 0));
+ this.setEndColor(cc.color(179, 204, 255, 128));
+ this.setEndColorVar(cc.color(0, 0, 0, 0));
+
+ // additive
+ this.setBlendAdditive(false);
+ return true;
+ }
+ return false;
+ }
+});
+
+/**
+ * Create a rain particle system
+ * @deprecated since v3.0 please use cc.ParticleRain() instead.
+ * @return {cc.ParticleRain}
+ */
+cc.ParticleRain.create = function () {
+ return new cc.ParticleRain();
+};
diff --git a/cocos2d/particle/CCParticleSystem.js b/cocos2d/particle/CCParticleSystem.js
new file mode 100644
index 0000000000..661fdaa22f
--- /dev/null
+++ b/cocos2d/particle/CCParticleSystem.js
@@ -0,0 +1,2241 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+// ideas taken from:
+// . The ocean spray in your face [Jeff Lander]
+// http://www.double.co.nz/dust/col0798.pdf
+// . Building an Advanced Particle System [John van der Burg]
+// http://www.gamasutra.com/features/20000623/vanderburg_01.htm
+// . LOVE game engine
+// http://love2d.org/
+//
+//
+// Radius mode support, from 71 squared
+// http://particledesigner.71squared.com/
+//
+// IMPORTANT: Particle Designer is supported by cocos2d, but
+// 'Radius Mode' in Particle Designer uses a fixed emit rate of 30 hz. Since that can't be guarateed in cocos2d,
+// cocos2d uses a another approach, but the results are almost identical.
+//
+
+
+// tCCPositionType
+// possible types of particle positions
+
+
+/**
+ * Structure that contains the values of each particle
+ * @Class
+ * @Construct
+ * @param {cc.Vec2} [pos=cc.p(0,0)] Position of particle
+ * @param {cc.Vec2} [startPos=cc.p(0,0)]
+ * @param {cc.Color} [color= cc.color(0, 0, 0, 255)]
+ * @param {cc.Color} [deltaColor=cc.color(0, 0, 0, 255)]
+ * @param {cc.Size} [size=0]
+ * @param {cc.Size} [deltaSize=0]
+ * @param {Number} [rotation=0]
+ * @param {Number} [deltaRotation=0]
+ * @param {Number} [timeToLive=0]
+ * @param {Number} [atlasIndex=0]
+ * @param {cc.Particle.ModeA} [modeA=]
+ * @param {cc.Particle.ModeA} [modeB=]
+ */
+cc.Particle = function (pos, startPos, color, deltaColor, size, deltaSize, rotation, deltaRotation, timeToLive, atlasIndex, modeA, modeB) {
+ this.pos = pos ? pos : cc.p(0,0);
+ this.startPos = startPos ? startPos : cc.p(0,0);
+ this.color = color ? color : {r:0, g: 0, b:0, a:255};
+ this.deltaColor = deltaColor ? deltaColor : {r:0, g: 0, b:0, a:255} ;
+ this.size = size || 0;
+ this.deltaSize = deltaSize || 0;
+ this.rotation = rotation || 0;
+ this.deltaRotation = deltaRotation || 0;
+ this.timeToLive = timeToLive || 0;
+ this.atlasIndex = atlasIndex || 0;
+ this.modeA = modeA ? modeA : new cc.Particle.ModeA();
+ this.modeB = modeB ? modeB : new cc.Particle.ModeB();
+ this.isChangeColor = false;
+ this.drawPos = cc.p(0, 0);
+};
+
+/**
+ * Mode A: gravity, direction, radial accel, tangential accel
+ * @Class
+ * @Construct
+ * @param {cc.Vec2} dir direction of particle
+ * @param {Number} radialAccel
+ * @param {Number} tangentialAccel
+ */
+cc.Particle.ModeA = function (dir, radialAccel, tangentialAccel) {
+ this.dir = dir ? dir : cc.p(0,0);
+ this.radialAccel = radialAccel || 0;
+ this.tangentialAccel = tangentialAccel || 0;
+};
+
+/**
+ * Mode B: radius mode
+ * @Class
+ * @Construct
+ * @param {Number} angle
+ * @param {Number} degreesPerSecond
+ * @param {Number} radius
+ * @param {Number} deltaRadius
+ */
+cc.Particle.ModeB = function (angle, degreesPerSecond, radius, deltaRadius) {
+ this.angle = angle || 0;
+ this.degreesPerSecond = degreesPerSecond || 0;
+ this.radius = radius || 0;
+ this.deltaRadius = deltaRadius || 0;
+};
+
+/**
+ * Array of Point instances used to optimize particle updates
+ */
+cc.Particle.TemporaryPoints = [
+ cc.p(),
+ cc.p(),
+ cc.p(),
+ cc.p()
+];
+
+/**
+ *
+ * Particle System base class.
+ * Attributes of a Particle System:
+ * - emmision rate of the particles
+ * - Gravity Mode (Mode A):
+ * - gravity
+ * - direction
+ * - speed +- variance
+ * - tangential acceleration +- variance
+ * - radial acceleration +- variance
+ * - Radius Mode (Mode B):
+ * - startRadius +- variance
+ * - endRadius +- variance
+ * - rotate +- variance
+ * - Properties common to all modes:
+ * - life +- life variance
+ * - start spin +- variance
+ * - end spin +- variance
+ * - start size +- variance
+ * - end size +- variance
+ * - start color +- variance
+ * - end color +- variance
+ * - life +- variance
+ * - blending function
+ * - texture
+ *
+ * cocos2d also supports particles generated by Particle Designer (http://particledesigner.71squared.com/).
+ * 'Radius Mode' in Particle Designer uses a fixed emit rate of 30 hz. Since that can't be guarateed in cocos2d,
+ * cocos2d uses a another approach, but the results are almost identical.
+ * cocos2d supports all the variables used by Particle Designer plus a bit more:
+ * - spinning particles (supported when using ParticleSystem)
+ * - tangential acceleration (Gravity mode)
+ * - radial acceleration (Gravity mode)
+ * - radius direction (Radius mode) (Particle Designer supports outwards to inwards direction only)
+ * It is possible to customize any of the above mentioned properties in runtime. Example:
+ *
+ * @class
+ * @extends cc.Node
+ *
+ * @property {Boolean} opacityModifyRGB - Indicate whether the alpha value modify color.
+ * @property {cc.SpriteBatchNode} batchNode - Weak reference to the sprite batch node.
+ * @property {Boolean} active - <@readonly> Indicate whether the particle system is activated.
+ * @property {Number} shapeType - ShapeType of ParticleSystem : cc.ParticleSystem.BALL_SHAPE | cc.ParticleSystem.STAR_SHAPE.
+ * @property {Number} atlasIndex - Index of system in batch node array.
+ * @property {Number} particleCount - Current quantity of particles that are being simulated.
+ * @property {Number} duration - How many seconds the emitter wil run. -1 means 'forever'
+ * @property {cc.Vec2} sourcePos - Source position of the emitter.
+ * @property {cc.Vec2} posVar - Variation of source position.
+ * @property {Number} life - Life of each particle setter.
+ * @property {Number} lifeVar - Variation of life.
+ * @property {Number} angle - Angle of each particle setter.
+ * @property {Number} angleVar - Variation of angle of each particle setter.
+ * @property {Number} startSize - Start size in pixels of each particle.
+ * @property {Number} startSizeVar - Variation of start size in pixels.
+ * @property {Number} endSize - End size in pixels of each particle.
+ * @property {Number} endSizeVar - Variation of end size in pixels.
+ * @property {Number} startSpin - Start angle of each particle.
+ * @property {Number} startSpinVar - Variation of start angle.
+ * @property {Number} endSpin - End angle of each particle.
+ * @property {Number} endSpinVar - Variation of end angle.
+ * @property {cc.Vec2} gravity - Gravity of the emitter.
+ * @property {cc.Vec2} speed - Speed of the emitter.
+ * @property {cc.Vec2} speedVar - Variation of the speed.
+ * @property {Number} tangentialAccel - Tangential acceleration of each particle. Only available in 'Gravity' mode.
+ * @property {Number} tangentialAccelVar - Variation of the tangential acceleration.
+ * @property {Number} tangentialAccel - Radial acceleration of each particle. Only available in 'Gravity' mode.
+ * @property {Number} tangentialAccelVar - Variation of the radial acceleration.
+ * @property {Boolean} rotationIsDir - Indicate whether the rotation of each particle equals to its direction. Only available in 'Gravity' mode.
+ * @property {Number} startRadius - Starting radius of the particles. Only available in 'Radius' mode.
+ * @property {Number} startRadiusVar - Variation of the starting radius.
+ * @property {Number} endRadius - Ending radius of the particles. Only available in 'Radius' mode.
+ * @property {Number} endRadiusVar - Variation of the ending radius.
+ * @property {Number} rotatePerS - Number of degress to rotate a particle around the source pos per second. Only available in 'Radius' mode.
+ * @property {Number} rotatePerSVar - Variation of the degress to rotate a particle around the source pos per second.
+ * @property {cc.Color} startColor - Start color of each particle.
+ * @property {cc.Color} startColorVar - Variation of the start color.
+ * @property {cc.Color} endColor - Ending color of each particle.
+ * @property {cc.Color} endColorVar - Variation of the end color.
+ * @property {Number} emissionRate - Emission rate of the particles.
+ * @property {cc.ParticleSystem.Mode} emitterMode - Emitter modes: cc.ParticleSystem.Mode.GRAVITY: uses gravity, speed, radial and tangential acceleration; cc.ParticleSystem.Mode.RADIUS: uses radius movement + rotation.
+ * @property {cc.ParticleSystem.Type} positionType - Particles movement type: cc.ParticleSystem.Type.FREE | cc.ParticleSystem.Type.GROUPED.
+ * @property {Number} totalParticles - Maximum particles of the system.
+ * @property {Boolean} autoRemoveOnFinish - Indicate whether the node will be auto-removed when it has no particles left.
+ * @property {cc.Texture2D} texture - Texture of Particle System.
+ *
+ * @example
+ * emitter.radialAccel = 15;
+ * emitter.startSpin = 0;
+ */
+cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
+ _className:"ParticleSystem",
+ //***********variables*************
+ _plistFile: "",
+ //! time elapsed since the start of the system (in seconds)
+ _elapsed: 0,
+ _dontTint: false,
+
+ // Different modes
+ //! Mode A:Gravity + Tangential Accel + Radial Accel
+ modeA: null,
+ //! Mode B: circular movement (gravity, radial accel and tangential accel don't are not used in this mode)
+ modeB: null,
+
+ //private POINTZERO for ParticleSystem
+ _pointZeroForParticle: cc.p(0, 0),
+
+ //! Array of particles
+ _particles: null,
+
+ // color modulate
+ // BOOL colorModulate;
+
+ //! How many particles can be emitted per second
+ _emitCounter: 0,
+ //! particle idx
+ _particleIdx: 0,
+
+ _batchNode: null,
+ atlasIndex: 0,
+
+ //true if scaled or rotated
+ _transformSystemDirty: false,
+ _allocatedParticles: 0,
+
+ _isActive: false,
+ particleCount: 0,
+ duration: 0,
+ _sourcePosition: null,
+ _posVar: null,
+ life: 0,
+ lifeVar: 0,
+ angle: 0,
+ angleVar: 0,
+ startSize: 0,
+ startSizeVar: 0,
+ endSize: 0,
+ endSizeVar: 0,
+ _startColor: null,
+ _startColorVar: null,
+ _endColor: null,
+ _endColorVar: null,
+ startSpin: 0,
+ startSpinVar: 0,
+ endSpin: 0,
+ endSpinVar: 0,
+ emissionRate: 0,
+ _totalParticles: 0,
+ _texture: null,
+ _blendFunc: null,
+ _opacityModifyRGB: false,
+ positionType: null,
+ autoRemoveOnFinish: false,
+ emitterMode: 0,
+
+ _textureLoaded: null,
+
+ /**
+ * return the string found by key in dict.
+ * This plist files can be create manually or with Particle Designer:
+ * http://particledesigner.71squared.com/
+ *
+ * Constructor of cc.ParticleSystem
+ * @param {String|Number} plistFile
+ */
+ ctor:function (plistFile) {
+ cc.Node.prototype.ctor.call(this);
+ this.emitterMode = cc.ParticleSystem.Mode.GRAVITY;
+ this.modeA = new cc.ParticleSystem.ModeA();
+ this.modeB = new cc.ParticleSystem.ModeB();
+ this._blendFunc = {src:cc.BLEND_SRC, dst:cc.BLEND_DST};
+
+ this._particles = [];
+ this._sourcePosition = cc.p(0, 0);
+ this._posVar = cc.p(0, 0);
+
+ this._startColor = cc.color(255, 255, 255, 255);
+ this._startColorVar = cc.color(255, 255, 255, 255);
+ this._endColor = cc.color(255, 255, 255, 255);
+ this._endColorVar = cc.color(255, 255, 255, 255);
+
+ this._plistFile = "";
+ this._elapsed = 0;
+ this._dontTint = false;
+ this._pointZeroForParticle = cc.p(0, 0);
+ this._emitCounter = 0;
+ this._particleIdx = 0;
+ this._batchNode = null;
+ this.atlasIndex = 0;
+
+ this._transformSystemDirty = false;
+ this._allocatedParticles = 0;
+ this._isActive = false;
+ this.particleCount = 0;
+ this.duration = 0;
+ this.life = 0;
+ this.lifeVar = 0;
+ this.angle = 0;
+ this.angleVar = 0;
+ this.startSize = 0;
+ this.startSizeVar = 0;
+ this.endSize = 0;
+ this.endSizeVar = 0;
+
+ this.startSpin = 0;
+ this.startSpinVar = 0;
+ this.endSpin = 0;
+ this.endSpinVar = 0;
+ this.emissionRate = 0;
+ this._totalParticles = 0;
+ this._texture = null;
+ this._opacityModifyRGB = false;
+ this.positionType = cc.ParticleSystem.Type.FREE;
+ this.autoRemoveOnFinish = false;
+
+ this._textureLoaded = true;
+
+ if (!plistFile || cc.js.isNumber(plistFile)) {
+ var ton = plistFile || 100;
+ this.setDrawMode(cc.ParticleSystem.TEXTURE_MODE);
+ this.initWithTotalParticles(ton);
+ } else if (cc.js.isString(plistFile)) {
+ this.initWithFile(plistFile);
+ } else if (cc.js.isObject(plistFile)) {
+ this.initWithDictionary(plistFile, "");
+ }
+ },
+
+ _createRenderCmd: function(){
+ if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ return new cc.ParticleSystem.CanvasRenderCmd(this);
+ else
+ return new cc.ParticleSystem.WebGLRenderCmd(this);
+ },
+
+ /**
+ * This is a hack function for performance, it's only available on Canvas mode.
+ * It's very expensive to change color on Canvas mode, so if set it to true, particle system will ignore the changing color operation.
+ * @param {boolean} ignore
+ */
+ ignoreColor: function(ignore){
+ this._dontTint = ignore;
+ },
+
+ /**
+ * initializes the texture with a rectangle measured Points
+ * pointRect should be in Texture coordinates, not pixel coordinates
+ *
+ * @param {cc.Rect} pointRect
+ */
+ initTexCoordsWithRect:function (pointRect) {
+ this._renderCmd.initTexCoordsWithRect(pointRect);
+ },
+
+ /**
+ * return weak reference to the cc.SpriteBatchNode that renders the cc.Sprite
+ * @return {cc.ParticleBatchNode}
+ */
+ getBatchNode:function () {
+ return this._batchNode;
+ },
+
+ /**
+ * set weak reference to the cc.SpriteBatchNode that renders the cc.Sprite
+ * @param {cc.ParticleBatchNode} batchNode
+ */
+ setBatchNode:function (batchNode) {
+ this._renderCmd.setBatchNode(batchNode);
+ },
+
+ /**
+ * return index of system in batch node array
+ * @return {Number}
+ */
+ getAtlasIndex:function () {
+ return this.atlasIndex;
+ },
+
+ /**
+ * set index of system in batch node array
+ * @param {Number} atlasIndex
+ */
+ setAtlasIndex:function (atlasIndex) {
+ this.atlasIndex = atlasIndex;
+ },
+
+ /**
+ * Return DrawMode of ParticleSystem (Canvas Mode only)
+ * @return {Number}
+ */
+ getDrawMode:function () {
+ return this._renderCmd.getDrawMode();
+ },
+
+ /**
+ * DrawMode of ParticleSystem setter (Canvas Mode only)
+ * @param {Number} drawMode
+ */
+ setDrawMode:function (drawMode) {
+ this._renderCmd.setDrawMode(drawMode);
+ },
+
+ /**
+ * Return ShapeType of ParticleSystem (Canvas Mode only)
+ * @return {Number}
+ */
+ getShapeType:function () {
+ return this._renderCmd.getShapeType();
+ },
+
+ /**
+ * ShapeType of ParticleSystem setter (Canvas Mode only)
+ * @param {Number} shapeType
+ */
+ setShapeType:function (shapeType) {
+ this._renderCmd.setShapeType(shapeType);
+ },
+
+ /**
+ * Return ParticleSystem is active
+ * @return {Boolean}
+ */
+ isActive:function () {
+ return this._isActive;
+ },
+
+ /**
+ * Quantity of particles that are being simulated at the moment
+ * @return {Number}
+ */
+ getParticleCount:function () {
+ return this.particleCount;
+ },
+
+ /**
+ * Quantity of particles setter
+ * @param {Number} particleCount
+ */
+ setParticleCount:function (particleCount) {
+ this.particleCount = particleCount;
+ },
+
+ /**
+ * How many seconds the emitter wil run. -1 means 'forever'
+ * @return {Number}
+ */
+ getDuration:function () {
+ return this.duration;
+ },
+
+ /**
+ * set run seconds of the emitter
+ * @param {Number} duration
+ */
+ setDuration:function (duration) {
+ this.duration = duration;
+ },
+
+ /**
+ * Return sourcePosition of the emitter
+ * @return {cc.Vec2 | Object}
+ */
+ getSourcePosition:function () {
+ return {x: this._sourcePosition.x, y: this._sourcePosition.y};
+ },
+
+ /**
+ * sourcePosition of the emitter setter
+ * @param sourcePosition
+ */
+ setSourcePosition:function (sourcePosition) {
+ this._sourcePosition = sourcePosition;
+ },
+
+ /**
+ * Return Position variance of the emitter
+ * @return {cc.Vec2 | Object}
+ */
+ getPosVar:function () {
+ return {x: this._posVar.x, y: this._posVar.y};
+ },
+
+ /**
+ * Position variance of the emitter setter
+ * @param {cc.Vec2} posVar
+ */
+ setPosVar:function (posVar) {
+ this._posVar = posVar;
+ },
+
+ /**
+ * Return life of each particle
+ * @return {Number}
+ */
+ getLife:function () {
+ return this.life;
+ },
+
+ /**
+ * life of each particle setter
+ * @param {Number} life
+ */
+ setLife:function (life) {
+ this.life = life;
+ },
+
+ /**
+ * Return life variance of each particle
+ * @return {Number}
+ */
+ getLifeVar:function () {
+ return this.lifeVar;
+ },
+
+ /**
+ * life variance of each particle setter
+ * @param {Number} lifeVar
+ */
+ setLifeVar:function (lifeVar) {
+ this.lifeVar = lifeVar;
+ },
+
+ /**
+ * Return angle of each particle
+ * @return {Number}
+ */
+ getAngle:function () {
+ return this.angle;
+ },
+
+ /**
+ * angle of each particle setter
+ * @param {Number} angle
+ */
+ setAngle:function (angle) {
+ this.angle = angle;
+ },
+
+ /**
+ * Return angle variance of each particle
+ * @return {Number}
+ */
+ getAngleVar:function () {
+ return this.angleVar;
+ },
+
+ /**
+ * angle variance of each particle setter
+ * @param angleVar
+ */
+ setAngleVar:function (angleVar) {
+ this.angleVar = angleVar;
+ },
+
+ // mode A
+ /**
+ * Return Gravity of emitter
+ * @return {cc.Vec2}
+ */
+ getGravity:function () {
+ var locGravity = this.modeA.gravity;
+ return cc.p(locGravity.x, locGravity.y);
+ },
+
+ /**
+ * Gravity of emitter setter
+ * @param {cc.Vec2} gravity
+ */
+ setGravity:function (gravity) {
+ this.modeA.gravity = gravity;
+ },
+
+ /**
+ * Return Speed of each particle
+ * @return {Number}
+ */
+ getSpeed:function () {
+ return this.modeA.speed;
+ },
+
+ /**
+ * Speed of each particle setter
+ * @param {Number} speed
+ */
+ setSpeed:function (speed) {
+ this.modeA.speed = speed;
+ },
+
+ /**
+ * return speed variance of each particle. Only available in 'Gravity' mode.
+ * @return {Number}
+ */
+ getSpeedVar:function () {
+ return this.modeA.speedVar;
+ },
+
+ /**
+ * speed variance of each particle setter. Only available in 'Gravity' mode.
+ * @param {Number} speedVar
+ */
+ setSpeedVar:function (speedVar) {
+ this.modeA.speedVar = speedVar;
+ },
+
+ /**
+ * Return tangential acceleration of each particle. Only available in 'Gravity' mode.
+ * @return {Number}
+ */
+ getTangentialAccel:function () {
+ return this.modeA.tangentialAccel;
+ },
+
+ /**
+ * Tangential acceleration of each particle setter. Only available in 'Gravity' mode.
+ * @param {Number} tangentialAccel
+ */
+ setTangentialAccel:function (tangentialAccel) {
+ this.modeA.tangentialAccel = tangentialAccel;
+ },
+
+ /**
+ * Return tangential acceleration variance of each particle. Only available in 'Gravity' mode.
+ * @return {Number}
+ */
+ getTangentialAccelVar:function () {
+ return this.modeA.tangentialAccelVar;
+ },
+
+ /**
+ * tangential acceleration variance of each particle setter. Only available in 'Gravity' mode.
+ * @param {Number} tangentialAccelVar
+ */
+ setTangentialAccelVar:function (tangentialAccelVar) {
+ this.modeA.tangentialAccelVar = tangentialAccelVar;
+ },
+
+ /**
+ * Return radial acceleration of each particle. Only available in 'Gravity' mode.
+ * @return {Number}
+ */
+ getRadialAccel:function () {
+ return this.modeA.radialAccel;
+ },
+
+ /**
+ * radial acceleration of each particle setter. Only available in 'Gravity' mode.
+ * @param {Number} radialAccel
+ */
+ setRadialAccel:function (radialAccel) {
+ this.modeA.radialAccel = radialAccel;
+ },
+
+ /**
+ * Return radial acceleration variance of each particle. Only available in 'Gravity' mode.
+ * @return {Number}
+ */
+ getRadialAccelVar:function () {
+ return this.modeA.radialAccelVar;
+ },
+
+ /**
+ * radial acceleration variance of each particle setter. Only available in 'Gravity' mode.
+ * @param {Number} radialAccelVar
+ */
+ setRadialAccelVar:function (radialAccelVar) {
+ this.modeA.radialAccelVar = radialAccelVar;
+ },
+
+ /**
+ * get the rotation of each particle to its direction Only available in 'Gravity' mode.
+ * @returns {boolean}
+ */
+ getRotationIsDir: function(){
+ return this.modeA.rotationIsDir;
+ },
+
+ /**
+ * set the rotation of each particle to its direction Only available in 'Gravity' mode.
+ * @param {boolean} t
+ */
+ setRotationIsDir: function(t){
+ this.modeA.rotationIsDir = t;
+ },
+
+ // mode B
+ /**
+ * Return starting radius of the particles. Only available in 'Radius' mode.
+ * @return {Number}
+ */
+ getStartRadius:function () {
+ return this.modeB.startRadius;
+ },
+
+ /**
+ * starting radius of the particles setter. Only available in 'Radius' mode.
+ * @param {Number} startRadius
+ */
+ setStartRadius:function (startRadius) {
+ this.modeB.startRadius = startRadius;
+ },
+
+ /**
+ * Return starting radius variance of the particles. Only available in 'Radius' mode.
+ * @return {Number}
+ */
+ getStartRadiusVar:function () {
+ return this.modeB.startRadiusVar;
+ },
+
+ /**
+ * starting radius variance of the particles setter. Only available in 'Radius' mode.
+ * @param {Number} startRadiusVar
+ */
+ setStartRadiusVar:function (startRadiusVar) {
+ this.modeB.startRadiusVar = startRadiusVar;
+ },
+
+ /**
+ * Return ending radius of the particles. Only available in 'Radius' mode.
+ * @return {Number}
+ */
+ getEndRadius:function () {
+ return this.modeB.endRadius;
+ },
+
+ /**
+ * ending radius of the particles setter. Only available in 'Radius' mode.
+ * @param {Number} endRadius
+ */
+ setEndRadius:function (endRadius) {
+ this.modeB.endRadius = endRadius;
+ },
+
+ /**
+ * Return ending radius variance of the particles. Only available in 'Radius' mode.
+ * @return {Number}
+ */
+ getEndRadiusVar:function () {
+ return this.modeB.endRadiusVar;
+ },
+
+ /**
+ * ending radius variance of the particles setter. Only available in 'Radius' mode.
+ * @param endRadiusVar
+ */
+ setEndRadiusVar:function (endRadiusVar) {
+ this.modeB.endRadiusVar = endRadiusVar;
+ },
+
+ /**
+ * get Number of degress to rotate a particle around the source pos per second. Only available in 'Radius' mode.
+ * @return {Number}
+ */
+ getRotatePerSecond:function () {
+ return this.modeB.rotatePerSecond;
+ },
+
+ /**
+ * set Number of degress to rotate a particle around the source pos per second. Only available in 'Radius' mode.
+ * @param {Number} degrees
+ */
+ setRotatePerSecond:function (degrees) {
+ this.modeB.rotatePerSecond = degrees;
+ },
+
+ /**
+ * Return Variance in degrees for rotatePerSecond. Only available in 'Radius' mode.
+ * @return {Number}
+ */
+ getRotatePerSecondVar:function () {
+ return this.modeB.rotatePerSecondVar;
+ },
+
+ /**
+ * Variance in degrees for rotatePerSecond setter. Only available in 'Radius' mode.
+ * @param degrees
+ */
+ setRotatePerSecondVar:function (degrees) {
+ this.modeB.rotatePerSecondVar = degrees;
+ },
+ //////////////////////////////////////////////////////////////////////////
+
+ //don't use a transform matrix, this is faster
+ setScale:function (scale, scaleY) {
+ this._transformSystemDirty = true;
+ cc.Node.prototype.setScale.call(this, scale, scaleY);
+ },
+
+ setRotation:function (newRotation) {
+ this._transformSystemDirty = true;
+ cc.Node.prototype.setRotation.call(this, newRotation);
+ },
+
+ setScaleX:function (newScaleX) {
+ this._transformSystemDirty = true;
+ cc.Node.prototype.setScaleX.call(this, newScaleX);
+ },
+
+ setScaleY:function (newScaleY) {
+ this._transformSystemDirty = true;
+ cc.Node.prototype.setScaleY.call(this, newScaleY);
+ },
+
+ /**
+ * get start size in pixels of each particle
+ * @return {Number}
+ */
+ getStartSize:function () {
+ return this.startSize;
+ },
+
+ /**
+ * set start size in pixels of each particle
+ * @param {Number} startSize
+ */
+ setStartSize:function (startSize) {
+ this.startSize = startSize;
+ },
+
+ /**
+ * get size variance in pixels of each particle
+ * @return {Number}
+ */
+ getStartSizeVar:function () {
+ return this.startSizeVar;
+ },
+
+ /**
+ * set size variance in pixels of each particle
+ * @param {Number} startSizeVar
+ */
+ setStartSizeVar:function (startSizeVar) {
+ this.startSizeVar = startSizeVar;
+ },
+
+ /**
+ * get end size in pixels of each particle
+ * @return {Number}
+ */
+ getEndSize:function () {
+ return this.endSize;
+ },
+
+ /**
+ * set end size in pixels of each particle
+ * @param endSize
+ */
+ setEndSize:function (endSize) {
+ this.endSize = endSize;
+ },
+
+ /**
+ * get end size variance in pixels of each particle
+ * @return {Number}
+ */
+ getEndSizeVar:function () {
+ return this.endSizeVar;
+ },
+
+ /**
+ * set end size variance in pixels of each particle
+ * @param {Number} endSizeVar
+ */
+ setEndSizeVar:function (endSizeVar) {
+ this.endSizeVar = endSizeVar;
+ },
+
+ /**
+ * set start color of each particle
+ * @return {cc.Color}
+ */
+ getStartColor:function () {
+ return cc.color(this._startColor.r, this._startColor.g, this._startColor.b, this._startColor.a);
+ },
+
+ /**
+ * get start color of each particle
+ * @param {cc.Color} startColor
+ */
+ setStartColor:function (startColor) {
+ this._startColor = cc.color(startColor);
+ },
+
+ /**
+ * get start color variance of each particle
+ * @return {cc.Color}
+ */
+ getStartColorVar:function () {
+ return cc.color(this._startColorVar.r, this._startColorVar.g, this._startColorVar.b, this._startColorVar.a);
+ },
+
+ /**
+ * set start color variance of each particle
+ * @param {cc.Color} startColorVar
+ */
+ setStartColorVar:function (startColorVar) {
+ this._startColorVar = cc.color(startColorVar);
+ },
+
+ /**
+ * get end color and end color variation of each particle
+ * @return {cc.Color}
+ */
+ getEndColor:function () {
+ return cc.color(this._endColor.r, this._endColor.g, this._endColor.b, this._endColor.a);
+ },
+
+ /**
+ * set end color and end color variation of each particle
+ * @param {cc.Color} endColor
+ */
+ setEndColor:function (endColor) {
+ this._endColor = cc.color(endColor);
+ },
+
+ /**
+ * get end color variance of each particle
+ * @return {cc.Color}
+ */
+ getEndColorVar:function () {
+ return cc.color(this._endColorVar.r, this._endColorVar.g, this._endColorVar.b, this._endColorVar.a);
+ },
+
+ /**
+ * set end color variance of each particle
+ * @param {cc.Color} endColorVar
+ */
+ setEndColorVar:function (endColorVar) {
+ this._endColorVar = cc.color(endColorVar);
+ },
+
+ /**
+ * get initial angle of each particle
+ * @return {Number}
+ */
+ getStartSpin:function () {
+ return this.startSpin;
+ },
+
+ /**
+ * set initial angle of each particle
+ * @param {Number} startSpin
+ */
+ setStartSpin:function (startSpin) {
+ this.startSpin = startSpin;
+ },
+
+ /**
+ * get initial angle variance of each particle
+ * @return {Number}
+ */
+ getStartSpinVar:function () {
+ return this.startSpinVar;
+ },
+
+ /**
+ * set initial angle variance of each particle
+ * @param {Number} startSpinVar
+ */
+ setStartSpinVar:function (startSpinVar) {
+ this.startSpinVar = startSpinVar;
+ },
+
+ /**
+ * get end angle of each particle
+ * @return {Number}
+ */
+ getEndSpin:function () {
+ return this.endSpin;
+ },
+
+ /**
+ * set end angle of each particle
+ * @param {Number} endSpin
+ */
+ setEndSpin:function (endSpin) {
+ this.endSpin = endSpin;
+ },
+
+ /**
+ * get end angle variance of each particle
+ * @return {Number}
+ */
+ getEndSpinVar:function () {
+ return this.endSpinVar;
+ },
+
+ /**
+ * set end angle variance of each particle
+ * @param {Number} endSpinVar
+ */
+ setEndSpinVar:function (endSpinVar) {
+ this.endSpinVar = endSpinVar;
+ },
+
+ /**
+ * get emission rate of the particles
+ * @return {Number}
+ */
+ getEmissionRate:function () {
+ return this.emissionRate;
+ },
+
+ /**
+ * set emission rate of the particles
+ * @param {Number} emissionRate
+ */
+ setEmissionRate:function (emissionRate) {
+ this.emissionRate = emissionRate;
+ },
+
+ /**
+ * get maximum particles of the system
+ * @return {Number}
+ */
+ getTotalParticles:function () {
+ return this._totalParticles;
+ },
+
+ /**
+ * set maximum particles of the system
+ * @param {Number} tp totalParticles
+ */
+ setTotalParticles:function (tp) {
+ this._renderCmd.setTotalParticles(tp);
+ },
+
+ /**
+ * get Texture of Particle System
+ * @return {cc.Texture2D}
+ */
+ getTexture:function () {
+ return this._texture;
+ },
+
+ /**
+ * set Texture of Particle System
+ * @param {cc.Texture2D } texture
+ */
+ setTexture:function (texture) {
+ if(!texture)
+ return;
+
+ if(texture.isLoaded()){
+ this.setTextureWithRect(texture, cc.rect(0, 0, texture.width, texture.height));
+ } else {
+ this._textureLoaded = false;
+ texture.once("load", function (event) {
+ this._textureLoaded = true;
+ this.setTextureWithRect(texture, cc.rect(0, 0, texture.width, texture.height));
+ }, this);
+ }
+ },
+
+ /** conforms to CocosNodeTexture protocol */
+ /**
+ * get BlendFunc of Particle System
+ * @return {cc.BlendFunc}
+ */
+ getBlendFunc:function () {
+ return this._blendFunc;
+ },
+
+ /**
+ * set BlendFunc of Particle System
+ * @param {Number} src
+ * @param {Number} dst
+ */
+ setBlendFunc:function (src, dst) {
+ if (dst === undefined) {
+ if (this._blendFunc !== src) {
+ this._blendFunc = src;
+ this._updateBlendFunc();
+ }
+ } else {
+ if (this._blendFunc.src !== src || this._blendFunc.dst !== dst) {
+ this._blendFunc = {src:src, dst:dst};
+ this._updateBlendFunc();
+ }
+ }
+ },
+
+ /**
+ * does the alpha value modify color getter
+ * @return {Boolean}
+ */
+ isOpacityModifyRGB:function () {
+ return this._opacityModifyRGB;
+ },
+
+ /**
+ * does the alpha value modify color setter
+ * @param newValue
+ */
+ setOpacityModifyRGB:function (newValue) {
+ this._opacityModifyRGB = newValue;
+ },
+
+ /**
+ * whether or not the particles are using blend additive.
+ * If enabled, the following blending function will be used.
+ *
+ * @return {Boolean}
+ * @example
+ * source blend function = GL_SRC_ALPHA;
+ * dest blend function = GL_ONE;
+ */
+ isBlendAdditive:function () {
+ return (( this._blendFunc.src === cc.SRC_ALPHA && this._blendFunc.dst === cc.ONE) || (this._blendFunc.src === cc.ONE && this._blendFunc.dst === cc.ONE));
+ },
+
+ /**
+ * whether or not the particles are using blend additive.
+ * If enabled, the following blending function will be used.
+ *
+ * @param {Boolean} isBlendAdditive
+ */
+ setBlendAdditive:function (isBlendAdditive) {
+ var locBlendFunc = this._blendFunc;
+ if (isBlendAdditive) {
+ locBlendFunc.src = cc.SRC_ALPHA;
+ locBlendFunc.dst = cc.ONE;
+ } else {
+ this._renderCmd._setBlendAdditive();
+ }
+ },
+
+ /**
+ * get particles movement type: Free or Grouped
+ * @return {Number}
+ */
+ getPositionType:function () {
+ return this.positionType;
+ },
+
+ /**
+ * set particles movement type: Free or Grouped
+ * @param {Number} positionType
+ */
+ setPositionType:function (positionType) {
+ this.positionType = positionType;
+ },
+
+ /**
+ * return whether or not the node will be auto-removed when it has no particles left.
+ * By default it is false.
+ *
+ * @return {Boolean}
+ */
+ isAutoRemoveOnFinish:function () {
+ return this.autoRemoveOnFinish;
+ },
+
+ /**
+ * set whether or not the node will be auto-removed when it has no particles left.
+ * By default it is false.
+ *
+ * @param {Boolean} isAutoRemoveOnFinish
+ */
+ setAutoRemoveOnFinish:function (isAutoRemoveOnFinish) {
+ this.autoRemoveOnFinish = isAutoRemoveOnFinish;
+ },
+
+ /**
+ * return kind of emitter modes
+ * @return {Number}
+ */
+ getEmitterMode:function () {
+ return this.emitterMode;
+ },
+
+ /**
+ * Switch between different kind of emitter modes:
+ * - CCParticleSystem.Mode.GRAVITY: uses gravity, speed, radial and tangential acceleration
+ * - CCParticleSystem.Mode.RADIUS: uses radius movement + rotation
+ *
+ * @param {Number} emitterMode
+ */
+ setEmitterMode:function (emitterMode) {
+ this.emitterMode = emitterMode;
+ },
+
+ /**
+ * initializes a cc.ParticleSystem
+ */
+ init:function () {
+ return this.initWithTotalParticles(150);
+ },
+
+ /**
+ *
+ * initializes a CCParticleSystem from a plist file.
+ * This plist files can be creted manually or with Particle Designer:
+ * http://particledesigner.71squared.com/
+ *
+ * @param {String} plistFile
+ * @return {boolean}
+ */
+ initWithFile:function (plistFile) {
+ this._plistFile = plistFile;
+ var dict = cc.loader.getRes(plistFile);
+ if(!dict){
+ cc.log("cc.ParticleSystem.initWithFile(): Particles: file not found");
+ return false;
+ }
+
+ // XXX compute path from a path, should define a function somewhere to do it
+ return this.initWithDictionary(dict, "");
+ },
+
+ /**
+ * return bounding box of particle system in world space
+ * @return {cc.Rect}
+ */
+ getBoundingBoxToWorld:function () {
+ return cc.rect(0, 0, cc._canvas.width, cc._canvas.height);
+ },
+
+ /**
+ * initializes a particle system from a NSDictionary and the path from where to load the png
+ * @param {object} dictionary
+ * @param {String} dirname
+ * @return {Boolean}
+ */
+ initWithDictionary:function (dictionary, dirname) {
+ var ret = false;
+ var buffer = null;
+ var image = null;
+ var locValueForKey = this._valueForKey;
+
+ var maxParticles = parseInt(locValueForKey("maxParticles", dictionary));
+ // self, not super
+ if (this.initWithTotalParticles(maxParticles)) {
+ // angle
+ this.angle = parseFloat(locValueForKey("angle", dictionary));
+ this.angleVar = parseFloat(locValueForKey("angleVariance", dictionary));
+
+ // duration
+ this.duration = parseFloat(locValueForKey("duration", dictionary));
+
+ // blend function
+ this._blendFunc.src = parseInt(locValueForKey("blendFuncSource", dictionary));
+ this._blendFunc.dst = parseInt(locValueForKey("blendFuncDestination", dictionary));
+
+ // color
+ var locStartColor = this._startColor;
+ locStartColor.r = parseFloat(locValueForKey("startColorRed", dictionary)) * 255;
+ locStartColor.g = parseFloat(locValueForKey("startColorGreen", dictionary)) * 255;
+ locStartColor.b = parseFloat(locValueForKey("startColorBlue", dictionary)) * 255;
+ locStartColor.a = parseFloat(locValueForKey("startColorAlpha", dictionary)) * 255;
+
+ var locStartColorVar = this._startColorVar;
+ locStartColorVar.r = parseFloat(locValueForKey("startColorVarianceRed", dictionary)) * 255;
+ locStartColorVar.g = parseFloat(locValueForKey("startColorVarianceGreen", dictionary)) * 255;
+ locStartColorVar.b = parseFloat(locValueForKey("startColorVarianceBlue", dictionary)) * 255;
+ locStartColorVar.a = parseFloat(locValueForKey("startColorVarianceAlpha", dictionary)) * 255;
+
+ var locEndColor = this._endColor;
+ locEndColor.r = parseFloat(locValueForKey("finishColorRed", dictionary)) * 255;
+ locEndColor.g = parseFloat(locValueForKey("finishColorGreen", dictionary)) * 255;
+ locEndColor.b = parseFloat(locValueForKey("finishColorBlue", dictionary)) * 255;
+ locEndColor.a = parseFloat(locValueForKey("finishColorAlpha", dictionary)) * 255;
+
+ var locEndColorVar = this._endColorVar;
+ locEndColorVar.r = parseFloat(locValueForKey("finishColorVarianceRed", dictionary)) * 255;
+ locEndColorVar.g = parseFloat(locValueForKey("finishColorVarianceGreen", dictionary)) * 255;
+ locEndColorVar.b = parseFloat(locValueForKey("finishColorVarianceBlue", dictionary)) * 255;
+ locEndColorVar.a = parseFloat(locValueForKey("finishColorVarianceAlpha", dictionary)) * 255;
+
+ // particle size
+ this.startSize = parseFloat(locValueForKey("startParticleSize", dictionary));
+ this.startSizeVar = parseFloat(locValueForKey("startParticleSizeVariance", dictionary));
+ this.endSize = parseFloat(locValueForKey("finishParticleSize", dictionary));
+ this.endSizeVar = parseFloat(locValueForKey("finishParticleSizeVariance", dictionary));
+
+ // position
+ this.setPosition(parseFloat(locValueForKey("sourcePositionx", dictionary)),
+ parseFloat(locValueForKey("sourcePositiony", dictionary)));
+ this._posVar.x = parseFloat(locValueForKey("sourcePositionVariancex", dictionary));
+ this._posVar.y = parseFloat(locValueForKey("sourcePositionVariancey", dictionary));
+
+ // Spinning
+ this.startSpin = parseFloat(locValueForKey("rotationStart", dictionary));
+ this.startSpinVar = parseFloat(locValueForKey("rotationStartVariance", dictionary));
+ this.endSpin = parseFloat(locValueForKey("rotationEnd", dictionary));
+ this.endSpinVar = parseFloat(locValueForKey("rotationEndVariance", dictionary));
+
+ this.emitterMode = parseInt(locValueForKey("emitterType", dictionary));
+
+ // Mode A: Gravity + tangential accel + radial accel
+ if (this.emitterMode === cc.ParticleSystem.Mode.GRAVITY) {
+ var locModeA = this.modeA;
+ // gravity
+ locModeA.gravity.x = parseFloat(locValueForKey("gravityx", dictionary));
+ locModeA.gravity.y = parseFloat(locValueForKey("gravityy", dictionary));
+
+ // speed
+ locModeA.speed = parseFloat(locValueForKey("speed", dictionary));
+ locModeA.speedVar = parseFloat(locValueForKey("speedVariance", dictionary));
+
+ // radial acceleration
+ var pszTmp = locValueForKey("radialAcceleration", dictionary);
+ locModeA.radialAccel = (pszTmp) ? parseFloat(pszTmp) : 0;
+
+ pszTmp = locValueForKey("radialAccelVariance", dictionary);
+ locModeA.radialAccelVar = (pszTmp) ? parseFloat(pszTmp) : 0;
+
+ // tangential acceleration
+ pszTmp = locValueForKey("tangentialAcceleration", dictionary);
+ locModeA.tangentialAccel = (pszTmp) ? parseFloat(pszTmp) : 0;
+
+ pszTmp = locValueForKey("tangentialAccelVariance", dictionary);
+ locModeA.tangentialAccelVar = (pszTmp) ? parseFloat(pszTmp) : 0;
+
+ // rotation is dir
+ var locRotationIsDir = locValueForKey("rotationIsDir", dictionary).toLowerCase();
+ locModeA.rotationIsDir = (locRotationIsDir != null && (locRotationIsDir === "true" || locRotationIsDir === "1"));
+ } else if (this.emitterMode === cc.ParticleSystem.Mode.RADIUS) {
+ // or Mode B: radius movement
+ var locModeB = this.modeB;
+ locModeB.startRadius = parseFloat(locValueForKey("maxRadius", dictionary));
+ locModeB.startRadiusVar = parseFloat(locValueForKey("maxRadiusVariance", dictionary));
+ locModeB.endRadius = parseFloat(locValueForKey("minRadius", dictionary));
+ locModeB.endRadiusVar = 0;
+ locModeB.rotatePerSecond = parseFloat(locValueForKey("rotatePerSecond", dictionary));
+ locModeB.rotatePerSecondVar = parseFloat(locValueForKey("rotatePerSecondVariance", dictionary));
+ } else {
+ cc.log("cc.ParticleSystem.initWithDictionary(): Invalid emitterType in config file");
+ return false;
+ }
+
+ // life span
+ this.life = parseFloat(locValueForKey("particleLifespan", dictionary));
+ this.lifeVar = parseFloat(locValueForKey("particleLifespanVariance", dictionary));
+
+ // emission Rate
+ this.emissionRate = this._totalParticles / this.life;
+
+ //don't get the internal texture if a batchNode is used
+ if (!this._batchNode) {
+ // Set a compatible default for the alpha transfer
+ this._opacityModifyRGB = false;
+
+ // texture
+ // Try to get the texture from the cache
+ var textureName = locValueForKey("textureFileName", dictionary);
+ var imgPath = cc.path.changeBasename(this._plistFile, textureName);
+ var tex = cc.textureCache.getTextureForKey(imgPath);
+
+ if (tex) {
+ this.setTexture(tex);
+ } else {
+ var textureData = locValueForKey("textureImageData", dictionary);
+
+ if (!textureData || textureData.length === 0) {
+ tex = cc.textureCache.addImage(imgPath);
+ if (!tex)
+ return false;
+ this.setTexture(tex);
+ } else {
+ buffer = cc.unzipBase64AsArray(textureData, 1);
+ if (!buffer) {
+ cc.log("cc.ParticleSystem: error decoding or ungzipping textureImageData");
+ return false;
+ }
+
+ var imageFormat = cc.getImageFormatByData(buffer);
+
+ if(imageFormat !== cc.FMT_TIFF && imageFormat !== cc.FMT_PNG){
+ cc.log("cc.ParticleSystem: unknown image format with Data");
+ return false;
+ }
+
+ var canvasObj = document.createElement("canvas");
+ if(imageFormat === cc.FMT_PNG){
+ var myPngObj = new cc.PNGReader(buffer);
+ myPngObj.render(canvasObj);
+ } else {
+ var myTIFFObj = cc.tiffReader;
+ myTIFFObj.parseTIFF(buffer,canvasObj);
+ }
+
+ cc.textureCache.cacheImage(imgPath, canvasObj);
+
+ var addTexture = cc.textureCache.getTextureForKey(imgPath);
+ if(!addTexture)
+ cc.log("cc.ParticleSystem.initWithDictionary() : error loading the texture");
+ this.setTexture(addTexture);
+ }
+ }
+ }
+ ret = true;
+ }
+ return ret;
+ },
+
+ /**
+ * Initializes a system with a fixed number of particles
+ * @param {Number} numberOfParticles
+ * @return {Boolean}
+ */
+ initWithTotalParticles:function (numberOfParticles) {
+ this._totalParticles = numberOfParticles;
+
+ var i, locParticles = this._particles;
+ locParticles.length = 0;
+ for(i = 0; i< numberOfParticles; i++){
+ locParticles[i] = new cc.Particle();
+ }
+
+ if (!locParticles) {
+ cc.log("Particle system: not enough memory");
+ return false;
+ }
+ this._allocatedParticles = numberOfParticles;
+
+ if (this._batchNode)
+ for (i = 0; i < this._totalParticles; i++)
+ locParticles[i].atlasIndex = i;
+
+ // default, active
+ this._isActive = true;
+
+ // default blend function
+ this._blendFunc.src = cc.BLEND_SRC;
+ this._blendFunc.dst = cc.BLEND_DST;
+
+ // default movement type;
+ this.positionType = cc.ParticleSystem.Type.FREE;
+
+ // by default be in mode A:
+ this.emitterMode = cc.ParticleSystem.Mode.GRAVITY;
+
+ // default: modulate
+ // XXX: not used
+ // colorModulate = YES;
+ this.autoRemoveOnFinish = false;
+
+ //for batchNode
+ this._transformSystemDirty = false;
+
+ // udpate after action in run!
+ this.scheduleUpdateWithPriority(1);
+ this._renderCmd._initWithTotalParticles(numberOfParticles);
+ return true;
+ },
+
+ /**
+ * Unschedules the "update" method.
+ * @function
+ * @see scheduleUpdate();
+ */
+ destroyParticleSystem:function () {
+ this.unscheduleUpdate();
+ },
+
+ /**
+ * Add a particle to the emitter
+ * @return {Boolean}
+ */
+ addParticle: function () {
+ if (this.isFull())
+ return false;
+
+ var particle = this._renderCmd.addParticle();
+ this.initParticle(particle);
+ ++this.particleCount;
+ return true;
+ },
+
+ /**
+ * Initializes a particle
+ * @param {cc.Particle} particle
+ */
+ initParticle:function (particle) {
+ var locRandomMinus11 = cc.randomMinus1To1;
+ // timeToLive
+ // no negative life. prevent division by 0
+ particle.timeToLive = this.life + this.lifeVar * locRandomMinus11();
+ particle.timeToLive = Math.max(0, particle.timeToLive);
+
+ // position
+ particle.pos.x = this._sourcePosition.x + this._posVar.x * locRandomMinus11();
+ particle.pos.y = this._sourcePosition.y + this._posVar.y * locRandomMinus11();
+
+ // Color
+ var start, end;
+ var locStartColor = this._startColor, locStartColorVar = this._startColorVar;
+ var locEndColor = this._endColor, locEndColorVar = this._endColorVar;
+ start = {
+ r: cc.clampf(locStartColor.r + locStartColorVar.r * locRandomMinus11(), 0, 255),
+ g: cc.clampf(locStartColor.g + locStartColorVar.g * locRandomMinus11(), 0, 255),
+ b: cc.clampf(locStartColor.b + locStartColorVar.b * locRandomMinus11(), 0, 255),
+ a: cc.clampf(locStartColor.a + locStartColorVar.a * locRandomMinus11(), 0, 255)
+ };
+ end = {
+ r: cc.clampf(locEndColor.r + locEndColorVar.r * locRandomMinus11(), 0, 255),
+ g: cc.clampf(locEndColor.g + locEndColorVar.g * locRandomMinus11(), 0, 255),
+ b: cc.clampf(locEndColor.b + locEndColorVar.b * locRandomMinus11(), 0, 255),
+ a: cc.clampf(locEndColor.a + locEndColorVar.a * locRandomMinus11(), 0, 255)
+ };
+
+ particle.color = start;
+ var locParticleDeltaColor = particle.deltaColor, locParticleTimeToLive = particle.timeToLive;
+ locParticleDeltaColor.r = (end.r - start.r) / locParticleTimeToLive;
+ locParticleDeltaColor.g = (end.g - start.g) / locParticleTimeToLive;
+ locParticleDeltaColor.b = (end.b - start.b) / locParticleTimeToLive;
+ locParticleDeltaColor.a = (end.a - start.a) / locParticleTimeToLive;
+
+ // size
+ var startS = this.startSize + this.startSizeVar * locRandomMinus11();
+ startS = Math.max(0, startS); // No negative value
+
+ particle.size = startS;
+ if (this.endSize === cc.ParticleSystem.START_SIZE_EQUAL_TO_END_SIZE) {
+ particle.deltaSize = 0;
+ } else {
+ var endS = this.endSize + this.endSizeVar * locRandomMinus11();
+ endS = Math.max(0, endS); // No negative values
+ particle.deltaSize = (endS - startS) / locParticleTimeToLive;
+ }
+
+ // rotation
+ var startA = this.startSpin + this.startSpinVar * locRandomMinus11();
+ var endA = this.endSpin + this.endSpinVar * locRandomMinus11();
+ particle.rotation = startA;
+ particle.deltaRotation = (endA - startA) / locParticleTimeToLive;
+
+ // position
+ if (this.positionType === cc.ParticleSystem.Type.FREE)
+ particle.startPos = this.convertToWorldSpace(this._pointZeroForParticle);
+ else if (this.positionType === cc.ParticleSystem.Type.RELATIVE){
+ particle.startPos.x = this._position.x;
+ particle.startPos.y = this._position.y;
+ }
+
+ // direction
+ var a = cc.degreesToRadians(this.angle + this.angleVar * locRandomMinus11());
+
+ // Mode Gravity: A
+ if (this.emitterMode === cc.ParticleSystem.Mode.GRAVITY) {
+ var locModeA = this.modeA, locParticleModeA = particle.modeA;
+ var s = locModeA.speed + locModeA.speedVar * locRandomMinus11();
+
+ // direction
+ locParticleModeA.dir.x = Math.cos(a);
+ locParticleModeA.dir.y = Math.sin(a);
+ cc.pMultIn(locParticleModeA.dir, s);
+
+ // radial accel
+ locParticleModeA.radialAccel = locModeA.radialAccel + locModeA.radialAccelVar * locRandomMinus11();
+
+ // tangential accel
+ locParticleModeA.tangentialAccel = locModeA.tangentialAccel + locModeA.tangentialAccelVar * locRandomMinus11();
+
+ // rotation is dir
+ if(locModeA.rotationIsDir)
+ particle.rotation = -cc.radiansToDegrees(cc.pToAngle(locParticleModeA.dir));
+ } else {
+ // Mode Radius: B
+ var locModeB = this.modeB, locParitlceModeB = particle.modeB;
+
+ // Set the default diameter of the particle from the source position
+ var startRadius = locModeB.startRadius + locModeB.startRadiusVar * locRandomMinus11();
+ var endRadius = locModeB.endRadius + locModeB.endRadiusVar * locRandomMinus11();
+
+ locParitlceModeB.radius = startRadius;
+ locParitlceModeB.deltaRadius = (locModeB.endRadius === cc.ParticleSystem.START_RADIUS_EQUAL_TO_END_RADIUS) ? 0 : (endRadius - startRadius) / locParticleTimeToLive;
+
+ locParitlceModeB.angle = a;
+ locParitlceModeB.degreesPerSecond = cc.degreesToRadians(locModeB.rotatePerSecond + locModeB.rotatePerSecondVar * locRandomMinus11());
+ }
+ },
+
+ /**
+ * stop emitting particles. Running particles will continue to run until they die
+ */
+ stopSystem:function () {
+ this._isActive = false;
+ this._elapsed = this.duration;
+ this._emitCounter = 0;
+ },
+
+ /**
+ * Kill all living particles.
+ */
+ resetSystem:function () {
+ this._isActive = true;
+ this._elapsed = 0;
+ var locParticles = this._particles;
+ for (this._particleIdx = 0; this._particleIdx < this.particleCount; ++this._particleIdx)
+ locParticles[this._particleIdx].timeToLive = 0 ;
+ },
+
+ /**
+ * whether or not the system is full
+ * @return {Boolean}
+ */
+ isFull:function () {
+ return (this.particleCount >= this._totalParticles);
+ },
+
+ /**
+ * should be overridden by subclasses
+ * @param {cc.Particle} particle
+ * @param {cc.Vec2} newPosition
+ */
+ updateQuadWithParticle:function (particle, newPosition) {
+ this._renderCmd.updateQuadWithParticle(particle, newPosition);
+ },
+
+ /**
+ * should be overridden by subclasses
+ */
+ postStep:function () {
+ this._renderCmd.postStep();
+ },
+
+ /**
+ * update emitter's status
+ * @override
+ * @param {Number} dt delta time
+ */
+ update:function (dt) {
+ if (this._isActive && this.emissionRate) {
+ var rate = 1.0 / this.emissionRate;
+ //issue #1201, prevent bursts of particles, due to too high emitCounter
+ if (this.particleCount < this._totalParticles)
+ this._emitCounter += dt;
+
+ while ((this.particleCount < this._totalParticles) && (this._emitCounter > rate)) {
+ this.addParticle();
+ this._emitCounter -= rate;
+ }
+
+ this._elapsed += dt;
+ if (this.duration !== -1 && this.duration < this._elapsed)
+ this.stopSystem();
+ }
+ this._particleIdx = 0;
+
+ var currentPosition = cc.Particle.TemporaryPoints[0];
+ if (this.positionType === cc.ParticleSystem.Type.FREE) {
+ cc.pIn(currentPosition, this.convertToWorldSpace(this._pointZeroForParticle));
+ } else if (this.positionType === cc.ParticleSystem.Type.RELATIVE) {
+ currentPosition.x = this._position.x;
+ currentPosition.y = this._position.y;
+ }
+
+ if (this._visible) {
+ // Used to reduce memory allocation / creation within the loop
+ var tpa = cc.Particle.TemporaryPoints[1],
+ tpb = cc.Particle.TemporaryPoints[2],
+ tpc = cc.Particle.TemporaryPoints[3];
+
+ var locParticles = this._particles;
+ while (this._particleIdx < this.particleCount) {
+
+ // Reset the working particles
+ cc.pZeroIn(tpa);
+ cc.pZeroIn(tpb);
+ cc.pZeroIn(tpc);
+
+ var selParticle = locParticles[this._particleIdx];
+
+ // life
+ selParticle.timeToLive -= dt;
+
+ if (selParticle.timeToLive > 0) {
+ // Mode A: gravity, direction, tangential accel & radial accel
+ if (this.emitterMode === cc.ParticleSystem.Mode.GRAVITY) {
+
+ var tmp = tpc, radial = tpa, tangential = tpb;
+
+ // radial acceleration
+ if (selParticle.pos.x || selParticle.pos.y) {
+ cc.pIn(radial, selParticle.pos);
+ cc.pNormalizeIn(radial);
+ } else {
+ cc.pZeroIn(radial);
+ }
+
+ cc.pIn(tangential, radial);
+ cc.pMultIn(radial, selParticle.modeA.radialAccel);
+
+ // tangential acceleration
+ var newy = tangential.x;
+ tangential.x = -tangential.y;
+ tangential.y = newy;
+
+ cc.pMultIn(tangential, selParticle.modeA.tangentialAccel);
+
+ cc.pIn(tmp, radial);
+ cc.pAddIn(tmp, tangential);
+ cc.pAddIn(tmp, this.modeA.gravity);
+ cc.pMultIn(tmp, dt);
+ cc.pAddIn(selParticle.modeA.dir, tmp);
+
+
+ cc.pIn(tmp, selParticle.modeA.dir);
+ cc.pMultIn(tmp, dt);
+ cc.pAddIn(selParticle.pos, tmp);
+ } else {
+ // Mode B: radius movement
+ var selModeB = selParticle.modeB;
+ // Update the angle and radius of the particle.
+ selModeB.angle += selModeB.degreesPerSecond * dt;
+ selModeB.radius += selModeB.deltaRadius * dt;
+
+ selParticle.pos.x = -Math.cos(selModeB.angle) * selModeB.radius;
+ selParticle.pos.y = -Math.sin(selModeB.angle) * selModeB.radius;
+ }
+
+ // color
+ this._renderCmd._updateDeltaColor(selParticle, dt);
+
+ // size
+ selParticle.size += (selParticle.deltaSize * dt);
+ selParticle.size = Math.max(0, selParticle.size);
+
+ // angle
+ selParticle.rotation += (selParticle.deltaRotation * dt);
+
+ //
+ // update values in quad
+ //
+ var newPos = tpa;
+ if (this.positionType === cc.ParticleSystem.Type.FREE || this.positionType === cc.ParticleSystem.Type.RELATIVE) {
+ var diff = tpb;
+ cc.pIn(diff, currentPosition);
+ cc.pSubIn(diff, selParticle.startPos);
+
+ cc.pIn(newPos, selParticle.pos);
+ cc.pSubIn(newPos, diff);
+ } else {
+ cc.pIn(newPos, selParticle.pos);
+ }
+
+ // translate newPos to correct position, since matrix transform isn't performed in batchnode
+ // don't update the particle with the new position information, it will interfere with the radius and tangential calculations
+ if (this._batchNode) {
+ newPos.x += this._position.x;
+ newPos.y += this._position.y;
+ }
+ this._renderCmd.updateParticlePosition(selParticle, newPos);
+
+ // update particle counter
+ ++this._particleIdx;
+ } else {
+ // life < 0
+ var currentIndex = selParticle.atlasIndex;
+ if(this._particleIdx !== this.particleCount -1){
+ var deadParticle = locParticles[this._particleIdx];
+ locParticles[this._particleIdx] = locParticles[this.particleCount -1];
+ locParticles[this.particleCount -1] = deadParticle;
+ }
+ if (this._batchNode) {
+ //disable the switched particle
+ this._batchNode.disableParticle(this.atlasIndex + currentIndex);
+ //switch indexes
+ locParticles[this.particleCount - 1].atlasIndex = currentIndex;
+ }
+
+ --this.particleCount;
+ if (this.particleCount === 0 && this.autoRemoveOnFinish) {
+ this.unscheduleUpdate();
+ this._parent.removeChild(this, true);
+ return;
+ }
+ }
+ }
+ this._transformSystemDirty = false;
+ }
+
+ if (!this._batchNode)
+ this.postStep();
+ },
+
+ /**
+ * update emitter's status (dt = 0)
+ */
+ updateWithNoTime:function () {
+ this.update(0);
+ },
+
+ //
+ // return the string found by key in dict.
+ // @param {string} key
+ // @param {object} dict
+ // @return {String} "" if not found; return the string if found.
+ // @private
+ //
+ _valueForKey:function (key, dict) {
+ if (dict) {
+ var pString = dict[key];
+ return pString != null ? pString : "";
+ }
+ return "";
+ },
+
+ _updateBlendFunc:function () {
+ if(this._batchNode){
+ cc.log("Can't change blending functions when the particle is being batched");
+ return;
+ }
+
+ var locTexture = this._texture;
+ if (locTexture && locTexture instanceof cc.Texture2D) {
+ this._opacityModifyRGB = false;
+ var locBlendFunc = this._blendFunc;
+ if (locBlendFunc.src === cc.BLEND_SRC && locBlendFunc.dst === cc.BLEND_DST) {
+ if (locTexture.hasPremultipliedAlpha()) {
+ this._opacityModifyRGB = true;
+ } else {
+ locBlendFunc.src = cc.SRC_ALPHA;
+ locBlendFunc.dst = cc.ONE_MINUS_SRC_ALPHA;
+ }
+ }
+ }
+ },
+
+ /**
+ * to copy object with deep copy.
+ * returns a clone of action.
+ *
+ * @return {cc.ParticleSystem}
+ */
+ clone:function () {
+ var retParticle = new cc.ParticleSystem();
+
+ // self, not super
+ if (retParticle.initWithTotalParticles(this.getTotalParticles())) {
+ // angle
+ retParticle.setAngle(this.getAngle());
+ retParticle.setAngleVar(this.getAngleVar());
+
+ // duration
+ retParticle.setDuration(this.getDuration());
+
+ // blend function
+ var blend = this.getBlendFunc();
+ retParticle.setBlendFunc(blend.src,blend.dst);
+
+ // color
+ retParticle.setStartColor(this.getStartColor());
+
+ retParticle.setStartColorVar(this.getStartColorVar());
+
+ retParticle.setEndColor(this.getEndColor());
+
+ retParticle.setEndColorVar(this.getEndColorVar());
+
+ // this size
+ retParticle.setStartSize(this.getStartSize());
+ retParticle.setStartSizeVar(this.getStartSizeVar());
+ retParticle.setEndSize(this.getEndSize());
+ retParticle.setEndSizeVar(this.getEndSizeVar());
+
+ // position
+ retParticle.setPosition(cc.p(this.x, this.y));
+ retParticle.setPosVar(cc.p(this.getPosVar().x,this.getPosVar().y));
+
+ retParticle.setPositionType(this.getPositionType());
+
+ // Spinning
+ retParticle.setStartSpin(this.getStartSpin()||0);
+ retParticle.setStartSpinVar(this.getStartSpinVar()||0);
+ retParticle.setEndSpin(this.getEndSpin()||0);
+ retParticle.setEndSpinVar(this.getEndSpinVar()||0);
+
+ retParticle.setEmitterMode(this.getEmitterMode());
+
+ // Mode A: Gravity + tangential accel + radial accel
+ if (this.getEmitterMode() === cc.ParticleSystem.Mode.GRAVITY) {
+ // gravity
+ var gra = this.getGravity();
+ retParticle.setGravity(cc.p(gra.x,gra.y));
+
+ // speed
+ retParticle.setSpeed(this.getSpeed());
+ retParticle.setSpeedVar(this.getSpeedVar());
+
+ // radial acceleration
+ retParticle.setRadialAccel(this.getRadialAccel());
+ retParticle.setRadialAccelVar(this.getRadialAccelVar());
+
+ // tangential acceleration
+ retParticle.setTangentialAccel(this.getTangentialAccel());
+ retParticle.setTangentialAccelVar(this.getTangentialAccelVar());
+
+ } else if (this.getEmitterMode() === cc.ParticleSystem.Mode.RADIUS) {
+ // or Mode B: radius movement
+ retParticle.setStartRadius(this.getStartRadius());
+ retParticle.setStartRadiusVar(this.getStartRadiusVar());
+ retParticle.setEndRadius(this.getEndRadius());
+ retParticle.setEndRadiusVar(this.getEndRadiusVar());
+
+ retParticle.setRotatePerSecond(this.getRotatePerSecond());
+ retParticle.setRotatePerSecondVar(this.getRotatePerSecondVar());
+ }
+
+ // life span
+ retParticle.setLife(this.getLife());
+ retParticle.setLifeVar(this.getLifeVar());
+
+ // emission Rate
+ retParticle.setEmissionRate(this.getEmissionRate());
+
+ //don't get the internal texture if a batchNode is used
+ if (!this.getBatchNode()) {
+ // Set a compatible default for the alpha transfer
+ retParticle.setOpacityModifyRGB(this.isOpacityModifyRGB());
+ // texture
+ var texture = this.getTexture();
+ if(texture){
+ var size = texture.getContentSize();
+ retParticle.setTextureWithRect(texture, cc.rect(0, 0, size.width, size.height));
+ }
+ }
+ }
+ return retParticle;
+ },
+
+ /**
+ * Sets a new CCSpriteFrame as particle.
+ * WARNING: this method is experimental. Use setTextureWithRect instead.
+ *
+ * @param {cc.SpriteFrame} spriteFrame
+ */
+ setDisplayFrame: function (spriteFrame) {
+ if (!spriteFrame)
+ return;
+
+ var locOffset = spriteFrame.getOffsetInPixels();
+ if (locOffset.x !== 0 || locOffset.y !== 0)
+ cc.log("cc.ParticleSystem.setDisplayFrame(): QuadParticle only supports SpriteFrames with no offsets");
+
+ // update texture before updating texture rect
+ var texture = spriteFrame.getTexture(), locTexture = this._texture;
+ if (locTexture !== texture)
+ this.setTexture(texture);
+ },
+
+ /**
+ * Sets a new texture with a rect. The rect is in Points.
+ * @param {cc.Texture2D} texture
+ * @param {cc.Rect} rect
+ */
+ setTextureWithRect: function (texture, rect) {
+ var locTexture = this._texture;
+ if (locTexture !== texture) {
+ this._texture = texture;
+ this._updateBlendFunc();
+ }
+ this.initTexCoordsWithRect(rect);
+ },
+
+ /**
+ * listen the event that coming to foreground on Android (An empty function for native)
+ * @param {cc._Class} obj
+ */
+ listenBackToForeground:function (obj) {
+ //do nothing
+ }
+});
+
+var _p = cc.ParticleSystem.prototype;
+
+// Extended properties
+/** @expose */
+_p.opacityModifyRGB;
+cc.defineGetterSetter(_p, "opacityModifyRGB", _p.isOpacityModifyRGB, _p.setOpacityModifyRGB);
+/** @expose */
+_p.batchNode;
+cc.defineGetterSetter(_p, "batchNode", _p.getBatchNode, _p.setBatchNode);
+/** @expose */
+_p.drawMode;
+cc.defineGetterSetter(_p, "drawMode", _p.getDrawMode, _p.setDrawMode);
+/** @expose */
+_p.shapeType;
+cc.defineGetterSetter(_p, "shapeType", _p.getShapeType, _p.setShapeType);
+/** @expose */
+_p.active;
+cc.defineGetterSetter(_p, "active", _p.isActive);
+/** @expose */
+_p.sourcePos;
+cc.defineGetterSetter(_p, "sourcePos", _p.getSourcePosition, _p.setSourcePosition);
+/** @expose */
+_p.posVar;
+cc.defineGetterSetter(_p, "posVar", _p.getPosVar, _p.setPosVar);
+/** @expose */
+_p.gravity;
+cc.defineGetterSetter(_p, "gravity", _p.getGravity, _p.setGravity);
+/** @expose */
+_p.speed;
+cc.defineGetterSetter(_p, "speed", _p.getSpeed, _p.setSpeed);
+/** @expose */
+_p.speedVar;
+cc.defineGetterSetter(_p, "speedVar", _p.getSpeedVar, _p.setSpeedVar);
+/** @expose */
+_p.tangentialAccel;
+cc.defineGetterSetter(_p, "tangentialAccel", _p.getTangentialAccel, _p.setTangentialAccel);
+/** @expose */
+_p.tangentialAccelVar;
+cc.defineGetterSetter(_p, "tangentialAccelVar", _p.getTangentialAccelVar, _p.setTangentialAccelVar);
+/** @expose */
+_p.radialAccel;
+cc.defineGetterSetter(_p, "radialAccel", _p.getRadialAccel, _p.setRadialAccel);
+/** @expose */
+_p.radialAccelVar;
+cc.defineGetterSetter(_p, "radialAccelVar", _p.getRadialAccelVar, _p.setRadialAccelVar);
+/** @expose */
+_p.rotationIsDir;
+cc.defineGetterSetter(_p, "rotationIsDir", _p.getRotationIsDir, _p.setRotationIsDir);
+/** @expose */
+_p.startRadius;
+cc.defineGetterSetter(_p, "startRadius", _p.getStartRadius, _p.setStartRadius);
+/** @expose */
+_p.startRadiusVar;
+cc.defineGetterSetter(_p, "startRadiusVar", _p.getStartRadiusVar, _p.setStartRadiusVar);
+/** @expose */
+_p.endRadius;
+cc.defineGetterSetter(_p, "endRadius", _p.getEndRadius, _p.setEndRadius);
+/** @expose */
+_p.endRadiusVar;
+cc.defineGetterSetter(_p, "endRadiusVar", _p.getEndRadiusVar, _p.setEndRadiusVar);
+/** @expose */
+_p.rotatePerS;
+cc.defineGetterSetter(_p, "rotatePerS", _p.getRotatePerSecond, _p.setRotatePerSecond);
+/** @expose */
+_p.rotatePerSVar;
+cc.defineGetterSetter(_p, "rotatePerSVar", _p.getRotatePerSecondVar, _p.setRotatePerSecondVar);
+/** @expose */
+_p.startColor;
+cc.defineGetterSetter(_p, "startColor", _p.getStartColor, _p.setStartColor);
+/** @expose */
+_p.startColorVar;
+cc.defineGetterSetter(_p, "startColorVar", _p.getStartColorVar, _p.setStartColorVar);
+/** @expose */
+_p.endColor;
+cc.defineGetterSetter(_p, "endColor", _p.getEndColor, _p.setEndColor);
+/** @expose */
+_p.endColorVar;
+cc.defineGetterSetter(_p, "endColorVar", _p.getEndColorVar, _p.setEndColorVar);
+/** @expose */
+_p.totalParticles;
+cc.defineGetterSetter(_p, "totalParticles", _p.getTotalParticles, _p.setTotalParticles);
+/** @expose */
+_p.texture;
+cc.defineGetterSetter(_p, "texture", _p.getTexture, _p.setTexture);
+
+
+/**
+ * return the string found by key in dict.
+ * This plist files can be create manually or with Particle Designer:
+ * http://particledesigner.71squared.com/
+ *
+ * @deprecated since v3.0 please use new cc.ParticleSysytem(plistFile) instead.
+ * @param {String|Number} plistFile
+ * @return {cc.ParticleSystem}
+ */
+cc.ParticleSystem.create = function (plistFile) {
+ return new cc.ParticleSystem(plistFile);
+};
+
+/**
+ * return the string found by key in dict.
+ * This plist files can be create manually or with Particle Designer:
+ * http://particledesigner.71squared.com/
+ *
+ * @deprecated since v3.0 please use new cc.ParticleSysytem(plistFile) instead.
+ * @function
+ * @param {String|Number} plistFile
+ * @return {cc.ParticleSystem}
+ */
+cc.ParticleSystem.createWithTotalParticles = cc.ParticleSystem.create;
+
+// Different modes
+/**
+ * Mode A:Gravity + Tangential Accel + Radial Accel
+ * @Class
+ * @Construct
+ * @param {cc.Vec2} [gravity=] Gravity value.
+ * @param {Number} [speed=0] speed of each particle.
+ * @param {Number} [speedVar=0] speed variance of each particle.
+ * @param {Number} [tangentialAccel=0] tangential acceleration of each particle.
+ * @param {Number} [tangentialAccelVar=0] tangential acceleration variance of each particle.
+ * @param {Number} [radialAccel=0] radial acceleration of each particle.
+ * @param {Number} [radialAccelVar=0] radial acceleration variance of each particle.
+ * @param {boolean} [rotationIsDir=false]
+ */
+cc.ParticleSystem.ModeA = function (gravity, speed, speedVar, tangentialAccel, tangentialAccelVar, radialAccel, radialAccelVar, rotationIsDir) {
+ /** Gravity value. Only available in 'Gravity' mode. */
+ this.gravity = gravity ? gravity : cc.p(0,0);
+ /** speed of each particle. Only available in 'Gravity' mode. */
+ this.speed = speed || 0;
+ /** speed variance of each particle. Only available in 'Gravity' mode. */
+ this.speedVar = speedVar || 0;
+ /** tangential acceleration of each particle. Only available in 'Gravity' mode. */
+ this.tangentialAccel = tangentialAccel || 0;
+ /** tangential acceleration variance of each particle. Only available in 'Gravity' mode. */
+ this.tangentialAccelVar = tangentialAccelVar || 0;
+ /** radial acceleration of each particle. Only available in 'Gravity' mode. */
+ this.radialAccel = radialAccel || 0;
+ /** radial acceleration variance of each particle. Only available in 'Gravity' mode. */
+ this.radialAccelVar = radialAccelVar || 0;
+ /** set the rotation of each particle to its direction Only available in 'Gravity' mode. */
+ this.rotationIsDir = rotationIsDir || false;
+};
+
+/**
+ * Mode B: circular movement (gravity, radial accel and tangential accel don't are not used in this mode)
+ * @Class
+ * @Construct
+ * @param {Number} [startRadius=0] The starting radius of the particles.
+ * @param {Number} [startRadiusVar=0] The starting radius variance of the particles.
+ * @param {Number} [endRadius=0] The ending radius of the particles.
+ * @param {Number} [endRadiusVar=0] The ending radius variance of the particles.
+ * @param {Number} [rotatePerSecond=0] Number of degrees to rotate a particle around the source pos per second.
+ * @param {Number} [rotatePerSecondVar=0] Variance in degrees for rotatePerSecond.
+ */
+cc.ParticleSystem.ModeB = function (startRadius, startRadiusVar, endRadius, endRadiusVar, rotatePerSecond, rotatePerSecondVar) {
+ /** The starting radius of the particles. Only available in 'Radius' mode. */
+ this.startRadius = startRadius || 0;
+ /** The starting radius variance of the particles. Only available in 'Radius' mode. */
+ this.startRadiusVar = startRadiusVar || 0;
+ /** The ending radius of the particles. Only available in 'Radius' mode. */
+ this.endRadius = endRadius || 0;
+ /** The ending radius variance of the particles. Only available in 'Radius' mode. */
+ this.endRadiusVar = endRadiusVar || 0;
+ /** Number of degress to rotate a particle around the source pos per second. Only available in 'Radius' mode. */
+ this.rotatePerSecond = rotatePerSecond || 0;
+ /** Variance in degrees for rotatePerSecond. Only available in 'Radius' mode. */
+ this.rotatePerSecondVar = rotatePerSecondVar || 0;
+};
+
+/**
+ * Shape Mode of Particle Draw
+ * @constant
+ * @type Number
+ */
+cc.ParticleSystem.SHAPE_MODE = 0;
+
+/**
+ * Texture Mode of Particle Draw
+ * @constant
+ * @type Number
+ */
+cc.ParticleSystem.TEXTURE_MODE = 1;
+
+/**
+ * Star Shape for ShapeMode of Particle
+ * @constant
+ * @type Number
+ */
+cc.ParticleSystem.STAR_SHAPE = 0;
+
+/**
+ * Ball Shape for ShapeMode of Particle
+ * @constant
+ * @type Number
+ */
+cc.ParticleSystem.BALL_SHAPE = 1;
+
+/**
+ * The Particle emitter lives forever
+ * @constant
+ * @type Number
+ */
+cc.ParticleSystem.DURATION_INFINITY = -1;
+
+/**
+ * The starting size of the particle is equal to the ending size
+ * @constant
+ * @type Number
+ */
+cc.ParticleSystem.START_SIZE_EQUAL_TO_END_SIZE = -1;
+
+/**
+ * The starting radius of the particle is equal to the ending radius
+ * @constant
+ * @type Number
+ */
+cc.ParticleSystem.START_RADIUS_EQUAL_TO_END_RADIUS = -1;
+
+/**
+ * Enum for particle mode
+ * @readonly
+ * @enum {number}
+ */
+cc.ParticleSystem.Mode = cc.Enum({
+ /** The gravity mode (A mode) */
+ GRAVITY: 0,
+ /** The radius mode (B mode) */
+ RADIUS: 1
+});
+
+/**
+ * Enum for particle type
+ * @readonly
+ * @enum {number}
+ */
+cc.ParticleSystem.Type = cc.Enum({
+ /**
+ * Living particles are attached to the world and are unaffected by emitter repositioning.
+ */
+ FREE: 0,
+
+ /**
+ * Living particles are attached to the world but will follow the emitter repositioning.
+ * Use case: Attach an emitter to an sprite, and you want that the emitter follows the sprite.
+ */
+ RELATIVE: 1,
+
+ /**
+ * Living particles are attached to the emitter and are translated along with it.
+ */
+ GROUPED: 2
+});
diff --git a/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js b/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js
new file mode 100644
index 0000000000..de78252346
--- /dev/null
+++ b/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js
@@ -0,0 +1,199 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+/**
+ * ParticleSystem's canvas render command
+ */
+(function(){
+ cc.ParticleSystem.CanvasRenderCmd = function(renderable){
+ cc.Node.CanvasRenderCmd.call(this, renderable);
+ this._needDraw = true;
+
+ this._drawMode = cc.ParticleSystem.TEXTURE_MODE;
+ this._shapeType = cc.ParticleSystem.BALL_SHAPE;
+
+ this._pointRect = cc.rect(0, 0, 0, 0);
+ this._tintCache = document.createElement("canvas");
+ };
+ var proto = cc.ParticleSystem.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
+ proto.constructor = cc.ParticleSystem.CanvasRenderCmd;
+
+ proto.getDrawMode = function(){
+ return this._drawMode;
+ };
+
+ proto.setDrawMode = function(drawMode){
+ this._drawMode = drawMode;
+ };
+
+ proto.getShapeType = function(){
+ return this._shapeType;
+ };
+
+ proto.setShapeType = function(shapeType){
+ this._shapeType = shapeType;
+ };
+
+ proto.setBatchNode = function(batchNode){
+ if (this._batchNode !== batchNode) {
+ this._node._batchNode = batchNode;
+ }
+ };
+
+ proto.updateQuadWithParticle = function (particle, newPosition) {
+ //do nothing
+ };
+
+ proto.updateParticlePosition = function(particle, position){
+ cc.pIn(particle.drawPos, position);
+ };
+
+ proto.rendering = function (ctx, scaleX, scaleY) {
+ //TODO: need refactor rendering for performance
+ var wrapper = ctx || cc._renderContext, context = wrapper.getContext(),
+ node = this._node, pointRect = this._pointRect;
+
+ wrapper.setTransform(this._worldTransform, scaleX, scaleY);
+ wrapper.save();
+ if (node.isBlendAdditive())
+ context.globalCompositeOperation = 'lighter';
+ else
+ context.globalCompositeOperation = 'source-over';
+
+ var i, particle, lpx, alpha;
+ var particleCount = this._node.particleCount, particles = this._node._particles;
+ if (node.drawMode !== cc.ParticleSystem.SHAPE_MODE && node._texture) {
+ // Delay drawing until the texture is fully loaded by the browser
+ if (!node._texture._textureLoaded) {
+ wrapper.restore();
+ return;
+ }
+ var element = node._texture.getHtmlElementObj();
+ if (!element.width || !element.height) {
+ wrapper.restore();
+ return;
+ }
+
+ var drawElement = element;
+ for (i = 0; i < particleCount; i++) {
+ particle = particles[i];
+ lpx = (0 | (particle.size * 0.5));
+
+ alpha = particle.color.a / 255;
+ if (alpha === 0) continue;
+ context.globalAlpha = alpha;
+
+ context.save();
+ context.translate((0 | particle.drawPos.x), -(0 | particle.drawPos.y));
+
+ var size = Math.floor(particle.size / 4) * 4;
+ var w = pointRect.width;
+ var h = pointRect.height;
+
+ context.scale(Math.max((1 / w) * size, 0.000001), Math.max((1 / h) * size, 0.000001));
+ if (particle.rotation)
+ context.rotate(cc.degreesToRadians(particle.rotation));
+
+ drawElement = particle.isChangeColor ? this._changeTextureColor(node._texture, particle.color, this._pointRect) : element;
+ context.drawImage(drawElement, -(0 | (w / 2)), -(0 | (h / 2)));
+ context.restore();
+ }
+ } else {
+ var drawTool = cc._drawingUtil;
+ for (i = 0; i < particleCount; i++) {
+ particle = particles[i];
+ lpx = (0 | (particle.size * 0.5));
+ alpha = particle.color.a / 255;
+ if (alpha === 0) continue;
+ context.globalAlpha = alpha;
+
+ context.save();
+ context.translate(0 | particle.drawPos.x, -(0 | particle.drawPos.y));
+ if (node.shapeType === cc.ParticleSystem.STAR_SHAPE) {
+ if (particle.rotation)
+ context.rotate(cc.degreesToRadians(particle.rotation));
+ drawTool.drawStar(wrapper, lpx, particle.color);
+ } else
+ drawTool.drawColorBall(wrapper, lpx, particle.color);
+ context.restore();
+ }
+ }
+ wrapper.restore();
+ cc.g_NumberOfDraws++;
+ };
+
+ proto._changeTextureColor = function(texture, color, rect){
+ var tintCache = this._tintCache;
+ var textureContentSize = texture.getContentSize();
+ tintCache.width = textureContentSize.width;
+ tintCache.height = textureContentSize.height;
+ return texture._generateColorTexture(color.r, color.g, color.b, rect, tintCache);
+ };
+
+ proto.initTexCoordsWithRect = function(pointRect){
+ this._pointRect = pointRect;
+ };
+
+ proto.setTotalParticles = function(tp){
+ //cc.assert(tp <= this._allocatedParticles, "Particle: resizing particle array only supported for quads");
+ this._node._totalParticles = (tp < 200) ? tp : 200;
+ };
+
+ proto.addParticle = function(){
+ var node = this._node,
+ particles = node._particles,
+ particle;
+ if (node.particleCount < particles.length) {
+ particle = particles[node.particleCount];
+ } else {
+ particle = new cc.Particle();
+ particles.push(particle);
+ }
+ return particle;
+ };
+
+ proto._setupVBO = function(){};
+ proto._allocMemory = function(){
+ return true;
+ };
+
+ proto.postStep = function(){};
+
+ proto._setBlendAdditive = function(){
+ var locBlendFunc = this._node._blendFunc;
+ locBlendFunc.src = cc.BLEND_SRC;
+ locBlendFunc.dst = cc.BLEND_DST;
+ };
+
+ proto._initWithTotalParticles = function(totalParticles){};
+ proto._updateDeltaColor = function(selParticle, dt){
+ if (!this._node._dontTint) {
+ selParticle.color.r += selParticle.deltaColor.r * dt;
+ selParticle.color.g += selParticle.deltaColor.g * dt;
+ selParticle.color.b += selParticle.deltaColor.b * dt;
+ selParticle.color.a += selParticle.deltaColor.a * dt;
+ selParticle.isChangeColor = true;
+ }
+ };
+})();
diff --git a/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js b/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js
new file mode 100644
index 0000000000..7811947122
--- /dev/null
+++ b/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js
@@ -0,0 +1,401 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+(function(){
+ /**
+ * ParticleSystem's WebGL render command
+ */
+ cc.ParticleSystem.WebGLRenderCmd = function(renderable){
+ cc.Node.WebGLRenderCmd.call(this, renderable);
+ this._needDraw = true;
+
+ this._buffersVBO = [0, 0];
+ this._quads = [];
+ this._indices = [];
+ this._quadsArrayBuffer = null;
+ };
+ var proto = cc.ParticleSystem.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
+ proto.constructor = cc.ParticleSystem.WebGLRenderCmd;
+
+ proto.getDrawMode = function(){};
+ proto.setDrawMode = function(drawMode){};
+ proto.getShapeType = function(){};
+ proto.setShapeType = function(shapeType){};
+
+ proto.setBatchNode = function(batchNode){
+ var node = this._node;
+ if (node._batchNode !== batchNode) {
+ var oldBatch = node._batchNode;
+ node._batchNode = batchNode; //weak reference
+
+ if (batchNode) {
+ var locParticles = node._particles;
+ for (var i = 0; i < node._totalParticles; i++)
+ locParticles[i].atlasIndex = i;
+ }
+
+ // NEW: is self render ?
+ if (!batchNode) {
+ this._allocMemory();
+ this.initIndices(node._totalParticles);
+ node.setTexture(oldBatch.getTexture());
+ this._setupVBO();
+
+ } else if (!oldBatch) {
+ // OLD: was it self render cleanup ?
+ // copy current state to batch
+ node._batchNode.textureAtlas._copyQuadsToTextureAtlas(this._quads, node.atlasIndex);
+
+ //delete buffer
+ cc._renderContext.deleteBuffer(this._buffersVBO[1]); //where is re-bindBuffer code?
+ }
+ }
+ };
+
+ proto.initIndices = function (totalParticles) {
+ var locIndices = this._indices;
+ for (var i = 0, len = totalParticles; i < len; ++i) {
+ var i6 = i * 6;
+ var i4 = i * 4;
+ locIndices[i6 + 0] = i4 + 0;
+ locIndices[i6 + 1] = i4 + 1;
+ locIndices[i6 + 2] = i4 + 2;
+
+ locIndices[i6 + 5] = i4 + 1;
+ locIndices[i6 + 4] = i4 + 2;
+ locIndices[i6 + 3] = i4 + 3;
+ }
+ };
+
+ proto.isDifferentTexture = function(texture1, texture2){
+ return (texture1 === texture2);
+ };
+
+ proto.updateParticlePosition = function(particle, position){
+ // IMPORTANT: newPos may not be used as a reference here! (as it is just the temporary tpa point)
+ // the implementation of updateQuadWithParticle must use
+ // the x and y values directly
+ this.updateQuadWithParticle(particle, position);
+ };
+
+ proto.updateQuadWithParticle = function (particle, newPosition) {
+ var quad = null, node = this._node;
+ if (node._batchNode) {
+ var batchQuads = node._batchNode.textureAtlas.quads;
+ quad = batchQuads[node.atlasIndex + particle.atlasIndex];
+ node._batchNode.textureAtlas.dirty = true;
+ } else
+ quad = this._quads[node._particleIdx];
+
+ var r, g, b, a;
+ if (node._opacityModifyRGB) {
+ r = 0 | (particle.color.r * particle.color.a/255);
+ g = 0 | (particle.color.g * particle.color.a/255);
+ b = 0 | (particle.color.b * particle.color.a/255);
+ } else {
+ r = 0 | (particle.color.r );
+ g = 0 | (particle.color.g );
+ b = 0 | (particle.color.b );
+ }
+ a = 0 | (particle.color.a );
+
+ var blColors = quad.bl.colors, brColors = quad.br.colors, tlColors = quad.tl.colors, trColors = quad.tr.colors;
+ blColors.r = brColors.r = tlColors.r = trColors.r = r;
+ blColors.g = brColors.g = tlColors.g = trColors.g = g;
+ blColors.b = brColors.b = tlColors.b = trColors.b = b;
+ blColors.a = brColors.a = tlColors.a = trColors.a = a;
+
+ // vertices
+ var size_2 = particle.size / 2;
+ if (particle.rotation) {
+ var x1 = -size_2, y1 = -size_2;
+
+ var x2 = size_2, y2 = size_2;
+ var x = newPosition.x, y = newPosition.y;
+
+ var rad = -cc.degreesToRadians(particle.rotation);
+ var cr = Math.cos(rad), sr = Math.sin(rad);
+ var ax = x1 * cr - y1 * sr + x;
+ var ay = x1 * sr + y1 * cr + y;
+ var bx = x2 * cr - y1 * sr + x;
+ var by = x2 * sr + y1 * cr + y;
+ var cx = x2 * cr - y2 * sr + x;
+ var cy = x2 * sr + y2 * cr + y;
+ var dx = x1 * cr - y2 * sr + x;
+ var dy = x1 * sr + y2 * cr + y;
+
+ // bottom-left
+ quad.bl.vertices.x = ax;
+ quad.bl.vertices.y = ay;
+
+ // bottom-right vertex:
+ quad.br.vertices.x = bx;
+ quad.br.vertices.y = by;
+
+ // top-left vertex:
+ quad.tl.vertices.x = dx;
+ quad.tl.vertices.y = dy;
+
+ // top-right vertex:
+ quad.tr.vertices.x = cx;
+ quad.tr.vertices.y = cy;
+ } else {
+ // bottom-left vertex:
+ quad.bl.vertices.x = newPosition.x - size_2;
+ quad.bl.vertices.y = newPosition.y - size_2;
+
+ // bottom-right vertex:
+ quad.br.vertices.x = newPosition.x + size_2;
+ quad.br.vertices.y = newPosition.y - size_2;
+
+ // top-left vertex:
+ quad.tl.vertices.x = newPosition.x - size_2;
+ quad.tl.vertices.y = newPosition.y + size_2;
+
+ // top-right vertex:
+ quad.tr.vertices.x = newPosition.x + size_2;
+ quad.tr.vertices.y = newPosition.y + size_2;
+ }
+ };
+
+ proto.rendering = function (ctx) {
+ var node = this._node;
+ if (!node._texture)
+ return;
+
+ var gl = ctx || cc._renderContext;
+
+ this._shaderProgram.use();
+ this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix); //;
+
+ cc.glBindTexture2D(node._texture);
+ cc.glBlendFuncForParticle(node._blendFunc.src, node._blendFunc.dst);
+
+ //
+ // Using VBO without VAO
+ //
+ cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POS_COLOR_TEX);
+
+ gl.bindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]);
+ gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 24, 0); // vertices
+ gl.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, 24, 12); // colors
+ gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 24, 16); // tex coords
+
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._buffersVBO[1]);
+ gl.drawElements(gl.TRIANGLES, node._particleIdx * 6, gl.UNSIGNED_SHORT, 0);
+ };
+
+ proto.initTexCoordsWithRect = function(pointRect){
+ var node = this._node;
+ var texture = node.texture;
+ var scaleFactor = cc.contentScaleFactor();
+ // convert to pixels coords
+ var rect = cc.rect(
+ pointRect.x * scaleFactor,
+ pointRect.y * scaleFactor,
+ pointRect.width * scaleFactor,
+ pointRect.height * scaleFactor);
+
+ var wide = pointRect.width;
+ var high = pointRect.height;
+
+ if (texture) {
+ wide = texture.getPixelWidth();
+ high = texture.getPixelHeight();
+ }
+
+ var left, bottom, right, top;
+ if (cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL) {
+ left = (rect.x * 2 + 1) / (wide * 2);
+ bottom = (rect.y * 2 + 1) / (high * 2);
+ right = left + (rect.width * 2 - 2) / (wide * 2);
+ top = bottom + (rect.height * 2 - 2) / (high * 2);
+ } else {
+ left = rect.x / wide;
+ bottom = rect.y / high;
+ right = left + rect.width / wide;
+ top = bottom + rect.height / high;
+ }
+
+ // Important. Texture in cocos2d are inverted, so the Y component should be inverted
+ var temp = top;
+ top = bottom;
+ bottom = temp;
+
+ var quads;
+ var start = 0, end = 0;
+ if (node._batchNode) {
+ quads = node._batchNode.textureAtlas.quads;
+ start = node.atlasIndex;
+ end = node.atlasIndex + node._totalParticles;
+ } else {
+ quads = this._quads;
+ start = 0;
+ end = node._totalParticles;
+ }
+
+ for (var i = start; i < end; i++) {
+ if (!quads[i])
+ quads[i] = cc.V3F_C4B_T2F_QuadZero();
+
+ // bottom-left vertex:
+ var selQuad = quads[i];
+ selQuad.bl.texCoords.u = left;
+ selQuad.bl.texCoords.v = bottom;
+ // bottom-right vertex:
+ selQuad.br.texCoords.u = right;
+ selQuad.br.texCoords.v = bottom;
+ // top-left vertex:
+ selQuad.tl.texCoords.u = left;
+ selQuad.tl.texCoords.v = top;
+ // top-right vertex:
+ selQuad.tr.texCoords.u = right;
+ selQuad.tr.texCoords.v = top;
+ }
+ };
+
+ proto.setTotalParticles = function(tp){
+ var node = this._node;
+ // If we are setting the total numer of particles to a number higher
+ // than what is allocated, we need to allocate new arrays
+ if (tp > node._allocatedParticles) {
+ var quadSize = cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT;
+ // Allocate new memory
+ this._indices = new Uint16Array(tp * 6);
+ var locQuadsArrayBuffer = new ArrayBuffer(tp * quadSize);
+ //TODO need fix
+ // Assign pointers
+ var locParticles = node._particles;
+ locParticles.length = 0;
+ var locQuads = this._quads;
+ locQuads.length = 0;
+ for (var j = 0; j < tp; j++) {
+ locParticles[j] = new cc.Particle();
+ locQuads[j] = new cc.V3F_C4B_T2F_Quad(null, null, null, null, locQuadsArrayBuffer, j * quadSize);
+ }
+ node._allocatedParticles = tp;
+ node._totalParticles = tp;
+
+ // Init particles
+ if (node._batchNode) {
+ for (var i = 0; i < tp; i++)
+ locParticles[i].atlasIndex = i;
+ }
+
+ this._quadsArrayBuffer = locQuadsArrayBuffer;
+ this.initIndices(tp);
+ this._setupVBO();
+
+ //set the texture coord
+ if(node._texture){
+ this.initTexCoordsWithRect(cc.rect(0, 0, node._texture.width, node._texture.height));
+ }
+ } else
+ node._totalParticles = tp;
+ node.resetSystem();
+ };
+
+ proto.addParticle = function(){
+ var node = this._node,
+ particles = node._particles;
+ return particles[node.particleCount];
+ };
+
+ proto._setupVBO = function(){
+ var node = this;
+ var gl = cc._renderContext;
+
+ //gl.deleteBuffer(this._buffersVBO[0]);
+ this._buffersVBO[0] = gl.createBuffer();
+ gl.bindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]);
+ gl.bufferData(gl.ARRAY_BUFFER, this._quadsArrayBuffer, gl.DYNAMIC_DRAW);
+
+ this._buffersVBO[1] = gl.createBuffer();
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._buffersVBO[1]);
+ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this._indices, gl.STATIC_DRAW);
+
+ //cc.checkGLErrorDebug();
+ };
+
+ proto._allocMemory = function(){
+ var node = this._node;
+ //cc.assert((!this._quads && !this._indices), "Memory already allocated");
+ if(node._batchNode){
+ cc.log("cc.ParticleSystem._allocMemory(): Memory should not be allocated when not using batchNode");
+ return false;
+ }
+
+ var quadSize = cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT;
+ var totalParticles = node._totalParticles;
+ var locQuads = this._quads;
+ locQuads.length = 0;
+ this._indices = new Uint16Array(totalParticles * 6);
+ var locQuadsArrayBuffer = new ArrayBuffer(quadSize * totalParticles);
+
+ for (var i = 0; i < totalParticles; i++)
+ locQuads[i] = new cc.V3F_C4B_T2F_Quad(null, null, null, null, locQuadsArrayBuffer, i * quadSize);
+ if (!locQuads || !this._indices) {
+ cc.log("cocos2d: Particle system: not enough memory");
+ return false;
+ }
+ this._quadsArrayBuffer = locQuadsArrayBuffer;
+ return true;
+ };
+
+ proto.postStep = function(){
+ var gl = cc._renderContext;
+ gl.bindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]);
+ gl.bufferData(gl.ARRAY_BUFFER, this._quadsArrayBuffer, gl.DYNAMIC_DRAW);
+ };
+
+ proto._setBlendAdditive = function(){
+ var locBlendFunc = this._node._blendFunc;
+ if (this._texture && !this._texture.hasPremultipliedAlpha()) {
+ locBlendFunc.src = cc.SRC_ALPHA;
+ locBlendFunc.dst = cc.ONE_MINUS_SRC_ALPHA;
+ } else {
+ locBlendFunc.src = cc.BLEND_SRC;
+ locBlendFunc.dst = cc.BLEND_DST;
+ }
+ };
+
+ proto._initWithTotalParticles = function(totalParticles){
+ // allocating data space
+ if (!this._allocMemory())
+ return false;
+
+ this.initIndices(totalParticles);
+ this._setupVBO();
+
+ this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURECOLOR);
+ };
+
+ proto._updateDeltaColor = function (selParticle, dt) {
+ selParticle.color.r += selParticle.deltaColor.r * dt;
+ selParticle.color.g += selParticle.deltaColor.g * dt;
+ selParticle.color.b += selParticle.deltaColor.b * dt;
+ selParticle.color.a += selParticle.deltaColor.a * dt;
+ selParticle.isChangeColor = true;
+ };
+})();
\ No newline at end of file
diff --git a/cocos2d/particle/CCTIFFReader.js b/cocos2d/particle/CCTIFFReader.js
new file mode 100644
index 0000000000..185486539a
--- /dev/null
+++ b/cocos2d/particle/CCTIFFReader.js
@@ -0,0 +1,692 @@
+/****************************************************************************
+ Copyright (c) 2011 Gordon P. Hemsley
+ http://gphemsley.org/
+
+ 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.tiffReader is a singleton object, it's a tiff file reader, it can parse byte array to draw into a canvas
+ * @class
+ * @name cc.tiffReader
+ */
+cc.tiffReader = /** @lends cc.tiffReader# */{
+ _littleEndian: false,
+ _tiffData: null,
+ _fileDirectories: [],
+
+ getUint8: function (offset) {
+ return this._tiffData[offset];
+ },
+
+ getUint16: function (offset) {
+ if (this._littleEndian)
+ return (this._tiffData[offset + 1] << 8) | (this._tiffData[offset]);
+ else
+ return (this._tiffData[offset] << 8) | (this._tiffData[offset + 1]);
+ },
+
+ getUint32: function (offset) {
+ var a = this._tiffData;
+ if (this._littleEndian)
+ return (a[offset + 3] << 24) | (a[offset + 2] << 16) | (a[offset + 1] << 8) | (a[offset]);
+ else
+ return (a[offset] << 24) | (a[offset + 1] << 16) | (a[offset + 2] << 8) | (a[offset + 3]);
+ },
+
+ checkLittleEndian: function () {
+ var BOM = this.getUint16(0);
+
+ if (BOM === 0x4949) {
+ this.littleEndian = true;
+ } else if (BOM === 0x4D4D) {
+ this.littleEndian = false;
+ } else {
+ console.log(BOM);
+ throw TypeError("Invalid byte order value.");
+ }
+
+ return this.littleEndian;
+ },
+
+ hasTowel: function () {
+ // Check for towel.
+ if (this.getUint16(2) !== 42) {
+ throw RangeError("You forgot your towel!");
+ return false;
+ }
+
+ return true;
+ },
+
+ getFieldTypeName: function (fieldType) {
+ var typeNames = this.fieldTypeNames;
+ if (fieldType in typeNames) {
+ return typeNames[fieldType];
+ }
+ return null;
+ },
+
+ getFieldTagName: function (fieldTag) {
+ var tagNames = this.fieldTagNames;
+
+ if (fieldTag in tagNames) {
+ return tagNames[fieldTag];
+ } else {
+ console.log("Unknown Field Tag:", fieldTag);
+ return "Tag" + fieldTag;
+ }
+ },
+
+ getFieldTypeLength: function (fieldTypeName) {
+ if (['BYTE', 'ASCII', 'SBYTE', 'UNDEFINED'].indexOf(fieldTypeName) !== -1) {
+ return 1;
+ } else if (['SHORT', 'SSHORT'].indexOf(fieldTypeName) !== -1) {
+ return 2;
+ } else if (['LONG', 'SLONG', 'FLOAT'].indexOf(fieldTypeName) !== -1) {
+ return 4;
+ } else if (['RATIONAL', 'SRATIONAL', 'DOUBLE'].indexOf(fieldTypeName) !== -1) {
+ return 8;
+ }
+ return null;
+ },
+
+ getFieldValues: function (fieldTagName, fieldTypeName, typeCount, valueOffset) {
+ var fieldValues = [];
+ var fieldTypeLength = this.getFieldTypeLength(fieldTypeName);
+ var fieldValueSize = fieldTypeLength * typeCount;
+
+ if (fieldValueSize <= 4) {
+ // The value is stored at the big end of the valueOffset.
+ if (this.littleEndian === false)
+ fieldValues.push(valueOffset >>> ((4 - fieldTypeLength) * 8));
+ else
+ fieldValues.push(valueOffset);
+ } else {
+ for (var i = 0; i < typeCount; i++) {
+ var indexOffset = fieldTypeLength * i;
+ if (fieldTypeLength >= 8) {
+ if (['RATIONAL', 'SRATIONAL'].indexOf(fieldTypeName) !== -1) {
+ // Numerator
+ fieldValues.push(this.getUint32(valueOffset + indexOffset));
+ // Denominator
+ fieldValues.push(this.getUint32(valueOffset + indexOffset + 4));
+ } else {
+ cc.log("Can't handle this field type or size");
+ }
+ } else {
+ fieldValues.push(this.getBytes(fieldTypeLength, valueOffset + indexOffset));
+ }
+ }
+ }
+
+ if (fieldTypeName === 'ASCII') {
+ fieldValues.forEach(function (e, i, a) {
+ a[i] = String.fromCharCode(e);
+ });
+ }
+ return fieldValues;
+ },
+
+ getBytes: function (numBytes, offset) {
+ if (numBytes <= 0) {
+ cc.log("No bytes requested");
+ } else if (numBytes <= 1) {
+ return this.getUint8(offset);
+ } else if (numBytes <= 2) {
+ return this.getUint16(offset);
+ } else if (numBytes <= 3) {
+ return this.getUint32(offset) >>> 8;
+ } else if (numBytes <= 4) {
+ return this.getUint32(offset);
+ } else {
+ cc.log("Too many bytes requested");
+ }
+ },
+
+ getBits: function (numBits, byteOffset, bitOffset) {
+ bitOffset = bitOffset || 0;
+ var extraBytes = Math.floor(bitOffset / 8);
+ var newByteOffset = byteOffset + extraBytes;
+ var totalBits = bitOffset + numBits;
+ var shiftRight = 32 - numBits;
+ var shiftLeft,rawBits;
+
+ if (totalBits <= 0) {
+ console.log("No bits requested");
+ } else if (totalBits <= 8) {
+ shiftLeft = 24 + bitOffset;
+ rawBits = this.getUint8(newByteOffset);
+ } else if (totalBits <= 16) {
+ shiftLeft = 16 + bitOffset;
+ rawBits = this.getUint16(newByteOffset);
+ } else if (totalBits <= 32) {
+ shiftLeft = bitOffset;
+ rawBits = this.getUint32(newByteOffset);
+ } else {
+ console.log( "Too many bits requested" );
+ }
+
+ return {
+ 'bits': ((rawBits << shiftLeft) >>> shiftRight),
+ 'byteOffset': newByteOffset + Math.floor(totalBits / 8),
+ 'bitOffset': totalBits % 8
+ };
+ },
+
+ parseFileDirectory: function (byteOffset) {
+ var numDirEntries = this.getUint16(byteOffset);
+ var tiffFields = [];
+
+ for (var i = byteOffset + 2, entryCount = 0; entryCount < numDirEntries; i += 12, entryCount++) {
+ var fieldTag = this.getUint16(i);
+ var fieldType = this.getUint16(i + 2);
+ var typeCount = this.getUint32(i + 4);
+ var valueOffset = this.getUint32(i + 8);
+
+ var fieldTagName = this.getFieldTagName(fieldTag);
+ var fieldTypeName = this.getFieldTypeName(fieldType);
+ var fieldValues = this.getFieldValues(fieldTagName, fieldTypeName, typeCount, valueOffset);
+
+ tiffFields[fieldTagName] = { type: fieldTypeName, values: fieldValues };
+ }
+
+ this._fileDirectories.push(tiffFields);
+
+ var nextIFDByteOffset = this.getUint32(i);
+ if (nextIFDByteOffset !== 0x00000000) {
+ this.parseFileDirectory(nextIFDByteOffset);
+ }
+ },
+
+ clampColorSample: function(colorSample, bitsPerSample) {
+ var multiplier = Math.pow(2, 8 - bitsPerSample);
+
+ return Math.floor((colorSample * multiplier) + (multiplier - 1));
+ },
+
+ /**
+ * @function
+ * @param {Array} tiffData
+ * @param {HTMLCanvasElement} canvas
+ * @returns {*}
+ */
+ parseTIFF: function (tiffData, canvas) {
+ canvas = canvas || document.createElement('canvas');
+
+ this._tiffData = tiffData;
+ this.canvas = canvas;
+
+ this.checkLittleEndian();
+
+ if (!this.hasTowel()) {
+ return;
+ }
+
+ var firstIFDByteOffset = this.getUint32(4);
+
+ this._fileDirectories.length = 0;
+ this.parseFileDirectory(firstIFDByteOffset);
+
+ var fileDirectory = this._fileDirectories[0];
+
+ var imageWidth = fileDirectory['ImageWidth'].values[0];
+ var imageLength = fileDirectory['ImageLength'].values[0];
+
+ this.canvas.width = imageWidth;
+ this.canvas.height = imageLength;
+
+ var strips = [];
+
+ var compression = (fileDirectory['Compression']) ? fileDirectory['Compression'].values[0] : 1;
+
+ var samplesPerPixel = fileDirectory['SamplesPerPixel'].values[0];
+
+ var sampleProperties = [];
+
+ var bitsPerPixel = 0;
+ var hasBytesPerPixel = false;
+
+ fileDirectory['BitsPerSample'].values.forEach(function (bitsPerSample, i, bitsPerSampleValues) {
+ sampleProperties[i] = {
+ bitsPerSample: bitsPerSample,
+ hasBytesPerSample: false,
+ bytesPerSample: undefined
+ };
+
+ if ((bitsPerSample % 8) === 0) {
+ sampleProperties[i].hasBytesPerSample = true;
+ sampleProperties[i].bytesPerSample = bitsPerSample / 8;
+ }
+
+ bitsPerPixel += bitsPerSample;
+ }, this);
+
+ if ((bitsPerPixel % 8) === 0) {
+ hasBytesPerPixel = true;
+ var bytesPerPixel = bitsPerPixel / 8;
+ }
+
+ var stripOffsetValues = fileDirectory['StripOffsets'].values;
+ var numStripOffsetValues = stripOffsetValues.length;
+
+ // StripByteCounts is supposed to be required, but see if we can recover anyway.
+ if (fileDirectory['StripByteCounts']) {
+ var stripByteCountValues = fileDirectory['StripByteCounts'].values;
+ } else {
+ cc.log("Missing StripByteCounts!");
+
+ // Infer StripByteCounts, if possible.
+ if (numStripOffsetValues === 1) {
+ var stripByteCountValues = [Math.ceil((imageWidth * imageLength * bitsPerPixel) / 8)];
+ } else {
+ throw Error("Cannot recover from missing StripByteCounts");
+ }
+ }
+
+ // Loop through strips and decompress as necessary.
+ for (var i = 0; i < numStripOffsetValues; i++) {
+ var stripOffset = stripOffsetValues[i];
+ strips[i] = [];
+
+ var stripByteCount = stripByteCountValues[i];
+
+ // Loop through pixels.
+ for (var byteOffset = 0, bitOffset = 0, jIncrement = 1, getHeader = true, pixel = [], numBytes = 0, sample = 0, currentSample = 0;
+ byteOffset < stripByteCount; byteOffset += jIncrement) {
+ // Decompress strip.
+ switch (compression) {
+ // Uncompressed
+ case 1:
+ // Loop through samples (sub-pixels).
+ for (var m = 0, pixel = []; m < samplesPerPixel; m++) {
+ if (sampleProperties[m].hasBytesPerSample) {
+ // XXX: This is wrong!
+ var sampleOffset = sampleProperties[m].bytesPerSample * m;
+ pixel.push(this.getBytes(sampleProperties[m].bytesPerSample, stripOffset + byteOffset + sampleOffset));
+ } else {
+ var sampleInfo = this.getBits(sampleProperties[m].bitsPerSample, stripOffset + byteOffset, bitOffset);
+ pixel.push(sampleInfo.bits);
+ byteOffset = sampleInfo.byteOffset - stripOffset;
+ bitOffset = sampleInfo.bitOffset;
+
+ throw RangeError("Cannot handle sub-byte bits per sample");
+ }
+ }
+
+ strips[i].push(pixel);
+
+ if (hasBytesPerPixel) {
+ jIncrement = bytesPerPixel;
+ } else {
+ jIncrement = 0;
+ throw RangeError("Cannot handle sub-byte bits per pixel");
+ }
+ break;
+
+ // CITT Group 3 1-Dimensional Modified Huffman run-length encoding
+ case 2:
+ // XXX: Use PDF.js code?
+ break;
+
+ // Group 3 Fax
+ case 3:
+ // XXX: Use PDF.js code?
+ break;
+
+ // Group 4 Fax
+ case 4:
+ // XXX: Use PDF.js code?
+ break;
+
+ // LZW
+ case 5:
+ // XXX: Use PDF.js code?
+ break;
+
+ // Old-style JPEG (TIFF 6.0)
+ case 6:
+ // XXX: Use PDF.js code?
+ break;
+
+ // New-style JPEG (TIFF Specification Supplement 2)
+ case 7:
+ // XXX: Use PDF.js code?
+ break;
+
+ // PackBits
+ case 32773:
+ // Are we ready for a new block?
+ if (getHeader) {
+ getHeader = false;
+
+ var blockLength = 1;
+ var iterations = 1;
+
+ // The header byte is signed.
+ var header = this.getInt8(stripOffset + byteOffset);
+
+ if ((header >= 0) && (header <= 127)) { // Normal pixels.
+ blockLength = header + 1;
+ } else if ((header >= -127) && (header <= -1)) { // Collapsed pixels.
+ iterations = -header + 1;
+ } else /*if (header === -128)*/ { // Placeholder byte?
+ getHeader = true;
+ }
+ } else {
+ var currentByte = this.getUint8(stripOffset + byteOffset);
+
+ // Duplicate bytes, if necessary.
+ for (var m = 0; m < iterations; m++) {
+ if (sampleProperties[sample].hasBytesPerSample) {
+ // We're reading one byte at a time, so we need to handle multi-byte samples.
+ currentSample = (currentSample << (8 * numBytes)) | currentByte;
+ numBytes++;
+
+ // Is our sample complete?
+ if (numBytes === sampleProperties[sample].bytesPerSample) {
+ pixel.push(currentSample);
+ currentSample = numBytes = 0;
+ sample++;
+ }
+ } else {
+ throw RangeError("Cannot handle sub-byte bits per sample");
+ }
+
+ // Is our pixel complete?
+ if (sample === samplesPerPixel) {
+ strips[i].push(pixel);
+ pixel = [];
+ sample = 0;
+ }
+ }
+
+ blockLength--;
+
+ // Is our block complete?
+ if (blockLength === 0) {
+ getHeader = true;
+ }
+ }
+
+ jIncrement = 1;
+ break;
+
+ // Unknown compression algorithm
+ default:
+ // Do not attempt to parse the image data.
+ break;
+ }
+ }
+ }
+
+ if (canvas.getContext) {
+ var ctx = this.canvas.getContext("2d");
+
+ // Set a default fill style.
+ ctx.fillStyle = "rgba(255, 255, 255, 0)";
+
+ // If RowsPerStrip is missing, the whole image is in one strip.
+ var rowsPerStrip = fileDirectory['RowsPerStrip'] ? fileDirectory['RowsPerStrip'].values[0] : imageLength;
+
+ var numStrips = strips.length;
+
+ var imageLengthModRowsPerStrip = imageLength % rowsPerStrip;
+ var rowsInLastStrip = (imageLengthModRowsPerStrip === 0) ? rowsPerStrip : imageLengthModRowsPerStrip;
+
+ var numRowsInStrip = rowsPerStrip;
+ var numRowsInPreviousStrip = 0;
+
+ var photometricInterpretation = fileDirectory['PhotometricInterpretation'].values[0];
+
+ var extraSamplesValues = [];
+ var numExtraSamples = 0;
+
+ if (fileDirectory['ExtraSamples']) {
+ extraSamplesValues = fileDirectory['ExtraSamples'].values;
+ numExtraSamples = extraSamplesValues.length;
+ }
+
+ if (fileDirectory['ColorMap']) {
+ var colorMapValues = fileDirectory['ColorMap'].values;
+ var colorMapSampleSize = Math.pow(2, sampleProperties[0].bitsPerSample);
+ }
+
+ // Loop through the strips in the image.
+ for (var i = 0; i < numStrips; i++) {
+ // The last strip may be short.
+ if ((i + 1) === numStrips) {
+ numRowsInStrip = rowsInLastStrip;
+ }
+
+ var numPixels = strips[i].length;
+ var yPadding = numRowsInPreviousStrip * i;
+
+ // Loop through the rows in the strip.
+ for (var y = 0, j = 0; y < numRowsInStrip, j < numPixels; y++) {
+ // Loop through the pixels in the row.
+ for (var x = 0; x < imageWidth; x++, j++) {
+ var pixelSamples = strips[i][j];
+
+ var red = 0;
+ var green = 0;
+ var blue = 0;
+ var opacity = 1.0;
+
+ if (numExtraSamples > 0) {
+ for (var k = 0; k < numExtraSamples; k++) {
+ if (extraSamplesValues[k] === 1 || extraSamplesValues[k] === 2) {
+ // Clamp opacity to the range [0,1].
+ opacity = pixelSamples[3 + k] / 256;
+
+ break;
+ }
+ }
+ }
+
+ switch (photometricInterpretation) {
+ // Bilevel or Grayscale
+ // WhiteIsZero
+ case 0:
+ if (sampleProperties[0].hasBytesPerSample) {
+ var invertValue = Math.pow(0x10, sampleProperties[0].bytesPerSample * 2);
+ }
+
+ // Invert samples.
+ pixelSamples.forEach(function (sample, index, samples) {
+ samples[index] = invertValue - sample;
+ });
+
+ // Bilevel or Grayscale
+ // BlackIsZero
+ case 1:
+ red = green = blue = this.clampColorSample(pixelSamples[0], sampleProperties[0].bitsPerSample);
+ break;
+
+ // RGB Full Color
+ case 2:
+ red = this.clampColorSample(pixelSamples[0], sampleProperties[0].bitsPerSample);
+ green = this.clampColorSample(pixelSamples[1], sampleProperties[1].bitsPerSample);
+ blue = this.clampColorSample(pixelSamples[2], sampleProperties[2].bitsPerSample);
+ break;
+
+ // RGB Color Palette
+ case 3:
+ if (colorMapValues === undefined) {
+ throw Error("Palette image missing color map");
+ }
+
+ var colorMapIndex = pixelSamples[0];
+
+ red = this.clampColorSample(colorMapValues[colorMapIndex], 16);
+ green = this.clampColorSample(colorMapValues[colorMapSampleSize + colorMapIndex], 16);
+ blue = this.clampColorSample(colorMapValues[(2 * colorMapSampleSize) + colorMapIndex], 16);
+ break;
+
+ // Unknown Photometric Interpretation
+ default:
+ throw RangeError('Unknown Photometric Interpretation:', photometricInterpretation);
+ break;
+ }
+
+ ctx.fillStyle = "rgba(" + red + ", " + green + ", " + blue + ", " + opacity + ")";
+ ctx.fillRect(x, yPadding + y, 1, 1);
+ }
+ }
+
+ numRowsInPreviousStrip = numRowsInStrip;
+ }
+ }
+
+ return this.canvas;
+ },
+
+ // See: http://www.digitizationguidelines.gov/guidelines/TIFF_Metadata_Final.pdf
+ // See: http://www.digitalpreservation.gov/formats/content/tiff_tags.shtml
+ fieldTagNames: {
+ // TIFF Baseline
+ 0x013B: 'Artist',
+ 0x0102: 'BitsPerSample',
+ 0x0109: 'CellLength',
+ 0x0108: 'CellWidth',
+ 0x0140: 'ColorMap',
+ 0x0103: 'Compression',
+ 0x8298: 'Copyright',
+ 0x0132: 'DateTime',
+ 0x0152: 'ExtraSamples',
+ 0x010A: 'FillOrder',
+ 0x0121: 'FreeByteCounts',
+ 0x0120: 'FreeOffsets',
+ 0x0123: 'GrayResponseCurve',
+ 0x0122: 'GrayResponseUnit',
+ 0x013C: 'HostComputer',
+ 0x010E: 'ImageDescription',
+ 0x0101: 'ImageLength',
+ 0x0100: 'ImageWidth',
+ 0x010F: 'Make',
+ 0x0119: 'MaxSampleValue',
+ 0x0118: 'MinSampleValue',
+ 0x0110: 'Model',
+ 0x00FE: 'NewSubfileType',
+ 0x0112: 'Orientation',
+ 0x0106: 'PhotometricInterpretation',
+ 0x011C: 'PlanarConfiguration',
+ 0x0128: 'ResolutionUnit',
+ 0x0116: 'RowsPerStrip',
+ 0x0115: 'SamplesPerPixel',
+ 0x0131: 'Software',
+ 0x0117: 'StripByteCounts',
+ 0x0111: 'StripOffsets',
+ 0x00FF: 'SubfileType',
+ 0x0107: 'Threshholding',
+ 0x011A: 'XResolution',
+ 0x011B: 'YResolution',
+
+ // TIFF Extended
+ 0x0146: 'BadFaxLines',
+ 0x0147: 'CleanFaxData',
+ 0x0157: 'ClipPath',
+ 0x0148: 'ConsecutiveBadFaxLines',
+ 0x01B1: 'Decode',
+ 0x01B2: 'DefaultImageColor',
+ 0x010D: 'DocumentName',
+ 0x0150: 'DotRange',
+ 0x0141: 'HalftoneHints',
+ 0x015A: 'Indexed',
+ 0x015B: 'JPEGTables',
+ 0x011D: 'PageName',
+ 0x0129: 'PageNumber',
+ 0x013D: 'Predictor',
+ 0x013F: 'PrimaryChromaticities',
+ 0x0214: 'ReferenceBlackWhite',
+ 0x0153: 'SampleFormat',
+ 0x022F: 'StripRowCounts',
+ 0x014A: 'SubIFDs',
+ 0x0124: 'T4Options',
+ 0x0125: 'T6Options',
+ 0x0145: 'TileByteCounts',
+ 0x0143: 'TileLength',
+ 0x0144: 'TileOffsets',
+ 0x0142: 'TileWidth',
+ 0x012D: 'TransferFunction',
+ 0x013E: 'WhitePoint',
+ 0x0158: 'XClipPathUnits',
+ 0x011E: 'XPosition',
+ 0x0211: 'YCbCrCoefficients',
+ 0x0213: 'YCbCrPositioning',
+ 0x0212: 'YCbCrSubSampling',
+ 0x0159: 'YClipPathUnits',
+ 0x011F: 'YPosition',
+
+ // EXIF
+ 0x9202: 'ApertureValue',
+ 0xA001: 'ColorSpace',
+ 0x9004: 'DateTimeDigitized',
+ 0x9003: 'DateTimeOriginal',
+ 0x8769: 'Exif IFD',
+ 0x9000: 'ExifVersion',
+ 0x829A: 'ExposureTime',
+ 0xA300: 'FileSource',
+ 0x9209: 'Flash',
+ 0xA000: 'FlashpixVersion',
+ 0x829D: 'FNumber',
+ 0xA420: 'ImageUniqueID',
+ 0x9208: 'LightSource',
+ 0x927C: 'MakerNote',
+ 0x9201: 'ShutterSpeedValue',
+ 0x9286: 'UserComment',
+
+ // IPTC
+ 0x83BB: 'IPTC',
+
+ // ICC
+ 0x8773: 'ICC Profile',
+
+ // XMP
+ 0x02BC: 'XMP',
+
+ // GDAL
+ 0xA480: 'GDAL_METADATA',
+ 0xA481: 'GDAL_NODATA',
+
+ // Photoshop
+ 0x8649: 'Photoshop'
+ },
+
+ fieldTypeNames: {
+ 0x0001: 'BYTE',
+ 0x0002: 'ASCII',
+ 0x0003: 'SHORT',
+ 0x0004: 'LONG',
+ 0x0005: 'RATIONAL',
+ 0x0006: 'SBYTE',
+ 0x0007: 'UNDEFINED',
+ 0x0008: 'SSHORT',
+ 0x0009: 'SLONG',
+ 0x000A: 'SRATIONAL',
+ 0x000B: 'FLOAT',
+ 0x000C: 'DOUBLE'
+ }
+};
\ No newline at end of file
diff --git a/cocos2d/physics/CCPhysicsDebugNode.js b/cocos2d/physics/CCPhysicsDebugNode.js
new file mode 100644
index 0000000000..003bfe3f74
--- /dev/null
+++ b/cocos2d/physics/CCPhysicsDebugNode.js
@@ -0,0 +1,212 @@
+/****************************************************************************
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2012 Scott Lembcke and Howling Moon Software
+
+ 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.
+ ****************************************************************************/
+
+/*
+ IMPORTANT - READ ME!
+
+ This file sets pokes around in the private API a lot to provide efficient
+ debug rendering given nothing more than reference to a Chipmunk space.
+ It is not recommended to write rendering code like this in your own games
+ as the private API may change with little or no warning.
+ */
+
+/**
+ * Converts an array of numbers into an array of vectors(x,y)
+ * @function
+ * @param {Array} verts
+ * @return {Array}
+ */
+cc.__convertVerts = function (verts) {
+ var ret = [];
+ for (var i = 0; i < verts.length / 2; i++) {
+ ret[i] = {x:verts[i * 2], y:verts[i * 2 + 1]};
+ }
+ return ret;
+};
+
+/**
+ * color for body
+ * @function
+ * @param {cp.Body} body
+ * @return {cc.color}
+ */
+cc.ColorForBody = function (body) {
+ if (body.isRogue() || body.isSleeping()) {
+ return cc.color(128, 128, 128, 128);
+ } else if (body.nodeIdleTime > body.space.sleepTimeThreshold) {
+ return cc.color(84, 84, 84, 128);
+ } else {
+ return cc.color(255, 0, 0, 128);
+ }
+};
+
+/**
+ * draw shape
+ * @param {cp.Shape} shape
+ * @param renderer
+ */
+cc.DrawShape = function (shape, renderer) {
+ var body = shape.body;
+ var color = cc.ColorForBody(body);
+ switch (shape.collisionCode) {
+ case cp.CircleShape.prototype.collisionCode:
+ this.drawDot(shape.tc, Math.max(shape.r, 1.0), color);
+ this.drawSegment(shape.tc, cp.v.add(shape.tc, cp.v.mult(body.rot, shape.r)), 1.0, color);
+ break;
+ case cp.SegmentShape.prototype.collisionCode:
+ this.drawSegment(shape.ta, shape.tb, Math.max(shape.r, 2.0), color);
+ break;
+ case cp.PolyShape.prototype.collisionCode:
+ var line = cc.color(color.r, color.g, color.b, cc.lerp(color.a, 255, 0.5));
+ this.drawPoly(cc.__convertVerts(shape.tVerts), color, 1.0, line);
+ break;
+ default:
+ cc.log("cc.DrawShape(): Bad assertion in DrawShape()");
+ break;
+ }
+};
+
+/**
+ * draw constraint
+ * @param {cp.Constraint} constraint
+ * @param renderer
+ */
+cc.DrawConstraint = function (constraint, renderer) {
+ var body_a = constraint.a;
+ var body_b = constraint.b;
+ var a, b;
+
+ if (constraint instanceof cp.PinJoint) {
+ a = body_a.local2World(constraint.anchr1);
+ b = body_b.local2World(constraint.anchr2);
+ this.drawDot(a, 3.0, cc.CONSTRAINT_COLOR);
+ this.drawDot(b, 3.0, cc.CONSTRAINT_COLOR);
+ this.drawSegment(a, b, 1.0, cc.CONSTRAINT_COLOR);
+ } else if (constraint instanceof cp.SlideJoint) {
+ a = body_a.local2World(constraint.anchr1);
+ b = body_b.local2World(constraint.anchr2);
+
+ this.drawDot(a, 3.0, cc.CONSTRAINT_COLOR);
+ this.drawDot(b, 3.0, cc.CONSTRAINT_COLOR);
+ this.drawSegment(a, b, 1.0, cc.CONSTRAINT_COLOR);
+ } else if (constraint instanceof cp.PivotJoint) {
+ a = body_a.local2World(constraint.anchr1);
+ b = body_b.local2World(constraint.anchr2);
+ this.drawDot(a, 3.0, cc.CONSTRAINT_COLOR);
+ this.drawDot(b, 3.0, cc.CONSTRAINT_COLOR);
+ } else if (constraint instanceof cp.GrooveJoint) {
+ a = body_a.local2World(constraint.grv_a);
+ b = body_a.local2World(constraint.grv_b);
+ var c = body_b.local2World(constraint.anchr2);
+
+ this.drawDot(c, 3.0, cc.CONSTRAINT_COLOR);
+ this.drawSegment(a, b, 1.0, cc.CONSTRAINT_COLOR);
+ } else if (constraint instanceof cp.DampedSpring) {
+ // TODO
+ } else {
+ //printf("Cannot draw constraint\n");
+ }
+};
+
+/**
+ * @constant
+ * @type {cc.color}
+ */
+cc.CONSTRAINT_COLOR = cc.color(0, 255, 0, 128);
+
+
+/**
+ * A Node that draws the components of a physics engine.
+ * Supported physics engines:
+ * - Chipmunk
+ * - Objective-Chipmunk
+ *
+ * @class
+ * @extends cc.DrawNode
+ *
+ * @property {cp.Space} space Physic world space
+ */
+cc.PhysicsDebugNode = cc.DrawNode.extend({
+ _space:null,
+ _className:"PhysicsDebugNode",
+
+ /**
+ * constructor of cc.PhysicsDebugNode
+ * @param {cp.Space} space
+ */
+ ctor: function (space) {
+ cc.DrawNode.prototype.ctor.call(this);
+ this._space = space;
+ },
+
+ /**
+ * get space
+ * @returns {cp.Space}
+ */
+ getSpace:function () {
+ return this._space;
+ },
+
+ /**
+ * set space
+ * @param {cp.Space} space
+ */
+ setSpace:function (space) {
+ this._space = space;
+ },
+
+ /**
+ * draw
+ * @param {object} context
+ */
+ draw:function (context) {
+ if (!this._space)
+ return;
+
+ this._space.eachShape(cc.DrawShape.bind(this));
+ this._space.eachConstraint(cc.DrawConstraint.bind(this));
+ cc.DrawNode.prototype.draw.call(this);
+ this.clear();
+ },
+
+ _createRenderCmd: function(){
+ if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ return new cc.PhysicsDebugNode.CanvasRenderCmd(this);
+ else
+ return new cc.PhysicsDebugNode.WebGLRenderCmd(this);
+ }
+});
+
+/**
+ * Create a debug node for a regular Chipmunk space.
+ * @deprecated since v3.0, please use new cc.PhysicsDebugNode(space)
+ * @param {cp.Space} space
+ * @return {cc.PhysicsDebugNode}
+ */
+cc.PhysicsDebugNode.create = function (space) {
+ return new cc.PhysicsDebugNode(space);
+};
diff --git a/cocos2d/physics/CCPhysicsDebugNodeCanvasRenderCmd.js b/cocos2d/physics/CCPhysicsDebugNodeCanvasRenderCmd.js
new file mode 100644
index 0000000000..be1f6f14ba
--- /dev/null
+++ b/cocos2d/physics/CCPhysicsDebugNodeCanvasRenderCmd.js
@@ -0,0 +1,52 @@
+/****************************************************************************
+ 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.PhysicsDebugNode's rendering objects of Canvas
+ */
+(function(){
+ cc.PhysicsDebugNode.CanvasRenderCmd = function(renderableObject){
+ cc.Node.CanvasRenderCmd.call(this, renderableObject);
+ this._buffer = renderableObject._buffer;
+ this._needDraw = true;
+ };
+
+ var proto = cc.PhysicsDebugNode.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
+ proto.constructor = cc.PhysicsDebugNode.CanvasRenderCmd;
+
+ proto.rendering = function(ctx, scaleX, scaleY){
+ var node = this._node;
+ if (!node._space)
+ return;
+ node._space.eachShape(cc.DrawShape.bind(node));
+ node._space.eachConstraint(cc.DrawConstraint.bind(node));
+ cc.DrawNode.CanvasRenderCmd.prototype.rendering.call(this, ctx, scaleX, scaleY);
+ node.clear();
+ };
+
+ proto._drawDot = cc.DrawNode.CanvasRenderCmd.prototype._drawDot;
+ proto._drawSegment = cc.DrawNode.CanvasRenderCmd.prototype._drawSegment;
+ proto._drawPoly = cc.DrawNode.CanvasRenderCmd.prototype._drawPoly;
+
+})();
diff --git a/cocos2d/physics/CCPhysicsDebugNodeWebGLRenderCmd.js b/cocos2d/physics/CCPhysicsDebugNodeWebGLRenderCmd.js
new file mode 100644
index 0000000000..38ddf9f630
--- /dev/null
+++ b/cocos2d/physics/CCPhysicsDebugNodeWebGLRenderCmd.js
@@ -0,0 +1,53 @@
+/****************************************************************************
+ 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.PhysicsDebugNode's rendering objects of WebGL
+ */
+(function(){
+ cc.PhysicsDebugNode.WebGLRenderCmd = function (renderableObject) {
+ cc.Node.WebGLRenderCmd.call(this, renderableObject);
+ this._needDraw = true;
+ };
+
+ cc.PhysicsDebugNode.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
+ cc.PhysicsDebugNode.WebGLRenderCmd.prototype.constructor = cc.PhysicsDebugNode.WebGLRenderCmd;
+
+ cc.PhysicsDebugNode.WebGLRenderCmd.prototype.rendering = function (ctx) {
+ var node = this._node;
+ if (!node._space)
+ return;
+
+ node._space.eachShape(cc.DrawShape.bind(node));
+ node._space.eachConstraint(cc.DrawConstraint.bind(node));
+
+ //cc.DrawNode.prototype.draw.call(node);
+ cc.glBlendFunc(node._blendFunc.src, node._blendFunc.dst);
+ this._shaderProgram.use();
+ this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix);
+ node._render();
+
+ node.clear();
+ };
+})();
\ No newline at end of file
diff --git a/cocos2d/physics/CCPhysicsSprite.js b/cocos2d/physics/CCPhysicsSprite.js
new file mode 100644
index 0000000000..30d7bcdb11
--- /dev/null
+++ b/cocos2d/physics/CCPhysicsSprite.js
@@ -0,0 +1,447 @@
+/**
+ * Copyright (c) 2012 Scott Lembcke and Howling Moon Software
+ * Copyright (c) 2008-2010 Ricardo Quesada
+ * Copyright (c) 2011-2012 cocos2d-x.org
+ * Copyright (c) 2013-2014 Chukong Technologies Inc.
+ *
+ * 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 CCSprite subclass that is bound to a physics body.
+ It works with:
+ - Chipmunk: Preprocessor macro CC_ENABLE_CHIPMUNK_INTEGRATION should be defined
+ - Objective-Chipmunk: Preprocessor macro CC_ENABLE_CHIPMUNK_INTEGRATION should be defined
+ - Box2d: Preprocessor macro CC_ENABLE_BOX2D_INTEGRATION should be defined
+
+ Features and Limitations:
+ - Scale and Skew properties are ignored.
+ - Position and rotation are going to updated from the physics body
+ - If you update the rotation or position manually, the physics body will be updated
+ - You can't eble both Chipmunk support and Box2d support at the same time. Only one can be enabled at compile time
+ */
+(function () {
+ var box2dAPI = {
+ _ignoreBodyRotation:false,
+ _body:null,
+ _PTMRatio:32,
+ _rotation:1,
+ /**
+ * Create a PhysicsSprite with filename and rect
+ * Constructor of cc.PhysicsSprite for Box2d
+ * @param {String|cc.Texture2D|cc.SpriteFrame} fileName
+ * @param {cc.Rect} rect
+ * @example
+ *
+ * 1.Create a sprite with image path and rect
+ * var physicsSprite1 = new cc.PhysicsSprite("res/HelloHTML5World.png");
+ * var physicsSprite2 = new cc.PhysicsSprite("res/HelloHTML5World.png",cc.rect(0,0,480,320));
+ *
+ * 2.Create a sprite with a sprite frame name. Must add "#" before fame name.
+ * var physicsSprite = new cc.PhysicsSprite('#grossini_dance_01.png');
+ *
+ * 3.Create a sprite with a sprite frame
+ * var spriteFrame = cc.spriteFrameCache.getSpriteFrame("grossini_dance_01.png");
+ * var physicsSprite = new cc.PhysicsSprite(spriteFrame);
+ *
+ * 4.Creates a sprite with an existing texture contained in a CCTexture2D object
+ * After creation, the rect will be the size of the texture, and the offset will be (0,0).
+ * var texture = cc.textureCache.addImage("HelloHTML5World.png");
+ * var physicsSprite1 = new cc.PhysicsSprite(texture);
+ * var physicsSprite2 = new cc.PhysicsSprite(texture, cc.rect(0,0,480,320));
+ *
+ */
+ ctor:function(fileName, rect){
+ cc.Sprite.prototype.ctor.call(this);
+
+ if (fileName === undefined) {
+ cc.PhysicsSprite.prototype.init.call(this);
+ }else if (cc.js.isString(fileName)) {
+ if (fileName[0] === "#") {
+ //init with a sprite frame name
+ var frameName = fileName.substr(1, fileName.length - 1);
+ var spriteFrame = cc.spriteFrameCache.getSpriteFrame(frameName);
+ this.initWithSpriteFrame(spriteFrame);
+ } else {
+ //init with filename and rect
+ this.init(fileName, rect);
+ }
+ }else if (cc.js.isObject(fileName)) {
+ if (fileName instanceof cc.Texture2D) {
+ //init with texture and rect
+ this.initWithTexture(fileName, rect);
+ } else if (fileName instanceof cc.SpriteFrame) {
+ //init with a sprite frame
+ this.initWithSpriteFrame(fileName);
+ }
+ }
+ //this._transformCmd = new cc.PhysicsSpriteTransformCmdCanvas(this);
+ //cc.rendererCanvas.pushRenderCommand(this._transformCmd);
+ },
+
+ //visit: function(){
+ // cc.Sprite.prototype.visit.call(this);
+ // cc.rendererCanvas.pushRenderCommand(this._transformCmd);
+ //},
+
+ /**
+ * set body
+ * @param {Box2D.Dynamics.b2Body} body
+ */
+ setBody:function (body) {
+ this._body = body;
+ },
+
+ /**
+ * get body
+ * @return {Box2D.Dynamics.b2Body}
+ */
+ getBody:function () {
+ return this._body;
+ },
+
+ /**
+ * set PTM ratio
+ * @param {Number} r
+ */
+ setPTMRatio:function (r) {
+ this._PTMRatio = r;
+ },
+
+ /**
+ * get PTM ration
+ * @return {Number}
+ */
+ getPTMRatio:function () {
+ return this._PTMRatio;
+ },
+
+ /**
+ * get position
+ * @return {cc.Vec2}
+ */
+ getPosition:function () {
+ var pos = this._body.GetPosition();
+ var locPTMRatio =this._PTMRatio;
+ return cc.p(pos.x * locPTMRatio, pos.y * locPTMRatio);
+ },
+
+ /**
+ * set position
+ * @param {cc.Vec2} p
+ */
+ setPosition:function (p) {
+ var angle = this._body.GetAngle();
+ var locPTMRatio =this._PTMRatio;
+ this._body.setTransform(Box2D.b2Vec2(p.x / locPTMRatio, p.y / locPTMRatio), angle);
+ this.setNodeDirty();
+ },
+
+ /**
+ * get rotation
+ * @return {Number}
+ */
+ getRotation:function () {
+ return (this._ignoreBodyRotation ? cc.radiansToDegrees(this._rotationRadians) : cc.radiansToDegrees(this._body.GetAngle()));
+ },
+
+ /**
+ * set rotation
+ * @param {Number} r
+ */
+ setRotation:function (r) {
+ if (this._ignoreBodyRotation) {
+ this._rotation = r;
+ } else {
+ var locBody = this._body;
+ var p = locBody.GetPosition();
+ locBody.SetTransform(p, cc.degreesToRadians(r));
+ }
+ this.setNodeDirty();
+ },
+ _syncPosition:function () {
+ var pos = this._body.GetPosition();
+ this._position.x = pos.x * this._PTMRatio;
+ this._position.y = pos.y * this._PTMRatio;
+ this._rotationRadians = this._rotation * (Math.PI / 180);
+ },
+ _syncRotation:function () {
+ this._rotationRadians = this._body.GetAngle();
+ },
+ /**
+ * visit
+ */
+ visit:function () {
+ if (this._body && this._PTMRatio) {
+ this._syncPosition();
+ if (!this._ignoreBodyRotation)
+ this._syncRotation();
+ }
+ else {
+ cc.log("PhysicsSprite body or PTIMRatio was not set");
+ }
+ this._super();
+ },
+
+ /**
+ * set whether to ingore body's rotation
+ * @param {Boolean} b
+ */
+ setIgnoreBodyRotation: function(b) {
+ this._ignoreBodyRotation = b;
+ }
+ };
+
+ var chipmunkAPI = {
+ _ignoreBodyRotation:false,
+ _body:null, //physics body
+ _rotation:1,
+
+ /**
+ * Create a PhysicsSprite with filename and rect
+ * Constructor of cc.PhysicsSprite for chipmunk
+ * @param {String|cc.Texture2D|cc.SpriteFrame} fileName
+ * @param {cc.Rect} rect
+ * @example
+ *
+ * 1.Create a sprite with image path and rect
+ * var physicsSprite1 = new cc.PhysicsSprite("res/HelloHTML5World.png");
+ * var physicsSprite2 = new cc.PhysicsSprite("res/HelloHTML5World.png",cc.rect(0,0,480,320));
+ *
+ * 2.Create a sprite with a sprite frame name. Must add "#" before frame name.
+ * var physicsSprite = new cc.PhysicsSprite('#grossini_dance_01.png');
+ *
+ * 3.Create a sprite with a sprite frame
+ * var spriteFrame = cc.spriteFrameCache.getSpriteFrame("grossini_dance_01.png");
+ * var physicsSprite = new cc.PhysicsSprite(spriteFrame);
+ *
+ * 4.Creates a sprite with an exsiting texture contained in a CCTexture2D object
+ * After creation, the rect will be the size of the texture, and the offset will be (0,0).
+ * var texture = cc.textureCache.addImage("HelloHTML5World.png");
+ * var physicsSprite1 = new cc.PhysicsSprite(texture);
+ * var physicsSprite2 = new cc.PhysicsSprite(texture, cc.rect(0,0,480,320));
+ *
+ */
+ ctor:function(fileName, rect){
+ cc.Sprite.prototype.ctor.call(this);
+
+ if (fileName === undefined) {
+ cc.PhysicsSprite.prototype.init.call(this);
+ }else if (cc.js.isString(fileName)) {
+ if (fileName[0] === "#") {
+ //init with a sprite frame name
+ var frameName = fileName.substr(1, fileName.length - 1);
+ var spriteFrame = cc.spriteFrameCache.getSpriteFrame(frameName);
+ this.initWithSpriteFrame(spriteFrame);
+ } else {
+ //init with filename and rect
+ this.init(fileName, rect);
+ }
+ }else if (cc.js.isObject(fileName)) {
+ if (fileName instanceof cc.Texture2D) {
+ //init with texture and rect
+ this.initWithTexture(fileName, rect);
+ } else if (fileName instanceof cc.SpriteFrame) {
+ //init with a sprite frame
+ this.initWithSpriteFrame(fileName);
+ }
+ }
+
+ cc.renderer.pushRenderCommand(this._renderCmd);
+ },
+
+ visit: function(){
+ cc.renderer.pushRenderCommand(this._renderCmd);
+ cc.Sprite.prototype.visit.call(this);
+ },
+
+ /**
+ * set body
+ * @param {cp.Body} body
+ */
+ setBody:function (body) {
+ this._body = body;
+ },
+
+ /**
+ * get body
+ * @returns {cp.Body}
+ */
+ getBody:function () {
+ return this._body;
+ },
+
+ /**
+ * get position
+ * @return {cc.Vec2}
+ */
+ getPosition:function () {
+ var locBody = this._body;
+ return {x:locBody.p.x, y:locBody.p.y};
+ },
+
+ /**
+ * get position x
+ * @return {Number}
+ */
+ getPositionX:function () {
+ return this._body.p.x;
+ },
+
+ /**
+ * get position y
+ * @return {Number}
+ */
+ getPositionY:function () {
+ return this._body.p.y;
+ },
+
+ /**
+ * set position
+ * @param {cc.Vec2|Number}newPosOrxValue
+ * @param {Number}yValue
+ */
+ setPosition:function (newPosOrxValue, yValue) {
+ if (yValue === undefined) {
+ this._body.p.x = newPosOrxValue.x;
+ this._body.p.y = newPosOrxValue.y;
+ } else {
+ this._body.p.x = newPosOrxValue;
+ this._body.p.y = yValue;
+ }
+ //this._syncPosition();
+ },
+
+ /**
+ * set position x
+ * @param {Number} xValue
+ */
+ setPositionX:function (xValue) {
+ this._body.p.x = xValue;
+ //this._syncPosition();
+ },
+
+ /**
+ * set position y
+ * @param {Number} yValue
+ */
+ setPositionY:function (yValue) {
+ this._body.p.y = yValue;
+ //this._syncPosition();
+ },
+
+ _syncPosition:function () {
+ var locPosition = this._position, locBody = this._body;
+ if (locPosition.x !== locBody.p.x || locPosition.y !== locBody.p.y) {
+ cc.Sprite.prototype.setPosition.call(this, locBody.p.x, locBody.p.y);
+ }
+ },
+
+ /**
+ * get rotation
+ * @return {Number}
+ */
+ getRotation:function () {
+ return this._ignoreBodyRotation ? this._rotationX : -cc.radiansToDegrees(this._body.a);
+ },
+
+ /**
+ * set rotation
+ * @param {Number} r
+ */
+ setRotation:function (r) {
+ if (this._ignoreBodyRotation) {
+ cc.Sprite.prototype.setRotation.call(this, r);
+ } else {
+ this._body.a = -cc.degreesToRadians(r);
+ //this._syncRotation();
+ }
+ },
+ _syncRotation:function () {
+ if (this._rotationX !== -cc.radiansToDegrees(this._body.a)) {
+ cc.Sprite.prototype.setRotation.call(this, -cc.radiansToDegrees(this._body.a));
+ }
+ },
+
+ /**
+ * get the affine transform matrix of node to parent coordinate frame
+ * @return {cc.AffineTransform}
+ */
+ getNodeToParentTransform:function () {
+ return this._renderCmd.getNodeToParentTransform();
+ },
+
+ /**
+ * whether dirty
+ * @return {Boolean}
+ */
+ isDirty:function(){
+ return !this._body.isSleeping();
+ },
+ setDirty: function(){ },
+
+ /**
+ * set whether to ignore rotation of body
+ * @param {Boolean} b
+ */
+ setIgnoreBodyRotation: function(b) {
+ this._ignoreBodyRotation = b;
+ },
+
+ _createRenderCmd: function(){
+ if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ return new cc.PhysicsSprite.CanvasRenderCmd(this);
+ else
+ return new cc.PhysicsSprite.WebGLRenderCmd(this);
+ }
+ };
+ cc.PhysicsSprite = cc.Sprite.extend(chipmunkAPI);
+ cc.PhysicsSprite._className = "PhysicsSprite";
+ var _p = cc.PhysicsSprite.prototype;
+ // Extended properties
+ /** @expose */
+ _p.body;
+ cc.defineGetterSetter(_p, "body", _p.getBody, _p.setBody);
+ /** @expose */
+ _p.dirty;
+ cc.defineGetterSetter(_p, "dirty", _p.isDirty, _p.setDirty);
+
+
+ /**
+ * Create a PhysicsSprite with filename and rect
+ * @deprecated since v3.0, please use new cc.PhysicsSprite(fileName, rect) instead
+ * @param {String|cc.Texture2D|cc.SpriteFrame} fileName
+ * @param {cc.Rect} rect
+ * @return {cc.PhysicsSprite}
+ */
+ cc.PhysicsSprite.create = function (fileName, rect) {
+ return new cc.PhysicsSprite(fileName, rect);
+ };
+
+ /**
+ * @deprecated since v3.0, please use new cc.PhysicsSprite(spriteFrameName) instead
+ * @type {Function}
+ */
+ cc.PhysicsSprite.createWithSpriteFrameName = cc.PhysicsSprite.create;
+
+ /**
+ * @deprecated since v3.0, please use new cc.PhysicsSprite(spriteFrame) instead
+ * @type {Function}
+ */
+ cc.PhysicsSprite.createWithSpriteFrame = cc.PhysicsSprite.create;
+})();
diff --git a/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js b/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js
new file mode 100644
index 0000000000..ae95d94df9
--- /dev/null
+++ b/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js
@@ -0,0 +1,93 @@
+/****************************************************************************
+ 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.PhysicsSprite's rendering objects of Canvas
+ */
+(function(){
+ cc.PhysicsSprite.CanvasRenderCmd = function(renderableObject){
+ cc.Sprite.CanvasRenderCmd.call(this, renderableObject);
+ this._needDraw = true;
+ };
+
+ var proto = cc.PhysicsSprite.CanvasRenderCmd.prototype = Object.create(cc.Sprite.CanvasRenderCmd.prototype);
+ proto.constructor = cc.PhysicsSprite.CanvasRenderCmd;
+
+ proto.rendering = function(ctx, scaleX, scaleY){
+ // This is a special class
+ // Sprite can not obtain sign
+ // So here must to calculate of each frame
+ var node = this._node;
+ node._syncPosition();
+ if(!node._ignoreBodyRotation)
+ node._syncRotation();
+ this.transform(this.getParentRenderCmd());
+
+ cc.Sprite.CanvasRenderCmd.prototype.rendering.call(this, ctx, scaleX, scaleY);
+ };
+
+ proto.getNodeToParentTransform = function(){
+ var node = this._node;
+
+ var t = this._transform;// quick reference
+ // base position
+ var locBody = node._body, locScaleX = node._scaleX, locScaleY = node._scaleY, locAnchorPIP = this._anchorPointInPoints;
+ t.tx = locBody.p.x;
+ t.ty = locBody.p.y;
+
+ // rotation Cos and Sin
+ var radians = -locBody.a;
+ var Cos = 1, Sin = 0;
+ if (radians && !node._ignoreBodyRotation) {
+ Cos = Math.cos(radians);
+ Sin = Math.sin(radians);
+ }
+
+ // base abcd
+ t.a = t.d = Cos;
+ t.b = -Sin;
+ t.c = Sin;
+
+ // scale
+ if (locScaleX !== 1 || locScaleY !== 1) {
+ t.a *= locScaleX;
+ t.c *= locScaleX;
+ t.b *= locScaleY;
+ t.d *= locScaleY;
+ }
+
+ // adjust anchorPoint
+ t.tx += Cos * -locAnchorPIP.x * locScaleX + -Sin * locAnchorPIP.y * locScaleY;
+ t.ty -= Sin * -locAnchorPIP.x * locScaleX + Cos * locAnchorPIP.y * locScaleY;
+
+ // if ignore anchorPoint
+ if (this._ignoreAnchorPointForPosition) {
+ t.tx += locAnchorPIP.x;
+ t.ty += locAnchorPIP.y;
+ }
+
+ return this._transform;
+ };
+
+})();
\ No newline at end of file
diff --git a/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js b/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js
new file mode 100644
index 0000000000..339610ed36
--- /dev/null
+++ b/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js
@@ -0,0 +1,92 @@
+/****************************************************************************
+ 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.PhysicsSprite's rendering objects of WebGL
+ */
+(function(){
+ cc.PhysicsSprite.WebGLRenderCmd = function(renderableObject){
+ cc.Sprite.WebGLRenderCmd.call(this, renderableObject);
+ this._needDraw = true;
+ };
+
+ var proto = cc.PhysicsSprite.WebGLRenderCmd.prototype = Object.create(cc.Sprite.WebGLRenderCmd.prototype);
+ proto.constructor = cc.PhysicsSprite.WebGLRenderCmd;
+
+ proto.rendering = function(ctx){
+ // This is a special class
+ // Sprite can not obtain sign
+ // So here must to calculate of each frame
+ var node = this._node;
+ node._syncPosition();
+ if(!node._ignoreBodyRotation)
+ node._syncRotation();
+ this.transform(this.getParentRenderCmd(), true);
+
+ cc.Sprite.WebGLRenderCmd.prototype.rendering.call(this, ctx);
+ };
+
+ proto.getNodeToParentTransform = function(){
+ var node = this._node;
+ var locBody = node._body, locAnchorPIP = this._anchorPointInPoints, locScaleX = node._scaleX, locScaleY = node._scaleY;
+ var x = locBody.p.x;
+ var y = locBody.p.y;
+
+ if (this._ignoreAnchorPointForPosition) {
+ x += locAnchorPIP.x;
+ y += locAnchorPIP.y;
+ }
+
+ // Make matrix
+ var radians = locBody.a, c = 1, s=0;
+ if (radians && !node._ignoreBodyRotation) {
+ c = Math.cos(radians);
+ s = Math.sin(radians);
+ }
+
+ // Although scale is not used by physics engines, it is calculated just in case
+ // the sprite is animated (scaled up/down) using actions.
+ // For more info see: http://www.cocos2d-iphone.org/forum/topic/68990
+ if (!cc._rectEqualToZero(locAnchorPIP)) {
+ x += c * -locAnchorPIP.x * locScaleX + -s * -locAnchorPIP.y * locScaleY;
+ y += s * -locAnchorPIP.x * locScaleX + c * -locAnchorPIP.y * locScaleY;
+ }
+
+ // Rot, Translate Matrix
+ this._transform = cc.affineTransformMake(c * locScaleX, s * locScaleX,
+ -s * locScaleY, c * locScaleY, x, y);
+
+ return this._transform;
+ };
+
+ proto.updateTransform = function(){
+ var node = this._node;
+ var dirty = node.isDirty();
+ if(dirty){
+ var cmd = node._renderCmd;
+ cmd && cmd.setDirtyRecursively(true);
+ }
+ cc.Sprite.WebGLRenderCmd.prototype.updateTransform.call(this);
+ };
+})();
\ No newline at end of file
diff --git a/cocos2d/progress-timer/CCActionProgressTimer.js b/cocos2d/progress-timer/CCActionProgressTimer.js
new file mode 100644
index 0000000000..026af89750
--- /dev/null
+++ b/cocos2d/progress-timer/CCActionProgressTimer.js
@@ -0,0 +1,227 @@
+/****************************************************************************
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (C) 2010 Lam Pham
+
+ 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.
+ ****************************************************************************/
+
+/**
+ * Progress to percentage
+ * @class
+ * @extends cc.ActionInterval
+ * @param {Number} duration duration in seconds
+ * @param {Number} percent
+ * @example
+ * var to = new cc.ProgressTo(2, 100);
+ */
+cc.ProgressTo = cc.ActionInterval.extend(/** @lends cc.ProgressTo# */{
+ _to:0,
+ _from:0,
+
+ /**
+ * Creates a ProgressTo action with a duration and a percent
+ * Constructor of cc.ProgressTo
+ * @param {Number} duration duration in seconds
+ * @param {Number} percent
+ */
+ ctor: function(duration, percent){
+ cc.ActionInterval.prototype.ctor.call(this);
+ this._to = 0;
+ this._from = 0;
+
+ percent !== undefined && this.initWithDuration(duration, percent);
+ },
+
+ /** Initializes with a duration and a percent
+ * @param {Number} duration duration in seconds
+ * @param {Number} percent
+ * @return {Boolean}
+ */
+ initWithDuration:function (duration, percent) {
+ if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
+ this._to = percent;
+ return true;
+ }
+ return false;
+ },
+ /**
+ * return a new cc.ProgressTo, all the configuration is the same as the original
+ * @returns {cc.ProgressTo}
+ */
+ clone:function(){
+ var action = new cc.ProgressTo();
+ action.initWithDuration(this._duration, this._to);
+ return action;
+ },
+ /**
+ * reverse hasn't been supported
+ * @returns {null}
+ */
+ reverse: function(){
+ cc.log("cc.ProgressTo.reverse(): reverse hasn't been supported.");
+ return null;
+ },
+
+ /**
+ * start with a target
+ * @param {cc.Node} target
+ */
+ startWithTarget:function (target) {
+ cc.ActionInterval.prototype.startWithTarget.call(this, target);
+ this._from = target.percentage;
+ },
+
+ /**
+ * custom update
+ * @param {Number} time time in seconds
+ */
+ update:function (time) {
+ if (this.target instanceof cc.ProgressTimer)
+ this.target.percentage = this._from + (this._to - this._from) * time;
+ }
+});
+
+/**
+ * Creates and initializes with a duration and a percent
+ * @function
+ * @param {Number} duration duration in seconds
+ * @param {Number} percent
+ * @return {cc.ProgressTo}
+ * @example
+ * // example
+ * var to = cc.progressTo(2, 100);
+ */
+cc.progressTo = function (duration, percent) {
+ return new cc.ProgressTo(duration, percent);
+};
+/**
+ * Please use cc.progressTo instead
+ * Creates and initializes with a duration and a percent
+ * @static
+ * @deprecated since v3.0,please use cc.progressTo instead.
+ * @param {Number} duration duration in seconds
+ * @param {Number} percent
+ * @return {cc.ProgressTo}
+ */
+cc.ProgressTo.create = cc.progressTo;
+
+/**
+ * Progress from a percentage to another percentage
+ * @class
+ * @extends cc.ActionInterval
+ * @param {Number} duration duration in seconds
+ * @param {Number} fromPercentage
+ * @param {Number} toPercentage
+ * @example
+ * var fromTo = new cc.ProgressFromTo(2, 100.0, 0.0);
+ */
+cc.ProgressFromTo = cc.ActionInterval.extend(/** @lends cc.ProgressFromTo# */{
+ _to:0,
+ _from:0,
+
+ /**
+ * Creates and initializes the action with a duration, a "from" percentage and a "to" percentage
+ * Constructor of cc.ProgressFromTo
+ * @param {Number} duration duration in seconds
+ * @param {Number} fromPercentage
+ * @param {Number} toPercentage
+ */
+ ctor:function(duration, fromPercentage, toPercentage){
+ cc.ActionInterval.prototype.ctor.call(this);
+ this._to = 0;
+ this._from = 0;
+
+ toPercentage !== undefined && this.initWithDuration(duration, fromPercentage, toPercentage);
+ },
+
+ /** Initializes the action with a duration, a "from" percentage and a "to" percentage
+ * @param {Number} duration duration in seconds
+ * @param {Number} fromPercentage
+ * @param {Number} toPercentage
+ * @return {Boolean}
+ */
+ initWithDuration:function (duration, fromPercentage, toPercentage) {
+ if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
+ this._to = toPercentage;
+ this._from = fromPercentage;
+ return true;
+ }
+ return false;
+ },
+ /**
+ * return a new cc.ProgressTo, all the configuration is the same as the original
+ * @returns {cc.ProgressFromTo}
+ */
+ clone:function(){
+ var action = new cc.ProgressFromTo();
+ action.initWithDuration(this._duration, this._from, this._to);
+ return action;
+ },
+
+ /**
+ * @return {cc.ActionInterval}
+ */
+ reverse:function () {
+ return cc.progressFromTo(this._duration, this._to, this._from);
+ },
+
+ /**
+ * start with a target
+ * @param {cc.Node} target
+ */
+ startWithTarget:function (target) {
+ cc.ActionInterval.prototype.startWithTarget.call(this, target);
+ },
+
+ /**
+ * @param {Number} time time in seconds
+ */
+ update:function (time) {
+ if (this.target instanceof cc.ProgressTimer)
+ this.target.percentage = this._from + (this._to - this._from) * time;
+ }
+});
+
+/** Creates and initializes the action with a duration, a "from" percentage and a "to" percentage
+ * @function
+ * @param {Number} duration duration in seconds
+ * @param {Number} fromPercentage
+ * @param {Number} toPercentage
+ * @return {cc.ProgressFromTo}
+ * @example
+ * // example
+ * var fromTo = cc.progressFromTo(2, 100.0, 0.0);
+ */
+cc.progressFromTo = function (duration, fromPercentage, toPercentage) {
+ return new cc.ProgressFromTo(duration, fromPercentage, toPercentage);
+};
+/**
+ * Creates and initializes the action with a duration, a "from" percentage and a "to" percentage
+ * @static
+ * @deprecated since v3.0,please use cc.ProgressFromTo(duration, fromPercentage, toPercentage) instead.
+ * @param {Number} duration duration in seconds
+ * @param {Number} fromPercentage
+ * @param {Number} toPercentage
+ * @return {cc.ProgressFromTo}
+ */
+cc.ProgressFromTo.create = cc.progressFromTo;
diff --git a/cocos2d/progress-timer/CCProgressTimer.js b/cocos2d/progress-timer/CCProgressTimer.js
new file mode 100644
index 0000000000..65f103744b
--- /dev/null
+++ b/cocos2d/progress-timer/CCProgressTimer.js
@@ -0,0 +1,344 @@
+/****************************************************************************
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2010 Lam Pham
+
+ 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.Progresstimer is a subclass of cc.Node.
+ * It renders the inner sprite according to the percentage.
+ * The progress can be Radial, Horizontal or vertical.
+ * @class
+ * @extends cc.Node
+ *
+ * @property {cc.Vec2} midPoint - Midpoint is used to modify the progress start position.
+ * If you're using radials type then the midpoint changes the center point
+ * If you're using bar type the the midpoint changes the bar growth
+ * it expands from the center but clamps to the sprites edge so:
+ * you want a left to right then set the midpoint all the way to cc.p(0,y)
+ * you want a right to left then set the midpoint all the way to cc.p(1,y)
+ * you want a bottom to top then set the midpoint all the way to cc.p(x,0)
+ * you want a top to bottom then set the midpoint all the way to cc.p(x,1)
+ * @property {cc.Vec2} barChangeRate - This allows the bar type to move the component at a specific rate.
+ * @property {cc.ProgressTimer.Type} type - Type of the progress timer.
+ * @property {Number} percentage - Percentage to change progress, from 0 to 100.
+ * @property {cc.Sprite} sprite - The sprite to show the progress percentage.
+ * @property {Boolean} reverseDir - Indicate whether the direction is reversed.
+ *
+ */
+cc.ProgressTimer = cc.Node.extend(/** @lends cc.ProgressTimer# */{
+ _type:null,
+ _percentage:0.0,
+ _sprite:null,
+
+ _midPoint:null,
+ _barChangeRate:null,
+ _reverseDirection:false,
+ _className:"ProgressTimer",
+
+ /**
+ * constructor of cc.ProgressTimer
+ * @function
+ * @param {cc.Sprite} sprite
+ */
+ ctor: function(sprite){
+ cc.Node.prototype.ctor.call(this);
+
+ this._type = cc.ProgressTimer.Type.RADIAL;
+ this._percentage = 0.0;
+ this._midPoint = cc.p(0, 0);
+ this._barChangeRate = cc.p(0, 0);
+ this._reverseDirection = false;
+ this._sprite = null;
+
+ sprite && this.initWithSprite(sprite);
+ },
+
+ /**
+ * Midpoint is used to modify the progress start position.
+ * If you're using radials type then the midpoint changes the center point
+ * If you're using bar type the the midpoint changes the bar growth
+ * it expands from the center but clamps to the sprites edge so:
+ * you want a left to right then set the midpoint all the way to cc.p(0,y)
+ * you want a right to left then set the midpoint all the way to cc.p(1,y)
+ * you want a bottom to top then set the midpoint all the way to cc.p(x,0)
+ * you want a top to bottom then set the midpoint all the way to cc.p(x,1)
+ * @return {cc.Vec2}
+ */
+ getMidpoint:function () {
+ return cc.p(this._midPoint.x, this._midPoint.y);
+ },
+
+ /**
+ * Midpoint setter
+ * @param {cc.Vec2} mpoint
+ */
+ setMidpoint:function (mpoint) {
+ this._midPoint = cc.pClamp(mpoint, cc.p(0, 0), cc.p(1, 1));
+ },
+
+ /**
+ * This allows the bar type to move the component at a specific rate
+ * Set the component to 0 to make sure it stays at 100%.
+ * For example you want a left to right bar but not have the height stay 100%
+ * Set the rate to be cc.p(0,1); and set the midpoint to = cc.p(0,.5f);
+ * @return {cc.Vec2}
+ */
+ getBarChangeRate:function () {
+ return cc.p(this._barChangeRate.x, this._barChangeRate.y);
+ },
+
+ /**
+ * @param {cc.Vec2} barChangeRate
+ */
+ setBarChangeRate:function (barChangeRate) {
+ this._barChangeRate = cc.pClamp(barChangeRate, cc.p(0, 0), cc.p(1, 1));
+ },
+
+ /**
+ * Change the percentage to change progress
+ * @return {cc.ProgressTimer.Type}
+ */
+ getType:function () {
+ return this._type;
+ },
+
+ /**
+ * Percentages are from 0 to 100
+ * @return {Number}
+ */
+ getPercentage:function () {
+ return this._percentage;
+ },
+
+ /**
+ * The image to show the progress percentage, retain
+ * @return {cc.Sprite}
+ */
+ getSprite:function () {
+ return this._sprite;
+ },
+
+ /**
+ * from 0-100
+ * @param {Number} percentage
+ */
+ setPercentage:function (percentage) {
+ if (this._percentage !== percentage) {
+ this._percentage = cc.clampf(percentage, 0, 100);
+ this._renderCmd._updateProgress();
+ }
+ },
+ /**
+ * only use for jsbinding
+ * @param bValue
+ */
+ setOpacityModifyRGB:function (bValue) {
+ },
+ /**
+ * only use for jsbinding
+ * @returns {boolean}
+ */
+ isOpacityModifyRGB:function () {
+ return false;
+ },
+ /**
+ * return if reverse direction
+ * @returns {boolean}
+ */
+ isReverseDirection:function () {
+ return this._reverseDirection;
+ },
+
+ /**
+ * set color of sprite
+ * @param {cc.Color} color
+ */
+ setColor:function (color) {
+ this._sprite.color = color;
+ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty);
+ },
+
+ /**
+ * set opacity of sprite
+ * @param {Number} opacity
+ */
+ setOpacity:function (opacity) {
+ this._sprite.opacity = opacity;
+ //this._renderCmd._updateColor();
+ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.opacityDirty);
+ },
+
+ /**
+ * return color of sprite
+ * @return {cc.Color}
+ */
+ getColor:function () {
+ return this._sprite.color;
+ },
+
+ /**
+ * return Opacity of sprite
+ * @return {Number}
+ */
+ getOpacity:function () {
+ return this._sprite.opacity;
+ },
+
+ /**
+ * set reverse cc.ProgressTimer
+ * @function
+ * @param {Boolean} reverse
+ */
+ setReverseProgress: function(reverse){
+ if (this._reverseDirection !== reverse){
+ this._reverseDirection = reverse;
+ this._renderCmd.releaseData();
+ }
+ },
+
+ /**
+ * set sprite for cc.ProgressTimer
+ * @function
+ * @param {cc.Sprite} sprite
+ */
+ setSprite: function(sprite){
+ if (this._sprite !== sprite) {
+ this._sprite = sprite;
+ if(sprite)
+ this.setContentSize(sprite.width,sprite.height);
+ else
+ this.setContentSize(0,0);
+ this._renderCmd.releaseData();
+ }
+ },
+
+ /**
+ * set Progress type of cc.ProgressTimer
+ * @function
+ * @param {cc.ProgressTimer.Type} type
+ */
+ setType: function(type){
+ if (type !== this._type){
+ this._type = type;
+ this._renderCmd.releaseData();
+ }
+ },
+
+ /**
+ * Reverse Progress setter
+ * @function
+ * @param {Boolean} reverse
+ */
+ setReverseDirection: function(reverse){
+ if (this._reverseDirection !== reverse){
+ this._reverseDirection = reverse;
+ this._renderCmd.releaseData();
+ }
+ },
+
+ /**
+ * Initializes a progress timer with the sprite as the shape the timer goes through
+ * @function
+ * @param {cc.Sprite} sprite
+ * @return {Boolean}
+ */
+ initWithSprite: function(sprite){
+ this.percentage = 0;
+ this.setAnchorPoint(0.5,0.5);
+
+ this._type = cc.ProgressTimer.Type.RADIAL;
+ this._reverseDirection = false;
+ this.midPoint = cc.p(0.5, 0.5);
+ this.barChangeRate = cc.p(1, 1);
+ this.setSprite(sprite);
+ this._renderCmd.initCmd();
+ return true;
+ },
+
+ _createRenderCmd: function(){
+ if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ return new cc.ProgressTimer.CanvasRenderCmd(this);
+ else
+ return new cc.ProgressTimer.WebGLRenderCmd(this);
+ }
+});
+
+// Extended properties
+var _p = cc.ProgressTimer.prototype;
+
+/** @expose */
+_p.midPoint;
+cc.defineGetterSetter(_p, "midPoint", _p.getMidpoint, _p.setMidpoint);
+/** @expose */
+_p.barChangeRate;
+cc.defineGetterSetter(_p, "barChangeRate", _p.getBarChangeRate, _p.setBarChangeRate);
+/** @expose */
+_p.type;
+cc.defineGetterSetter(_p, "type", _p.getType, _p.setType);
+/** @expose */
+_p.percentage;
+cc.defineGetterSetter(_p, "percentage", _p.getPercentage, _p.setPercentage);
+/** @expose */
+_p.sprite;
+cc.defineGetterSetter(_p, "sprite", _p.getSprite, _p.setSprite);
+/** @expose */
+_p.reverseDir;
+cc.defineGetterSetter(_p, "reverseDir", _p.isReverseDirection, _p.setReverseDirection);
+
+
+/**
+ * create a progress timer object with image file name that renders the inner sprite according to the percentage
+ * @deprecated since v3.0,please use new cc.ProgressTimer(sprite) instead.
+ * @param {cc.Sprite} sprite
+ * @return {cc.ProgressTimer}
+ */
+cc.ProgressTimer.create = function (sprite) {
+ return new cc.ProgressTimer(sprite);
+};
+
+/**
+ * @constant
+ * @type Number
+ */
+cc.ProgressTimer.TEXTURE_COORDS_COUNT = 4;
+
+/**
+ * @constant
+ * @type Number
+ */
+cc.ProgressTimer.TEXTURE_COORDS = 0x4b;
+
+/**
+ * Enum for type of ProgressTimer
+ * @readonly
+ * @enum {number}
+ */
+cc.ProgressTimer.Type = cc.Enum({
+ /**
+ * Radial Counter-Clockwise
+ */
+ RADIAL: 0,
+ BAR: 1
+});
diff --git a/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js b/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js
new file mode 100644
index 0000000000..7015d944ea
--- /dev/null
+++ b/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js
@@ -0,0 +1,270 @@
+/****************************************************************************
+ 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.ProgressTimer's rendering objects of Canvas
+ */
+(function(){
+ cc.ProgressTimer.CanvasRenderCmd = function(renderableObject){
+ cc.Node.CanvasRenderCmd.call(this, renderableObject);
+ this._needDraw = true;
+
+ this._PI180 = Math.PI / 180;
+ this._barRect = cc.rect(0, 0, 0, 0);
+ this._origin = cc.p(0, 0);
+ this._radius = 0;
+ this._startAngle = 270;
+ this._endAngle = 270;
+ this._counterClockWise = false;
+ };
+
+ var proto = cc.ProgressTimer.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
+ proto.constructor = cc.ProgressTimer.CanvasRenderCmd;
+
+ proto.rendering = function (ctx, scaleX, scaleY) {
+ var wrapper = ctx || cc._renderContext,context = wrapper.getContext(), node = this._node, locSprite = node._sprite;
+ var locTextureCoord = locSprite._renderCmd._textureCoord, alpha = locSprite._renderCmd._displayedOpacity / 255;
+
+ if (locTextureCoord.width === 0 || locTextureCoord.height === 0)
+ return;
+ if (!locSprite._texture || !locTextureCoord.validRect || alpha === 0)
+ return;
+
+ wrapper.setTransform(this._worldTransform, scaleX, scaleY);
+ wrapper.setCompositeOperation(locSprite._blendFuncStr);
+ wrapper.setGlobalAlpha(alpha);
+
+ var locRect = locSprite._rect, locOffsetPosition = locSprite._offsetPosition;
+ var locX = locOffsetPosition.x,
+ locY = -locOffsetPosition.y - locRect.height,
+ locWidth = locRect.width,
+ locHeight = locRect.height;
+
+ wrapper.save();
+ if (locSprite._flippedX) {
+ locX = -locX - locWidth;
+ context.scale(-1, 1);
+ }
+ if (locSprite._flippedY) {
+ locY = locOffsetPosition.y;
+ context.scale(1, -1);
+ }
+
+ //clip
+ if (node._type === cc.ProgressTimer.Type.BAR) {
+ var locBarRect = this._barRect;
+ context.beginPath();
+ context.rect(locBarRect.x * scaleX, locBarRect.y * scaleY, locBarRect.width * scaleX, locBarRect.height * scaleY);
+ context.clip();
+ context.closePath();
+ } else if (node._type === cc.ProgressTimer.Type.RADIAL) {
+ var locOriginX = this._origin.x * scaleX;
+ var locOriginY = this._origin.y * scaleY;
+ context.beginPath();
+ context.arc(locOriginX, locOriginY, this._radius * scaleY, this._PI180 * this._startAngle, this._PI180 * this._endAngle, this._counterClockWise);
+ context.lineTo(locOriginX, locOriginY);
+ context.clip();
+ context.closePath();
+ }
+
+ //draw sprite
+ var image = locSprite._texture.getHtmlElementObj();
+ if (locSprite._renderCmd._colorized) {
+ context.drawImage(image,
+ 0, 0, locTextureCoord.width, locTextureCoord.height,
+ locX * scaleX, locY * scaleY, locWidth * scaleX, locHeight * scaleY);
+ } else {
+ context.drawImage(image,
+ locTextureCoord.renderX, locTextureCoord.renderY, locTextureCoord.width, locTextureCoord.height,
+ locX * scaleX, locY * scaleY, locWidth * scaleX, locHeight * scaleY);
+ }
+ wrapper.restore();
+ cc.g_NumberOfDraws++;
+ };
+
+ proto.releaseData = function(){};
+
+ proto.initCmd = function(){};
+
+ proto._updateProgress = function(){
+ var node = this._node;
+ var locSprite = node._sprite;
+ var sw = locSprite.width, sh = locSprite.height;
+ var locMidPoint = node._midPoint;
+
+ if (node._type === cc.ProgressTimer.Type.RADIAL) {
+ this._radius = Math.round(Math.sqrt(sw * sw + sh * sh));
+ var locStartAngle, locEndAngle, locCounterClockWise = false, locOrigin = this._origin;
+ locOrigin.x = sw * locMidPoint.x;
+ locOrigin.y = -sh * locMidPoint.y;
+
+ if (node._reverseDirection) {
+ locEndAngle = 270;
+ locStartAngle = 270 - 3.6 * node._percentage;
+ } else {
+ locStartAngle = -90;
+ locEndAngle = -90 + 3.6 * node._percentage;
+ }
+
+ if (locSprite._flippedX) {
+ locOrigin.x -= sw * (node._midPoint.x * 2);
+ locStartAngle = -locStartAngle;
+ locEndAngle = -locEndAngle;
+ locStartAngle -= 180;
+ locEndAngle -= 180;
+ locCounterClockWise = !locCounterClockWise;
+ }
+ if (locSprite._flippedY) {
+ locOrigin.y += sh * (node._midPoint.y * 2);
+ locCounterClockWise = !locCounterClockWise;
+ locStartAngle = -locStartAngle;
+ locEndAngle = -locEndAngle;
+ }
+
+ this._startAngle = locStartAngle;
+ this._endAngle = locEndAngle;
+ this._counterClockWise = locCounterClockWise;
+ } else {
+ var locBarChangeRate = node._barChangeRate;
+ var percentageF = node._percentage / 100;
+ var locBarRect = this._barRect;
+
+ var drewSize = cc.size((sw * (1 - locBarChangeRate.x)), (sh * (1 - locBarChangeRate.y)));
+ var drawingSize = cc.size((sw - drewSize.width) * percentageF, (sh - drewSize.height) * percentageF);
+ var currentDrawSize = cc.size(drewSize.width + drawingSize.width, drewSize.height + drawingSize.height);
+
+ var startPoint = cc.p(sw * locMidPoint.x, sh * locMidPoint.y);
+
+ var needToLeft = startPoint.x - currentDrawSize.width / 2;
+ if ((locMidPoint.x > 0.5) && (currentDrawSize.width / 2 >= sw - startPoint.x))
+ needToLeft = sw - currentDrawSize.width;
+
+ var needToTop = startPoint.y - currentDrawSize.height / 2;
+ if ((locMidPoint.y > 0.5) && (currentDrawSize.height / 2 >= sh - startPoint.y))
+ needToTop = sh - currentDrawSize.height;
+
+ //left pos
+ locBarRect.x = 0;
+ var flipXNeed = 1;
+ if (locSprite._flippedX) {
+ locBarRect.x -= currentDrawSize.width;
+ flipXNeed = -1;
+ }
+
+ if (needToLeft > 0)
+ locBarRect.x += needToLeft * flipXNeed;
+
+ //right pos
+ locBarRect.y = 0;
+ var flipYNeed = 1;
+ if (locSprite._flippedY) {
+ locBarRect.y += currentDrawSize.height;
+ flipYNeed = -1;
+ }
+
+ if (needToTop > 0)
+ locBarRect.y -= needToTop * flipYNeed;
+
+ //clip width and clip height
+ locBarRect.width = currentDrawSize.width;
+ locBarRect.height = -currentDrawSize.height;
+ }
+ };
+
+ proto._updateColor = function(){};
+
+ proto._syncStatus = function (parentCmd) {
+ var node = this._node;
+ if(!node._sprite)
+ return;
+ var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag;
+ var parentNode = parentCmd ? parentCmd._node : null;
+
+ if(parentNode && parentNode._cascadeColorEnabled && (parentCmd._dirtyFlag & flags.colorDirty))
+ locFlag |= flags.colorDirty;
+
+ if(parentNode && parentNode._cascadeOpacityEnabled && (parentCmd._dirtyFlag & flags.opacityDirty))
+ locFlag |= flags.opacityDirty;
+
+ if(parentCmd && (parentCmd._dirtyFlag & flags.transformDirty))
+ locFlag |= flags.transformDirty;
+
+ this._dirtyFlag = locFlag;
+
+ var spriteCmd = node._sprite._renderCmd;
+ var spriteFlag = spriteCmd._dirtyFlag;
+
+ var colorDirty = spriteFlag & flags.colorDirty,
+ opacityDirty = spriteFlag & flags.opacityDirty;
+
+ if (colorDirty){
+ spriteCmd._syncDisplayColor();
+ }
+
+ if (opacityDirty){
+ spriteCmd._syncDisplayOpacity();
+ }
+
+ if(colorDirty || opacityDirty){
+ spriteCmd._updateColor();
+ //this._updateColor();
+ }
+
+ if (locFlag & flags.transformDirty) {
+ //update the transform
+ this.transform(parentCmd);
+ }
+ };
+
+ proto.updateStatus = function () {
+ var node = this._node;
+ if(!node._sprite)
+ return;
+ var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag;
+ var spriteCmd = node._sprite._renderCmd;
+ var spriteFlag = spriteCmd._dirtyFlag;
+
+ var colorDirty = spriteFlag & flags.colorDirty,
+ opacityDirty = spriteFlag & flags.opacityDirty;
+
+ if(colorDirty){
+ spriteCmd._updateDisplayColor();
+ }
+
+ if(opacityDirty){
+ spriteCmd._updateDisplayOpacity();
+ }
+
+ if(colorDirty || opacityDirty){
+ spriteCmd._updateColor();
+ //this._updateColor();
+ }
+
+ if(locFlag & flags.transformDirty){
+ //update the transform
+ this.transform(this.getParentRenderCmd(), true);
+ }
+ this._dirtyFlag = 0;
+ };
+})();
\ No newline at end of file
diff --git a/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js b/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js
new file mode 100644
index 0000000000..cc14d703d5
--- /dev/null
+++ b/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js
@@ -0,0 +1,486 @@
+/****************************************************************************
+ 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.ProgressTimer's rendering objects of WebGL
+ */
+(function(){
+ cc.ProgressTimer.WebGLRenderCmd = function(renderableObject){
+ cc.Node.WebGLRenderCmd.call(this, renderableObject);
+ this._needDraw = true;
+
+ this._vertexWebGLBuffer = cc._renderContext.createBuffer();
+ this._vertexDataCount = 0;
+ this._vertexData = null;
+ this._vertexArrayBuffer = null;
+ this._vertexDataDirty = false;
+ };
+
+ var proto = cc.ProgressTimer.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
+ proto.constructor = cc.ProgressTimer.WebGLRenderCmd;
+
+ proto.rendering = function (ctx) {
+ var node = this._node;
+ var context = ctx || cc._renderContext;
+ if (!this._vertexData || !node._sprite)
+ return;
+
+ this._shaderProgram.use();
+ this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix);
+
+ var blendFunc = node._sprite._blendFunc;
+ cc.glBlendFunc(blendFunc.src, blendFunc.dst);
+ cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POS_COLOR_TEX);
+
+ cc.glBindTexture2D(node._sprite.texture);
+
+ context.bindBuffer(context.ARRAY_BUFFER, this._vertexWebGLBuffer);
+ if (this._vertexDataDirty) {
+ context.bufferData(context.ARRAY_BUFFER, this._vertexArrayBuffer, context.DYNAMIC_DRAW);
+ this._vertexDataDirty = false;
+ }
+ var locVertexDataLen = cc.V2F_C4B_T2F.BYTES_PER_ELEMENT;
+ context.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, context.FLOAT, false, locVertexDataLen, 0);
+ context.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, context.UNSIGNED_BYTE, true, locVertexDataLen, 8);
+ context.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, context.FLOAT, false, locVertexDataLen, 12);
+
+ if (node._type === cc.ProgressTimer.Type.RADIAL)
+ context.drawArrays(context.TRIANGLE_FAN, 0, this._vertexDataCount);
+ else if (node._type === cc.ProgressTimer.Type.BAR) {
+ if (!node._reverseDirection)
+ context.drawArrays(context.TRIANGLE_STRIP, 0, this._vertexDataCount);
+ else {
+ context.drawArrays(context.TRIANGLE_STRIP, 0, this._vertexDataCount / 2);
+ context.drawArrays(context.TRIANGLE_STRIP, 4, this._vertexDataCount / 2);
+ // 2 draw calls
+ cc.g_NumberOfDraws++;
+ }
+ }
+ cc.g_NumberOfDraws++;
+ };
+
+ proto._syncStatus = function (parentCmd) {
+ var node = this._node;
+ if(!node._sprite)
+ return;
+ var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag;
+ var parentNode = parentCmd ? parentCmd._node : null;
+
+ if(parentNode && parentNode._cascadeColorEnabled && (parentCmd._dirtyFlag & flags.colorDirty))
+ locFlag |= flags.colorDirty;
+ if(parentNode && parentNode._cascadeOpacityEnabled && (parentCmd._dirtyFlag & flags.opacityDirty))
+ locFlag |= flags.opacityDirty;
+ if(parentCmd && (parentCmd._dirtyFlag & flags.transformDirty))
+ locFlag |= flags.transformDirty;
+ this._dirtyFlag = locFlag;
+
+ var spriteCmd = node._sprite._renderCmd;
+ var spriteFlag = spriteCmd._dirtyFlag;
+
+ var colorDirty = spriteFlag & flags.colorDirty,
+ opacityDirty = spriteFlag & flags.opacityDirty;
+
+ if (colorDirty){
+ spriteCmd._syncDisplayColor();
+ }
+
+ if (opacityDirty){
+ spriteCmd._syncDisplayOpacity();
+ }
+
+ if(colorDirty || opacityDirty){
+ spriteCmd._updateColor();
+ this._updateColor();
+ }
+
+ //if (locFlag & flags.transformDirty) {
+ //update the transform
+ this.transform(parentCmd);
+ //}
+
+ spriteCmd._dirtyFlag = 0;
+ };
+
+ proto.updateStatus = function () {
+ var node = this._node;
+ if(!node._sprite)
+ return;
+ var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag;
+ var spriteCmd = node._sprite._renderCmd;
+ var spriteFlag = spriteCmd._dirtyFlag;
+
+ var colorDirty = spriteFlag & flags.colorDirty,
+ opacityDirty = spriteFlag & flags.opacityDirty;
+
+ if(colorDirty){
+ spriteCmd._updateDisplayColor();
+ this._dirtyFlag = this._dirtyFlag & flags.colorDirty ^ this._dirtyFlag;
+ }
+
+ if(opacityDirty){
+ spriteCmd._updateDisplayOpacity();
+ this._dirtyFlag = this._dirtyFlag & flags.opacityDirty ^ this._dirtyFlag;
+ }
+
+ if(colorDirty || opacityDirty){
+ spriteCmd._updateColor();
+ this._updateColor();
+ }
+
+ if(locFlag & flags.transformDirty){
+ //update the transform
+ this.transform(this.getParentRenderCmd(), true);
+ }
+ };
+
+ proto.releaseData = function(){
+ if (this._vertexData) {
+ //release all previous information
+ this._vertexData = null;
+ this._vertexArrayBuffer = null;
+ this._vertexDataCount = 0;
+ }
+ };
+
+ proto.initCmd = function(){
+ this._vertexData = null;
+ this._vertexArrayBuffer = null;
+ this._vertexDataCount = 0;
+
+ //shader program
+ this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURECOLOR);
+ };
+
+ proto._updateProgress = function(){
+ var node = this._node;
+ var locType = node._type;
+ if(locType === cc.ProgressTimer.Type.RADIAL)
+ this._updateRadial();
+ else if(locType === cc.ProgressTimer.Type.BAR)
+ this._updateBar();
+ this._vertexDataDirty = true;
+ };
+
+ /**
+ *
+ * Update does the work of mapping the texture onto the triangles for the bar
+ * It now doesn't occur the cost of free/alloc data every update cycle.
+ * It also only changes the percentage point but no other points if they have not been modified.
+ *
+ * It now deals with flipped texture. If you run into this problem, just use the
+ * sprite property and enable the methods flipX, flipY.
+ *
+ * @private
+ */
+ proto._updateBar = function(){
+ var node = this._node;
+ if (!node._sprite)
+ return;
+
+ var i, alpha = node._percentage / 100.0;
+ var locBarChangeRate = node._barChangeRate;
+ var alphaOffset = cc.pMult(cc.p((1.0 - locBarChangeRate.x) + alpha * locBarChangeRate.x,
+ (1.0 - locBarChangeRate.y) + alpha * locBarChangeRate.y), 0.5);
+ var min = cc.pSub(node._midPoint, alphaOffset), max = cc.pAdd(node._midPoint, alphaOffset);
+
+ if (min.x < 0) {
+ max.x += -min.x;
+ min.x = 0;
+ }
+
+ if (max.x > 1) {
+ min.x -= max.x - 1;
+ max.x = 1;
+ }
+
+ if (min.y < 0) {
+ max.y += -min.y;
+ min.y = 0;
+ }
+
+ if (max.y > 1) {
+ min.y -= max.y - 1;
+ max.y = 1;
+ }
+
+ var locVertexData;
+ if (!this._reverseDirection) {
+ if (!this._vertexData) {
+ this._vertexDataCount = 4;
+ var vertexDataLen = cc.V2F_C4B_T2F.BYTES_PER_ELEMENT, locCount = 4;
+ this._vertexArrayBuffer = new ArrayBuffer(locCount * vertexDataLen);
+ this._vertexData = [];
+ for (i = 0; i < locCount; i++)
+ this._vertexData[i] = new cc.V2F_C4B_T2F(null, null, null, this._vertexArrayBuffer, i * vertexDataLen);
+ }
+
+ locVertexData = this._vertexData;
+ // TOPLEFT
+ locVertexData[0].texCoords = this._textureCoordFromAlphaPoint(cc.p(min.x, max.y));
+ locVertexData[0].vertices = this._vertexFromAlphaPoint(cc.p(min.x, max.y));
+
+ // BOTLEFT
+ locVertexData[1].texCoords = this._textureCoordFromAlphaPoint(cc.p(min.x, min.y));
+ locVertexData[1].vertices = this._vertexFromAlphaPoint(cc.p(min.x, min.y));
+
+ // TOPRIGHT
+ locVertexData[2].texCoords = this._textureCoordFromAlphaPoint(cc.p(max.x, max.y));
+ locVertexData[2].vertices = this._vertexFromAlphaPoint(cc.p(max.x, max.y));
+
+ // BOTRIGHT
+ locVertexData[3].texCoords = this._textureCoordFromAlphaPoint(cc.p(max.x, min.y));
+ locVertexData[3].vertices = this._vertexFromAlphaPoint(cc.p(max.x, min.y));
+ } else {
+ if (!this._vertexData) {
+ this._vertexDataCount = 8;
+ var rVertexDataLen = cc.V2F_C4B_T2F.BYTES_PER_ELEMENT, rLocCount = 8;
+ this._vertexArrayBuffer = new ArrayBuffer(rLocCount * rVertexDataLen);
+ var rTempData = [];
+ for (i = 0; i < rLocCount; i++)
+ rTempData[i] = new cc.V2F_C4B_T2F(null, null, null, this._vertexArrayBuffer, i * rVertexDataLen);
+ // TOPLEFT 1
+ rTempData[0].texCoords = this._textureCoordFromAlphaPoint(cc.p(0, 1));
+ rTempData[0].vertices = this._vertexFromAlphaPoint(cc.p(0, 1));
+
+ // BOTLEFT 1
+ rTempData[1].texCoords = this._textureCoordFromAlphaPoint(cc.p(0, 0));
+ rTempData[1].vertices = this._vertexFromAlphaPoint(cc.p(0, 0));
+
+ // TOPRIGHT 2
+ rTempData[6].texCoords = this._textureCoordFromAlphaPoint(cc.p(1, 1));
+ rTempData[6].vertices = this._vertexFromAlphaPoint(cc.p(1, 1));
+
+ // BOTRIGHT 2
+ rTempData[7].texCoords = this._textureCoordFromAlphaPoint(cc.p(1, 0));
+ rTempData[7].vertices = this._vertexFromAlphaPoint(cc.p(1, 0));
+
+ this._vertexData = rTempData;
+ }
+
+ locVertexData = this._vertexData;
+ // TOPRIGHT 1
+ locVertexData[2].texCoords = this._textureCoordFromAlphaPoint(cc.p(min.x, max.y));
+ locVertexData[2].vertices = this._vertexFromAlphaPoint(cc.p(min.x, max.y));
+
+ // BOTRIGHT 1
+ locVertexData[3].texCoords = this._textureCoordFromAlphaPoint(cc.p(min.x, min.y));
+ locVertexData[3].vertices = this._vertexFromAlphaPoint(cc.p(min.x, min.y));
+
+ // TOPLEFT 2
+ locVertexData[4].texCoords = this._textureCoordFromAlphaPoint(cc.p(max.x, max.y));
+ locVertexData[4].vertices = this._vertexFromAlphaPoint(cc.p(max.x, max.y));
+
+ // BOTLEFT 2
+ locVertexData[5].texCoords = this._textureCoordFromAlphaPoint(cc.p(max.x, min.y));
+ locVertexData[5].vertices = this._vertexFromAlphaPoint(cc.p(max.x, min.y));
+ }
+ this._updateColor();
+ };
+
+ /**
+ *
+ * Update does the work of mapping the texture onto the triangles
+ * It now doesn't occur the cost of free/alloc data every update cycle.
+ * It also only changes the percentage point but no other points if they have not been modified.
+ *
+ * It now deals with flipped texture. If you run into this problem, just use the
+ * sprite property and enable the methods flipX, flipY.
+ *
+ * @private
+ */
+ proto._updateRadial = function () {
+ var node = this._node;
+ if (!node._sprite)
+ return;
+
+ var i, locMidPoint = node._midPoint;
+ var alpha = node._percentage / 100;
+ var angle = 2 * (cc.PI) * ( node._reverseDirection ? alpha : 1.0 - alpha);
+
+ // We find the vector to do a hit detection based on the percentage
+ // We know the first vector is the one @ 12 o'clock (top,mid) so we rotate
+ // from that by the progress angle around the m_tMidpoint pivot
+ var topMid = cc.p(locMidPoint.x, 1);
+ var percentagePt = cc.pRotateByAngle(topMid, locMidPoint, angle);
+
+ var index = 0;
+ var hit;
+
+ if (alpha === 0) {
+ // More efficient since we don't always need to check intersection
+ // If the alpha is zero then the hit point is top mid and the index is 0.
+ hit = topMid;
+ index = 0;
+ } else if (alpha === 1) {
+ // More efficient since we don't always need to check intersection
+ // If the alpha is one then the hit point is top mid and the index is 4.
+ hit = topMid;
+ index = 4;
+ } else {
+ // We run a for loop checking the edges of the texture to find the
+ // intersection point
+ // We loop through five points since the top is split in half
+
+ var min_t = cc.FLT_MAX;
+ var locProTextCoordsCount = cc.ProgressTimer.TEXTURE_COORDS_COUNT;
+ for (i = 0; i <= locProTextCoordsCount; ++i) {
+ var pIndex = (i + (locProTextCoordsCount - 1)) % locProTextCoordsCount;
+
+ var edgePtA = this._boundaryTexCoord(i % locProTextCoordsCount);
+ var edgePtB = this._boundaryTexCoord(pIndex);
+
+ // Remember that the top edge is split in half for the 12 o'clock position
+ // Let's deal with that here by finding the correct endpoints
+ if (i === 0)
+ edgePtB = cc.pLerp(edgePtA, edgePtB, 1 - locMidPoint.x);
+ else if (i === 4)
+ edgePtA = cc.pLerp(edgePtA, edgePtB, 1 - locMidPoint.x);
+
+ // retPoint are returned by ccpLineIntersect
+ var retPoint = cc.p(0, 0);
+ if (cc.pLineIntersect(edgePtA, edgePtB, locMidPoint, percentagePt, retPoint)) {
+ // Since our hit test is on rays we have to deal with the top edge
+ // being in split in half so we have to test as a segment
+ if ((i === 0 || i === 4)) {
+ // s represents the point between edgePtA--edgePtB
+ if (!(0 <= retPoint.x && retPoint.x <= 1))
+ continue;
+ }
+ // As long as our t isn't negative we are at least finding a
+ // correct hitpoint from m_tMidpoint to percentagePt.
+ if (retPoint.y >= 0) {
+ // Because the percentage line and all the texture edges are
+ // rays we should only account for the shortest intersection
+ if (retPoint.y < min_t) {
+ min_t = retPoint.y;
+ index = i;
+ }
+ }
+ }
+ }
+
+ // Now that we have the minimum magnitude we can use that to find our intersection
+ hit = cc.pAdd(locMidPoint, cc.pMult(cc.pSub(percentagePt, locMidPoint), min_t));
+ }
+
+ // The size of the vertex data is the index from the hitpoint
+ // the 3 is for the m_tMidpoint, 12 o'clock point and hitpoint position.
+ var sameIndexCount = true;
+ if (this._vertexDataCount !== index + 3) {
+ sameIndexCount = false;
+ this._vertexData = null;
+ this._vertexArrayBuffer = null;
+ this._vertexDataCount = 0;
+ }
+
+ if (!this._vertexData) {
+ this._vertexDataCount = index + 3;
+ var locCount = this._vertexDataCount, vertexDataLen = cc.V2F_C4B_T2F.BYTES_PER_ELEMENT;
+ this._vertexArrayBuffer = new ArrayBuffer(locCount * vertexDataLen);
+ var locData = [];
+ for (i = 0; i < locCount; i++)
+ locData[i] = new cc.V2F_C4B_T2F(null, null, null, this._vertexArrayBuffer, i * vertexDataLen);
+
+ this._vertexData = locData;
+ if(!this._vertexData){
+ cc.log( "cc.ProgressTimer._updateRadial() : Not enough memory");
+ return;
+ }
+ }
+ this._updateColor();
+
+ var locVertexData = this._vertexData;
+ if (!sameIndexCount) {
+ // First we populate the array with the m_tMidpoint, then all
+ // vertices/texcoords/colors of the 12 'o clock start and edges and the hitpoint
+ locVertexData[0].texCoords = this._textureCoordFromAlphaPoint(locMidPoint);
+ locVertexData[0].vertices = this._vertexFromAlphaPoint(locMidPoint);
+
+ locVertexData[1].texCoords = this._textureCoordFromAlphaPoint(topMid);
+ locVertexData[1].vertices = this._vertexFromAlphaPoint(topMid);
+
+ for (i = 0; i < index; i++) {
+ var alphaPoint = this._boundaryTexCoord(i);
+ locVertexData[i + 2].texCoords = this._textureCoordFromAlphaPoint(alphaPoint);
+ locVertexData[i + 2].vertices = this._vertexFromAlphaPoint(alphaPoint);
+ }
+ }
+
+ // hitpoint will go last
+ locVertexData[this._vertexDataCount - 1].texCoords = this._textureCoordFromAlphaPoint(hit);
+ locVertexData[this._vertexDataCount - 1].vertices = this._vertexFromAlphaPoint(hit);
+ };
+
+ proto._boundaryTexCoord = function (index) {
+ if (index < cc.ProgressTimer.TEXTURE_COORDS_COUNT) {
+ var locProTextCoords = cc.ProgressTimer.TEXTURE_COORDS;
+ if (this._node._reverseDirection)
+ return cc.p((locProTextCoords >> (7 - (index << 1))) & 1, (locProTextCoords >> (7 - ((index << 1) + 1))) & 1);
+ else
+ return cc.p((locProTextCoords >> ((index << 1) + 1)) & 1, (locProTextCoords >> (index << 1)) & 1);
+ }
+ return cc.p(0,0);
+ };
+
+ proto._textureCoordFromAlphaPoint = function (alpha) {
+ var locSprite = this._node._sprite;
+ if (!locSprite) {
+ return {u:0, v:0}; //new cc.Tex2F(0, 0);
+ }
+ var quad = locSprite.quad;
+ var min = cc.p(quad.bl.texCoords.u, quad.bl.texCoords.v);
+ var max = cc.p(quad.tr.texCoords.u, quad.tr.texCoords.v);
+
+ // Fix bug #1303 so that progress timer handles sprite frame texture rotation
+ if (locSprite.textureRectRotated) {
+ var temp = alpha.x;
+ alpha.x = alpha.y;
+ alpha.y = temp;
+ }
+ return {u: min.x * (1 - alpha.x) + max.x * alpha.x, v: min.y * (1 - alpha.y) + max.y * alpha.y};
+ };
+
+ proto._vertexFromAlphaPoint = function (alpha) {
+ var locSprite = this._node._sprite;
+ if (!locSprite) {
+ return {x: 0, y: 0};
+ }
+ var quad = locSprite.quad;
+ var min = cc.p(quad.bl.vertices.x, quad.bl.vertices.y);
+ var max = cc.p(quad.tr.vertices.x, quad.tr.vertices.y);
+ return {x: min.x * (1 - alpha.x) + max.x * alpha.x, y: min.y * (1 - alpha.y) + max.y * alpha.y};
+ };
+
+ proto._updateColor = function(){
+ var node = this._node;
+ if (!node._sprite || !this._vertexData)
+ return;
+
+ var sc = node._sprite.quad.tl.colors;
+ var locVertexData = this._vertexData;
+ for (var i = 0, len = this._vertexDataCount; i < len; ++i)
+ locVertexData[i].colors = sc;
+ this._vertexDataDirty = true;
+ };
+})();
\ No newline at end of file
diff --git a/cocos2d/render-texture/CCRenderTexture.js b/cocos2d/render-texture/CCRenderTexture.js
new file mode 100644
index 0000000000..24c8d7ea07
--- /dev/null
+++ b/cocos2d/render-texture/CCRenderTexture.js
@@ -0,0 +1,406 @@
+/****************************************************************************
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2009 Jason Booth
+
+ 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.
+ ****************************************************************************/
+
+/**
+ * enum for jpg
+ * @constant
+ * @type Number
+ */
+cc.IMAGE_FORMAT_JPEG = 0;
+/**
+ * enum for png
+ * @constant
+ * @type Number
+ */
+cc.IMAGE_FORMAT_PNG = 1;
+/**
+ * enum for raw
+ * @constant
+ * @type Number
+ */
+cc.IMAGE_FORMAT_RAWDATA = 9;
+
+/**
+ * @param {Number} x
+ * @return {Number}
+ * Constructor
+ */
+cc.NextPOT = function (x) {
+ x = x - 1;
+ x = x | (x >> 1);
+ x = x | (x >> 2);
+ x = x | (x >> 4);
+ x = x | (x >> 8);
+ x = x | (x >> 16);
+ return x + 1;
+};
+
+/**
+ * cc.RenderTexture is a generic rendering target. To render things into it,
+ * simply construct a render target, call begin on it, call visit on any cocos
+ * scenes or objects to render them, and call end. For convenience, render texture
+ * adds a sprite as it's display child with the results, so you can simply add
+ * the render texture to your scene and treat it like any other CocosNode.
+ * There are also functions for saving the render texture to disk in PNG or JPG format.
+ * @class
+ * @extends cc.Node
+ *
+ * @property {cc.Sprite} sprite - The sprite.
+ * @property {cc.Sprite} clearFlags - Code for "auto" update.
+ * @property {Number} clearDepthVal - Clear depth value.
+ * @property {Boolean} autoDraw - Indicate auto draw mode activate or not.
+ * @property {Number} clearStencilVal - Clear stencil value.
+ * @property {cc.Color} clearColorVal - Clear color value, valid only when "autoDraw" is true.
+ */
+cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
+ sprite:null,
+
+ //
+ // Code for "auto" update
+ // Valid flags: GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT.
+ // They can be OR'ed. Valid when "autoDraw is YES.
+ // @public
+ //
+ clearFlags:0,
+
+ clearDepthVal:0,
+ autoDraw:false,
+
+ _texture:null,
+ _pixelFormat:0,
+
+ clearStencilVal:0,
+ _clearColor:null,
+
+ _className:"RenderTexture",
+
+ /**
+ * creates a RenderTexture object with width and height in Points and a pixel format, only RGB and RGBA formats are valid
+ * Constructor of cc.RenderTexture for Canvas
+ * @param {Number} width
+ * @param {Number} height
+ * @param {cc.IMAGE_FORMAT_JPEG|cc.IMAGE_FORMAT_PNG|cc.IMAGE_FORMAT_RAWDATA} format
+ * @param {Number} depthStencilFormat
+ * @example
+ * // Example
+ * var rt = new cc.RenderTexture(width, height, format, depthStencilFormat)
+ * @function
+ */
+ ctor: function(width, height, format, depthStencilFormat){
+ cc.Node.prototype.ctor.call(this);
+ this._cascadeColorEnabled = true;
+ this._cascadeOpacityEnabled = true;
+ this._pixelFormat = cc.Texture2D.PIXEL_FORMAT_RGBA8888;
+ this._clearColor = new cc.Color(0,0,0,255);
+
+ if(width !== undefined && height !== undefined) {
+ format = format || cc.Texture2D.PIXEL_FORMAT_RGBA8888;
+ depthStencilFormat = depthStencilFormat || 0;
+ this.initWithWidthAndHeight(width, height, format, depthStencilFormat);
+ }
+ this.setAnchorPoint(0,0);
+ },
+
+ _createRenderCmd: function(){
+ if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ return new cc.RenderTexture.CanvasRenderCmd(this);
+ else
+ return new cc.RenderTexture.WebGLRenderCmd(this);
+ },
+
+ /**
+ * Clear RenderTexture.
+ * @function
+ */
+ cleanup: function(){
+ cc.Node.prototype.onExit.call(this);
+ this._renderCmd.cleanup();
+ },
+
+ /**
+ * Gets the sprite
+ * @return {cc.Sprite}
+ */
+ getSprite:function () {
+ return this.sprite;
+ },
+
+ /**
+ * Set the sprite
+ * @param {cc.Sprite} sprite
+ */
+ setSprite:function (sprite) {
+ this.sprite = sprite;
+ },
+
+ /**
+ * Used for grab part of screen to a texture.
+ * @param {cc.Vec2} rtBegin
+ * @param {cc.Rect} fullRect
+ * @param {cc.Rect} fullViewport
+ */
+ setVirtualViewport: function(rtBegin, fullRect, fullViewport){
+ this._renderCmd.setVirtualViewport(rtBegin, fullRect, fullViewport);
+ },
+
+ /**
+ * Initializes the instance of cc.RenderTexture
+ * @function
+ * @param {Number} width
+ * @param {Number} height
+ * @param {cc.IMAGE_FORMAT_JPEG|cc.IMAGE_FORMAT_PNG|cc.IMAGE_FORMAT_RAWDATA} [format]
+ * @param {Number} [depthStencilFormat]
+ * @return {Boolean}
+ */
+ initWithWidthAndHeight: function(width, height, format, depthStencilFormat){
+ return this._renderCmd.initWithWidthAndHeight(width, height, format, depthStencilFormat);
+ },
+
+ /**
+ * starts grabbing
+ * @function
+ */
+ begin: function(){
+ cc.renderer._turnToCacheMode(this.__instanceId);
+ this._renderCmd.begin();
+ },
+ /**
+ * starts rendering to the texture while clearing the texture first.
+ * This is more efficient then calling -clear first and then -begin
+ * @param {Number} r red 0-255
+ * @param {Number} g green 0-255
+ * @param {Number} b blue 0-255
+ * @param {Number} a alpha 0-255 0 is transparent
+ * @param {Number} [depthValue=]
+ * @param {Number} [stencilValue=]
+ */
+ beginWithClear:function (r, g, b, a, depthValue, stencilValue) {
+ //todo: only for WebGL?
+ var gl = cc._renderContext;
+ depthValue = depthValue || gl.COLOR_BUFFER_BIT;
+ stencilValue = stencilValue || (gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
+
+ this._beginWithClear(r , g , b , a , depthValue, stencilValue, (gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT));
+ },
+
+ _beginWithClear: function(r, g, b, a, depthValue, stencilValue, flags){
+ this.begin();
+ this._renderCmd._beginWithClear(r, g, b, a, depthValue, stencilValue, flags);
+ },
+
+ /**
+ * ends grabbing
+ * @function
+ */
+ end: function(){
+ this._renderCmd.end();
+ },
+
+ /**
+ * clears the texture with a color
+ * @param {Number|cc.Rect} r red 0-1
+ * @param {Number} g green 0-1
+ * @param {Number} b blue 0-1
+ * @param {Number} a alpha 0-1
+ */
+ clear:function (r, g, b, a) {
+ this.beginWithClear(r, g, b, a);
+ this.end();
+ },
+
+ /**
+ * clears the texture with rect.
+ * @function
+ * @param {number} x
+ * @param {number} y
+ * @param {number} width
+ * @param {number} height
+ */
+ clearRect: function(x, y, width, height){
+ this._renderCmd.clearRect(x, y, width, height);
+ },
+
+ /**
+ * clears the texture with a specified depth value
+ * @function
+ * @param {Number} depthValue
+ */
+ clearDepth: function(depthValue){
+ this._renderCmd.clearDepth(depthValue);
+ },
+
+ /**
+ * clears the texture with a specified stencil value
+ * @function
+ * @param {Number} stencilValue
+ */
+ clearStencil: function(stencilValue) {
+ this._renderCmd.clearStencil(stencilValue);
+ },
+
+ /**
+ * Valid flags: GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT. They can be OR'ed. Valid when "autoDraw is YES.
+ * @return {Number}
+ */
+ getClearFlags:function () {
+ return this.clearFlags;
+ },
+
+ /**
+ * Set the clearFlags
+ * @param {Number} clearFlags
+ */
+ setClearFlags:function (clearFlags) {
+ this.clearFlags = clearFlags;
+ },
+
+ /**
+ * Clear color value. Valid only when "autoDraw" is true.
+ * @function
+ * @return {cc.Color}
+ */
+ getClearColor:function () {
+ return this._clearColor;
+ },
+
+ /**
+ * Set the clear color value. Valid only when "autoDraw" is true.
+ * @function
+ * @param {cc.Color} clearColor The clear color
+ */
+ setClearColor: function(clearColor){
+ var locClearColor = this._clearColor;
+ locClearColor.r = clearColor.r;
+ locClearColor.g = clearColor.g;
+ locClearColor.b = clearColor.b;
+ locClearColor.a = clearColor.a;
+ this._renderCmd.updateClearColor(clearColor);
+ },
+
+ /**
+ * Value for clearDepth. Valid only when autoDraw is true.
+ * @return {Number}
+ */
+ getClearDepth:function () {
+ return this.clearDepthVal;
+ },
+
+ /**
+ * Set value for clearDepth. Valid only when autoDraw is true.
+ * @param {Number} clearDepth
+ */
+ setClearDepth:function (clearDepth) {
+ this.clearDepthVal = clearDepth;
+ },
+
+ /**
+ * Value for clear Stencil. Valid only when autoDraw is true
+ * @return {Number}
+ */
+ getClearStencil:function () {
+ return this.clearStencilVal;
+ },
+
+ /**
+ * Set value for clear Stencil. Valid only when autoDraw is true
+ * @return {Number}
+ */
+ setClearStencil:function (clearStencil) {
+ this.clearStencilVal = clearStencil;
+ },
+
+ /**
+ * When enabled, it will render its children into the texture automatically. Disabled by default for compatiblity reasons.
+ * Will be enabled in the future.
+ * @return {Boolean}
+ */
+ isAutoDraw:function () {
+ return this.autoDraw;
+ },
+
+ /**
+ * When enabled, it will render its children into the texture automatically. Disabled by default for compatiblity reasons.
+ * Will be enabled in the future.
+ * @return {Boolean}
+ */
+ setAutoDraw:function (autoDraw) {
+ this.autoDraw = autoDraw;
+ },
+
+ //---- some stub functions for jsb
+ /**
+ * saves the texture into a file using JPEG format. The file will be saved in the Documents folder.
+ * Returns YES if the operation is successful.
+ * (doesn't support in HTML5)
+ * @param {Number} filePath
+ * @param {Number} format
+ */
+ saveToFile:function (filePath, format) {
+ cc.log("saveToFile isn't supported on Cocos2d-Html5");
+ },
+
+ /**
+ * creates a new CCImage from with the texture's data. Caller is responsible for releasing it by calling delete.
+ * @return {*}
+ */
+ newCCImage:function(flipImage){
+ cc.log("saveToFile isn't supported on cocos2d-html5");
+ return null;
+ },
+
+ /**
+ * Listen "come to background" message, and save render texture. It only has effect on Android.
+ * @param {cc._Class} obj
+ */
+ listenToBackground:function (obj) { },
+
+ /**
+ * Listen "come to foreground" message and restore the frame buffer object. It only has effect on Android.
+ * @param {cc._Class} obj
+ */
+ listenToForeground:function (obj) { }
+});
+
+var _p = cc.RenderTexture.prototype;
+// Extended
+/** @expose */
+_p.clearColorVal;
+cc.defineGetterSetter(_p, "clearColorVal", _p.getClearColor, _p.setClearColor);
+
+
+/**
+ * creates a RenderTexture object with width and height in Points and a pixel format, only RGB and RGBA formats are valid
+ * @deprecated since v3.0 please use new cc.RenderTexture() instead.
+ * @param {Number} width
+ * @param {Number} height
+ * @param {cc.IMAGE_FORMAT_JPEG|cc.IMAGE_FORMAT_PNG|cc.IMAGE_FORMAT_RAWDATA} format
+ * @param {Number} depthStencilFormat
+ * @return {cc.RenderTexture}
+ */
+cc.RenderTexture.create = function (width, height, format, depthStencilFormat) {
+ return new cc.RenderTexture(width, height, format, depthStencilFormat);
+};
diff --git a/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js b/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js
new file mode 100644
index 0000000000..854ebba1cc
--- /dev/null
+++ b/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js
@@ -0,0 +1,107 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+(function(){
+ cc.RenderTexture.CanvasRenderCmd = function(renderableObject){
+ cc.Node.CanvasRenderCmd.call(this, renderableObject);
+ this._needDraw = true;
+ this._clearColorStr = "rgba(255,255,255,1)";
+
+ this._cacheCanvas = document.createElement('canvas');
+ this._cacheContext = new cc.CanvasContextWrapper(this._cacheCanvas.getContext('2d'));
+ };
+
+ var proto = cc.RenderTexture.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
+ proto.constructor = cc.RenderTexture.CanvasRenderCmd;
+
+ proto.cleanup = function(){
+ this._cacheContext = null;
+ this._cacheCanvas = null;
+ };
+
+ proto.clearStencil = function (stencilValue) { };
+
+ proto.setVirtualViewport = function(rtBegin, fullRect, fullViewport) {};
+
+ proto.updateClearColor = function(clearColor){
+ this._clearColorStr = "rgba(" + (0 | clearColor.r) + "," + (0 | clearColor.g) + "," + (0 | clearColor.b) + "," + clearColor.a / 255 + ")";
+ };
+
+ proto.initWithWidthAndHeight = function(width, height, format, depthStencilFormat){
+ var node = this._node;
+ var locCacheCanvas = this._cacheCanvas, locScaleFactor = cc.contentScaleFactor();
+ locCacheCanvas.width = 0 | (width * locScaleFactor);
+ locCacheCanvas.height = 0 | (height * locScaleFactor);
+
+ var texture = new cc.Texture2D();
+ texture.initWithElement(locCacheCanvas);
+ texture.handleLoadedTexture();
+
+ var locSprite = node.sprite = new cc.Sprite(texture);
+ locSprite.setBlendFunc(cc.ONE, cc.ONE_MINUS_SRC_ALPHA);
+ // Disabled by default.
+ node.autoDraw = false;
+ // add sprite for backward compatibility
+ node.addChild(locSprite);
+ return true;
+ };
+
+ proto.begin = function(){};
+
+ proto._beginWithClear = function(r, g, b, a, depthValue, stencilValue, flags){
+ r = r || 0;
+ g = g || 0;
+ b = b || 0;
+ a = isNaN(a) ? 255 : a;
+
+ var context = this._cacheContext.getContext();
+ var locCanvas = this._cacheCanvas;
+ context.setTransform(1,0,0,1,0,0);
+ this._cacheContext.setFillStyle("rgba(" + (0 | r) + "," + (0 | g) + "," + (0 | b) + "," + a / 255 + ")");
+ context.clearRect(0, 0, locCanvas.width, locCanvas.height);
+ context.fillRect(0, 0, locCanvas.width, locCanvas.height);
+ };
+
+ proto.end = function(){
+ var node = this._node;
+
+ var scale = cc.contentScaleFactor();
+ cc.renderer._renderingToCacheCanvas(this._cacheContext, node.__instanceId, scale, scale);
+ };
+
+ proto.clearRect = function(x, y, width, height){
+ this._cacheContext.clearRect(x, y, width, -height);
+ };
+
+ proto.clearDepth = function(depthValue){
+ cc.log("clearDepth isn't supported on Cocos2d-Html5");
+ };
+
+ proto.visit = function(parentCmd){
+ var node = this._node;
+ this._syncStatus(parentCmd);
+ node.sprite.visit(this);
+ this._dirtyFlag = 0;
+ };
+})();
\ No newline at end of file
diff --git a/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js b/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js
new file mode 100644
index 0000000000..50bed35f16
--- /dev/null
+++ b/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js
@@ -0,0 +1,387 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+(function(){
+ cc.RenderTexture.WebGLRenderCmd = function(renderableObject){
+ cc.Node.WebGLRenderCmd.call(this, renderableObject);
+ this._needDraw = true;
+
+ this._fBO = null;
+ this._oldFBO = null;
+ this._textureCopy = null;
+ this._depthRenderBuffer = null;
+
+ this._rtTextureRect = new cc.Rect();
+ this._fullRect = new cc.Rect();
+ this._fullViewport = new cc.Rect();
+ };
+
+ var proto = cc.RenderTexture.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
+ proto.constructor = cc.RenderTexture.WebGLRenderCmd;
+
+ proto.setVirtualViewport = function(rtBegin, fullRect, fullViewport) {
+ this._rtTextureRect.x = rtBegin.x;
+ this._rtTextureRect.y = rtBegin.y;
+
+ this._fullRect = fullRect;
+ this._fullViewport = fullViewport;
+ };
+
+ proto.rendering = function (ctx) {
+ var gl = ctx || cc._renderContext;
+ var node = this._node;
+ if (node.autoDraw) {
+ node.begin();
+
+ var locClearFlags = node.clearFlags;
+ if (locClearFlags) {
+ var oldClearColor = [0.0, 0.0, 0.0, 0.0];
+ var oldDepthClearValue = 0.0;
+ var oldStencilClearValue = 0;
+
+ // backup and set
+ if (locClearFlags & gl.COLOR_BUFFER_BIT) {
+ oldClearColor = gl.getParameter(gl.COLOR_CLEAR_VALUE);
+ gl.clearColor(node._clearColor.r / 255, node._clearColor.g / 255, node._clearColor.b / 255, node._clearColor.a / 255);
+ }
+
+ if (locClearFlags & gl.DEPTH_BUFFER_BIT) {
+ oldDepthClearValue = gl.getParameter(gl.DEPTH_CLEAR_VALUE);
+ gl.clearDepth(node.clearDepthVal);
+ }
+
+ if (locClearFlags & gl.STENCIL_BUFFER_BIT) {
+ oldStencilClearValue = gl.getParameter(gl.STENCIL_CLEAR_VALUE);
+ gl.clearStencil(node.clearStencilVal);
+ }
+
+ // clear
+ gl.clear(locClearFlags);
+
+ // restore
+ if (locClearFlags & gl.COLOR_BUFFER_BIT)
+ gl.clearColor(oldClearColor[0], oldClearColor[1], oldClearColor[2], oldClearColor[3]);
+
+ if (locClearFlags & gl.DEPTH_BUFFER_BIT)
+ gl.clearDepth(oldDepthClearValue);
+
+ if (locClearFlags & gl.STENCIL_BUFFER_BIT)
+ gl.clearStencil(oldStencilClearValue);
+ }
+
+ //! make sure all children are drawn
+ node.sortAllChildren();
+ var locChildren = node._children;
+ for (var i = 0; i < locChildren.length; i++) {
+ var getChild = locChildren[i];
+ if (getChild !== node.sprite){
+ getChild._renderCmd.visit(node.sprite._renderCmd); //TODO it's very Strange
+ }
+ }
+ node.end();
+ }
+ };
+
+ proto.clearStencil = function(stencilValue) {
+ var gl = cc._renderContext;
+ // save old stencil value
+ var stencilClearValue = gl.getParameter(gl.STENCIL_CLEAR_VALUE);
+
+ gl.clearStencil(stencilValue);
+ gl.clear(gl.STENCIL_BUFFER_BIT);
+
+ // restore clear color
+ gl.clearStencil(stencilClearValue);
+ };
+
+ proto.cleanup = function(){
+ var node = this._node;
+ //node.sprite = null;
+ this._textureCopy = null;
+
+ var gl = cc._renderContext;
+ gl.deleteFramebuffer(this._fBO);
+ if (this._depthRenderBuffer)
+ gl.deleteRenderbuffer(this._depthRenderBuffer);
+ };
+
+ proto.updateClearColor = function(clearColor){ };
+
+ proto.initWithWidthAndHeight = function(width, height, format, depthStencilFormat){
+ var node = this._node;
+ if(format === cc.Texture2D.PIXEL_FORMAT_A8)
+ cc.log( "cc.RenderTexture._initWithWidthAndHeightForWebGL() : only RGB and RGBA formats are valid for a render texture;");
+
+ var gl = cc._renderContext, locScaleFactor = cc.contentScaleFactor();
+ this._fullRect = new cc.Rect(0,0, width, height);
+ this._fullViewport = new cc.Rect(0,0, width, height);
+
+ width = 0 | (width * locScaleFactor);
+ height = 0 | (height * locScaleFactor);
+
+ this._oldFBO = gl.getParameter(gl.FRAMEBUFFER_BINDING);
+
+ // textures must be power of two squared
+ var powW , powH;
+
+ if (cc.configuration.supportsNPOT()) {
+ powW = width;
+ powH = height;
+ } else {
+ powW = cc.NextPOT(width);
+ powH = cc.NextPOT(height);
+ }
+
+ //void *data = malloc(powW * powH * 4);
+ var dataLen = powW * powH * 4;
+ var data = new Uint8Array(dataLen);
+ //memset(data, 0, (int)(powW * powH * 4));
+ for (var i = 0; i < powW * powH * 4; i++)
+ data[i] = 0;
+
+ this._pixelFormat = format;
+
+ var locTexture = node._texture = new cc.Texture2D();
+ if (!node._texture)
+ return false;
+
+ locTexture.initWithData(data, node._pixelFormat, powW, powH, cc.size(width, height));
+ //free( data );
+
+ var oldRBO = gl.getParameter(gl.RENDERBUFFER_BINDING);
+
+ if (cc.configuration.checkForGLExtension("GL_QCOM")) {
+ this._textureCopy = new cc.Texture2D();
+ if (!this._textureCopy)
+ return false;
+ this._textureCopy.initWithData(data, node._pixelFormat, powW, powH, cc.size(width, height));
+ }
+
+ // generate FBO
+ this._fBO = gl.createFramebuffer();
+ gl.bindFramebuffer(gl.FRAMEBUFFER, this._fBO);
+
+ // associate texture with FBO
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, locTexture._webTextureObj, 0);
+
+ if (depthStencilFormat !== 0) {
+ //create and attach depth buffer
+ this._depthRenderBuffer = gl.createRenderbuffer();
+ gl.bindRenderbuffer(gl.RENDERBUFFER, this._depthRenderBuffer);
+ gl.renderbufferStorage(gl.RENDERBUFFER, depthStencilFormat, powW, powH);
+ if(depthStencilFormat === gl.DEPTH_STENCIL)
+ gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this._depthRenderBuffer);
+ else if(depthStencilFormat === gl.STENCIL_INDEX || depthStencilFormat === gl.STENCIL_INDEX8)
+ gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, this._depthRenderBuffer);
+ else if(depthStencilFormat === gl.DEPTH_COMPONENT16)
+ gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, this._depthRenderBuffer);
+ }
+
+ // check if it worked (probably worth doing :) )
+ if(gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE)
+ cc.log("Could not attach texture to the framebuffer");
+
+ locTexture.setAliasTexParameters();
+
+ var locSprite = node.sprite = new cc.Sprite(locTexture);
+ locSprite.scaleY = -1;
+ locSprite.setBlendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+
+ gl.bindRenderbuffer(gl.RENDERBUFFER, oldRBO);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, this._oldFBO);
+
+ // Disabled by default.
+ node.autoDraw = false;
+
+ // add sprite for backward compatibility
+ node.addChild(locSprite);
+ return true;
+ };
+
+ proto.begin = function(){
+ var node = this._node;
+ // Save the current matrix
+ cc.kmGLMatrixMode(cc.KM_GL_PROJECTION);
+ cc.kmGLPushMatrix();
+ cc.kmGLMatrixMode(cc.KM_GL_MODELVIEW);
+ cc.kmGLPushMatrix();
+
+ var gl = cc._renderContext;
+
+ var director = cc.director;
+ director.setProjection(director.getProjection());
+
+ var texSize = node._texture.getContentSizeInPixels();
+
+ // Calculate the adjustment ratios based on the old and new projections
+ var size = cc.director.getWinSizeInPixels();
+ var widthRatio = size.width / texSize.width;
+ var heightRatio = size.height / texSize.height;
+
+ var orthoMatrix = cc.math.Matrix4.createOrthographicProjection(-1.0 / widthRatio, 1.0 / widthRatio,
+ -1.0 / heightRatio, 1.0 / heightRatio, -1, 1);
+ cc.kmGLMultMatrix(orthoMatrix);
+
+ //calculate viewport
+ var viewport = new cc.Rect(0, 0, 0, 0);
+ viewport.width = this._fullViewport.width;
+ viewport.height = this._fullViewport.height;
+ var viewPortRectWidthRatio = viewport.width / this._fullRect.width;
+ var viewPortRectHeightRatio = viewport.height / this._fullRect.height;
+ viewport.x = (this._fullRect.x - this._rtTextureRect.x) * viewPortRectWidthRatio;
+ viewport.y = (this._fullRect.y - this._rtTextureRect.y) * viewPortRectHeightRatio;
+ gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height);
+
+ this._oldFBO = gl.getParameter(gl.FRAMEBUFFER_BINDING);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, this._fBO);//Will direct drawing to the frame buffer created above
+
+ /* Certain Qualcomm Andreno gpu's will retain data in memory after a frame buffer switch which corrupts the render to the texture.
+ * The solution is to clear the frame buffer before rendering to the texture. However, calling glClear has the unintended result of clearing the current texture.
+ * Create a temporary texture to overcome this. At the end of CCRenderTexture::begin(), switch the attached texture to the second one, call glClear,
+ * and then switch back to the original texture. This solution is unnecessary for other devices as they don't have the same issue with switching frame buffers.
+ */
+ if (cc.configuration.checkForGLExtension("GL_QCOM")) {
+ // -- bind a temporary texture so we can clear the render buffer without losing our texture
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this._textureCopy._webTextureObj, 0);
+ //cc.checkGLErrorDebug();
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, node._texture._webTextureObj, 0);
+ }
+ };
+
+ proto._beginWithClear = function(r, g, b, a, depthValue, stencilValue, flags){
+ r = r / 255;
+ g = g / 255;
+ b = b / 255;
+ a = a / 255;
+
+ var gl = cc._renderContext;
+
+ // save clear color
+ var clearColor = [0.0, 0.0, 0.0, 0.0];
+ var depthClearValue = 0.0;
+ var stencilClearValue = 0;
+
+ if (flags & gl.COLOR_BUFFER_BIT) {
+ clearColor = gl.getParameter(gl.COLOR_CLEAR_VALUE);
+ gl.clearColor(r, g, b, a);
+ }
+
+ if (flags & gl.DEPTH_BUFFER_BIT) {
+ depthClearValue = gl.getParameter(gl.DEPTH_CLEAR_VALUE);
+ gl.clearDepth(depthValue);
+ }
+
+ if (flags & gl.STENCIL_BUFFER_BIT) {
+ stencilClearValue = gl.getParameter(gl.STENCIL_CLEAR_VALUE);
+ gl.clearStencil(stencilValue);
+ }
+
+ gl.clear(flags);
+
+ // restore
+ if (flags & gl.COLOR_BUFFER_BIT)
+ gl.clearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3]);
+
+ if (flags & gl.DEPTH_BUFFER_BIT)
+ gl.clearDepth(depthClearValue);
+
+ if (flags & gl.STENCIL_BUFFER_BIT)
+ gl.clearStencil(stencilClearValue);
+ };
+
+ proto.end = function(){
+ var node = this._node;
+ cc.renderer._renderingToBuffer(node.__instanceId);
+
+ var gl = cc._renderContext;
+ var director = cc.director;
+ gl.bindFramebuffer(gl.FRAMEBUFFER, this._oldFBO);
+
+ //restore viewport
+ director.setViewport();
+ cc.kmGLMatrixMode(cc.KM_GL_PROJECTION);
+ cc.kmGLPopMatrix();
+ cc.kmGLMatrixMode(cc.KM_GL_MODELVIEW);
+ cc.kmGLPopMatrix();
+
+ /* var size = director.getWinSizeInPixels();
+
+ // restore viewport
+ gl.viewport(0, 0, size.width * cc.contentScaleFactor(), size.height * cc.contentScaleFactor());
+
+ // special viewport for 3d projection + retina display
+ if (director.getProjection() == cc.Director.PROJECTION_3D && cc.contentScaleFactor() != 1) {
+ gl.viewport((-size.width / 2), (-size.height / 2), (size.width * cc.contentScaleFactor()), (size.height * cc.contentScaleFactor()));
+ }
+
+ director.setProjection(director.getProjection());*/
+ };
+
+ proto.clearRect = function(x, y, width, height){
+ //TODO need to implement
+ };
+
+ proto.clearDepth = function(depthValue){
+ var node = this._node;
+ node.begin();
+
+ var gl = cc._renderContext;
+ //! save old depth value
+ var depthClearValue = gl.getParameter(gl.DEPTH_CLEAR_VALUE);
+
+ gl.clearDepth(depthValue);
+ gl.clear(gl.DEPTH_BUFFER_BIT);
+
+ // restore clear color
+ gl.clearDepth(depthClearValue);
+ node.end();
+ };
+
+ proto.visit = function(parentCmd){
+ var node = this._node;
+ if (!node._visible)
+ return;
+ cc.kmGLPushMatrix();
+
+ //TODO using GridNode
+ /* var locGrid = this.grid;
+ if (locGrid && locGrid.isActive()) {
+ locGrid.beforeDraw();
+ this.transformAncestors();
+ }*/
+
+ this._syncStatus(parentCmd);
+ //this.toRenderer();
+ cc.renderer.pushRenderCommand(this);
+ node.sprite.visit(this);
+
+ //TODO GridNode
+ /* if (locGrid && locGrid.isActive())
+ locGrid.afterDraw(this);*/
+
+ this._dirtyFlag = 0;
+ cc.kmGLPopMatrix();
+ };
+})();
\ No newline at end of file
diff --git a/cocos2d/shaders/CCGLProgram.js b/cocos2d/shaders/CCGLProgram.js
new file mode 100644
index 0000000000..3eb4f505ad
--- /dev/null
+++ b/cocos2d/shaders/CCGLProgram.js
@@ -0,0 +1,767 @@
+/****************************************************************************
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright 2011 Jeff Lamarche
+ Copyright 2012 Goffredo Marocchi
+
+ 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.HashUniformEntry = function (value, location, hh) {
+ this.value = value;
+ this.location = location;
+ this.hh = hh || {};
+};
+
+/**
+ * Class that implements a WebGL program
+ * @class
+ * @extends cc._Class
+ */
+cc.GLProgram = cc._Class.extend(/** @lends cc.GLProgram# */{
+ _glContext: null,
+ _programObj: null,
+ _vertShader: null,
+ _fragShader: null,
+ _uniforms: null,
+ _hashForUniforms: null,
+ _usesTime: false,
+
+ // Uniform cache
+ _updateUniformLocation: function (location, data, bytes) {
+ if (location == null)
+ return false;
+
+ var updated = true;
+ var element = null;
+ for (var i = 0; i < this._hashForUniforms.length; i++)
+ if (this._hashForUniforms[i].location == location)
+ element = this._hashForUniforms[i];
+
+ if (!element) {
+ element = new cc.HashUniformEntry();
+ // key
+ element.location = location;
+ // value
+ element.value = data;
+ this._hashForUniforms.push(element);
+ } else {
+ if (element.value == data)
+ updated = false;
+ else
+ element.value = data;
+ }
+
+ return updated;
+ },
+
+ _description: function () {
+ return "";
+ },
+
+ _compileShader: function (shader, type, source) {
+ if (!source || !shader)
+ return false;
+
+ var preStr = cc.GLProgram._isHighpSupported() ? "precision highp float;\n" : "precision mediump float;\n";
+ source = preStr
+ + "uniform mat4 CC_PMatrix; \n"
+ + "uniform mat4 CC_MVMatrix; \n"
+ + "uniform mat4 CC_MVPMatrix; \n"
+ + "uniform vec4 CC_Time; \n"
+ + "uniform vec4 CC_SinTime; \n"
+ + "uniform vec4 CC_CosTime; \n"
+ + "uniform vec4 CC_Random01; \n"
+ + "uniform sampler2D CC_Texture0; \n"
+ + "//CC INCLUDES END \n" + source;
+
+ this._glContext.shaderSource(shader, source);
+ this._glContext.compileShader(shader);
+ var status = this._glContext.getShaderParameter(shader, this._glContext.COMPILE_STATUS);
+
+ if (!status) {
+ cc.log("cocos2d: ERROR: Failed to compile shader:\n" + this._glContext.getShaderSource(shader));
+ if (type === this._glContext.VERTEX_SHADER)
+ cc.log("cocos2d: \n" + this.vertexShaderLog());
+ else
+ cc.log("cocos2d: \n" + this.fragmentShaderLog());
+ }
+ return ( status === true );
+ },
+
+ /**
+ * Create a cc.GLProgram object
+ * @param {String} vShaderFileName
+ * @param {String} fShaderFileName
+ * @returns {cc.GLProgram}
+ */
+ ctor: function (vShaderFileName, fShaderFileName, glContext) {
+ this._uniforms = [];
+ this._hashForUniforms = [];
+ this._glContext = glContext || cc._renderContext;
+
+ vShaderFileName && fShaderFileName && this.init(vShaderFileName, fShaderFileName);
+ },
+
+ /**
+ * destroy program
+ */
+ destroyProgram: function () {
+ this._vertShader = null;
+ this._fragShader = null;
+ this._uniforms = null;
+ this._hashForUniforms = null;
+
+ this._glContext.deleteProgram(this._programObj);
+ },
+
+ /**
+ * Initializes the cc.GLProgram with a vertex and fragment with string
+ * @param {String} vertShaderStr
+ * @param {String} fragShaderStr
+ * @return {Boolean}
+ */
+ initWithVertexShaderByteArray: function (vertShaderStr, fragShaderStr) {
+ var locGL = this._glContext;
+ this._programObj = locGL.createProgram();
+ //cc.checkGLErrorDebug();
+
+ this._vertShader = null;
+ this._fragShader = null;
+
+ if (vertShaderStr) {
+ this._vertShader = locGL.createShader(locGL.VERTEX_SHADER);
+ if (!this._compileShader(this._vertShader, locGL.VERTEX_SHADER, vertShaderStr)) {
+ cc.log("cocos2d: ERROR: Failed to compile vertex shader");
+ }
+ }
+
+ // Create and compile fragment shader
+ if (fragShaderStr) {
+ this._fragShader = locGL.createShader(locGL.FRAGMENT_SHADER);
+ if (!this._compileShader(this._fragShader, locGL.FRAGMENT_SHADER, fragShaderStr)) {
+ cc.log("cocos2d: ERROR: Failed to compile fragment shader");
+ }
+ }
+
+ if (this._vertShader)
+ locGL.attachShader(this._programObj, this._vertShader);
+ cc.checkGLErrorDebug();
+
+ if (this._fragShader)
+ locGL.attachShader(this._programObj, this._fragShader);
+ this._hashForUniforms.length = 0;
+
+ cc.checkGLErrorDebug();
+ return true;
+ },
+
+ /**
+ * Initializes the cc.GLProgram with a vertex and fragment with string
+ * @param {String} vertShaderStr
+ * @param {String} fragShaderStr
+ * @return {Boolean}
+ */
+ initWithString: function (vertShaderStr, fragShaderStr) {
+ return this.initWithVertexShaderByteArray(vertShaderStr, fragShaderStr);
+ },
+
+ /**
+ * Initializes the CCGLProgram with a vertex and fragment with contents of filenames
+ * @param {String} vShaderFilename
+ * @param {String} fShaderFileName
+ * @return {Boolean}
+ */
+ initWithVertexShaderFilename: function (vShaderFilename, fShaderFileName) {
+ var vertexSource = cc.loader.getRes(vShaderFilename);
+ if(!vertexSource) throw new Error("Please load the resource firset : " + vShaderFilename);
+ var fragmentSource = cc.loader.getRes(fShaderFileName);
+ if(!fragmentSource) throw new Error("Please load the resource firset : " + fShaderFileName);
+ return this.initWithVertexShaderByteArray(vertexSource, fragmentSource);
+ },
+
+ /**
+ * Initializes the CCGLProgram with a vertex and fragment with contents of filenames
+ * @param {String} vShaderFilename
+ * @param {String} fShaderFileName
+ * @return {Boolean}
+ */
+ init: function (vShaderFilename, fShaderFileName) {
+ return this.initWithVertexShaderFilename(vShaderFilename, fShaderFileName);
+ },
+
+ /**
+ * It will add a new attribute to the shader
+ * @param {String} attributeName
+ * @param {Number} index
+ */
+ addAttribute: function (attributeName, index) {
+ this._glContext.bindAttribLocation(this._programObj, index, attributeName);
+ },
+
+ /**
+ * links the glProgram
+ * @return {Boolean}
+ */
+ link: function () {
+ if(!this._programObj) {
+ cc.log("cc.GLProgram.link(): Cannot link invalid program");
+ return false;
+ }
+
+ this._glContext.linkProgram(this._programObj);
+
+ if (this._vertShader)
+ this._glContext.deleteShader(this._vertShader);
+ if (this._fragShader)
+ this._glContext.deleteShader(this._fragShader);
+
+ this._vertShader = null;
+ this._fragShader = null;
+
+ if (cc.game.config[cc.game.CONFIG_KEY.debugMode]) {
+ var status = this._glContext.getProgramParameter(this._programObj, this._glContext.LINK_STATUS);
+ if (!status) {
+ cc.log("cocos2d: ERROR: Failed to link program: " + this._glContext.getProgramInfoLog(this._programObj));
+ cc.glDeleteProgram(this._programObj);
+ this._programObj = null;
+ return false;
+ }
+ }
+
+ return true;
+ },
+
+ /**
+ * it will call glUseProgram()
+ */
+ use: function () {
+ cc.glUseProgram(this._programObj);
+ },
+
+ /**
+ * It will create 4 uniforms:
+ * cc.UNIFORM_PMATRIX
+ * cc.UNIFORM_MVMATRIX
+ * cc.UNIFORM_MVPMATRIX
+ * cc.UNIFORM_SAMPLER
+ */
+ updateUniforms: function () {
+ this._uniforms[cc.UNIFORM_PMATRIX] = this._glContext.getUniformLocation(this._programObj, cc.UNIFORM_PMATRIX_S);
+ this._uniforms[cc.UNIFORM_MVMATRIX] = this._glContext.getUniformLocation(this._programObj, cc.UNIFORM_MVMATRIX_S);
+ this._uniforms[cc.UNIFORM_MVPMATRIX] = this._glContext.getUniformLocation(this._programObj, cc.UNIFORM_MVPMATRIX_S);
+ this._uniforms[cc.UNIFORM_TIME] = this._glContext.getUniformLocation(this._programObj, cc.UNIFORM_TIME_S);
+ this._uniforms[cc.UNIFORM_SINTIME] = this._glContext.getUniformLocation(this._programObj, cc.UNIFORM_SINTIME_S);
+ this._uniforms[cc.UNIFORM_COSTIME] = this._glContext.getUniformLocation(this._programObj, cc.UNIFORM_COSTIME_S);
+
+ this._usesTime = (this._uniforms[cc.UNIFORM_TIME] != null || this._uniforms[cc.UNIFORM_SINTIME] != null || this._uniforms[cc.UNIFORM_COSTIME] != null);
+
+ this._uniforms[cc.UNIFORM_RANDOM01] = this._glContext.getUniformLocation(this._programObj, cc.UNIFORM_RANDOM01_S);
+ this._uniforms[cc.UNIFORM_SAMPLER] = this._glContext.getUniformLocation(this._programObj, cc.UNIFORM_SAMPLER_S);
+
+ this.use();
+ // Since sample most probably won't change, set it to 0 now.
+ this.setUniformLocationWith1i(this._uniforms[cc.UNIFORM_SAMPLER], 0);
+ },
+
+ /**
+ * calls retrieves the named uniform location for this shader program.
+ * @param {String} name
+ * @returns {Number}
+ */
+ getUniformLocationForName:function(name){
+ if(!name)
+ throw new Error("cc.GLProgram.getUniformLocationForName(): uniform name should be non-null");
+ if(!this._programObj)
+ throw new Error("cc.GLProgram.getUniformLocationForName(): Invalid operation. Cannot get uniform location when program is not initialized");
+
+ return this._glContext.getUniformLocation(this._programObj, name);
+ },
+
+ /**
+ * get uniform MVP matrix
+ * @returns {WebGLUniformLocation}
+ */
+ getUniformMVPMatrix: function () {
+ return this._uniforms[cc.UNIFORM_MVPMATRIX];
+ },
+
+ /**
+ * get uniform sampler
+ * @returns {WebGLUniformLocation}
+ */
+ getUniformSampler: function () {
+ return this._uniforms[cc.UNIFORM_SAMPLER];
+ },
+
+ /**
+ * calls glUniform1i only if the values are different than the previous call for this same shader program.
+ * @param {WebGLUniformLocation} location
+ * @param {Number} i1
+ */
+ setUniformLocationWith1i: function (location, i1) {
+ var updated = this._updateUniformLocation(location, i1);
+ if (updated)
+ this._glContext.uniform1i(location, i1);
+ },
+
+ /**
+ * calls glUniform2i only if the values are different than the previous call for this same shader program.
+ * @param {WebGLUniformLocation} location
+ * @param {Number} i1
+ * @param {Number} i2
+ */
+ setUniformLocationWith2i:function(location, i1,i2){
+ var intArray= [i1,i2];
+ var updated = this._updateUniformLocation(location, intArray);
+
+ if( updated )
+ this._glContext.uniform2i(location, i1, i2);
+ },
+
+ /**
+ * calls glUniform3i only if the values are different than the previous call for this same shader program.
+ * @param {WebGLUniformLocation} location
+ * @param {Number} i1
+ * @param {Number} i2
+ * @param {Number} i3
+ */
+ setUniformLocationWith3i:function(location, i1, i2, i3){
+ var intArray = [i1,i2,i3];
+ var updated = this._updateUniformLocation(location, intArray);
+
+ if( updated )
+ this._glContext.uniform3i(location, i1, i2, i3);
+ },
+
+ /**
+ * calls glUniform4i only if the values are different than the previous call for this same shader program.
+ * @param {WebGLUniformLocation} location
+ * @param {Number} i1
+ * @param {Number} i2
+ * @param {Number} i3
+ * @param {Number} i4
+ */
+ setUniformLocationWith4i:function(location, i1, i2, i3, i4){
+ var intArray = [i1,i2,i3,i4];
+ var updated = this._updateUniformLocation(location, intArray);
+
+ if( updated )
+ this._glContext.uniform4i(location, i1, i2, i3, i4);
+ },
+
+ /**
+ * calls glUniform2iv only if the values are different than the previous call for this same shader program.
+ * @param {WebGLUniformLocation} location
+ * @param {Int32Array} intArray
+ * @param {Number} numberOfArrays
+ */
+ setUniformLocationWith2iv:function(location, intArray, numberOfArrays){
+ var updated = this._updateUniformLocation(location, intArray);
+
+ if( updated )
+ this._glContext.uniform2iv(location, intArray);
+ },
+
+ /**
+ * calls glUniform3iv only if the values are different than the previous call for this same shader program.
+ * @param {WebGLUniformLocation} location
+ * @param {Int32Array} intArray
+ * @param {Number} numberOfArrays
+ */
+ setUniformLocationWith3iv:function(location, intArray, numberOfArrays){
+ var updated = this._updateUniformLocation(location, intArray);
+
+ if( updated )
+ this._glContext.uniform3iv(location, intArray);
+ },
+
+ /**
+ * calls glUniform4iv only if the values are different than the previous call for this same shader program.
+ * @param {WebGLUniformLocation} location
+ * @param {Int32Array} intArray
+ * @param {Number} numberOfArrays
+ */
+ setUniformLocationWith4iv:function(location, intArray, numberOfArrays){
+ var updated = this._updateUniformLocation(location, intArray);
+
+ if( updated )
+ this._glContext.uniform4iv(location, intArray);
+ },
+
+ /**
+ * calls glUniform1i only if the values are different than the previous call for this same shader program.
+ * @param {WebGLUniformLocation} location
+ * @param {Number} i1
+ */
+ setUniformLocationI32: function (location, i1) {
+ this.setUniformLocationWith1i(arguments[0], arguments[1]);
+ },
+
+ /**
+ * calls glUniform1f only if the values are different than the previous call for this same shader program.
+ * @param {WebGLUniformLocation} location
+ * @param {Number} f1
+ */
+ setUniformLocationWith1f: function (location, f1) {
+ var updated = this._updateUniformLocation(location, f1);
+ if (updated)
+ this._glContext.uniform1f(location, f1);
+ },
+
+ /**
+ * calls glUniform2f only if the values are different than the previous call for this same shader program.
+ * @param {WebGLUniformLocation} location
+ * @param {Number} f1
+ * @param {Number} f2
+ */
+ setUniformLocationWith2f: function (location, f1, f2) {
+ var floats = [f1, f2];
+ var updated = this._updateUniformLocation(location, floats);
+ if (updated)
+ this._glContext.uniform2f(location, f1, f2);
+ },
+
+ /**
+ * calls glUniform3f only if the values are different than the previous call for this same shader program.
+ * @param {WebGLUniformLocation} location
+ * @param {Number} f1
+ * @param {Number} f2
+ * @param {Number} f3
+ */
+ setUniformLocationWith3f: function (location, f1, f2, f3) {
+ var floats = [f1, f2, f3];
+ var updated = this._updateUniformLocation(location, floats);
+ if (updated)
+ this._glContext.uniform3f(location, f1, f2, f3);
+ },
+
+ /**
+ * calls glUniform4f only if the values are different than the previous call for this same shader program.
+ * @param {WebGLUniformLocation} location
+ * @param {Number} f1
+ * @param {Number} f2
+ * @param {Number} f3
+ * @param {Number} f4
+ */
+ setUniformLocationWith4f: function (location, f1, f2, f3, f4) {
+ var floats = [f1, f2, f3, f4];
+ var updated = this._updateUniformLocation(location, floats);
+ if (updated)
+ this._glContext.uniform4f(location, f1, f2, f3, f4);
+ },
+
+ /**
+ * calls glUniform2fv only if the values are different than the previous call for this same shader program.
+ * @param {WebGLUniformLocation} location
+ * @param {Float32Array} floatArray
+ * @param {Number} numberOfArrays
+ */
+ setUniformLocationWith2fv: function (location, floatArray, numberOfArrays) {
+ var updated = this._updateUniformLocation(location, floatArray);
+ if (updated)
+ this._glContext.uniform2fv(location, floatArray);
+ },
+
+ /**
+ * calls glUniform3fv only if the values are different than the previous call for this same shader program.
+ * @param {WebGLUniformLocation} location
+ * @param {Float32Array} floatArray
+ * @param {Number} numberOfArrays
+ */
+ setUniformLocationWith3fv: function (location, floatArray, numberOfArrays) {
+ var updated = this._updateUniformLocation(location, floatArray);
+ if (updated)
+ this._glContext.uniform3fv(location, floatArray);
+ },
+
+ /**
+ * calls glUniform4fv only if the values are different than the previous call for this same shader program.
+ * @param {WebGLUniformLocation} location
+ * @param {Float32Array} floatArray
+ * @param {Number} numberOfArrays
+ */
+ setUniformLocationWith4fv: function (location, floatArray, numberOfArrays) {
+ var updated = this._updateUniformLocation(location, floatArray);
+ if (updated)
+ this._glContext.uniform4fv(location, floatArray);
+ },
+
+ /**
+ * calls glUniformMatrix4fv only if the values are different than the previous call for this same shader program.
+ * @param {WebGLUniformLocation} location
+ * @param {Float32Array} matrixArray
+ * @param {Number} numberOfMatrices
+ */
+ setUniformLocationWithMatrix4fv: function (location, matrixArray, numberOfMatrices) {
+ var updated = this._updateUniformLocation(location, matrixArray);
+ if (updated)
+ this._glContext.uniformMatrix4fv(location, false, matrixArray);
+ },
+
+ setUniformLocationF32: function () {
+ if (arguments.length < 2)
+ return;
+
+ switch (arguments.length) {
+ case 2:
+ this.setUniformLocationWith1f(arguments[0], arguments[1]);
+ break;
+ case 3:
+ this.setUniformLocationWith2f(arguments[0], arguments[1], arguments[2]);
+ break;
+ case 4:
+ this.setUniformLocationWith3f(arguments[0], arguments[1], arguments[2], arguments[3]);
+ break;
+ case 5:
+ this.setUniformLocationWith4f(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4]);
+ break;
+ }
+ },
+
+ /**
+ * will update the builtin uniforms if they are different than the previous call for this same shader program.
+ */
+ setUniformsForBuiltins: function () {
+ var matrixP = new cc.math.Matrix4();
+ var matrixMV = new cc.math.Matrix4();
+ var matrixMVP = new cc.math.Matrix4();
+
+ cc.kmGLGetMatrix(cc.KM_GL_PROJECTION, matrixP);
+ cc.kmGLGetMatrix(cc.KM_GL_MODELVIEW, matrixMV);
+
+ cc.kmMat4Multiply(matrixMVP, matrixP, matrixMV);
+
+ this.setUniformLocationWithMatrix4fv(this._uniforms[cc.UNIFORM_PMATRIX], matrixP.mat, 1);
+ this.setUniformLocationWithMatrix4fv(this._uniforms[cc.UNIFORM_MVMATRIX], matrixMV.mat, 1);
+ this.setUniformLocationWithMatrix4fv(this._uniforms[cc.UNIFORM_MVPMATRIX], matrixMVP.mat, 1);
+
+ if (this._usesTime) {
+ var director = cc.director;
+ // This doesn't give the most accurate global time value.
+ // Cocos2D doesn't store a high precision time value, so this will have to do.
+ // Getting Mach time per frame per shader using time could be extremely expensive.
+ var time = director.getTotalFrames() * director.getAnimationInterval();
+
+ this.setUniformLocationWith4f(this._uniforms[cc.UNIFORM_TIME], time / 10.0, time, time * 2, time * 4);
+ this.setUniformLocationWith4f(this._uniforms[cc.UNIFORM_SINTIME], time / 8.0, time / 4.0, time / 2.0, Math.sin(time));
+ this.setUniformLocationWith4f(this._uniforms[cc.UNIFORM_COSTIME], time / 8.0, time / 4.0, time / 2.0, Math.cos(time));
+ }
+
+ if (this._uniforms[cc.UNIFORM_RANDOM01] !== -1)
+ this.setUniformLocationWith4f(this._uniforms[cc.UNIFORM_RANDOM01], Math.random(), Math.random(), Math.random(), Math.random());
+ },
+
+ _setUniformsForBuiltinsForRenderer: function (node) {
+ if(!node || !node._renderCmd)
+ return;
+
+ var matrixP = new cc.math.Matrix4();
+ //var matrixMV = new cc.kmMat4();
+ var matrixMVP = new cc.math.Matrix4();
+
+ cc.kmGLGetMatrix(cc.KM_GL_PROJECTION, matrixP);
+ //cc.kmGLGetMatrix(cc.KM_GL_MODELVIEW, node._stackMatrix);
+
+ cc.kmMat4Multiply(matrixMVP, matrixP, node._renderCmd._stackMatrix);
+
+ this.setUniformLocationWithMatrix4fv(this._uniforms[cc.UNIFORM_PMATRIX], matrixP.mat, 1);
+ this.setUniformLocationWithMatrix4fv(this._uniforms[cc.UNIFORM_MVMATRIX], node._renderCmd._stackMatrix.mat, 1);
+ this.setUniformLocationWithMatrix4fv(this._uniforms[cc.UNIFORM_MVPMATRIX], matrixMVP.mat, 1);
+
+ if (this._usesTime) {
+ var director = cc.director;
+ // This doesn't give the most accurate global time value.
+ // Cocos2D doesn't store a high precision time value, so this will have to do.
+ // Getting Mach time per frame per shader using time could be extremely expensive.
+ var time = director.getTotalFrames() * director.getAnimationInterval();
+
+ this.setUniformLocationWith4f(this._uniforms[cc.UNIFORM_TIME], time / 10.0, time, time * 2, time * 4);
+ this.setUniformLocationWith4f(this._uniforms[cc.UNIFORM_SINTIME], time / 8.0, time / 4.0, time / 2.0, Math.sin(time));
+ this.setUniformLocationWith4f(this._uniforms[cc.UNIFORM_COSTIME], time / 8.0, time / 4.0, time / 2.0, Math.cos(time));
+ }
+
+ if (this._uniforms[cc.UNIFORM_RANDOM01] !== -1)
+ this.setUniformLocationWith4f(this._uniforms[cc.UNIFORM_RANDOM01], Math.random(), Math.random(), Math.random(), Math.random());
+ },
+
+ /**
+ * will update the MVP matrix on the MVP uniform if it is different than the previous call for this same shader program.
+ */
+ setUniformForModelViewProjectionMatrix: function () {
+ this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_MVPMATRIX], false,
+ cc.getMat4MultiplyValue(cc.projection_matrix_stack.top, cc.modelview_matrix_stack.top));
+ },
+
+ setUniformForModelViewProjectionMatrixWithMat4: function (swapMat4) {
+ cc.kmMat4Multiply(swapMat4, cc.projection_matrix_stack.top, cc.modelview_matrix_stack.top);
+ this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_MVPMATRIX], false, swapMat4.mat);
+ },
+
+ setUniformForModelViewAndProjectionMatrixWithMat4: function () {
+ this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_MVMATRIX], false, cc.modelview_matrix_stack.top.mat);
+ this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_PMATRIX], false, cc.projection_matrix_stack.top.mat);
+ },
+
+ _setUniformForMVPMatrixWithMat4: function(modelViewMatrix){
+ if(!modelViewMatrix)
+ throw new Error("modelView matrix is undefined.");
+ this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_MVMATRIX], false, modelViewMatrix.mat);
+ this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_PMATRIX], false, cc.projection_matrix_stack.top.mat);
+ },
+
+ /**
+ * returns the vertexShader error log
+ * @return {String}
+ */
+ vertexShaderLog: function () {
+ return this._glContext.getShaderInfoLog(this._vertShader);
+ },
+
+ /**
+ * returns the vertexShader error log
+ * @return {String}
+ */
+ getVertexShaderLog: function () {
+ return this._glContext.getShaderInfoLog(this._vertShader);
+ },
+
+ /**
+ * returns the fragmentShader error log
+ * @returns {String}
+ */
+ getFragmentShaderLog: function () {
+ return this._glContext.getShaderInfoLog(this._vertShader);
+ },
+
+ /**
+ * returns the fragmentShader error log
+ * @return {String}
+ */
+ fragmentShaderLog: function () {
+ return this._glContext.getShaderInfoLog(this._fragShader);
+ },
+
+ /**
+ * returns the program error log
+ * @return {String}
+ */
+ programLog: function () {
+ return this._glContext.getProgramInfoLog(this._programObj);
+ },
+
+ /**
+ * returns the program error log
+ * @return {String}
+ */
+ getProgramLog: function () {
+ return this._glContext.getProgramInfoLog(this._programObj);
+ },
+
+ /**
+ * reload all shaders, this function is designed for android
+ * when opengl context lost, so don't call it.
+ */
+ reset: function () {
+ this._vertShader = null;
+ this._fragShader = null;
+ this._uniforms.length = 0;
+
+ // it is already deallocated by android
+ //ccGLDeleteProgram(m_uProgram);
+ this._glContext.deleteProgram(this._programObj);
+ this._programObj = null;
+
+ // Purge uniform hash
+ for (var i = 0; i < this._hashForUniforms.length; i++) {
+ this._hashForUniforms[i].value = null;
+ this._hashForUniforms[i] = null;
+ }
+
+ this._hashForUniforms.length = 0;
+ },
+
+ /**
+ * get WebGLProgram object
+ * @return {WebGLProgram}
+ */
+ getProgram: function () {
+ return this._programObj;
+ },
+
+ /**
+ * 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 () {
+ },
+ release: function () {
+ }
+});
+
+/**
+ * Create a cc.GLProgram object
+ * @deprecated since v3.0, please use new cc.GLProgram(vShaderFileName, fShaderFileName) instead
+ * @param {String} vShaderFileName
+ * @param {String} fShaderFileName
+ * @returns {cc.GLProgram}
+ */
+cc.GLProgram.create = function (vShaderFileName, fShaderFileName) {
+ return new cc.GLProgram(vShaderFileName, fShaderFileName);
+};
+
+cc.GLProgram._highpSupported = null;
+
+cc.GLProgram._isHighpSupported = function(){
+ if(cc.GLProgram._highpSupported == null){
+ var ctx = cc._renderContext;
+ var highp = ctx.getShaderPrecisionFormat(ctx.FRAGMENT_SHADER, ctx.HIGH_FLOAT);
+ cc.GLProgram._highpSupported = highp.precision !== 0;
+ }
+ return cc.GLProgram._highpSupported;
+};
+
+/**
+ *
+ * Sets the shader program for this node
+ *
+ * Since v2.0, each rendering node must set its shader program.
+ * It should be set in initialize phase.
+ *
+ * @function
+ * @param {cc.Node} node
+ * @param {cc.GLProgram} program The shader program which fetches from CCShaderCache.
+ * @example
+ * cc.setGLProgram(node, cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURECOLOR));
+ */
+cc.setProgram = function (node, program) {
+ node.shaderProgram = program;
+
+ var children = node.children;
+ if (!children)
+ return;
+
+ for (var i = 0; i < children.length; i++)
+ cc.setProgram(children[i], program);
+};
diff --git a/cocos2d/shaders/CCGLStateCache.js b/cocos2d/shaders/CCGLStateCache.js
new file mode 100644
index 0000000000..f048ce03e3
--- /dev/null
+++ b/cocos2d/shaders/CCGLStateCache.js
@@ -0,0 +1,340 @@
+/****************************************************************************
+ 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._currentProjectionMatrix = -1;
+cc._vertexAttribPosition = false;
+cc._vertexAttribColor = false;
+cc._vertexAttribTexCoords = false;
+
+if (cc.ENABLE_GL_STATE_CACHE) {
+ cc.MAX_ACTIVETEXTURE = 16;
+
+ cc._currentShaderProgram = -1;
+ cc._currentBoundTexture = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1];
+ cc._blendingSource = -1;
+ cc._blendingDest = -1;
+ cc._GLServerState = 0;
+ if(cc.TEXTURE_ATLAS_USE_VAO)
+ cc._uVAO = 0;
+}
+
+// GL State Cache functions
+
+/**
+ * Invalidates the GL state cache.
+ * If CC_ENABLE_GL_STATE_CACHE it will reset the GL state cache.
+ * @function
+ */
+cc.glInvalidateStateCache = function () {
+ cc.kmGLFreeAll();
+ cc._currentProjectionMatrix = -1;
+ cc._vertexAttribPosition = false;
+ cc._vertexAttribColor = false;
+ cc._vertexAttribTexCoords = false;
+ if (cc.ENABLE_GL_STATE_CACHE) {
+ cc._currentShaderProgram = -1;
+ for (var i = 0; i < cc.MAX_ACTIVETEXTURE; i++) {
+ cc._currentBoundTexture[i] = -1;
+ }
+ cc._blendingSource = -1;
+ cc._blendingDest = -1;
+ cc._GLServerState = 0;
+ }
+};
+
+/**
+ * Uses the GL program in case program is different than the current one.
+ * If CC_ENABLE_GL_STATE_CACHE is disabled, it will the glUseProgram() directly.
+ * @function
+ * @param {WebGLProgram} program
+ */
+cc.glUseProgram = function (program) {
+ if (program !== cc._currentShaderProgram) {
+ cc._currentShaderProgram = program;
+ cc._renderContext.useProgram(program);
+ }
+};
+
+if(!cc.ENABLE_GL_STATE_CACHE){
+ cc.glUseProgram = function (program) {
+ cc._renderContext.useProgram(program);
+ }
+}
+
+/**
+ * Deletes the GL program. If it is the one that is being used, it invalidates it.
+ * If CC_ENABLE_GL_STATE_CACHE is disabled, it will the glDeleteProgram() directly.
+ * @function
+ * @param {WebGLProgram} program
+ */
+cc.glDeleteProgram = function (program) {
+ if (cc.ENABLE_GL_STATE_CACHE) {
+ if (program === cc._currentShaderProgram)
+ cc._currentShaderProgram = -1;
+ }
+ gl.deleteProgram(program);
+};
+
+/**
+ * Uses a blending function in case it not already used.
+ * If CC_ENABLE_GL_STATE_CACHE is disabled, it will the glBlendFunc() directly.
+ * @function
+ * @param {Number} sfactor
+ * @param {Number} dfactor
+ */
+cc.glBlendFunc = function (sfactor, dfactor) {
+ if ((sfactor !== cc._blendingSource) || (dfactor !== cc._blendingDest)) {
+ cc._blendingSource = sfactor;
+ cc._blendingDest = dfactor;
+ cc.setBlending(sfactor, dfactor);
+ }
+};
+
+/**
+ * @function
+ * @param {Number} sfactor
+ * @param {Number} dfactor
+ */
+cc.setBlending = function (sfactor, dfactor) {
+ var ctx = cc._renderContext;
+ if ((sfactor === ctx.ONE) && (dfactor === ctx.ZERO)) {
+ ctx.disable(ctx.BLEND);
+ } else {
+ ctx.enable(ctx.BLEND);
+ cc._renderContext.blendFunc(sfactor,dfactor);
+ //TODO need fix for WebGL
+ //ctx.blendFuncSeparate(ctx.SRC_ALPHA, dfactor, sfactor, dfactor);
+ }
+};
+
+/**
+ * @function
+ * @param {Number} sfactor
+ * @param {Number} dfactor
+ */
+cc.glBlendFuncForParticle = function(sfactor, dfactor) {
+ if ((sfactor !== cc._blendingSource) || (dfactor !== cc._blendingDest)) {
+ cc._blendingSource = sfactor;
+ cc._blendingDest = dfactor;
+ var ctx = cc._renderContext;
+ if ((sfactor === ctx.ONE) && (dfactor === ctx.ZERO)) {
+ ctx.disable(ctx.BLEND);
+ } else {
+ ctx.enable(ctx.BLEND);
+ //TODO need fix for WebGL
+ ctx.blendFuncSeparate(ctx.SRC_ALPHA, dfactor, sfactor, dfactor);
+ }
+ }
+};
+
+if(!cc.ENABLE_GL_STATE_CACHE){
+ cc.glBlendFunc = cc.setBlending;
+};
+
+/**
+ * Resets the blending mode back to the cached state in case you used glBlendFuncSeparate() or glBlendEquation().
+ * If CC_ENABLE_GL_STATE_CACHE is disabled, it will just set the default blending mode using GL_FUNC_ADD.
+ * @function
+ */
+cc.glBlendResetToCache = function () {
+ var ctx = cc._renderContext;
+ ctx.blendEquation(ctx.FUNC_ADD);
+ if (cc.ENABLE_GL_STATE_CACHE)
+ cc.setBlending(cc._blendingSource, cc._blendingDest);
+ else
+ cc.setBlending(ctx.BLEND_SRC, ctx.BLEND_DST);
+};
+
+/**
+ * sets the projection matrix as dirty
+ * @function
+ */
+cc.setProjectionMatrixDirty = function () {
+ cc._currentProjectionMatrix = -1;
+};
+
+/**
+ *
+ * Will enable the vertex attribs that are passed as flags.
+ * Possible flags:
+ * cc.VERTEX_ATTRIB_FLAG_POSITION
+ * cc.VERTEX_ATTRIB_FLAG_COLOR
+ * cc.VERTEX_ATTRIB_FLAG_TEX_COORDS
+ *
+ * These flags can be ORed. The flags that are not present, will be disabled.
+ *
+ * @function
+ * @param {cc.VERTEX_ATTRIB_FLAG_POSITION | cc.VERTEX_ATTRIB_FLAG_COLOR | cc.VERTEX_ATTRIB_FLAG_TEX_OORDS} flags
+ */
+cc.glEnableVertexAttribs = function (flags) {
+ /* Position */
+ var ctx = cc._renderContext;
+ var enablePosition = ( flags & cc.VERTEX_ATTRIB_FLAG_POSITION );
+ if (enablePosition !== cc._vertexAttribPosition) {
+ if (enablePosition)
+ ctx.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION);
+ else
+ ctx.disableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION);
+ cc._vertexAttribPosition = enablePosition;
+ }
+
+ /* Color */
+ var enableColor = (flags & cc.VERTEX_ATTRIB_FLAG_COLOR);
+ if (enableColor !== cc._vertexAttribColor) {
+ if (enableColor)
+ ctx.enableVertexAttribArray(cc.VERTEX_ATTRIB_COLOR);
+ else
+ ctx.disableVertexAttribArray(cc.VERTEX_ATTRIB_COLOR);
+ cc._vertexAttribColor = enableColor;
+ }
+
+ /* Tex Coords */
+ var enableTexCoords = (flags & cc.VERTEX_ATTRIB_FLAG_TEX_COORDS);
+ if (enableTexCoords !== cc._vertexAttribTexCoords) {
+ if (enableTexCoords)
+ ctx.enableVertexAttribArray(cc.VERTEX_ATTRIB_TEX_COORDS);
+ else
+ ctx.disableVertexAttribArray(cc.VERTEX_ATTRIB_TEX_COORDS);
+ cc._vertexAttribTexCoords = enableTexCoords;
+ }
+};
+
+/**
+ * If the texture is not already bound, it binds it.
+ * If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glBindTexture() directly.
+ * @function
+ * @param {cc.Texture2D} textureId
+ */
+cc.glBindTexture2D = function (textureId) {
+ cc.glBindTexture2DN(0, textureId);
+};
+
+/**
+ * If the texture is not already bound to a given unit, it binds it.
+ * If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glBindTexture() directly.
+ * @function
+ * @param {Number} textureUnit
+ * @param {cc.Texture2D} textureId
+ */
+cc.glBindTexture2DN = function (textureUnit, textureId) {
+ if (cc._currentBoundTexture[textureUnit] === textureId)
+ return;
+ cc._currentBoundTexture[textureUnit] = textureId;
+
+ var ctx = cc._renderContext;
+ ctx.activeTexture(ctx.TEXTURE0 + textureUnit);
+ if(textureId)
+ ctx.bindTexture(ctx.TEXTURE_2D, textureId._webTextureObj);
+ else
+ ctx.bindTexture(ctx.TEXTURE_2D, null);
+};
+if (!cc.ENABLE_GL_STATE_CACHE){
+ cc.glBindTexture2DN = function (textureUnit, textureId) {
+ var ctx = cc._renderContext;
+ ctx.activeTexture(ctx.TEXTURE0 + textureUnit);
+ if(textureId)
+ ctx.bindTexture(ctx.TEXTURE_2D, textureId._webTextureObj);
+ else
+ ctx.bindTexture(ctx.TEXTURE_2D, null);
+ };
+}
+
+/**
+ * It will delete a given texture. If the texture was bound, it will invalidate the cached.
+ * If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glDeleteTextures() directly.
+ * @function
+ * @param {WebGLTexture} textureId
+ */
+cc.glDeleteTexture = function (textureId) {
+ cc.glDeleteTextureN(0, textureId);
+};
+
+/**
+ * It will delete a given texture. If the texture was bound, it will invalidate the cached for the given texture unit.
+ * If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glDeleteTextures() directly.
+ * @function
+ * @param {Number} textureUnit
+ * @param {WebGLTexture} textureId
+ */
+cc.glDeleteTextureN = function (textureUnit, textureId) {
+ if (cc.ENABLE_GL_STATE_CACHE) {
+ if (textureId === cc._currentBoundTexture[ textureUnit ])
+ cc._currentBoundTexture[ textureUnit ] = -1;
+ }
+ cc._renderContext.deleteTexture(textureId);
+};
+
+/**
+ * If the vertex array is not already bound, it binds it.
+ * If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glBindVertexArray() directly.
+ * @function
+ * @param {Number} vaoId
+ */
+cc.glBindVAO = function (vaoId) {
+ if (!cc.TEXTURE_ATLAS_USE_VAO)
+ return;
+
+ if (cc.ENABLE_GL_STATE_CACHE) {
+ if (cc._uVAO !== vaoId) {
+ cc._uVAO = vaoId;
+ //TODO need fixed
+ //glBindVertexArray(vaoId);
+ }
+ } else {
+ //glBindVertexArray(vaoId);
+ }
+};
+
+/**
+ * It will enable / disable the server side GL states.
+ * If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glEnable() directly.
+ * @function
+ * @param {Number} flags
+ */
+cc.glEnable = function (flags) {
+ if (cc.ENABLE_GL_STATE_CACHE) {
+ /*var enabled;
+
+ */
+ /* GL_BLEND */
+ /*
+ if ((enabled = (flags & cc.GL_BLEND)) != (cc._GLServerState & cc.GL_BLEND)) {
+ if (enabled) {
+ cc._renderContext.enable(cc._renderContext.BLEND);
+ cc._GLServerState |= cc.GL_BLEND;
+ } else {
+ cc._renderContext.disable(cc._renderContext.BLEND);
+ cc._GLServerState &= ~cc.GL_BLEND;
+ }
+ }*/
+ } else {
+ /*if ((flags & cc.GL_BLEND))
+ cc._renderContext.enable(cc._renderContext.BLEND);
+ else
+ cc._renderContext.disable(cc._renderContext.BLEND);*/
+ }
+};
+
diff --git a/cocos2d/shaders/CCShaderCache.js b/cocos2d/shaders/CCShaderCache.js
new file mode 100644
index 0000000000..f78780ddb6
--- /dev/null
+++ b/cocos2d/shaders/CCShaderCache.js
@@ -0,0 +1,301 @@
+/****************************************************************************
+ 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.shaderCache is a singleton object that stores manages GL shaders
+ * @class
+ * @name cc.shaderCache
+ */
+cc.shaderCache = /** @lends cc.shaderCache# */{
+
+ /**
+ * @public
+ * @constant
+ * @type {Number}
+ */
+ TYPE_POSITION_TEXTURECOLOR: 0,
+ /**
+ * @public
+ * @constant
+ * @type {Number}
+ */
+ TYPE_POSITION_TEXTURECOLOR_ALPHATEST: 1,
+ /**
+ * @public
+ * @constant
+ * @type {Number}
+ */
+ TYPE_POSITION_COLOR: 2,
+ /**
+ * @public
+ * @constant
+ * @type {Number}
+ */
+ TYPE_POSITION_TEXTURE: 3,
+ /**
+ * @public
+ * @constant
+ * @type {Number}
+ */
+ TYPE_POSITION_TEXTURE_UCOLOR: 4,
+ /**
+ * @public
+ * @constant
+ * @type {Number}
+ */
+ TYPE_POSITION_TEXTURE_A8COLOR: 5,
+ /**
+ * @public
+ * @constant
+ * @type {Number}
+ */
+ TYPE_POSITION_UCOLOR: 6,
+ /**
+ * @public
+ * @constant
+ * @type {Number}
+ */
+ TYPE_POSITION_LENGTH_TEXTURECOLOR: 7,
+ /**
+ * @public
+ * @constant
+ * @type {Number}
+ */
+ TYPE_MAX: 8,
+
+ _programs: {},
+
+ _init: function () {
+ this.loadDefaultShaders();
+ return true;
+ },
+
+ _loadDefaultShader: function (program, type) {
+ switch (type) {
+ case this.TYPE_POSITION_TEXTURECOLOR:
+ program.initWithVertexShaderByteArray(cc.SHADER_POSITION_TEXTURE_COLOR_VERT, cc.SHADER_POSITION_TEXTURE_COLOR_FRAG);
+
+ program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
+ program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR);
+ program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
+ break;
+ case this.TYPE_POSITION_TEXTURECOLOR_ALPHATEST:
+ program.initWithVertexShaderByteArray(cc.SHADER_POSITION_TEXTURE_COLOR_VERT, cc.SHADER_POSITION_TEXTURE_COLOR_ALPHATEST_FRAG);
+
+ program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
+ program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR);
+ program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
+ break;
+ case this.TYPE_POSITION_COLOR:
+ program.initWithVertexShaderByteArray(cc.SHADER_POSITION_COLOR_VERT, cc.SHADER_POSITION_COLOR_FRAG);
+
+ program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
+ program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR);
+ break;
+ case this.TYPE_POSITION_TEXTURE:
+ program.initWithVertexShaderByteArray(cc.SHADER_POSITION_TEXTURE_VERT, cc.SHADER_POSITION_TEXTURE_FRAG);
+
+ program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
+ program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
+ break;
+ case this.TYPE_POSITION_TEXTURE_UCOLOR:
+ program.initWithVertexShaderByteArray(cc.SHADER_POSITION_TEXTURE_UCOLOR_VERT, cc.SHADER_POSITION_TEXTURE_UCOLOR_FRAG);
+
+ program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
+ program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
+ break;
+ case this.TYPE_POSITION_TEXTURE_A8COLOR:
+ program.initWithVertexShaderByteArray(cc.SHADER_POSITION_TEXTURE_A8COLOR_VERT, cc.SHADER_POSITION_TEXTURE_A8COLOR_FRAG);
+
+ program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
+ program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR);
+ program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
+ break;
+ case this.TYPE_POSITION_UCOLOR:
+ program.initWithVertexShaderByteArray(cc.SHADER_POSITION_UCOLOR_VERT, cc.SHADER_POSITION_UCOLOR_FRAG);
+ program.addAttribute("aVertex", cc.VERTEX_ATTRIB_POSITION);
+ break;
+ case this.TYPE_POSITION_LENGTH_TEXTURECOLOR:
+ program.initWithVertexShaderByteArray(cc.SHADER_POSITION_COLOR_LENGTH_TEXTURE_VERT, cc.SHADER_POSITION_COLOR_LENGTH_TEXTURE_FRAG);
+
+ program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
+ program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
+ program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR);
+ break;
+ default:
+ cc.log("cocos2d: cc.shaderCache._loadDefaultShader, error shader type");
+ return;
+ }
+
+ program.link();
+ program.updateUniforms();
+
+ //cc.checkGLErrorDebug();
+ },
+
+ /**
+ * loads the default shaders
+ */
+ loadDefaultShaders: function () {
+ // Position Texture Color shader
+ var program = new cc.GLProgram();
+ this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURECOLOR);
+ this._programs[cc.SHADER_POSITION_TEXTURECOLOR] = program;
+ this._programs["ShaderPositionTextureColor"] = program;
+
+ // Position Texture Color alpha test
+ program = new cc.GLProgram();
+ this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURECOLOR_ALPHATEST);
+ this._programs[cc.SHADER_POSITION_TEXTURECOLORALPHATEST] = program;
+ this._programs["ShaderPositionTextureColorAlphaTest"] = program;
+
+ //
+ // Position, Color shader
+ //
+ program = new cc.GLProgram();
+ this._loadDefaultShader(program, this.TYPE_POSITION_COLOR);
+ this._programs[cc.SHADER_POSITION_COLOR] = program;
+ this._programs["ShaderPositionColor"] = program;
+
+ //
+ // Position Texture shader
+ //
+ program = new cc.GLProgram();
+ this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURE);
+ this._programs[cc.SHADER_POSITION_TEXTURE] = program;
+ this._programs["ShaderPositionTexture"] = program;
+
+ //
+ // Position, Texture attribs, 1 Color as uniform shader
+ //
+ program = new cc.GLProgram();
+ this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURE_UCOLOR);
+ this._programs[cc.SHADER_POSITION_TEXTURE_UCOLOR] = program;
+ this._programs["ShaderPositionTextureUColor"] = program;
+
+ //
+ // Position Texture A8 Color shader
+ //
+ program = new cc.GLProgram();
+ this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURE_A8COLOR);
+ this._programs[cc.SHADER_POSITION_TEXTUREA8COLOR] = program;
+ this._programs["ShaderPositionTextureA8Color"] = program;
+
+ //
+ // Position and 1 color passed as a uniform (to similate glColor4ub )
+ //
+ program = new cc.GLProgram();
+ this._loadDefaultShader(program, this.TYPE_POSITION_UCOLOR);
+ this._programs[cc.SHADER_POSITION_UCOLOR] = program;
+ this._programs["ShaderPositionUColor"] = program;
+
+ //
+ // Position, Legth(TexCoords, Color (used by Draw Node basically )
+ //
+ program = new cc.GLProgram();
+ this._loadDefaultShader(program, this.TYPE_POSITION_LENGTH_TEXTURECOLOR);
+ this._programs[cc.SHADER_POSITION_LENGTHTEXTURECOLOR] = program;
+ this._programs["ShaderPositionLengthTextureColor"] = program;
+ },
+
+ /**
+ * reload the default shaders
+ */
+ reloadDefaultShaders: function () {
+ // reset all programs and reload them
+
+ // Position Texture Color shader
+ var program = this.programForKey(cc.SHADER_POSITION_TEXTURECOLOR);
+ program.reset();
+ this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURECOLOR);
+
+ // Position Texture Color alpha test
+ program = this.programForKey(cc.SHADER_POSITION_TEXTURECOLORALPHATEST);
+ program.reset();
+ this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURECOLOR_ALPHATEST);
+
+ //
+ // Position, Color shader
+ //
+ program = this.programForKey(cc.SHADER_POSITION_COLOR);
+ program.reset();
+ this._loadDefaultShader(program, this.TYPE_POSITION_COLOR);
+
+ //
+ // Position Texture shader
+ //
+ program = this.programForKey(cc.SHADER_POSITION_TEXTURE);
+ program.reset();
+ this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURE);
+
+ //
+ // Position, Texture attribs, 1 Color as uniform shader
+ //
+ program = this.programForKey(cc.SHADER_POSITION_TEXTURE_UCOLOR);
+ program.reset();
+ this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURE_UCOLOR);
+
+ //
+ // Position Texture A8 Color shader
+ //
+ program = this.programForKey(cc.SHADER_POSITION_TEXTUREA8COLOR);
+ program.reset();
+ this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURE_A8COLOR);
+
+ //
+ // Position and 1 color passed as a uniform (to similate glColor4ub )
+ //
+ program = this.programForKey(cc.SHADER_POSITION_UCOLOR);
+ program.reset();
+ this._loadDefaultShader(program, this.TYPE_POSITION_UCOLOR);
+ },
+
+ /**
+ * returns a GL program for a given key
+ * @param {String} key
+ */
+ programForKey: function (key) {
+ return this._programs[key];
+ },
+
+ /**
+ * returns a GL program for a shader name
+ * @param {String} shaderName
+ * @return {cc.GLProgram}
+ */
+ getProgram: function (shaderName) {
+ return this._programs[shaderName];
+ },
+
+ /**
+ * adds a CCGLProgram to the cache for a given name
+ * @param {cc.GLProgram} program
+ * @param {String} key
+ */
+ addProgram: function (program, key) {
+ this._programs[key] = program;
+ }
+};
\ No newline at end of file
diff --git a/cocos2d/shaders/CCShaders.js b/cocos2d/shaders/CCShaders.js
new file mode 100644
index 0000000000..437ce589aa
--- /dev/null
+++ b/cocos2d/shaders/CCShaders.js
@@ -0,0 +1,280 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+//-----------------------Shader_Position_uColor Shader Source--------------------------
+/**
+ * @constant
+ * @type {String}
+ */
+cc.SHADER_POSITION_UCOLOR_FRAG =
+ "precision lowp float;\n"
+ + "varying vec4 v_fragmentColor;\n"
+ + "void main() \n"
+ + "{ \n"
+ + " gl_FragColor = v_fragmentColor; \n"
+ + "}\n";
+/**
+ * @constant
+ * @type {String}
+ */
+cc.SHADER_POSITION_UCOLOR_VERT =
+ "attribute vec4 a_position;\n"
+ + "uniform vec4 u_color;\n"
+ + "uniform float u_pointSize;\n"
+ + "varying lowp vec4 v_fragmentColor; \n"
+ + "void main(void) \n"
+ + "{\n"
+ //+ " gl_Position = CC_MVPMatrix * a_position; \n"
+ + " gl_Position = (CC_PMatrix * CC_MVMatrix) * a_position; \n"
+ + " gl_PointSize = u_pointSize; \n"
+ + " v_fragmentColor = u_color; \n"
+ + "}";
+
+//---------------------Shader_PositionColor Shader Source-----------------------
+/**
+ * @constant
+ * @type {String}
+ */
+cc.SHADER_POSITION_COLOR_FRAG =
+ "precision lowp float; \n"
+ + "varying vec4 v_fragmentColor; \n"
+ + "void main() \n"
+ + "{ \n"
+ + " gl_FragColor = v_fragmentColor; \n"
+ + "} ";
+
+/**
+ * @constant
+ * @type {String}
+ */
+cc.SHADER_POSITION_COLOR_VERT =
+ "attribute vec4 a_position;\n"
+ + "attribute vec4 a_color;\n"
+ + "varying lowp vec4 v_fragmentColor;\n"
+ + "void main()\n"
+ + "{\n"
+ //+ " gl_Position = CC_MVPMatrix * a_position; \n"
+ + " gl_Position = (CC_PMatrix * CC_MVMatrix) * a_position; \n"
+ + " v_fragmentColor = a_color; \n"
+ + "}";
+
+// --------------------- Shader_PositionColorLengthTexture Shader source------------------------
+/**
+ * @constant
+ * @type {String}
+ */
+cc.SHADER_POSITION_COLOR_LENGTH_TEXTURE_FRAG =
+ "// #extension GL_OES_standard_derivatives : enable\n"
+ + "varying mediump vec4 v_color;\n"
+ + "varying mediump vec2 v_texcoord;\n"
+ + "void main() \n"
+ + "{ \n"
+ + "// #if defined GL_OES_standard_derivatives \n"
+ + "// gl_FragColor = v_color*smoothstep(0.0, length(fwidth(v_texcoord)), 1.0 - length(v_texcoord)); \n"
+ + "// #else \n"
+ + "gl_FragColor = v_color * step(0.0, 1.0 - length(v_texcoord)); \n"
+ + "// #endif \n"
+ + "}";
+
+/**
+ * @constant
+ * @type {String}
+ */
+cc.SHADER_POSITION_COLOR_LENGTH_TEXTURE_VERT =
+ "attribute mediump vec4 a_position; \n"
+ + "attribute mediump vec2 a_texcoord; \n"
+ + "attribute mediump vec4 a_color; \n"
+ + "varying mediump vec4 v_color; \n"
+ + "varying mediump vec2 v_texcoord; \n"
+ + "void main() \n"
+ + "{ \n"
+ + " v_color = a_color;//vec4(a_color.rgb * a_color.a, a_color.a); \n"
+ + " v_texcoord = a_texcoord; \n"
+ //+ " gl_Position = CC_MVPMatrix * a_position; \n"
+ + " gl_Position = (CC_PMatrix * CC_MVMatrix) * a_position; \n"
+ + "}";
+
+// ----------------------Shader_PositionTexture Shader Source-------------------------------------
+/**
+ * @constant
+ * @type {String}
+ */
+cc.SHADER_POSITION_TEXTURE_FRAG =
+ "precision lowp float; \n"
+ + "varying vec2 v_texCoord; \n"
+ + "void main() \n"
+ + "{ \n"
+ + " gl_FragColor = texture2D(CC_Texture0, v_texCoord); \n"
+ + "}";
+
+/**
+ * @constant
+ * @type {String}
+ */
+cc.SHADER_POSITION_TEXTURE_VERT =
+ "attribute vec4 a_position; \n"
+ + "attribute vec2 a_texCoord; \n"
+ + "varying mediump vec2 v_texCoord; \n"
+ + "void main() \n"
+ + "{ \n"
+ //+ " gl_Position = CC_MVPMatrix * a_position; \n"
+ + " gl_Position = (CC_PMatrix * CC_MVMatrix) * a_position; \n"
+ + " v_texCoord = a_texCoord; \n"
+ + "}";
+
+// ------------------------Shader_PositionTexture_uColor Shader Source-------------------------------
+/**
+ * @constant
+ * @type {String}
+ */
+cc.SHADER_POSITION_TEXTURE_UCOLOR_FRAG =
+ "precision lowp float; \n"
+ + "uniform vec4 u_color; \n"
+ + "varying vec2 v_texCoord; \n"
+ + "void main() \n"
+ + "{ \n"
+ + " gl_FragColor = texture2D(CC_Texture0, v_texCoord) * u_color; \n"
+ + "}";
+
+/**
+ * @constant
+ * @type {String}
+ */
+cc.SHADER_POSITION_TEXTURE_UCOLOR_VERT =
+ "attribute vec4 a_position;\n"
+ + "attribute vec2 a_texCoord; \n"
+ + "varying mediump vec2 v_texCoord; \n"
+ + "void main() \n"
+ + "{ \n"
+ //+ " gl_Position = CC_MVPMatrix * a_position; \n"
+ + " gl_Position = (CC_PMatrix * CC_MVMatrix) * a_position; \n"
+ + " v_texCoord = a_texCoord; \n"
+ + "}";
+
+//---------------------Shader_PositionTextureA8Color Shader source-------------------------------
+/**
+ * @constant
+ * @type {String}
+ */
+cc.SHADER_POSITION_TEXTURE_A8COLOR_FRAG =
+ "precision lowp float; \n"
+ + "varying vec4 v_fragmentColor; \n"
+ + "varying vec2 v_texCoord; \n"
+ + "void main() \n"
+ + "{ \n"
+ + " gl_FragColor = vec4( v_fragmentColor.rgb, \n" // RGB from uniform
+ + " v_fragmentColor.a * texture2D(CC_Texture0, v_texCoord).a \n" // A from texture and uniform
+ + " ); \n"
+ + "}";
+
+/**
+ * @constant
+ * @type {String}
+ */
+cc.SHADER_POSITION_TEXTURE_A8COLOR_VERT =
+ "attribute vec4 a_position; \n"
+ + "attribute vec2 a_texCoord; \n"
+ + "attribute vec4 a_color; \n"
+ + "varying lowp vec4 v_fragmentColor; \n"
+ + "varying mediump vec2 v_texCoord; \n"
+ + "void main() \n"
+ + "{ \n"
+ //+ " gl_Position = CC_MVPMatrix * a_position; \n"
+ + " gl_Position = (CC_PMatrix * CC_MVMatrix) * a_position; \n"
+ + " v_fragmentColor = a_color; \n"
+ + " v_texCoord = a_texCoord; \n"
+ + "}";
+
+// ------------------------Shader_PositionTextureColor Shader source------------------------------------
+/**
+ * @constant
+ * @type {String}
+ */
+cc.SHADER_POSITION_TEXTURE_COLOR_FRAG =
+ "precision lowp float;\n"
+ + "varying vec4 v_fragmentColor; \n"
+ + "varying vec2 v_texCoord; \n"
+ + "void main() \n"
+ + "{ \n"
+ + " gl_FragColor = v_fragmentColor * texture2D(CC_Texture0, v_texCoord); \n"
+ + "}";
+
+/**
+ * @constant
+ * @type {String}
+ */
+cc.SHADER_POSITION_TEXTURE_COLOR_VERT =
+ "attribute vec4 a_position; \n"
+ + "attribute vec2 a_texCoord; \n"
+ + "attribute vec4 a_color; \n"
+ + "varying lowp vec4 v_fragmentColor; \n"
+ + "varying mediump vec2 v_texCoord; \n"
+ + "void main() \n"
+ + "{ \n"
+ //+ " gl_Position = CC_MVPMatrix * a_position; \n"
+ + " gl_Position = (CC_PMatrix * CC_MVMatrix) * a_position; \n"
+ + " v_fragmentColor = a_color; \n"
+ + " v_texCoord = a_texCoord; \n"
+ + "}";
+
+//-----------------------Shader_PositionTextureColorAlphaTest_frag Shader Source----------------------------
+/**
+ * @constant
+ * @type {String}
+ */
+cc.SHADER_POSITION_TEXTURE_COLOR_ALPHATEST_FRAG =
+ "precision lowp float; \n"
+ + "varying vec4 v_fragmentColor; \n"
+ + "varying vec2 v_texCoord; \n"
+ + "uniform float CC_alpha_value; \n"
+ + "void main() \n"
+ + "{ \n"
+ + " vec4 texColor = texture2D(CC_Texture0, v_texCoord); \n"
+ // mimic: glAlphaFunc(GL_GREATER)
+ //pass if ( incoming_pixel >= CC_alpha_value ) => fail if incoming_pixel < CC_alpha_value
+ + " if ( texColor.a <= CC_alpha_value ) \n"
+ + " discard; \n"
+ + " gl_FragColor = texColor * v_fragmentColor; \n"
+ + "}";
+
+//-----------------------ShaderEx_SwitchMask_frag Shader Source----------------------------
+/**
+ * @constant
+ * @type {String}
+ */
+cc.SHADEREX_SWITCHMASK_FRAG =
+ "precision lowp float; \n"
+ + "varying vec4 v_fragmentColor; \n"
+ + "varying vec2 v_texCoord; \n"
+ + "uniform sampler2D u_texture; \n"
+ + "uniform sampler2D u_mask; \n"
+ + "void main() \n"
+ + "{ \n"
+ + " vec4 texColor = texture2D(u_texture, v_texCoord); \n"
+ + " vec4 maskColor = texture2D(u_mask, v_texCoord); \n"
+ + " vec4 finalColor = vec4(texColor.r, texColor.g, texColor.b, maskColor.a * texColor.a); \n"
+ + " gl_FragColor = v_fragmentColor * finalColor; \n"
+ + "}";
\ No newline at end of file
diff --git a/cocos2d/shape-nodes/CCDrawNode.js b/cocos2d/shape-nodes/CCDrawNode.js
new file mode 100644
index 0000000000..7eb69935ef
--- /dev/null
+++ b/cocos2d/shape-nodes/CCDrawNode.js
@@ -0,0 +1,905 @@
+/****************************************************************************
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2012 Scott Lembcke and Howling Moon Software
+
+ 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.
+ ****************************************************************************/
+
+/**
+ * Code copied & pasted from SpacePatrol game https://github.com/slembcke/SpacePatrol
+ *
+ * Renamed and added some changes for cocos2d
+ *
+ */
+cc.v2fzero = function () {
+ return {x: 0, y: 0};
+};
+
+cc.v2f = function (x, y) {
+ return {x: x, y: y};
+};
+
+cc.v2fadd = function (v0, v1) {
+ return cc.v2f(v0.x + v1.x, v0.y + v1.y);
+};
+
+cc.v2fsub = function (v0, v1) {
+ return cc.v2f(v0.x - v1.x, v0.y - v1.y);
+};
+
+cc.v2fmult = function (v, s) {
+ return cc.v2f(v.x * s, v.y * s);
+};
+
+cc.v2fperp = function (p0) {
+ return cc.v2f(-p0.y, p0.x);
+};
+
+cc.v2fneg = function (p0) {
+ return cc.v2f(-p0.x, -p0.y);
+};
+
+cc.v2fdot = function (p0, p1) {
+ return p0.x * p1.x + p0.y * p1.y;
+};
+
+cc.v2fforangle = function (_a_) {
+ return cc.v2f(Math.cos(_a_), Math.sin(_a_));
+};
+
+cc.v2fnormalize = function (p) {
+ var r = cc.pNormalize(cc.p(p.x, p.y));
+ return cc.v2f(r.x, r.y);
+};
+
+cc.__v2f = function (v) {
+ return cc.v2f(v.x, v.y);
+};
+
+cc.__t = function (v) {
+ return {u: v.x, v: v.y};
+};
+
+/**
+ * CCDrawNode
+ * Node that draws dots, segments and polygons.
+ * Faster than the "drawing primitives" since they it draws everything in one single batch.
+ * @class
+ * @name cc.DrawNode
+ * @extends cc.Node
+ */
+cc.DrawNode = cc.Node.extend(/** @lends cc.DrawNode# */{
+//TODO need refactor
+
+ _buffer:null,
+ _blendFunc:null,
+ _lineWidth: 1,
+ _drawColor: null,
+
+ /**
+ * Gets the blend func
+ * @returns {Object}
+ */
+ getBlendFunc: function () {
+ return this._blendFunc;
+ },
+
+ /**
+ * Set the blend func
+ * @param blendFunc
+ * @param dst
+ */
+ setBlendFunc: function (blendFunc, dst) {
+ if (dst === undefined) {
+ this._blendFunc.src = blendFunc.src;
+ this._blendFunc.dst = blendFunc.dst;
+ } else {
+ this._blendFunc.src = blendFunc;
+ this._blendFunc.dst = dst;
+ }
+ },
+
+ /**
+ * line width setter
+ * @param {Number} width
+ */
+ setLineWidth: function (width) {
+ this._lineWidth = width;
+ },
+
+ /**
+ * line width getter
+ * @returns {Number}
+ */
+ getLineWidth: function () {
+ return this._lineWidth;
+ },
+
+ /**
+ * draw color setter
+ * @param {cc.Color} color
+ */
+ setDrawColor: function (color) {
+ var locDrawColor = this._drawColor;
+ locDrawColor.r = color.r;
+ locDrawColor.g = color.g;
+ locDrawColor.b = color.b;
+ locDrawColor.a = (color.a == null) ? 255 : color.a;
+ },
+
+ /**
+ * draw color getter
+ * @returns {cc.Color}
+ */
+ getDrawColor: function () {
+ return cc.color(this._drawColor.r, this._drawColor.g, this._drawColor.b, this._drawColor.a);
+ }
+});
+
+/**
+ * Creates a DrawNode
+ * @deprecated since v3.0 please use new cc.DrawNode() instead.
+ * @return {cc.DrawNode}
+ */
+cc.DrawNode.create = function () {
+ return new cc.DrawNode();
+};
+
+cc.DrawNode.TYPE_DOT = 0;
+cc.DrawNode.TYPE_SEGMENT = 1;
+cc.DrawNode.TYPE_POLY = 2;
+
+cc.game.once(cc.game.EVENT_RENDERER_INITED, function () {
+ if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
+
+ cc._DrawNodeElement = function (type, verts, fillColor, lineWidth, lineColor, lineCap, isClosePolygon, isFill, isStroke) {
+ var _t = this;
+ _t.type = type;
+ _t.verts = verts || null;
+ _t.fillColor = fillColor || null;
+ _t.lineWidth = lineWidth || 0;
+ _t.lineColor = lineColor || null;
+ _t.lineCap = lineCap || "butt";
+ _t.isClosePolygon = isClosePolygon || false;
+ _t.isFill = isFill || false;
+ _t.isStroke = isStroke || false;
+ };
+
+ cc.js.mixin(cc.DrawNode.prototype, /** @lends cc.DrawNode# */{
+ _className:"DrawNodeCanvas",
+
+ /**
+ * The cc.DrawNodeCanvas's constructor.
+ * This function will automatically be invoked when you create a node using new construction: "var node = new cc.DrawNodeCanvas()".
+ * Override it to extend its behavior, remember to call "this._super()" in the extended "ctor" function.
+ */
+ ctor: function () {
+ cc.Node.prototype.ctor.call(this);
+ var locCmd = this._renderCmd;
+ locCmd._buffer = this._buffer = [];
+ locCmd._drawColor = this._drawColor = cc.color(255, 255, 255, 255);
+ locCmd._blendFunc = this._blendFunc = new cc.BlendFunc(cc.SRC_ALPHA, cc.ONE_MINUS_SRC_ALPHA);
+
+ this.init();
+ },
+
+ /**
+ * draws a rectangle given the origin and destination point measured in points.
+ * @param {cc.Vec2} origin
+ * @param {cc.Vec2} destination
+ * @param {cc.Color} fillColor
+ * @param {Number} lineWidth
+ * @param {cc.Color} lineColor
+ */
+ drawRect: function (origin, destination, fillColor, lineWidth, lineColor) {
+ lineWidth = (lineWidth == null) ? this._lineWidth : lineWidth;
+ lineColor = lineColor || this.getDrawColor();
+ if(lineColor.a == null)
+ lineColor.a = 255;
+
+ var vertices = [
+ origin,
+ cc.p(destination.x, origin.y),
+ destination,
+ cc.p(origin.x, destination.y)
+ ];
+ var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY);
+ element.verts = vertices;
+ element.lineWidth = lineWidth;
+ element.lineColor = lineColor;
+ element.isClosePolygon = true;
+ element.isStroke = true;
+ element.lineCap = "butt";
+ element.fillColor = fillColor;
+ if (fillColor) {
+ if(fillColor.a == null)
+ fillColor.a = 255;
+ element.isFill = true;
+ }
+ this._buffer.push(element);
+ },
+
+ /**
+ * draws a circle given the center, radius and number of segments.
+ * @override
+ * @param {cc.Vec2} center center of circle
+ * @param {Number} radius
+ * @param {Number} angle angle in radians
+ * @param {Number} segments
+ * @param {Boolean} drawLineToCenter
+ * @param {Number} lineWidth
+ * @param {cc.Color} color
+ */
+ drawCircle: function (center, radius, angle, segments, drawLineToCenter, lineWidth, color) {
+ lineWidth = lineWidth || this._lineWidth;
+ color = color || this.getDrawColor();
+ if (color.a == null)
+ color.a = 255;
+
+ var coef = 2.0 * Math.PI / segments;
+ var vertices = [];
+ for (var i = 0; i <= segments; i++) {
+ var rads = i * coef;
+ var j = radius * Math.cos(rads + angle) + center.x;
+ var k = radius * Math.sin(rads + angle) + center.y;
+ vertices.push(cc.p(j, k));
+ }
+ if (drawLineToCenter) {
+ vertices.push(cc.p(center.x, center.y));
+ }
+
+ var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY);
+ element.verts = vertices;
+ element.lineWidth = lineWidth;
+ element.lineColor = color;
+ element.isClosePolygon = true;
+ element.isStroke = true;
+ this._buffer.push(element);
+ },
+
+ /**
+ * draws a quad bezier path
+ * @override
+ * @param {cc.Vec2} origin
+ * @param {cc.Vec2} control
+ * @param {cc.Vec2} destination
+ * @param {Number} segments
+ * @param {Number} lineWidth
+ * @param {cc.Color} color
+ */
+ drawQuadBezier: function (origin, control, destination, segments, lineWidth, color) {
+ lineWidth = lineWidth || this._lineWidth;
+ color = color || this.getDrawColor();
+ if (color.a == null)
+ color.a = 255;
+
+ var vertices = [], t = 0.0;
+ for (var i = 0; i < segments; i++) {
+ var x = Math.pow(1 - t, 2) * origin.x + 2.0 * (1 - t) * t * control.x + t * t * destination.x;
+ var y = Math.pow(1 - t, 2) * origin.y + 2.0 * (1 - t) * t * control.y + t * t * destination.y;
+ vertices.push(cc.p(x, y));
+ t += 1.0 / segments;
+ }
+ vertices.push(cc.p(destination.x, destination.y));
+
+ var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY);
+ element.verts = vertices;
+ element.lineWidth = lineWidth;
+ element.lineColor = color;
+ element.isStroke = true;
+ element.lineCap = "round";
+ this._buffer.push(element);
+ },
+
+ /**
+ * draws a cubic bezier path
+ * @override
+ * @param {cc.Vec2} origin
+ * @param {cc.Vec2} control1
+ * @param {cc.Vec2} control2
+ * @param {cc.Vec2} destination
+ * @param {Number} segments
+ * @param {Number} lineWidth
+ * @param {cc.Color} color
+ */
+ drawCubicBezier: function (origin, control1, control2, destination, segments, lineWidth, color) {
+ lineWidth = lineWidth || this._lineWidth;
+ color = color || this.getDrawColor();
+ if (color.a == null)
+ color.a = 255;
+
+ var vertices = [], t = 0;
+ for (var i = 0; i < segments; i++) {
+ var x = Math.pow(1 - t, 3) * origin.x + 3.0 * Math.pow(1 - t, 2) * t * control1.x + 3.0 * (1 - t) * t * t * control2.x + t * t * t * destination.x;
+ var y = Math.pow(1 - t, 3) * origin.y + 3.0 * Math.pow(1 - t, 2) * t * control1.y + 3.0 * (1 - t) * t * t * control2.y + t * t * t * destination.y;
+ vertices.push(cc.p(x, y));
+ t += 1.0 / segments;
+ }
+ vertices.push(cc.p(destination.x, destination.y));
+
+ var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY);
+ element.verts = vertices;
+ element.lineWidth = lineWidth;
+ element.lineColor = color;
+ element.isStroke = true;
+ element.lineCap = "round";
+ this._buffer.push(element);
+ },
+
+ /**
+ * draw a CatmullRom curve
+ * @override
+ * @param {Array} points
+ * @param {Number} segments
+ * @param {Number} lineWidth
+ * @param {cc.Color} color
+ */
+ drawCatmullRom: function (points, segments, lineWidth, color) {
+ this.drawCardinalSpline(points, 0.5, segments, lineWidth, color);
+ },
+
+ /**
+ * draw a cardinal spline path
+ * @override
+ * @param {Array} config
+ * @param {Number} tension
+ * @param {Number} segments
+ * @param {Number} lineWidth
+ * @param {cc.Color} color
+ */
+ drawCardinalSpline: function (config, tension, segments, lineWidth, color) {
+ lineWidth = lineWidth || this._lineWidth;
+ color = color || this.getDrawColor();
+ if(color.a == null)
+ color.a = 255;
+
+ var vertices = [], p, lt, deltaT = 1.0 / config.length;
+ for (var i = 0; i < segments + 1; i++) {
+ var dt = i / segments;
+ // border
+ if (dt === 1) {
+ p = config.length - 1;
+ lt = 1;
+ } else {
+ p = 0 | (dt / deltaT);
+ lt = (dt - deltaT * p) / deltaT;
+ }
+
+ // Interpolate
+ var newPos = cc.cardinalSplineAt(
+ cc.getControlPointAt(config, p - 1),
+ cc.getControlPointAt(config, p - 0),
+ cc.getControlPointAt(config, p + 1),
+ cc.getControlPointAt(config, p + 2),
+ tension, lt);
+ vertices.push(newPos);
+ }
+
+ var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY);
+ element.verts = vertices;
+ element.lineWidth = lineWidth;
+ element.lineColor = color;
+ element.isStroke = true;
+ element.lineCap = "round";
+ this._buffer.push(element);
+ },
+
+ /**
+ * draw a dot at a position, with a given radius and color
+ * @param {cc.Vec2} pos
+ * @param {Number} radius
+ * @param {cc.Color} color
+ */
+ drawDot: function (pos, radius, color) {
+ color = color || this.getDrawColor();
+ if (color.a == null)
+ color.a = 255;
+ var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_DOT);
+ element.verts = [pos];
+ element.lineWidth = radius;
+ element.fillColor = color;
+ this._buffer.push(element);
+ },
+
+ /**
+ * draws an array of points.
+ * @override
+ * @param {Array} points point of array
+ * @param {Number} radius
+ * @param {cc.Color} color
+ */
+ drawDots: function(points, radius, color){
+ if(!points || points.length == 0)
+ return;
+ color = color || this.getDrawColor();
+ if (color.a == null)
+ color.a = 255;
+ for(var i = 0, len = points.length; i < len; i++)
+ this.drawDot(points[i], radius, color);
+ },
+
+ /**
+ * draw a segment with a radius and color
+ * @param {cc.Vec2} from
+ * @param {cc.Vec2} to
+ * @param {Number} lineWidth
+ * @param {cc.Color} color
+ */
+ drawSegment: function (from, to, lineWidth, color) {
+ lineWidth = lineWidth || this._lineWidth;
+ color = color || this.getDrawColor();
+ if (color.a == null)
+ color.a = 255;
+ var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY);
+ element.verts = [from, to];
+ element.lineWidth = lineWidth * 2;
+ element.lineColor = color;
+ element.isStroke = true;
+ element.lineCap = "round";
+ this._buffer.push(element);
+ },
+
+ /**
+ * draw a polygon with a fill color and line color without copying the vertex list
+ * @param {Array} verts
+ * @param {cc.Color} fillColor
+ * @param {Number} lineWidth
+ * @param {cc.Color} color
+ */
+ drawPoly_: function (verts, fillColor, lineWidth, color) {
+ lineWidth = (lineWidth == null ) ? this._lineWidth : lineWidth;
+ color = color || this.getDrawColor();
+ if (color.a == null)
+ color.a = 255;
+ var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY);
+
+ element.verts = verts;
+ element.fillColor = fillColor;
+ element.lineWidth = lineWidth;
+ element.lineColor = color;
+ element.isClosePolygon = true;
+ element.isStroke = true;
+ element.lineCap = "round";
+ if (fillColor)
+ element.isFill = true;
+ this._buffer.push(element);
+ },
+
+ /**
+ * draw a polygon with a fill color and line color, copying the vertex list
+ * @param {Array} verts
+ * @param {cc.Color} fillColor
+ * @param {Number} lineWidth
+ * @param {cc.Color} color
+ */
+ drawPoly: function (verts, fillColor, lineWidth, color) {
+ var vertsCopy = [];
+ for (var i=0; i < verts.length; i++) {
+ vertsCopy.push(cc.p(verts[i].x, verts[i].y));
+ }
+ return this.drawPoly_(vertsCopy, fillColor, lineWidth, color);
+ },
+
+ /**
+ * Clear the geometry in the node's buffer.
+ */
+ clear: function () {
+ this._buffer.length = 0;
+ },
+
+ _createRenderCmd: function(){
+ return new cc.DrawNode.CanvasRenderCmd(this);
+ }
+ });
+ }
+ else if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
+
+ cc.js.mixin(cc.DrawNode.prototype, {
+ _bufferCapacity:0,
+
+ _trianglesArrayBuffer:null,
+ _trianglesWebBuffer:null,
+ _trianglesReader:null,
+
+ _dirty:false,
+ _className:"DrawNodeWebGL",
+
+ ctor:function () {
+ cc.Node.prototype.ctor.call(this);
+ this._buffer = [];
+ this._blendFunc = new cc.BlendFunc(cc.SRC_ALPHA, cc.ONE_MINUS_SRC_ALPHA);
+ this._drawColor = new cc.WebGLColor(255,255,255,255);
+
+ this.init();
+ },
+
+ init:function () {
+ if (cc.Node.prototype.init.call(this)) {
+ this.shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_LENGTHTEXTURECOLOR);
+ this._ensureCapacity(64);
+ this._trianglesWebBuffer = cc._renderContext.createBuffer();
+ this._dirty = true;
+ return true;
+ }
+ return false;
+ },
+
+ drawRect: function (origin, destination, fillColor, lineWidth, lineColor) {
+ lineWidth = (lineWidth == null) ? this._lineWidth : lineWidth;
+ lineColor = lineColor || this.getDrawColor();
+ if (lineColor.a == null)
+ lineColor.a = 255;
+ var vertices = [origin, cc.p(destination.x, origin.y), destination, cc.p(origin.x, destination.y)];
+ if(fillColor == null)
+ this._drawSegments(vertices, lineWidth, lineColor, true);
+ else
+ this.drawPoly(vertices, fillColor, lineWidth, lineColor);
+ },
+
+ drawCircle: function (center, radius, angle, segments, drawLineToCenter, lineWidth, color) {
+ lineWidth = lineWidth || this._lineWidth;
+ color = color || this.getDrawColor();
+ if (color.a == null)
+ color.a = 255;
+ var coef = 2.0 * Math.PI / segments, vertices = [], i, len;
+ for (i = 0; i <= segments; i++) {
+ var rads = i * coef;
+ var j = radius * Math.cos(rads + angle) + center.x;
+ var k = radius * Math.sin(rads + angle) + center.y;
+ vertices.push(cc.p(j, k));
+ }
+ if (drawLineToCenter)
+ vertices.push(cc.p(center.x, center.y));
+
+ lineWidth *= 0.5;
+ for (i = 0, len = vertices.length; i < len - 1; i++)
+ this.drawSegment(vertices[i], vertices[i + 1], lineWidth, color);
+ },
+
+ drawQuadBezier: function (origin, control, destination, segments, lineWidth, color) {
+ lineWidth = lineWidth || this._lineWidth;
+ color = color || this.getDrawColor();
+ if (color.a == null)
+ color.a = 255;
+ var vertices = [], t = 0.0;
+ for (var i = 0; i < segments; i++) {
+ var x = Math.pow(1 - t, 2) * origin.x + 2.0 * (1 - t) * t * control.x + t * t * destination.x;
+ var y = Math.pow(1 - t, 2) * origin.y + 2.0 * (1 - t) * t * control.y + t * t * destination.y;
+ vertices.push(cc.p(x, y));
+ t += 1.0 / segments;
+ }
+ vertices.push(cc.p(destination.x, destination.y));
+ this._drawSegments(vertices, lineWidth, color, false);
+ },
+
+ drawCubicBezier: function (origin, control1, control2, destination, segments, lineWidth, color) {
+ lineWidth = lineWidth || this._lineWidth;
+ color = color || this.getDrawColor();
+ if (color.a == null)
+ color.a = 255;
+ var vertices = [], t = 0;
+ for (var i = 0; i < segments; i++) {
+ var x = Math.pow(1 - t, 3) * origin.x + 3.0 * Math.pow(1 - t, 2) * t * control1.x + 3.0 * (1 - t) * t * t * control2.x + t * t * t * destination.x;
+ var y = Math.pow(1 - t, 3) * origin.y + 3.0 * Math.pow(1 - t, 2) * t * control1.y + 3.0 * (1 - t) * t * t * control2.y + t * t * t * destination.y;
+ vertices.push(cc.p(x, y));
+ t += 1.0 / segments;
+ }
+ vertices.push(cc.p(destination.x, destination.y));
+ this._drawSegments(vertices, lineWidth, color, false);
+ },
+
+ drawCatmullRom: function (points, segments, lineWidth, color) {
+ this.drawCardinalSpline(points, 0.5, segments, lineWidth, color);
+ },
+
+ drawCardinalSpline: function (config, tension, segments, lineWidth, color) {
+ lineWidth = lineWidth || this._lineWidth;
+ color = color || this.getDrawColor();
+ if (color.a == null)
+ color.a = 255;
+ var vertices = [], p, lt, deltaT = 1.0 / config.length;
+
+ for (var i = 0; i < segments + 1; i++) {
+ var dt = i / segments;
+
+ // border
+ if (dt === 1) {
+ p = config.length - 1;
+ lt = 1;
+ } else {
+ p = 0 | (dt / deltaT);
+ lt = (dt - deltaT * p) / deltaT;
+ }
+
+ // Interpolate
+ var newPos = cc.cardinalSplineAt(
+ cc.getControlPointAt(config, p - 1),
+ cc.getControlPointAt(config, p - 0),
+ cc.getControlPointAt(config, p + 1),
+ cc.getControlPointAt(config, p + 2),
+ tension, lt);
+ vertices.push(newPos);
+ }
+
+ lineWidth *= 0.5;
+ for (var j = 0, len = vertices.length; j < len - 1; j++)
+ this.drawSegment(vertices[j], vertices[j + 1], lineWidth, color);
+ },
+
+ _render:function () {
+ var gl = cc._renderContext;
+
+ cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POS_COLOR_TEX);
+ gl.bindBuffer(gl.ARRAY_BUFFER, this._trianglesWebBuffer);
+ if (this._dirty) {
+ gl.bufferData(gl.ARRAY_BUFFER, this._trianglesArrayBuffer, gl.STREAM_DRAW);
+ this._dirty = false;
+ }
+ var triangleSize = cc.V2F_C4B_T2F.BYTES_PER_ELEMENT;
+
+ // vertex
+ gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, triangleSize, 0);
+ // color
+ gl.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, triangleSize, 8);
+ // texcood
+ gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, triangleSize, 12);
+
+ gl.drawArrays(gl.TRIANGLES, 0, this._buffer.length * 3);
+ cc.incrementGLDraws(1);
+ //cc.checkGLErrorDebug();
+ },
+
+ _ensureCapacity:function(count){
+ var _t = this;
+ var locBuffer = _t._buffer;
+ if(locBuffer.length + count > _t._bufferCapacity){
+ var TriangleLength = cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT;
+ _t._bufferCapacity += Math.max(_t._bufferCapacity, count);
+ //re alloc
+ if((locBuffer == null) || (locBuffer.length === 0)){
+ //init
+ _t._buffer = [];
+ _t._trianglesArrayBuffer = new ArrayBuffer(TriangleLength * _t._bufferCapacity);
+ _t._trianglesReader = new Uint8Array(_t._trianglesArrayBuffer);
+ } else {
+ var newTriangles = [];
+ var newArrayBuffer = new ArrayBuffer(TriangleLength * _t._bufferCapacity);
+ for(var i = 0; i < locBuffer.length;i++){
+ newTriangles[i] = new cc.V2F_C4B_T2F_Triangle(locBuffer[i].a,locBuffer[i].b,locBuffer[i].c,
+ newArrayBuffer, i * TriangleLength);
+ }
+ _t._trianglesReader = new Uint8Array(newArrayBuffer);
+ _t._trianglesArrayBuffer = newArrayBuffer;
+ _t._buffer = newTriangles;
+ }
+ }
+ },
+
+ drawDot:function (pos, radius, color) {
+ color = color || this.getDrawColor();
+ if (color.a == null)
+ color.a = 255;
+ var c4bColor = {r: 0 | color.r, g: 0 | color.g, b: 0 | color.b, a: 0 | color.a};
+ var a = {vertices: {x: pos.x - radius, y: pos.y - radius}, colors: c4bColor, texCoords: {u: -1.0, v: -1.0}};
+ var b = {vertices: {x: pos.x - radius, y: pos.y + radius}, colors: c4bColor, texCoords: {u: -1.0, v: 1.0}};
+ var c = {vertices: {x: pos.x + radius, y: pos.y + radius}, colors: c4bColor, texCoords: {u: 1.0, v: 1.0}};
+ var d = {vertices: {x: pos.x + radius, y: pos.y - radius}, colors: c4bColor, texCoords: {u: 1.0, v: -1.0}};
+
+ this._ensureCapacity(2*3);
+
+ this._buffer.push(new cc.V2F_C4B_T2F_Triangle(a, b, c, this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT));
+ this._buffer.push(new cc.V2F_C4B_T2F_Triangle(a, c, d, this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT));
+ this._dirty = true;
+ },
+
+ drawDots: function(points, radius,color) {
+ if(!points || points.length === 0)
+ return;
+ color = color || this.getDrawColor();
+ if (color.a == null)
+ color.a = 255;
+ for(var i = 0, len = points.length; i < len; i++)
+ this.drawDot(points[i], radius, color);
+ },
+
+ drawSegment:function (from, to, radius, color) {
+ color = color || this.getDrawColor();
+ if (color.a == null)
+ color.a = 255;
+ radius = radius || (this._lineWidth * 0.5);
+ var vertexCount = 6*3;
+ this._ensureCapacity(vertexCount);
+
+ var c4bColor = {r: 0 | color.r, g: 0 | color.g, b: 0 | color.b, a: 0 | color.a};
+ var a = cc.__v2f(from), b = cc.__v2f(to);
+ var n = cc.v2fnormalize(cc.v2fperp(cc.v2fsub(b, a))), t = cc.v2fperp(n);
+ var nw = cc.v2fmult(n, radius), tw = cc.v2fmult(t, radius);
+
+ var v0 = cc.v2fsub(b, cc.v2fadd(nw, tw));
+ var v1 = cc.v2fadd(b, cc.v2fsub(nw, tw));
+ var v2 = cc.v2fsub(b, nw);
+ var v3 = cc.v2fadd(b, nw);
+ var v4 = cc.v2fsub(a, nw);
+ var v5 = cc.v2fadd(a, nw);
+ var v6 = cc.v2fsub(a, cc.v2fsub(nw, tw));
+ var v7 = cc.v2fadd(a, cc.v2fadd(nw, tw));
+
+ var TriangleLength = cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT, triangleBuffer = this._trianglesArrayBuffer, locBuffer = this._buffer;
+ locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v0, colors: c4bColor, texCoords: cc.__t(cc.v2fneg(cc.v2fadd(n, t)))},
+ {vertices: v1, colors: c4bColor, texCoords: cc.__t(cc.v2fsub(n, t))}, {vertices: v2, colors: c4bColor, texCoords: cc.__t(cc.v2fneg(n))},
+ triangleBuffer, locBuffer.length * TriangleLength));
+
+ locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v3, colors: c4bColor, texCoords: cc.__t(n)},
+ {vertices: v1, colors: c4bColor, texCoords: cc.__t(cc.v2fsub(n, t))}, {vertices: v2, colors: c4bColor, texCoords: cc.__t(cc.v2fneg(n))},
+ triangleBuffer, locBuffer.length * TriangleLength));
+
+ locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v3, colors: c4bColor, texCoords: cc.__t(n)},
+ {vertices: v4, colors: c4bColor, texCoords: cc.__t(cc.v2fneg(n))}, {vertices: v2, colors: c4bColor, texCoords: cc.__t(cc.v2fneg(n))},
+ triangleBuffer, locBuffer.length * TriangleLength));
+
+ locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v3, colors: c4bColor, texCoords: cc.__t(n)},
+ {vertices: v4, colors: c4bColor, texCoords: cc.__t(cc.v2fneg(n))}, {vertices: v5, colors: c4bColor, texCoords: cc.__t(n)},
+ triangleBuffer, locBuffer.length * TriangleLength));
+
+ locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v6, colors: c4bColor, texCoords: cc.__t(cc.v2fsub(t, n))},
+ {vertices: v4, colors: c4bColor, texCoords: cc.__t(cc.v2fneg(n))}, {vertices: v5, colors: c4bColor, texCoords: cc.__t(n)},
+ triangleBuffer, locBuffer.length * TriangleLength));
+
+ locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v6, colors: c4bColor, texCoords: cc.__t(cc.v2fsub(t, n))},
+ {vertices: v7, colors: c4bColor, texCoords: cc.__t(cc.v2fadd(n, t))}, {vertices: v5, colors: c4bColor, texCoords: cc.__t(n)},
+ triangleBuffer, locBuffer.length * TriangleLength));
+ this._dirty = true;
+ },
+
+ drawPoly:function (verts, fillColor, borderWidth, borderColor) {
+ if(fillColor == null){
+ this._drawSegments(verts, borderWidth, borderColor, true);
+ return;
+ }
+ if (fillColor.a == null)
+ fillColor.a = 255;
+ if (borderColor.a == null)
+ borderColor.a = 255;
+ borderWidth = (borderWidth == null)? this._lineWidth : borderWidth;
+ borderWidth *= 0.5;
+ var c4bFillColor = {r: 0 | fillColor.r, g: 0 | fillColor.g, b: 0 | fillColor.b, a: 0 | fillColor.a};
+ var c4bBorderColor = {r: 0 | borderColor.r, g: 0 | borderColor.g, b: 0 | borderColor.b, a: 0 | borderColor.a};
+ var extrude = [], i, v0, v1, v2, count = verts.length;
+ for (i = 0; i < count; i++) {
+ v0 = cc.__v2f(verts[(i - 1 + count) % count]);
+ v1 = cc.__v2f(verts[i]);
+ v2 = cc.__v2f(verts[(i + 1) % count]);
+ var n1 = cc.v2fnormalize(cc.v2fperp(cc.v2fsub(v1, v0)));
+ var n2 = cc.v2fnormalize(cc.v2fperp(cc.v2fsub(v2, v1)));
+ var offset = cc.v2fmult(cc.v2fadd(n1, n2), 1.0 / (cc.v2fdot(n1, n2) + 1.0));
+ extrude[i] = {offset: offset, n: n2};
+ }
+ var outline = (borderWidth > 0.0), triangleCount = 3 * count - 2, vertexCount = 3 * triangleCount;
+ this._ensureCapacity(vertexCount);
+
+ var triangleBytesLen = cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT, trianglesBuffer = this._trianglesArrayBuffer;
+ var locBuffer = this._buffer;
+ var inset = (outline == false ? 0.5 : 0.0);
+ for (i = 0; i < count - 2; i++) {
+ v0 = cc.v2fsub(cc.__v2f(verts[0]), cc.v2fmult(extrude[0].offset, inset));
+ v1 = cc.v2fsub(cc.__v2f(verts[i + 1]), cc.v2fmult(extrude[i + 1].offset, inset));
+ v2 = cc.v2fsub(cc.__v2f(verts[i + 2]), cc.v2fmult(extrude[i + 2].offset, inset));
+ locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v0, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())},
+ {vertices: v1, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())}, {vertices: v2, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())},
+ trianglesBuffer, locBuffer.length * triangleBytesLen));
+ }
+
+ for (i = 0; i < count; i++) {
+ var j = (i + 1) % count;
+ v0 = cc.__v2f(verts[i]);
+ v1 = cc.__v2f(verts[j]);
+
+ var n0 = extrude[i].n;
+ var offset0 = extrude[i].offset;
+ var offset1 = extrude[j].offset;
+ var inner0 = outline ? cc.v2fsub(v0, cc.v2fmult(offset0, borderWidth)) : cc.v2fsub(v0, cc.v2fmult(offset0, 0.5));
+ var inner1 = outline ? cc.v2fsub(v1, cc.v2fmult(offset1, borderWidth)) : cc.v2fsub(v1, cc.v2fmult(offset1, 0.5));
+ var outer0 = outline ? cc.v2fadd(v0, cc.v2fmult(offset0, borderWidth)) : cc.v2fadd(v0, cc.v2fmult(offset0, 0.5));
+ var outer1 = outline ? cc.v2fadd(v1, cc.v2fmult(offset1, borderWidth)) : cc.v2fadd(v1, cc.v2fmult(offset1, 0.5));
+
+ if (outline) {
+ locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bBorderColor, texCoords: cc.__t(cc.v2fneg(n0))},
+ {vertices: inner1, colors: c4bBorderColor, texCoords: cc.__t(cc.v2fneg(n0))}, {vertices: outer1, colors: c4bBorderColor, texCoords: cc.__t(n0)},
+ trianglesBuffer, locBuffer.length * triangleBytesLen));
+ locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bBorderColor, texCoords: cc.__t(cc.v2fneg(n0))},
+ {vertices: outer0, colors: c4bBorderColor, texCoords: cc.__t(n0)}, {vertices: outer1, colors: c4bBorderColor, texCoords: cc.__t(n0)},
+ trianglesBuffer, locBuffer.length * triangleBytesLen));
+ } else {
+ locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())},
+ {vertices: inner1, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())}, {vertices: outer1, colors: c4bFillColor, texCoords: cc.__t(n0)},
+ trianglesBuffer, locBuffer.length * triangleBytesLen));
+ locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())},
+ {vertices: outer0, colors: c4bFillColor, texCoords: cc.__t(n0)}, {vertices: outer1, colors: c4bFillColor, texCoords: cc.__t(n0)},
+ trianglesBuffer, locBuffer.length * triangleBytesLen));
+ }
+ }
+ extrude = null;
+ this._dirty = true;
+ },
+
+ _drawSegments: function(verts, borderWidth, borderColor, closePoly){
+ borderWidth = (borderWidth == null) ? this._lineWidth : borderWidth;
+ borderColor = borderColor || this._drawColor;
+ if(borderColor.a == null)
+ borderColor.a = 255;
+ borderWidth *= 0.5;
+ if (borderWidth <= 0)
+ return;
+
+ var c4bBorderColor = {r: 0 | borderColor.r, g: 0 | borderColor.g, b: 0 | borderColor.b, a: 0 | borderColor.a };
+ var extrude = [], i, v0, v1, v2, count = verts.length;
+ for (i = 0; i < count; i++) {
+ v0 = cc.__v2f(verts[(i - 1 + count) % count]);
+ v1 = cc.__v2f(verts[i]);
+ v2 = cc.__v2f(verts[(i + 1) % count]);
+ var n1 = cc.v2fnormalize(cc.v2fperp(cc.v2fsub(v1, v0)));
+ var n2 = cc.v2fnormalize(cc.v2fperp(cc.v2fsub(v2, v1)));
+ var offset = cc.v2fmult(cc.v2fadd(n1, n2), 1.0 / (cc.v2fdot(n1, n2) + 1.0));
+ extrude[i] = {offset: offset, n: n2};
+ }
+
+ var triangleCount = 3 * count - 2, vertexCount = 3 * triangleCount;
+ this._ensureCapacity(vertexCount);
+
+ var triangleBytesLen = cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT, trianglesBuffer = this._trianglesArrayBuffer;
+ var locBuffer = this._buffer;
+ var len = closePoly ? count : count - 1;
+ for (i = 0; i < len; i++) {
+ var j = (i + 1) % count;
+ v0 = cc.__v2f(verts[i]);
+ v1 = cc.__v2f(verts[j]);
+
+ var n0 = extrude[i].n;
+ var offset0 = extrude[i].offset;
+ var offset1 = extrude[j].offset;
+ var inner0 = cc.v2fsub(v0, cc.v2fmult(offset0, borderWidth));
+ var inner1 = cc.v2fsub(v1, cc.v2fmult(offset1, borderWidth));
+ var outer0 = cc.v2fadd(v0, cc.v2fmult(offset0, borderWidth));
+ var outer1 = cc.v2fadd(v1, cc.v2fmult(offset1, borderWidth));
+ locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bBorderColor, texCoords: cc.__t(cc.v2fneg(n0))},
+ {vertices: inner1, colors: c4bBorderColor, texCoords: cc.__t(cc.v2fneg(n0))}, {vertices: outer1, colors: c4bBorderColor, texCoords: cc.__t(n0)},
+ trianglesBuffer, locBuffer.length * triangleBytesLen));
+ locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bBorderColor, texCoords: cc.__t(cc.v2fneg(n0))},
+ {vertices: outer0, colors: c4bBorderColor, texCoords: cc.__t(n0)}, {vertices: outer1, colors: c4bBorderColor, texCoords: cc.__t(n0)},
+ trianglesBuffer, locBuffer.length * triangleBytesLen));
+ }
+ extrude = null;
+ this._dirty = true;
+ },
+
+ clear:function () {
+ this._buffer.length = 0;
+ this._dirty = true;
+ },
+
+ _createRenderCmd: function () {
+ return new cc.DrawNode.WebGLRenderCmd(this);
+ }
+ });
+ }
+});
diff --git a/cocos2d/shape-nodes/CCDrawNodeCanvasRenderCmd.js b/cocos2d/shape-nodes/CCDrawNodeCanvasRenderCmd.js
new file mode 100644
index 0000000000..4cf153766e
--- /dev/null
+++ b/cocos2d/shape-nodes/CCDrawNodeCanvasRenderCmd.js
@@ -0,0 +1,131 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+(function(){
+
+ cc.DrawNode.CanvasRenderCmd = function(renderableObject){
+ cc.Node.CanvasRenderCmd.call(this, renderableObject);
+ this._needDraw = true;
+ this._buffer = null;
+ this._drawColor = null;
+ this._blendFunc = null;
+ };
+
+ cc.DrawNode.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
+ cc.DrawNode.CanvasRenderCmd.prototype.constructor = cc.DrawNode.CanvasRenderCmd;
+ cc.js.mixin( cc.DrawNode.CanvasRenderCmd.prototype, {
+ rendering: function (ctx, scaleX, scaleY) {
+ var wrapper = ctx || cc._renderContext, context = wrapper.getContext(), node = this._node;
+ var alpha = node._displayedOpacity / 255;
+ if (alpha === 0)
+ return;
+
+ wrapper.setTransform(this._worldTransform, scaleX, scaleY);
+
+ //context.save();
+ wrapper.setGlobalAlpha(alpha);
+ if ((this._blendFunc && (this._blendFunc.src === cc.SRC_ALPHA) && (this._blendFunc.dst === cc.ONE)))
+ wrapper.setCompositeOperation('lighter'); //todo: need refactor
+ var locBuffer = this._buffer;
+ for (var i = 0, len = locBuffer.length; i < len; i++) {
+ var element = locBuffer[i];
+ switch (element.type) {
+ case cc.DrawNode.TYPE_DOT:
+ this._drawDot(wrapper, element, scaleX, scaleY);
+ break;
+ case cc.DrawNode.TYPE_SEGMENT:
+ this._drawSegment(wrapper, element, scaleX, scaleY);
+ break;
+ case cc.DrawNode.TYPE_POLY:
+ this._drawPoly(wrapper, element, scaleX, scaleY);
+ break;
+ }
+ }
+ //context.restore(); //todo It can be reserve
+ },
+
+ _drawDot: function (wrapper, element, scaleX, scaleY) {
+ var locColor = element.fillColor, locPos = element.verts[0], locRadius = element.lineWidth;
+
+ var ctx = wrapper.getContext();
+ wrapper.setFillStyle("rgba(" + (0 | locColor.r) + "," + (0 | locColor.g) + "," + (0 | locColor.b) + "," + locColor.a / 255 + ")");
+
+ ctx.beginPath();
+ ctx.arc(locPos.x * scaleX, -locPos.y * scaleY, locRadius * scaleX, 0, Math.PI * 2, false);
+ ctx.closePath();
+ ctx.fill();
+ },
+
+ _drawSegment: function (wrapper, element, scaleX, scaleY) {
+ var locColor = element.lineColor;
+ var locFrom = element.verts[0], locTo = element.verts[1];
+ var locLineWidth = element.lineWidth, locLineCap = element.lineCap;
+
+ var ctx = wrapper.getContext();
+ wrapper.setStrokeStyle("rgba(" + (0 | locColor.r) + "," + (0 | locColor.g) + "," + (0 | locColor.b) + "," + locColor.a / 255 + ")");
+
+ ctx.lineWidth = locLineWidth * scaleX;
+ ctx.beginPath();
+ ctx.lineCap = locLineCap;
+ ctx.moveTo(locFrom.x * scaleX, -locFrom.y * scaleY);
+ ctx.lineTo(locTo.x * scaleX, -locTo.y * scaleY);
+ ctx.stroke();
+ },
+
+ _drawPoly: function (wrapper, element, scaleX, scaleY) {
+ var locVertices = element.verts, locLineCap = element.lineCap;
+ if (locVertices == null)
+ return;
+
+ var locFillColor = element.fillColor, locLineWidth = element.lineWidth;
+ var locLineColor = element.lineColor, locIsClosePolygon = element.isClosePolygon;
+ var locIsFill = element.isFill, locIsStroke = element.isStroke;
+
+ var ctx = wrapper.getContext();
+ var firstPoint = locVertices[0];
+ ctx.lineCap = locLineCap;
+ if (locFillColor)
+ wrapper.setFillStyle("rgba(" + (0 | locFillColor.r) + "," + (0 | locFillColor.g) + ","
+ + (0 | locFillColor.b) + "," + locFillColor.a / 255 + ")");
+ if (locLineWidth)
+ ctx.lineWidth = locLineWidth * scaleX;
+ if (locLineColor)
+ wrapper.setStrokeStyle("rgba(" + (0 | locLineColor.r) + "," + (0 | locLineColor.g) + ","
+ + (0 | locLineColor.b) + "," + locLineColor.a / 255 + ")");
+
+ ctx.beginPath();
+ ctx.moveTo(firstPoint.x * scaleX, -firstPoint.y * scaleY);
+ for (var i = 1, len = locVertices.length; i < len; i++)
+ ctx.lineTo(locVertices[i].x * scaleX, -locVertices[i].y * scaleY);
+
+ if (locIsClosePolygon)
+ ctx.closePath();
+ if (locIsFill)
+ ctx.fill();
+ if (locIsStroke)
+ ctx.stroke();
+ }
+ });
+
+})();
\ No newline at end of file
diff --git a/cocos2d/shape-nodes/CCDrawNodeWebGLRenderCmd.js b/cocos2d/shape-nodes/CCDrawNodeWebGLRenderCmd.js
new file mode 100644
index 0000000000..2c393c6cdb
--- /dev/null
+++ b/cocos2d/shape-nodes/CCDrawNodeWebGLRenderCmd.js
@@ -0,0 +1,41 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+(function(){
+ cc.DrawNode.WebGLRenderCmd = function (renderableObject) {
+ cc.Node.WebGLRenderCmd.call(this, renderableObject);
+ this._needDraw = true;
+ };
+
+ cc.DrawNode.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
+ cc.DrawNode.WebGLRenderCmd.prototype.constructor = cc.DrawNode.WebGLRenderCmd;
+
+ cc.DrawNode.WebGLRenderCmd.prototype.rendering = function (ctx) {
+ var node = this._node;
+ cc.glBlendFunc(node._blendFunc.src, node._blendFunc.dst);
+ this._shaderProgram.use();
+ this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix);
+ node._render();
+ };
+})();
\ No newline at end of file
diff --git a/cocos2d/text-input/CCIMEDispatcher.js b/cocos2d/text-input/CCIMEDispatcher.js
new file mode 100644
index 0000000000..f3e098ef0d
--- /dev/null
+++ b/cocos2d/text-input/CCIMEDispatcher.js
@@ -0,0 +1,534 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+/**
+ * IME Keyboard Notification Info structure
+ * @param {cc.Rect} begin the soft keyboard rectangle when animatin begin
+ * @param {cc.Rect} end the soft keyboard rectangle when animatin end
+ * @param {Number} duration the soft keyboard animation duration
+ */
+cc.IMEKeyboardNotificationInfo = function (begin, end, duration) {
+ this.begin = begin || cc.rect(0, 0, 0, 0);
+ this.end = end || cc.rect(0, 0, 0, 0);
+ this.duration = duration || 0;
+};
+
+/**
+ * Input method editor delegate.
+ * @class
+ * @extends cc._Class
+ */
+cc.IMEDelegate = cc._Class.extend(/** @lends cc.IMEDelegate# */{
+ /**
+ * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
+ */
+ ctor:function () {
+ cc.imeDispatcher.addDelegate(this);
+ },
+ /**
+ * Remove delegate
+ */
+ removeDelegate:function () {
+ cc.imeDispatcher.removeDelegate(this);
+ },
+ /**
+ * Remove delegate
+ * @return {Boolean}
+ */
+ attachWithIME:function () {
+ return cc.imeDispatcher.attachDelegateWithIME(this);
+ },
+ /**
+ * Detach with IME
+ * @return {Boolean}
+ */
+ detachWithIME:function () {
+ return cc.imeDispatcher.detachDelegateWithIME(this);
+ },
+
+ /**
+ * Decide the delegate instance is ready for receive ime message or not.
+ * Called by CCIMEDispatcher.
+ * @return {Boolean}
+ */
+ canAttachWithIME:function () {
+ return false;
+ },
+
+ /**
+ * When the delegate detach with IME, this method call by CCIMEDispatcher.
+ */
+ didAttachWithIME:function () {
+ },
+
+ /**
+ * Decide the delegate instance can stop receive ime message or not.
+ * @return {Boolean}
+ */
+ canDetachWithIME:function () {
+ return false;
+ },
+
+ /**
+ * When the delegate detach with IME, this method call by CCIMEDispatcher.
+ */
+ didDetachWithIME:function () {
+ },
+
+ /**
+ * Called by CCIMEDispatcher when some text input from IME.
+ */
+ insertText:function (text, len) {
+ },
+
+ /**
+ * Called by CCIMEDispatcher when user clicked the backward key.
+ */
+ deleteBackward:function () {
+ },
+
+ /**
+ * Called by CCIMEDispatcher for get text which delegate already has.
+ * @return {String}
+ */
+ getContentText:function () {
+ return "";
+ },
+
+ //////////////////////////////////////////////////////////////////////////
+ // keyboard show/hide notification
+ //////////////////////////////////////////////////////////////////////////
+ keyboardWillShow:function (info) {
+ },
+ keyboardDidShow:function (info) {
+ },
+ keyboardWillHide:function (info) {
+ },
+ keyboardDidHide:function (info) {
+ }
+});
+
+/**
+ * cc.imeDispatcher is a singleton object which manage input message dispatching.
+ * @class
+ * @name cc.imeDispatcher
+ */
+cc.IMEDispatcher = cc._Class.extend(/** @lends cc.imeDispatcher# */{
+ _domInputControl:null,
+ impl:null,
+ _currentInputString:"",
+ _lastClickPosition:null,
+ /**
+ * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
+ */
+ ctor:function () {
+ this.impl = new cc.IMEDispatcher.Impl();
+ this._lastClickPosition = cc.p(0, 0);
+ },
+
+ init:function () {
+ if (cc.sys.isMobile)
+ return;
+ this._domInputControl = cc.$("#imeDispatcherInput");
+ if (!this._domInputControl) {
+ this._domInputControl = cc.$new("input");
+ this._domInputControl.setAttribute("type", "text");
+ this._domInputControl.setAttribute("id", "imeDispatcherInput");
+ this._domInputControl.resize(0.0, 0.0);
+ this._domInputControl.translates(0, 0);
+ this._domInputControl.style.opacity = "0";
+ //this._domInputControl.style.filter = "alpha(opacity = 0)";
+ this._domInputControl.style.fontSize = "1px";
+ this._domInputControl.setAttribute('tabindex', 2);
+ this._domInputControl.style.position = "absolute";
+ this._domInputControl.style.top = 0;
+ this._domInputControl.style.left = 0;
+ document.body.appendChild(this._domInputControl);
+ }
+ var selfPointer = this;
+ //add event listener
+ this._domInputControl.addEventListener("input", function () {
+ selfPointer._processDomInputString(selfPointer._domInputControl.value);
+ }, false);
+ this._domInputControl.addEventListener("keydown", function (e) {
+ // ignore tab key
+ if (e.keyCode === cc.KEY.tab) {
+ e.stopPropagation();
+ e.preventDefault();
+ } else if (e.keyCode === cc.KEY.enter) {
+ selfPointer.dispatchInsertText("\n", 1);
+ e.stopPropagation();
+ e.preventDefault();
+ }
+ }, false);
+
+ if (/msie/i.test(navigator.userAgent)) {
+ this._domInputControl.addEventListener("keyup", function (e) {
+ if (e.keyCode === cc.KEY.backspace) {
+ selfPointer._processDomInputString(selfPointer._domInputControl.value);
+ }
+ }, false);
+ }
+
+ window.addEventListener('mousedown', function (event) {
+ var tx = event.pageX || 0;
+ var ty = event.pageY || 0;
+
+ selfPointer._lastClickPosition.x = tx;
+ selfPointer._lastClickPosition.y = ty;
+ }, false);
+ },
+
+ _processDomInputString:function (text) {
+ var i, startPos;
+ var len = this._currentInputString.length < text.length ? this._currentInputString.length : text.length;
+ for (startPos = 0; startPos < len; startPos++) {
+ if (text[startPos] !== this._currentInputString[startPos])
+ break;
+ }
+ var delTimes = this._currentInputString.length - startPos;
+ var insTimes = text.length - startPos;
+ for (i = 0; i < delTimes; i++)
+ this.dispatchDeleteBackward();
+
+ for (i = 0; i < insTimes; i++)
+ this.dispatchInsertText(text[startPos + i], 1);
+
+ this._currentInputString = text;
+ },
+
+ /**
+ * Dispatch the input text from ime
+ * @param {String} text
+ * @param {Number} len
+ */
+ dispatchInsertText:function (text, len) {
+ if (!this.impl || !text || len <= 0)
+ return;
+
+ // there is no delegate attach with ime
+ if (!this.impl._delegateWithIme)
+ return;
+
+ this.impl._delegateWithIme.insertText(text, len);
+ },
+
+ /**
+ * Dispatch the delete backward operation
+ */
+ dispatchDeleteBackward:function () {
+ if (!this.impl) {
+ return;
+ }
+
+ // there is no delegate attach with ime
+ if (!this.impl._delegateWithIme)
+ return;
+
+ this.impl._delegateWithIme.deleteBackward();
+ },
+
+ /**
+ * Get the content text, which current CCIMEDelegate which attached with IME has.
+ * @return {String}
+ */
+ getContentText:function () {
+ if (this.impl && this.impl._delegateWithIme) {
+ var pszContentText = this.impl._delegateWithIme.getContentText();
+ return (pszContentText) ? pszContentText : "";
+ }
+ return "";
+ },
+
+ /**
+ * Dispatch keyboard notification
+ * @param {cc.IMEKeyboardNotificationInfo} info
+ */
+ dispatchKeyboardWillShow:function (info) {
+ if (this.impl) {
+ for (var i = 0; i < this.impl._delegateList.length; i++) {
+ var delegate = this.impl._delegateList[i];
+ if (delegate) {
+ delegate.keyboardWillShow(info);
+ }
+ }
+ }
+ },
+
+ /**
+ * Dispatch keyboard notification
+ * @param {cc.IMEKeyboardNotificationInfo} info
+ */
+ dispatchKeyboardDidShow:function (info) {
+ if (this.impl) {
+ for (var i = 0; i < this.impl._delegateList.length; i++) {
+ var delegate = this.impl._delegateList[i];
+ if (delegate)
+ delegate.keyboardDidShow(info);
+ }
+ }
+ },
+
+ /**
+ * Dispatch keyboard notification
+ * @param {cc.IMEKeyboardNotificationInfo} info
+ */
+ dispatchKeyboardWillHide:function (info) {
+ if (this.impl) {
+ for (var i = 0; i < this.impl._delegateList.length; i++) {
+ var delegate = this.impl._delegateList[i];
+ if (delegate) {
+ delegate.keyboardWillHide(info);
+ }
+ }
+ }
+ },
+
+ /**
+ * Dispatch keyboard notification
+ * @param {cc.IMEKeyboardNotificationInfo} info
+ */
+ dispatchKeyboardDidHide:function (info) {
+ if (this.impl) {
+ for (var i = 0; i < this.impl._delegateList.length; i++) {
+ var delegate = this.impl._delegateList[i];
+ if (delegate) {
+ delegate.keyboardDidHide(info);
+ }
+ }
+ }
+ },
+
+ /**
+ * Add delegate to concern ime msg
+ * @param {cc.IMEDelegate} delegate
+ * @example
+ * //example
+ * cc.imeDispatcher.addDelegate(this);
+ */
+ addDelegate:function (delegate) {
+ if (!delegate || !this.impl)
+ return;
+
+ if (this.impl._delegateList.indexOf(delegate) > -1) {
+ // delegate already in list
+ return;
+ }
+ this.impl._delegateList.splice(0, 0, delegate);
+ },
+
+ /**
+ * Attach the pDeleate with ime.
+ * @param {cc.IMEDelegate} delegate
+ * @return {Boolean} If the old delegate can detattach with ime and the new delegate can attach with ime, return true, otherwise return false.
+ * @example
+ * //example
+ * var ret = cc.imeDispatcher.attachDelegateWithIME(this);
+ */
+ attachDelegateWithIME:function (delegate) {
+ if (!this.impl || !delegate)
+ return false;
+
+ // if delegate is not in delegate list, return
+ if (this.impl._delegateList.indexOf(delegate) === -1)
+ return false;
+
+ if (this.impl._delegateWithIme) {
+ // if old delegate canDetachWithIME return false
+ // or delegate canAttachWithIME return false,
+ // do nothing.
+ if (!this.impl._delegateWithIme.canDetachWithIME()
+ || !delegate.canAttachWithIME())
+ return false;
+
+ // detach first
+ var pOldDelegate = this.impl._delegateWithIme;
+ this.impl._delegateWithIme = null;
+ pOldDelegate.didDetachWithIME();
+
+ this._focusDomInput(delegate);
+ return true;
+ }
+
+ // havn't delegate attached with IME yet
+ if (!delegate.canAttachWithIME())
+ return false;
+
+ this._focusDomInput(delegate);
+ return true;
+ },
+
+ _focusDomInput:function (delegate) {
+ if(cc.sys.isMobile){
+ this.impl._delegateWithIme = delegate;
+ delegate.didAttachWithIME();
+ //prompt
+ this._currentInputString = delegate.string || "";
+
+ var tipMessage = delegate.getTipMessage ? delegate.getTipMessage() : "please enter your word:";
+ // wechat cover the prompt funciton .So need use the Window.prototype.prompt
+ var userInput;
+ if(window.Window && Window.prototype.prompt != prompt){
+ userInput = Window.prototype.prompt.call(window, tipMessage, this._currentInputString);
+ }else{
+ userInput = prompt(tipMessage, this._currentInputString);
+ }
+ if(userInput != null)
+ this._processDomInputString(userInput);
+ this.dispatchInsertText("\n", 1);
+ }else{
+ this.impl._delegateWithIme = delegate;
+ this._currentInputString = delegate.string || "";
+ delegate.didAttachWithIME();
+ this._domInputControl.focus();
+ this._domInputControl.value = this._currentInputString;
+ this._domInputControlTranslate();
+ }
+ },
+
+ _domInputControlTranslate:function () {
+ if (/msie/i.test(navigator.userAgent)) {
+ this._domInputControl.style.left = this._lastClickPosition.x + "px";
+ this._domInputControl.style.top = this._lastClickPosition.y + "px";
+ } else {
+ this._domInputControl.translates(this._lastClickPosition.x, this._lastClickPosition.y);
+ }
+ },
+
+ /**
+ * Detach the pDeleate with ime.
+ * @param {cc.IMEDelegate} delegate
+ * @return {Boolean} If the old delegate can detattach with ime and the new delegate can attach with ime, return true, otherwise return false.
+ * @example
+ * //example
+ * var ret = cc.imeDispatcher.detachDelegateWithIME(this);
+ */
+ detachDelegateWithIME:function (delegate) {
+ if (!this.impl || !delegate)
+ return false;
+
+ // if delegate is not the current delegate attached with ime, return
+ if (this.impl._delegateWithIme !== delegate)
+ return false;
+
+ if (!delegate.canDetachWithIME())
+ return false;
+
+ this.impl._delegateWithIme = null;
+ delegate.didDetachWithIME();
+ cc._canvas.focus();
+ return true;
+ },
+
+ /**
+ * Remove the delegate from the delegates who concern ime msg
+ * @param {cc.IMEDelegate} delegate
+ * @example
+ * //example
+ * cc.imeDispatcher.removeDelegate(this);
+ */
+ removeDelegate:function (delegate) {
+ if (!this.impl || !delegate)
+ return;
+
+ // if delegate is not in delegate list, return
+ if (this.impl._delegateList.indexOf(delegate) === -1)
+ return;
+
+ if (this.impl._delegateWithIme) {
+ if (delegate === this.impl._delegateWithIme) {
+ this.impl._delegateWithIme = null;
+ }
+ }
+ cc.js.array.remove(this.impl._delegateList, delegate);
+ },
+
+ /**
+ * Process keydown's keycode
+ * @param {Number} keyCode
+ * @example
+ * //example
+ * document.addEventListener("keydown", function (e) {
+ * cc.imeDispatcher.processKeycode(e.keyCode);
+ * });
+ */
+ processKeycode:function (keyCode) {
+ if (keyCode < 32) {
+ if (keyCode === cc.KEY.backspace) {
+ this.dispatchDeleteBackward();
+ } else if (keyCode === cc.KEY.enter) {
+ this.dispatchInsertText("\n", 1);
+ } else if (keyCode === cc.KEY.tab) {
+ //tab input
+ } else if (keyCode === cc.KEY.escape) {
+ //ESC input
+ }
+ } else if (keyCode < 255) {
+ this.dispatchInsertText(String.fromCharCode(keyCode), 1);
+ } else {
+ //
+ }
+ }
+});
+
+/**
+ * Create the cc.IMEDispatcher.Imp Object.
+ * This is the inner class...
+ * @class
+ * @extends cc._Class
+ * @name cc.IMEDispatcher.Impl
+ */
+cc.IMEDispatcher.Impl = cc._Class.extend(/** @lends cc.IMEDispatcher.Impl# */{
+ _delegateWithIme:null,
+ _delegateList:null,
+ /**
+ * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
+ */
+ ctor:function () {
+ this._delegateList = [];
+ },
+ /**
+ * Find delegate
+ * @param {cc.IMEDelegate} delegate
+ * @return {Number|Null}
+ */
+ findDelegate:function (delegate) {
+ for (var i = 0; i < this._delegateList.length; i++) {
+ if (this._delegateList[i] === delegate)
+ return i;
+ }
+ return null;
+ }
+});
+
+// Initialize imeDispatcher singleton
+cc.imeDispatcher = new cc.IMEDispatcher();
+
+document.body ?
+ cc.imeDispatcher.init() :
+ window.addEventListener('load', function () {
+ cc.imeDispatcher.init();
+ }, false);
diff --git a/cocos2d/text-input/CCTextFieldTTF.js b/cocos2d/text-input/CCTextFieldTTF.js
new file mode 100644
index 0000000000..cca8793964
--- /dev/null
+++ b/cocos2d/text-input/CCTextFieldTTF.js
@@ -0,0 +1,500 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+/**
+ * Text field delegate
+ * @class
+ * @extends cc._Class
+ */
+cc.TextFieldDelegate = cc._Class.extend(/** @lends cc.TextFieldDelegate# */{
+ /**
+ * If the sender doesn't want to attach with IME, return true;
+ * @param {cc.TextFieldTTF} sender
+ * @return {Boolean}
+ */
+ onTextFieldAttachWithIME:function (sender) {
+ return false;
+ },
+
+ /**
+ * If the sender doesn't want to detach with IME, return true;
+ * @param {cc.TextFieldTTF} sender
+ * @return {Boolean}
+ */
+ onTextFieldDetachWithIME:function (sender) {
+ return false;
+ },
+
+ /**
+ * If the sender doesn't want to insert the text, return true;
+ * @param {cc.TextFieldTTF} sender
+ * @param {String} text
+ * @param {Number} len
+ * @return {Boolean}
+ */
+ onTextFieldInsertText:function (sender, text, len) {
+ return false
+ },
+
+ /**
+ * If the sender doesn't want to delete the delText, return true;
+ * @param {cc.TextFieldTTF} sender
+ * @param {String} delText
+ * @param {Number} len
+ * @return {Boolean}
+ */
+ onTextFieldDeleteBackward:function (sender, delText, len) {
+ return false;
+ },
+
+ /**
+ * If doesn't want draw sender as default, return true.
+ * @param {cc.TextFieldTTF} sender
+ * @return {Boolean}
+ */
+ onDraw:function (sender) {
+ return false;
+ }
+});
+
+/**
+ * A simple text input field with TTF font.
+ * @class
+ * @extends cc.LabelTTF
+ *
+ * @property {cc.Node} delegate - Delegate
+ * @property {Number} charCount - <@readonly> Characators count
+ * @property {String} placeHolder - Place holder for the field
+ * @property {cc.Color} colorSpaceHolder
+ *
+ * @param {String} placeholder
+ * @param {cc.Size} dimensions
+ * @param {Number} alignment
+ * @param {String} fontName
+ * @param {Number} fontSize
+ *
+ * @example
+ * //example
+ * // When five parameters
+ * var textField = new cc.TextFieldTTF("", cc.size(100,50), cc.TextAlignment.LEFT,"Arial", 32);
+ * // When three parameters
+ * var textField = new cc.TextFieldTTF("", "Arial", 32);
+ */
+cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{
+ delegate:null,
+ colorSpaceHolder:null,
+
+ _colorText: null,
+ _lens:null,
+ _inputText:"",
+ _placeHolder:"",
+ _charCount:0,
+ _className:"TextFieldTTF",
+
+ /**
+ * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
+ * creates a cc.TextFieldTTF from a fontName, alignment, dimension and font size.
+ * @param {String} placeholder
+ * @param {cc.Size} dimensions
+ * @param {Number} alignment
+ * @param {String} fontName
+ * @param {Number} fontSize
+ */
+ ctor:function (placeholder, dimensions, alignment, fontName, fontSize) {
+ this.colorSpaceHolder = cc.color(127, 127, 127);
+ this._colorText = cc.color(255,255,255, 255);
+ cc.LabelTTF.prototype.ctor.call(this);
+
+ if(fontSize !== undefined){
+ this.initWithPlaceHolder("", dimensions, alignment, fontName, fontSize);
+ if(placeholder)
+ this.setPlaceHolder(placeholder);
+ }else if(fontName === undefined && alignment !== undefined){
+ this.initWithString("", arguments[1], arguments[2]);
+ if(placeholder)
+ this.setPlaceHolder(placeholder);
+ }
+ },
+
+ onEnter: function(){
+ cc.LabelTTF.prototype.onEnter.call(this);
+ cc.imeDispatcher.addDelegate(this);
+ },
+
+ onExit: function(){
+ cc.LabelTTF.prototype.onExit.call(this);
+ cc.imeDispatcher.removeDelegate(this);
+ },
+
+ /**
+ * Gets the delegate.
+ * @return {cc.Node}
+ */
+ getDelegate:function () {
+ return this.delegate;
+ },
+
+ /**
+ * Set the delegate.
+ * @param {cc.Node} value
+ */
+ setDelegate:function (value) {
+ this.delegate = value;
+ },
+
+ /**
+ * Gets the char count.
+ * @return {Number}
+ */
+ getCharCount:function () {
+ return this._charCount;
+ },
+
+ /**
+ * Returns the color of space holder.
+ * @return {cc.Color}
+ */
+ getColorSpaceHolder:function () {
+ return cc.color(this.colorSpaceHolder);
+ },
+
+ /**
+ * Sets the color of space holder.
+ * @param {cc.Color} value
+ */
+ setColorSpaceHolder:function (value) {
+ this.colorSpaceHolder.r = value.r;
+ this.colorSpaceHolder.g = value.g;
+ this.colorSpaceHolder.b = value.b;
+ this.colorSpaceHolder.a = cc.js.isUndefined(value.a) ? 255 : value.a;
+ if(!this._inputText.length)
+ this.setColor(this.colorSpaceHolder);
+ },
+
+ /**
+ * Sets the color of cc.TextFieldTTF's text.
+ * @param {cc.Color} textColor
+ */
+ setTextColor:function(textColor){
+ this._colorText.r = textColor.r;
+ this._colorText.g = textColor.g;
+ this._colorText.b = textColor.b;
+ this._colorText.a = cc.js.isUndefined(textColor.a) ? 255 : textColor.a;
+ if(this._inputText.length)
+ this.setColor(this._colorText);
+ },
+
+ /**
+ * Initializes the cc.TextFieldTTF with a font name, alignment, dimension and font size
+ * @param {String} placeholder
+ * @param {cc.Size} dimensions
+ * @param {Number} alignment
+ * @param {String} fontName
+ * @param {Number} fontSize
+ * @return {Boolean}
+ * @example
+ * //example
+ * var textField = new cc.TextFieldTTF();
+ * // When five parameters
+ * textField.initWithPlaceHolder("", cc.size(100,50), cc.TextAlignment.LEFT,"Arial", 32);
+ * // When three parameters
+ * textField.initWithPlaceHolder("", "Arial", 32);
+ */
+ initWithPlaceHolder:function (placeholder, dimensions, alignment, fontName, fontSize) {
+ switch (arguments.length) {
+ case 5:
+ if (placeholder)
+ this.setPlaceHolder(placeholder);
+ return this.initWithString(this._placeHolder,fontName, fontSize, dimensions, alignment);
+ break;
+ case 3:
+ if (placeholder)
+ this.setPlaceHolder(placeholder);
+ return this.initWithString(this._placeHolder, arguments[1], arguments[2]);
+ break;
+ default:
+ throw new Error("Argument must be non-nil ");
+ break;
+ }
+ },
+
+ /**
+ * Input text property
+ * @param {String} text
+ */
+ setString:function (text) {
+ text = String(text);
+ this._inputText = text || "";
+
+ // if there is no input text, display placeholder instead
+ if (!this._inputText.length){
+ cc.LabelTTF.prototype.setString.call(this, this._placeHolder);
+ this.setColor(this.colorSpaceHolder);
+ } else {
+ cc.LabelTTF.prototype.setString.call(this,this._inputText);
+ this.setColor(this._colorText);
+ }
+ if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ this._renderCmd._updateTexture();
+ this._charCount = this._inputText.length;
+ },
+
+ /**
+ * Gets the string
+ * @return {String}
+ */
+ getString:function () {
+ return this._inputText;
+ },
+
+ /**
+ * Set the place holder.
+ * display this string if string equal "".
+ * @param {String} text
+ */
+ setPlaceHolder:function (text) {
+ this._placeHolder = text || "";
+ if (!this._inputText.length) {
+ cc.LabelTTF.prototype.setString.call(this,this._placeHolder);
+ this.setColor(this.colorSpaceHolder);
+ }
+ },
+
+ /**
+ * Gets the place holder.
+ * default display string.
+ * @return {String}
+ */
+ getPlaceHolder:function () {
+ return this._placeHolder;
+ },
+
+ /**
+ * Render function using the canvas 2d context or WebGL context, internal usage only, please do not call this function.
+ * @param {CanvasRenderingContext2D | WebGLRenderingContext} ctx The render context
+ */
+ draw:function (ctx) {
+ //console.log("size",this._contentSize);
+ var context = ctx || cc._renderContext;
+ if (this.delegate && this.delegate.onDraw(this))
+ return;
+
+ cc.LabelTTF.prototype.draw.call(this, context);
+ },
+
+ /**
+ * Recursive method that visit its children and draw them.
+ * @param {CanvasRenderingContext2D|WebGLRenderingContext} ctx
+ */
+ visit: function(ctx){
+ this._super(ctx);
+ },
+
+ //////////////////////////////////////////////////////////////////////////
+ // CCIMEDelegate interface
+ //////////////////////////////////////////////////////////////////////////
+ /**
+ * Open keyboard and receive input text.
+ * @return {Boolean}
+ */
+ attachWithIME:function () {
+ return cc.imeDispatcher.attachDelegateWithIME(this);
+ },
+
+ /**
+ * End text input and close keyboard.
+ * @return {Boolean}
+ */
+ detachWithIME:function () {
+ return cc.imeDispatcher.detachDelegateWithIME(this);
+ },
+
+ /**
+ * Return whether to allow attach with IME.
+ * @return {Boolean}
+ */
+ canAttachWithIME:function () {
+ return (this.delegate) ? (!this.delegate.onTextFieldAttachWithIME(this)) : true;
+ },
+
+ /**
+ * When the delegate detach with IME, this method call by CCIMEDispatcher.
+ */
+ didAttachWithIME:function () {
+ },
+
+ /**
+ * Return whether to allow detach with IME.
+ * @return {Boolean}
+ */
+ canDetachWithIME:function () {
+ return (this.delegate) ? (!this.delegate.onTextFieldDetachWithIME(this)) : true;
+ },
+
+ /**
+ * When the delegate detach with IME, this method call by CCIMEDispatcher.
+ */
+ didDetachWithIME:function () {
+ },
+
+ /**
+ * Delete backward
+ */
+ deleteBackward:function () {
+ var strLen = this._inputText.length;
+ if (strLen === 0)
+ return;
+
+ // get the delete byte number
+ var deleteLen = 1; // default, erase 1 byte
+
+ if (this.delegate && this.delegate.onTextFieldDeleteBackward(this, this._inputText[strLen - deleteLen], deleteLen)) {
+ // delegate don't want delete backward
+ return;
+ }
+
+ // if delete all text, show space holder string
+ if (strLen <= deleteLen) {
+ this._inputText = "";
+ this._charCount = 0;
+ cc.LabelTTF.prototype.setString.call(this,this._placeHolder);
+ this.setColor(this.colorSpaceHolder);
+ return;
+ }
+
+ // set new input text
+ this.string = this._inputText.substring(0, strLen - deleteLen);
+ },
+
+ /**
+ * Remove delegate
+ */
+ removeDelegate:function () {
+ cc.imeDispatcher.removeDelegate(this);
+ },
+
+ _tipMessage: "please enter your word:",
+ /**
+ * Sets the input tip message to show on mobile browser. (mobile Web only)
+ * @param {string} tipMessage
+ */
+ setTipMessage: function (tipMessage) {
+ if (tipMessage == null)
+ return;
+ this._tipMessage = tipMessage;
+ },
+
+ /**
+ * Gets the input tip message to show on mobile browser. (mobile Web only)
+ * @returns {string}
+ */
+ getTipMessage: function () {
+ return this._tipMessage;
+ },
+
+ /**
+ * Append the text.
+ * Input the character.
+ * @param {String} text
+ * @param {Number} len
+ */
+ insertText:function (text, len) {
+ var sInsert = text;
+
+ // insert \n means input end
+ var pos = sInsert.indexOf('\n');
+ if (pos > -1) {
+ sInsert = sInsert.substring(0, pos);
+ }
+
+ if (sInsert.length > 0) {
+ if (this.delegate && this.delegate.onTextFieldInsertText(this, sInsert, sInsert.length)) {
+ // delegate doesn't want insert text
+ return;
+ }
+
+ var sText = this._inputText + sInsert;
+ this._charCount = sText.length;
+ this.string = sText;
+ }
+
+ if (pos === -1)
+ return;
+
+ // '\n' has inserted, let delegate process first
+ if (this.delegate && this.delegate.onTextFieldInsertText(this, "\n", 1))
+ return;
+
+ // if delegate hasn't process, detach with ime as default
+ this.detachWithIME();
+ },
+
+ /**
+ * Gets the input text.
+ * @return {String}
+ */
+ getContentText:function () {
+ return this._inputText;
+ },
+
+ //////////////////////////////////////////////////////////////////////////
+ // keyboard show/hide notification
+ //////////////////////////////////////////////////////////////////////////
+ keyboardWillShow:function (info) {
+ },
+ keyboardDidShow:function (info) {
+ },
+ keyboardWillHide:function (info) {
+ },
+ keyboardDidHide:function (info) {
+ }
+});
+
+var _p = cc.TextFieldTTF.prototype;
+
+// Extended properties
+/** @expose */
+_p.charCount;
+cc.defineGetterSetter(_p, "charCount", _p.getCharCount);
+/** @expose */
+_p.placeHolder;
+cc.defineGetterSetter(_p, "placeHolder", _p.getPlaceHolder, _p.setPlaceHolder);
+
+/**
+ * Please use new TextFieldTTF instead.
+ * Creates a cc.TextFieldTTF from a fontName, alignment, dimension and font size.
+ * @deprecated since v3.0 Please use new TextFieldTTF instead.
+ * @param {String} placeholder
+ * @param {cc.Size} dimensions
+ * @param {Number} alignment
+ * @param {String} fontName
+ * @param {Number} fontSize
+ * @return {cc.TextFieldTTF|Null}
+ */
+cc.TextFieldTTF.create = function (placeholder, dimensions, alignment, fontName, fontSize) {
+ return new cc.TextFieldTTF(placeholder, dimensions, alignment, fontName, fontSize);
+};
+
diff --git a/cocos2d/tilemap/CCTGAlib.js b/cocos2d/tilemap/CCTGAlib.js
new file mode 100644
index 0000000000..d5ed229a06
--- /dev/null
+++ b/cocos2d/tilemap/CCTGAlib.js
@@ -0,0 +1,437 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+/**
+ * @constant
+ * @type Number
+ */
+cc.TGA_OK = 0;
+
+/**
+ * @constant
+ * @type Number
+ */
+cc.TGA_ERROR_FILE_OPEN = 1;
+
+/**
+ * @constant
+ * @type Number
+ */
+cc.TGA_ERROR_READING_FILE = 2;
+
+/**
+ * @constant
+ * @type Number
+ */
+cc.TGA_ERROR_INDEXED_COLOR = 3;
+
+/**
+ * @constant
+ * @type Number
+ */
+cc.TGA_ERROR_MEMORY = 4;
+
+/**
+ * @constant
+ * @type Number
+ */
+cc.TGA_ERROR_COMPRESSED_FILE = 5;
+
+/**
+ * TGA format
+ * @param {Number} status
+ * @param {Number} type
+ * @param {Number} pixelDepth
+ * @param {Number} width map width
+ * @param {Number} height map height
+ * @param {Array} imageData raw data
+ * @param {Number} flipped
+ * @constructor
+ */
+cc.ImageTGA = function (status, type, pixelDepth, width, height, imageData, flipped) {
+ this.status = status || 0;
+ this.type = type || 0;
+ this.pixelDepth = pixelDepth || 0;
+ this.width = width || 0;
+ this.height = height || 0;
+ this.imageData = imageData || [];
+ this.flipped = flipped || 0;
+};
+
+/**
+ * load the image header field from stream. We only keep those that matter!
+ * @param {Array} buffer
+ * @param {Number} bufSize
+ * @param {cc.ImageTGA} psInfo
+ * @return {Boolean}
+ */
+cc.tgaLoadHeader = function (buffer, bufSize, psInfo) {
+ var step = 2;
+ if (step + 1 > bufSize)
+ return false;
+
+ var binaryReader = new cc.BinaryStreamReader(buffer);
+
+ binaryReader.setOffset(step);
+ psInfo.type = binaryReader.readByte();
+ step += 10; // . step += sizeof(unsigned char) * 2; step += sizeof(signed short) * 4;
+
+ if (step + 4 + 1 > bufSize)
+ return false;
+ binaryReader.setOffset(step);
+ psInfo.width = binaryReader.readUnsignedShort();
+ psInfo.height = binaryReader.readUnsignedInteger();
+ psInfo.pixelDepth = binaryReader.readByte();
+
+ step += 5; // . step += sizeof(unsigned char); step += sizeof(signed short) * 2;
+ if (step + 1 > bufSize)
+ return false;
+
+ var garbage = binaryReader.readByte();
+ psInfo.flipped = 0;
+ if (garbage & 0x20)
+ psInfo.flipped = 1;
+ return true;
+};
+
+/**
+ * loads the image pixels. You shouldn't call this function directly.
+ * @param {Array} buffer
+ * @param {Number} bufSize
+ * @param {cc.ImageTGA} psInfo
+ * @return {Boolean}
+ */
+cc.tgaLoadImageData = function (buffer, bufSize, psInfo) {
+ var mode, total, i, aux;
+ var step = 18; // .size_t step = (sizeof(unsigned char) + sizeof(signed short)) * 6;
+
+ // mode equal the number of components for each pixel
+ mode = 0 | (psInfo.pixelDepth / 2);
+ // total is the number of unsigned chars we'll have to read
+ total = psInfo.height * psInfo.width * mode;
+
+ if (step + total > bufSize)
+ return false;
+
+ psInfo.imageData = cc.__getSubArray(buffer, step, step + total);
+
+ // mode=3 or 4 implies that the image is RGB(A). However TGA
+ // stores it as BGR(A) so we'll have to swap R and B.
+ if (mode >= 3) {
+ for (i = 0; i < total; i += mode) {
+ aux = psInfo.imageData[i];
+ psInfo.imageData[i] = psInfo.imageData[i + 2];
+ psInfo.imageData[i + 2] = aux;
+ }
+ }
+ return true;
+};
+
+/**
+ * converts RGB to grayscale
+ * @param {cc.ImageTGA} psInfo
+ */
+cc.tgaRGBtogreyscale = function (psInfo) {
+ var i, j;
+
+ // if the image is already grayscale do nothing
+ if (psInfo.pixelDepth === 8)
+ return;
+
+ // compute the number of actual components
+ var mode = psInfo.pixelDepth / 8;
+
+ // allocate an array for the new image data
+ var newImageData = new Uint8Array(psInfo.height * psInfo.width);
+ if (newImageData === null)
+ return;
+
+ // convert pixels: grayscale = o.30 * R + 0.59 * G + 0.11 * B
+ for (i = 0, j = 0; j < psInfo.width * psInfo.height; i += mode, j++)
+ newImageData[j] = (0.30 * psInfo.imageData[i] + 0.59 * psInfo.imageData[i + 1] + 0.11 * psInfo.imageData[i + 2]);
+
+ // reassign pixelDepth and type according to the new image type
+ psInfo.pixelDepth = 8;
+ psInfo.type = 3;
+ // reassigning imageData to the new array.
+ psInfo.imageData = newImageData;
+};
+
+/**
+ * releases the memory used for the image
+ * @param {cc.ImageTGA} psInfo
+ */
+cc.tgaDestroy = function (psInfo) {
+ if (!psInfo)
+ return;
+
+ psInfo.imageData = null;
+ psInfo = null;
+};
+
+/**
+ * Load RLE image data
+ * @param buffer
+ * @param bufSize
+ * @param psInfo
+ * @returns {boolean}
+ */
+cc.tgaLoadRLEImageData = function (buffer, bufSize, psInfo) {
+ var mode, total, i, index = 0 , skip = 0, flag = 0;
+ var aux = [], runlength = 0;
+
+ var step = 18; // . size_t step = (sizeof(unsigned char) + sizeof(signed short)) * 6;
+
+ // mode equal the number of components for each pixel
+ mode = psInfo.pixelDepth / 8;
+ // total is the number of unsigned chars we'll have to read
+ total = psInfo.height * psInfo.width;
+
+ for (i = 0; i < total; i++) {
+ // if we have a run length pending, run it
+ if (runlength !== 0) {
+ // we do, update the run length count
+ runlength--;
+ skip = (flag !== 0);
+ } else {
+ // otherwise, read in the run length token
+ if (step + 1 > bufSize)
+ break;
+ runlength = buffer[step];
+ step += 1;
+
+ // see if it's a RLE encoded sequence
+ flag = runlength & 0x80;
+ if (flag)
+ runlength -= 128;
+ skip = 0;
+ }
+
+ // do we need to skip reading this pixel?
+ if (!skip) {
+ // no, read in the pixel data
+ if (step + mode > bufSize)
+ break;
+ aux = cc.__getSubArray(buffer, step, step + mode);
+ step += mode;
+
+ // mode=3 or 4 implies that the image is RGB(A). However TGA
+ // stores it as BGR(A) so we'll have to swap R and B.
+ if (mode >= 3) {
+ var tmp = aux[0];
+ aux[0] = aux[2];
+ aux[2] = tmp;
+ }
+ }
+
+ // add the pixel to our image
+ for (var j = 0; j < mode; j++)
+ psInfo.imageData[index + j] = aux[j];
+
+ index += mode;
+ }
+
+ return true;
+};
+
+/**
+ * ImageTGA Flip
+ * @param {cc.ImageTGA} psInfo
+ */
+cc.tgaFlipImage = function (psInfo) {
+ // mode equal the number of components for each pixel
+ var mode = psInfo.pixelDepth / 8;
+ var rowbytes = psInfo.width * mode;
+
+ for (var y = 0; y < (psInfo.height / 2); y++) {
+ var row = cc.__getSubArray(psInfo.imageData, y * rowbytes, y * rowbytes + rowbytes);
+ cc.__setDataToArray(cc.__getSubArray(psInfo.imageData, (psInfo.height - (y + 1)) * rowbytes, rowbytes), psInfo.imageData, y * rowbytes);
+ cc.__setDataToArray(row, psInfo.imageData, (psInfo.height - (y + 1)) * rowbytes);
+ }
+ psInfo.flipped = 0;
+};
+
+cc.__getSubArray = function (array, start, end) {
+ if (array instanceof Array)
+ return array.slice(start, end);
+ else
+ return array.subarray(start, end);
+};
+
+cc.__setDataToArray = function (sourceData, destArray, startIndex) {
+ for (var i = 0; i < sourceData.length; i++)
+ destArray[startIndex + i] = sourceData[i];
+};
+
+/**
+ * Binary Stream Reader
+ *
+ * @class
+ * @param binaryData
+ */
+cc.BinaryStreamReader = cc._Class.extend({
+ _binaryData:null,
+ _offset:0,
+
+ /**
+ * The cc.BinaryStreamReader's constructor.
+ * This function will automatically be invoked when you create a node using new construction: "var node = new cc.BinaryStreamReader()".
+ * Override it to extend its behavior, remember to call "this._super()" in the extended "ctor" function.
+ * @param binaryData
+ */
+ ctor:function (binaryData) {
+ this._binaryData = binaryData;
+ },
+
+ /**
+ * Set the binaryData.
+ * @param binaryData
+ */
+ setBinaryData:function (binaryData) {
+ this._binaryData = binaryData;
+ this._offset = 0;
+ },
+
+ /**
+ * Gets the binaryData.
+ * @returns {Object}
+ */
+ getBinaryData:function () {
+ return this._binaryData;
+ },
+
+ _checkSize:function (neededBits) {
+ if (!(this._offset + Math.ceil(neededBits / 8) < this._data.length))
+ throw new Error("Index out of bound");
+ },
+
+ _decodeFloat:function (precisionBits, exponentBits) {
+ var length = precisionBits + exponentBits + 1;
+ var size = length >> 3;
+ this._checkSize(length);
+
+ var bias = Math.pow(2, exponentBits - 1) - 1;
+ var signal = this._readBits(precisionBits + exponentBits, 1, size);
+ var exponent = this._readBits(precisionBits, exponentBits, size);
+ var significand = 0;
+ var divisor = 2;
+ var curByte = 0; //length + (-precisionBits >> 3) - 1;
+ do {
+ var byteValue = this._readByte(++curByte, size);
+ var startBit = precisionBits % 8 || 8;
+ var mask = 1 << startBit;
+ while (mask >>= 1) {
+ if (byteValue & mask)
+ significand += 1 / divisor;
+ divisor *= 2;
+ }
+ } while (precisionBits -= startBit);
+
+ this._offset += size;
+
+ return exponent === (bias << 1) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity
+ : (1 + signal * -2) * (exponent || significand ? !exponent ? Math.pow(2, -bias + 1) * significand
+ : Math.pow(2, exponent - bias) * (1 + significand) : 0);
+ },
+
+ _readByte:function (i, size) {
+ return this._data[this._offset + size - i - 1];
+ },
+
+ _decodeInt:function (bits, signed) {
+ var x = this._readBits(0, bits, bits / 8), max = Math.pow(2, bits);
+ var result = signed && x >= max / 2 ? x - max : x;
+
+ this._offset += bits / 8;
+ return result;
+ },
+
+ _shl:function (a, b) {
+ for (++b; --b; a = ((a %= 0x7fffffff + 1) & 0x40000000) === 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1){};
+ return a;
+ },
+
+ _readBits:function (start, length, size) {
+ var offsetLeft = (start + length) % 8;
+ var offsetRight = start % 8;
+ var curByte = size - (start >> 3) - 1;
+ var lastByte = size + (-(start + length) >> 3);
+ var diff = curByte - lastByte;
+
+ var sum = (this._readByte(curByte, size) >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1);
+
+ if (diff && offsetLeft)
+ sum += (this._readByte(lastByte++, size) & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight;
+
+ while (diff)
+ sum += this._shl(this._readByte(lastByte++, size), (diff-- << 3) - offsetRight);
+
+ return sum;
+ },
+
+ readInteger:function () {
+ return this._decodeInt(32, true);
+ },
+
+ readUnsignedInteger:function () {
+ return this._decodeInt(32, false);
+ },
+
+ readSingle:function () {
+ return this._decodeFloat(23, 8);
+ },
+
+ readShort:function () {
+ return this._decodeInt(16, true);
+ },
+
+ readUnsignedShort:function () {
+ return this._decodeInt(16, false);
+ },
+
+ readByte:function () {
+ var readByte = this._data[this._offset];
+ this._offset += 1;
+ return readByte;
+ },
+
+ readData:function (start, end) {
+ if (this._binaryData instanceof Array) {
+ return this._binaryData.slice(start, end);
+ } else {
+ //typed array
+ return this._binaryData.subarray(start, end);
+ }
+ },
+
+ setOffset:function (offset) {
+ this._offset = offset;
+ },
+
+ getOffset:function () {
+ return this._offset;
+ }
+});
diff --git a/cocos2d/tilemap/CCTMXLayer.js b/cocos2d/tilemap/CCTMXLayer.js
new file mode 100644
index 0000000000..e0c88cba97
--- /dev/null
+++ b/cocos2d/tilemap/CCTMXLayer.js
@@ -0,0 +1,914 @@
+/****************************************************************************
+ 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.TMXLayer represents the TMX layer.
+ *
+ * It is a subclass of cc.SpriteBatchNode. By default the tiles are rendered using a cc.TextureAtlas.
+ * If you modify a tile on runtime, then, that tile will become a cc.Sprite, otherwise no cc.Sprite objects are created.
+ * The benefits of using cc.Sprite objects as tiles are:
+ * - tiles (cc.Sprite) can be rotated/scaled/moved with a nice API
+ *
+ * If the layer contains a property named "cc.vertexz" with an integer (in can be positive or negative),
+ * then all the tiles belonging to the layer will use that value as their OpenGL vertex Z for depth.
+ *
+ * On the other hand, if the "cc.vertexz" property has the "automatic" value, then the tiles will use an automatic vertex Z value.
+ * Also before drawing the tiles, GL_ALPHA_TEST will be enabled, and disabled after drawing them. The used alpha func will be:
+ *
+ * glAlphaFunc( GL_GREATER, value )
+ *
+ * "value" by default is 0, but you can change it from Tiled by adding the "cc_alpha_func" property to the layer.
+ * The value 0 should work for most cases, but if you have tiles that are semi-transparent, then you might want to use a different value, like 0.5.
+ * @class
+ * @extends cc.SpriteBatchNode
+ *
+ * @property {Array} tiles - Tiles for layer
+ * @property {cc.TMXTilesetInfo} tileset - Tileset for layer
+ * @property {Number} layerOrientation - Layer orientation
+ * @property {Array} properties - Properties from the layer. They can be added using tilemap editors
+ * @property {String} layerName - Name of the layer
+ * @property {Number} layerWidth - Width of the layer
+ * @property {Number} layerHeight - Height of the layer
+ * @property {Number} tileWidth - Width of a tile
+ * @property {Number} tileHeight - Height of a tile
+ */
+cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{
+ tiles: null,
+ tileset: null,
+ layerOrientation: null,
+ properties: null,
+ layerName: "",
+
+ //size of the layer in tiles
+ _layerSize: null,
+ _mapTileSize: null,
+ //TMX Layer supports opacity
+ _opacity: 255,
+ _minGID: null,
+ _maxGID: null,
+ //Only used when vertexZ is used
+ _vertexZvalue: null,
+ _useAutomaticVertexZ: null,
+ //used for optimization
+ _reusedTile: null,
+ _atlasIndexArray: null,
+ //used for retina display
+ _contentScaleFactor: null,
+
+ _className:"TMXLayer",
+
+ /**
+ * Creates a cc.TMXLayer with an tile set info, a layer info and a map info
+ * Constructor of cc.TMXLayer
+ * @param {cc.TMXTilesetInfo} tilesetInfo
+ * @param {cc.TMXLayerInfo} layerInfo
+ * @param {cc.TMXMapInfo} mapInfo
+ */
+ ctor:function (tilesetInfo, layerInfo, mapInfo) {
+ cc.SpriteBatchNode.prototype.ctor.call(this);
+ this._descendants = [];
+
+ this._layerSize = cc.size(0, 0);
+ this._mapTileSize = cc.size(0, 0);
+
+ if(mapInfo !== undefined)
+ this.initWithTilesetInfo(tilesetInfo, layerInfo, mapInfo);
+ },
+
+ _createRenderCmd: function(){
+ if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ return new cc.TMXLayer.CanvasRenderCmd(this);
+ else
+ return new cc.TMXLayer.WebGLRenderCmd(this);
+ },
+
+ /**
+ * Sets the untransformed size of the TMXLayer.
+ * @override
+ * @param {cc.Size|Number} size The untransformed size of the TMXLayer or The untransformed size's width of the TMXLayer.
+ * @param {Number} [height] The untransformed size's height of the TMXLayer.
+ */
+ setContentSize:function (size, height) {
+ cc.Node.prototype.setContentSize.call(this, size, height);
+ this._renderCmd._updateCacheContext(size, height);
+ },
+
+ /**
+ * Return texture of cc.SpriteBatchNode
+ * @function
+ * @return {cc.Texture2D}
+ */
+ getTexture: function(){
+ return this._renderCmd.getTexture();
+ },
+
+ /**
+ * Gets layer size.
+ * @return {cc.Size}
+ */
+ getLayerSize:function () {
+ return cc.size(this._layerSize.width, this._layerSize.height);
+ },
+
+ /**
+ * Set layer size
+ * @param {cc.Size} Var
+ */
+ setLayerSize:function (Var) {
+ this._layerSize.width = Var.width;
+ this._layerSize.height = Var.height;
+ },
+
+ _getLayerWidth: function () {
+ return this._layerSize.width;
+ },
+ _setLayerWidth: function (width) {
+ this._layerSize.width = width;
+ },
+ _getLayerHeight: function () {
+ return this._layerSize.height;
+ },
+ _setLayerHeight: function (height) {
+ this._layerSize.height = height;
+ },
+
+ /**
+ * Size of the map's tile (could be different from the tile's size)
+ * @return {cc.Size}
+ */
+ getMapTileSize:function () {
+ return cc.size(this._mapTileSize.width,this._mapTileSize.height);
+ },
+
+ /**
+ * Set the map tile size.
+ * @param {cc.Size} Var
+ */
+ setMapTileSize:function (Var) {
+ this._mapTileSize.width = Var.width;
+ this._mapTileSize.height = Var.height;
+ },
+
+ _getTileWidth: function () {
+ return this._mapTileSize.width;
+ },
+ _setTileWidth: function (width) {
+ this._mapTileSize.width = width;
+ },
+ _getTileHeight: function () {
+ return this._mapTileSize.height;
+ },
+ _setTileHeight: function (height) {
+ this._mapTileSize.height = height;
+ },
+
+ /**
+ * Pointer to the map of tiles
+ * @return {Array}
+ */
+ getTiles:function () {
+ return this.tiles;
+ },
+
+ /**
+ * Pointer to the map of tiles
+ * @param {Array} Var
+ */
+ setTiles:function (Var) {
+ this.tiles = Var;
+ },
+
+ /**
+ * Tile set information for the layer
+ * @return {cc.TMXTilesetInfo}
+ */
+ getTileset:function () {
+ return this.tileset;
+ },
+
+ /**
+ * Tile set information for the layer
+ * @param {cc.TMXTilesetInfo} Var
+ */
+ setTileset:function (Var) {
+ this.tileset = Var;
+ },
+
+ /**
+ * Layer orientation, which is the same as the map orientation
+ * @return {Number}
+ */
+ getLayerOrientation:function () {
+ return this.layerOrientation;
+ },
+
+ /**
+ * Layer orientation, which is the same as the map orientation
+ * @param {Number} Var
+ */
+ setLayerOrientation:function (Var) {
+ this.layerOrientation = Var;
+ },
+
+ /**
+ * properties from the layer. They can be added using Tiled
+ * @return {Array}
+ */
+ getProperties:function () {
+ return this.properties;
+ },
+
+ /**
+ * properties from the layer. They can be added using Tiled
+ * @param {Array} Var
+ */
+ setProperties:function (Var) {
+ this.properties = Var;
+ },
+
+ /**
+ * Initializes a cc.TMXLayer with a tileset info, a layer info and a map info
+ * @param {cc.TMXTilesetInfo} tilesetInfo
+ * @param {cc.TMXLayerInfo} layerInfo
+ * @param {cc.TMXMapInfo} mapInfo
+ * @return {Boolean}
+ */
+ initWithTilesetInfo:function (tilesetInfo, layerInfo, mapInfo) {
+ // XXX: is 35% a good estimate ?
+ var size = layerInfo._layerSize;
+ var totalNumberOfTiles = parseInt(size.width * size.height);
+ var capacity = totalNumberOfTiles * 0.35 + 1; // 35 percent is occupied ?
+ var texture;
+ if (tilesetInfo)
+ texture = cc.textureCache.addImage(tilesetInfo.sourceImage);
+
+ if (this.initWithTexture(texture, capacity)) {
+ // layerInfo
+ this.layerName = layerInfo.name;
+ this._layerSize = size;
+ this.tiles = layerInfo._tiles;
+ this._minGID = layerInfo._minGID;
+ this._maxGID = layerInfo._maxGID;
+ this._opacity = layerInfo._opacity;
+ this.properties = layerInfo.properties;
+ this._contentScaleFactor = cc.director.getContentScaleFactor();
+
+ // tilesetInfo
+ this.tileset = tilesetInfo;
+
+ // mapInfo
+ this._mapTileSize = mapInfo.getTileSize();
+ this.layerOrientation = mapInfo.orientation;
+
+ // offset (after layer orientation is set);
+ var offset = this._calculateLayerOffset(layerInfo.offset);
+ this.setPosition(cc.pointPixelsToPoints(offset));
+
+ this._atlasIndexArray = [];
+ this.setContentSize(cc.sizePixelsToPoints(cc.size(this._layerSize.width * this._mapTileSize.width,
+ this._layerSize.height * this._mapTileSize.height)));
+ this._useAutomaticVertexZ = false;
+ this._vertexZvalue = 0;
+ return true;
+ }
+ return false;
+ },
+
+ /**
+ * Dealloc the map that contains the tile position from memory.
+ * Unless you want to know at runtime the tiles positions, you can safely call this method.
+ * If you are going to call layer.getTileGIDAt() then, don't release the map
+ */
+ releaseMap:function () {
+ if (this.tiles)
+ this.tiles = null;
+
+ if (this._atlasIndexArray)
+ this._atlasIndexArray = null;
+ },
+
+ /**
+ * Returns the tile (cc.Sprite) at a given a tile coordinate.
+ * The returned cc.Sprite will be already added to the cc.TMXLayer. Don't add it again.
+ * The cc.Sprite can be treated like any other cc.Sprite: rotated, scaled, translated, opacity, color, etc.
+ * You can remove either by calling:
+ * - layer.removeChild(sprite, cleanup);
+ * - or layer.removeTileAt(ccp(x,y));
+ * @param {cc.Vec2|Number} pos or x
+ * @param {Number} [y]
+ * @return {cc.Sprite}
+ */
+ getTileAt: function (pos, y) {
+ if(!pos)
+ throw new Error("cc.TMXLayer.getTileAt(): pos should be non-null");
+ if(y !== undefined)
+ pos = cc.p(pos, y);
+ if(pos.x >= this._layerSize.width || pos.y >= this._layerSize.height || pos.x < 0 || pos.y < 0)
+ throw new Error("cc.TMXLayer.getTileAt(): invalid position");
+ if(!this.tiles || !this._atlasIndexArray){
+ cc.log("cc.TMXLayer.getTileAt(): TMXLayer: the tiles map has been released");
+ return null;
+ }
+
+ var tile = null, gid = this.getTileGIDAt(pos);
+
+ // if GID == 0, then no tile is present
+ if (gid === 0)
+ return tile;
+
+ var z = 0 | (pos.x + pos.y * this._layerSize.width);
+ tile = this.getChildByTag(z);
+ // tile not created yet. create it
+ if (!tile) {
+ var rect = this.tileset.rectForGID(gid);
+ rect = cc.rectPixelsToPoints(rect);
+
+ tile = new cc.Sprite();
+ tile.initWithTexture(this.texture, rect);
+ tile.batchNode = this;
+ tile.setPosition(this.getPositionAt(pos));
+ tile.vertexZ = this._vertexZForPos(pos);
+ tile.anchorX = 0;
+ tile.anchorY = 0;
+ tile.opacity = this._opacity;
+
+ var indexForZ = this._atlasIndexForExistantZ(z);
+ this.addSpriteWithoutQuad(tile, indexForZ, z);
+ }
+ return tile;
+ },
+
+ /**
+ * Returns the tile gid at a given tile coordinate.
+ * if it returns 0, it means that the tile is empty.
+ * This method requires the the tile map has not been previously released (eg. don't call layer.releaseMap())
+ * @param {cc.Vec2|Number} pos or x
+ * @param {Number} [y]
+ * @return {Number}
+ */
+ getTileGIDAt:function (pos, y) {
+ if(pos == null)
+ throw new Error("cc.TMXLayer.getTileGIDAt(): pos should be non-null");
+ if(y !== undefined)
+ pos = cc.p(pos, y);
+ if(pos.x >= this._layerSize.width || pos.y >= this._layerSize.height || pos.x < 0 || pos.y < 0)
+ throw new Error("cc.TMXLayer.getTileGIDAt(): invalid position");
+ if(!this.tiles || !this._atlasIndexArray){
+ cc.log("cc.TMXLayer.getTileGIDAt(): TMXLayer: the tiles map has been released");
+ return null;
+ }
+
+ var idx = 0 | (pos.x + pos.y * this._layerSize.width);
+ // Bits on the far end of the 32-bit global tile ID are used for tile flags
+ var tile = this.tiles[idx];
+
+ return (tile & cc.TMX_TILE_FLIPPED_MASK) >>> 0;
+ },
+ // XXX: deprecated
+ // tileGIDAt:getTileGIDAt,
+
+ /**
+ * lipped tiles can be changed dynamically
+ * @param {cc.Vec2|Number} pos or x
+ * @param {Number} [y]
+ * @return {Number}
+ */
+ getTileFlagsAt:function (pos, y) {
+ if(!pos)
+ throw new Error("cc.TMXLayer.getTileFlagsAt(): pos should be non-null");
+ if(y !== undefined)
+ pos = cc.p(pos, y);
+ if(pos.x >= this._layerSize.width || pos.y >= this._layerSize.height || pos.x < 0 || pos.y < 0)
+ throw new Error("cc.TMXLayer.getTileFlagsAt(): invalid position");
+ if(!this.tiles || !this._atlasIndexArray){
+ cc.log("cc.TMXLayer.getTileFlagsAt(): TMXLayer: the tiles map has been released");
+ return null;
+ }
+
+ var idx = 0 | (pos.x + pos.y * this._layerSize.width);
+ // Bits on the far end of the 32-bit global tile ID are used for tile flags
+ var tile = this.tiles[idx];
+
+ return (tile & cc.TMX_TILE_FLIPPED_ALL) >>> 0;
+ },
+ // XXX: deprecated
+ // tileFlagAt:getTileFlagsAt,
+
+ /**
+ * Sets the tile gid (gid = tile global id) at a given tile coordinate.
+ * The Tile GID can be obtained by using the method "tileGIDAt" or by using the TMX editor . Tileset Mgr +1.
+ * If a tile is already placed at that position, then it will be removed.
+ * @param {Number} gid
+ * @param {cc.Vec2|Number} posOrX position or x
+ * @param {Number} flagsOrY flags or y
+ * @param {Number} [flags]
+ */
+ setTileGID: function(gid, posOrX, flagsOrY, flags) {
+ if(!posOrX)
+ throw new Error("cc.TMXLayer.setTileGID(): pos should be non-null");
+ var pos;
+ if (flags !== undefined) {
+ pos = cc.p(posOrX, flagsOrY);
+ } else {
+ pos = posOrX;
+ flags = flagsOrY;
+ }
+ if(pos.x >= this._layerSize.width || pos.y >= this._layerSize.height || pos.x < 0 || pos.y < 0)
+ throw new Error("cc.TMXLayer.setTileGID(): invalid position");
+ if(!this.tiles || !this._atlasIndexArray){
+ cc.log("cc.TMXLayer.setTileGID(): TMXLayer: the tiles map has been released");
+ return;
+ }
+ if(gid !== 0 && gid < this.tileset.firstGid){
+ cc.log( "cc.TMXLayer.setTileGID(): invalid gid:" + gid);
+ return;
+ }
+
+ flags = flags || 0;
+ this._setNodeDirtyForCache();
+ var currentFlags = this.getTileFlagsAt(pos);
+ var currentGID = this.getTileGIDAt(pos);
+
+ if (currentGID !== gid || currentFlags !== flags) {
+ var gidAndFlags = (gid | flags) >>> 0;
+ // setting gid=0 is equal to remove the tile
+ if (gid === 0)
+ this.removeTileAt(pos);
+ else if (currentGID === 0) // empty tile. create a new one
+ this._insertTileForGID(gidAndFlags, pos);
+ else { // modifying an existing tile with a non-empty tile
+ var z = pos.x + pos.y * this._layerSize.width;
+ var sprite = this.getChildByTag(z);
+ if (sprite) {
+ var rect = this.tileset.rectForGID(gid);
+ rect = cc.rectPixelsToPoints(rect);
+
+ sprite.setTextureRect(rect, false);
+ if (flags != null)
+ this._setupTileSprite(sprite, pos, gidAndFlags);
+
+ this.tiles[z] = gidAndFlags;
+ } else
+ this._updateTileForGID(gidAndFlags, pos);
+ }
+ }
+ },
+
+ /**
+ * Removes a tile at given tile coordinate
+ * @param {cc.Vec2|Number} pos position or x
+ * @param {Number} [y]
+ */
+ removeTileAt:function (pos, y) {
+ if(!pos)
+ throw new Error("cc.TMXLayer.removeTileAt(): pos should be non-null");
+ if(y !== undefined)
+ pos = cc.p(pos, y);
+ if(pos.x >= this._layerSize.width || pos.y >= this._layerSize.height || pos.x < 0 || pos.y < 0)
+ throw new Error("cc.TMXLayer.removeTileAt(): invalid position");
+ if(!this.tiles || !this._atlasIndexArray){
+ cc.log("cc.TMXLayer.removeTileAt(): TMXLayer: the tiles map has been released");
+ return;
+ }
+
+ var gid = this.getTileGIDAt(pos);
+ if (gid !== 0) {
+ if (cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ this._setNodeDirtyForCache();
+ var z = 0 | (pos.x + pos.y * this._layerSize.width);
+ var atlasIndex = this._atlasIndexForExistantZ(z);
+ // remove tile from GID map
+ this.tiles[z] = 0;
+
+ // remove tile from atlas position array
+ this._atlasIndexArray.splice(atlasIndex, 1);
+
+ // remove it from sprites and/or texture atlas
+ var sprite = this.getChildByTag(z);
+
+ if (sprite)
+ cc.SpriteBatchNode.prototype.removeChild.call(this, sprite, true); //this.removeChild(sprite, true);
+ else {
+ if(cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ this.textureAtlas.removeQuadAtIndex(atlasIndex);
+
+ // update possible children
+ if (this._children) {
+ var locChildren = this._children;
+ for (var i = 0, len = locChildren.length; i < len; i++) {
+ var child = locChildren[i];
+ if (child) {
+ var ai = child.atlasIndex;
+ if (ai >= atlasIndex)
+ child.atlasIndex = ai - 1;
+ }
+ }
+ }
+ }
+ }
+ },
+
+ /**
+ * Returns the position in pixels of a given tile coordinate
+ * @param {cc.Vec2|Number} pos position or x
+ * @param {Number} [y]
+ * @return {cc.Vec2}
+ */
+ getPositionAt:function (pos, y) {
+ if (y !== undefined)
+ pos = cc.p(pos, y);
+ var ret = cc.p(0,0);
+ switch (this.layerOrientation) {
+ case cc.TMX_ORIENTATION_ORTHO:
+ ret = this._positionForOrthoAt(pos);
+ break;
+ case cc.TMX_ORIENTATION_ISO:
+ ret = this._positionForIsoAt(pos);
+ break;
+ case cc.TMX_ORIENTATION_HEX:
+ ret = this._positionForHexAt(pos);
+ break;
+ }
+ return cc.pointPixelsToPoints(ret);
+ },
+ // XXX: Deprecated. For backward compatibility only
+ // positionAt:getPositionAt,
+
+ /**
+ * Return the value for the specific property name
+ * @param {String} propertyName
+ * @return {*}
+ */
+ getProperty:function (propertyName) {
+ return this.properties[propertyName];
+ },
+
+ /**
+ * Creates the tiles
+ */
+ setupTiles:function () {
+ // Optimization: quick hack that sets the image size on the tileset
+ this._renderCmd.initImageSize();
+
+ // Parse cocos2d properties
+ this._parseInternalProperties();
+ if (cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ this._setNodeDirtyForCache();
+
+ var locLayerHeight = this._layerSize.height, locLayerWidth = this._layerSize.width;
+ for (var y = 0; y < locLayerHeight; y++) {
+ for (var x = 0; x < locLayerWidth; x++) {
+ var pos = x + locLayerWidth * y;
+ var gid = this.tiles[pos];
+
+ // XXX: gid == 0 -. empty tile
+ if (gid !== 0) {
+ this._appendTileForGID(gid, cc.p(x, y));
+ // Optimization: update min and max GID rendered by the layer
+ this._minGID = Math.min(gid, this._minGID);
+ this._maxGID = Math.max(gid, this._maxGID);
+ }
+ }
+ }
+
+ if (!((this._maxGID >= this.tileset.firstGid) && (this._minGID >= this.tileset.firstGid))) {
+ cc.log("cocos2d:TMX: Only 1 tileset per layer is supported");
+ }
+ },
+
+ /**
+ * cc.TMXLayer doesn't support adding a cc.Sprite manually.
+ * @warning addChild(child); is not supported on cc.TMXLayer. Instead of setTileGID.
+ * @param {cc.Node} child
+ * @param {number} zOrder
+ * @param {number} tag
+ */
+ addChild:function (child, zOrder, tag) {
+ cc.log("addChild: is not supported on cc.TMXLayer. Instead use setTileGID or tileAt.");
+ },
+
+ /**
+ * Remove child
+ * @param {cc.Sprite} sprite
+ * @param {Boolean} cleanup
+ */
+ removeChild:function (sprite, cleanup) {
+ // allows removing nil objects
+ if (!sprite)
+ return;
+
+ if(this._children.indexOf(sprite) === -1){
+ cc.log("cc.TMXLayer.removeChild(): Tile does not belong to TMXLayer");
+ return;
+ }
+
+ if (cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ this._setNodeDirtyForCache();
+ var atlasIndex = sprite.atlasIndex;
+ var zz = this._atlasIndexArray[atlasIndex];
+ this.tiles[zz] = 0;
+ this._atlasIndexArray.splice(atlasIndex, 1);
+ cc.SpriteBatchNode.prototype.removeChild.call(this, sprite, cleanup);
+ cc.renderer.childrenOrderDirty = true;
+ },
+
+ /**
+ * Gets the layer name
+ * @return {String}
+ */
+ getLayerName:function () {
+ return this.layerName;
+ },
+
+ /**
+ * Set the layer name
+ * @param {String} layerName
+ */
+ setLayerName:function (layerName) {
+ this.layerName = layerName;
+ },
+
+ _positionForIsoAt:function (pos) {
+ return cc.p(this._mapTileSize.width / 2 * ( this._layerSize.width + pos.x - pos.y - 1),
+ this._mapTileSize.height / 2 * (( this._layerSize.height * 2 - pos.x - pos.y) - 2));
+ },
+
+ _positionForOrthoAt:function (pos) {
+ return cc.p(pos.x * this._mapTileSize.width,
+ (this._layerSize.height - pos.y - 1) * this._mapTileSize.height);
+ },
+
+ _positionForHexAt:function (pos) {
+ var diffY = (pos.x % 2 === 1) ? (-this._mapTileSize.height / 2) : 0;
+ return cc.p(pos.x * this._mapTileSize.width * 3 / 4,
+ (this._layerSize.height - pos.y - 1) * this._mapTileSize.height + diffY);
+ },
+
+ _calculateLayerOffset:function (pos) {
+ var ret = cc.p(0,0);
+ switch (this.layerOrientation) {
+ case cc.TMX_ORIENTATION_ORTHO:
+ ret = cc.p(pos.x * this._mapTileSize.width, -pos.y * this._mapTileSize.height);
+ break;
+ case cc.TMX_ORIENTATION_ISO:
+ ret = cc.p((this._mapTileSize.width / 2) * (pos.x - pos.y),
+ (this._mapTileSize.height / 2 ) * (-pos.x - pos.y));
+ break;
+ case cc.TMX_ORIENTATION_HEX:
+ if(pos.x !== 0 || pos.y !== 0)
+ cc.log("offset for hexagonal map not implemented yet");
+ break;
+ }
+ return ret;
+ },
+
+ _appendTileForGID:function (gid, pos) {
+ var rect = this.tileset.rectForGID(gid);
+ rect = cc.rectPixelsToPoints(rect);
+
+ var z = 0 | (pos.x + pos.y * this._layerSize.width);
+ var tile = this._renderCmd._reusedTileWithRect(rect);
+ this._setupTileSprite(tile, pos, gid);
+
+ // optimization:
+ // The difference between appendTileForGID and insertTileforGID is that append is faster, since
+ // it appends the tile at the end of the texture atlas
+ var indexForZ = this._atlasIndexArray.length;
+
+ // don't add it using the "standard" way.
+ this.insertQuadFromSprite(tile, indexForZ);
+
+ // append should be after addQuadFromSprite since it modifies the quantity values
+ this._atlasIndexArray.splice(indexForZ, 0, z);
+ return tile;
+ },
+
+ _insertTileForGID:function (gid, pos) {
+ var rect = this.tileset.rectForGID(gid);
+ rect = cc.rectPixelsToPoints(rect);
+
+ var z = 0 | (pos.x + pos.y * this._layerSize.width);
+ var tile = this._renderCmd._reusedTileWithRect(rect);
+ this._setupTileSprite(tile, pos, gid);
+
+ // get atlas index
+ var indexForZ = this._atlasIndexForNewZ(z);
+
+ // Optimization: add the quad without adding a child
+ this.insertQuadFromSprite(tile, indexForZ);
+
+ // insert it into the local atlasindex array
+ this._atlasIndexArray.splice(indexForZ, 0, z);
+ // update possible children
+ if (this._children) {
+ var locChildren = this._children;
+ for (var i = 0, len = locChildren.length; i < len; i++) {
+ var child = locChildren[i];
+ if (child) {
+ var ai = child.atlasIndex;
+ if (ai >= indexForZ)
+ child.atlasIndex = ai + 1;
+ }
+ }
+ }
+ this.tiles[z] = gid;
+ return tile;
+ },
+
+ _updateTileForGID:function (gid, pos) {
+ var rect = this.tileset.rectForGID(gid);
+ var locScaleFactor = this._contentScaleFactor;
+ rect = cc.rect(rect.x / locScaleFactor, rect.y / locScaleFactor,
+ rect.width / locScaleFactor, rect.height / locScaleFactor);
+ var z = pos.x + pos.y * this._layerSize.width;
+
+ var tile = this._renderCmd._reusedTileWithRect(rect);
+ this._setupTileSprite(tile, pos, gid);
+
+ // get atlas index
+ tile.atlasIndex = this._atlasIndexForExistantZ(z);
+ tile.dirty = true;
+ tile.updateTransform();
+ this.tiles[z] = gid;
+
+ return tile;
+ },
+
+ //The layer recognizes some special properties, like cc_vertez
+ _parseInternalProperties:function () {
+ // if cc_vertex=automatic, then tiles will be rendered using vertexz
+ var vertexz = this.getProperty("cc_vertexz");
+ if (vertexz) {
+ if (vertexz === "automatic") {
+ this._useAutomaticVertexZ = true;
+ var alphaFuncVal = this.getProperty("cc_alpha_func");
+ var alphaFuncValue = 0;
+ if (alphaFuncVal)
+ alphaFuncValue = parseFloat(alphaFuncVal);
+
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { //todo: need move to WebGL render cmd
+ this.shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURECOLORALPHATEST);
+ var alphaValueLocation = cc._renderContext.getUniformLocation(this.shaderProgram.getProgram(), cc.UNIFORM_ALPHA_TEST_VALUE_S);
+ // NOTE: alpha test shader is hard-coded to use the equivalent of a glAlphaFunc(GL_GREATER) comparison
+ this.shaderProgram.use();
+ this.shaderProgram.setUniformLocationWith1f(alphaValueLocation, alphaFuncValue);
+ }
+ } else
+ this._vertexZvalue = parseInt(vertexz, 10);
+ }
+ },
+
+ _setupTileSprite:function (sprite, pos, gid) {
+ var z = pos.x + pos.y * this._layerSize.width;
+ sprite.setPosition(this.getPositionAt(pos));
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ sprite.vertexZ = this._vertexZForPos(pos);
+ else
+ sprite.tag = z;
+
+ sprite.anchorX = 0;
+ sprite.anchorY = 0;
+ sprite.opacity = this._opacity;
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
+ sprite.rotation = 0.0;
+ }
+
+ sprite.setFlippedX(false);
+ sprite.setFlippedY(false);
+
+ // Rotation in tiled is achieved using 3 flipped states, flipping across the horizontal, vertical, and diagonal axes of the tiles.
+ if ((gid & cc.TMX_TILE_DIAGONAL_FLAG) >>> 0) {
+ // put the anchor in the middle for ease of rotation.
+ sprite.anchorX = 0.5;
+ sprite.anchorY = 0.5;
+ sprite.x = this.getPositionAt(pos).x + sprite.width / 2;
+ sprite.y = this.getPositionAt(pos).y + sprite.height / 2;
+
+ var flag = (gid & (cc.TMX_TILE_HORIZONTAL_FLAG | cc.TMX_TILE_VERTICAL_FLAG) >>> 0) >>> 0;
+ // handle the 4 diagonally flipped states.
+ if (flag === cc.TMX_TILE_HORIZONTAL_FLAG)
+ sprite.rotation = 90;
+ else if (flag === cc.TMX_TILE_VERTICAL_FLAG)
+ sprite.rotation = 270;
+ else if (flag === (cc.TMX_TILE_VERTICAL_FLAG | cc.TMX_TILE_HORIZONTAL_FLAG) >>> 0) {
+ sprite.rotation = 90;
+ sprite.setFlippedX(true);
+ } else {
+ sprite.rotation = 270;
+ sprite.setFlippedX(true);
+ }
+ } else {
+ if ((gid & cc.TMX_TILE_HORIZONTAL_FLAG) >>> 0) {
+ sprite.setFlippedX(true);
+ }
+
+ if ((gid & cc.TMX_TILE_VERTICAL_FLAG) >>> 0) {
+ sprite.setFlippedY(true);
+ }
+ }
+ },
+
+ _vertexZForPos:function (pos) {
+ var ret = 0;
+ var maxVal = 0;
+ if (this._useAutomaticVertexZ) {
+ switch (this.layerOrientation) {
+ case cc.TMX_ORIENTATION_ISO:
+ maxVal = this._layerSize.width + this._layerSize.height;
+ ret = -(maxVal - (pos.x + pos.y));
+ break;
+ case cc.TMX_ORIENTATION_ORTHO:
+ ret = -(this._layerSize.height - pos.y);
+ break;
+ case cc.TMX_ORIENTATION_HEX:
+ cc.log("TMX Hexa zOrder not supported");
+ break;
+ default:
+ cc.log("TMX invalid value");
+ break;
+ }
+ } else
+ ret = this._vertexZvalue;
+ return ret;
+ },
+
+ _atlasIndexForExistantZ:function (z) {
+ var item;
+ if (this._atlasIndexArray) {
+ var locAtlasIndexArray = this._atlasIndexArray;
+ for (var i = 0, len = locAtlasIndexArray.length; i < len; i++) {
+ item = locAtlasIndexArray[i];
+ if (item === z)
+ break;
+ }
+ }
+ if(!cc.js.isNumber(item))
+ cc.log("cc.TMXLayer._atlasIndexForExistantZ(): TMX atlas index not found. Shall not happen");
+ return i;
+ },
+
+ _atlasIndexForNewZ:function (z) {
+ var locAtlasIndexArray = this._atlasIndexArray;
+ for (var i = 0, len = locAtlasIndexArray.length; i < len; i++) {
+ var val = locAtlasIndexArray[i];
+ if (z < val)
+ break;
+ }
+ return i;
+ }
+});
+
+var _p = cc.TMXLayer.prototype;
+
+/** @expose */
+cc.defineGetterSetter(_p, "texture", _p.getTexture, _p.setTexture);
+
+// Extended properties
+/** @expose */
+_p.layerWidth;
+cc.defineGetterSetter(_p, "layerWidth", _p._getLayerWidth, _p._setLayerWidth);
+/** @expose */
+_p.layerHeight;
+cc.defineGetterSetter(_p, "layerHeight", _p._getLayerHeight, _p._setLayerHeight);
+/** @expose */
+_p.tileWidth;
+cc.defineGetterSetter(_p, "tileWidth", _p._getTileWidth, _p._setTileWidth);
+/** @expose */
+_p.tileHeight;
+cc.defineGetterSetter(_p, "tileHeight", _p._getTileHeight, _p._setTileHeight);
+
+
+/**
+ * Creates a cc.TMXLayer with an tile set info, a layer info and a map info
+ * @deprecated since v3.0 please use new cc.TMXLayer(tilesetInfo, layerInfo, mapInfo) instead.
+ * @param {cc.TMXTilesetInfo} tilesetInfo
+ * @param {cc.TMXLayerInfo} layerInfo
+ * @param {cc.TMXMapInfo} mapInfo
+ * @return {cc.TMXLayer|Null}
+ */
+cc.TMXLayer.create = function (tilesetInfo, layerInfo, mapInfo) {
+ return new cc.TMXLayer(tilesetInfo, layerInfo, mapInfo);
+};
diff --git a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js
new file mode 100644
index 0000000000..79a1ff197d
--- /dev/null
+++ b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js
@@ -0,0 +1,220 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+(function(){
+ cc.TMXLayer.CanvasRenderCmd = function(renderable){
+ cc.SpriteBatchNode.CanvasRenderCmd.call(this, renderable);
+ this._needDraw = true;
+ this._realWorldTransform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0};
+
+ var locCanvas = cc._canvas;
+ var tmpCanvas = document.createElement('canvas');
+ tmpCanvas.width = locCanvas.width;
+ tmpCanvas.height = locCanvas.height;
+ this._cacheCanvas = tmpCanvas;
+ this._cacheContext = new cc.CanvasContextWrapper(this._cacheCanvas.getContext('2d'));
+ var tempTexture = new cc.Texture2D();
+ tempTexture.initWithElement(tmpCanvas);
+ tempTexture.handleLoadedTexture();
+ this._cacheTexture = tempTexture;
+ // This class uses cache, so its default cachedParent should be himself
+ this._cacheDirty = false;
+ };
+
+ var proto = cc.TMXLayer.CanvasRenderCmd.prototype = Object.create(cc.SpriteBatchNode.CanvasRenderCmd.prototype);
+ proto.constructor = cc.TMXLayer.CanvasRenderCmd;
+
+ //set the cache dirty flag for canvas
+ proto._setNodeDirtyForCache = function () {
+ this._cacheDirty = true;
+ };
+
+ proto._renderingChildToCache = function () {
+ if (this._cacheDirty) {
+ var wrapper = this._cacheContext,
+ context = wrapper.getContext(), locCanvas = this._cacheCanvas;
+
+ //wrapper.save();
+ context.setTransform(1, 0, 0, 1, 0, 0);
+ context.clearRect(0, 0, locCanvas.width, locCanvas.height);
+ //reset the cache context
+
+ var locChildren = this._node._children;
+ for (var i = 0, len = locChildren.length; i < len; i++) {
+ if (locChildren[i]){
+ var selCmd = locChildren[i]._renderCmd;
+ if(selCmd){
+ selCmd.rendering(wrapper, 1, 1);
+ selCmd._cacheDirty = false;
+ }
+ }
+ }
+
+ //wrapper.restore();
+ this._cacheDirty = false;
+ }
+ };
+
+ proto.rendering = function (ctx, scaleX, scaleY) {
+ var alpha = this._displayedOpacity / 255;
+ if (alpha <= 0)
+ return;
+
+ var node = this._node;
+ this._renderingChildToCache();
+ var wrapper = ctx || cc._renderContext, context = wrapper.getContext();
+ wrapper.setGlobalAlpha(alpha);
+
+ var locCacheCanvas = this._cacheCanvas;
+ //direct draw image by canvas drawImage
+ if (locCacheCanvas && locCacheCanvas.width !== 0 && locCacheCanvas.height !== 0) {
+ wrapper.setTransform(this._realWorldTransform, scaleX, scaleY);
+ var locCanvasHeight = locCacheCanvas.height * scaleY;
+ if (node.layerOrientation === cc.TMX_ORIENTATION_HEX) {
+ var halfTileSize = node._mapTileSize.height * 0.5 * scaleY;
+ context.drawImage(locCacheCanvas, 0, 0, locCacheCanvas.width, locCacheCanvas.height,
+ 0, -locCanvasHeight + halfTileSize, locCacheCanvas.width * scaleX, locCanvasHeight);
+ } else {
+ context.drawImage(locCacheCanvas, 0, 0, locCacheCanvas.width, locCacheCanvas.height,
+ 0, -locCanvasHeight, locCacheCanvas.width * scaleX, locCanvasHeight);
+ }
+ }
+ cc.g_NumberOfDraws++;
+ };
+
+ proto._updateCacheContext = function(size, height){
+ var node = this._node,
+ locContentSize = node._contentSize,
+ locCanvas = this._cacheCanvas,
+ scaleFactor = cc.contentScaleFactor();
+ locCanvas.width = 0 | (locContentSize.width * 1.5 * scaleFactor);
+ locCanvas.height = 0 | (locContentSize.height * 1.5 * scaleFactor);
+
+ //todo: need change the wrapper's height
+ if(node.layerOrientation === cc.TMX_ORIENTATION_HEX)
+ this._cacheContext.setOffset(0, -node._mapTileSize.height * 0.5); //translate for hexagonal
+ else
+ this._cacheContext.setOffset(0, 0);
+ var locTexContentSize = this._cacheTexture._contentSize;
+ locTexContentSize.width = locCanvas.width;
+ locTexContentSize.height = locCanvas.height;
+ };
+
+ proto.getTexture = function(){
+ return this._cacheTexture;
+ };
+
+ proto.visit = function(parentCmd){
+ var node = this._node;
+ //TODO: it will implement dynamic compute child cutting automation.
+ var i, len, locChildren = node._children;
+ // quick return if not visible
+ if (!node._visible || !locChildren || locChildren.length === 0)
+ return;
+
+ parentCmd = parentCmd || this.getParentRenderCmd();
+ if (parentCmd)
+ this._curLevel = parentCmd._curLevel + 1;
+
+ this._syncStatus(parentCmd);
+ if (this._cacheDirty) {
+ var wrapper = this._cacheContext, locCanvas = this._cacheCanvas, context = wrapper.getContext(),
+ instanceID = node.__instanceId, renderer = cc.renderer;
+ //begin cache
+ renderer._turnToCacheMode(instanceID);
+
+ node.sortAllChildren();
+ for (i = 0, len = locChildren.length; i < len; i++) {
+ if (locChildren[i]){
+ var selCmd = locChildren[i]._renderCmd;
+ if(selCmd){
+ selCmd.visit(this);
+ selCmd._cacheDirty = false;
+ }
+ }
+ }
+
+ //wrapper.save();
+ context.setTransform(1, 0, 0, 1, 0, 0);
+ context.clearRect(0, 0, locCanvas.width, locCanvas.height);
+ //set the wrapper's offset
+
+ //draw to cache canvas
+ renderer._renderingToCacheCanvas(wrapper, instanceID);
+ //wrapper.restore(); //todo: it can be reserve.
+ this._cacheDirty = false
+ }
+ cc.renderer.pushRenderCommand(this);
+ this._dirtyFlag = 0;
+ };
+
+ proto.transform = function (parentCmd, recursive) {
+ // transform for canvas
+ var t = this.getNodeToParentTransform(),
+ worldT = this._realWorldTransform; //get the world transform
+
+ if (parentCmd) {
+ var pt = parentCmd._worldTransform;
+ // cc.AffineTransformConcat is incorrect at get world transform
+ worldT.a = t.a * pt.a + t.b * pt.c; //a
+ worldT.b = t.a * pt.b + t.b * pt.d; //b
+ worldT.c = t.c * pt.a + t.d * pt.c; //c
+ worldT.d = t.c * pt.b + t.d * pt.d; //d
+
+ worldT.tx = pt.a * t.tx + pt.c * t.ty + pt.tx;
+ worldT.ty = pt.d * t.ty + pt.ty + pt.b * t.tx;
+ } else {
+ worldT.a = t.a;
+ worldT.b = t.b;
+ worldT.c = t.c;
+ worldT.d = t.d;
+ worldT.tx = t.tx;
+ worldT.ty = t.ty;
+ }
+ if (recursive) {
+ var locChildren = this._node._children;
+ if (!locChildren || locChildren.length === 0)
+ return;
+ var i, len;
+ for (i = 0, len = locChildren.length; i < len; i++) {
+ locChildren[i]._renderCmd.transform(this, recursive);
+ }
+ }
+ };
+
+ proto.initImageSize = function(){
+ var node = this._node;
+ node.tileset.imageSize = this._texture.getContentSizeInPixels();
+ };
+
+ proto._reusedTileWithRect = function(rect){
+ var node = this._node;
+ node._reusedTile = new cc.Sprite();
+ node._reusedTile.initWithTexture(this._texture, rect, false);
+ node._reusedTile.batchNode = node;
+ node._reusedTile.parent = node;
+ node._reusedTile._renderCmd._cachedParent = node._renderCmd;
+ return node._reusedTile;
+ };
+})();
\ No newline at end of file
diff --git a/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js b/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js
new file mode 100644
index 0000000000..8c1906f640
--- /dev/null
+++ b/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js
@@ -0,0 +1,67 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+(function(){
+ cc.TMXLayer.WebGLRenderCmd = function(renderableObject){
+ cc.SpriteBatchNode.WebGLRenderCmd.call(this, renderableObject);
+ this._needDraw = true;
+ };
+
+ var proto = cc.TMXLayer.WebGLRenderCmd.prototype = Object.create(cc.SpriteBatchNode.WebGLRenderCmd.prototype);
+ proto.constructor = cc.TMXLayer.WebGLRenderCmd;
+
+ proto._updateCacheContext = function(){};
+
+ proto.initImageSize = function(){
+ var node = this._node;
+ node.tileset.imageSize = this._textureAtlas.texture.getContentSizeInPixels();
+
+ // By default all the tiles are aliased
+ // pros:
+ // - easier to render
+ // cons:
+ // - difficult to scale / rotate / etc.
+ this._textureAtlas.texture.setAliasTexParameters();
+ };
+
+ proto._reusedTileWithRect = function(rect){
+ var node = this._node;
+ if (!node._reusedTile) {
+ node._reusedTile = new cc.Sprite();
+ node._reusedTile.initWithTexture(node.texture, rect, false);
+ node._reusedTile.batchNode = node;
+ } else {
+ // XXX HACK: Needed because if "batch node" is nil,
+ // then the Sprite'squad will be reset
+ node._reusedTile.batchNode = null;
+
+ // Re-init the sprite
+ node._reusedTile.setTextureRect(rect, false);
+
+ // restore the batch node
+ node._reusedTile.batchNode = node;
+ }
+ return node._reusedTile;
+ };
+})();
diff --git a/cocos2d/tilemap/CCTMXObjectGroup.js b/cocos2d/tilemap/CCTMXObjectGroup.js
new file mode 100644
index 0000000000..6589d7c607
--- /dev/null
+++ b/cocos2d/tilemap/CCTMXObjectGroup.js
@@ -0,0 +1,157 @@
+/****************************************************************************
+ 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.TMXObjectGroup represents the TMX object group.
+ * @class
+ * @extends cc._Class
+ *
+ * @property {Array} properties - Properties from the group. They can be added using tilemap editors
+ * @property {String} groupName - Name of the group
+ */
+cc.TMXObjectGroup = cc._Class.extend(/** @lends cc.TMXObjectGroup# */{
+ properties: null,
+ groupName: "",
+
+ _positionOffset: null,
+ _objects: null,
+
+ /**
+ * The cc.TMXObjectGroup's constructor.
+ * This function will automatically be invoked when you create a node using new construction: "var node = new cc.TMXObjectGroup()".
+ * Override it to extend its behavior, remember to call "this._super()" in the extended "ctor" function.
+ */
+ ctor:function () {
+ this.groupName = "";
+ this._positionOffset = cc.p(0,0);
+ this.properties = [];
+ this._objects = [];
+ },
+
+ /**
+ * Offset position of child objects
+ * @return {cc.Vec2}
+ */
+ getPositionOffset:function () {
+ return cc.p(this._positionOffset);
+ },
+
+ /**
+ * Offset position of child objects
+ * @param {cc.Vec2} offset
+ */
+ setPositionOffset:function (offset) {
+ this._positionOffset.x = offset.x;
+ this._positionOffset.y = offset.y;
+ },
+
+ /**
+ * List of properties stored in a dictionary
+ * @return {Array}
+ */
+ getProperties:function () {
+ return this.properties;
+ },
+
+ /**
+ * List of properties stored in a dictionary
+ * @param {object} Var
+ */
+ setProperties:function (Var) {
+ this.properties.push(Var);
+ },
+
+ /**
+ * Gets the Group name.
+ * @return {String}
+ */
+ getGroupName:function () {
+ return this.groupName.toString();
+ },
+
+ /**
+ * Set the Group name
+ * @param {String} groupName
+ */
+ setGroupName:function (groupName) {
+ this.groupName = groupName;
+ },
+
+ /**
+ * Return the value for the specific property name
+ * @param {String} propertyName
+ * @return {object}
+ */
+ propertyNamed:function (propertyName) {
+ return this.properties[propertyName];
+ },
+
+ /**
+ * Return the dictionary for the specific object name.
+ * It will return the 1st object found on the array for the given name.
+ * @deprecated since v3.4 please use .getObject
+ * @param {String} objectName
+ * @return {object|Null}
+ */
+ objectNamed:function (objectName) {
+ return this.getObject(objectName);
+ },
+
+ /**
+ * Return the dictionary for the specific object name.
+ * It will return the 1st object found on the array for the given name.
+ * @param {String} objectName
+ * @return {object|Null}
+ */
+ getObject: function(objectName){
+ if (this._objects && this._objects.length > 0) {
+ var locObjects = this._objects;
+ for (var i = 0, len = locObjects.length; i < len; i++) {
+ var name = locObjects[i]["name"];
+ if (name && name === objectName)
+ return locObjects[i];
+ }
+ }
+ // object not found
+ return null;
+ },
+
+ /**
+ * Gets the objects.
+ * @return {Array}
+ */
+ getObjects:function () {
+ return this._objects;
+ },
+
+ /**
+ * Set the objects.
+ * @param {object} objects
+ */
+ setObjects:function (objects) {
+ this._objects.push(objects);
+ }
+});
diff --git a/cocos2d/tilemap/CCTMXTiledMap.js b/cocos2d/tilemap/CCTMXTiledMap.js
new file mode 100644
index 0000000000..fe14fa788f
--- /dev/null
+++ b/cocos2d/tilemap/CCTMXTiledMap.js
@@ -0,0 +1,479 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+/**
+ Orthogonal orientation
+ * @constant
+ * @type Number
+ */
+cc.TMX_ORIENTATION_ORTHO = 0;
+
+/**
+ * Hexagonal orientation
+ * @constant
+ * @type Number
+ */
+
+cc.TMX_ORIENTATION_HEX = 1;
+
+/**
+ * Isometric orientation
+ * @constant
+ * @type Number
+ */
+cc.TMX_ORIENTATION_ISO = 2;
+
+/**
+ * cc.TMXTiledMap knows how to parse and render a TMX map.
+ *
+ * It adds support for the TMX tiled map format used by http://www.mapeditor.org
+ * It supports isometric, hexagonal and orthogonal tiles.
+ * It also supports object groups, objects, and properties.
+ *
+ * Features:
+ * - Each tile will be treated as an cc.Sprite
+ * - The sprites are created on demand. They will be created only when you call "layer.getTileAt(position)"
+ * - Each tile can be rotated / moved / scaled / tinted / "opacitied", since each tile is a cc.Sprite
+ * - Tiles can be added/removed in runtime
+ * - The z-order of the tiles can be modified in runtime
+ * - Each tile has an anchorPoint of (0,0)
+ * - The anchorPoint of the TMXTileMap is (0,0)
+ * - The TMX layers will be added as a child
+ * - The TMX layers will be aliased by default
+ * - The tileset image will be loaded using the cc.TextureCache
+ * - Each tile will have a unique tag
+ * - Each tile will have a unique z value. top-left: z=1, bottom-right: z=max z
+ * - Each object group will be treated as an cc.MutableArray
+ * - Object class which will contain all the properties in a dictionary
+ * - Properties can be assigned to the Map, Layer, Object Group, and Object
+ *
+ * Limitations:
+ * - It only supports one tileset per layer.
+ * - Embeded images are not supported
+ * - It only supports the XML format (the JSON format is not supported)
+ *
+ * Technical description:
+ * Each layer is created using an cc.TMXLayer (subclass of cc.SpriteBatchNode). If you have 5 layers, then 5 cc.TMXLayer will be created,
+ * unless the layer visibility is off. In that case, the layer won't be created at all.
+ * You can obtain the layers (cc.TMXLayer objects) at runtime by:
+ * - map.getChildByTag(tag_number); // 0=1st layer, 1=2nd layer, 2=3rd layer, etc...
+ * - map.getLayer(name_of_the_layer);
+ *
+ * Each object group is created using a cc.TMXObjectGroup which is a subclass of cc.MutableArray.
+ * You can obtain the object groups at runtime by:
+ * - map.getObjectGroup(name_of_the_object_group);
+ *
+ * Each object is a cc.TMXObject.
+ *
+ * Each property is stored as a key-value pair in an cc.MutableDictionary.
+ * You can obtain the properties at runtime by:
+ *
+ * map.getProperty(name_of_the_property);
+ * layer.getProperty(name_of_the_property);
+ * objectGroup.getProperty(name_of_the_property);
+ * object.getProperty(name_of_the_property);
+ * @class
+ * @extends cc.Node
+ * @param {String} tmxFile tmxFile fileName or content string
+ * @param {String} resourcePath If tmxFile is a file name ,it is not required.If tmxFile is content string ,it is must required.
+
+ *
+ * @property {Array} properties - Properties from the map. They can be added using tilemap editors
+ * @property {Number} mapOrientation - Map orientation
+ * @property {Array} objectGroups - Object groups of the map
+ * @property {Number} mapWidth - Width of the map
+ * @property {Number} mapHeight - Height of the map
+ * @property {Number} tileWidth - Width of a tile
+ * @property {Number} tileHeight - Height of a tile
+ *
+ * @example
+ * //example
+ * 1.
+ * //create a TMXTiledMap with file name
+ * var tmxTiledMap = new cc.TMXTiledMap("res/orthogonal-test1.tmx");
+ * 2.
+ * //create a TMXTiledMap with content string and resource path
+ * var resources = "res/TileMaps";
+ * var filePath = "res/TileMaps/orthogonal-test1.tmx";
+ * var xmlStr = cc.loader.getRes(filePath);
+ * var tmxTiledMap = new cc.TMXTiledMap(xmlStr, resources);
+ */
+cc.TMXTiledMap = cc.Node.extend(/** @lends cc.TMXTiledMap# */{
+ properties: null,
+ mapOrientation: null,
+ objectGroups: null,
+
+ //the map's size property measured in tiles
+ _mapSize: null,
+ _tileSize: null,
+ //tile properties
+ _tileProperties: null,
+ _className: "TMXTiledMap",
+
+ /**
+ * Creates a TMX Tiled Map with a TMX file or content string.
+ * Constructor of cc.TMXTiledMap
+ * @param {String} tmxFile tmxFile fileName or content string
+ * @param {String} resourcePath If tmxFile is a file name ,it is not required.If tmxFile is content string ,it is must required.
+ */
+ ctor:function(tmxFile,resourcePath){
+ cc.Node.prototype.ctor.call(this);
+ this._mapSize = cc.size(0, 0);
+ this._tileSize = cc.size(0, 0);
+
+ if(resourcePath !== undefined){
+ this.initWithXML(tmxFile,resourcePath);
+ }else if(tmxFile !== undefined){
+ this.initWithTMXFile(tmxFile);
+ }
+ },
+
+ /**
+ * Gets the map size.
+ * @return {cc.Size}
+ */
+ getMapSize:function () {
+ return cc.size(this._mapSize.width, this._mapSize.height);
+ },
+
+ /**
+ * Set the map size.
+ * @param {cc.Size} Var
+ */
+ setMapSize:function (Var) {
+ this._mapSize.width = Var.width;
+ this._mapSize.height = Var.height;
+ },
+
+ _getMapWidth: function () {
+ return this._mapSize.width;
+ },
+ _setMapWidth: function (width) {
+ this._mapSize.width = width;
+ },
+ _getMapHeight: function () {
+ return this._mapSize.height;
+ },
+ _setMapHeight: function (height) {
+ this._mapSize.height = height;
+ },
+
+ /**
+ * Gets the tile size.
+ * @return {cc.Size}
+ */
+ getTileSize:function () {
+ return cc.size(this._tileSize.width, this._tileSize.height);
+ },
+
+ /**
+ * Set the tile size
+ * @param {cc.Size} Var
+ */
+ setTileSize:function (Var) {
+ this._tileSize.width = Var.width;
+ this._tileSize.height = Var.height;
+ },
+
+ _getTileWidth: function () {
+ return this._tileSize.width;
+ },
+ _setTileWidth: function (width) {
+ this._tileSize.width = width;
+ },
+ _getTileHeight: function () {
+ return this._tileSize.height;
+ },
+ _setTileHeight: function (height) {
+ this._tileSize.height = height;
+ },
+
+ /**
+ * map orientation
+ * @return {Number}
+ */
+ getMapOrientation:function () {
+ return this.mapOrientation;
+ },
+
+ /**
+ * map orientation
+ * @param {Number} Var
+ */
+ setMapOrientation:function (Var) {
+ this.mapOrientation = Var;
+ },
+
+ /**
+ * object groups
+ * @return {Array}
+ */
+ getObjectGroups:function () {
+ return this.objectGroups;
+ },
+
+ /**
+ * object groups
+ * @param {Array} Var
+ */
+ setObjectGroups:function (Var) {
+ this.objectGroups = Var;
+ },
+
+ /**
+ * Gets the properties
+ * @return {object}
+ */
+ getProperties:function () {
+ return this.properties;
+ },
+
+ /**
+ * Set the properties
+ * @param {object} Var
+ */
+ setProperties:function (Var) {
+ this.properties = Var;
+ },
+
+ /**
+ * Initializes the instance of cc.TMXTiledMap with tmxFile
+ * @param {String} tmxFile
+ * @return {Boolean} Whether the initialization was successful.
+ * @example
+ * //example
+ * var map = new cc.TMXTiledMap()
+ * map.initWithTMXFile("hello.tmx");
+ */
+ initWithTMXFile:function (tmxFile) {
+ if(!tmxFile || tmxFile.length === 0)
+ throw new Error("cc.TMXTiledMap.initWithTMXFile(): tmxFile should be non-null or non-empty string.");
+ this.width = 0;
+ this.height = 0;
+ var mapInfo = new cc.TMXMapInfo(tmxFile);
+ if (!mapInfo)
+ return false;
+
+ var locTilesets = mapInfo.getTilesets();
+ if(!locTilesets || locTilesets.length === 0)
+ cc.log("cc.TMXTiledMap.initWithTMXFile(): Map not found. Please check the filename.");
+ this._buildWithMapInfo(mapInfo);
+ return true;
+ },
+
+ /**
+ * Initializes the instance of cc.TMXTiledMap with tmxString
+ * @param {String} tmxString
+ * @param {String} resourcePath
+ * @return {Boolean} Whether the initialization was successful.
+ */
+ initWithXML:function(tmxString, resourcePath){
+ this.width = 0;
+ this.height = 0;
+
+ var mapInfo = new cc.TMXMapInfo(tmxString, resourcePath);
+ var locTilesets = mapInfo.getTilesets();
+ if(!locTilesets || locTilesets.length === 0)
+ cc.log("cc.TMXTiledMap.initWithXML(): Map not found. Please check the filename.");
+ this._buildWithMapInfo(mapInfo);
+ return true;
+ },
+
+ _buildWithMapInfo:function (mapInfo) {
+ this._mapSize = mapInfo.getMapSize();
+ this._tileSize = mapInfo.getTileSize();
+ this.mapOrientation = mapInfo.orientation;
+ this.objectGroups = mapInfo.getObjectGroups();
+ this.properties = mapInfo.properties;
+ this._tileProperties = mapInfo.getTileProperties();
+
+ var idx = 0;
+ var layers = mapInfo.getLayers();
+ if (layers) {
+ var layerInfo = null;
+ for (var i = 0, len = layers.length; i < len; i++) {
+ layerInfo = layers[i];
+ if (layerInfo && layerInfo.visible) {
+ var child = this._parseLayer(layerInfo, mapInfo);
+ this.addChild(child, idx, idx);
+ // update content size with the max size
+ this.width = Math.max(this.width, child.width);
+ this.height = Math.max(this.height, child.height);
+ idx++;
+ }
+ }
+ }
+ },
+
+ /**
+ * Return All layers array.
+ * @returns {Array}
+ */
+ allLayers: function () {
+ var retArr = [], locChildren = this._children;
+ for(var i = 0, len = locChildren.length;i< len;i++){
+ var layer = locChildren[i];
+ if(layer && layer instanceof cc.TMXLayer)
+ retArr.push(layer);
+ }
+ return retArr;
+ },
+
+ /**
+ * return the TMXLayer for the specific layer
+ * @param {String} layerName
+ * @return {cc.TMXLayer}
+ */
+ getLayer:function (layerName) {
+ if(!layerName || layerName.length === 0)
+ throw new Error("cc.TMXTiledMap.getLayer(): layerName should be non-null or non-empty string.");
+ var locChildren = this._children;
+ for (var i = 0; i < locChildren.length; i++) {
+ var layer = locChildren[i];
+ if (layer && layer.layerName === layerName)
+ return layer;
+ }
+ // layer not found
+ return null;
+ },
+
+ /**
+ * Return the TMXObjectGroup for the specific group
+ * @param {String} groupName
+ * @return {cc.TMXObjectGroup}
+ */
+ getObjectGroup:function (groupName) {
+ if(!groupName || groupName.length === 0)
+ throw new Error("cc.TMXTiledMap.getObjectGroup(): groupName should be non-null or non-empty string.");
+ if (this.objectGroups) {
+ for (var i = 0; i < this.objectGroups.length; i++) {
+ var objectGroup = this.objectGroups[i];
+ if (objectGroup && objectGroup.groupName === groupName) {
+ return objectGroup;
+ }
+ }
+ }
+ // objectGroup not found
+ return null;
+ },
+
+ /**
+ * Return the value for the specific property name
+ * @param {String} propertyName
+ * @return {String}
+ */
+ getProperty:function (propertyName) {
+ return this.properties[propertyName.toString()];
+ },
+
+ /**
+ * Return properties dictionary for tile GID
+ * @param {Number} GID
+ * @return {object}
+ * @deprecated
+ */
+ propertiesForGID:function (GID) {
+ cc.log("propertiesForGID is deprecated. Please use getPropertiesForGID instead.");
+ return this.getPropertiesForGID[GID];
+ },
+
+ /**
+ * Return properties dictionary for tile GID
+ * @param {Number} GID
+ * @return {object}
+ */
+ getPropertiesForGID: function(GID) {
+ return this._tileProperties[GID];
+ },
+
+ _parseLayer:function (layerInfo, mapInfo) {
+ var tileset = this._tilesetForLayer(layerInfo, mapInfo);
+ var layer = new cc.TMXLayer(tileset, layerInfo, mapInfo);
+ // tell the layerinfo to release the ownership of the tiles map.
+ layerInfo.ownTiles = false;
+ layer.setupTiles();
+ return layer;
+ },
+
+ _tilesetForLayer:function (layerInfo, mapInfo) {
+ var size = layerInfo._layerSize;
+ var tilesets = mapInfo.getTilesets();
+ if (tilesets) {
+ for (var i = tilesets.length - 1; i >= 0; i--) {
+ var tileset = tilesets[i];
+ if (tileset) {
+ for (var y = 0; y < size.height; y++) {
+ for (var x = 0; x < size.width; x++) {
+ var pos = x + size.width * y;
+ var gid = layerInfo._tiles[pos];
+ if (gid !== 0) {
+ // Optimization: quick return
+ // if the layer is invalid (more than 1 tileset per layer) an cc.assert will be thrown later
+ if (((gid & cc.TMX_TILE_FLIPPED_MASK)>>>0) >= tileset.firstGid) {
+ return tileset;
+ }
+ }
+
+ }
+ }
+ }
+ }
+ }
+
+ // If all the tiles are 0, return empty tileset
+ cc.log("cocos2d: Warning: TMX Layer " + layerInfo.name + " has no tiles");
+ return null;
+ }
+});
+
+var _p = cc.TMXTiledMap.prototype;
+
+// Extended properties
+/** @expose */
+_p.mapWidth;
+cc.defineGetterSetter(_p, "mapWidth", _p._getMapWidth, _p._setMapWidth);
+/** @expose */
+_p.mapHeight;
+cc.defineGetterSetter(_p, "mapHeight", _p._getMapHeight, _p._setMapHeight);
+/** @expose */
+_p.tileWidth;
+cc.defineGetterSetter(_p, "tileWidth", _p._getTileWidth, _p._setTileWidth);
+/** @expose */
+_p.tileHeight;
+cc.defineGetterSetter(_p, "tileHeight", _p._getTileHeight, _p._setTileHeight);
+
+
+/**
+ * Creates a TMX Tiled Map with a TMX file or content string.
+ * Implementation cc.TMXTiledMap
+ * @deprecated since v3.0 please use new cc.TMXTiledMap(tmxFile,resourcePath) instead.
+ * @param {String} tmxFile tmxFile fileName or content string
+ * @param {String} resourcePath If tmxFile is a file name ,it is not required.If tmxFile is content string ,it is must required.
+ * @return {cc.TMXTiledMap|undefined}
+ */
+cc.TMXTiledMap.create = function (tmxFile,resourcePath) {
+ return new cc.TMXTiledMap(tmxFile,resourcePath);
+};
diff --git a/cocos2d/tilemap/CCTMXXMLParser.js b/cocos2d/tilemap/CCTMXXMLParser.js
new file mode 100644
index 0000000000..de9a70090b
--- /dev/null
+++ b/cocos2d/tilemap/CCTMXXMLParser.js
@@ -0,0 +1,950 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+/**
+ * @constant
+ * @type Number
+ */
+cc.TMX_PROPERTY_NONE = 0;
+
+/**
+ * @constant
+ * @type Number
+ */
+cc.TMX_PROPERTY_MAP = 1;
+
+/**
+ * @constant
+ * @type Number
+ */
+cc.TMX_PROPERTY_LAYER = 2;
+
+/**
+ * @constant
+ * @type Number
+ */
+cc.TMX_PROPERTY_OBJECTGROUP = 3;
+
+/**
+ * @constant
+ * @type Number
+ */
+cc.TMX_PROPERTY_OBJECT = 4;
+
+/**
+ * @constant
+ * @type Number
+ */
+cc.TMX_PROPERTY_TILE = 5;
+
+/**
+ * @constant
+ * @type Number
+ */
+cc.TMX_TILE_HORIZONTAL_FLAG = 0x80000000;
+
+
+/**
+ * @constant
+ * @type Number
+ */
+cc.TMX_TILE_VERTICAL_FLAG = 0x40000000;
+
+/**
+ * @constant
+ * @type Number
+ */
+cc.TMX_TILE_DIAGONAL_FLAG = 0x20000000;
+
+/**
+ * @constant
+ * @type Number
+ */
+cc.TMX_TILE_FLIPPED_ALL = (cc.TMX_TILE_HORIZONTAL_FLAG | cc.TMX_TILE_VERTICAL_FLAG | cc.TMX_TILE_DIAGONAL_FLAG) >>> 0;
+
+/**
+ * @constant
+ * @type Number
+ */
+cc.TMX_TILE_FLIPPED_MASK = (~(cc.TMX_TILE_FLIPPED_ALL)) >>> 0;
+
+// Bits on the far end of the 32-bit global tile ID (GID's) are used for tile flags
+
+/**
+ * cc.TMXLayerInfo contains the information about the layers like:
+ * - Layer name
+ * - Layer size
+ * - Layer opacity at creation time (it can be modified at runtime)
+ * - Whether the layer is visible (if it's not visible, then the CocosNode won't be created)
+ *
+ * This information is obtained from the TMX file.
+ * @class
+ * @extends cc._Class
+ *
+ * @property {Array} properties - Properties of the layer info.
+ */
+cc.TMXLayerInfo = cc._Class.extend(/** @lends cc.TMXLayerInfo# */{
+ properties:null,
+
+ name:"",
+ _layerSize:null,
+ _tiles:null,
+ visible:null,
+ _opacity:null,
+ ownTiles:true,
+ _minGID:100000,
+ _maxGID:0,
+ offset:null,
+
+ ctor:function () {
+ this.properties = [];
+ this.name = "";
+ this._layerSize = null;
+ this._tiles = [];
+ this.visible = true;
+ this._opacity = 0;
+ this.ownTiles = true;
+ this._minGID = 100000;
+ this._maxGID = 0;
+ this.offset = cc.p(0,0);
+ },
+
+ /**
+ * Gets the Properties.
+ * @return {Array}
+ */
+ getProperties:function () {
+ return this.properties;
+ },
+
+ /**
+ * Set the Properties.
+ * @param {object} value
+ */
+ setProperties:function (value) {
+ this.properties = value;
+ }
+});
+
+/**
+ * cc.TMXTilesetInfo contains the information about the tilesets like:
+ * - Tileset name
+ * - Tileset spacing
+ * - Tileset margin
+ * - size of the tiles
+ * - Image used for the tiles
+ * - Image size
+ *
+ * This information is obtained from the TMX file.
+ * @class
+ * @extends cc._Class
+ *
+ * @property {string} name - Tileset name
+ * @property {number} firstGid - First grid
+ * @property {number} spacing - Spacing
+ * @property {number} margin - Margin
+ * @property {string} sourceImage - Filename containing the tiles (should be sprite sheet / texture atlas)
+ * @property {cc.Size|null} imageSize - Size in pixels of the image
+ */
+cc.TMXTilesetInfo = cc._Class.extend(/** @lends cc.TMXTilesetInfo# */{
+
+ //Tileset name
+ name:"",
+
+ //First grid
+ firstGid:0,
+ _tileSize:null,
+
+ //Spacing
+ spacing:0,
+
+ //Margin
+ margin:0,
+
+ //Filename containing the tiles (should be sprite sheet / texture atlas)
+ sourceImage:"",
+
+ //Size in pixels of the image
+ imageSize:null,
+
+ ctor:function () {
+ this._tileSize = cc.size(0, 0);
+ this.imageSize = cc.size(0, 0);
+ },
+
+ /**
+ * Return rect
+ * @param {Number} gid
+ * @return {cc.Rect}
+ */
+ rectForGID:function (gid) {
+ var rect = cc.rect(0, 0, 0, 0);
+ rect.width = this._tileSize.width;
+ rect.height = this._tileSize.height;
+ gid &= cc.TMX_TILE_FLIPPED_MASK;
+ gid = gid - parseInt(this.firstGid, 10);
+ var max_x = parseInt((this.imageSize.width - this.margin * 2 + this.spacing) / (this._tileSize.width + this.spacing), 10);
+ rect.x = parseInt((gid % max_x) * (this._tileSize.width + this.spacing) + this.margin, 10);
+ rect.y = parseInt(parseInt(gid / max_x, 10) * (this._tileSize.height + this.spacing) + this.margin, 10);
+ return rect;
+ }
+});
+
+/**
+ * cc.TMXMapInfo contains the information about the map like:
+ *- Map orientation (hexagonal, isometric or orthogonal)
+ *- Tile size
+ *- Map size
+ *
+ * And it also contains:
+ * - Layers (an array of TMXLayerInfo objects)
+ * - Tilesets (an array of TMXTilesetInfo objects)
+ * - ObjectGroups (an array of TMXObjectGroupInfo objects)
+ *
+ * This information is obtained from the TMX file.
+ * @class
+ * @extends cc.saxParser
+ *
+ * @property {Array} properties - Properties of the map info.
+ * @property {Number} orientation - Map orientation.
+ * @property {Object} parentElement - Parent element.
+ * @property {Number} parentGID - Parent GID.
+ * @property {Object} layerAttrs - Layer attributes.
+ * @property {Boolean} storingCharacters - Is reading storing characters stream.
+ * @property {String} tmxFileName - TMX file name.
+ * @property {String} currentString - Current string stored from characters stream.
+ * @property {Number} mapWidth - Width of the map
+ * @property {Number} mapHeight - Height of the map
+ * @property {Number} tileWidth - Width of a tile
+ * @property {Number} tileHeight - Height of a tile
+ *
+ * @param {String} tmxFile fileName or content string
+ * @param {String} resourcePath If tmxFile is a file name ,it is not required.If tmxFile is content string ,it is must required.
+ * @example
+ * 1.
+ * //create a TMXMapInfo with file name
+ * var tmxMapInfo = new cc.TMXMapInfo("res/orthogonal-test1.tmx");
+ * 2.
+ * //create a TMXMapInfo with content string and resource path
+ * var resources = "res/TileMaps";
+ * var filePath = "res/TileMaps/orthogonal-test1.tmx";
+ * var xmlStr = cc.loader.getRes(filePath);
+ * var tmxMapInfo = new cc.TMXMapInfo(xmlStr, resources);
+ */
+cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{
+ properties:null,
+ orientation:null,
+ parentElement:null,
+ parentGID:null,
+ layerAttrs:0,
+ storingCharacters:false,
+ tmxFileName:null,
+ currentString:null,
+
+ _objectGroups:null,
+ _mapSize:null,
+ _tileSize:null,
+ _layers:null,
+ _tilesets:null,
+ // tile properties
+ _tileProperties:null,
+ _resources:"",
+ _currentFirstGID:0,
+
+ /**
+ * Creates a TMX Format with a tmx file or content string
+ * Constructor of cc.TMXMapInfo
+ * @param {String} tmxFile fileName or content string
+ * @param {String} resourcePath If tmxFile is a file name ,it is not required.If tmxFile is content string ,it is must required.
+ */
+ ctor:function (tmxFile, resourcePath) {
+ cc.SAXParser.prototype.ctor.apply(this);
+ this._mapSize = cc.size(0, 0);
+ this._tileSize = cc.size(0, 0);
+ this._layers = [];
+ this._tilesets = [];
+ this._objectGroups = [];
+ this.properties = [];
+ this._tileProperties = {};
+
+ this._currentFirstGID = 0;
+
+ if (resourcePath !== undefined) {
+ this.initWithXML(tmxFile,resourcePath);
+ } else if(tmxFile !== undefined){
+ this.initWithTMXFile(tmxFile);
+ }
+ },
+ /**
+ * Gets Map orientation.
+ * @return {Number}
+ */
+ getOrientation:function () {
+ return this.orientation;
+ },
+
+ /**
+ * Set the Map orientation.
+ * @param {Number} value
+ */
+ setOrientation:function (value) {
+ this.orientation = value;
+ },
+
+ /**
+ * Map width & height
+ * @return {cc.Size}
+ */
+ getMapSize:function () {
+ return cc.size(this._mapSize.width,this._mapSize.height);
+ },
+
+ /**
+ * Map width & height
+ * @param {cc.Size} value
+ */
+ setMapSize:function (value) {
+ this._mapSize.width = value.width;
+ this._mapSize.height = value.height;
+ },
+
+ _getMapWidth: function () {
+ return this._mapSize.width;
+ },
+ _setMapWidth: function (width) {
+ this._mapSize.width = width;
+ },
+ _getMapHeight: function () {
+ return this._mapSize.height;
+ },
+ _setMapHeight: function (height) {
+ this._mapSize.height = height;
+ },
+
+ /**
+ * Tiles width & height
+ * @return {cc.Size}
+ */
+ getTileSize:function () {
+ return cc.size(this._tileSize.width, this._tileSize.height);
+ },
+
+ /**
+ * Tiles width & height
+ * @param {cc.Size} value
+ */
+ setTileSize:function (value) {
+ this._tileSize.width = value.width;
+ this._tileSize.height = value.height;
+ },
+
+ _getTileWidth: function () {
+ return this._tileSize.width;
+ },
+ _setTileWidth: function (width) {
+ this._tileSize.width = width;
+ },
+ _getTileHeight: function () {
+ return this._tileSize.height;
+ },
+ _setTileHeight: function (height) {
+ this._tileSize.height = height;
+ },
+
+ /**
+ * Layers
+ * @return {Array}
+ */
+ getLayers:function () {
+ return this._layers;
+ },
+
+ /**
+ * Layers
+ * @param {cc.TMXLayerInfo} value
+ */
+ setLayers:function (value) {
+ this._layers.push(value);
+ },
+
+ /**
+ * tilesets
+ * @return {Array}
+ */
+ getTilesets:function () {
+ return this._tilesets;
+ },
+
+ /**
+ * tilesets
+ * @param {cc.TMXTilesetInfo} value
+ */
+ setTilesets:function (value) {
+ this._tilesets.push(value);
+ },
+
+ /**
+ * ObjectGroups
+ * @return {Array}
+ */
+ getObjectGroups:function () {
+ return this._objectGroups;
+ },
+
+ /**
+ * ObjectGroups
+ * @param {cc.TMXObjectGroup} value
+ */
+ setObjectGroups:function (value) {
+ this._objectGroups.push(value);
+ },
+
+ /**
+ * parent element
+ * @return {Object}
+ */
+ getParentElement:function () {
+ return this.parentElement;
+ },
+
+ /**
+ * parent element
+ * @param {Object} value
+ */
+ setParentElement:function (value) {
+ this.parentElement = value;
+ },
+
+ /**
+ * parent GID
+ * @return {Number}
+ */
+ getParentGID:function () {
+ return this.parentGID;
+ },
+
+ /**
+ * parent GID
+ * @param {Number} value
+ */
+ setParentGID:function (value) {
+ this.parentGID = value;
+ },
+
+ /**
+ * Layer attribute
+ * @return {Object}
+ */
+ getLayerAttribs:function () {
+ return this.layerAttrs;
+ },
+
+ /**
+ * Layer attribute
+ * @param {Object} value
+ */
+ setLayerAttribs:function (value) {
+ this.layerAttrs = value;
+ },
+
+ /**
+ * Is reading storing characters stream
+ * @return {Boolean}
+ */
+ getStoringCharacters:function () {
+ return this.storingCharacters;
+ },
+
+ /**
+ * Is reading storing characters stream
+ * @param {Boolean} value
+ */
+ setStoringCharacters:function (value) {
+ this.storingCharacters = value;
+ },
+
+ /**
+ * Properties
+ * @return {Array}
+ */
+ getProperties:function () {
+ return this.properties;
+ },
+
+ /**
+ * Properties
+ * @param {object} value
+ */
+ setProperties:function (value) {
+ this.properties = value;
+ },
+
+ /**
+ * Initializes a TMX format with a tmx file
+ * @param {String} tmxFile
+ * @return {Element}
+ */
+ initWithTMXFile:function (tmxFile) {
+ this._internalInit(tmxFile, null);
+ return this.parseXMLFile(tmxFile);
+ },
+
+ /**
+ * initializes a TMX format with an XML string and a TMX resource path
+ * @param {String} tmxString
+ * @param {String} resourcePath
+ * @return {Boolean}
+ */
+ initWithXML:function (tmxString, resourcePath) {
+ this._internalInit(null, resourcePath);
+ return this.parseXMLString(tmxString);
+ },
+
+ /** Initalises parsing of an XML file, either a tmx (Map) file or tsx (Tileset) file
+ * @param {String} tmxFile
+ * @param {boolean} [isXmlString=false]
+ * @return {Element}
+ */
+ parseXMLFile:function (tmxFile, isXmlString) {
+ isXmlString = isXmlString || false;
+ var xmlStr = isXmlString ? tmxFile : cc.loader.getRes(tmxFile);
+ if(!xmlStr) throw new Error("Please load the resource first : " + tmxFile);
+
+ var mapXML = this._parseXML(xmlStr);
+ var i, j;
+
+ // PARSE
+ var map = mapXML.documentElement;
+
+ var version = map.getAttribute('version');
+ var orientationStr = map.getAttribute('orientation');
+
+ if (map.nodeName === "map") {
+ if (version !== "1.0" && version !== null)
+ cc.log("cocos2d: TMXFormat: Unsupported TMX version:" + version);
+
+ if (orientationStr === "orthogonal")
+ this.orientation = cc.TMX_ORIENTATION_ORTHO;
+ else if (orientationStr === "isometric")
+ this.orientation = cc.TMX_ORIENTATION_ISO;
+ else if (orientationStr === "hexagonal")
+ this.orientation = cc.TMX_ORIENTATION_HEX;
+ else if (orientationStr !== null)
+ cc.log("cocos2d: TMXFomat: Unsupported orientation:" + orientationStr);
+
+ var mapSize = cc.size(0, 0);
+ mapSize.width = parseFloat(map.getAttribute('width'));
+ mapSize.height = parseFloat(map.getAttribute('height'));
+ this.setMapSize(mapSize);
+
+ mapSize = cc.size(0, 0);
+ mapSize.width = parseFloat(map.getAttribute('tilewidth'));
+ mapSize.height = parseFloat(map.getAttribute('tileheight'));
+ this.setTileSize(mapSize);
+
+ // The parent element is the map
+ var propertyArr = map.querySelectorAll("map > properties > property");
+ if (propertyArr) {
+ var aPropertyDict = {};
+ for (i = 0; i < propertyArr.length; i++) {
+ aPropertyDict[propertyArr[i].getAttribute('name')] = propertyArr[i].getAttribute('value');
+ }
+ this.properties = aPropertyDict;
+ }
+ }
+
+ // PARSE
+ var tilesets = map.getElementsByTagName('tileset');
+ if (map.nodeName !== "map") {
+ tilesets = [];
+ tilesets.push(map);
+ }
+
+ for (i = 0; i < tilesets.length; i++) {
+ var selTileset = tilesets[i];
+ // If this is an external tileset then start parsing that
+ var tsxName = selTileset.getAttribute('source');
+ if (tsxName) {
+ //this._currentFirstGID = parseInt(selTileset.getAttribute('firstgid'));
+ var tsxPath = isXmlString ? cc.path.join(this._resources, tsxName) : cc.path.changeBasename(tmxFile, tsxName);
+ this.parseXMLFile(tsxPath);
+ } else {
+ var tileset = new cc.TMXTilesetInfo();
+ tileset.name = selTileset.getAttribute('name') || "";
+ //TODO need fix
+ //if(this._currentFirstGID === 0){
+ tileset.firstGid = parseInt(selTileset.getAttribute('firstgid')) || 0;
+ //}else{
+ // tileset.firstGid = this._currentFirstGID;
+ // this._currentFirstGID = 0;
+ //}
+
+ tileset.spacing = parseInt(selTileset.getAttribute('spacing')) || 0;
+ tileset.margin = parseInt(selTileset.getAttribute('margin')) || 0;
+
+ var tilesetSize = cc.size(0, 0);
+ tilesetSize.width = parseFloat(selTileset.getAttribute('tilewidth'));
+ tilesetSize.height = parseFloat(selTileset.getAttribute('tileheight'));
+ tileset._tileSize = tilesetSize;
+
+ var image = selTileset.getElementsByTagName('image')[0];
+ var imagename = image.getAttribute('source');
+ var num = -1;
+ if(this.tmxFileName)
+ num = this.tmxFileName.lastIndexOf("/");
+ if (num !== -1) {
+ var dir = this.tmxFileName.substr(0, num + 1);
+ tileset.sourceImage = dir + imagename;
+ } else {
+ tileset.sourceImage = this._resources + (this._resources ? "/" : "") + imagename;
+ }
+ this.setTilesets(tileset);
+
+ // PARSE
+ var tiles = selTileset.getElementsByTagName('tile');
+ if (tiles) {
+ for (var tIdx = 0; tIdx < tiles.length; tIdx++) {
+ var t = tiles[tIdx];
+ this.parentGID = parseInt(tileset.firstGid) + parseInt(t.getAttribute('id') || 0);
+ var tp = t.querySelectorAll("properties > property");
+ if (tp) {
+ var dict = {};
+ for (j = 0; j < tp.length; j++) {
+ var name = tp[j].getAttribute('name');
+ dict[name] = tp[j].getAttribute('value');
+ }
+ this._tileProperties[this.parentGID] = dict;
+ }
+ }
+ }
+ }
+ }
+
+ // PARSE
+ var layers = map.getElementsByTagName('layer');
+ if (layers) {
+ for (i = 0; i < layers.length; i++) {
+ var selLayer = layers[i];
+ var data = selLayer.getElementsByTagName('data')[0];
+
+ var layer = new cc.TMXLayerInfo();
+ layer.name = selLayer.getAttribute('name');
+
+ var layerSize = cc.size(0, 0);
+ layerSize.width = parseFloat(selLayer.getAttribute('width'));
+ layerSize.height = parseFloat(selLayer.getAttribute('height'));
+ layer._layerSize = layerSize;
+
+ var visible = selLayer.getAttribute('visible');
+ layer.visible = !(visible == "0");
+
+ var opacity = selLayer.getAttribute('opacity') || 1;
+
+ if (opacity)
+ layer._opacity = parseInt(255 * parseFloat(opacity));
+ else
+ layer._opacity = 255;
+ layer.offset = cc.p(parseFloat(selLayer.getAttribute('x')) || 0, parseFloat(selLayer.getAttribute('y')) || 0);
+
+ var nodeValue = '';
+ for (j = 0; j < data.childNodes.length; j++) {
+ nodeValue += data.childNodes[j].nodeValue
+ }
+ nodeValue = nodeValue.trim();
+
+ // Unpack the tilemap data
+ var compression = data.getAttribute('compression');
+ var encoding = data.getAttribute('encoding');
+ if(compression && compression !== "gzip" && compression !== "zlib"){
+ cc.log("cc.TMXMapInfo.parseXMLFile(): unsupported compression method");
+ return null;
+ }
+ switch (compression) {
+ case 'gzip':
+ layer._tiles = cc.unzipBase64AsArray(nodeValue, 4);
+ break;
+ case 'zlib':
+ var inflator = new Zlib.Inflate(cc.Codec.Base64.decodeAsArray(nodeValue, 1));
+ layer._tiles = cc.uint8ArrayToUint32Array(inflator.decompress());
+ break;
+ case null:
+ case '':
+ // Uncompressed
+ if (encoding === "base64")
+ layer._tiles = cc.Codec.Base64.decodeAsArray(nodeValue, 4);
+ else if (encoding === "csv") {
+ layer._tiles = [];
+ var csvTiles = nodeValue.split(',');
+ for (var csvIdx = 0; csvIdx < csvTiles.length; csvIdx++)
+ layer._tiles.push(parseInt(csvTiles[csvIdx]));
+ } else {
+ //XML format
+ var selDataTiles = data.getElementsByTagName("tile");
+ layer._tiles = [];
+ for (var xmlIdx = 0; xmlIdx < selDataTiles.length; xmlIdx++)
+ layer._tiles.push(parseInt(selDataTiles[xmlIdx].getAttribute("gid")));
+ }
+ break;
+ default:
+ if(this.layerAttrs === cc.TMXLayerInfo.ATTRIB_NONE)
+ cc.log("cc.TMXMapInfo.parseXMLFile(): Only base64 and/or gzip/zlib maps are supported");
+ break;
+ }
+
+ // The parent element is the last layer
+ var layerProps = selLayer.querySelectorAll("properties > property");
+ if (layerProps) {
+ var layerProp = {};
+ for (j = 0; j < layerProps.length; j++) {
+ layerProp[layerProps[j].getAttribute('name')] = layerProps[j].getAttribute('value');
+ }
+ layer.properties = layerProp;
+ }
+ this.setLayers(layer);
+ }
+ }
+
+ // PARSE
+ var objectGroups = map.getElementsByTagName('objectgroup');
+ if (objectGroups) {
+ for (i = 0; i < objectGroups.length; i++) {
+ var selGroup = objectGroups[i];
+ var objectGroup = new cc.TMXObjectGroup();
+ objectGroup.groupName = selGroup.getAttribute('name');
+ objectGroup.setPositionOffset(cc.p(parseFloat(selGroup.getAttribute('x')) * this.getTileSize().width || 0,
+ parseFloat(selGroup.getAttribute('y')) * this.getTileSize().height || 0));
+
+ var groupProps = selGroup.querySelectorAll("objectgroup > properties > property");
+ if (groupProps) {
+ for (j = 0; j < groupProps.length; j++) {
+ var groupProp = {};
+ groupProp[groupProps[j].getAttribute('name')] = groupProps[j].getAttribute('value');
+ // Add the property to the layer
+ objectGroup.properties = groupProp;
+ }
+ }
+
+ var objects = selGroup.querySelectorAll('object');
+ var getContentScaleFactor = cc.director.getContentScaleFactor();
+ if (objects) {
+ for (j = 0; j < objects.length; j++) {
+ var selObj = objects[j];
+ // The value for "type" was blank or not a valid class name
+ // Create an instance of TMXObjectInfo to store the object and its properties
+ var objectProp = {};
+
+ // Set the name of the object to the value for "name"
+ objectProp["name"] = selObj.getAttribute('name') || "";
+
+ // Assign all the attributes as key/name pairs in the properties dictionary
+ objectProp["type"] = selObj.getAttribute('type') || "";
+
+ objectProp["width"] = parseInt(selObj.getAttribute('width')) || 0;
+ objectProp["height"] = parseInt(selObj.getAttribute('height')) || 0;
+
+ objectProp["x"] = (((selObj.getAttribute('x') || 0) | 0) + objectGroup.getPositionOffset().x) / getContentScaleFactor;
+ var y = ((selObj.getAttribute('y') || 0) | 0) + objectGroup.getPositionOffset().y / getContentScaleFactor;
+ // Correct y position. (Tiled uses Flipped, cocos2d uses Standard)
+ objectProp["y"] = (parseInt(this.getMapSize().height * this.getTileSize().height) - y - objectProp["height"]) / cc.director.getContentScaleFactor();
+
+ objectProp["rotation"] = parseInt(selObj.getAttribute('rotation')) || 0;
+
+ var docObjProps = selObj.querySelectorAll("properties > property");
+ if (docObjProps) {
+ for (var k = 0; k < docObjProps.length; k++)
+ objectProp[docObjProps[k].getAttribute('name')] = docObjProps[k].getAttribute('value');
+ }
+
+ //polygon
+ var polygonProps = selObj.querySelectorAll("polygon");
+ if(polygonProps && polygonProps.length > 0) {
+ var selPgPointStr = polygonProps[0].getAttribute('points');
+ if(selPgPointStr)
+ objectProp["points"] = this._parsePointsString(selPgPointStr);
+ }
+
+ //polyline
+ var polylineProps = selObj.querySelectorAll("polyline");
+ if(polylineProps && polylineProps.length > 0) {
+ var selPlPointStr = polylineProps[0].getAttribute('points');
+ if(selPlPointStr)
+ objectProp["polylinePoints"] = this._parsePointsString(selPlPointStr);
+ }
+
+ // Add the object to the objectGroup
+ objectGroup.setObjects(objectProp);
+ }
+ }
+
+ this.setObjectGroups(objectGroup);
+ }
+ }
+ return map;
+ },
+
+ _parsePointsString:function(pointsString){
+ if(!pointsString)
+ return null;
+
+ var points = [];
+ var pointsStr = pointsString.split(' ');
+ for(var i = 0; i < pointsStr.length; i++){
+ var selPointStr = pointsStr[i].split(',');
+ points.push({'x':selPointStr[0], 'y':selPointStr[1]});
+ }
+ return points;
+ },
+
+ /**
+ * initializes parsing of an XML string, either a tmx (Map) string or tsx (Tileset) string
+ * @param {String} xmlString
+ * @return {Boolean}
+ */
+ parseXMLString:function (xmlString) {
+ return this.parseXMLFile(xmlString, true);
+ },
+
+ /**
+ * Gets the tile properties.
+ * @return {object}
+ */
+ getTileProperties:function () {
+ return this._tileProperties;
+ },
+
+ /**
+ * Set the tile properties.
+ * @param {object} tileProperties
+ */
+ setTileProperties:function (tileProperties) {
+ this._tileProperties.push(tileProperties);
+ },
+
+ /**
+ * Gets the currentString
+ * @return {String}
+ */
+ getCurrentString:function () {
+ return this.currentString;
+ },
+
+ /**
+ * Set the currentString
+ * @param {String} currentString
+ */
+ setCurrentString:function (currentString) {
+ this.currentString = currentString;
+ },
+
+ /**
+ * Gets the tmxFileName
+ * @return {String}
+ */
+ getTMXFileName:function () {
+ return this.tmxFileName;
+ },
+
+ /**
+ * Set the tmxFileName
+ * @param {String} fileName
+ */
+ setTMXFileName:function (fileName) {
+ this.tmxFileName = fileName;
+ },
+
+ _internalInit:function (tmxFileName, resourcePath) {
+ this._tilesets.length = 0;
+ this._layers.length = 0;
+
+ this.tmxFileName = tmxFileName;
+ if (resourcePath)
+ this._resources = resourcePath;
+
+ this._objectGroups.length = 0;
+ this.properties.length = 0;
+ this._tileProperties.length = 0;
+
+ // tmp vars
+ this.currentString = "";
+ this.storingCharacters = false;
+ this.layerAttrs = cc.TMXLayerInfo.ATTRIB_NONE;
+ this.parentElement = cc.TMX_PROPERTY_NONE;
+ this._currentFirstGID = 0;
+ }
+});
+
+var _p = cc.TMXMapInfo.prototype;
+
+// Extended properties
+/** @expose */
+_p.mapWidth;
+cc.defineGetterSetter(_p, "mapWidth", _p._getMapWidth, _p._setMapWidth);
+/** @expose */
+_p.mapHeight;
+cc.defineGetterSetter(_p, "mapHeight", _p._getMapHeight, _p._setMapHeight);
+/** @expose */
+_p.tileWidth;
+cc.defineGetterSetter(_p, "tileWidth", _p._getTileWidth, _p._setTileWidth);
+/** @expose */
+_p.tileHeight;
+cc.defineGetterSetter(_p, "tileHeight", _p._getTileHeight, _p._setTileHeight);
+
+
+/**
+ * Creates a TMX Format with a tmx file or content string
+ * @deprecated since v3.0 please use new cc.TMXMapInfo(tmxFile, resourcePath) instead.
+ * @param {String} tmxFile fileName or content string
+ * @param {String} resourcePath If tmxFile is a file name ,it is not required.If tmxFile is content string ,it is must required.
+ * @return {cc.TMXMapInfo}
+ */
+cc.TMXMapInfo.create = function (tmxFile, resourcePath) {
+ return new cc.TMXMapInfo(tmxFile, resourcePath);
+};
+
+
+cc.loader.register(["tmx", "tsx"], cc._txtLoader);
+
+
+/**
+ * @constant
+ * @type Number
+ */
+cc.TMXLayerInfo.ATTRIB_NONE = 1 << 0;
+/**
+ * @constant
+ * @type Number
+ */
+cc.TMXLayerInfo.ATTRIB_BASE64 = 1 << 1;
+/**
+ * @constant
+ * @type Number
+ */
+cc.TMXLayerInfo.ATTRIB_GZIP = 1 << 2;
+/**
+ * @constant
+ * @type Number
+ */
+cc.TMXLayerInfo.ATTRIB_ZLIB = 1 << 3;
diff --git a/cocos2d/transitions/CCTransition.js b/cocos2d/transitions/CCTransition.js
new file mode 100644
index 0000000000..949893ba2f
--- /dev/null
+++ b/cocos2d/transitions/CCTransition.js
@@ -0,0 +1,1966 @@
+/****************************************************************************
+ 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 tag constant for identifying fade scenes
+ * @constant
+ * @type Number
+ */
+cc.SCENE_FADE = 4208917214;
+
+/**
+ * horizontal orientation Type where the Left is nearer
+ * @constant
+ * @type Number
+ */
+cc.TRANSITION_ORIENTATION_LEFT_OVER = 0;
+/**
+ * horizontal orientation type where the Right is nearer
+ * @constant
+ * @type Number
+ */
+cc.TRANSITION_ORIENTATION_RIGHT_OVER = 1;
+/**
+ * vertical orientation type where the Up is nearer
+ * @constant
+ * @type Number
+ */
+cc.TRANSITION_ORIENTATION_UP_OVER = 0;
+/**
+ * vertical orientation type where the Bottom is nearer
+ * @constant
+ * @type Number
+ */
+cc.TRANSITION_ORIENTATION_DOWN_OVER = 1;
+
+/**
+ * @class
+ * @extends cc.Scene
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene the scene to transit with
+ * @example
+ * var trans = new TransitionScene(time,scene);
+ */
+cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{
+ _inScene:null,
+ _outScene:null,
+ _duration:null,
+ _isInSceneOnTop:false,
+ _isSendCleanupToScene:false,
+ _className:"TransitionScene",
+
+ /**
+ * creates a base transition with duration and incoming scene
+ * Constructor of cc.TransitionScene
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene the scene to transit with
+ */
+ ctor:function (t, scene) {
+ cc.Scene.prototype.ctor.call(this);
+ if(t !== undefined && scene !== undefined)
+ this.initWithDuration(t, scene);
+ },
+
+ //private
+ _setNewScene:function (dt) {
+ this.unschedule(this._setNewScene);
+ // Before replacing, save the "send cleanup to scene"
+ var director = cc.director;
+ this._isSendCleanupToScene = director.isSendCleanupToScene();
+ director.runScene(this._inScene);
+
+ // enable events while transitions
+ cc.eventManager.setEnabled(true);
+
+ // issue #267
+ this._outScene.visible = true;
+ },
+
+ //protected
+ _sceneOrder:function () {
+ this._isInSceneOnTop = true;
+ },
+
+ /**
+ * stuff gets drawn here
+ */
+ visit:function () {
+ if (this._isInSceneOnTop) {
+ this._outScene.visit();
+ this._inScene.visit();
+ } else {
+ this._inScene.visit();
+ this._outScene.visit();
+ }
+ cc.Node.prototype.visit.call(this);
+ },
+
+ /**
+ *
+ * Event callback that is invoked every time when cc.TransitionScene enters the 'stage'.
+ * If the TransitionScene enters the 'stage' with a transition, this event is called when the transition starts.
+ * During onEnter you can't access a "sister/brother" node.
+ * If you override onEnter, you must call its parent's onEnter function with this._super().
+ *
+ */
+ onEnter:function () {
+ cc.Node.prototype.onEnter.call(this);
+
+ // disable events while transitions
+ cc.eventManager.setEnabled(false);
+
+ // outScene should not receive the onEnter callback
+ // only the onExitTransitionDidStart
+ this._outScene.onExitTransitionDidStart();
+
+ this._inScene.onEnter();
+ },
+
+ /**
+ *
+ * callback that is called every time the cc.TransitionScene leaves the 'stage'.
+ * If the cc.TransitionScene leaves the 'stage' with a transition, this callback is called when the transition finishes.
+ * During onExit you can't access a sibling node.
+ * If you override onExit, you shall call its parent's onExit with this._super().
+ *
+ */
+ onExit:function () {
+ cc.Node.prototype.onExit.call(this);
+
+ // enable events while transitions
+ cc.eventManager.setEnabled(true);
+
+ this._outScene.onExit();
+
+ // _inScene should not receive the onEnter callback
+ // only the onEnterTransitionDidFinish
+ this._inScene.onEnterTransitionDidFinish();
+ },
+
+ /**
+ * custom cleanup
+ */
+ cleanup:function () {
+ cc.Node.prototype.cleanup.call(this);
+
+ if (this._isSendCleanupToScene)
+ this._outScene.cleanup();
+ },
+
+ /**
+ * initializes a transition with duration and incoming scene
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene a scene to transit to
+ * @return {Boolean} return false if error
+ */
+ initWithDuration:function (t, scene) {
+ if(!scene)
+ throw new Error("cc.TransitionScene.initWithDuration(): Argument scene must be non-nil");
+
+ if (this.init()) {
+ this._duration = t;
+ this.attr({
+ x: 0,
+ y: 0,
+ anchorX: 0,
+ anchorY: 0
+ });
+ // retain
+ this._inScene = scene;
+ this._outScene = cc.director.getRunningScene();
+ if (!this._outScene) {
+ this._outScene = new cc.Scene();
+ this._outScene.init();
+ }
+
+ if(this._inScene === this._outScene)
+ throw new Error("cc.TransitionScene.initWithDuration(): Incoming scene must be different from the outgoing scene");
+
+ this._sceneOrder();
+ return true;
+ } else {
+ return false;
+ }
+ },
+
+ /**
+ * called after the transition finishes
+ */
+ finish:function () {
+ // clean up
+ this._inScene.attr({
+ visible: true,
+ x: 0,
+ y: 0,
+ scale: 1.0,
+ rotation: 0.0
+ });
+ if(cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ this._inScene.getCamera().restore();
+
+ this._outScene.attr({
+ visible: false,
+ x: 0,
+ y: 0,
+ scale: 1.0,
+ rotation: 0.0
+ });
+ if(cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ this._outScene.getCamera().restore();
+
+ //[self schedule:@selector(setNewScene:) interval:0];
+ this.schedule(this._setNewScene, 0);
+ },
+
+ /**
+ * set hide the out scene and show in scene
+ */
+ hideOutShowIn:function () {
+ this._inScene.visible = true;
+ this._outScene.visible = false;
+ }
+});
+/**
+ * creates a base transition with duration and incoming scene
+ * @deprecated since v3.0, please use new cc.TransitionScene(t,scene) instead
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene the scene to transit with
+ * @return {cc.TransitionScene|Null}
+ */
+cc.TransitionScene.create = function (t, scene) {
+ return new cc.TransitionScene(t, scene);
+};
+
+/**
+ * A cc.Transition that supports orientation like.
+ * Possible orientation: LeftOver, RightOver, UpOver, DownOver
+ * useful for when you want to make a transition happen between 2 orientations
+ * @class
+ * @extends cc.TransitionScene
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} orientation
+ * @example
+ * var trans = new cc.TransitionSceneOriented(time,scene,orientation);
+ */
+cc.TransitionSceneOriented = cc.TransitionScene.extend(/** @lends cc.TransitionSceneOriented# */{
+ _orientation:0,
+
+ /**
+ * Constructor of TransitionSceneOriented
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} orientation
+ */
+ ctor:function (t, scene, orientation) {
+ cc.TransitionScene.prototype.ctor.call(this);
+ orientation != undefined && this.initWithDuration(t, scene, orientation);
+ },
+ /**
+ * initialize the transition
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} orientation
+ * @return {Boolean}
+ */
+ initWithDuration:function (t, scene, orientation) {
+ if (cc.TransitionScene.prototype.initWithDuration.call(this, t, scene)) {
+ this._orientation = orientation;
+ }
+ return true;
+ }
+});
+
+/**
+ * creates a base transition with duration and incoming scene
+ * @deprecated since v3.0 ,please use new cc.TransitionSceneOriented(t, scene, orientation) instead.
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} orientation
+ * @return {cc.TransitionSceneOriented}
+ */
+cc.TransitionSceneOriented.create = function (t, scene, orientation) {
+ return new cc.TransitionSceneOriented(t, scene, orientation);
+};
+
+/**
+ * Rotate and zoom out the outgoing scene, and then rotate and zoom in the incoming
+ * @class
+ * @extends cc.TransitionScene
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @example
+ * var trans = new cc.TransitionRotoZoom(t, scene);
+ */
+cc.TransitionRotoZoom = cc.TransitionScene.extend(/** @lends cc.TransitionRotoZoom# */{
+
+ /**
+ * Constructor of TransitionRotoZoom
+ * @function
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ */
+ ctor:function (t, scene) {
+ cc.TransitionScene.prototype.ctor.call(this);
+ scene && this.initWithDuration(t, scene);
+ },
+ /**
+ * Custom On Enter callback
+ * @override
+ */
+ onEnter:function () {
+ cc.TransitionScene.prototype.onEnter.call(this);
+
+ this._inScene.attr({
+ scale: 0.001,
+ anchorX: 0.5,
+ anchorY: 0.5
+ });
+ this._outScene.attr({
+ scale: 1.0,
+ anchorX: 0.5,
+ anchorY: 0.5
+ });
+
+ var rotoZoom = cc.sequence(
+ cc.spawn(cc.scaleBy(this._duration / 2, 0.001),
+ cc.rotateBy(this._duration / 2, 360 * 2)),
+ cc.delayTime(this._duration / 2));
+
+ this._outScene.runAction(rotoZoom);
+ this._inScene.runAction(
+ cc.sequence(rotoZoom.reverse(),
+ cc.callFunc(this.finish, this)));
+ }
+});
+
+/**
+ * Creates a Transtion rotation and zoom
+ * @deprecated since v3.0,please use new cc.TransitionRotoZoom(t, scene) instead
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene the scene to work with
+ * @return {cc.TransitionRotoZoom}
+ */
+cc.TransitionRotoZoom.create = function (t, scene) {
+ return new cc.TransitionRotoZoom(t, scene);
+};
+
+/**
+ * Zoom out and jump the outgoing scene, and then jump and zoom in the incoming
+ * @class
+ * @extends cc.TransitionScene
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @example
+ * var trans = new cc.TransitionJumpZoom(t, scene);
+ */
+cc.TransitionJumpZoom = cc.TransitionScene.extend(/** @lends cc.TransitionJumpZoom# */{
+ /**
+ * Constructor of TransitionJumpZoom
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ */
+ ctor:function (t, scene) {
+ cc.TransitionScene.prototype.ctor.call(this);
+ scene && this.initWithDuration(t, scene);
+ },
+ /**
+ * Custom on enter
+ */
+ onEnter:function () {
+ cc.TransitionScene.prototype.onEnter.call(this);
+ var winSize = cc.director.getWinSize();
+
+ this._inScene.attr({
+ scale: 0.5,
+ x: winSize.width,
+ y: 0,
+ anchorX: 0.5,
+ anchorY: 0.5
+ });
+ this._outScene.anchorX = 0.5;
+ this._outScene.anchorY = 0.5;
+
+ var jump = cc.jumpBy(this._duration / 4, cc.p(-winSize.width, 0), winSize.width / 4, 2);
+ var scaleIn = cc.scaleTo(this._duration / 4, 1.0);
+ var scaleOut = cc.scaleTo(this._duration / 4, 0.5);
+
+ var jumpZoomOut = cc.sequence(scaleOut, jump);
+ var jumpZoomIn = cc.sequence(jump, scaleIn);
+
+ var delay = cc.delayTime(this._duration / 2);
+ this._outScene.runAction(jumpZoomOut);
+ this._inScene.runAction(cc.sequence(delay, jumpZoomIn, cc.callFunc(this.finish, this)));
+ }
+});
+
+/**
+ * creates a scene transition that zooms then jump across the screen, the same for the incoming scene
+ * @deprecated since v3.0,please use new cc.TransitionJumpZoom(t, scene);
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @return {cc.TransitionJumpZoom}
+ */
+cc.TransitionJumpZoom.create = function (t, scene) {
+ return new cc.TransitionJumpZoom(t, scene);
+};
+
+/**
+ * Move in from to the left the incoming scene.
+ * @class
+ * @extends cc.TransitionScene
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @example
+ * var trans = new cc.TransitionMoveInL(time,scene);
+ */
+cc.TransitionMoveInL = cc.TransitionScene.extend(/** @lends cc.TransitionMoveInL# */{
+ /**
+ * Constructor of TransitionMoveInL
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ */
+ ctor:function (t, scene) {
+ cc.TransitionScene.prototype.ctor.call(this);
+ scene && this.initWithDuration(t, scene);
+ },
+ /**
+ * Custom on enter
+ */
+ onEnter:function () {
+ cc.TransitionScene.prototype.onEnter.call(this);
+ this.initScenes();
+
+ var action = this.action();
+ this._inScene.runAction(
+ cc.sequence(this.easeActionWithAction(action), cc.callFunc(this.finish, this))
+ );
+ },
+
+ /**
+ * initializes the scenes
+ */
+ initScenes:function () {
+ this._inScene.setPosition(-cc.director.getWinSize().width, 0);
+ },
+
+ /**
+ * returns the action that will be performed
+ */
+ action:function () {
+ return cc.moveTo(this._duration, cc.p(0, 0));
+ },
+
+ /**
+ * creates an ease action from action
+ * @param {cc.ActionInterval} action
+ * @return {cc.EaseOut}
+ */
+ easeActionWithAction:function (action) {
+ return new cc.EaseOut(action, 2.0);
+ }
+});
+
+/**
+ * creates an action that Move in from to the left the incoming scene.
+ * @deprecated since v3.0,please use new cc.TransitionMoveInL(t, scene) instead
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @return {cc.TransitionMoveInL}
+ */
+cc.TransitionMoveInL.create = function (t, scene) {
+ return new cc.TransitionMoveInL(t, scene);
+};
+
+/**
+ * Move in from to the right the incoming scene.
+ * @class
+ * @extends cc.TransitionMoveInL
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @example
+ * var trans = new cc.TransitionMoveInR(time,scene);
+ */
+cc.TransitionMoveInR = cc.TransitionMoveInL.extend(/** @lends cc.TransitionMoveInR# */{
+ /**
+ * Constructor of TransitionMoveInR
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ */
+ ctor:function (t, scene) {
+ cc.TransitionMoveInL.prototype.ctor.call(this);
+ scene && this.initWithDuration(t, scene);
+ },
+ /**
+ * Init function
+ */
+ initScenes:function () {
+ this._inScene.setPosition(cc.director.getWinSize().width, 0);
+ }
+});
+
+/**
+ * create a scene transition that Move in from to the right the incoming scene.
+ * @deprecated since v3.0,please use new cc.TransitionMoveInR(t, scene) instead
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @return {cc.TransitionMoveInR}
+ */
+cc.TransitionMoveInR.create = function (t, scene) {
+ return new cc.TransitionMoveInR(t, scene);
+};
+
+/**
+ * Move in from to the top the incoming scene.
+ * @class
+ * @extends cc.TransitionMoveInL
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @example
+ * var trans = new cc.TransitionMoveInT(time,scene);
+ */
+cc.TransitionMoveInT = cc.TransitionMoveInL.extend(/** @lends cc.TransitionMoveInT# */{
+ /**
+ * Constructor of TransitionMoveInT
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ */
+ ctor:function (t, scene) {
+ cc.TransitionMoveInL.prototype.ctor.call(this);
+ scene && this.initWithDuration(t, scene);
+ },
+ /**
+ * init function
+ */
+ initScenes:function () {
+ this._inScene.setPosition(0, cc.director.getWinSize().height);
+ }
+});
+
+/**
+ * Move in from to the top the incoming scene.
+ * @deprecated since v3.0,please use new cc.TransitionMoveInT(t, scene) instead
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @return {cc.TransitionMoveInT}
+ */
+cc.TransitionMoveInT.create = function (t, scene) {
+ return new cc.TransitionMoveInT(t, scene);
+};
+
+/**
+ * Move in from to the bottom the incoming scene.
+ * @class
+ * @extends cc.TransitionMoveInL
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @example
+ * var trans = new cc.TransitionMoveInB(time,scene);
+ */
+cc.TransitionMoveInB = cc.TransitionMoveInL.extend(/** @lends cc.TransitionMoveInB# */{
+ /**
+ * Constructor of TransitionMoveInB
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ */
+ ctor:function (t, scene) {
+ cc.TransitionMoveInL.prototype.ctor.call(this);
+ scene && this.initWithDuration(t, scene);
+ },
+
+ /**
+ * init function
+ */
+ initScenes:function () {
+ this._inScene.setPosition(0, -cc.director.getWinSize().height);
+ }
+});
+
+/**
+ * create a scene transition that Move in from to the bottom the incoming scene.
+ * @deprecated since v3.0,please use new cc.TransitionMoveInB(t, scene) instead
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @return {cc.TransitionMoveInB}
+ */
+cc.TransitionMoveInB.create = function (t, scene) {
+ return new cc.TransitionMoveInB(t, scene);
+};
+
+/**
+ * The adjust factor is needed to prevent issue #442
+ * One solution is to use DONT_RENDER_IN_SUBPIXELS images, but NO
+ * The other issue is that in some transitions (and I don't know why)
+ * the order should be reversed (In in top of Out or vice-versa).
+ * @constant
+ * @type Number
+ */
+cc.ADJUST_FACTOR = 0.5;
+
+/**
+ * a transition that a new scene is slided from left
+ * @class
+ * @extends cc.TransitionScene
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @example
+ * var trans = cc.TransitionSlideInL(time,scene);
+ */
+cc.TransitionSlideInL = cc.TransitionScene.extend(/** @lends cc.TransitionSlideInL# */{
+ /**
+ * Constructor of TransitionSlideInL
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ */
+ ctor:function (t, scene) {
+ cc.TransitionScene.prototype.ctor.call(this);
+ scene && this.initWithDuration(t, scene);
+ },
+ _sceneOrder:function () {
+ this._isInSceneOnTop = false;
+ },
+
+ /**
+ * custom on enter
+ */
+ onEnter:function () {
+ cc.TransitionScene.prototype.onEnter.call(this);
+ this.initScenes();
+
+ var inA = this.action();
+ var outA = this.action();
+
+ var inAction = cc.sequence(this.easeActionWithAction(inA), cc.callFunc(this.finish, this));
+ var outAction = this.easeActionWithAction(outA);
+ this._inScene.runAction(inAction);
+ this._outScene.runAction(outAction);
+ },
+
+ /**
+ * initializes the scenes
+ */
+ initScenes:function () {
+ this._inScene.setPosition(-cc.director.getWinSize().width + cc.ADJUST_FACTOR, 0);
+ },
+ /**
+ * returns the action that will be performed by the incomming and outgoing scene
+ * @return {cc.MoveBy}
+ */
+ action:function () {
+ return cc.moveBy(this._duration, cc.p(cc.director.getWinSize().width - cc.ADJUST_FACTOR, 0));
+ },
+
+ /**
+ * @param {cc.ActionInterval} action
+ * @return {*}
+ */
+ easeActionWithAction:function (action) {
+ return new cc.EaseInOut(action, 2.0);
+ }
+});
+
+/**
+ * create a transition that a new scene is slided from left
+ * @deprecated since v3.0,please use new cc.TransitionSlideInL(t, scene) instead
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @return {cc.TransitionSlideInL}
+ */
+cc.TransitionSlideInL.create = function (t, scene) {
+ return new cc.TransitionSlideInL(t, scene);
+};
+
+/**
+ * Slide in the incoming scene from the right border.
+ * @class
+ * @extends cc.TransitionSlideInL
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @example
+ * var trans = new cc.TransitionSlideInR(time,scene);
+ */
+cc.TransitionSlideInR = cc.TransitionSlideInL.extend(/** @lends cc.TransitionSlideInR# */{
+ /**
+ * Constructor of TransitionSlideInR
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ */
+ ctor:function (t, scene) {
+ cc.TransitionSlideInL.prototype.ctor.call(this);
+ scene && this.initWithDuration(t, scene);
+ },
+ _sceneOrder:function () {
+ this._isInSceneOnTop = true;
+ },
+ /**
+ * initializes the scenes
+ */
+ initScenes:function () {
+ this._inScene.setPosition(cc.director.getWinSize().width - cc.ADJUST_FACTOR, 0);
+ },
+ /**
+ * returns the action that will be performed by the incomming and outgoing scene
+ * @return {cc.MoveBy}
+ */
+ action:function () {
+ return cc.moveBy(this._duration, cc.p(-(cc.director.getWinSize().width - cc.ADJUST_FACTOR), 0));
+ }
+});
+
+/**
+ * create Slide in the incoming scene from the right border.
+ * @deprecated since v3.0,please use new cc.TransitionSlideInR(t, scene) instead
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @return {cc.TransitionSlideInR}
+ */
+cc.TransitionSlideInR.create = function (t, scene) {
+ return new cc.TransitionSlideInR(t, scene);
+};
+
+/**
+ * Slide in the incoming scene from the bottom border.
+ * @class
+ * @extends cc.TransitionSlideInL
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @example
+ * var trans = new cc.TransitionSlideInB(time,scene);
+ */
+cc.TransitionSlideInB = cc.TransitionSlideInL.extend(/** @lends cc.TransitionSlideInB# */{
+ /**
+ * Constructor of TransitionSlideInB
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ */
+ ctor:function (t, scene) {
+ cc.TransitionSlideInL.prototype.ctor.call(this);
+ scene && this.initWithDuration(t, scene);
+ },
+ _sceneOrder:function () {
+ this._isInSceneOnTop = false;
+ },
+
+ /**
+ * initializes the scenes
+ */
+ initScenes:function () {
+ this._inScene.setPosition(0, -(cc.director.getWinSize().height - cc.ADJUST_FACTOR));
+ },
+
+ /**
+ * returns the action that will be performed by the incomming and outgoing scene
+ * @return {cc.MoveBy}
+ */
+ action:function () {
+ return cc.moveBy(this._duration, cc.p(0, cc.director.getWinSize().height - cc.ADJUST_FACTOR));
+ }
+});
+
+/**
+ * create a Slide in the incoming scene from the bottom border.
+ * @deprecated since v3.0,please use new cc.TransitionSlideInB(t, scene) instead.
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @return {cc.TransitionSlideInB}
+ */
+cc.TransitionSlideInB.create = function (t, scene) {
+ return new cc.TransitionSlideInB(t, scene);
+};
+
+/**
+ * Slide in the incoming scene from the top border.
+ * @class
+ * @extends cc.TransitionSlideInL
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @example
+ * var trans = new cc.TransitionSlideInT(time,scene);
+ */
+cc.TransitionSlideInT = cc.TransitionSlideInL.extend(/** @lends cc.TransitionSlideInT# */{
+ /**
+ * Constructor of TransitionSlideInT
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ */
+ ctor:function (t, scene) {
+ cc.TransitionSlideInL.prototype.ctor.call(this);
+ scene && this.initWithDuration(t, scene);
+ },
+ _sceneOrder:function () {
+ this._isInSceneOnTop = true;
+ },
+
+ /**
+ * initializes the scenes
+ */
+ initScenes:function () {
+ this._inScene.setPosition(0, cc.director.getWinSize().height - cc.ADJUST_FACTOR);
+ },
+
+ /**
+ * returns the action that will be performed by the incomming and outgoing scene
+ * @return {cc.MoveBy}
+ */
+ action:function () {
+ return cc.moveBy(this._duration, cc.p(0, -(cc.director.getWinSize().height - cc.ADJUST_FACTOR)));
+ }
+});
+
+/**
+ * create a Slide in the incoming scene from the top border.
+ * @deprecated since v3.0,please use new cc.TransitionSlideInT(t, scene) instead.
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @return {cc.TransitionSlideInT}
+ */
+cc.TransitionSlideInT.create = function (t, scene) {
+ return new cc.TransitionSlideInT(t, scene);
+};
+
+/**
+ * Shrink the outgoing scene while grow the incoming scene
+ * @class
+ * @extends cc.TransitionScene
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @example
+ * var trans = new cc.TransitionShrinkGrow(time,scene);
+ */
+cc.TransitionShrinkGrow = cc.TransitionScene.extend(/** @lends cc.TransitionShrinkGrow# */{
+ /**
+ * Constructor of TransitionShrinkGrow
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ */
+ ctor:function (t, scene) {
+ cc.TransitionScene.prototype.ctor.call(this);
+ scene && this.initWithDuration(t, scene);
+ },
+ /**
+ * Custom on enter
+ */
+ onEnter:function () {
+ cc.TransitionScene.prototype.onEnter.call(this);
+
+ this._inScene.attr({
+ scale: 0.001,
+ anchorX: 2 / 3.0,
+ anchorY: 0.5
+ });
+ this._outScene.attr({
+ scale: 1.0,
+ anchorX: 1 / 3.0,
+ anchorY: 0.5
+ });
+
+ var scaleOut = cc.scaleTo(this._duration, 0.01);
+ var scaleIn = cc.scaleTo(this._duration, 1.0);
+
+ this._inScene.runAction(cc.sequence(this.easeActionWithAction(scaleIn), cc.callFunc(this.finish, this)));
+ this._outScene.runAction(this.easeActionWithAction(scaleOut));
+ },
+
+ /**
+ * @param action
+ * @return {cc.EaseOut}
+ */
+ easeActionWithAction:function (action) {
+ return new cc.EaseOut(action, 2.0);
+ }
+});
+
+/**
+ * Shrink the outgoing scene while grow the incoming scene
+ * @deprecated since v3.0,please use new cc.TransitionShrinkGrow(t, scene) instead.
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @return {cc.TransitionShrinkGrow}
+ */
+cc.TransitionShrinkGrow.create = function (t, scene) {
+ return new cc.TransitionShrinkGrow(t, scene);
+};
+
+/**
+ * Flips the screen horizontally.
+ * The front face is the outgoing scene and the back face is the incoming scene.
+ * @class
+ * @extends cc.TransitionSceneOriented
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o
+ * @example
+ * var trans = new cc.TransitionFlipX(t,scene,o);
+ */
+cc.TransitionFlipX = cc.TransitionSceneOriented.extend(/** @lends cc.TransitionFlipX# */{
+ /**
+ * Constructor of TransitionFlipX
+ * @function
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o
+ */
+ ctor:function (t, scene, o) {
+ cc.TransitionSceneOriented.prototype.ctor.call(this);
+ if(o == null)
+ o = cc.TRANSITION_ORIENTATION_RIGHT_OVER;
+ scene && this.initWithDuration(t, scene, o);
+ },
+
+ /**
+ * custom on enter
+ */
+ onEnter:function () {
+ cc.TransitionScene.prototype.onEnter.call(this);
+
+ var inA, outA;
+ this._inScene.visible = false;
+
+ var inDeltaZ, inAngleZ, outDeltaZ, outAngleZ;
+
+ if (this._orientation === cc.TRANSITION_ORIENTATION_RIGHT_OVER) {
+ inDeltaZ = 90;
+ inAngleZ = 270;
+ outDeltaZ = 90;
+ outAngleZ = 0;
+ } else {
+ inDeltaZ = -90;
+ inAngleZ = 90;
+ outDeltaZ = -90;
+ outAngleZ = 0;
+ }
+
+ inA = cc.sequence(
+ cc.delayTime(this._duration / 2), cc.show(),
+ cc.orbitCamera(this._duration / 2, 1, 0, inAngleZ, inDeltaZ, 0, 0),
+ cc.callFunc(this.finish, this)
+ );
+
+ outA = cc.sequence(
+ cc.orbitCamera(this._duration / 2, 1, 0, outAngleZ, outDeltaZ, 0, 0),
+ cc.hide(), cc.delayTime(this._duration / 2)
+ );
+
+ this._inScene.runAction(inA);
+ this._outScene.runAction(outA);
+ }
+});
+
+/**
+ * Flips the screen horizontally.
+ * The front face is the outgoing scene and the back face is the incoming scene.
+ * @deprecated since v3.0,please use new cc.TransitionFlipX(t, scene,o) instead.
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o
+ * @return {cc.TransitionFlipX}
+ */
+cc.TransitionFlipX.create = function (t, scene, o) {
+ return new cc.TransitionFlipX(t, scene, o);
+};
+
+/**
+ * Flips the screen vertically.
+ * The front face is the outgoing scene and the back face is the incoming scene.
+ * @class
+ * @extends cc.TransitionSceneOriented
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o
+ * @example
+ * var trans = new cc.TransitionFlipY(time,scene,0);
+ */
+cc.TransitionFlipY = cc.TransitionSceneOriented.extend(/** @lends cc.TransitionFlipY# */{
+
+ /**
+ * Constructor of TransitionFlipY
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o
+ */
+ ctor:function (t, scene, o) {
+ cc.TransitionSceneOriented.prototype.ctor.call(this);
+ if(o == null)
+ o = cc.TRANSITION_ORIENTATION_UP_OVER;
+ scene && this.initWithDuration(t, scene, o);
+ },
+ /**
+ * custom on enter
+ */
+ onEnter:function () {
+ cc.TransitionScene.prototype.onEnter.call(this);
+
+ var inA, outA;
+ this._inScene.visible = false;
+
+ var inDeltaZ, inAngleZ, outDeltaZ, outAngleZ;
+
+ if (this._orientation === cc.TRANSITION_ORIENTATION_UP_OVER) {
+ inDeltaZ = 90;
+ inAngleZ = 270;
+ outDeltaZ = 90;
+ outAngleZ = 0;
+ } else {
+ inDeltaZ = -90;
+ inAngleZ = 90;
+ outDeltaZ = -90;
+ outAngleZ = 0;
+ }
+
+ inA = cc.sequence(
+ cc.delayTime(this._duration / 2), cc.show(),
+ cc.orbitCamera(this._duration / 2, 1, 0, inAngleZ, inDeltaZ, 90, 0),
+ cc.callFunc(this.finish, this)
+ );
+ outA = cc.sequence(
+ cc.orbitCamera(this._duration / 2, 1, 0, outAngleZ, outDeltaZ, 90, 0),
+ cc.hide(), cc.delayTime(this._duration / 2)
+ );
+
+ this._inScene.runAction(inA);
+ this._outScene.runAction(outA);
+ }
+});
+
+/**
+ * Flips the screen vertically.
+ * The front face is the outgoing scene and the back face is the incoming scene.
+ * @deprecated since v3.0,please use new cc.TransitionFlipY(t, scene,o) instead.
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o
+ * @return {cc.TransitionFlipY}
+ */
+cc.TransitionFlipY.create = function (t, scene, o) {
+ return new cc.TransitionFlipY(t, scene, o);
+};
+
+/**
+ * Flips the screen half horizontally and half vertically.
+ * The front face is the outgoing scene and the back face is the incoming scene.
+ * @class
+ * @extends cc.TransitionSceneOriented
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o
+ * @example
+ * var trans = cc.TransitionFlipAngular(time,scene,o);
+ */
+cc.TransitionFlipAngular = cc.TransitionSceneOriented.extend(/** @lends cc.TransitionFlipAngular# */{
+ /**
+ * Constructor of TransitionFlipAngular
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o
+ */
+ ctor:function (t, scene, o) {
+ cc.TransitionSceneOriented.prototype.ctor.call(this);
+ if(o == null)
+ o = cc.TRANSITION_ORIENTATION_RIGHT_OVER;
+ scene && this.initWithDuration(t, scene, o);
+ },
+ /**
+ * custom on enter
+ */
+ onEnter:function () {
+ cc.TransitionScene.prototype.onEnter.call(this);
+
+ var inA, outA;
+ this._inScene.visible = false;
+
+ var inDeltaZ, inAngleZ, outDeltaZ, outAngleZ;
+
+ if (this._orientation === cc.TRANSITION_ORIENTATION_RIGHT_OVER) {
+ inDeltaZ = 90;
+ inAngleZ = 270;
+ outDeltaZ = 90;
+ outAngleZ = 0;
+ } else {
+ inDeltaZ = -90;
+ inAngleZ = 90;
+ outDeltaZ = -90;
+ outAngleZ = 0;
+ }
+
+ inA = cc.sequence(
+ cc.delayTime(this._duration / 2), cc.show(),
+ cc.orbitCamera(this._duration / 2, 1, 0, inAngleZ, inDeltaZ, -45, 0),
+ cc.callFunc(this.finish, this)
+ );
+ outA = cc.sequence(
+ cc.orbitCamera(this._duration / 2, 1, 0, outAngleZ, outDeltaZ, 45, 0),
+ cc.hide(), cc.delayTime(this._duration / 2)
+ );
+
+ this._inScene.runAction(inA);
+ this._outScene.runAction(outA);
+ }
+});
+
+/**
+ * Flips the screen half horizontally and half vertically.
+ * The front face is the outgoing scene and the back face is the incoming scene.
+ * @deprecated since v3.0,please use new new cc.TransitionFlipAngular(t, scene, o) instead
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o
+ * @return {cc.TransitionFlipAngular}
+ */
+cc.TransitionFlipAngular.create = function (t, scene, o) {
+ return new cc.TransitionFlipAngular(t, scene, o);
+};
+
+/**
+ * Flips the screen horizontally doing a zoom out/in
+ * The front face is the outgoing scene and the back face is the incoming scene.
+ * @class
+ * @extends cc.TransitionSceneOriented
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o
+ * @example
+ * var trans = new cc.TransitionZoomFlipX(time,scene,o);
+ */
+cc.TransitionZoomFlipX = cc.TransitionSceneOriented.extend(/** @lends cc.TransitionZoomFlipX# */{
+
+ /**
+ * Constructor of TransitionZoomFlipX
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o
+ */
+ ctor:function (t, scene, o) {
+ cc.TransitionSceneOriented.prototype.ctor.call(this);
+ if(o == null)
+ o = cc.TRANSITION_ORIENTATION_RIGHT_OVER;
+ scene && this.initWithDuration(t, scene, o);
+ },
+ /**
+ * custom on enter
+ */
+ onEnter:function () {
+ cc.TransitionScene.prototype.onEnter.call(this);
+
+ var inA, outA;
+ this._inScene.visible = false;
+
+ var inDeltaZ, inAngleZ, outDeltaZ, outAngleZ;
+
+ if (this._orientation === cc.TRANSITION_ORIENTATION_RIGHT_OVER) {
+ inDeltaZ = 90;
+ inAngleZ = 270;
+ outDeltaZ = 90;
+ outAngleZ = 0;
+ } else {
+ inDeltaZ = -90;
+ inAngleZ = 90;
+ outDeltaZ = -90;
+ outAngleZ = 0;
+ }
+
+ inA = cc.sequence(
+ cc.delayTime(this._duration / 2),
+ cc.spawn(
+ cc.orbitCamera(this._duration / 2, 1, 0, inAngleZ, inDeltaZ, 0, 0),
+ cc.scaleTo(this._duration / 2, 1), cc.show()),
+ cc.callFunc(this.finish, this)
+ );
+ outA = cc.sequence(
+ cc.spawn(
+ cc.orbitCamera(this._duration / 2, 1, 0, outAngleZ, outDeltaZ, 0, 0),
+ cc.scaleTo(this._duration / 2, 0.5)),
+ cc.hide(),
+ cc.delayTime(this._duration / 2)
+ );
+
+ this._inScene.scale = 0.5;
+ this._inScene.runAction(inA);
+ this._outScene.runAction(outA);
+ }
+});
+
+/**
+ * Flips the screen horizontally doing a zoom out/in
+ * The front face is the outgoing scene and the back face is the incoming scene.
+ * @deprecated since v3.0,please use new new cc.TransitionZoomFlipX(t, scene, o) instead
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o
+ * @return {cc.TransitionZoomFlipX}
+ */
+cc.TransitionZoomFlipX.create = function (t, scene, o) {
+ return new cc.TransitionZoomFlipX(t, scene, o);
+};
+
+/**
+ * Flips the screen vertically doing a little zooming out/in
+ * The front face is the outgoing scene and the back face is the incoming scene.
+ * @class
+ * @extends cc.TransitionSceneOriented
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o
+ * @example
+ * var trans = new cc.TransitionZoomFlipY(t,scene,o);
+ */
+cc.TransitionZoomFlipY = cc.TransitionSceneOriented.extend(/** @lends cc.TransitionZoomFlipY# */{
+
+ /**
+ * Constructor of TransitionZoomFlipY
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o
+ */
+ ctor:function (t, scene, o) {
+ cc.TransitionSceneOriented.prototype.ctor.call(this);
+ if(o == null)
+ o = cc.TRANSITION_ORIENTATION_UP_OVER;
+ scene && this.initWithDuration(t, scene, o);
+ },
+ /**
+ * custom on enter
+ */
+ onEnter:function () {
+ cc.TransitionScene.prototype.onEnter.call(this);
+
+ var inA, outA;
+ this._inScene.visible = false;
+
+ var inDeltaZ, inAngleZ, outDeltaZ, outAngleZ;
+
+ if (this._orientation === cc.TRANSITION_ORIENTATION_UP_OVER) {
+ inDeltaZ = 90;
+ inAngleZ = 270;
+ outDeltaZ = 90;
+ outAngleZ = 0;
+ } else {
+ inDeltaZ = -90;
+ inAngleZ = 90;
+ outDeltaZ = -90;
+ outAngleZ = 0;
+ }
+
+ inA = cc.sequence(
+ cc.delayTime(this._duration / 2),
+ cc.spawn(
+ cc.orbitCamera(this._duration / 2, 1, 0, inAngleZ, inDeltaZ, 90, 0),
+ cc.scaleTo(this._duration / 2, 1), cc.show()),
+ cc.callFunc(this.finish, this));
+
+ outA = cc.sequence(
+ cc.spawn(
+ cc.orbitCamera(this._duration / 2, 1, 0, outAngleZ, outDeltaZ, 90, 0),
+ cc.scaleTo(this._duration / 2, 0.5)),
+ cc.hide(), cc.delayTime(this._duration / 2));
+
+ this._inScene.scale = 0.5;
+ this._inScene.runAction(inA);
+ this._outScene.runAction(outA);
+ }
+});
+
+/**
+ * Flips the screen vertically doing a little zooming out/in
+ * The front face is the outgoing scene and the back face is the incoming scene.
+ * @deprecated since v3.0,please use new new cc.TransitionZoomFlipY(t, scene, o) instead
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o
+ * @return {cc.TransitionZoomFlipY}
+ */
+cc.TransitionZoomFlipY.create = function (t, scene, o) {
+ return new cc.TransitionZoomFlipY(t, scene, o);
+};
+
+/**
+ * Flips the screen half horizontally and half vertically doing a little zooming out/in.
+ * The front face is the outgoing scene and the back face is the incoming scene.
+ * @class
+ * @extends cc.TransitionSceneOriented
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o
+ * @example
+ * var trans = new cc.TransitionZoomFlipAngular(time,scene,o);
+ */
+cc.TransitionZoomFlipAngular = cc.TransitionSceneOriented.extend(/** @lends cc.TransitionZoomFlipAngular# */{
+
+ /**
+ * Constructor of TransitionZoomFlipAngular
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o
+ */
+ ctor:function (t, scene, o) {
+ cc.TransitionSceneOriented.prototype.ctor.call(this);
+ if(o == null)
+ o = cc.TRANSITION_ORIENTATION_RIGHT_OVER;
+ scene && this.initWithDuration(t, scene, o);
+ },
+ /**
+ * custom on enter
+ */
+ onEnter:function () {
+ cc.TransitionScene.prototype.onEnter.call(this);
+
+ var inA, outA;
+ this._inScene.visible = false;
+
+ var inDeltaZ, inAngleZ, outDeltaZ, outAngleZ;
+ if (this._orientation === cc.TRANSITION_ORIENTATION_RIGHT_OVER) {
+ inDeltaZ = 90;
+ inAngleZ = 270;
+ outDeltaZ = 90;
+ outAngleZ = 0;
+ } else {
+ inDeltaZ = -90;
+ inAngleZ = 90;
+ outDeltaZ = -90;
+ outAngleZ = 0;
+ }
+
+ inA = cc.sequence(
+ cc.delayTime(this._duration / 2),
+ cc.spawn(
+ cc.orbitCamera(this._duration / 2, 1, 0, inAngleZ, inDeltaZ, -45, 0),
+ cc.scaleTo(this._duration / 2, 1), cc.show()),
+ cc.show(),
+ cc.callFunc(this.finish, this));
+ outA = cc.sequence(
+ cc.spawn(
+ cc.orbitCamera(this._duration / 2, 1, 0, outAngleZ, outDeltaZ, 45, 0),
+ cc.scaleTo(this._duration / 2, 0.5)),
+ cc.hide(), cc.delayTime(this._duration / 2));
+
+ this._inScene.scale = 0.5;
+ this._inScene.runAction(inA);
+ this._outScene.runAction(outA);
+ }
+});
+
+/**
+ * Flips the screen half horizontally and half vertically doing a little zooming out/in.
+ * The front face is the outgoing scene and the back face is the incoming scene.
+ * @deprecated since v3.0,please use new new cc.TransitionZoomFlipAngular(t, scene, o) instead
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o
+ * @return {cc.TransitionZoomFlipAngular}
+ */
+cc.TransitionZoomFlipAngular.create = function (t, scene, o) {
+ return new cc.TransitionZoomFlipAngular(t, scene, o);
+};
+
+/**
+ * Fade out the outgoing scene and then fade in the incoming scene.
+ * @class
+ * @extends cc.TransitionScene
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o
+ * @example
+ * var trans = new cc.TransitionFade(time,scene,color)
+ */
+cc.TransitionFade = cc.TransitionScene.extend(/** @lends cc.TransitionFade# */{
+ _color:null,
+
+ /**
+ * Constructor of TransitionFade
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o
+ */
+ ctor:function (t, scene, color) {
+ cc.TransitionScene.prototype.ctor.call(this);
+ this._color = cc.color();
+ scene && this.initWithDuration(t, scene, color);
+ },
+
+ /**
+ * custom on enter
+ */
+ onEnter:function () {
+ cc.TransitionScene.prototype.onEnter.call(this);
+
+ var l = new cc.LayerColor(this._color);
+ this._inScene.visible = false;
+
+ this.addChild(l, 2, cc.SCENE_FADE);
+ var f = this.getChildByTag(cc.SCENE_FADE);
+
+ var a = cc.sequence(
+ cc.fadeIn(this._duration / 2),
+ cc.callFunc(this.hideOutShowIn, this),
+ cc.fadeOut(this._duration / 2),
+ cc.callFunc(this.finish, this)
+ );
+ f.runAction(a);
+ },
+
+ /**
+ * custom on exit
+ */
+ onExit:function () {
+ cc.TransitionScene.prototype.onExit.call(this);
+ this.removeChildByTag(cc.SCENE_FADE, false);
+ },
+
+ /**
+ * initializes the transition with a duration and with an RGB color
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @param {cc.Color} color
+ * @return {Boolean}
+ */
+ initWithDuration:function (t, scene, color) {
+ color = color || cc.Color.BLACK;
+ if (cc.TransitionScene.prototype.initWithDuration.call(this, t, scene)) {
+ this._color.r = color.r;
+ this._color.g = color.g;
+ this._color.b = color.b;
+ this._color.a = 0;
+ }
+ return true;
+ }
+});
+
+
+/**
+ * Fade out the outgoing scene and then fade in the incoming scene.
+ * @deprecated since v3.0,please use new cc.TransitionFade(time,scene,color) instead.
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @param {cc.Color} color
+ * @return {cc.TransitionFade}
+ */
+cc.TransitionFade.create = function (t, scene, color) {
+ return new cc.TransitionFade(t, scene, color);
+};
+
+/**
+ * Cross fades two scenes using the cc.RenderTexture object.
+ * @class
+ * @extends cc.TransitionScene
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @example
+ * var trans = new cc.TransitionCrossFade(time,scene);
+ */
+cc.TransitionCrossFade = cc.TransitionScene.extend(/** @lends cc.TransitionCrossFade# */{
+ /**
+ * Constructor of TransitionCrossFade
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ */
+ ctor:function (t, scene) {
+ cc.TransitionScene.prototype.ctor.call(this);
+ scene && this.initWithDuration(t, scene);
+ },
+ /**
+ * custom on enter
+ */
+ onEnter:function () {
+ cc.TransitionScene.prototype.onEnter.call(this);
+
+ // create a transparent color layer
+ // in which we are going to add our rendertextures
+ var color = cc.color(0, 0, 0, 0);
+ var winSize = cc.director.getWinSize();
+ var layer = new cc.LayerColor(color);
+
+ // create the first render texture for inScene
+ var inTexture = new cc.RenderTexture(winSize.width, winSize.height);
+
+ inTexture.sprite.anchorX = 0.5;
+ inTexture.sprite.anchorY = 0.5;
+ inTexture.attr({
+ x: winSize.width / 2,
+ y: winSize.height / 2,
+ anchorX: 0.5,
+ anchorY: 0.5
+ });
+
+ // render inScene to its texturebuffer
+ inTexture.begin();
+ this._inScene.visit();
+ inTexture.end();
+
+ // create the second render texture for outScene
+ var outTexture = new cc.RenderTexture(winSize.width, winSize.height);
+ outTexture.setPosition(winSize.width / 2, winSize.height / 2);
+ outTexture.sprite.anchorX = outTexture.anchorX = 0.5;
+ outTexture.sprite.anchorY = outTexture.anchorY = 0.5;
+
+ // render outScene to its texturebuffer
+ outTexture.begin();
+ this._outScene.visit();
+ outTexture.end();
+
+ inTexture.sprite.setBlendFunc(cc.ONE, cc.ONE); // inScene will lay on background and will not be used with alpha
+ outTexture.sprite.setBlendFunc(cc.SRC_ALPHA, cc.ONE_MINUS_SRC_ALPHA); // we are going to blend outScene via alpha
+
+ // add render textures to the layer
+ layer.addChild(inTexture);
+ layer.addChild(outTexture);
+
+ // initial opacity:
+ inTexture.sprite.opacity = 255;
+ outTexture.sprite.opacity = 255;
+
+ // create the blend action
+ var layerAction = cc.sequence(
+ cc.fadeTo(this._duration, 0), cc.callFunc(this.hideOutShowIn, this),
+ cc.callFunc(this.finish, this)
+ );
+
+ // run the blend action
+ outTexture.sprite.runAction(layerAction);
+
+ // add the layer (which contains our two rendertextures) to the scene
+ this.addChild(layer, 2, cc.SCENE_FADE);
+ },
+
+ /**
+ * custom on exit
+ */
+ onExit:function () {
+ this.removeChildByTag(cc.SCENE_FADE, false);
+ cc.TransitionScene.prototype.onExit.call(this);
+ },
+
+ /**
+ * stuff gets drawn here
+ */
+ visit:function () {
+ cc.Node.prototype.visit.call(this);
+ },
+
+ /**
+ * overide draw
+ */
+ draw:function () {
+ // override draw since both scenes (textures) are rendered in 1 scene
+ }
+});
+
+/**
+ * Cross fades two scenes using the cc.RenderTexture object.
+ * @deprecated since v3.0,please use new cc.TransitionCrossFade(t, scene) instead.
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @return {cc.TransitionCrossFade}
+ */
+cc.TransitionCrossFade.create = function (t, scene) {
+ return new cc.TransitionCrossFade(t, scene);
+};
+
+/**
+ * Turn off the tiles of the outgoing scene in random order
+ * @class
+ * @extends cc.TransitionScene
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @example
+ * var trans = new cc.TransitionTurnOffTiles(time,scene);
+ */
+cc.TransitionTurnOffTiles = cc.TransitionScene.extend(/** @lends cc.TransitionTurnOffTiles# */{
+ _gridProxy: null,
+ /**
+ * Constructor of TransitionCrossFade
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ */
+ ctor:function (t, scene) {
+ cc.TransitionScene.prototype.ctor.call(this);
+ this._gridProxy = new cc.NodeGrid();
+ scene && this.initWithDuration(t, scene);
+ },
+
+ _sceneOrder:function () {
+ this._isInSceneOnTop = false;
+ },
+
+ /**
+ * custom on enter
+ */
+ onEnter:function () {
+ cc.TransitionScene.prototype.onEnter.call(this);
+ this._gridProxy.setTarget(this._outScene);
+ this._gridProxy.onEnter();
+
+ var winSize = cc.director.getWinSize();
+ var aspect = winSize.width / winSize.height;
+ var x = 0 | (12 * aspect);
+ var y = 12;
+ var toff = cc.turnOffTiles(this._duration, cc.size(x, y));
+ var action = this.easeActionWithAction(toff);
+ this._gridProxy.runAction(cc.sequence(action, cc.callFunc(this.finish, this), cc.stopGrid()));
+ },
+
+ visit: function(){
+ this._inScene.visit();
+ this._gridProxy.visit();
+ },
+
+ /**
+ * @param {cc.ActionInterval} action
+ * @return {cc.ActionInterval}
+ */
+ easeActionWithAction:function (action) {
+ return action;
+ }
+});
+
+/**
+ * Turn off the tiles of the outgoing scene in random order
+ * @deprecated since v3.0,please use new cc.TransitionTurnOffTiles(t, scene) instead.
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @return {cc.TransitionTurnOffTiles}
+ */
+cc.TransitionTurnOffTiles.create = function (t, scene) {
+ return new cc.TransitionTurnOffTiles(t, scene);
+};
+
+/**
+ * The odd columns goes upwards while the even columns goes downwards.
+ * @class
+ * @extends cc.TransitionScene
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @example
+ * var trans = new cc.TransitionSplitCols(time,scene);
+ */
+cc.TransitionSplitCols = cc.TransitionScene.extend(/** @lends cc.TransitionSplitCols# */{
+ _gridProxy: null,
+
+ _switchTargetToInscene: function(){
+ this._gridProxy.setTarget(this._inScene);
+ },
+
+ /**
+ * Constructor of TransitionSplitCols
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ */
+ ctor:function (t, scene) {
+ cc.TransitionScene.prototype.ctor.call(this);
+ this._gridProxy = new cc.NodeGrid();
+ scene && this.initWithDuration(t, scene);
+ },
+ /**
+ * custom on enter
+ */
+ onEnter:function () {
+ cc.TransitionScene.prototype.onEnter.call(this);
+ //this._inScene.visible = false;
+ this._gridProxy.setTarget(this._outScene);
+ this._gridProxy.onEnter();
+
+ var split = this.action();
+ var seq = cc.sequence(
+ split, cc.callFunc(this._switchTargetToInscene, this), split.reverse());
+
+ this._gridProxy.runAction(
+ cc.sequence(this.easeActionWithAction(seq), cc.callFunc(this.finish, this), cc.stopGrid())
+ );
+ },
+
+ onExit: function(){
+ this._gridProxy.setTarget(null);
+ this._gridProxy.onExit();
+ cc.TransitionScene.prototype.onExit.call(this);
+ },
+
+ visit: function(){
+ this._gridProxy.visit();
+ },
+
+ /**
+ * @param {cc.ActionInterval} action
+ * @return {cc.EaseInOut}
+ */
+ easeActionWithAction:function (action) {
+ return new cc.EaseInOut(action, 3.0);
+ },
+
+ /**
+ * @return {*}
+ */
+ action:function () {
+ return cc.splitCols(this._duration / 2.0, 3);
+ }
+});
+
+/**
+ * The odd columns goes upwards while the even columns goes downwards.
+ * @deprecated since v3.0,please use new cc.TransitionSplitCols(t, scene) instead.
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @return {cc.TransitionSplitCols}
+ */
+cc.TransitionSplitCols.create = function (t, scene) {
+ return new cc.TransitionSplitCols(t, scene);
+};
+
+/**
+ * The odd rows goes to the left while the even rows goes to the right.
+ * @class
+ * @extends cc.TransitionSplitCols
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @example
+ * var trans = new cc.TransitionSplitRows(time,scene);
+ */
+cc.TransitionSplitRows = cc.TransitionSplitCols.extend(/** @lends cc.TransitionSplitRows# */{
+
+ /**
+ * Constructor of TransitionSplitRows
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ */
+ ctor:function (t, scene) {
+ cc.TransitionSplitCols.prototype.ctor.call(this);
+ scene && this.initWithDuration(t, scene);
+ },
+ /**
+ * @return {*}
+ */
+ action:function () {
+ return cc.splitRows(this._duration / 2.0, 3);
+ }
+});
+
+/**
+ * The odd rows goes to the left while the even rows goes to the right.
+ * @deprecated since v3.0,please use new cc.TransitionSplitRows(t, scene) instead.
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @return {cc.TransitionSplitRows}
+ */
+cc.TransitionSplitRows.create = function (t, scene) {
+ return new cc.TransitionSplitRows(t, scene);
+};
+
+/**
+ * Fade the tiles of the outgoing scene from the left-bottom corner the to top-right corner.
+ * @class
+ * @extends cc.TransitionScene
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @example
+ * var trans = new cc.TransitionFadeTR(time,scene);
+ */
+cc.TransitionFadeTR = cc.TransitionScene.extend(/** @lends cc.TransitionFadeTR# */{
+ _gridProxy: null,
+ /**
+ * Constructor of TransitionFadeTR
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ */
+ ctor:function (t, scene) {
+ cc.TransitionScene.prototype.ctor.call(this);
+ this._gridProxy = new cc.NodeGrid();
+ scene && this.initWithDuration(t, scene);
+ },
+ _sceneOrder:function () {
+ this._isInSceneOnTop = false;
+ },
+
+ /**
+ * Custom on enter
+ */
+ onEnter:function () {
+ cc.TransitionScene.prototype.onEnter.call(this);
+
+ this._gridProxy.setTarget(this._outScene);
+ this._gridProxy.onEnter();
+
+ var winSize = cc.director.getWinSize();
+ var aspect = winSize.width / winSize.height;
+ var x = 0 | (12 * aspect);
+ var y = 12;
+
+ var action = this.actionWithSize(cc.size(x, y));
+ this._gridProxy.runAction(
+ cc.sequence(this.easeActionWithAction(action), cc.callFunc(this.finish, this), cc.stopGrid())
+ );
+ },
+
+ visit: function(){
+ this._inScene.visit();
+ this._gridProxy.visit();
+ },
+
+ /**
+ * @param {cc.ActionInterval} action
+ * @return {cc.ActionInterval}
+ */
+ easeActionWithAction:function (action) {
+ return action;
+ },
+
+ /**
+ * @param {cc.Size} size
+ * @return {*}
+ */
+ actionWithSize:function (size) {
+ return cc.fadeOutTRTiles(this._duration, size);
+ }
+});
+
+/**
+ * Fade the tiles of the outgoing scene from the left-bottom corner the to top-right corner.
+ * @deprecated since v3.0 please use new cc.TransitionFadeTR(t, scene) instead.
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @return {cc.TransitionFadeTR}
+ */
+cc.TransitionFadeTR.create = function (t, scene) {
+ return new cc.TransitionFadeTR(t, scene);
+};
+
+/**
+ * Fade the tiles of the outgoing scene from the top-right corner to the bottom-left corner.
+ * @class
+ * @extends cc.TransitionFadeTR
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @example
+ * var trans = new cc.TransitionFadeBL(time,scene)
+ */
+cc.TransitionFadeBL = cc.TransitionFadeTR.extend(/** @lends cc.TransitionFadeBL# */{
+ /**
+ * Constructor of TransitionFadeBL
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ */
+ ctor:function (t, scene) {
+ cc.TransitionFadeTR.prototype.ctor.call(this);
+ scene && this.initWithDuration(t, scene);
+ },
+
+ /**
+ * @param {cc.Size} size
+ * @return {*}
+ */
+ actionWithSize:function (size) {
+ return cc.fadeOutBLTiles(this._duration, size);
+ }
+});
+
+/**
+ * Fade the tiles of the outgoing scene from the top-right corner to the bottom-left corner.
+ * @deprecated since v3.0,please use new cc.TransitionFadeBL(t, scene);
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @return {cc.TransitionFadeBL}
+ */
+cc.TransitionFadeBL.create = function (t, scene) {
+ return new cc.TransitionFadeBL(t, scene);
+};
+
+/**
+ * Fade the tiles of the outgoing scene from the top-right corner to the bottom-left corner.
+ * @class
+ * @extends cc.TransitionFadeTR
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @example
+ * var trans = new cc.TransitionFadeUp(time,scene);
+ */
+cc.TransitionFadeUp = cc.TransitionFadeTR.extend(/** @lends cc.TransitionFadeUp# */{
+
+ /**
+ * Constructor of TransitionFadeUp
+ * @function
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ */
+ ctor:function (t, scene) {
+ cc.TransitionFadeTR.prototype.ctor.call(this);
+ scene && this.initWithDuration(t, scene);
+ },
+
+ /**
+ * @param {cc.Size} size
+ * @return {cc.FadeOutUpTiles}
+ */
+ actionWithSize:function (size) {
+ return new cc.FadeOutUpTiles(this._duration, size);
+ }
+});
+
+/**
+ * Fade the tiles of the outgoing scene from the top-right corner to the bottom-left corner.
+ * @deprecated since v3.0,please use new cc.TransitionFadeUp(t, scene) instead.
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @return {cc.TransitionFadeUp}
+ */
+cc.TransitionFadeUp.create = function (t, scene) {
+ return new cc.TransitionFadeUp(t, scene);
+};
+
+/**
+ * Fade the tiles of the outgoing scene from the top to the bottom.
+ * @class
+ * @extends cc.TransitionFadeTR
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @example
+ * var trans = new cc.TransitionFadeDown(time,scene);
+ */
+cc.TransitionFadeDown = cc.TransitionFadeTR.extend(/** @lends cc.TransitionFadeDown# */{
+
+ /**
+ * Constructor of TransitionFadeDown
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ */
+ ctor:function (t, scene) {
+ cc.TransitionFadeTR.prototype.ctor.call(this);
+ scene && this.initWithDuration(t, scene);
+ },
+
+ /**
+ * @param {cc.Size} size
+ * @return {*}
+ */
+ actionWithSize:function (size) {
+ return cc.fadeOutDownTiles( this._duration, size);
+ }
+});
+
+/**
+ * Fade the tiles of the outgoing scene from the top to the bottom.
+ * @deprecated since v3.0,please use new cc.TransitionFadeDown(t, scene) instead.
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @return {cc.TransitionFadeDown}
+ */
+cc.TransitionFadeDown.create = function (t, scene) {
+ return new cc.TransitionFadeDown(t, scene);
+};
diff --git a/cocos2d/transitions/CCTransitionPageTurn.js b/cocos2d/transitions/CCTransitionPageTurn.js
new file mode 100644
index 0000000000..6b71fd848b
--- /dev/null
+++ b/cocos2d/transitions/CCTransitionPageTurn.js
@@ -0,0 +1,152 @@
+/****************************************************************************
+ 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 transition which peels back the bottom right hand corner of a scene
+ * to transition to the scene beneath it simulating a page turn.
+ *
+ * This uses a 3DAction so it's strongly recommended that depth buffering
+ * is turned on in cc.director using:
+ *
+ * cc.director.setDepthBufferFormat(kDepthBuffer16);
+ * @class
+ * @extends cc.TransitionScene
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @param {Boolean} backwards
+ * @example
+ * var trans = new cc.TransitionPageTurn(t, scene, backwards);
+ */
+cc.TransitionPageTurn = cc.TransitionScene.extend(/** @lends cc.TransitionPageTurn# */{
+
+ /**
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @param {Boolean} backwards
+ */
+ ctor:function (t, scene, backwards) {
+ cc.TransitionScene.prototype.ctor.call(this);
+ this._gridProxy = new cc.NodeGrid();
+ this.initWithDuration(t, scene, backwards);
+ },
+
+ /**
+ * @type Boolean
+ */
+ _back:true,
+ _gridProxy: null,
+ _className:"TransitionPageTurn",
+
+ /**
+ * Creates a base transition with duration and incoming scene.
+ * If back is true then the effect is reversed to appear as if the incoming
+ * scene is being turned from left over the outgoing scene.
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @param {Boolean} backwards
+ * @return {Boolean}
+ */
+ initWithDuration:function (t, scene, backwards) {
+ // XXX: needed before [super init]
+ this._back = backwards;
+
+ if (cc.TransitionScene.prototype.initWithDuration.call(this, t, scene)) {
+ // do something
+ }
+ return true;
+ },
+
+ /**
+ * @param {cc.Size} vector
+ * @return {cc.ReverseTime|cc.TransitionScene}
+ */
+ actionWithSize:function (vector) {
+ if (this._back)
+ return cc.reverseTime(cc.pageTurn3D(this._duration, vector)); // Get hold of the PageTurn3DAction
+ else
+ return cc.pageTurn3D(this._duration, vector); // Get hold of the PageTurn3DAction
+ },
+
+ /**
+ * custom on enter
+ */
+ onEnter:function () {
+ cc.TransitionScene.prototype.onEnter.call(this);
+ var winSize = cc.director.getWinSize();
+ var x, y;
+ if (winSize.width > winSize.height) {
+ x = 16;
+ y = 12;
+ } else {
+ x = 12;
+ y = 16;
+ }
+
+ var action = this.actionWithSize(cc.size(x, y)), gridProxy = this._gridProxy;
+
+ if (!this._back) {
+ gridProxy.setTarget(this._outScene);
+ gridProxy.onEnter();
+ gridProxy.runAction( cc.sequence(action,cc.callFunc(this.finish, this),cc.stopGrid()));
+ } else {
+ gridProxy.setTarget(this._inScene);
+ gridProxy.onEnter();
+ // to prevent initial flicker
+ this._inScene.visible = false;
+ gridProxy.runAction(
+ cc.sequence(action, cc.callFunc(this.finish, this), cc.stopGrid())
+ );
+ this._inScene.runAction(cc.show());
+ }
+ },
+
+ visit: function(){
+ //cc.TransitionScene.prototype.visit.call(this);
+ if(this._back)
+ this._outScene.visit();
+ else
+ this._inScene.visit();
+ this._gridProxy.visit();
+ },
+
+ _sceneOrder:function () {
+ this._isInSceneOnTop = this._back;
+ }
+});
+
+/**
+ * Creates a base transition with duration and incoming scene.
+ * If back is true then the effect is reversed to appear as if the incoming
+ * scene is being turned from left over the outgoing scene.
+ * @deprecated since v3.0,please use new cc.TransitionPageTurn(t, scene, backwards) instead.
+ * @param {Number} t time in seconds
+ * @param {cc.Scene} scene
+ * @param {Boolean} backwards
+ * @return {cc.TransitionPageTurn}
+ */
+cc.TransitionPageTurn.create = function (t, scene, backwards) {
+ return new cc.TransitionPageTurn(t, scene, backwards);
+};
diff --git a/cocos2d/transitions/CCTransitionProgress.js b/cocos2d/transitions/CCTransitionProgress.js
new file mode 100644
index 0000000000..4d4a077516
--- /dev/null
+++ b/cocos2d/transitions/CCTransitionProgress.js
@@ -0,0 +1,458 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+/**
+ * tag for scene redial
+ * @constant
+ * @type Number
+ */
+cc.SCENE_RADIAL = 0xc001;
+
+/**
+ * cc.TransitionProgress transition.
+ * @class
+ * @extends cc.TransitionScene
+ * @param {Number} t time
+ * @param {cc.Scene} scene
+ * @example
+ * var trans = new cc.TransitionProgress(time,scene);
+ */
+cc.TransitionProgress = cc.TransitionScene.extend(/** @lends cc.TransitionProgress# */{
+ _to:0,
+ _from:0,
+ _sceneToBeModified:null,
+ _className:"TransitionProgress",
+
+ /**
+ * @param {Number} t time
+ * @param {cc.Scene} scene
+ */
+ ctor:function (t, scene) {
+ cc.TransitionScene.prototype.ctor.call(this);
+ scene && this.initWithDuration(t, scene);
+ },
+
+ _setAttrs: function(node, x, y) {
+ node.attr({
+ x: x,
+ y: y,
+ anchorX: 0.5,
+ anchorY: 0.5
+ });
+ },
+
+ /**
+ * @override
+ * custom on enter
+ */
+ onEnter:function () {
+ cc.TransitionScene.prototype.onEnter.call(this);
+ this._setupTransition();
+
+ // create a transparent color layer
+ // in which we are going to add our rendertextures
+ var winSize = cc.director.getWinSize();
+
+ // create the second render texture for outScene
+ var texture = new cc.RenderTexture(winSize.width, winSize.height);
+ texture.sprite.anchorX = 0.5;
+ texture.sprite.anchorY = 0.5;
+ this._setAttrs(texture, winSize.width / 2, winSize.height / 2);
+
+ // render outScene to its texturebuffer
+ texture.clear(0, 0, 0, 1);
+ texture.begin();
+ this._sceneToBeModified.visit();
+ texture.end();
+
+ // Since we've passed the outScene to the texture we don't need it.
+ if (this._sceneToBeModified === this._outScene)
+ this.hideOutShowIn();
+
+ // We need the texture in RenderTexture.
+ var pNode = this._progressTimerNodeWithRenderTexture(texture);
+
+ // create the blend action
+ var layerAction = cc.sequence(
+ cc.progressFromTo(this._duration, this._from, this._to),
+ cc.callFunc(this.finish, this));
+ // run the blend action
+ pNode.runAction(layerAction);
+
+ // add the layer (which contains our two rendertextures) to the scene
+ this.addChild(pNode, 2, cc.SCENE_RADIAL);
+ },
+
+ /**
+ * @override
+ * custom on exit
+ */
+ onExit:function () {
+ // remove our layer and release all containing objects
+ this.removeChildByTag(cc.SCENE_RADIAL, true);
+ cc.TransitionScene.prototype.onExit.call(this);
+ },
+
+ _setupTransition:function () {
+ this._sceneToBeModified = this._outScene;
+ this._from = 100;
+ this._to = 0;
+ },
+
+ _progressTimerNodeWithRenderTexture:function (texture) {
+ cc.log("cc.TransitionProgress._progressTimerNodeWithRenderTexture(): should be overridden in subclass");
+ return null;
+ },
+
+ _sceneOrder:function () {
+ this._isInSceneOnTop = false;
+ }
+});
+
+/**
+ * create a cc.TransitionProgress object
+ * @deprecated since v3.0,please use new cc.TransitionProgress(t, scene) instead.
+ * @function
+ * @param {Number} t time
+ * @param {cc.Scene} scene
+ * @return {cc.TransitionProgress}
+ */
+cc.TransitionProgress.create = function (t, scene) {
+ return new cc.TransitionProgress(t, scene);
+};
+
+/**
+ * cc.TransitionRadialCCW transition.
+ * A counter clock-wise radial transition to the next scene
+ * @class
+ * @extends cc.TransitionProgress
+ * @param {Number} t time
+ * @param {cc.Scene} scene
+ * @example
+ * var trans = new cc.TransitionProgressRadialCCW(t, scene);
+ */
+cc.TransitionProgressRadialCCW = cc.TransitionProgress.extend(/** @lends cc.TransitionProgressRadialCCW# */{
+
+ /**
+ * @param {Number} t time
+ * @param {cc.Scene} scene
+ */
+ ctor:function (t, scene) {
+ cc.TransitionProgress.prototype.ctor.call(this);
+ scene && this.initWithDuration(t, scene);
+ },
+
+ _progressTimerNodeWithRenderTexture:function (texture) {
+ var size = cc.director.getWinSize();
+
+ var pNode = new cc.ProgressTimer(texture.sprite);
+
+ // but it is flipped upside down so we flip the sprite
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ pNode.sprite.flippedY = true;
+ pNode.type = cc.ProgressTimer.Type.RADIAL;
+
+ // Return the radial type that we want to use
+ pNode.reverseDir = false;
+ pNode.percentage = 100;
+ this._setAttrs(pNode, size.width / 2, size.height / 2);
+
+ return pNode;
+ }
+});
+
+/**
+ * create a cc.TransitionProgressRadialCCW object
+ * @deprecated since v3.0,please use new cc.TransitionProgressRadialCCW(t, scene) instead.
+ * @param {Number} t time
+ * @param {cc.Scene} scene
+ * @return {cc.TransitionProgressRadialCCW}
+ * @example
+ * var trans = new cc.TransitionProgressRadialCCW(time,scene);
+ */
+cc.TransitionProgressRadialCCW.create = function (t, scene) {
+ return new cc.TransitionProgressRadialCCW(t, scene);
+};
+
+/**
+ * cc.TransitionRadialCW transition.
+ * A counter colock-wise radial transition to the next scene
+ * @class
+ * @extends cc.TransitionProgress
+ * @param {Number} t time
+ * @param {cc.Scene} scene
+ * @example
+ * var trans = new cc.TransitionProgressRadialCW(t, scene);
+ */
+cc.TransitionProgressRadialCW = cc.TransitionProgress.extend(/** @lends cc.TransitionProgressRadialCW# */{
+ /**
+ * @param {Number} t time
+ * @param {cc.Scene} scene
+ */
+ ctor:function (t, scene) {
+ cc.TransitionProgress.prototype.ctor.call(this);
+ scene && this.initWithDuration(t, scene);
+ },
+
+ _progressTimerNodeWithRenderTexture:function (texture) {
+ var size = cc.director.getWinSize();
+
+ var pNode = new cc.ProgressTimer(texture.sprite);
+
+ // but it is flipped upside down so we flip the sprite
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ pNode.sprite.flippedY = true;
+ pNode.type = cc.ProgressTimer.Type.RADIAL;
+
+ // Return the radial type that we want to use
+ pNode.reverseDir = true;
+ pNode.percentage = 100;
+ this._setAttrs(pNode, size.width / 2, size.height / 2);
+
+ return pNode;
+ }
+});
+
+/**
+ * create a cc.TransitionProgressRadialCW object
+ * @deprecated since v3.0,please use cc.TransitionProgressRadialCW(t, scene) instead.
+ * @param {Number} t time
+ * @param {cc.Scene} scene
+ * @return {cc.TransitionProgressRadialCW}
+ */
+cc.TransitionProgressRadialCW.create = function (t, scene) {
+ var tempScene = new cc.TransitionProgressRadialCW();
+ if ((tempScene !== null) && (tempScene.initWithDuration(t, scene))) {
+ return tempScene;
+ }
+ return new cc.TransitionProgressRadialCW(t, scene);
+};
+
+/**
+ * cc.TransitionProgressHorizontal transition.
+ * A colock-wise radial transition to the next scene
+ * @class
+ * @extends cc.TransitionProgress
+ * @param {Number} t time
+ * @param {cc.Scene} scene
+ * @example
+ * var trans = new cc.TransitionProgressHorizontal(t, scene);
+ */
+cc.TransitionProgressHorizontal = cc.TransitionProgress.extend(/** @lends cc.TransitionProgressHorizontal# */{
+ /**
+ * @param {Number} t time
+ * @param {cc.Scene} scene
+ */
+ ctor:function (t, scene) {
+ cc.TransitionProgress.prototype.ctor.call(this);
+ scene && this.initWithDuration(t, scene);
+ },
+
+ _progressTimerNodeWithRenderTexture:function (texture) {
+ var size = cc.director.getWinSize();
+
+ var pNode = new cc.ProgressTimer(texture.sprite);
+
+ // but it is flipped upside down so we flip the sprite
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ pNode.sprite.flippedY = true;
+ pNode.type = cc.ProgressTimer.Type.BAR;
+
+ pNode.midPoint = cc.p(1, 0);
+ pNode.barChangeRate = cc.p(1, 0);
+
+ pNode.percentage = 100;
+ this._setAttrs(pNode, size.width / 2, size.height / 2);
+
+ return pNode;
+ }
+});
+
+/**
+ * create a cc.TransitionProgressHorizontal object
+ * @deprecated since v3.0,please use new cc.TransitionProgressHorizontal(t, scene) instead.
+ * @param {Number} t time
+ * @param {cc.Scene} scene
+ * @return {cc.TransitionProgressHorizontal}
+ */
+cc.TransitionProgressHorizontal.create = function (t, scene) {
+ return new cc.TransitionProgressHorizontal(t, scene);
+};
+
+/**
+ * cc.TransitionProgressVertical transition.
+ * @class
+ * @extends cc.TransitionProgress
+ * @param {Number} t time
+ * @param {cc.Scene} scene
+ * @example
+ * var trans = new cc.TransitionProgressVertical(t, scene);
+ */
+cc.TransitionProgressVertical = cc.TransitionProgress.extend(/** @lends cc.TransitionProgressVertical# */{
+
+ /**
+ * @param {Number} t time
+ * @param {cc.Scene} scene
+ */
+ ctor:function (t, scene) {
+ cc.TransitionProgress.prototype.ctor.call(this);
+ scene && this.initWithDuration(t, scene);
+ },
+
+ _progressTimerNodeWithRenderTexture:function (texture) {
+ var size = cc.director.getWinSize();
+
+ var pNode = new cc.ProgressTimer(texture.sprite);
+
+ // but it is flipped upside down so we flip the sprite
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ pNode.sprite.flippedY = true;
+ pNode.type = cc.ProgressTimer.Type.BAR;
+
+ pNode.midPoint = cc.p(0, 0);
+ pNode.barChangeRate = cc.p(0, 1);
+
+ pNode.percentage = 100;
+ this._setAttrs(pNode, size.width / 2, size.height / 2);
+
+ return pNode;
+ }
+});
+
+/**
+ * create a cc.TransitionProgressVertical object
+ * @deprecated since v3.0,please use new cc.TransitionProgressVertical(t, scene) instead.
+ * @param {Number} t time
+ * @param {cc.Scene} scene
+ * @return {cc.TransitionProgressVertical}
+ */
+cc.TransitionProgressVertical.create = function (t, scene) {
+ return new cc.TransitionProgressVertical(t, scene);
+};
+
+/**
+ * cc.TransitionProgressInOut transition.
+ * @class
+ * @extends cc.TransitionProgress
+ */
+cc.TransitionProgressInOut = cc.TransitionProgress.extend(/** @lends cc.TransitionProgressInOut# */{
+
+ /**
+ * The constructor of cc.TransitionProgressInOut. override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
+ * @param {Number} t time
+ * @param {cc.Scene} scene
+ */
+ ctor:function (t, scene) {
+ cc.TransitionProgress.prototype.ctor.call(this);
+ scene && this.initWithDuration(t, scene);
+ },
+
+ _progressTimerNodeWithRenderTexture:function (texture) {
+ var size = cc.director.getWinSize();
+ var pNode = new cc.ProgressTimer(texture.sprite);
+
+ // but it is flipped upside down so we flip the sprite
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ pNode.sprite.flippedY = true;
+ pNode.type = cc.ProgressTimer.Type.BAR;
+
+ pNode.midPoint = cc.p(0.5, 0.5);
+ pNode.barChangeRate = cc.p(1, 1);
+
+ pNode.percentage = 0;
+ this._setAttrs(pNode, size.width / 2, size.height / 2);
+
+ return pNode;
+ },
+ _sceneOrder:function () {
+ this._isInSceneOnTop = false;
+ },
+ _setupTransition:function () {
+ this._sceneToBeModified = this._inScene;
+ this._from = 0;
+ this._to = 100;
+ }
+});
+
+/**
+ * create a cc.TransitionProgressInOut object
+ * @function
+ * @deprecated
+ * @param {Number} t time
+ * @param {cc.Scene} scene
+ * @return {cc.TransitionProgressInOut}
+ */
+cc.TransitionProgressInOut.create = function (t, scene) {
+ return new cc.TransitionProgressInOut(t, scene);
+};
+
+/**
+ * cc.TransitionProgressOutIn transition.
+ * @class
+ * @extends cc.TransitionProgress
+ */
+cc.TransitionProgressOutIn = cc.TransitionProgress.extend(/** @lends cc.TransitionProgressOutIn# */{
+
+ /**
+ * The constructor of cc.TransitionProgressOutIn. override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
+ * @param {Number} t time
+ * @param {cc.Scene} scene
+ */
+ ctor:function (t, scene) {
+ cc.TransitionProgress.prototype.ctor.call(this);
+ scene && this.initWithDuration(t, scene);
+ },
+
+ _progressTimerNodeWithRenderTexture:function (texture) {
+ var size = cc.director.getWinSize();
+ var pNode = new cc.ProgressTimer(texture.sprite);
+
+ // but it is flipped upside down so we flip the sprite
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ pNode.sprite.flippedY = true;
+ pNode.type = cc.ProgressTimer.Type.BAR;
+
+ pNode.midPoint = cc.p(0.5, 0.5);
+ pNode.barChangeRate = cc.p(1, 1);
+
+ pNode.percentage = 100;
+ this._setAttrs(pNode, size.width / 2, size.height / 2);
+
+ return pNode;
+ }
+});
+
+/**
+ * create a cc.TransitionProgressOutIn object
+ * @function
+ * @deprecated
+ * @param {Number} t time
+ * @param {cc.Scene} scene
+ * @return {cc.TransitionProgressOutIn}
+ */
+cc.TransitionProgressOutIn.create = function (t, scene) {
+ return new cc.TransitionProgressOutIn(t, scene);
+};
diff --git a/docs/cocos2d/core/CCActionManager/ActionManager.js b/docs/cocos2d/core/CCActionManager/ActionManager.js
new file mode 100644
index 0000000000..999d27bd1a
--- /dev/null
+++ b/docs/cocos2d/core/CCActionManager/ActionManager.js
@@ -0,0 +1,2 @@
+----
+var mng = new cc.ActionManager();
diff --git a/docs/cocos2d/core/CCScheduler/schedule.js b/docs/cocos2d/core/CCScheduler/schedule.js
new file mode 100644
index 0000000000..ccab42e5f1
--- /dev/null
+++ b/docs/cocos2d/core/CCScheduler/schedule.js
@@ -0,0 +1,3 @@
+-------------------
+//register a schedule to scheduler
+cc.director.getScheduler().schedule(callback, this, interval, !this._isRunning);
diff --git a/docs/cocos2d/core/CCScheduler/scheduleCallbackForTarget.js b/docs/cocos2d/core/CCScheduler/scheduleCallbackForTarget.js
new file mode 100644
index 0000000000..cb928db8ba
--- /dev/null
+++ b/docs/cocos2d/core/CCScheduler/scheduleCallbackForTarget.js
@@ -0,0 +1,3 @@
+-------------------
+//register a schedule to scheduler
+cc.director.getScheduler().scheduleCallbackForTarget(this, function, interval, repeat, delay, !this._isRunning );
diff --git a/docs/cocos2d/core/CCScheduler/scheduleUpdateForTarget.js b/docs/cocos2d/core/CCScheduler/scheduleUpdateForTarget.js
new file mode 100644
index 0000000000..3af3ee457c
--- /dev/null
+++ b/docs/cocos2d/core/CCScheduler/scheduleUpdateForTarget.js
@@ -0,0 +1,3 @@
+-------------------
+//register this object to scheduler
+cc.director.getScheduler().scheduleUpdateForTarget(this, priority, !this._isRunning );
diff --git a/docs/cocos2d/core/CCScheduler/unscheduleCallbackForTarget.js b/docs/cocos2d/core/CCScheduler/unscheduleCallbackForTarget.js
new file mode 100644
index 0000000000..af1c809c3a
--- /dev/null
+++ b/docs/cocos2d/core/CCScheduler/unscheduleCallbackForTarget.js
@@ -0,0 +1,3 @@
+-------------------
+//unschedule a callback of target
+cc.director.getScheduler().unscheduleCallbackForTarget(function, this);
diff --git a/docs/cocos2d/core/CCScheduler/unscheduleUpdateForTarget.js b/docs/cocos2d/core/CCScheduler/unscheduleUpdateForTarget.js
new file mode 100644
index 0000000000..25c769d006
--- /dev/null
+++ b/docs/cocos2d/core/CCScheduler/unscheduleUpdateForTarget.js
@@ -0,0 +1,3 @@
+-------------------
+//unschedules the "update" method.
+cc.director.getScheduler().unscheduleUpdateForTarget(this);
diff --git a/docs/cocos2d/core/components/CCSpriteRenerer/initWithSpriteFrameName.js b/docs/cocos2d/core/components/CCSpriteRenerer/initWithSpriteFrameName.js
new file mode 100644
index 0000000000..8681cb430c
--- /dev/null
+++ b/docs/cocos2d/core/components/CCSpriteRenerer/initWithSpriteFrameName.js
@@ -0,0 +1,3 @@
+---------
+var sprite = new cc.Sprite();
+sprite.initWithSpriteFrameName("grossini_dance_01.png");
diff --git a/docs/cocos2d/core/event-manager/CCEventListener/create.js b/docs/cocos2d/core/event-manager/CCEventListener/create.js
new file mode 100644
index 0000000000..534b300c52
--- /dev/null
+++ b/docs/cocos2d/core/event-manager/CCEventListener/create.js
@@ -0,0 +1,10 @@
+--------
+cc.EventListener.create({
+
+ event: cc.EventListener.TOUCH_ONE_BY_ONE,
+ swallowTouches: true,
+ onTouchBegan: function (touch, event) {
+ //do something
+ return true;
+ }
+ });
diff --git a/docs/cocos2d/core/event/_getCapturingTargets.js b/docs/cocos2d/core/event/_getCapturingTargets.js
new file mode 100644
index 0000000000..96d545b0ed
--- /dev/null
+++ b/docs/cocos2d/core/event/_getCapturingTargets.js
@@ -0,0 +1,8 @@
+----------
+Subclasses can override this method to make event propagable
+```js
+for (var target = this._parent; target; target = target._parent) {
+ if (target._capturingListeners && target._capturingListeners.has(type)) {
+ array.push(target);
+ }
+}
diff --git a/docs/cocos2d/core/platform/CCCommon/KEY.js b/docs/cocos2d/core/platform/CCCommon/KEY.js
new file mode 100644
index 0000000000..22edc52e95
--- /dev/null
+++ b/docs/cocos2d/core/platform/CCCommon/KEY.js
@@ -0,0 +1,9 @@
+-----
+cc.eventManager.addListener({
+ event: cc.EventListener.KEYBOARD,
+ onKeyPressed: function(keyCode, event){
+ if (cc.KEY["a"] == keyCode) {
+ cc.log("A is pressed");
+ }
+ }
+}, this);
diff --git a/docs/cocos2d/core/platform/CCMacro/lerp.js b/docs/cocos2d/core/platform/CCMacro/lerp.js
new file mode 100644
index 0000000000..db39662af2
--- /dev/null
+++ b/docs/cocos2d/core/platform/CCMacro/lerp.js
@@ -0,0 +1,4 @@
+----
+lerp
+cc.lerp(2,10,0.5)//returns 6
+cc.lerp(2,10,0.2)//returns 3.6
diff --git a/docs/cocos2d/core/platform/attribute/attr.js b/docs/cocos2d/core/platform/attribute/attr.js
new file mode 100644
index 0000000000..68b04fa5ff
--- /dev/null
+++ b/docs/cocos2d/core/platform/attribute/attr.js
@@ -0,0 +1,10 @@
+-----
+var myClass = function () { this.value = 0.5 };
+cc.Class.attr(myClass, 'value'); // return undefined
+cc.Class.attr(myClass, 'value', {}).min = 0; // assign new attribute table
+ //associated with 'value', and set its min = 0
+cc.Class.attr(myClass, 'value', { // set values max and default
+ max: 1,
+ default: 0.5,
+});
+cc.Class.attr(myClass, 'value'); // return { default: 0.5, min: 0, max: 1 }
diff --git a/docs/cocos2d/core/platform/url/raw.js b/docs/cocos2d/core/platform/url/raw.js
new file mode 100644
index 0000000000..88ec9b4c24
--- /dev/null
+++ b/docs/cocos2d/core/platform/url/raw.js
@@ -0,0 +1,3 @@
+---
+var url = cc.url.raw("textures/myTexture.png");
+console.log(url); // "resources/raw/textures/myTexture.png"
diff --git a/docs/cocos2d/core/sprites/SpriteFrame.js b/docs/cocos2d/core/sprites/SpriteFrame.js
new file mode 100644
index 0000000000..ee5830b9d6
--- /dev/null
+++ b/docs/cocos2d/core/sprites/SpriteFrame.js
@@ -0,0 +1,9 @@
+----------------------------------------------------
+// 1. Create a cc.SpriteFrame with image path
+var frame1 = new cc.SpriteFrame("res/grossini_dance.png",cc.rect(0,0,90,128));
+var frame2 = new cc.SpriteFrame("res/grossini_dance.png",cc.rect(0,0,90,128),false,0,cc.size(90,128));
+
+// 2. Create a cc.SpriteFrame with a texture, rect, rotated, offset and originalSize in pixels.
+var texture = cc.textureCache.addImage("res/grossini_dance.png");
+var frame1 = new cc.SpriteFrame(texture, cc.rect(0,0,90,128));
+var frame2 = new cc.SpriteFrame(texture, cc.rect(0,0,90,128),false,0,cc.size(90,128));
diff --git a/docs/cocos2d/core/sprites/addSpriteFrames.js b/docs/cocos2d/core/sprites/addSpriteFrames.js
new file mode 100644
index 0000000000..44c45c4f46
--- /dev/null
+++ b/docs/cocos2d/core/sprites/addSpriteFrames.js
@@ -0,0 +1,4 @@
+----------------------------------------------------
+// add SpriteFrames to SpriteFrameCache With File
+cc.spriteFrameCache.addSpriteFrames(s_grossiniPlist);
+cc.spriteFrameCache.addSpriteFrames(s_grossiniJson);
diff --git a/docs/cocos2d/core/sprites/getSpriteFrame.js b/docs/cocos2d/core/sprites/getSpriteFrame.js
new file mode 100644
index 0000000000..0c37dd966e
--- /dev/null
+++ b/docs/cocos2d/core/sprites/getSpriteFrame.js
@@ -0,0 +1,3 @@
+----------------------------------------------------
+//get a SpriteFrame by name
+var frame = cc.spriteFrameCache.getSpriteFrame("grossini_dance_01.png");
diff --git a/docs/cocos2d/core/support/pAdd.js b/docs/cocos2d/core/support/pAdd.js
new file mode 100644
index 0000000000..a1f5e8d7a3
--- /dev/null
+++ b/docs/cocos2d/core/support/pAdd.js
@@ -0,0 +1,4 @@
+-----------------
+cc.pAdd( cc.p(1,1), cc.p(2,2) ); // preferred cocos2d way
+cc.pAdd( cc.p(1,1), cc.p(2,2) ); // also ok but more verbose
+cc.pAdd( cc.cpv(1,1), cc.cpv(2,2) ); // mixing chipmunk and cocos2d (avoid)
diff --git a/docs/cocos2d/core/support/pCompOp.js b/docs/cocos2d/core/support/pCompOp.js
new file mode 100644
index 0000000000..9facaccb9f
--- /dev/null
+++ b/docs/cocos2d/core/support/pCompOp.js
@@ -0,0 +1,3 @@
+--------------
+//For example: let's try to take the floor of x,y
+var p = cc.pCompOp(cc.p(10,10),Math.abs);
diff --git a/docs/cocos2d/core/textures/TextureAtlas.js b/docs/cocos2d/core/textures/TextureAtlas.js
new file mode 100644
index 0000000000..e0d4542b39
--- /dev/null
+++ b/docs/cocos2d/core/textures/TextureAtlas.js
@@ -0,0 +1,7 @@
+--------------------------
+1. //creates a TextureAtlas with filename
+var textureAtlas = new cc.TextureAtlas("res/hello.png", 3);
+
+2. //creates a TextureAtlas with texture
+var texture = cc.textureCache.addImage("hello.png");
+var textureAtlas = new cc.TextureAtlas(texture, 3);
diff --git a/docs/cocos2d/core/textures/addImage.js b/docs/cocos2d/core/textures/addImage.js
new file mode 100644
index 0000000000..cd3cc39a03
--- /dev/null
+++ b/docs/cocos2d/core/textures/addImage.js
@@ -0,0 +1,2 @@
+----
+cc.textureCache.addImage("hello.png");
diff --git a/docs/cocos2d/core/textures/getKeyByTexture.js b/docs/cocos2d/core/textures/getKeyByTexture.js
new file mode 100644
index 0000000000..6617822a86
--- /dev/null
+++ b/docs/cocos2d/core/textures/getKeyByTexture.js
@@ -0,0 +1,2 @@
+---------
+var key = cc.textureCache.getKeyByTexture(texture);
diff --git a/docs/cocos2d/core/textures/getTextureColors.js b/docs/cocos2d/core/textures/getTextureColors.js
new file mode 100644
index 0000000000..75cc132550
--- /dev/null
+++ b/docs/cocos2d/core/textures/getTextureColors.js
@@ -0,0 +1,2 @@
+---------------
+var cacheTextureForColor = cc.textureCache.getTextureColors(texture);
diff --git a/docs/cocos2d/core/textures/getTextureForKey.js b/docs/cocos2d/core/textures/getTextureForKey.js
new file mode 100644
index 0000000000..7ce13d75de
--- /dev/null
+++ b/docs/cocos2d/core/textures/getTextureForKey.js
@@ -0,0 +1,2 @@
+------------------
+var key = cc.textureCache.getTextureForKey("hello.png");
diff --git a/docs/cocos2d/core/textures/initWithFile.js b/docs/cocos2d/core/textures/initWithFile.js
new file mode 100644
index 0000000000..e7cfc635fa
--- /dev/null
+++ b/docs/cocos2d/core/textures/initWithFile.js
@@ -0,0 +1,3 @@
+--------------------------------------------------
+var textureAtlas = new cc.TextureAtlas();
+textureAtlas.initWithTexture("hello.png", 3);
diff --git a/docs/cocos2d/core/textures/initWithTexture.js b/docs/cocos2d/core/textures/initWithTexture.js
new file mode 100644
index 0000000000..e1ae8a7282
--- /dev/null
+++ b/docs/cocos2d/core/textures/initWithTexture.js
@@ -0,0 +1,4 @@
+---------------------------
+var texture = cc.textureCache.addImage("hello.png");
+var textureAtlas = new cc.TextureAtlas();
+textureAtlas.initWithTexture(texture, 3);
diff --git a/docs/cocos2d/core/textures/removeAllTextures.js b/docs/cocos2d/core/textures/removeAllTextures.js
new file mode 100644
index 0000000000..e3e8bcdbeb
--- /dev/null
+++ b/docs/cocos2d/core/textures/removeAllTextures.js
@@ -0,0 +1,2 @@
+--------
+cc.textureCache.removeAllTextures();
diff --git a/docs/cocos2d/core/textures/removeTexture.js b/docs/cocos2d/core/textures/removeTexture.js
new file mode 100644
index 0000000000..e7e4782d87
--- /dev/null
+++ b/docs/cocos2d/core/textures/removeTexture.js
@@ -0,0 +1,2 @@
+-----
+cc.textureCache.removeTexture(texture);
diff --git a/docs/cocos2d/core/textures/removeTextureForKey.js b/docs/cocos2d/core/textures/removeTextureForKey.js
new file mode 100644
index 0000000000..27308cb054
--- /dev/null
+++ b/docs/cocos2d/core/textures/removeTextureForKey.js
@@ -0,0 +1,2 @@
+------
+cc.textureCache.removeTexture("hello.png");
diff --git a/docs/cocos2d/core/textures/textureForKey.js b/docs/cocos2d/core/textures/textureForKey.js
new file mode 100644
index 0000000000..28175de106
--- /dev/null
+++ b/docs/cocos2d/core/textures/textureForKey.js
@@ -0,0 +1,2 @@
+------------------
+var key = cc.textureCache.textureForKey("hello.png");
diff --git a/docs/cocos2d/core/utils/CCPath/basename.js b/docs/cocos2d/core/utils/CCPath/basename.js
new file mode 100644
index 0000000000..31a3db9a87
--- /dev/null
+++ b/docs/cocos2d/core/utils/CCPath/basename.js
@@ -0,0 +1,6 @@
+---------------------------------
+cc.path.basename("a/b.png"); //-->"b.png"
+cc.path.basename("a/b.png?a=1&b=2"); //-->"b.png"
+cc.path.basename("a/b.png", ".png"); //-->"b"
+cc.path.basename("a/b.png?a=1&b=2", ".png"); //-->"b"
+cc.path.basename("a/b.png", ".txt"); //-->"b.png"
diff --git a/docs/cocos2d/core/utils/CCPath/changeBasename.js b/docs/cocos2d/core/utils/CCPath/changeBasename.js
new file mode 100644
index 0000000000..6188cd1ba4
--- /dev/null
+++ b/docs/cocos2d/core/utils/CCPath/changeBasename.js
@@ -0,0 +1,6 @@
+----------------------------------
+cc.path.changeBasename("a/b/c.plist", "b.plist"); //-->"a/b/b.plist"
+cc.path.changeBasename("a/b/c.plist?a=1&b=2", "b.plist"); //-->"a/b/b.plist?a=1&b=2"
+cc.path.changeBasename("a/b/c.plist", ".png"); //-->"a/b/c.png"
+cc.path.changeBasename("a/b/c.plist", "b"); //-->"a/b/b"
+cc.path.changeBasename("a/b/c.plist", "b", true); //-->"a/b/b.plist"
diff --git a/docs/cocos2d/core/utils/CCPath/changeExtname.js b/docs/cocos2d/core/utils/CCPath/changeExtname.js
new file mode 100644
index 0000000000..8ca43f3bb2
--- /dev/null
+++ b/docs/cocos2d/core/utils/CCPath/changeExtname.js
@@ -0,0 +1,3 @@
+---------------------------------
+cc.path.changeExtname("a/b.png", ".plist"); //-->"a/b.plist"
+cc.path.changeExtname("a/b.png?a=1&b=2", ".plist"); //-->"a/b.plist?a=1&b=2"
diff --git a/docs/cocos2d/core/utils/CCPath/dirname.js b/docs/cocos2d/core/utils/CCPath/dirname.js
new file mode 100644
index 0000000000..3ed9445593
--- /dev/null
+++ b/docs/cocos2d/core/utils/CCPath/dirname.js
@@ -0,0 +1,9 @@
+---------------------------------
+* unix
+cc.path.driname("a/b/c.png"); //-->"a/b"
+cc.path.driname("a/b/c.png?a=1&b=2"); //-->"a/b"
+cc.path.dirname("a/b/"); //-->"a/b"
+cc.path.dirname("c.png"); //-->""
+* windows
+cc.path.driname("a\\b\\c.png"); //-->"a\b"
+cc.path.driname("a\\b\\c.png?a=1&b=2"); //-->"a\b"
diff --git a/docs/cocos2d/core/utils/CCPath/extname.js b/docs/cocos2d/core/utils/CCPath/extname.js
new file mode 100644
index 0000000000..d8718c8af1
--- /dev/null
+++ b/docs/cocos2d/core/utils/CCPath/extname.js
@@ -0,0 +1,5 @@
+---------------------------
+cc.path.extname("a/b.png"); //-->".png"
+cc.path.extname("a/b.png?a=1&b=2"); //-->".png"
+cc.path.extname("a/b"); //-->null
+cc.path.extname("a/b?a=1&b=2"); //-->null
diff --git a/docs/cocos2d/core/utils/CCPath/join.js b/docs/cocos2d/core/utils/CCPath/join.js
new file mode 100644
index 0000000000..efd2eb1936
--- /dev/null
+++ b/docs/cocos2d/core/utils/CCPath/join.js
@@ -0,0 +1,6 @@
+------------------------------
+cc.path.join("a", "b.png"); //-->"a/b.png"
+cc.path.join("a", "b", "c.png"); //-->"a/b/c.png"
+cc.path.join("a", "b"); //-->"a/b"
+cc.path.join("a", "b", "/"); //-->"a/b/"
+cc.path.join("a", "b/", "/"); //-->"a/b/"
diff --git a/docs/cocos2d/core/utils/node-wrapper/setPosition.js b/docs/cocos2d/core/utils/node-wrapper/setPosition.js
new file mode 100644
index 0000000000..c88584e473
--- /dev/null
+++ b/docs/cocos2d/core/utils/node-wrapper/setPosition.js
@@ -0,0 +1,3 @@
+---------------------------------
+var size = cc.winSize;
+node.setPosition(size.width/2, size.height/2);
diff --git a/docs/cocos2d/core/value-types/CCColor/color.js b/docs/cocos2d/core/value-types/CCColor/color.js
new file mode 100644
index 0000000000..86c4819aa4
--- /dev/null
+++ b/docs/cocos2d/core/value-types/CCColor/color.js
@@ -0,0 +1,7 @@
+-----------------------
+// 1. All channels seperately as parameters
+var color1 = cc.color(255, 255, 255, 255);
+// 2. Convert a hex string to a color
+var color2 = cc.color("#000000");
+// 3. An color object as parameter
+var color3 = cc.color({r: 255, g: 255, b: 255, a: 255});
diff --git a/docs/cocos2d/core/value-types/CCSize/size.js b/docs/cocos2d/core/value-types/CCSize/size.js
new file mode 100644
index 0000000000..d61e901452
--- /dev/null
+++ b/docs/cocos2d/core/value-types/CCSize/size.js
@@ -0,0 +1,5 @@
+-----
+var size1 = cc.size();
+var size2 = cc.size(100,100);
+var size3 = cc.size(size2);
+var size4 = cc.size({width: 100, height: 100});
diff --git a/docs/extensions/ccpool/putInPool.js b/docs/extensions/ccpool/putInPool.js
new file mode 100644
index 0000000000..c60bfe5893
--- /dev/null
+++ b/docs/extensions/ccpool/putInPool.js
@@ -0,0 +1,5 @@
+---------------------------------
+var sp = new cc.Sprite("a.png");
+this.addChild(sp);
+cc.pool.putInPool(sp);
+cc.pool.getFromPool(cc.Sprite, "a.png");
diff --git a/editor/dashboard/banner.jpg b/editor/dashboard/banner.jpg
new file mode 100644
index 0000000000..e4f251f5f8
Binary files /dev/null and b/editor/dashboard/banner.jpg differ
diff --git a/editor/dashboard/banner.png b/editor/dashboard/banner.png
new file mode 100644
index 0000000000..1523835f44
Binary files /dev/null and b/editor/dashboard/banner.png differ
diff --git a/editor/dashboard/logo.png b/editor/dashboard/logo.png
new file mode 100644
index 0000000000..2fb999edbe
Binary files /dev/null and b/editor/dashboard/logo.png differ
diff --git a/editor/template/new-scene.fire b/editor/template/new-scene.fire
new file mode 100644
index 0000000000..0a603c8942
--- /dev/null
+++ b/editor/template/new-scene.fire
@@ -0,0 +1,49 @@
+[
+ {
+ "__type__": "cc.SceneAsset",
+ "_name": "",
+ "_objFlags": 0,
+ "_rawFiles": null,
+ "scene": {
+ "__id__": 1
+ }
+ },
+ {
+ "__type__": "cc.Scene",
+ "_children": [
+ {
+ "__id__": 2
+ }
+ ]
+ },
+ {
+ "__type__": "cc.Node",
+ "_name": "Canvas",
+ "_parent": {
+ "__id__": 1
+ },
+ "_anchorPoint": {
+ "__type__": "cc.Vec2",
+ "x": 0,
+ "y": 0
+ },
+ "_position": {
+ "__type__": "cc.Vec2",
+ "x": 0,
+ "y": 0
+ },
+ "_components": [
+ {
+ "__id__": 3
+ }
+ ]
+ },
+ {
+ "__type__": "cc.Canvas",
+ "node": {
+ "__id__": 2
+ },
+ "_fitWidth": false,
+ "_fitHeight": false
+ }
+]
diff --git a/editor/template/new-script.coffee b/editor/template/new-script.coffee
new file mode 100644
index 0000000000..0baab69e43
--- /dev/null
+++ b/editor/template/new-script.coffee
@@ -0,0 +1,16 @@
+cc.Class {
+ extends: cc.Component
+
+ properties: {
+ # foo:
+ # default: null
+ # type: cc
+ # serializable: true # [optional], default is true
+ # visible: true # [optional], default is true
+ # displayName: 'Foo' # [optional], default is property name
+ # readonly: false # [optional], default is false
+ }
+
+ update: (dt) ->
+ # do your update here
+}
diff --git a/editor/template/new-script.js b/editor/template/new-script.js
new file mode 100644
index 0000000000..da1edcc6a0
--- /dev/null
+++ b/editor/template/new-script.js
@@ -0,0 +1,25 @@
+cc.Class({
+ extends: cc.Component,
+
+ properties: {
+ // foo: {
+ // default: null,
+ // url: cc.Texture2D, // optional, default is typeof default
+ // serializable: true, // optional, default is true
+ // visible: true, // optional, default is true
+ // displayName: 'Foo', // optional
+ // readonly: false, // optional, default is false
+ // },
+ // ...
+ },
+
+ // use this for initialization
+ onLoad: function () {
+
+ },
+
+ // called every frame
+ update: function (dt) {
+
+ },
+});
diff --git a/extends.js b/extends.js
new file mode 100644
index 0000000000..8024c9f8fa
--- /dev/null
+++ b/extends.js
@@ -0,0 +1,43 @@
+/****************************************************************************
+ Copyright (c) 2015 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.
+ ****************************************************************************/
+
+require('./cocos2d/core');
+require('./cocos2d/animation');
+
+require('./cocos2d/particle/CCParticleAsset');
+require('./cocos2d/particle/CCEParticleSystem');
+
+if (!(CC_EDITOR && Editor.isCoreLevel)) {
+ if (cc.sys.isNative) {
+ // TODO - add to jsb ?
+ function log () {
+ var text = cc.formatStr.apply(this, arguments);
+ console.log(text);
+ }
+ cc.log = log;
+ cc.error = log;
+ cc.warn = log;
+ cc.info = log;
+ }
+}
diff --git a/extensions/ccb-reader/CCBAnimationManager.js b/extensions/ccb-reader/CCBAnimationManager.js
new file mode 100644
index 0000000000..035dc0d760
--- /dev/null
+++ b/extensions/ccb-reader/CCBAnimationManager.js
@@ -0,0 +1,768 @@
+/****************************************************************************
+ 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.BuilderAnimationManagerDelegate = cc._Class.extend({
+ completedAnimationSequenceNamed:function (name) {}
+});
+
+cc.BuilderAnimationManager = cc._Class.extend({
+ _sequences:null,
+ _nodeSequences:null,
+ _baseValues:null,
+ _autoPlaySequenceId:0,
+
+ _rootNode:null,
+ _owner:null,
+ _rootContainerSize:null,
+
+ _delegate:null,
+ _runningSequence:null,
+
+ _documentOutletNames:null,
+ _documentOutletNodes:null,
+ _documentCallbackNames:null,
+ _documentCallbackNodes:null,
+ _documentCallbackControlEvents:null,
+ _documentControllerName:"",
+ _lastCompletedSequenceName:"",
+ _keyframeCallbacks:null,
+ _keyframeCallFuncs:null,
+
+ _animationCompleteCallbackFunc:null,
+ _target:null,
+ _jsControlled:false,
+
+ ctor:function () {
+ this._rootContainerSize = cc.size(0, 0);
+ this.init();
+ },
+
+ init:function () {
+ this._sequences = [];
+ this._nodeSequences = new cc._Dictionary();
+ this._baseValues = new cc._Dictionary();
+
+ this._documentOutletNames = [];
+ this._documentOutletNodes = [];
+ this._documentCallbackNames = [];
+ this._documentCallbackNodes = [];
+ this._documentCallbackControlEvents = [];
+
+ this._keyframeCallbacks = [];
+ this._keyframeCallFuncs = {};
+
+ return true;
+ },
+
+ getSequences:function () {
+ return this._sequences;
+ },
+
+ setSequences:function(seqs){
+ this._sequences = seqs;
+ },
+
+ getAutoPlaySequenceId:function () {
+ return this._autoPlaySequenceId;
+ },
+ setAutoPlaySequenceId:function (autoPlaySequenceId) {
+ this._autoPlaySequenceId = autoPlaySequenceId;
+ },
+
+ getRootNode:function () {
+ return this._rootNode;
+ },
+ setRootNode:function (rootNode) {
+ this._rootNode = rootNode;
+ },
+
+ getOwner:function () {
+ return this._owner;
+ },
+ setOwner:function (owner) {
+ this._owner = owner;
+ },
+
+ addDocumentCallbackNode:function(node){
+ this._documentCallbackNodes.push(node);
+ },
+
+ addDocumentCallbackName:function(name){
+ this._documentCallbackNames.push(name);
+ },
+
+ addDocumentCallbackControlEvents:function(controlEvents){
+ this._documentCallbackControlEvents.push(controlEvents);
+ },
+
+ addDocumentOutletNode:function(node){
+ this._documentOutletNodes.push(node);
+ },
+
+ addDocumentOutletName:function(name){
+ this._documentOutletNames.push(name);
+ },
+
+ setDocumentControllerName:function(name){
+ this._documentControllerName = name;
+ },
+
+ getDocumentControllerName:function(){
+ return this._documentControllerName;
+ },
+
+ getDocumentCallbackNames:function(){
+ return this._documentCallbackNames;
+ },
+
+ getDocumentCallbackNodes:function(){
+ return this._documentCallbackNodes;
+ },
+
+ getDocumentCallbackControlEvents:function(){
+ return this._documentCallbackControlEvents;
+ },
+
+ getDocumentOutletNames:function(){
+ return this._documentOutletNames;
+ },
+
+ getDocumentOutletNodes:function(){
+ return this._documentOutletNodes;
+ },
+
+ getLastCompletedSequenceName:function(){
+ return this._lastCompletedSequenceName;
+ },
+
+ getKeyframeCallbacks:function(){
+ return this._keyframeCallbacks;
+ },
+
+ getRootContainerSize:function () {
+ return this._rootContainerSize;
+ },
+ setRootContainerSize:function (rootContainerSize) {
+ this._rootContainerSize = cc.size(rootContainerSize.width, rootContainerSize.height);
+ },
+
+ getDelegate:function () {
+ return this._delegate;
+ },
+ setDelegate:function (delegate) {
+ this._delegate = delegate;
+ },
+
+ getRunningSequenceName:function () {
+ if(this._runningSequence)
+ return this._runningSequence.getName();
+ return null;
+ },
+
+ getContainerSize:function (node) {
+ if (node)
+ return node.getContentSize();
+ else
+ return this._rootContainerSize;
+ },
+
+ addNode:function (node, seq) {
+ this._nodeSequences.setObject(seq, node);
+ },
+ setBaseValue:function (value, node, propName) {
+ var props = this._baseValues.objectForKey(node);
+ if (!props) {
+ props = new cc._Dictionary();
+ this._baseValues.setObject(props, node);
+ }
+ props.setObject(value, propName);
+ },
+
+ moveAnimationsFromNode:function(fromNode,toNode){
+ // Move base values
+ var locBaseValues = this._baseValues;
+ var baseValue = locBaseValues.objectForKey(fromNode);
+ if(baseValue !== null) {
+ locBaseValues.setObject(baseValue, toNode);
+ locBaseValues.removeObjectForKey(fromNode);
+ }
+
+ // Move seqs
+ var locNodeSequences = this._nodeSequences;
+ var seqs = locNodeSequences.objectForKey(fromNode);
+ if(seqs != null) {
+ locNodeSequences.setObject(seqs, toNode);
+ locNodeSequences.removeObjectForKey(fromNode);
+ }
+ },
+
+ getActionForCallbackChannel:function(channel) {
+ var lastKeyframeTime = 0;
+
+ var actions = [];
+ var keyframes = channel.getKeyframes();
+ var numKeyframes = keyframes.length;
+
+ for (var i = 0; i < numKeyframes; ++i) {
+ var keyframe = keyframes[i];
+ var timeSinceLastKeyframe = keyframe.getTime() - lastKeyframeTime;
+ lastKeyframeTime = keyframe.getTime();
+ if(timeSinceLastKeyframe > 0) {
+ actions.push(cc.delayTime(timeSinceLastKeyframe));
+ }
+
+ var keyVal = keyframe.getValue();
+ var selectorName = keyVal[0];
+ var selectorTarget = keyVal[1];
+
+ if(this._jsControlled) {
+ var callbackName = selectorTarget + ":" + selectorName; //add number to the stream
+ var callback = this._keyframeCallFuncs[callbackName];
+
+ if(callback != null)
+ actions.push(callback);
+ } else {
+ var target;
+ if(selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT)
+ target = this._rootNode;
+ else if (selectorTarget === CCB_TARGETTYPE_OWNER)
+ target = this._owner;
+
+ if(target != null) {
+ if(selectorName.length > 0) {
+ var selCallFunc = 0;
+
+ if(target.onResolveCCBCCCallFuncSelector != null)
+ selCallFunc = target.onResolveCCBCCCallFuncSelector(target, selectorName);
+ if(selCallFunc === 0)
+ cc.log("Skipping selector '" + selectorName + "' since no CCBSelectorResolver is present.");
+ else
+ actions.push(cc.callFunc(selCallFunc,target));
+ } else {
+ cc.log("Unexpected empty selector.");
+ }
+ }
+ }
+ }
+ if(actions.length < 1)
+ return null;
+
+ return cc.sequence(actions);
+ },
+ getActionForSoundChannel:function(channel) {
+ var lastKeyframeTime = 0;
+
+ var actions = [];
+ var keyframes = channel.getKeyframes();
+ var numKeyframes = keyframes.length;
+
+ for (var i = 0; i < numKeyframes; ++i) {
+ var keyframe = keyframes[i];
+ var timeSinceLastKeyframe = keyframe.getTime() - lastKeyframeTime;
+ lastKeyframeTime = keyframe.getTime();
+ if(timeSinceLastKeyframe > 0) {
+ actions.push(cc.delayTime(timeSinceLastKeyframe));
+ }
+
+ var keyVal = keyframe.getValue();
+ var soundFile = cc.BuilderReader.getResourcePath() + keyVal[0];
+ var pitch = parseFloat(keyVal[1]), pan = parseFloat(keyVal[2]), gain = parseFloat(keyVal[3]);
+ actions.push(cc.BuilderSoundEffect.create(soundFile, pitch, pan, gain));
+ }
+
+ if(actions.length < 1)
+ return null;
+
+ return cc.sequence(actions);
+ },
+
+ runAnimationsForSequenceNamed:function(name){
+ this.runAnimationsForSequenceIdTweenDuration(this._getSequenceId(name), 0);
+ },
+
+ runAnimationsForSequenceNamedTweenDuration:function(name, tweenDuration){
+ this.runAnimationsForSequenceIdTweenDuration(this._getSequenceId(name), tweenDuration);
+ },
+
+ runAnimationsForSequenceIdTweenDuration:function(nSeqId, tweenDuration){
+ if(nSeqId === -1)
+ throw new Error("cc.BuilderAnimationManager.runAnimationsForSequenceIdTweenDuration(): Sequence id should not be -1");
+ tweenDuration = tweenDuration || 0;
+
+ this._rootNode.stopAllActions();
+
+ var allKeys = this._nodeSequences.allKeys();
+ for(var i = 0,len = allKeys.length ; i< len;i++){
+ var node = allKeys[i];
+ node.stopAllActions();
+
+ var seqs = this._nodeSequences.objectForKey(node);
+ var seqNodeProps = seqs.objectForKey(nSeqId);
+ var j;
+ var seqNodePropNames = [];
+ if(seqNodeProps){
+ var propKeys = seqNodeProps.allKeys();
+ for(j = 0; j < propKeys.length; j++){
+ var propName = propKeys[j];
+ var seqProp = seqNodeProps.objectForKey(propName);
+ seqNodePropNames.push(propName);
+
+ this._setFirstFrame(node, seqProp,tweenDuration);
+ this._runAction(node,seqProp,tweenDuration);
+ }
+ }
+
+ var nodeBaseValues = this._baseValues.objectForKey(node);
+ if(nodeBaseValues){
+ var baseKeys = nodeBaseValues.allKeys();
+ for(j = 0; j < baseKeys.length;j++){
+ var selBaseKey = baseKeys[j];
+ if(seqNodePropNames.indexOf(selBaseKey) === -1){
+ var value = nodeBaseValues.objectForKey(selBaseKey);
+ if(value != null)
+ this._setAnimatedProperty(selBaseKey,node, value, tweenDuration);
+ }
+ }
+ }
+ }
+
+ // Make callback at end of sequence
+ var seq = this._getSequence(nSeqId);
+ var completeAction = cc.sequence(cc.delayTime(seq.getDuration() + tweenDuration),
+ cc.callFunc(this._sequenceCompleted,this));
+ this._rootNode.runAction(completeAction);
+
+ // Playback callbacks and sounds
+ var action;
+ if (seq.getCallbackChannel()) {
+ // Build sound actions for channel
+ action = this.getActionForCallbackChannel(seq.getCallbackChannel());
+ if (action) {
+ this._rootNode.runAction(action);
+ }
+ }
+
+ if (seq.getSoundChannel()) {
+ // Build sound actions for channel
+ action = this.getActionForSoundChannel(seq.getSoundChannel());
+ if (action) {
+ this._rootNode.runAction(action);
+ }
+ }
+ // Set the running scene
+ this._runningSequence = this._getSequence(nSeqId);
+ },
+
+ runAnimations:function (name, tweenDuration) {
+ tweenDuration = tweenDuration || 0;
+ var nSeqId;
+ if(cc.js.isString(name))
+ nSeqId = this._getSequenceId(name);
+ else
+ nSeqId = name;
+
+ this.runAnimationsForSequenceIdTweenDuration(nSeqId, tweenDuration);
+ },
+
+ setAnimationCompletedCallback:function(target,callbackFunc){
+ this._target = target;
+ this._animationCompleteCallbackFunc = callbackFunc;
+ },
+
+ setCompletedAnimationCallback:function(target,callbackFunc){
+ this.setAnimationCompletedCallback(target,callbackFunc);
+ },
+ setCallFunc:function(callFunc, callbackNamed) {
+ this._keyframeCallFuncs[callbackNamed] = callFunc;
+ },
+
+ debug:function () {
+ },
+
+ _getBaseValue:function (node, propName) {
+ var props = this._baseValues.objectForKey(node);
+ if (props)
+ return props.objectForKey(propName);
+ return null;
+ },
+
+ _getSequenceId:function (sequenceName) {
+ var element = null;
+ var locSequences = this._sequences;
+ for (var i = 0, len = locSequences.length; i < len; i++) {
+ element = locSequences[i];
+ if (element && element.getName() === sequenceName)
+ return element.getSequenceId();
+ }
+ return -1;
+ },
+
+ _getSequence:function (sequenceId) {
+ var element = null;
+ var locSequences = this._sequences;
+ for (var i = 0, len = locSequences.length; i < len; i++) {
+ element = locSequences[i];
+ if (element && element.getSequenceId() === sequenceId)
+ return element;
+ }
+ return null;
+ },
+
+ _getAction:function (keyframe0, keyframe1, propName, node) {
+ var duration = keyframe1.getTime() - (keyframe0 ? keyframe0.getTime() : 0);
+ var getArr,type,getValueArr, x, y;
+
+ if (propName === "rotation") {
+ return cc.BuilderRotateTo.create(duration, keyframe1.getValue());
+ } else if (propName === "rotationX") {
+ return cc.BuilderRotateXTo.create(duration, keyframe1.getValue());
+ } else if (propName === "rotationY") {
+ return cc.BuilderRotateYTo.create(duration, keyframe1.getValue());
+ } else if (propName === "opacity") {
+ return cc.fadeTo(duration, keyframe1.getValue());
+ } else if (propName === "color") {
+ var selColor = keyframe1.getValue().getColor();
+ return cc.tintTo(duration, selColor.r, selColor.g, selColor.b);
+ } else if (propName === "visible") {
+ var isVisible = keyframe1.getValue();
+ if (isVisible) {
+ return cc.sequence(cc.delayTime(duration), cc.show());
+ } else {
+ return cc.sequence(cc.delayTime(duration), cc.hide());
+ }
+ } else if (propName === "displayFrame") {
+ return cc.sequence(cc.delayTime(duration), cc.BuilderSetSpriteFrame.create(keyframe1.getValue()));
+ } else if(propName === "position"){
+ getArr = this._getBaseValue(node,propName);
+ type = getArr[2];
+
+ //get relative position
+ getValueArr = keyframe1.getValue();
+ x = getValueArr[0];
+ y = getValueArr[1];
+
+ var containerSize = this.getContainerSize(node.getParent());
+
+ var absPos = cc._getAbsolutePosition(x,y, type,containerSize,propName);
+
+ return cc.moveTo(duration,absPos);
+ } else if( propName === "scale"){
+ getArr = this._getBaseValue(node,propName);
+ type = getArr[2];
+
+ //get relative position
+ getValueArr = keyframe1.getValue();
+ x = getValueArr[0];
+ y = getValueArr[1];
+
+ if(type === CCB_SCALETYPE_MULTIPLY_RESOLUTION){
+ //TODO need to test
+ var resolutionScale = cc.BuilderReader.getResolutionScale();
+ x *= resolutionScale;
+ y *= resolutionScale;
+ }
+
+ return cc.scaleTo(duration,x,y);
+ } else if( propName === "skew") {
+ //get relative position
+ getValueArr = keyframe1.getValue();
+ x = getValueArr[0];
+ y = getValueArr[1];
+ return cc.skewTo(duration,x,y);
+ } else {
+ cc.log("BuilderReader: Failed to create animation for property: " + propName);
+ }
+ return null;
+ },
+
+ _setAnimatedProperty:function (propName, node, value, tweenDuration) {
+ if(tweenDuration > 0){
+ // Create a fake keyframe to generate the action from
+ var kf1 = new cc.BuilderKeyframe();
+ kf1.setValue(value);
+ kf1.setTime(tweenDuration);
+ kf1.setEasingType(CCB_KEYFRAME_EASING_LINEAR);
+
+ // Animate
+ var tweenAction = this._getAction(null, kf1, propName, node);
+ node.runAction(tweenAction);
+ } else {
+ // Just set the value
+ var getArr, nType, x,y;
+ if(propName === "position"){
+ getArr = this._getBaseValue(node,propName);
+ nType = getArr[2];
+
+ x = value[0];
+ y = value[1];
+ node.setPosition(cc._getAbsolutePosition(x,y,nType, this.getContainerSize(node.getParent()),propName));
+ }else if(propName === "scale"){
+ getArr = this._getBaseValue(node,propName);
+ nType = getArr[2];
+
+ x = value[0];
+ y = value[1];
+
+ cc.setRelativeScale(node,x,y,nType,propName);
+ } else if( propName === "skew") {
+ x = value[0];
+ y = value[1];
+ node.setSkewX(x);
+ node.setSkewY(y);
+ }else {
+ // [node setValue:value forKey:name];
+ // TODO only handle rotation, opacity, displayFrame, color
+ if(propName === "rotation"){
+ node.setRotation(value);
+ } else if(propName === "rotationX")
+ {
+ node.setRotationSkewX(value);
+ }else if(propName === "rotationY")
+ {
+ node.setRotationSkewY(value);
+ }else if(propName === "opacity"){
+ node.setOpacity(value);
+ } else if(propName === "displayFrame"){
+ node.setSpriteFrame(value);
+ } else if(propName === "color"){
+ var ccColor3B = value.getColor();
+ if(ccColor3B.r !== 255 || ccColor3B.g !== 255 || ccColor3B.b !== 255){
+ node.setColor(ccColor3B);
+ }
+ } else if( propName === "visible"){
+ value = value || false;
+ node.setVisible(value);
+ } else {
+ cc.log("unsupported property name is "+ propName);
+ }
+ }
+ }
+ },
+
+ _setFirstFrame:function (node, seqProp, tweenDuration) {
+ var keyframes = seqProp.getKeyframes();
+
+ if (keyframes.length === 0) {
+ // Use base value (no animation)
+ var baseValue = this._getBaseValue(node, seqProp.getName());
+ if(!baseValue)
+ cc.log("cc.BuilderAnimationManager._setFirstFrame(): No baseValue found for property");
+ this._setAnimatedProperty(seqProp.getName(), node, baseValue, tweenDuration);
+ } else {
+ // Use first keyframe
+ var keyframe = keyframes[0];
+ this._setAnimatedProperty(seqProp.getName(), node, keyframe.getValue(), tweenDuration);
+ }
+ },
+
+ _getEaseAction:function (action, easingType, easingOpt) {
+ if (easingType === CCB_KEYFRAME_EASING_LINEAR || easingType === CCB_KEYFRAME_EASING_INSTANT ) {
+ return action;
+ } else if (easingType === CCB_KEYFRAME_EASING_CUBIC_IN) {
+ return action.easing(cc.easeIn(easingOpt));
+ } else if (easingType === CCB_KEYFRAME_EASING_CUBIC_OUT) {
+ return action.easing(cc.easeOut(easingOpt));
+ } else if (easingType === CCB_KEYFRAME_EASING_CUBIC_INOUT) {
+ return action.easing(cc.easeInOut(easingOpt));
+ } else if (easingType === CCB_KEYFRAME_EASING_BACK_IN) {
+ return action.easing(cc.easeBackIn());
+ } else if (easingType === CCB_KEYFRAME_EASING_BACK_OUT) {
+ return action.easing(cc.easeBackOut());
+ } else if (easingType === CCB_KEYFRAME_EASING_BACK_INOUT) {
+ return action.easing(cc.easeBackInOut());
+ } else if (easingType === CCB_KEYFRAME_EASING_BOUNCE_IN) {
+ return action.easing(cc.easeBounceIn());
+ } else if (easingType === CCB_KEYFRAME_EASING_BOUNCE_OUT) {
+ return action.easing(cc.easeBounceOut());
+ } else if (easingType === CCB_KEYFRAME_EASING_BOUNCE_INOUT) {
+ return action.easing(cc.easeBounceInOut());
+ } else if (easingType === CCB_KEYFRAME_EASING_ELASTIC_IN) {
+ return action.easing(cc.easeElasticIn(easingOpt));
+ } else if (easingType === CCB_KEYFRAME_EASING_ELASTIC_OUT) {
+ return action.easing(cc.easeElasticOut(easingOpt));
+ } else if (easingType === CCB_KEYFRAME_EASING_ELASTIC_INOUT) {
+ return action.easing(cc.easeElasticInOut(easingOpt));
+ } else {
+ cc.log("BuilderReader: Unkown easing type " + easingType);
+ return action;
+ }
+ },
+
+ _runAction:function (node, seqProp, tweenDuration) {
+ var keyframes = seqProp.getKeyframes();
+ var numKeyframes = keyframes.length;
+
+ if (numKeyframes > 1) {
+ // Make an animation!
+ var actions = [];
+
+ var keyframeFirst = keyframes[0];
+ var timeFirst = keyframeFirst.getTime() + tweenDuration;
+
+ if (timeFirst > 0) {
+ actions.push(cc.delayTime(timeFirst));
+ }
+
+ for (var i = 0; i < numKeyframes - 1; ++i) {
+ var kf0 = keyframes[i];
+ var kf1 = keyframes[(i+1)];
+
+ var action = this._getAction(kf0, kf1, seqProp.getName(), node);
+ if (action) {
+ // Apply easing
+ action = this._getEaseAction(action, kf0.getEasingType(), kf0.getEasingOpt());
+ actions.push(action);
+ }
+ }
+
+ node.runAction(cc.sequence(actions));
+ }
+ },
+
+ _sequenceCompleted:function () {
+ var locRunningSequence = this._runningSequence;
+
+ var locRunningName = locRunningSequence.getName();
+
+ if(this._lastCompletedSequenceName != locRunningSequence.getName()){
+ this._lastCompletedSequenceName = locRunningSequence.getName();
+ }
+
+ var nextSeqId = locRunningSequence.getChainedSequenceId();
+ this._runningSequence = null;
+
+ if (nextSeqId !== -1)
+ this.runAnimations(nextSeqId, 0);
+
+ if (this._delegate)
+ this._delegate.completedAnimationSequenceNamed(locRunningName);
+
+ if(this._target && this._animationCompleteCallbackFunc){
+ this._animationCompleteCallbackFunc.call(this._target);
+ }
+ }
+});
+
+
+cc.BuilderSetSpriteFrame = cc.ActionInstant.extend({
+ _spriteFrame:null,
+
+ initWithSpriteFrame:function (spriteFrame) {
+ this._spriteFrame = spriteFrame;
+ return true;
+ },
+ update:function (time) {
+ this.target.setSpriteFrame(this._spriteFrame);
+ }
+});
+
+cc.BuilderSetSpriteFrame.create = function (spriteFrame) {
+ var ret = new cc.BuilderSetSpriteFrame();
+ if (ret) {
+ if (ret.initWithSpriteFrame(spriteFrame))
+ return ret;
+ }
+ return null;
+};
+
+//
+// cc.BuilderRotateTo
+//
+cc.BuilderRotateTo = cc.ActionInterval.extend({
+ _startAngle:0,
+ _dstAngle:0,
+ _diffAngle:0,
+
+ initWithDuration:function (duration, angle) {
+ if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
+ this._dstAngle = angle;
+ return true;
+ } else {
+ return false;
+ }
+ },
+ update:function (time) {
+ this.target.setRotation(this._startAngle + (this._diffAngle * time));
+ },
+
+ startWithTarget:function (node) {
+ cc.ActionInterval.prototype.startWithTarget.call(this, node);
+ this._startAngle = this.target.getRotation();
+ this._diffAngle = this._dstAngle - this._startAngle;
+ }
+});
+
+cc.BuilderRotateTo.create = function (duration, angle) {
+ var ret = new cc.BuilderRotateTo();
+ if (ret) {
+ if (ret.initWithDuration(duration, angle))
+ return ret;
+ }
+ return null;
+};
+
+//
+// cc.BuilderRotateXTo
+//
+cc.BuilderRotateXTo = cc.ActionInterval.extend({
+ // TODO: rotationX is not implemented in HTML5
+});
+
+cc.BuilderRotateXTo.create = function (duration, angle) {
+ throw new Error("rotationX has not been implemented in cocos2d-html5");
+};
+
+//
+// cc.BuilderRotateYTo
+//
+cc.BuilderRotateYTo = cc.ActionInterval.extend({
+ // TODO: rotationX is not implemented in HTML5
+});
+
+cc.BuilderRotateYTo.create = function (duration, angle) {
+ throw new Error("rotationY has not been implemented in cocos2d-html5");
+};
+
+//
+// cc.BuilderSoundEffect
+//
+cc.BuilderSoundEffect = cc.ActionInstant.extend({
+ init:function(file) {
+ this._file = file;
+ return true;
+ },
+ update:function(dt) {
+ cc.audioEngine.playEffect(this._file);
+ }
+});
+cc.BuilderSoundEffect.create = function (file, pitch, pan, gain) {
+ var ret = new cc.BuilderSoundEffect();
+ if (ret && ret.init(file)) {
+ return ret;
+ }
+ return null;
+};
+
diff --git a/extensions/ccb-reader/CCBKeyframe.js b/extensions/ccb-reader/CCBKeyframe.js
new file mode 100644
index 0000000000..1458d8063a
--- /dev/null
+++ b/extensions/ccb-reader/CCBKeyframe.js
@@ -0,0 +1,60 @@
+/****************************************************************************
+ 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.BuilderKeyframe = cc._Class.extend({
+ _value:null,
+ _time:0,
+ _easingType:0,
+ _easingOpt:0,
+
+ getValue:function(){
+ return this._value;
+ },
+ setValue:function(value){
+ this._value = value;
+ },
+
+ getTime:function(){
+ return this._time;
+ },
+ setTime:function(time){
+ this._time = time;
+ },
+
+ getEasingType:function(){
+ return this._easingType;
+ },
+ setEasingType:function(easingType){
+ this._easingType = easingType;
+ },
+
+ getEasingOpt:function(){
+ return this._easingOpt;
+ },
+ setEasingOpt:function(easingOpt){
+ this._easingOpt = easingOpt;
+ }
+});
diff --git a/extensions/ccb-reader/CCBReader.js b/extensions/ccb-reader/CCBReader.js
new file mode 100644
index 0000000000..0a7af84bbe
--- /dev/null
+++ b/extensions/ccb-reader/CCBReader.js
@@ -0,0 +1,1126 @@
+/****************************************************************************
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+var CCB_VERSION = 5;
+
+var CCB_PROPTYPE_POSITION = 0;
+var CCB_PROPTYPE_SIZE = 1;
+var CCB_PROPTYPE_POINT = 2;
+var CCB_PROPTYPE_POINTLOCK = 3;
+var CCB_PROPTYPE_SCALELOCK = 4;
+var CCB_PROPTYPE_DEGREES = 5;
+var CCB_PROPTYPE_INTEGER = 6;
+var CCB_PROPTYPE_FLOAT = 7;
+var CCB_PROPTYPE_FLOATVAR = 8;
+var CCB_PROPTYPE_CHECK = 9;
+var CCB_PROPTYPE_SPRITEFRAME = 10;
+var CCB_PROPTYPE_TEXTURE = 11;
+var CCB_PROPTYPE_BYTE = 12;
+var CCB_PROPTYPE_COLOR3 = 13;
+var CCB_PROPTYPE_COLOR4VAR = 14;
+var CCB_PROPTYPE_FLIP = 15;
+var CCB_PROPTYPE_BLENDMODE = 16;
+var CCB_PROPTYPE_FNTFILE = 17;
+var CCB_PROPTYPE_TEXT = 18;
+var CCB_PROPTYPE_FONTTTF = 19;
+var CCB_PROPTYPE_INTEGERLABELED = 20;
+var CCB_PROPTYPE_BLOCK = 21;
+var CCB_PROPTYPE_ANIMATION = 22;
+var CCB_PROPTYPE_CCBFILE = 23;
+var CCB_PROPTYPE_STRING = 24;
+var CCB_PROPTYPE_BLOCKCCCONTROL = 25;
+var CCB_PROPTYPE_FLOATSCALE = 26;
+var CCB_PROPTYPE_FLOATXY = 27;
+
+var CCB_FLOAT0 = 0;
+var CCB_FLOAT1 = 1;
+var CCB_FLOAT_MINUS1 = 2;
+var CCB_FLOAT05 = 3;
+var CCB_FLOAT_INTEGER = 4;
+var CCB_FLOAT_FULL = 5;
+
+var CCB_PLATFORM_ALL = 0;
+var CCB_PLATFORM_IOS = 1;
+var CCB_PLATFORM_MAC = 2;
+
+var CCB_TARGETTYPE_NONE = 0;
+var CCB_TARGETTYPE_DOCUMENTROOT = 1;
+var CCB_TARGETTYPE_OWNER = 2;
+
+var CCB_KEYFRAME_EASING_INSTANT = 0;
+var CCB_KEYFRAME_EASING_LINEAR = 1;
+var CCB_KEYFRAME_EASING_CUBIC_IN = 2;
+var CCB_KEYFRAME_EASING_CUBIC_OUT = 3;
+var CCB_KEYFRAME_EASING_CUBIC_INOUT = 4;
+var CCB_KEYFRAME_EASING_ELASTIC_IN = 5;
+var CCB_KEYFRAME_EASING_ELASTIC_OUT = 6;
+var CCB_KEYFRAME_EASING_ELASTIC_INOUT = 7;
+var CCB_KEYFRAME_EASING_BOUNCE_IN = 8;
+var CCB_KEYFRAME_EASING_BOUNCE_OUT = 9;
+var CCB_KEYFRAME_EASING_BOUNCE_INOUT = 10;
+var CCB_KEYFRAME_EASING_BACK_IN = 11;
+var CCB_KEYFRAME_EASING_BACK_OUT = 12;
+var CCB_KEYFRAME_EASING_BACK_INOUT = 13;
+
+var CCB_POSITIONTYPE_RELATIVE_BOTTOM_LEFT = 0;
+var CCB_POSITIONTYPE_RELATIVE_TOP_LEFT = 1;
+var CCB_POSITIONTYPE_RELATIVE_TOP_RIGHT = 2;
+var CCB_POSITIONTYPE_RELATIVE_BOTTOM_RIGHT = 3;
+var CCB_POSITIONTYPE_PERCENT = 4;
+var CCB_POSITIONTYPE_MULTIPLY_RESOLUTION = 5;
+
+var CCB_SIZETYPE_ABSOLUTE = 0;
+var CCB_SIZETYPE_PERCENT = 1;
+var CCB_SIZETYPE_RELATIVE_CONTAINER = 2;
+var CCB_SIZETYPE_HORIZONTAL_PERCENT = 3;
+var CCB_SIZETYPE_VERTICAL_PERCENT = 4;
+var CCB_SIZETYPE_MULTIPLY_RESOLUTION = 5;
+
+var CCB_SCALETYPE_ABSOLUTE = 0;
+var CCB_SCALETYPE_MULTIPLY_RESOLUTION = 1;
+
+cc.BuilderFile = cc.Node.extend({
+ _ccbFileNode:null,
+
+ getCCBFileNode:function () {
+ return this._ccbFileNode;
+ },
+ setCCBFileNode:function (node) {
+ this._ccbFileNode = node;
+ }
+});
+
+cc.BuilderFile.create = function () {
+ return new cc.BuilderFile();
+};
+
+/**
+ * Parse CCBI file which is generated by CocosBuilder
+ */
+cc.BuilderReader = cc._Class.extend({
+ _jsControlled:false,
+ _data:null,
+ _ccbRootPath:"",
+
+ _bytes:0,
+ _currentByte:0,
+ _currentBit:0,
+
+ _stringCache:null,
+ _loadedSpriteSheets:null,
+
+ _owner:null,
+ _animationManager:null,
+ _animationManagers:null,
+ _animatedProps:null,
+
+ _ccNodeLoaderLibrary:null,
+ _ccNodeLoaderListener:null,
+ _ccbMemberVariableAssigner:null,
+ _ccbSelectorResolver:null,
+
+ _ownerOutletNames:null,
+ _ownerOutletNodes:null,
+ _nodesWithAnimationManagers:null,
+ _animationManagerForNodes:null,
+
+ _ownerCallbackNames:null,
+ _ownerCallbackNodes:null,
+ _ownerCallbackEvents:null,
+
+ _readNodeGraphFromData:false,
+
+ ctor:function (ccNodeLoaderLibrary, ccbMemberVariableAssigner, ccbSelectorResolver, ccNodeLoaderListener) {
+ this._stringCache = [];
+ this._loadedSpriteSheets = [];
+ this._currentBit = -1;
+ this._currentByte = -1;
+
+ if (arguments.length !== 0) {
+ if (ccNodeLoaderLibrary instanceof cc.BuilderReader) {
+ var ccbReader = ccNodeLoaderLibrary;
+
+ /* Borrow data from the 'parent' CCBReader. */
+ this._loadedSpriteSheets = ccbReader._loadedSpriteSheets;
+ this._ccNodeLoaderLibrary = ccbReader._ccNodeLoaderLibrary;
+
+ this._ccbMemberVariableAssigner = ccbReader._ccbMemberVariableAssigner;
+ this._ccbSelectorResolver = ccbReader._ccbSelectorResolver;
+ this._ccNodeLoaderListener = ccbReader._ccNodeLoaderListener;
+
+ this._ownerCallbackNames = ccbReader._ownerCallbackNames;
+ this._ownerCallbackNodes = ccbReader._ownerCallbackNodes;
+ this._ownerCallbackEvents = ccbReader._ownerCallbackEvents;
+ this._ownerOutletNames = ccbReader._ownerOutletNames;
+ this._ownerOutletNodes = ccbReader._ownerOutletNodes;
+ this._ccbRootPath = ccbReader._ccbRootPath;
+ } else {
+ this._ccNodeLoaderLibrary = ccNodeLoaderLibrary;
+ this._ccbMemberVariableAssigner = ccbMemberVariableAssigner;
+ this._ccbSelectorResolver = ccbSelectorResolver;
+ this._ccNodeLoaderListener = ccNodeLoaderListener;
+ }
+ }
+ },
+
+ getCCBRootPath:function () {
+ return this._ccbRootPath;
+ },
+
+ setCCBRootPath:function (rootPath) {
+ this._ccbRootPath = rootPath;
+ },
+
+ initWithData:function (data, owner) {
+ //setup action manager
+ this._animationManager = new cc.BuilderAnimationManager();
+
+ //setup byte array
+ //Array replace to CCData in Javascript
+ this._data = data;
+ this._bytes = data.length;
+ this._currentBit = 0;
+ this._currentByte = 0;
+
+ this._owner = owner;
+
+ //setup resolution scale and container size
+ this._animationManager.setRootContainerSize(cc.director.getWinSize());
+
+ return true;
+ },
+
+ _loadBinarySync : function(url){
+ var self = this;
+ var req = this.getXMLHttpRequest();
+ var errInfo = "load " + url + " failed!";
+ req.open('GET', url, false);
+ var arrayInfo = null;
+ if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) {
+ req.setRequestHeader("Accept-Charset", "x-user-defined");
+ req.send(null);
+ if (req.status !== 200) {
+ cc.log(errInfo);
+ return null;
+ }
+
+ var fileContents = cc._convertResponseBodyToText(req["responseBody"]);
+ if (fileContents) {
+ arrayInfo = this._stringConvertToArray(fileContents);
+ this._fileDataCache[url] = arrayInfo;
+ }
+ } else {
+ if (req.overrideMimeType)
+ req.overrideMimeType('text\/plain; charset=x-user-defined');
+ req.send(null);
+ if (req.status !== 200) {
+ cc.log(errInfo);
+ return null;
+ }
+
+ arrayInfo = this._stringConvertToArray(req.responseText);
+ this._fileDataCache[url] = arrayInfo;
+ }
+ return arrayInfo;
+ },
+
+ readNodeGraphFromFile:function (ccbFileName, owner, parentSize, animationManager) {
+ if (parentSize == null) {
+ parentSize = cc.director.getWinSize();
+ } else if (parentSize instanceof cc.BuilderAnimationManager) {
+ animationManager = parentSize;
+ parentSize = cc.director.getWinSize();
+ }
+
+ var data = cc.loader.getRes(ccbFileName);
+ if(!data){
+ var realUrl = cc.loader.getUrl(ccbFileName);
+ data = cc.loader.loadBinarySync(realUrl);
+ cc.loader.cache[ccbFileName] = data;
+ }
+
+ return this.readNodeGraphFromData(data, owner, parentSize, animationManager);
+ },
+
+ readNodeGraphFromData:function (data, owner, parentSize) {
+ this.initWithData(data, owner);
+ var locAnimationManager = this._animationManager;
+ locAnimationManager.setRootContainerSize(parentSize);
+ locAnimationManager.setOwner(owner);
+
+ this._ownerOutletNames = [];
+ this._ownerOutletNodes = [];
+ this._ownerCallbackNames = [];
+ this._ownerCallbackNodes = [];
+ this._ownerCallbackEvents = [];
+ this._animationManagers = new cc._Dictionary();
+
+ var nodeGraph = this.readFileWithCleanUp(true);
+
+ if (nodeGraph && locAnimationManager.getAutoPlaySequenceId() !== -1) {
+ //auto play animations
+ locAnimationManager.runAnimations(locAnimationManager.getAutoPlaySequenceId(), 0);
+ }
+
+ if (this._jsControlled) {
+ var locNodes = [];
+ var locAnimations = [];
+
+ var locAnimationManagers = this._animationManagers;
+ var getAllKeys = locAnimationManagers.allKeys();
+ for (var i = 0; i < getAllKeys.length; i++) {
+ locNodes.push(getAllKeys[i]);
+ locAnimations.push(locAnimationManagers.objectForKey(getAllKeys[i]));
+ }
+
+ this._nodesWithAnimationManagers = locNodes;
+ this._animationManagerForNodes = locAnimations;
+ }
+
+ return nodeGraph;
+ },
+
+ createSceneWithNodeGraphFromFile:function (ccbFileName, owner, parentSize, animationManager) {
+ var node = this.readNodeGraphFromFile(ccbFileName, owner, parentSize, animationManager);
+ var scene = new cc.Scene();
+ scene.addChild(node);
+ return scene;
+ },
+
+ getCCBMemberVariableAssigner:function () {
+ return this._ccbMemberVariableAssigner;
+ },
+
+ getCCBSelectorResolver:function () {
+ return this._ccbSelectorResolver;
+ },
+
+ getAnimationManager:function () {
+ return this._animationManager;
+ },
+
+ setAnimationManager:function (animationManager) {
+ this._animationManager = animationManager;
+ },
+
+ getAnimatedProperties:function () {
+ return this._animatedProps;
+ },
+
+ getLoadedSpriteSheet:function () {
+ return this._loadedSpriteSheets;
+ },
+
+ getOwner:function () {
+ return this._owner;
+ },
+
+ readInt:function (signed) {
+ var numBits = 0;
+ while (!this._getBit()) {
+ numBits++;
+ }
+
+ var current = 0;
+ for (var a = numBits - 1; a >= 0; a--) {
+ if (this._getBit()) {
+ current |= 1 << a;
+ }
+ }
+ current |= 1 << numBits;
+
+ var num;
+ if (signed) {
+ var s = current % 2;
+ if (s) {
+ num = 0 | (current / 2);
+ } else {
+ num = 0 | (-current / 2);
+ }
+ } else {
+ num = current - 1;
+ }
+
+ this._alignBits();
+
+ return num;
+ },
+
+ readByte:function () {
+ var byteValue = this._data[this._currentByte];
+ this._currentByte++;
+ return byteValue;
+ },
+
+ readBool:function () {
+ return (0 !== this.readByte());
+ },
+
+ readFloat:function () {
+ var type = this.readByte();
+
+ switch (type) {
+ case CCB_FLOAT0:
+ return 0;
+ case CCB_FLOAT1:
+ return 1;
+ case CCB_FLOAT_MINUS1:
+ return -1;
+ case CCB_FLOAT05:
+ return 0.5;
+ case CCB_FLOAT_INTEGER:
+ return this.readInt(true);
+ default:
+ /* using a memcpy since the compiler isn't
+ * doing the float ptr math correctly on device.
+ */
+ var pF = this._decodeFloat(23, 8); //this._bytes + this._currentByte;
+ //this._currentByte += 4;
+ return pF;
+ }
+ },
+
+ _decodeFloat:function (precisionBits, exponentBits) {
+ var length = precisionBits + exponentBits + 1;
+ var size = length >> 3;
+ this._checkSize(length);
+
+ var bias = Math.pow(2, exponentBits - 1) - 1;
+ var signal = this._readBitsOnly(precisionBits + exponentBits, 1, size);
+ var exponent = this._readBitsOnly(precisionBits, exponentBits, size);
+ var significand = 0;
+ var divisor = 2;
+ var curByte = 0; //length + (-precisionBits >> 3) - 1;
+ do {
+ var byteValue = this._readByteOnly(++curByte, size);
+ var startBit = precisionBits % 8 || 8;
+ var mask = 1 << startBit;
+ while (mask >>= 1) {
+ if (byteValue & mask) {
+ significand += 1 / divisor;
+ }
+ divisor *= 2;
+ }
+ } while (precisionBits -= startBit);
+
+ this._currentByte += size;
+
+ return exponent === (bias << 1) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity
+ : (1 + signal * -2) * (exponent || significand ? !exponent ? Math.pow(2, -bias + 1) * significand
+ : Math.pow(2, exponent - bias) * (1 + significand) : 0);
+ },
+
+ _readBitsOnly:function (start, length, size) {
+ var offsetLeft = (start + length) % 8;
+ var offsetRight = start % 8;
+ var curByte = size - (start >> 3) - 1;
+ var lastByte = size + (-(start + length) >> 3);
+ var diff = curByte - lastByte;
+
+ var sum = (this._readByteOnly(curByte, size) >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1);
+
+ if (diff && offsetLeft) {
+ sum += (this._readByteOnly(lastByte++, size) & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight;
+ }
+
+ while (diff) {
+ sum += this._shl(this._readByteOnly(lastByte++, size), (diff-- << 3) - offsetRight);
+ }
+
+ return sum;
+ },
+
+ _readByteOnly:function (i, size) {
+ return this._data[this._currentByte + size - i - 1];
+ },
+
+ _shl:function (a, b) {
+ for (++b; --b; a = ((a %= 0x7fffffff + 1) & 0x40000000) === 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1);
+ return a;
+ },
+
+ _checkSize:function (neededBits) {
+ if (!(this._currentByte + Math.ceil(neededBits / 8) < this._data.length)) {
+ throw new Error("Index out of bound");
+ }
+ },
+
+ readCachedString:function () {
+ return this._stringCache[this.readInt(false)];
+ },
+
+ isJSControlled:function () {
+ return this._jsControlled;
+ },
+
+ getOwnerCallbackNames:function () {
+ return this._ownerCallbackNames;
+ },
+
+ getOwnerCallbackNodes:function () {
+ return this._ownerCallbackNodes;
+ },
+
+ getOwnerCallbackControlEvents:function(){
+ return this._ownerCallbackEvents;
+ },
+
+ getOwnerOutletNames:function () {
+ return this._ownerOutletNames;
+ },
+
+ getOwnerOutletNodes:function () {
+ return this._ownerOutletNodes;
+ },
+
+ getNodesWithAnimationManagers:function () {
+ return this._nodesWithAnimationManagers;
+ },
+
+ getAnimationManagersForNodes:function () {
+ return this._animationManagerForNodes;
+ },
+
+ getAnimationManagers:function () {
+ return this._animationManagers;
+ },
+
+ setAnimationManagers:function (animationManagers) {
+ this._animationManagers = animationManagers;
+ },
+
+ addOwnerCallbackName:function (name) {
+ this._ownerCallbackNames.push(name)
+ },
+
+ addOwnerCallbackNode:function (node) {
+ this._ownerCallbackNodes.push(node);
+ },
+
+ addOwnerCallbackControlEvents:function(event){
+ this._ownerCallbackEvents.push(event);
+ },
+
+ addDocumentCallbackName:function (name) {
+ this._animationManager.addDocumentCallbackName(name);
+ },
+
+ addDocumentCallbackNode:function (node) {
+ this._animationManager.addDocumentCallbackNode(node);
+ },
+
+ addDocumentCallbackControlEvents:function(controlEvents){
+ this._animationManager.addDocumentCallbackControlEvents(controlEvents);
+ },
+
+ readFileWithCleanUp:function (cleanUp) {
+ if (!this._readHeader())
+ return null;
+ if (!this._readStringCache())
+ return null;
+ if (!this._readSequences())
+ return null;
+
+ var node = this._readNodeGraph();
+ this._animationManagers.setObject(this._animationManager, node);
+
+ if (cleanUp)
+ this._cleanUpNodeGraph(node);
+ return node;
+ },
+
+ addOwnerOutletName: function(name){
+ this._ownerOutletNames.push(name);
+ },
+
+ addOwnerOutletNode: function(node){
+ if(node == null)
+ return;
+
+ this._ownerOutletNodes.push(node);
+ },
+
+ _cleanUpNodeGraph:function (node) {
+ node.userObject = null;
+ var getChildren = node.getChildren();
+ for (var i = 0, len = getChildren.length; i < len; i++) {
+ this._cleanUpNodeGraph(getChildren[i]);
+ }
+ },
+
+ _readCallbackKeyframesForSeq:function(seq) {
+ var numKeyframes = this.readInt(false);
+
+ if (!numKeyframes)
+ return true;
+
+ var channel = new cc.BuilderSequenceProperty();
+ var locJsControlled = this._jsControlled, locAnimationManager = this._animationManager, locKeyframes = channel.getKeyframes();
+ for (var i = 0; i < numKeyframes; i++) {
+ var time = this.readFloat();
+ var callbackName = this.readCachedString();
+ var callbackType = this.readInt(false);
+
+ var value = [ callbackName, callbackType];
+
+ var keyframe = new cc.BuilderKeyframe();
+ keyframe.setTime(time);
+ keyframe.setValue(value);
+
+ if(locJsControlled)
+ locAnimationManager.getKeyframeCallbacks().push(callbackType+":"+callbackName);
+
+ locKeyframes.push(keyframe);
+ }
+
+ // Assign to sequence
+ seq.setCallbackChannel(channel);
+
+ return true;
+ },
+
+ _readSoundKeyframesForSeq:function(seq) {
+ var numKeyframes = this.readInt(false);
+
+ if (!numKeyframes)
+ return true;
+
+ var channel = new cc.BuilderSequenceProperty();
+ var locKeyframes = channel.getKeyframes();
+ for (var i = 0; i < numKeyframes; i++) {
+ var time = this.readFloat();
+ var soundFile = this.readCachedString();
+ var pitch = this.readFloat();
+ var pan = this.readFloat();
+ var gain = this.readFloat();
+
+ var value = [soundFile, pitch, pan, gain];
+ var keyframe = new cc.BuilderKeyframe();
+ keyframe.setTime(time);
+ keyframe.setValue(value);
+
+ locKeyframes.push(keyframe);
+ }
+
+ // Assign to sequence
+ seq.setSoundChannel(channel);
+ return true;
+ },
+ _readSequences:function () {
+ var sequences = this._animationManager.getSequences();
+ var numSeqs = this.readInt(false);
+ for (var i = 0; i < numSeqs; i++) {
+ var seq = new cc.BuilderSequence();
+ seq.setDuration(this.readFloat());
+ seq.setName(this.readCachedString());
+ seq.setSequenceId(this.readInt(false));
+ seq.setChainedSequenceId(this.readInt(true));
+
+ if (!this._readCallbackKeyframesForSeq(seq))
+ return false;
+ if (!this._readSoundKeyframesForSeq(seq))
+ return false;
+
+ sequences.push(seq);
+ }
+ this._animationManager.setAutoPlaySequenceId(this.readInt(true));
+ return true;
+ },
+
+ readKeyframe:function (type) {
+ var keyframe = new cc.BuilderKeyframe();
+ keyframe.setTime(this.readFloat());
+ var easingType = this.readInt(false);
+ var easingOpt = 0;
+ var value = null;
+
+ if (easingType === CCB_KEYFRAME_EASING_CUBIC_IN
+ || easingType === CCB_KEYFRAME_EASING_CUBIC_OUT
+ || easingType === CCB_KEYFRAME_EASING_CUBIC_INOUT
+ || easingType === CCB_KEYFRAME_EASING_ELASTIC_IN
+ || easingType === CCB_KEYFRAME_EASING_ELASTIC_OUT
+ || easingType === CCB_KEYFRAME_EASING_ELASTIC_INOUT) {
+ easingOpt = this.readFloat();
+ }
+
+ keyframe.setEasingType(easingType);
+ keyframe.setEasingOpt(easingOpt);
+
+ if (type === CCB_PROPTYPE_CHECK) {
+ value = this.readBool();
+ } else if (type === CCB_PROPTYPE_BYTE) {
+ value = this.readByte();
+ } else if (type === CCB_PROPTYPE_COLOR3) {
+ var c = cc.color(this.readByte(), this.readByte(), this.readByte());
+ value = cc.Color3BWapper.create(c);
+ } else if (type === CCB_PROPTYPE_FLOATXY) {
+ value = [this.readFloat(), this.readFloat()];
+ } else if (type === CCB_PROPTYPE_DEGREES) {
+ value = this.readFloat();
+ } else if (type === CCB_PROPTYPE_SCALELOCK || type === CCB_PROPTYPE_POSITION || type === CCB_PROPTYPE_FLOATXY) {
+ value = [this.readFloat(), this.readFloat()];
+ } else if (type === CCB_PROPTYPE_SPRITEFRAME) {
+ var spriteSheet = this.readCachedString();
+ var spriteFile = this.readCachedString();
+
+ if (spriteSheet === "") {
+ spriteFile = this._ccbRootPath + spriteFile;
+ var texture = cc.textureCache.addImage(spriteFile);
+ var locContentSize = texture.getContentSize();
+ var bounds = cc.rect(0, 0, locContentSize.width, locContentSize.height);
+ value = new cc.SpriteFrame(texture, bounds);
+ } else {
+ spriteSheet = this._ccbRootPath + spriteSheet;
+ var frameCache = cc.spriteFrameCache;
+ // Load the sprite sheet only if it is not loaded
+ if (this._loadedSpriteSheets.indexOf(spriteSheet) === -1) {
+ frameCache.addSpriteFrames(spriteSheet);
+ this._loadedSpriteSheets.push(spriteSheet);
+ }
+ value = frameCache.getSpriteFrame(spriteFile);
+ }
+ }
+ keyframe.setValue(value);
+ return keyframe;
+ },
+
+ _readHeader:function () {
+ /* If no bytes loaded, don't crash about it. */
+ if (!this._data)
+ return false;
+
+ /* Read magic bytes */
+ var magicBytes = this._readStringFromBytes(this._currentByte, 4, true);
+ this._currentByte += 4;
+
+ if (magicBytes !== 'ccbi') {
+ return false;
+ }
+
+ /* Read version. */
+ var version = this.readInt(false);
+ if (version !== CCB_VERSION) {
+ cc.log("WARNING! Incompatible ccbi file version (file: " + version + " reader: " + CCB_VERSION + ")");
+ return false;
+ }
+
+ this._jsControlled = this.readBool();
+ this._animationManager._jsControlled = this._jsControlled;
+ // no need to set if it is "jscontrolled". It is obvious.
+ return true;
+ },
+
+ _readStringFromBytes:function (startIndex, strLen, reverse) {
+ reverse = reverse || false;
+ var strValue = "";
+ var i, locData = this._data, locCurrentByte = this._currentByte;
+ if (reverse) {
+ for (i = strLen - 1; i >= 0; i--)
+ strValue += String.fromCharCode(locData[locCurrentByte + i]);
+ } else {
+ for (i = 0; i < strLen; i++)
+ strValue += String.fromCharCode(locData[locCurrentByte + i]);
+ }
+ return strValue;
+ },
+
+ _readStringCache:function () {
+ var numStrings = this.readInt(false);
+ for (var i = 0; i < numStrings; i++)
+ this._readStringCacheEntry();
+ return true;
+ },
+
+ _readStringCacheEntry:function () {
+ var b0 = this.readByte();
+ var b1 = this.readByte();
+
+ var numBytes = b0 << 8 | b1;
+
+ var str = "", locData = this._data, locCurrentByte = this._currentByte;
+ for (var i = 0; i < numBytes; i++) {
+ var hexChar = locData[locCurrentByte + i].toString("16").toUpperCase();
+ hexChar = hexChar.length > 1 ? hexChar : "0" + hexChar;
+ str += "%" + hexChar;
+ }
+ str = decodeURIComponent(str);
+
+ this._currentByte += numBytes;
+ this._stringCache.push(str);
+ },
+
+ _readNodeGraph:function (parent) {
+ /* Read class name. */
+ var className = this.readCachedString();
+
+ var jsControlledName, locJsControlled = this._jsControlled, locActionManager = this._animationManager;
+ if (locJsControlled)
+ jsControlledName = this.readCachedString();
+
+ var memberVarAssignmentType = this.readInt(false);
+ var memberVarAssignmentName;
+ if (memberVarAssignmentType !== CCB_TARGETTYPE_NONE) {
+ memberVarAssignmentName = this.readCachedString();
+ }
+
+ var ccNodeLoader = this._ccNodeLoaderLibrary.getCCNodeLoader(className);
+ if (!ccNodeLoader) {
+ ccNodeLoader = this._ccNodeLoaderLibrary.getCCNodeLoader("CCNode");
+ //cc.log("no corresponding node loader for" + className);
+ //return null;
+ }
+ var node = ccNodeLoader.loadCCNode(parent, this);
+
+ //set root node
+ if (!locActionManager.getRootNode())
+ locActionManager.setRootNode(node);
+
+ if (locJsControlled && node === locActionManager.getRootNode()) {
+ locActionManager.setDocumentControllerName(jsControlledName);
+ }
+
+ //read animated properties
+ var seqs = new cc._Dictionary();
+ this._animatedProps = [];
+
+ var i, locAnimatedProps = this._animatedProps;
+ var numSequence = this.readInt(false);
+ for (i = 0; i < numSequence; ++i) {
+ var seqId = this.readInt(false);
+ var seqNodeProps = new cc._Dictionary();
+
+ var numProps = this.readInt(false);
+
+ for (var j = 0; j < numProps; ++j) {
+ var seqProp = new cc.BuilderSequenceProperty();
+ seqProp.setName(this.readCachedString());
+ seqProp.setType(this.readInt(false));
+
+ locAnimatedProps.push(seqProp.getName());
+ var numKeyframes = this.readInt(false);
+ var locKeyframes = seqProp.getKeyframes();
+ for (var k = 0; k < numKeyframes; ++k) {
+ var keyFrame = this.readKeyframe(seqProp.getType());
+ locKeyframes.push(keyFrame);
+ }
+ seqNodeProps.setObject(seqProp, seqProp.getName());
+ }
+ seqs.setObject(seqNodeProps, seqId);
+ }
+
+ if (seqs.count() > 0)
+ locActionManager.addNode(node, seqs);
+
+ //read properties
+ ccNodeLoader.parseProperties(node, parent, this);
+
+ //handle sub ccb files(remove middle node)
+ var isCCBFileNode = node instanceof cc.BuilderFile;
+ if (isCCBFileNode) {
+ var embeddedNode = node.getCCBFileNode();
+ embeddedNode.setPosition(node.getPosition());
+ embeddedNode.setRotation(node.getRotation());
+ embeddedNode.setScaleX(node.getScaleX());
+ embeddedNode.setScaleY(node.getScaleY());
+ embeddedNode.setTag(node.getTag());
+ embeddedNode.setVisible(true);
+ //embeddedNode.ignoreAnchorPointForPosition(node.isIgnoreAnchorPointForPosition());
+
+ locActionManager.moveAnimationsFromNode(node, embeddedNode);
+ node.setCCBFileNode(null);
+ node = embeddedNode;
+ }
+ var target = null, locMemberAssigner = null;
+ if (memberVarAssignmentType !== CCB_TARGETTYPE_NONE) {
+ if (!locJsControlled) {
+ if (memberVarAssignmentType === CCB_TARGETTYPE_DOCUMENTROOT) {
+ target = locActionManager.getRootNode();
+ } else if (memberVarAssignmentType === CCB_TARGETTYPE_OWNER) {
+ target = this._owner;
+ }
+
+ if (!target) {
+ var assigned = false;
+
+ if (target.onAssignCCBMemberVariable)
+ assigned = target.onAssignCCBMemberVariable(target, memberVarAssignmentName, node);
+
+ locMemberAssigner = this._ccbMemberVariableAssigner;
+ if (!assigned && locMemberAssigner != null && locMemberAssigner.onAssignCCBMemberVariable) {
+ locMemberAssigner.onAssignCCBMemberVariable(target, memberVarAssignmentName, node);
+ }
+ }
+ } else {
+ if (memberVarAssignmentType === CCB_TARGETTYPE_DOCUMENTROOT) {
+ locActionManager.addDocumentOutletName(memberVarAssignmentName);
+ locActionManager.addDocumentOutletNode(node);
+ } else {
+ this._ownerOutletNames.push(memberVarAssignmentName);
+ this._ownerOutletNodes.push(node);
+ }
+ }
+ }
+
+ // Assign custom properties.
+ if (ccNodeLoader.getCustomProperties().length > 0) {
+ var customAssigned = false;
+ if(!locJsControlled) {
+ target = node;
+ if(target != null && target.onAssignCCBCustomProperty != null) {
+ var customProperties = ccNodeLoader.getCustomProperties();
+ var customPropKeys = customProperties.allKeys();
+ for(i = 0;i < customPropKeys.length;i++){
+ var customPropValue = customProperties.objectForKey(customPropKeys[i]);
+ customAssigned = target.onAssignCCBCustomProperty(target, customPropKeys[i], customPropValue);
+ locMemberAssigner = this._ccbMemberVariableAssigner;
+ if(!customAssigned && (locMemberAssigner != null) && (locMemberAssigner.onAssignCCBCustomProperty != null))
+ customAssigned = locMemberAssigner.onAssignCCBCustomProperty(target, customPropKeys[i], customPropValue);
+ }
+ }
+ }
+ }
+
+ this._animatedProps = null;
+
+ /* Read and add children. */
+ var numChildren = this.readInt(false);
+ for (i = 0; i < numChildren; i++) {
+ var child = this._readNodeGraph(node);
+ node.addChild(child);
+ }
+
+ // FIX ISSUE #1860: "onNodeLoaded will be called twice if ccb was added as a CCBFile".
+ // If it's a sub-ccb node, skip notification to CCNodeLoaderListener since it will be
+ // notified at LINE #734: CCNode * child = this->readNodeGraph(node);
+ if (!isCCBFileNode) {
+ // Call onNodeLoaded
+ if (node != null && node.onNodeLoaded)
+ node.onNodeLoaded(node, ccNodeLoader);
+ else if (this._ccNodeLoaderListener != null)
+ this._ccNodeLoaderListener.onNodeLoaded(node, ccNodeLoader);
+ }
+
+ return node;
+ },
+
+ _getBit:function () {
+ var bit = (this._data[this._currentByte] & (1 << this._currentBit)) !== 0;
+ this._currentBit++;
+
+ if (this._currentBit >= 8) {
+ this._currentBit = 0;
+ this._currentByte++;
+ if(this._currentByte > this._data.length)
+ throw new Error("out of the data bound");
+ }
+ return bit;
+ },
+
+ _alignBits:function () {
+ if (this._currentBit) {
+ this._currentBit = 0;
+ this._currentByte++;
+ }
+ },
+
+ _readUTF8:function () {
+ }
+});
+
+cc.BuilderReader._ccbResolutionScale = 1;
+cc.BuilderReader.setResolutionScale = function(scale){
+ cc.BuilderReader._ccbResolutionScale = scale;
+};
+
+cc.BuilderReader.getResolutionScale = function () {
+ return cc.BuilderReader._ccbResolutionScale;
+};
+
+cc.BuilderReader.loadAsScene = function (ccbFilePath, owner, parentSize, ccbRootPath) {
+ ccbRootPath = ccbRootPath || cc.BuilderReader.getResourcePath();
+
+ var getNode = cc.BuilderReader.load(ccbFilePath, owner, parentSize, ccbRootPath);
+
+ var scene = new cc.Scene();
+ scene.addChild(getNode);
+ return scene;
+};
+
+cc.BuilderReader._controllerClassCache = {};
+cc.BuilderReader.registerController = function(controllerName, controller){
+ cc.BuilderReader._controllerClassCache[controllerName] = cc._Class.extend(controller);
+};
+cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) {
+ ccbRootPath = ccbRootPath || cc.BuilderReader.getResourcePath();
+ var reader = new cc.BuilderReader(cc.NodeLoaderLibrary.newDefaultCCNodeLoaderLibrary());
+ reader.setCCBRootPath(ccbRootPath);
+ if((ccbFilePath.length < 5)||(ccbFilePath.toLowerCase().lastIndexOf(".ccbi") !== ccbFilePath.length - 5))
+ ccbFilePath = ccbFilePath + ".ccbi";
+
+ var node = reader.readNodeGraphFromFile(ccbFilePath, owner, parentSize);
+ var i;
+ var callbackName, callbackNode, callbackControlEvents, outletName, outletNode;
+ // Assign owner callbacks & member variables
+ if (owner) {
+ // Callbacks
+ var ownerCallbackNames = reader.getOwnerCallbackNames();
+ var ownerCallbackNodes = reader.getOwnerCallbackNodes();
+ var ownerCallbackControlEvents = reader.getOwnerCallbackControlEvents();
+ for (i = 0; i < ownerCallbackNames.length; i++) {
+ callbackName = ownerCallbackNames[i];
+ callbackNode = ownerCallbackNodes[i];
+ callbackControlEvents = ownerCallbackControlEvents[i];
+ if(callbackNode instanceof cc.ControlButton)
+ callbackNode.addTargetWithActionForControlEvents(owner, owner[callbackName], callbackControlEvents); //register all type of events
+ else
+ callbackNode.setCallback(owner[callbackName], owner);
+ }
+
+ // Variables
+ var ownerOutletNames = reader.getOwnerOutletNames();
+ var ownerOutletNodes = reader.getOwnerOutletNodes();
+ for (i = 0; i < ownerOutletNames.length; i++) {
+ outletName = ownerOutletNames[i];
+ outletNode = ownerOutletNodes[i];
+ owner[outletName] = outletNode;
+ }
+ }
+
+ var nodesWithAnimationManagers = reader.getNodesWithAnimationManagers();
+ var animationManagersForNodes = reader.getAnimationManagersForNodes();
+ if(!nodesWithAnimationManagers || !animationManagersForNodes)
+ return node;
+
+ var controllerClassCache = cc.BuilderReader._controllerClassCache;
+ // Attach animation managers to nodes and assign root node callbacks and member variables
+ for (i = 0; i < nodesWithAnimationManagers.length; i++) {
+ var innerNode = nodesWithAnimationManagers[i];
+ var animationManager = animationManagersForNodes[i];
+
+ var j;
+ innerNode.animationManager = animationManager;
+
+ var controllerName = animationManager.getDocumentControllerName();
+ if (!controllerName) continue;
+
+ // Create a controller
+ var controllerClass = controllerClassCache[controllerName];
+ if(!controllerClass) throw new Error("Can not find controller : " + controllerName);
+ var controller = new controllerClass();
+ controller.controllerName = controllerName;
+
+ innerNode.controller = controller;
+ controller.rootNode = innerNode;
+
+ // Callbacks
+ var documentCallbackNames = animationManager.getDocumentCallbackNames();
+ var documentCallbackNodes = animationManager.getDocumentCallbackNodes();
+ var documentCallbackControlEvents = animationManager.getDocumentCallbackControlEvents();
+ for (j = 0; j < documentCallbackNames.length; j++) {
+ callbackName = documentCallbackNames[j];
+ callbackNode = documentCallbackNodes[j];
+ callbackControlEvents = documentCallbackControlEvents[j];
+ if(callbackNode instanceof cc.ControlButton)
+ callbackNode.addTargetWithActionForControlEvents(controller, controller[callbackName], callbackControlEvents); //register all type of events
+ else
+ callbackNode.setCallback(controller[callbackName], controller);
+ }
+
+ // Variables
+ var documentOutletNames = animationManager.getDocumentOutletNames();
+ var documentOutletNodes = animationManager.getDocumentOutletNodes();
+ for (j = 0; j < documentOutletNames.length; j++) {
+ outletName = documentOutletNames[j];
+ outletNode = documentOutletNodes[j];
+
+ controller[outletName] = outletNode;
+ }
+
+ if (controller.onDidLoadFromCCB && cc.js.isFunction(controller.onDidLoadFromCCB))
+ controller.onDidLoadFromCCB();
+
+ // Setup timeline callbacks
+ var keyframeCallbacks = animationManager.getKeyframeCallbacks();
+ for (j = 0; j < keyframeCallbacks.length; j++) {
+ var callbackSplit = keyframeCallbacks[j].split(":");
+ var callbackType = callbackSplit[0];
+ var kfCallbackName = callbackSplit[1];
+
+ if (callbackType == 1){ // Document callback
+ animationManager.setCallFunc(cc.callFunc(controller[kfCallbackName], controller), keyframeCallbacks[j]);
+ } else if (callbackType == 2 && owner) {// Owner callback
+ animationManager.setCallFunc(cc.callFunc(owner[kfCallbackName], owner), keyframeCallbacks[j]);
+ }
+ }
+ }
+
+ //auto play animations
+ animationManager.runAnimations(animationManager.getAutoPlaySequenceId(), 0);
+
+ return node;
+};
+
+cc.BuilderReader._resourcePath = "";
+cc.BuilderReader.setResourcePath = function (rootPath) {
+ cc.BuilderReader._resourcePath = rootPath;
+};
+
+cc.BuilderReader.getResourcePath = function () {
+ return cc.BuilderReader._resourcePath;
+};
+
+cc.BuilderReader.lastPathComponent = function (pathStr) {
+ var slashPos = pathStr.lastIndexOf("/");
+ if (slashPos !== -1) {
+ return pathStr.substring(slashPos + 1, pathStr.length - slashPos);
+ }
+ return pathStr;
+};
+
+cc.BuilderReader.deletePathExtension = function (pathStr) {
+ var dotPos = pathStr.lastIndexOf(".");
+ if (dotPos !== -1) {
+ return pathStr.substring(0, dotPos);
+ }
+ return pathStr;
+};
+
+cc.BuilderReader.toLowerCase = function (sourceStr) {
+ return sourceStr.toLowerCase();
+};
+
+cc.BuilderReader.endsWith = function (sourceStr, ending) {
+ if (sourceStr.length >= ending.length)
+ return (sourceStr.lastIndexOf(ending) === 0);
+ else
+ return false;
+};
+
+cc.BuilderReader.concat = function (stringA, stringB) {
+ return stringA + stringB;
+};
+
+cc.loader.register(["ccbi"], cc._binaryLoader);
\ No newline at end of file
diff --git a/extensions/ccb-reader/CCBReaderUtil.js b/extensions/ccb-reader/CCBReaderUtil.js
new file mode 100644
index 0000000000..d992f14520
--- /dev/null
+++ b/extensions/ccb-reader/CCBReaderUtil.js
@@ -0,0 +1,61 @@
+/****************************************************************************
+ 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.NodeLoaderListener = cc._Class.extend({
+ onNodeLoaded:function(node,nodeLoader){}
+});
+
+cc.BuilderSelectorResolver = cc._Class.extend({
+ onResolveCCBCCMenuItemSelector:function(target, selectorName){},
+ onResolveCCBCCCallFuncSelector:function(target, selectorName){},
+ onResolveCCBCCControlSelector:function(target,selectorName){}
+});
+
+cc.BuilderScriptOwnerProtocol = cc._Class.extend({
+ createNew:function(){}
+});
+
+cc.BuilderMemberVariableAssigner = cc._Class.extend({
+ /**
+ * The callback function of assigning member variable.
+ * @note The member variable must be CCNode or its subclass.
+ * @param {Object} target The custom class
+ * @param {string} memberVariableName The name of the member variable.
+ * @param {cc.Node} node The member variable.
+ * @return {Boolean} Whether the assignment was successful.
+ */
+ onAssignCCBMemberVariable:function(target,memberVariableName, node){ return false;},
+
+ /**
+ * The callback function of assigning custom properties.
+ * @note The member variable must be Integer, Float, Boolean or String.
+ * @param {Object} target The custom class.
+ * @param {string} memberVariableName The name of the member variable.
+ * @param {*} value The value of the property.
+ * @return {Boolean} Whether the assignment was successful.
+ */
+ onAssignCCBCustomProperty:function(target, memberVariableName, value){ return false; }
+});
diff --git a/extensions/ccb-reader/CCBRelativePositioning.js b/extensions/ccb-reader/CCBRelativePositioning.js
new file mode 100644
index 0000000000..2b2df87bef
--- /dev/null
+++ b/extensions/ccb-reader/CCBRelativePositioning.js
@@ -0,0 +1,90 @@
+/****************************************************************************
+ 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.getAbsolutePosition = function(pt, type, containerSize, propName){
+ var absPt = cc.p(0,0);
+ if(type === CCB_POSITIONTYPE_RELATIVE_BOTTOM_LEFT)
+ absPt = pt;
+ else if(type === CCB_POSITIONTYPE_RELATIVE_TOP_LEFT){
+ absPt.x = pt.x;
+ absPt.y = containerSize.height - pt.y;
+ } else if(type === CCB_POSITIONTYPE_RELATIVE_TOP_RIGHT){
+ absPt.x = containerSize.width - pt.x;
+ absPt.y = containerSize.height - pt.y;
+ } else if (type === CCB_POSITIONTYPE_RELATIVE_BOTTOM_RIGHT) {
+ absPt.x = containerSize.width - pt.x;
+ absPt.y = pt.y;
+ } else if (type === CCB_POSITIONTYPE_PERCENT) {
+ absPt.x = (containerSize.width * pt.x / 100.0);
+ absPt.y = (containerSize.height * pt.y / 100.0);
+ } else if (type === CCB_POSITIONTYPE_MULTIPLY_RESOLUTION) {
+ var resolutionScale = cc.BuilderReader.getResolutionScale();
+ absPt.x = pt.x * resolutionScale;
+ absPt.y = pt.y * resolutionScale;
+ }
+
+ return absPt;
+};
+
+cc._getAbsolutePosition = function(x, y, type, containerSize, propName){
+ var absPt = cc.p(0,0);
+ if(type === CCB_POSITIONTYPE_RELATIVE_BOTTOM_LEFT){
+ absPt.x = x;
+ absPt.y = y;
+ } else if(type === CCB_POSITIONTYPE_RELATIVE_TOP_LEFT){
+ absPt.x = x;
+ absPt.y = containerSize.height - y;
+ } else if(type === CCB_POSITIONTYPE_RELATIVE_TOP_RIGHT){
+ absPt.x = containerSize.width - x;
+ absPt.y = containerSize.height - y;
+ } else if (type === CCB_POSITIONTYPE_RELATIVE_BOTTOM_RIGHT) {
+ absPt.x = containerSize.width - x;
+ absPt.y = y;
+ } else if (type === CCB_POSITIONTYPE_PERCENT) {
+ absPt.x = (containerSize.width * x / 100.0);
+ absPt.y = (containerSize.height * y / 100.0);
+ } else if (type === CCB_POSITIONTYPE_MULTIPLY_RESOLUTION) {
+ var resolutionScale = cc.BuilderReader.getResolutionScale();
+ absPt.x = x * resolutionScale;
+ absPt.y = y * resolutionScale;
+ }
+ return absPt;
+};
+
+cc.setRelativeScale = function(node,scaleX, scaleY, type, propName){
+ if(!node)
+ throw new Error("cc.setRelativeScale(): node should be non-null");
+
+ if (type === CCB_POSITIONTYPE_MULTIPLY_RESOLUTION) {
+ var resolutionScale = cc.BuilderReader.getResolutionScale();
+
+ scaleX *= resolutionScale;
+ scaleY *= resolutionScale;
+ }
+
+ node.setScaleX(scaleX);
+ node.setScaleY(scaleY);
+};
\ No newline at end of file
diff --git a/extensions/ccb-reader/CCBSequence.js b/extensions/ccb-reader/CCBSequence.js
new file mode 100644
index 0000000000..488cfc6f90
--- /dev/null
+++ b/extensions/ccb-reader/CCBSequence.js
@@ -0,0 +1,114 @@
+/****************************************************************************
+ 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.BuilderSequence = cc._Class.extend({
+ _duration:0,
+ _name:"",
+ _sequenceId:0,
+ _chainedSequenceId:0,
+ _callbackChannel:null,
+ _soundChannel:null,
+
+ ctor:function(){
+ this._name = "";
+ },
+
+ getDuration:function(){
+ return this._duration;
+ },
+ setDuration:function(duration){
+ this._duration = duration;
+ },
+
+ getName:function(){
+ return this._name;
+ },
+ setName:function(name){
+ this._name = name;
+ },
+
+ getSequenceId:function(){
+ return this._sequenceId;
+ },
+ setSequenceId:function(sequenceId){
+ this._sequenceId = sequenceId;
+ },
+
+ getChainedSequenceId:function(){
+ return this._chainedSequenceId;
+ },
+ setChainedSequenceId:function(chainedSequenceId){
+ this._chainedSequenceId = chainedSequenceId;
+ },
+
+ getCallbackChannel:function() {
+ return this._callbackChannel;
+ },
+ setCallbackChannel:function(channel) {
+ this._callbackChannel = channel;
+ },
+
+ getSoundChannel:function() {
+ return this._soundChannel;
+ },
+ setSoundChannel:function(channel) {
+ this._soundChannel = channel;
+ }
+});
+
+cc.BuilderSequenceProperty = cc._Class.extend({
+ _name : null,
+ _type:0,
+ _keyFrames:null,
+
+ ctor:function(){
+ this.init();
+ },
+
+ init:function(){
+ this._keyFrames = [];
+ this._name = "";
+ },
+
+ getName:function(){
+ return this._name;
+ },
+
+ setName :function(name){
+ this._name = name;
+ },
+
+ getType:function(){
+ return this._type;
+ },
+ setType :function(type){
+ this._type = type;
+ },
+
+ getKeyframes:function(){
+ return this._keyFrames;
+ }
+});
\ No newline at end of file
diff --git a/extensions/ccb-reader/CCBValue.js b/extensions/ccb-reader/CCBValue.js
new file mode 100644
index 0000000000..85fee5782c
--- /dev/null
+++ b/extensions/ccb-reader/CCBValue.js
@@ -0,0 +1,81 @@
+/****************************************************************************
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+cc.INT_VALUE = 0;
+
+cc.FLOAT_VALUE = 1;
+
+cc.POINTER_VALUE = 2;
+
+cc.BOOL_VALUE = 3;
+
+cc.UNSIGNEDCHAR_VALUE = 4;
+
+
+cc.Color3BWapper = cc._Class.extend({
+ _color:null,
+ ctor:function () {
+ this._color = cc.color(0, 0, 0);
+ },
+ getColor:function () {
+ return this._color;
+ }
+});
+
+cc.Color3BWapper.create = function (color) {
+ var ret = new cc.Color3BWapper();
+ if (ret) {
+ ret._color.r = color.r;
+ ret._color.g = color.g;
+ ret._color.b = color.b;
+ }
+ return ret;
+};
+
+cc.BuilderValue = cc._Class.extend({
+ _value:null,
+ _type:0,
+
+ getIntValue:function () {
+ },
+ getFloatValue:function () {
+ },
+ getBoolValue:function () {
+ },
+ getByteValue:function () {
+ },
+ getPointer:function () {
+ },
+
+ getValue:function(){
+ return this._value;
+ }
+});
+
+cc.BuilderValue.create = function (value) {
+ return new cc.BuilderValue();
+};
+
diff --git a/extensions/ccb-reader/CCControlLoader.js b/extensions/ccb-reader/CCControlLoader.js
new file mode 100644
index 0000000000..901f8509dd
--- /dev/null
+++ b/extensions/ccb-reader/CCControlLoader.js
@@ -0,0 +1,318 @@
+/****************************************************************************
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+var PROPERTY_CCBFILE = "ccbFile";
+
+cc.BuilderFileLoader = cc.NodeLoader.extend({
+ _createCCNode:function (parent, ccbReader) {
+ return cc.BuilderFile.create();
+ },
+ onHandlePropTypeCCBFile:function (node, parent, propertyName, ccbFileNode, ccbReader) {
+ if (propertyName === PROPERTY_CCBFILE) {
+ node.setCCBFileNode(ccbFileNode);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeCCBFile.call(this, node, parent, propertyName, ccbFileNode, ccbReader);
+ }
+ }
+});
+
+cc.BuilderFileLoader.loader = function () {
+ return new cc.BuilderFileLoader();
+};
+
+var PROPERTY_ENABLED = "enabled";
+var PROPERTY_SELECTED = "selected";
+var PROPERTY_CCCONTROL = "ccControl";
+
+cc.ControlLoader = cc.NodeLoader.extend({
+ _createCCNode:function (parent, ccbReander) {
+ },
+ onHandlePropTypeBlockCCControl:function (node, parent, propertyName, blockCCControlData, ccbReader) {
+ if (propertyName === PROPERTY_CCCONTROL) {
+ node.addTargetWithActionForControlEvents(blockCCControlData.target, blockCCControlData.selCCControlHandler, blockCCControlData.controlEvents);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeBlockCCControl.call(this, node, parent, propertyName, blockCCControlData, ccbReader);
+ }
+ },
+ onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) {
+ if (propertyName === PROPERTY_ENABLED) {
+ node.setEnabled(check);
+ } else if (propertyName === PROPERTY_SELECTED) {
+ node.setSelected(check);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeCheck.call(this, node, parent, propertyName, check, ccbReader);
+ }
+ }
+});
+
+var PROPERTY_ZOOMONTOUCHDOWN = "zoomOnTouchDown";
+var PROPERTY_TITLE_NORMAL = "title|1";
+var PROPERTY_TITLE_HIGHLIGHTED = "title|2";
+var PROPERTY_TITLE_DISABLED = "title|3";
+var PROPERTY_TITLECOLOR_NORMAL = "titleColor|1";
+var PROPERTY_TITLECOLOR_HIGHLIGHTED = "titleColor|2";
+var PROPERTY_TITLECOLOR_DISABLED = "titleColor|3";
+var PROPERTY_TITLETTF_NORMAL = "titleTTF|1";
+var PROPERTY_TITLETTF_HIGHLIGHTED = "titleTTF|2";
+var PROPERTY_TITLETTF_DISABLED = "titleTTF|3";
+var PROPERTY_TITLETTFSIZE_NORMAL = "titleTTFSize|1";
+var PROPERTY_TITLETTFSIZE_HIGHLIGHTED = "titleTTFSize|2";
+var PROPERTY_TITLETTFSIZE_DISABLED = "titleTTFSize|4";
+var PROPERTY_LABELANCHORPOINT = "labelAnchorPoint";
+var PROPERTY_PREFEREDSIZE = "preferedSize"; // TODO Should be = "preferredSize". This is a typo in cocos2d-iphone, cocos2d-x and CocosBuilder!
+var PROPERTY_BACKGROUNDSPRITEFRAME_NORMAL = "backgroundSpriteFrame|1";
+var PROPERTY_BACKGROUNDSPRITEFRAME_HIGHLIGHTED = "backgroundSpriteFrame|2";
+var PROPERTY_BACKGROUNDSPRITEFRAME_DISABLED = "backgroundSpriteFrame|3";
+
+cc.ControlButtonLoader = cc.ControlLoader.extend({
+ _createCCNode:function (parent, ccbReader) {
+ return new cc.ControlButton();
+ },
+
+ onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) {
+ if (propertyName === PROPERTY_ZOOMONTOUCHDOWN) {
+ node.setZoomOnTouchDown(check);
+ } else {
+ cc.ControlLoader.prototype.onHandlePropTypeCheck.call(this, node, parent, propertyName, check, ccbReader);
+ }
+ },
+ onHandlePropTypeString:function (node, parent, propertyName, stringValue, ccbReader) {
+ if (propertyName === PROPERTY_TITLE_NORMAL) {
+ node.setTitleForState(stringValue, cc.CONTROL_STATE_NORMAL);
+ } else if (propertyName === PROPERTY_TITLE_HIGHLIGHTED) {
+ node.setTitleForState(stringValue, cc.CONTROL_STATE_HIGHLIGHTED);
+ } else if (propertyName === PROPERTY_TITLE_DISABLED) {
+ node.setTitleForState(stringValue, cc.CONTROL_STATE_DISABLED);
+ } else {
+ cc.ControlLoader.prototype.onHandlePropTypeString.call(this, node, parent, propertyName, stringValue, ccbReader);
+ }
+ },
+ onHandlePropTypeFontTTF:function (node, parent, propertyName, fontTTF, ccbReader) {
+ if (propertyName === PROPERTY_TITLETTF_NORMAL) {
+ node.setTitleTTFForState(fontTTF, cc.CONTROL_STATE_NORMAL);
+ } else if (propertyName === PROPERTY_TITLETTF_HIGHLIGHTED) {
+ node.setTitleTTFForState(fontTTF, cc.CONTROL_STATE_HIGHLIGHTED);
+ } else if (propertyName === PROPERTY_TITLETTF_DISABLED) {
+ node.setTitleTTFForState(fontTTF, cc.CONTROL_STATE_DISABLED);
+ } else {
+ cc.ControlLoader.prototype.onHandlePropTypeFontTTF.call(this, node, parent, propertyName, fontTTF, ccbReader);
+ }
+ },
+ onHandlePropTypeFloatScale:function (node, parent, propertyName, floatScale, ccbReader) {
+ if (propertyName === PROPERTY_TITLETTFSIZE_NORMAL) {
+ node.setTitleTTFSizeForState(floatScale, cc.CONTROL_STATE_NORMAL);
+ } else if (propertyName === PROPERTY_TITLETTFSIZE_HIGHLIGHTED) {
+ node.setTitleTTFSizeForState(floatScale, cc.CONTROL_STATE_HIGHLIGHTED);
+ } else if (propertyName === PROPERTY_TITLETTFSIZE_DISABLED) {
+ node.setTitleTTFSizeForState(floatScale, cc.CONTROL_STATE_DISABLED);
+ } else {
+ cc.ControlLoader.prototype.onHandlePropTypeFloatScale.call(this, node, parent, propertyName, floatScale, ccbReader);
+ }
+ },
+ onHandlePropTypePoint:function (node, parent, propertyName, point, ccbReader) {
+ if (propertyName === PROPERTY_LABELANCHORPOINT) {
+ node.setLabelAnchorPoint(point);
+ } else {
+ cc.ControlLoader.prototype.onHandlePropTypePoint.call(this, node, parent, propertyName, point, ccbReader);
+ }
+ },
+ onHandlePropTypeSize:function (node, parent, propertyName, size, ccbReader) {
+ if (propertyName === PROPERTY_PREFEREDSIZE) {
+ node.setPreferredSize(size);
+ } else {
+ cc.ControlLoader.prototype.onHandlePropTypeSize.call(this, node, parent, propertyName, size, ccbReader);
+ }
+ },
+ onHandlePropTypeSpriteFrame:function (node, parent, propertyName, spriteFrame, ccbReader) {
+ if (propertyName === PROPERTY_BACKGROUNDSPRITEFRAME_NORMAL) {
+ if (spriteFrame != null) {
+ node.setBackgroundSpriteFrameForState(spriteFrame, cc.CONTROL_STATE_NORMAL);
+ }
+ } else if (propertyName === PROPERTY_BACKGROUNDSPRITEFRAME_HIGHLIGHTED) {
+ if (spriteFrame != null) {
+ node.setBackgroundSpriteFrameForState(spriteFrame, cc.CONTROL_STATE_HIGHLIGHTED);
+ }
+ } else if (propertyName === PROPERTY_BACKGROUNDSPRITEFRAME_DISABLED) {
+ if (spriteFrame != null) {
+ node.setBackgroundSpriteFrameForState(spriteFrame, cc.CONTROL_STATE_DISABLED);
+ }
+ } else {
+ cc.ControlLoader.prototype.onHandlePropTypeSpriteFrame.call(this, node, parent, propertyName, spriteFrame, ccbReader);
+ }
+ },
+ onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) {
+ if (propertyName === PROPERTY_TITLECOLOR_NORMAL) {
+ node.setTitleColorForState(ccColor3B, cc.CONTROL_STATE_NORMAL);
+ } else if (propertyName === PROPERTY_TITLECOLOR_HIGHLIGHTED) {
+ node.setTitleColorForState(ccColor3B, cc.CONTROL_STATE_HIGHLIGHTED);
+ } else if (propertyName === PROPERTY_TITLECOLOR_DISABLED) {
+ node.setTitleColorForState(ccColor3B, cc.CONTROL_STATE_DISABLED);
+ } else {
+ cc.ControlLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, ccColor3B, ccbReader);
+ }
+ }
+});
+
+cc.ControlButtonLoader.loader = function () {
+ return new cc.ControlButtonLoader();
+};
+
+var PROPERTY_CONTAINER = "container";
+var PROPERTY_DIRECTION = "direction";
+var PROPERTY_CLIPSTOBOUNDS = "clipsToBounds";
+var PROPERTY_BOUNCES = "bounces";
+var PROPERTY_SCALE = "scale";
+
+cc.ScrollViewLoader = cc.NodeLoader.extend({
+ _createCCNode:function (parent, ccbReader) {
+ return new cc.ScrollView();
+ },
+
+ onHandlePropTypeSize:function(node,parent,propertyName,size,ccbReader){
+ if(propertyName === PROPERTY_CONTENTSIZE){
+ node.setViewSize(size);
+ }else{
+ cc.NodeLoader.prototype.onHandlePropTypeSize.call(this, node,parent,propertyName,size,ccbReader);
+ }
+ },
+
+ onHandlePropTypeCCBFile:function (node, parent, propertyName, ccbFileNode, ccbReader) {
+ if (propertyName === PROPERTY_CONTAINER) {
+ node.setContainer(ccbFileNode);
+ node.updateInset();
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeCCBFile.call(this, node, parent, propertyName, ccbFileNode, ccbReader);
+ }
+ },
+ onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) {
+ if (propertyName === PROPERTY_CLIPSTOBOUNDS) {
+ node.setClippingToBounds(check);
+ } else if (propertyName === PROPERTY_BOUNCES) {
+ node.setBounceable(check);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeCheck.call(this, node, parent, propertyName, check, ccbReader);
+ }
+ },
+ onHandlePropTypeFloat:function (node, parent, propertyName, floatValue, ccbReader) {
+ if (propertyName === PROPERTY_SCALE) {
+ node.setScale(floatValue);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeFloat.call(this, node, parent, propertyName, floatValue, ccbReader);
+ }
+ },
+ onHandlePropTypeIntegerLabeled:function (node, parent, propertyName, integerLabeled, ccbReader) {
+ if (propertyName === PROPERTY_DIRECTION) {
+ node.setDirection(integerLabeled);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeIntegerLabeled.call(this, node, parent, propertyName, integerLabeled, ccbReader);
+ }
+ }
+});
+
+cc.ScrollViewLoader.loader = function () {
+ return new cc.ScrollViewLoader();
+};
+
+var PROPERTY_CONTENTSIZE = "contentSize";
+var PROPERTY_SPRITEFRAME = "spriteFrame";
+var PROPERTY_COLOR = "color";
+var PROPERTY_OPACITY = "opacity";
+var PROPERTY_BLENDFUNC = "blendFunc";
+var PROPERTY_INSETLEFT = "insetLeft";
+var PROPERTY_INSETTOP = "insetTop" ;
+var PROPERTY_INSETRIGHT = "insetRight";
+var PROPERTY_INSETBOTTOM = "insetBottom";
+
+cc.Scale9SpriteLoader = cc.NodeLoader.extend({
+ _createCCNode:function(parent,ccbReader){
+ var sprite = new cc.Scale9Sprite();
+
+ sprite.setAnchorPoint(0, 0);
+
+ return sprite;
+ },
+
+ onHandlePropTypeColor3:function(node, parent, propertyName, ccColor3B,ccbReader){
+ if(propertyName === PROPERTY_COLOR) {
+ if(ccColor3B.r !== 255 || ccColor3B.g !== 255 || ccColor3B.b !== 255){
+ node.setColor(ccColor3B);
+ }
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, ccColor3B,ccbReader);
+ }
+ },
+ onHandlePropTypeByte:function(node, parent, propertyName, byteValue,ccbReader){
+ if(propertyName === PROPERTY_OPACITY) {
+ node.setOpacity(byteValue);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeByte.call(this, node, parent, propertyName, byteValue,ccbReader);
+ }
+ },
+ onHandlePropTypeBlendFunc:function(node, parent, propertyName, ccBlendFunc,ccbReader){
+ if(propertyName === PROPERTY_BLENDFUNC) {
+ // TODO Not exported by CocosBuilder yet!
+ // node.setBlendFunc(ccBlendFunc);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccBlendFunc,ccbReader);
+ }
+ },
+ onHandlePropTypeSpriteFrame:function(node, parent, propertyName, spriteFrame,ccbReader){
+ if(propertyName === PROPERTY_SPRITEFRAME) {
+ node.setSpriteFrame(spriteFrame);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeSpriteFrame.call(this, node, parent, propertyName, spriteFrame,ccbReader);
+ }
+ },
+ onHandlePropTypeSize:function(node, parent, propertyName, size,ccbReader){
+ if(propertyName === PROPERTY_CONTENTSIZE) {
+ //node.setContentSize(size);
+ } else if(propertyName === PROPERTY_PREFEREDSIZE) {
+ node.setPreferredSize(size);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeSize.call(this, node, parent, propertyName, size,ccbReader);
+ }
+ },
+ onHandlePropTypeFloat:function(node, parent, propertyName, floatValue,ccbReader){
+ if(propertyName === PROPERTY_INSETLEFT) {
+ node.setInsetLeft(floatValue);
+ } else if(propertyName === PROPERTY_INSETTOP) {
+ node.setInsetTop(floatValue);
+ } else if(propertyName === PROPERTY_INSETRIGHT) {
+ node.setInsetRight(floatValue);
+ } else if(propertyName === PROPERTY_INSETBOTTOM) {
+ node.setInsetBottom(floatValue);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeFloat.call(this, node, parent, propertyName, floatValue,ccbReader);
+ }
+ }
+});
+
+cc.Scale9SpriteLoader.loader = function(){
+ return new cc.Scale9SpriteLoader();
+};
+
+
+
diff --git a/extensions/ccb-reader/CCNodeLoader.js b/extensions/ccb-reader/CCNodeLoader.js
new file mode 100644
index 0000000000..cbfb833aec
--- /dev/null
+++ b/extensions/ccb-reader/CCNodeLoader.js
@@ -0,0 +1,904 @@
+/****************************************************************************
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+var PROPERTY_POSITION = "position";
+var PROPERTY_CONTENTSIZE = "contentSize";
+var PROPERTY_SKEW = "skew";
+var PROPERTY_ANCHORPOINT = "anchorPoint";
+var PROPERTY_SCALE = "scale";
+var PROPERTY_ROTATION = "rotation";
+var PROPERTY_TAG = "tag";
+var PROPERTY_IGNOREANCHORPOINTFORPOSITION = "ignoreAnchorPointForPosition";
+var PROPERTY_VISIBLE = "visible";
+
+var ASSERT_FAIL_UNEXPECTED_PROPERTY = function (propertyName) {
+ cc.log("Unexpected property: '" + propertyName + "'!");
+};
+
+var ASSERT_FAIL_UNEXPECTED_PROPERTYTYPE = function (propertyName) {
+ cc.log("Unexpected property type: '" + propertyName + "'!");
+};
+
+function BlockData(selMenuHander, target) {
+ this.selMenuHander = selMenuHander;
+ this.target = target;
+}
+
+function BlockCCControlData(selCCControlHandler, target, controlEvents) {
+ this.selCCControlHandler = selCCControlHandler;
+ this.target = target;
+ this.controlEvents = controlEvents;
+}
+
+cc.NodeLoader = cc._Class.extend({
+ _customProperties:null,
+
+ ctor:function(){
+ this._customProperties = new cc._Dictionary();
+ },
+
+ loadCCNode:function (parent, ccbReader) {
+ return this._createCCNode(parent, ccbReader);
+ //this.parseProperties(node, parent, ccbReader);
+ //return node;
+ },
+
+ parseProperties:function (node, parent, ccbReader) {
+ var numRegularProps = ccbReader.readInt(false);
+ var numExturaProps = ccbReader.readInt(false);
+ var propertyCount = numRegularProps + numExturaProps;
+
+ for (var i = 0; i < propertyCount; i++) {
+ var isExtraProp = (i >= numRegularProps);
+ var type = ccbReader.readInt(false);
+ var propertyName = ccbReader.readCachedString();
+
+ // Check if the property can be set for this platform
+ var setProp = false;
+
+ var platform = ccbReader.readByte();
+ if ((platform === CCB_PLATFORM_ALL) ||(platform === CCB_PLATFORM_IOS) ||(platform === CCB_PLATFORM_MAC) )
+ setProp = true;
+
+ //forward properties for sub ccb files
+ if(node instanceof cc.BuilderFile){
+ if(node.getCCBFileNode() && isExtraProp){
+ node = node.getCCBFileNode();
+ //skip properties that doesn't have a value to override
+ var getExtraPropsNames = node.userObject;
+ setProp = getExtraPropsNames.indexOf(propertyName) !== -1;
+ }
+ } else if(isExtraProp && node === ccbReader.getAnimationManager().getRootNode()){
+ var extraPropsNames = node.userObject;
+ if(!extraPropsNames){
+ extraPropsNames = [];
+ node.userObject = extraPropsNames;
+ }
+ extraPropsNames.push(propertyName);
+ }
+
+ switch (type) {
+ case CCB_PROPTYPE_POSITION:
+ {
+ var position = this.parsePropTypePosition(node, parent, ccbReader, propertyName);
+ if (setProp)
+ this.onHandlePropTypePosition(node, parent, propertyName, position, ccbReader);
+ break;
+ }
+ case CCB_PROPTYPE_POINT:
+ {
+ var point = this.parsePropTypePoint(node, parent, ccbReader);
+ if (setProp)
+ this.onHandlePropTypePoint(node, parent, propertyName, point, ccbReader);
+ break;
+ }
+ case CCB_PROPTYPE_POINTLOCK:
+ {
+ var pointLock = this.parsePropTypePointLock(node, parent, ccbReader);
+ if (setProp)
+ this.onHandlePropTypePointLock(node, parent, propertyName, pointLock, ccbReader);
+ break;
+ }
+ case CCB_PROPTYPE_SIZE:
+ {
+ var size = this.parsePropTypeSize(node, parent, ccbReader);
+ if (setProp)
+ this.onHandlePropTypeSize(node, parent, propertyName, size, ccbReader);
+ break;
+ }
+ case CCB_PROPTYPE_SCALELOCK:
+ {
+ var scaleLock = this.parsePropTypeScaleLock(node, parent, ccbReader, propertyName);
+ if (setProp)
+ this.onHandlePropTypeScaleLock(node, parent, propertyName, scaleLock, ccbReader);
+ break;
+ }
+ case CCB_PROPTYPE_FLOATXY:
+ {
+ var xy = this.parsePropTypeFloatXY(node, parent, ccbReader);
+ if (setProp)
+ this.onHandlePropTypeFloatXY(node, parent, propertyName, xy, ccbReader);
+ break;
+ }
+
+ case CCB_PROPTYPE_FLOAT:
+ {
+ var f = this.parsePropTypeFloat(node, parent, ccbReader);
+ if (setProp) {
+ this.onHandlePropTypeFloat(node, parent, propertyName, f, ccbReader);
+ }
+ break;
+ }
+ case CCB_PROPTYPE_DEGREES:
+ {
+ var degrees = this.parsePropTypeDegrees(node, parent, ccbReader, propertyName);
+ if (setProp) {
+ this.onHandlePropTypeDegrees(node, parent, propertyName, degrees, ccbReader);
+ }
+ break;
+ }
+ case CCB_PROPTYPE_FLOATSCALE:
+ {
+ var floatScale = this.parsePropTypeFloatScale(node, parent, ccbReader);
+ if (setProp) {
+ this.onHandlePropTypeFloatScale(node, parent, propertyName, floatScale, ccbReader);
+ }
+ break;
+ }
+ case CCB_PROPTYPE_INTEGER:
+ {
+ var integer = this.parsePropTypeInteger(node, parent, ccbReader);
+ if (setProp) {
+ this.onHandlePropTypeInteger(node, parent, propertyName, integer, ccbReader);
+ }
+ break;
+ }
+ case CCB_PROPTYPE_INTEGERLABELED:
+ {
+ var integerLabeled = this.parsePropTypeIntegerLabeled(node, parent, ccbReader);
+ if (setProp) {
+ this.onHandlePropTypeIntegerLabeled(node, parent, propertyName, integerLabeled, ccbReader);
+ }
+ break;
+ }
+ case CCB_PROPTYPE_FLOATVAR:
+ {
+ var floatVar = this.parsePropTypeFloatVar(node, parent, ccbReader);
+ if (setProp) {
+ this.onHandlePropTypeFloatVar(node, parent, propertyName, floatVar, ccbReader);
+ }
+ break;
+ }
+ case CCB_PROPTYPE_CHECK:
+ {
+ var check = this.parsePropTypeCheck(node, parent, ccbReader, propertyName);
+ if (setProp) {
+ this.onHandlePropTypeCheck(node, parent, propertyName, check, ccbReader);
+ }
+ break;
+ }
+ case CCB_PROPTYPE_SPRITEFRAME:
+ {
+ var ccSpriteFrame = this.parsePropTypeSpriteFrame(node, parent, ccbReader, propertyName);
+ if (setProp) {
+ this.onHandlePropTypeSpriteFrame(node, parent, propertyName, ccSpriteFrame, ccbReader);
+ }
+ break;
+ }
+ case CCB_PROPTYPE_ANIMATION:
+ {
+ var ccAnimation = this.parsePropTypeAnimation(node, parent, ccbReader);
+ if (setProp) {
+ this.onHandlePropTypeAnimation(node, parent, propertyName, ccAnimation, ccbReader);
+ }
+ break;
+ }
+ case CCB_PROPTYPE_TEXTURE:
+ {
+ var ccTexture2D = this.parsePropTypeTexture(node, parent, ccbReader);
+ if (setProp) {
+ this.onHandlePropTypeTexture(node, parent, propertyName, ccTexture2D, ccbReader);
+ }
+ break;
+ }
+ case CCB_PROPTYPE_BYTE:
+ {
+ var byteValue = this.parsePropTypeByte(node, parent, ccbReader, propertyName);
+ if (setProp) {
+ this.onHandlePropTypeByte(node, parent, propertyName, byteValue, ccbReader);
+ }
+ break;
+ }
+ case CCB_PROPTYPE_COLOR3:
+ {
+ var color = this.parsePropTypeColor3(node, parent, ccbReader, propertyName);
+ if (setProp) {
+ this.onHandlePropTypeColor3(node, parent, propertyName, color, ccbReader);
+ }
+ break;
+ }
+ case CCB_PROPTYPE_COLOR4VAR:
+ {
+ var color4FVar = this.parsePropTypeColor4FVar(node, parent, ccbReader);
+ if (setProp) {
+ this.onHandlePropTypeColor4FVar(node, parent, propertyName, color4FVar, ccbReader);
+ }
+ break;
+ }
+ case CCB_PROPTYPE_FLIP:
+ {
+ var flip = this.parsePropTypeFlip(node, parent, ccbReader);
+ if (setProp) {
+ this.onHandlePropTypeFlip(node, parent, propertyName, flip, ccbReader);
+ }
+ break;
+ }
+ case CCB_PROPTYPE_BLENDMODE:
+ {
+ var blendFunc = this.parsePropTypeBlendFunc(node, parent, ccbReader);
+ if (setProp) {
+ this.onHandlePropTypeBlendFunc(node, parent, propertyName, blendFunc, ccbReader);
+ }
+ break;
+ }
+ case CCB_PROPTYPE_FNTFILE:
+ {
+ var fntFile = ccbReader.getCCBRootPath() + this.parsePropTypeFntFile(node, parent, ccbReader);
+ if (setProp) {
+ this.onHandlePropTypeFntFile(node, parent, propertyName, fntFile, ccbReader);
+ }
+ break;
+ }
+ case CCB_PROPTYPE_FONTTTF:
+ {
+ var fontTTF = this.parsePropTypeFontTTF(node, parent, ccbReader);
+ if (setProp) {
+ this.onHandlePropTypeFontTTF(node, parent, propertyName, fontTTF, ccbReader);
+ }
+ break;
+ }
+ case CCB_PROPTYPE_STRING:
+ {
+ var stringValue = this.parsePropTypeString(node, parent, ccbReader);
+ if (setProp) {
+ this.onHandlePropTypeString(node, parent, propertyName, stringValue, ccbReader);
+ }
+ break;
+ }
+ case CCB_PROPTYPE_TEXT:
+ {
+ var textValue = this.parsePropTypeText(node, parent, ccbReader);
+ if (setProp) {
+ this.onHandlePropTypeText(node, parent, propertyName, textValue, ccbReader);
+ }
+ break;
+ }
+ case CCB_PROPTYPE_BLOCK:
+ {
+ var blockData = this.parsePropTypeBlock(node, parent, ccbReader);
+ if (setProp) {
+ this.onHandlePropTypeBlock(node, parent, propertyName, blockData, ccbReader);
+ }
+ break;
+ }
+ case CCB_PROPTYPE_BLOCKCCCONTROL:
+ {
+ var blockCCControlData = this.parsePropTypeBlockCCControl(node, parent, ccbReader);
+ if (setProp && blockCCControlData != null) {
+ this.onHandlePropTypeBlockCCControl(node, parent, propertyName, blockCCControlData, ccbReader);
+ }
+ break;
+ }
+ case CCB_PROPTYPE_CCBFILE:
+ {
+ var ccbFileNode = this.parsePropTypeCCBFile(node, parent, ccbReader);
+ if (setProp) {
+ this.onHandlePropTypeCCBFile(node, parent, propertyName, ccbFileNode, ccbReader);
+ }
+ break;
+ }
+ default:
+ ASSERT_FAIL_UNEXPECTED_PROPERTYTYPE(type);
+ break;
+ }
+ }
+ },
+
+ getCustomProperties:function(){
+ return this._customProperties;
+ },
+
+ _createCCNode:function (parent, ccbReader) {
+ return new cc.Node();
+ },
+
+ parsePropTypePosition:function (node, parent, ccbReader, propertyName) {
+ var x = ccbReader.readFloat();
+ var y = ccbReader.readFloat();
+
+ var type = ccbReader.readInt(false);
+
+ var containerSize = ccbReader.getAnimationManager().getContainerSize(parent);
+ var pt = cc._getAbsolutePosition(x,y,type,containerSize,propertyName);
+ node.setPosition(cc.getAbsolutePosition(pt,type,containerSize,propertyName)); //different to -x node.setPosition(pt);
+
+ if(ccbReader.getAnimatedProperties().indexOf(propertyName) > -1){
+ var baseValue = [x,y,type];
+ ccbReader.getAnimationManager().setBaseValue(baseValue,node,propertyName);
+ }
+
+ return pt;
+ },
+
+ parsePropTypePoint:function (node, parent, ccbReader) {
+ var x = ccbReader.readFloat();
+ var y = ccbReader.readFloat();
+
+ return cc.p(x, y);
+ },
+
+ parsePropTypePointLock:function (node, parent, ccbReader) {
+ var x = ccbReader.readFloat();
+ var y = ccbReader.readFloat();
+
+ return cc.p(x, y);
+ },
+
+ parsePropTypeSize:function (node, parent, ccbReader) {
+ var width = ccbReader.readFloat();
+ var height = ccbReader.readFloat();
+
+ var type = ccbReader.readInt(false);
+
+ var containerSize = ccbReader.getAnimationManager().getContainerSize(parent);
+
+ switch (type) {
+ case CCB_SIZETYPE_ABSOLUTE:
+ /* Nothing. */
+ break;
+ case CCB_SIZETYPE_RELATIVE_CONTAINER:
+ width = containerSize.width - width;
+ height = containerSize.height - height;
+ break;
+ case CCB_SIZETYPE_PERCENT:
+ width = (containerSize.width * width / 100.0);
+ height = (containerSize.height * height / 100.0);
+ break;
+ case CCB_SIZETYPE_HORIZONTAL_PERCENT:
+ width = (containerSize.width * width / 100.0);
+ break;
+ case CCB_SIZETYPE_VERTICAL_PERCENT:
+ height = (containerSize.height * height / 100.0);
+ break;
+ case CCB_SIZETYPE_MULTIPLY_RESOLUTION:
+ var resolutionScale = cc.BuilderReader.getResolutionScale();
+ width *= resolutionScale;
+ height *= resolutionScale;
+ break;
+ default:
+ cc.log("Unknown CCB type.");
+ break;
+ }
+
+ return cc.size(width, height);
+ },
+
+ parsePropTypeScaleLock:function (node, parent, ccbReader, propertyName) {
+ var x = ccbReader.readFloat();
+ var y = ccbReader.readFloat();
+
+ var type = ccbReader.readInt(false);
+
+ cc.setRelativeScale(node,x,y,type,propertyName);
+
+ if(ccbReader.getAnimatedProperties().indexOf(propertyName) > -1){
+ ccbReader.getAnimationManager().setBaseValue([x,y,type],node,propertyName);
+ }
+
+ if (type === CCB_SCALETYPE_MULTIPLY_RESOLUTION) {
+ x *= cc.BuilderReader.getResolutionScale();
+ y *= cc.BuilderReader.getResolutionScale();
+ }
+
+ return [x, y];
+ },
+
+ parsePropTypeFloat:function (node, parent, ccbReader) {
+ return ccbReader.readFloat();
+ },
+
+ parsePropTypeDegrees:function (node, parent, ccbReader, propertyName) {
+ var ret = ccbReader.readFloat();
+ if(ccbReader.getAnimatedProperties().indexOf(propertyName) > -1){
+ ccbReader.getAnimationManager().setBaseValue(ret,node, propertyName);
+ }
+ return ret;
+ },
+
+ parsePropTypeFloatScale:function (node, parent, ccbReader) {
+ var f = ccbReader.readFloat();
+
+ var type = ccbReader.readInt(false);
+
+ if (type === CCB_SCALETYPE_MULTIPLY_RESOLUTION) {
+ f *= cc.BuilderReader.getResolutionScale();
+ }
+
+ return f;
+ },
+
+ parsePropTypeInteger:function (node, parent, ccbReader) {
+ return ccbReader.readInt(true);
+ },
+
+ parsePropTypeIntegerLabeled:function (node, parent, ccbReader) {
+ return ccbReader.readInt(true);
+ },
+
+ parsePropTypeFloatVar:function (node, parent, ccbReader) {
+ var f = ccbReader.readFloat();
+ var fVar = ccbReader.readFloat();
+ return [f, fVar];
+ },
+
+ parsePropTypeCheck:function (node, parent, ccbReader, propertyName) {
+ var ret = ccbReader.readBool();
+ if(ccbReader.getAnimatedProperties().indexOf(propertyName) > -1){
+ ccbReader.getAnimationManager().setBaseValue(ret,node, propertyName);
+ }
+ return ret;
+ },
+
+ parsePropTypeSpriteFrame:function (node, parent, ccbReader, propertyName) {
+ var spriteSheet = ccbReader.readCachedString();
+ var spriteFile = ccbReader.readCachedString();
+
+ var spriteFrame;
+ if(spriteFile != null && spriteFile.length !== 0){
+ if(spriteSheet.length === 0){
+ spriteFile = ccbReader.getCCBRootPath() + spriteFile;
+ var texture = cc.textureCache.addImage(spriteFile);
+
+ var locContentSize = texture.getContentSize();
+ var bounds = cc.rect(0, 0, locContentSize.width, locContentSize.height);
+ spriteFrame = new cc.SpriteFrame(texture, bounds);
+ } else {
+ var frameCache = cc.spriteFrameCache;
+ spriteSheet = ccbReader.getCCBRootPath() + spriteSheet;
+ //load the sprite sheet only if it is not loaded
+ if(ccbReader.getLoadedSpriteSheet().indexOf(spriteSheet) === -1){
+ frameCache.addSpriteFrames(spriteSheet);
+ ccbReader.getLoadedSpriteSheet().push(spriteSheet);
+ }
+ spriteFrame = frameCache.getSpriteFrame(spriteFile);
+ }
+ if(ccbReader.getAnimatedProperties().indexOf(propertyName) > -1){
+ ccbReader.getAnimationManager().setBaseValue(spriteFrame,node,propertyName);
+ }
+ }
+
+ return spriteFrame;
+ },
+
+ parsePropTypeAnimation:function (node, parent, ccbReader) {
+ var animationFile = ccbReader.getCCBRootPath() + ccbReader.readCachedString();
+ var animation = ccbReader.readCachedString();
+
+ var ccAnimation = null;
+
+ // Support for stripping relative file paths, since ios doesn't currently
+ // know what to do with them, since its pulling from bundle.
+ // Eventually this should be handled by a client side asset manager
+ // interface which figured out what resources to load.
+ // TODO Does this problem exist in C++?
+ animation = cc.BuilderReader.lastPathComponent(animation);
+ animationFile = cc.BuilderReader.lastPathComponent(animationFile);
+
+ if (animation != null && animation !== "") {
+ var animationCache = cc.animationCache;
+ animationCache.addAnimations(animationFile);
+
+ ccAnimation = animationCache.getAnimation(animation);
+ }
+ return ccAnimation;
+ },
+
+ parsePropTypeTexture:function (node, parent, ccbReader) {
+ var spriteFile = ccbReader.getCCBRootPath() + ccbReader.readCachedString();
+
+ if(spriteFile !== "")
+ return cc.textureCache.addImage(spriteFile);
+ return null;
+ },
+
+ parsePropTypeByte:function (node, parent, ccbReader, propertyName) {
+ var ret = ccbReader.readByte();
+ if(ccbReader.getAnimatedProperties().indexOf(propertyName) > -1){
+ ccbReader.getAnimationManager().setBaseValue(ret,node, propertyName);
+ }
+ return ret;
+ },
+
+ parsePropTypeColor3:function (node, parent, ccbReader, propertyName) {
+ var red = ccbReader.readByte();
+ var green = ccbReader.readByte();
+ var blue = ccbReader.readByte();
+ var color = {r:red, g:green, b:blue };
+ if(ccbReader.getAnimatedProperties().indexOf(propertyName) > -1){
+ ccbReader.getAnimationManager().setBaseValue(cc.Color3BWapper.create(color),node, propertyName);
+ }
+ return color;
+ },
+
+ parsePropTypeColor4FVar:function (node, parent, ccbReader) {
+ //TODO Color4F doesn't supports on HTML5
+ var red = 0 | (ccbReader.readFloat() * 255);
+ var green = 0 | (ccbReader.readFloat() * 255);
+ var blue = 0 | (ccbReader.readFloat() * 255);
+ var alpha = ccbReader.readFloat();
+ alpha = alpha <= 1 ? (0 | (alpha * 255)) : alpha;
+ var redVar = 0 | (ccbReader.readFloat() * 255);
+ var greenVar = 0 | (ccbReader.readFloat() * 255);
+ var blueVar = 0 | (ccbReader.readFloat() * 255);
+ var alphaVar = ccbReader.readFloat();
+ alphaVar = alphaVar <= 1 ? (0 | (alphaVar * 255)) : alphaVar;
+
+ var colors = [];
+ colors[0] = {r:red, g:green, b:blue, a:alpha};
+ colors[1] = {r:redVar, g:greenVar, b:blueVar, a:alphaVar};
+
+ return colors;
+ },
+
+ parsePropTypeFlip:function (node, parent, ccbReader) {
+ var flipX = ccbReader.readBool();
+ var flipY = ccbReader.readBool();
+
+ return [flipX, flipY];
+ },
+
+ parsePropTypeBlendFunc:function (node, parent, ccbReader) {
+ var source = ccbReader.readInt(false);
+ var destination = ccbReader.readInt(false);
+
+ return new cc.BlendFunc(source, destination);
+ },
+
+ parsePropTypeFntFile:function (node, parent, ccbReader) {
+ return ccbReader.readCachedString();
+ },
+
+ parsePropTypeString:function (node, parent, ccbReader) {
+ return ccbReader.readCachedString();
+ },
+
+ parsePropTypeText:function (node, parent, ccbReader) {
+ return ccbReader.readCachedString();
+ },
+
+ parsePropTypeFontTTF:function (node, parent, ccbReader) {
+ return ccbReader.readCachedString();
+ //var ttfEnding = ".ttf";
+
+ //TODO Fix me if it is wrong
+ /* If the fontTTF comes with the ".ttf" extension, prepend the absolute path.
+ * System fonts come without the ".ttf" extension and do not need the path prepended. */
+ /*if (cc.CCBReader.endsWith(fontTTF.toLowerCase(), ttfEnding)) {
+ fontTTF = ccbReader.getCCBRootPath() + fontTTF;
+ }*/
+ },
+
+ parsePropTypeBlock:function (node, parent, ccbReader) {
+ var selectorName = ccbReader.readCachedString();
+ var selectorTarget = ccbReader.readInt(false);
+
+ if (selectorTarget !== CCB_TARGETTYPE_NONE) {
+ var target = null;
+ if(!ccbReader.isJSControlled()) {
+ if (selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT) {
+ target = ccbReader.getAnimationManager().getRootNode();
+ } else if (selectorTarget === CCB_TARGETTYPE_OWNER) {
+ target = ccbReader.getOwner();
+ }
+
+ if (target !== null) {
+ if (selectorName.length > 0) {
+ var selMenuHandler = 0;
+
+ //var targetAsCCBSelectorResolver = target;
+ if (target.onResolveCCBCCMenuItemSelector)
+ selMenuHandler = target.onResolveCCBCCMenuItemSelector(target, selectorName);
+
+ if (selMenuHandler === 0) {
+ var ccbSelectorResolver = ccbReader.getCCBSelectorResolver();
+ if (ccbSelectorResolver != null)
+ selMenuHandler = ccbSelectorResolver.onResolveCCBCCMenuItemSelector(target, selectorName);
+ }
+
+ if (selMenuHandler === 0) {
+ cc.log("Skipping selector '" +selectorName+ "' since no CCBSelectorResolver is present.");
+ } else {
+ return new BlockData(selMenuHandler,target);
+ }
+ } else {
+ cc.log("Unexpected empty selector.");
+ }
+ } else {
+ cc.log("Unexpected NULL target for selector.");
+ }
+ } else {
+ if(selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT){
+ ccbReader.addDocumentCallbackNode(node);
+ ccbReader.addDocumentCallbackName(selectorName);
+ ccbReader.addDocumentCallbackControlEvents(0);
+ } else {
+ ccbReader.addOwnerCallbackNode(node);
+ ccbReader.addOwnerCallbackName(selectorName);
+ ccbReader.addOwnerCallbackControlEvents(0);
+ }
+ }
+ }
+ return null;
+ },
+
+ parsePropTypeBlockCCControl:function (node, parent, ccbReader) {
+ var selectorName = ccbReader.readCachedString();
+ var selectorTarget = ccbReader.readInt(false);
+ var controlEvents = ccbReader.readInt(false);
+
+ if (selectorTarget !== CCB_TARGETTYPE_NONE) {
+ if(!ccbReader.isJSControlled()){
+ var target = null;
+ if (selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT) {
+ target = ccbReader.getAnimationManager().getRootNode();
+ } else if (selectorTarget === CCB_TARGETTYPE_OWNER) {
+ target = ccbReader.getOwner();
+ }
+
+ if (target !== null) {
+ if (selectorName.length > 0) {
+ var selCCControlHandler = 0;
+
+ if (target.onResolveCCBCCControlSelector) {
+ selCCControlHandler = target.onResolveCCBCCControlSelector(target, selectorName);
+ }
+ if (selCCControlHandler === 0) {
+ var ccbSelectorResolver = ccbReader.getCCBSelectorResolver();
+ if (ccbSelectorResolver != null) {
+ selCCControlHandler = ccbSelectorResolver.onResolveCCBCCControlSelector(target, selectorName);
+ }
+ }
+
+ if (selCCControlHandler === 0) {
+ cc.log("Skipping selector '" + selectorName + "' since no CCBSelectorResolver is present.");
+ } else {
+ return new BlockCCControlData(selCCControlHandler,target,controlEvents);
+ }
+ } else {
+ cc.log("Unexpected empty selector.");
+ }
+ } else {
+ cc.log("Unexpected NULL target for selector.");
+ }
+ } else {
+ if(selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT){
+ ccbReader.addDocumentCallbackNode(node);
+ ccbReader.addDocumentCallbackName(selectorName);
+ ccbReader.addDocumentCallbackControlEvents(controlEvents);
+ } else {
+ ccbReader.addOwnerCallbackNode(node);
+ ccbReader.addOwnerCallbackName(selectorName);
+ ccbReader.addOwnerCallbackControlEvents(controlEvents);
+ }
+ }
+ }
+ return null;
+ },
+
+ parsePropTypeCCBFile:function (node, parent, ccbReader) {
+ var ccbFileName = ccbReader.getCCBRootPath() + ccbReader.readCachedString();
+
+ /* Change path extension to .ccbi. */
+ var ccbFileWithoutPathExtension = cc.BuilderReader.deletePathExtension(ccbFileName);
+ ccbFileName = ccbFileWithoutPathExtension + ".ccbi";
+
+ var myCCBReader = new cc.BuilderReader(ccbReader);
+
+ var bytes = cc.loader.getRes(ccbFileName);
+ if(!bytes){
+ var realUrl = cc.loader.getUrl(ccbFileName);
+ bytes = cc.loader.loadBinarySync(realUrl);
+ cc.loader.cache[ccbFileName] = bytes;
+ }
+
+ myCCBReader.initWithData(bytes,ccbReader.getOwner());
+ myCCBReader.getAnimationManager().setRootContainerSize(parent.getContentSize());
+ myCCBReader.setAnimationManagers(ccbReader.getAnimationManagers());
+
+ myCCBReader.getAnimationManager().setOwner(ccbReader.getOwner());
+ var ccbFileNode = myCCBReader.readFileWithCleanUp(false);
+ ccbReader.setAnimationManagers(myCCBReader.getAnimationManagers());
+
+ if(ccbFileNode && myCCBReader.getAnimationManager().getAutoPlaySequenceId() !== -1)
+ myCCBReader.getAnimationManager().runAnimations(myCCBReader.getAnimationManager().getAutoPlaySequenceId(),0);
+
+ return ccbFileNode;
+ },
+
+ parsePropTypeFloatXY:function(node, parent, ccbReader){
+ var x = ccbReader.readFloat();
+ var y = ccbReader.readFloat();
+ return [x,y];
+ },
+
+ onHandlePropTypePosition:function (node, parent, propertyName, position, ccbReader) {
+ if (propertyName === PROPERTY_POSITION) {
+ node.setPosition(position);
+ } else {
+ ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
+ }
+ },
+
+ onHandlePropTypePoint:function (node, parent, propertyName, position, ccbReader) {
+ if (propertyName === PROPERTY_ANCHORPOINT) {
+ node.setAnchorPoint(position);
+ } else {
+ ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
+ }
+ },
+
+ onHandlePropTypePointLock:function (node, parent, propertyName, pointLock, ccbReader) {
+ ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
+ },
+
+ onHandlePropTypeSize:function (node, parent, propertyName, sizeValue, ccbReader) {
+ if (propertyName === PROPERTY_CONTENTSIZE) {
+ node.setContentSize(sizeValue);
+ } else {
+ ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
+ }
+ },
+
+ onHandlePropTypeScaleLock:function (node, parent, propertyName, scaleLock, ccbReader) {
+ if (propertyName === PROPERTY_SCALE) {
+ node.setScaleX(scaleLock[0]);
+ node.setScaleY(scaleLock[1]);
+ } else {
+ ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
+ }
+ },
+ onHandlePropTypeFloatXY: function (node, parent, propertyName, xy, ccbReader) {
+ if (propertyName === PROPERTY_SKEW) {
+ node.setSkewX(xy[0]);
+ node.setSkewY(xy[1]);
+ } else {
+ var nameX = propertyName + "X";
+ var nameY = propertyName + "Y";
+ if (!node[nameX] || !node[nameY])
+ ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
+ //TODO throw an error when source code was confused
+ node[nameX](xy[0]);
+ node[nameY](xy[1]);
+ }
+ },
+ onHandlePropTypeFloat:function (node, parent, propertyName, floatValue, ccbReader) {
+ //ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
+ // It may be a custom property, add it to custom property dictionary.
+ this._customProperties.setObject(floatValue, propertyName);
+ },
+
+ onHandlePropTypeDegrees:function (node, parent, propertyName, degrees, ccbReader) {
+ if (propertyName === PROPERTY_ROTATION) {
+ node.setRotation(degrees);
+ } else {
+ ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
+ }
+ },
+
+ onHandlePropTypeFloatScale:function (node, parent, propertyName, floatScale, ccbReader) {
+ ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
+ },
+
+ onHandlePropTypeInteger:function (node, parent, propertyName, integer, ccbReader) {
+ if (propertyName === PROPERTY_TAG) {
+ node.setTag(integer);
+ } else {
+ ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
+ }
+ },
+
+ onHandlePropTypeIntegerLabeled:function (node, parent, propertyName, integerLabeled, ccbReader) {
+ ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
+ },
+
+ onHandlePropTypeFloatVar:function (node, parent, propertyName, floatVar, ccbReader) {
+ ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
+ },
+
+ onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) {
+ if (propertyName === PROPERTY_VISIBLE) {
+ node.setVisible(check);
+ } else if (propertyName === PROPERTY_IGNOREANCHORPOINTFORPOSITION) {
+ node.ignoreAnchorPointForPosition(check);
+ } else {
+ ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
+ }
+ },
+
+ onHandlePropTypeSpriteFrame:function (node, parent, propertyName, spriteFrame, ccbReader) {
+ ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
+ },
+
+ onHandlePropTypeAnimation:function (node, parent, propertyName, ccAnimation, ccbReader) {
+ ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
+ },
+
+ onHandlePropTypeTexture:function (node, parent, propertyName, ccTexture2D, ccbReader) {
+ ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
+ },
+ onHandlePropTypeByte:function (node, parent, propertyName, byteValue, ccbReader) {
+ ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
+ },
+ onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) {
+ ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
+ },
+ onHandlePropTypeColor4FVar:function (node, parent, propertyName, ccColor4FVar, ccbReader) {
+ ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
+ },
+ onHandlePropTypeFlip:function (node, parent, propertyName, flip, ccbReader) {
+ ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
+ },
+ onHandlePropTypeBlendFunc:function (node, parent, propertyName, ccBlendFunc, ccbReader) {
+ ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
+ },
+ onHandlePropTypeFntFile:function (node, parent, propertyName, fntFile, ccbReader) {
+ ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
+ },
+ onHandlePropTypeString:function (node, parent, propertyName, strValue, ccbReader) {
+ //ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
+ // It may be a custom property, add it to custom property dictionary.
+ this._customProperties.setObject(strValue, propertyName);
+ },
+ onHandlePropTypeText:function (node, parent, propertyName, textValue, ccbReader) {
+ ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
+ },
+ onHandlePropTypeFontTTF:function (node, parent, propertyName, fontTTF, ccbReader) {
+ ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
+ },
+ onHandlePropTypeBlock:function (node, parent, propertyName, blockData, ccbReader) {
+ ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
+ },
+ onHandlePropTypeBlockCCControl:function (node, parent, propertyName, blockCCControlData, ccbReader) {
+ ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
+ },
+ onHandlePropTypeCCBFile:function (node, parent, propertyName, ccbFileNode, ccbReader) {
+ ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
+ }
+});
+
+cc.NodeLoader.loader = function () {
+ return new cc.NodeLoader();
+};
diff --git a/extensions/ccb-reader/CCNodeLoaderLibrary.js b/extensions/ccb-reader/CCNodeLoaderLibrary.js
new file mode 100644
index 0000000000..cece42021f
--- /dev/null
+++ b/extensions/ccb-reader/CCNodeLoaderLibrary.js
@@ -0,0 +1,101 @@
+/****************************************************************************
+ 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.NodeLoaderLibrary = cc._Class.extend({
+ _ccNodeLoaders:null,
+
+ ctor:function(){
+ this._ccNodeLoaders = {};
+ },
+
+ registerDefaultCCNodeLoaders:function(){
+ this.registerCCNodeLoader("CCNode", cc.NodeLoader.loader());
+ this.registerCCNodeLoader("CCLayer", cc.LayerLoader.loader());
+ this.registerCCNodeLoader("CCLayerColor", cc.LayerColorLoader.loader());
+ this.registerCCNodeLoader("CCLayerGradient", cc.LayerGradientLoader.loader());
+ this.registerCCNodeLoader("CCSprite", cc.SpriteLoader.loader());
+ this.registerCCNodeLoader("CCLabelBMFont", cc.LabelBMFontLoader.loader());
+ this.registerCCNodeLoader("CCLabelTTF", cc.LabelTTFLoader.loader());
+ this.registerCCNodeLoader("CCScale9Sprite", cc.Scale9SpriteLoader.loader());
+ this.registerCCNodeLoader("CCScrollView", cc.ScrollViewLoader.loader());
+ this.registerCCNodeLoader("CCBFile", cc.BuilderFileLoader.loader());
+ this.registerCCNodeLoader("CCMenu", cc.MenuLoader.loader());
+ this.registerCCNodeLoader("CCMenuItemImage", cc.MenuItemImageLoader.loader());
+ this.registerCCNodeLoader("CCControlButton", cc.ControlButtonLoader.loader());
+ this.registerCCNodeLoader("CCParticleSystemQuad", cc.ParticleSystemLoader.loader());
+ },
+
+ registerCCNodeLoader:function(className,ccNodeLoader){
+ this._ccNodeLoaders[className] = ccNodeLoader;
+ },
+
+ unregisterCCNodeLoader:function(className){
+ if(this._ccNodeLoaders[className]){
+ delete this._ccNodeLoaders[className];
+ }
+ },
+
+ getCCNodeLoader:function(className){
+ if(this._ccNodeLoaders[className])
+ return this._ccNodeLoaders[className];
+ return null;
+ },
+
+ purge:function(releaseCCNodeLoaders){
+ if(releaseCCNodeLoaders) {
+ for(var className in this._ccNodeLoaders) {
+ delete this._ccNodeLoaders[className];
+ }
+ }
+ this._ccNodeLoaders = {};
+ }
+});
+
+cc.NodeLoaderLibrary.sSharedCCNodeLoaderLibrary = null;
+cc.NodeLoaderLibrary.library = function(){
+ return new cc.NodeLoaderLibrary();
+};
+
+cc.NodeLoaderLibrary.sharedCCNodeLoaderLibrary = function(){
+ if(cc.NodeLoaderLibrary.sSharedCCNodeLoaderLibrary == null) {
+ cc.NodeLoaderLibrary.sSharedCCNodeLoaderLibrary = new cc.NodeLoaderLibrary();
+ cc.NodeLoaderLibrary.sSharedCCNodeLoaderLibrary.registerDefaultCCNodeLoaders();
+ }
+ return cc.NodeLoaderLibrary.sSharedCCNodeLoaderLibrary;
+};
+
+cc.NodeLoaderLibrary.purgeSharedCCNodeLoaderLibrary = function(){
+ cc.NodeLoaderLibrary.sSharedCCNodeLoaderLibrary = null;
+};
+
+cc.NodeLoaderLibrary.newDefaultCCNodeLoaderLibrary = function(){
+ var ccNodeLoaderLibrary = cc.NodeLoaderLibrary.library();
+ ccNodeLoaderLibrary.registerDefaultCCNodeLoaders();
+ return ccNodeLoaderLibrary;
+};
+
+
+
diff --git a/extensions/ccb-reader/CCSpriteLoader.js b/extensions/ccb-reader/CCSpriteLoader.js
new file mode 100644
index 0000000000..857b2bb025
--- /dev/null
+++ b/extensions/ccb-reader/CCSpriteLoader.js
@@ -0,0 +1,544 @@
+/****************************************************************************
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+var PROPERTY_FLIP = "flip";
+var PROPERTY_DISPLAYFRAME = "displayFrame";
+var PROPERTY_COLOR = "color";
+var PROPERTY_OPACITY = "opacity";
+var PROPERTY_BLENDFUNC = "blendFunc";
+
+cc.SpriteLoader = cc.NodeLoader.extend({
+ _createCCNode:function (parent, ccbReader) {
+ return new cc.Sprite();
+ },
+
+ onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) {
+ if (propertyName === PROPERTY_COLOR) {
+ if(ccColor3B.r !== 255 || ccColor3B.g !== 255 || ccColor3B.b !== 255){
+ node.setColor(ccColor3B);
+ }
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, ccColor3B, ccbReader);
+ }
+ },
+ onHandlePropTypeByte:function (node, parent, propertyName, byteValue, ccbReader) {
+ if (propertyName === PROPERTY_OPACITY) {
+ node.setOpacity(byteValue);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeByte.call(this, node, parent, propertyName, byteValue, ccbReader);
+ }
+ },
+ onHandlePropTypeBlendFunc:function (node, parent, propertyName, ccbBlendFunc, ccbReader) {
+ if (propertyName === PROPERTY_BLENDFUNC) {
+ node.setBlendFunc(ccbBlendFunc);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccbBlendFunc, ccbReader);
+ }
+ },
+ onHandlePropTypeSpriteFrame:function (node, parent, propertyName, ccSpriteFrame, ccbReader) {
+ if (propertyName === PROPERTY_DISPLAYFRAME) {
+ if(ccSpriteFrame)
+ node.setSpriteFrame(ccSpriteFrame);
+ else
+ cc.log("ERROR: SpriteFrame is null");
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeSpriteFrame.call(this, node, parent, propertyName, ccSpriteFrame, ccbReader);
+ }
+ },
+ onHandlePropTypeFlip:function (node, parent, propertyName, flip, ccbReader) {
+ if (propertyName === PROPERTY_FLIP) {
+ node.setFlippedX(flip[0]);
+ node.setFlippedY(flip[1]);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeFlip.call(this, node, parent, propertyName, flip, ccbReader);
+ }
+ }
+});
+
+cc.SpriteLoader.loader = function () {
+ return new cc.SpriteLoader();
+};
+
+var PROPERTY_TOUCH_ENABLED = "touchEnabled";
+var PROPERTY_IS_TOUCH_ENABLED = "isTouchEnabled";
+var PROPERTY_ACCELEROMETER_ENABLED = "accelerometerEnabled";
+var PROPERTY_IS_ACCELEROMETER_ENABLED = "isAccelerometerEnabled";
+var PROPERTY_IS_MOUSE_ENABLED = "isMouseEnabled";
+var PROPERTY_MOUSE_ENABLED = "mouseEnabled";
+var PROPERTY_KEYBOARD_ENABLED = "keyboardEnabled";
+var PROPERTY_IS_KEYBOARD_ENABLED = "isKeyboardEnabled";
+
+cc.LayerLoader = cc.NodeLoader.extend({
+ _createCCNode:function (parent, ccbReader) {
+
+ var layer = new cc.Layer();
+
+ layer.setContentSize(0,0);
+
+ return layer;
+ },
+ onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) {
+ if (propertyName === PROPERTY_TOUCH_ENABLED || propertyName === PROPERTY_IS_TOUCH_ENABLED) {
+ //node.setTouchEnabled(check);
+ } else if (propertyName === PROPERTY_ACCELEROMETER_ENABLED || propertyName === PROPERTY_IS_ACCELEROMETER_ENABLED) {
+ //node.setAccelerometerEnabled(check);
+ } else if (propertyName === PROPERTY_MOUSE_ENABLED || propertyName === PROPERTY_IS_MOUSE_ENABLED ) {
+ //node.setMouseEnabled(check);
+ } else if (propertyName === PROPERTY_KEYBOARD_ENABLED || propertyName === PROPERTY_IS_KEYBOARD_ENABLED) {
+ // TODO XXX
+ if(node.setKeyboardEnabled && !cc.sys.isNative) {
+ node.setKeyboardEnabled(check);
+ } else {
+ cc.log("The property '" + PROPERTY_IS_KEYBOARD_ENABLED + "' is not supported!");
+ // This comes closest: ((CCLayer *)pNode).setKeypadEnabled(pCheck);
+ }
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeCheck.call(this, node, parent, propertyName, check, ccbReader);
+ }
+ }
+});
+
+cc.LayerLoader.loader = function () {
+ return new cc.LayerLoader();
+};
+
+
+cc.LayerColorLoader = cc.LayerLoader.extend({
+ _createCCNode:function (parent, ccbReader) {
+ return new cc.LayerColor();
+ },
+
+ onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) {
+ if (propertyName === PROPERTY_COLOR) {
+ node.setColor(ccColor3B);
+ } else {
+ cc.LayerLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, ccColor3B, ccbReader);
+ }
+ },
+ onHandlePropTypeByte:function (node, parent, propertyName, byteValue, ccbReader) {
+ if (propertyName === PROPERTY_OPACITY) {
+ node.setOpacity(byteValue);
+ } else {
+ cc.LayerLoader.prototype.onHandlePropTypeByte.call(this, node, parent, propertyName, byteValue, ccbReader);
+ }
+ },
+ onHandlePropTypeBlendFunc:function (node, parent, propertyName, ccBlendFunc, ccbReader) {
+ if (propertyName === PROPERTY_BLENDFUNC) {
+ node.setBlendFunc(ccBlendFunc);
+ } else {
+ cc.LayerLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccBlendFunc, ccbReader);
+ }
+ }
+});
+
+cc.LayerColorLoader.loader = function () {
+ return new cc.LayerColorLoader();
+};
+
+var PROPERTY_STARTCOLOR = "startColor";
+var PROPERTY_ENDCOLOR = "endColor";
+var PROPERTY_STARTOPACITY = "startOpacity";
+var PROPERTY_ENDOPACITY = "endOpacity";
+var PROPERTY_VECTOR = "vector";
+
+cc.LayerGradientLoader = cc.LayerLoader.extend({
+ _createCCNode:function (parent, ccbReader) {
+ return new cc.LayerGradient();
+ },
+ onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) {
+ if (propertyName === PROPERTY_STARTCOLOR) {
+ node.setStartColor(ccColor3B);
+ } else if (propertyName === PROPERTY_ENDCOLOR) {
+ node.setEndColor(ccColor3B);
+ } else {
+ cc.LayerLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, ccColor3B, ccbReader);
+ }
+ },
+ onHandlePropTypeByte:function (node, parent, propertyName, byteValue, ccbReader) {
+ if (propertyName === PROPERTY_STARTOPACITY) {
+ node.setStartOpacity(byteValue);
+ } else if (propertyName === PROPERTY_ENDOPACITY) {
+ node.setEndOpacity(byteValue);
+ } else {
+ cc.LayerLoader.prototype.onHandlePropTypeByte.call(this, node, parent, propertyName, byteValue, ccbReader);
+ }
+ },
+ onHandlePropTypePoint:function (node, parent, propertyName, point, ccbReader) {
+ if (propertyName === PROPERTY_VECTOR) {
+ node.setVector(point);
+ // TODO Not passed along the ccbi file.
+ // node.setCompressedInterpolation(true);
+ } else {
+ cc.LayerLoader.prototype.onHandlePropTypePoint.call(this, node, parent, propertyName, point, ccbReader);
+ }
+ },
+ onHandlePropTypeBlendFunc:function (node, parent, propertyName, ccBlendFunc, ccbReader) {
+ if (propertyName === PROPERTY_BLENDFUNC) {
+ node.setBlendFunc(ccBlendFunc);
+ } else {
+ cc.LayerLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccBlendFunc, ccbReader);
+ }
+ }
+});
+
+cc.LayerGradientLoader.loader = function () {
+ return new cc.LayerGradientLoader();
+};
+
+cc.MenuLoader = cc.LayerLoader.extend({
+ _createCCNode:function (parent, ccbReader) {
+ var menu = new cc.Menu();
+
+ menu.setContentSize(0,0);
+
+ return menu;
+ }
+});
+
+cc.MenuLoader.loader = function () {
+ return new cc.MenuLoader();
+};
+
+var PROPERTY_BLOCK = "block";
+var PROPERTY_ISENABLED = "isEnabled";
+
+cc.MenuItemLoader = cc.NodeLoader.extend({
+ _createCCNode:function (parent, ccbReader) {
+ return null;
+ },
+
+ onHandlePropTypeBlock:function (node, parent, propertyName, blockData, ccbReader) {
+ if (propertyName === PROPERTY_BLOCK) {
+ if (null != blockData) { // Add this condition to allow CCMenuItemImage without target/selector predefined
+ node.setTarget(blockData.selMenuHander, blockData.target);
+ }
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeBlock.call(this, node, parent, propertyName, blockData, ccbReader);
+ }
+ },
+ onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) {
+ if (propertyName === PROPERTY_ISENABLED) {
+ node.setEnabled(check);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeCheck.call(this, node, parent, propertyName, check, ccbReader);
+ }
+ }
+});
+
+var PROPERTY_NORMALDISPLAYFRAME = "normalSpriteFrame";
+var PROPERTY_SELECTEDDISPLAYFRAME = "selectedSpriteFrame";
+var PROPERTY_DISABLEDDISPLAYFRAME = "disabledSpriteFrame";
+
+cc.MenuItemImageLoader = cc.MenuItemLoader.extend({
+ _createCCNode:function (parent, ccbReader) {
+ return new cc.MenuItemImage();
+ },
+
+ onHandlePropTypeSpriteFrame:function (node, parent, propertyName, spriteFrame, ccbReader) {
+ if (propertyName === PROPERTY_NORMALDISPLAYFRAME) {
+ if (spriteFrame != null) {
+ node.setNormalSpriteFrame(spriteFrame);
+ }
+ } else if (propertyName === PROPERTY_SELECTEDDISPLAYFRAME) {
+ if (spriteFrame != null) {
+ node.setSelectedSpriteFrame(spriteFrame);
+ }
+ } else if (propertyName === PROPERTY_DISABLEDDISPLAYFRAME) {
+ if (spriteFrame != null) {
+ node.setDisabledSpriteFrame(spriteFrame);
+ }
+ } else {
+ cc.MenuItemLoader.prototype.onHandlePropTypeSpriteFrame.call(this, node, parent, propertyName, spriteFrame, ccbReader);
+ }
+ }
+});
+
+cc.MenuItemImageLoader.loader = function () {
+ return new cc.MenuItemImageLoader();
+};
+
+var PROPERTY_FONTNAME = "fontName";
+var PROPERTY_FONTSIZE = "fontSize";
+var PROPERTY_HORIZONTALALIGNMENT = "horizontalAlignment";
+var PROPERTY_VERTICALALIGNMENT = "verticalAlignment";
+var PROPERTY_STRING = "string";
+var PROPERTY_DIMENSIONS = "dimensions";
+
+cc.LabelTTFLoader = cc.NodeLoader.extend({
+ _createCCNode:function (parent, ccbReader) {
+ return new cc.LabelTTF();
+ },
+ onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) {
+ if (propertyName === PROPERTY_COLOR) {
+ if(ccColor3B.r !== 255 || ccColor3B.g !== 255 || ccColor3B.b !== 255){
+ node.setColor(ccColor3B);
+ }
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, ccColor3B, ccbReader);
+ }
+ },
+ onHandlePropTypeByte:function (node, parent, propertyName, byteValue, ccbReader) {
+ if (propertyName === PROPERTY_OPACITY) {
+ node.setOpacity(byteValue);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeByte.call(this, node, parent, propertyName, byteValue, ccbReader);
+ }
+ },
+ onHandlePropTypeBlendFunc:function (node, parent, propertyName, ccBlendFunc, ccbReader) {
+ if (propertyName === PROPERTY_BLENDFUNC) {
+ node.setBlendFunc(ccBlendFunc);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccBlendFunc, ccbReader);
+ }
+ },
+ onHandlePropTypeFontTTF:function (node, parent, propertyName, fontTTF, ccbReader) {
+ if (propertyName === PROPERTY_FONTNAME) {
+ node.setFontName(fontTTF);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeFontTTF.call(this, node, parent, propertyName, fontTTF, ccbReader);
+ }
+ },
+ onHandlePropTypeText:function (node, parent, propertyName, textValue, ccbReader) {
+ if (propertyName === PROPERTY_STRING) {
+ node.setString(textValue);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeText.call(this, node, parent, propertyName, textValue, ccbReader);
+ }
+ },
+ onHandlePropTypeFloatScale:function (node, parent, propertyName, floatScale, ccbReader) {
+ if (propertyName === PROPERTY_FONTSIZE) {
+ node.setFontSize(floatScale);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeFloatScale.call(this, node, parent, propertyName, floatScale, ccbReader);
+ }
+ },
+ onHandlePropTypeIntegerLabeled:function (node, parent, propertyName, integerLabeled, ccbReader) {
+ if (propertyName === PROPERTY_HORIZONTALALIGNMENT) {
+ node.setHorizontalAlignment(integerLabeled);
+ } else if (propertyName === PROPERTY_VERTICALALIGNMENT) {
+ node.setVerticalAlignment(integerLabeled);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeIntegerLabeled.call(this, node, parent, propertyName, integerLabeled, ccbReader);
+ }
+ },
+ onHandlePropTypeSize:function (node, parent, propertyName, size, ccbReader) {
+ if (propertyName === PROPERTY_DIMENSIONS) {
+ node.setDimensions(size);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeSize.call(this, node, parent, propertyName, size, ccbReader);
+ }
+ }
+});
+
+cc.LabelTTFLoader.loader = function () {
+ return new cc.LabelTTFLoader();
+};
+
+var PROPERTY_FNTFILE = "fntFile";
+
+cc.LabelBMFontLoader = cc.NodeLoader.extend({
+ _createCCNode:function (parent, ccbReader) {
+ return new cc.LabelBMFont();
+ },
+
+ onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) {
+ if (propertyName === PROPERTY_COLOR) {
+ if(ccColor3B.r !== 255 || ccColor3B.g !== 255 || ccColor3B.b !== 255){
+ node.setColor(ccColor3B);
+ }
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, ccColor3B, ccbReader);
+ }
+ },
+ onHandlePropTypeByte:function (node, parent, propertyName, byteValue, ccbReader) {
+ if (propertyName === PROPERTY_OPACITY) {
+ node.setOpacity(byteValue);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeByte.call(this, node, parent, propertyName, byteValue, ccbReader);
+ }
+ },
+ onHandlePropTypeBlendFunc:function (node, parent, propertyName, ccBlendFunc, ccbReader) {
+ if (propertyName === PROPERTY_BLENDFUNC) {
+ node.setBlendFunc(ccBlendFunc);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccBlendFunc, ccbReader);
+ }
+ },
+ onHandlePropTypeFntFile:function (node, parent, propertyName, fntFile, ccbReader) {
+ if (propertyName === PROPERTY_FNTFILE) {
+ node.setFntFile(fntFile);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeFntFile.call(this, node, parent, propertyName, fntFile, ccbReader);
+ }
+ },
+ onHandlePropTypeText:function (node, parent, propertyName, textValue, ccbReader) {
+ if (propertyName === PROPERTY_STRING) {
+ node.setString(textValue);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeText.call(this, node, parent, propertyName, textValue, ccbReader);
+ }
+ }
+});
+
+cc.LabelBMFontLoader.loader = function () {
+ return new cc.LabelBMFontLoader();
+};
+
+var PROPERTY_EMITERMODE = "emitterMode";
+var PROPERTY_POSVAR = "posVar";
+var PROPERTY_EMISSIONRATE = "emissionRate";
+var PROPERTY_DURATION = "duration";
+var PROPERTY_TOTALPARTICLES = "totalParticles";
+var PROPERTY_LIFE = "life";
+var PROPERTY_STARTSIZE = "startSize";
+var PROPERTY_ENDSIZE = "endSize";
+var PROPERTY_STARTSPIN = "startSpin";
+var PROPERTY_ENDSPIN = "endSpin";
+var PROPERTY_ANGLE = "angle";
+var PROPERTY_GRAVITY = "gravity";
+var PROPERTY_SPEED = "speed";
+var PROPERTY_TANGENTIALACCEL = "tangentialAccel";
+var PROPERTY_RADIALACCEL = "radialAccel";
+var PROPERTY_TEXTURE = "texture";
+var PROPERTY_STARTRADIUS = "startRadius";
+var PROPERTY_ENDRADIUS = "endRadius";
+var PROPERTY_ROTATEPERSECOND = "rotatePerSecond";
+
+cc.ParticleSystemLoader = cc.NodeLoader.extend({
+ _createCCNode:function (parent, ccbReader) {
+ return new cc.ParticleSystem();
+ },
+
+ onHandlePropTypeIntegerLabeled:function (node, parent, propertyName, integerLabeled, ccbReader) {
+ if (propertyName === PROPERTY_EMITERMODE) {
+ node.setEmitterMode(integerLabeled);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeIntegerLabeled.call(this, node, parent, propertyName, integerLabeled, ccbReader);
+ }
+ },
+ onHandlePropTypePoint:function (node, parent, propertyName, point, ccbReader) {
+ if (propertyName === PROPERTY_POSVAR) {
+ node.setPosVar(point);
+ } else if (propertyName === PROPERTY_GRAVITY) {
+ node.setGravity(point);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypePoint.call(this, node, parent, propertyName, point, ccbReader);
+ }
+ },
+ onHandlePropTypeFloat:function (node, parent, propertyName, floatValue, ccbReader) {
+ if (propertyName === PROPERTY_EMISSIONRATE) {
+ node.setEmissionRate(floatValue);
+ } else if (propertyName === PROPERTY_DURATION) {
+ node.setDuration(floatValue);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeFloat.call(this, node, parent, propertyName, floatValue, ccbReader);
+ }
+ },
+ onHandlePropTypeInteger:function (node, parent, propertyName, integerValue, ccbReader) {
+ if (propertyName === PROPERTY_TOTALPARTICLES) {
+ node.setTotalParticles(integerValue);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeInteger.call(this, node, parent, propertyName, integerValue, ccbReader);
+ }
+ },
+ onHandlePropTypeFloatVar:function (node, parent, propertyName, floatVar, ccbReader) {
+ if (propertyName === PROPERTY_LIFE) {
+ node.setLife(floatVar[0]);
+ node.setLifeVar(floatVar[1]);
+ } else if (propertyName === PROPERTY_STARTSIZE) {
+ node.setStartSize(floatVar[0]);
+ node.setStartSizeVar(floatVar[1]);
+ } else if (propertyName === PROPERTY_ENDSIZE) {
+ node.setEndSize(floatVar[0]);
+ node.setEndSizeVar(floatVar[1]);
+ } else if (propertyName === PROPERTY_STARTSPIN) {
+ node.setStartSpin(floatVar[0]);
+ node.setStartSpinVar(floatVar[1]);
+ } else if (propertyName === PROPERTY_ENDSPIN) {
+ node.setEndSpin(floatVar[0]);
+ node.setEndSpinVar(floatVar[1]);
+ } else if (propertyName === PROPERTY_ANGLE) {
+ node.setAngle(floatVar[0]);
+ node.setAngleVar(floatVar[1]);
+ } else if (propertyName === PROPERTY_SPEED) {
+ node.setSpeed(floatVar[0]);
+ node.setSpeedVar(floatVar[1]);
+ } else if (propertyName === PROPERTY_TANGENTIALACCEL) {
+ node.setTangentialAccel(floatVar[0]);
+ node.setTangentialAccelVar(floatVar[1]);
+ } else if (propertyName === PROPERTY_RADIALACCEL) {
+ node.setRadialAccel(floatVar[0]);
+ node.setRadialAccelVar(floatVar[1]);
+ } else if (propertyName === PROPERTY_STARTRADIUS) {
+ node.setStartRadius(floatVar[0]);
+ node.setStartRadiusVar(floatVar[1]);
+ } else if (propertyName === PROPERTY_ENDRADIUS) {
+ node.setEndRadius(floatVar[0]);
+ node.setEndRadiusVar(floatVar[1]);
+ } else if (propertyName === PROPERTY_ROTATEPERSECOND) {
+ node.setRotatePerSecond(floatVar[0]);
+ node.setRotatePerSecondVar(floatVar[1]);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeFloatVar.call(this, node, parent, propertyName, floatVar, ccbReader);
+ }
+ },
+ onHandlePropTypeColor4FVar:function (node, parent, propertyName, ccColor4FVar, ccbReader) {
+ if (propertyName === PROPERTY_STARTCOLOR) {
+ node.setStartColor(ccColor4FVar[0]);
+ node.setStartColorVar(ccColor4FVar[1]);
+ } else if (propertyName === PROPERTY_ENDCOLOR) {
+ node.setEndColor(ccColor4FVar[0]);
+ node.setEndColorVar(ccColor4FVar[1]);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeColor4FVar.call(this, node, parent, propertyName, ccColor4FVar, ccbReader);
+ }
+ },
+ onHandlePropTypeBlendFunc:function (node, parent, propertyName, ccBlendFunc, ccbReader) {
+ if (propertyName === PROPERTY_BLENDFUNC) {
+ node.setBlendFunc(ccBlendFunc);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccBlendFunc, ccbReader);
+ }
+ },
+ onHandlePropTypeTexture:function (node, parent, propertyName, ccTexture2D, ccbReader) {
+ if (propertyName === PROPERTY_TEXTURE) {
+ node.setTexture(ccTexture2D);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeTexture.call(this, node, parent, propertyName, ccTexture2D, ccbReader);
+ }
+ }
+});
+
+cc.ParticleSystemLoader.loader = function () {
+ return new cc.ParticleSystemLoader();
+};
+
+
+
+
+
+
+
diff --git a/extensions/ccpool/CCPool.js b/extensions/ccpool/CCPool.js
new file mode 100644
index 0000000000..464f3b7543
--- /dev/null
+++ b/extensions/ccpool/CCPool.js
@@ -0,0 +1,141 @@
+/****************************************************************************
+ 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.pool is a singleton object serves as an object cache pool.
+ * It can helps you to improve your game performance for objects which need frequent release and recreate operations
+ * Some common use case is :
+ * 1. Bullets in game (die very soon, massive creation and recreation, no side effect on other objects)
+ * 2. Blocks in candy crash (massive creation and recreation)
+ * etc...
+ *
+ *
+ * @class pool
+ */
+cc.pool = /** @lends cc.pool# */{
+ _pool: {},
+
+ _releaseCB: function () {
+ this.release();
+ },
+
+ _autoRelease: function (obj) {
+ var running = obj._running === undefined ? false : !obj._running;
+ cc.director.getScheduler().schedule(this._releaseCB, obj, 0, 0, 0, running)
+ },
+
+ /**
+ * Put the obj in pool.
+ * @method putInPool
+ * @param {Object} obj - The need put in pool object.
+ * @example {@link utils/api/cocos/docs/extensions/ccpool/putInPool.js}
+ */
+ putInPool: function (obj) {
+ var cid = cc.js._getClassId(obj.constructor);
+ if (!cid) {
+ return;
+ }
+ if (!this._pool[cid]) {
+ this._pool[cid] = [];
+ }
+ // JSB retain to avoid being auto released
+ obj.retain && obj.retain();
+ // User implementation for disable the object
+ obj.unuse && obj.unuse();
+ this._pool[cid].push(obj);
+ },
+
+ /**
+ * Check if this kind of obj has already in pool.
+ * @method hasObject
+ * @param {Object} objClass - The check object class.
+ * @returns {Boolean} If this kind of obj is already in pool return true,else return false.
+ */
+ hasObject: function (objClass) {
+ var cid = cc.js._getClassId(objClass);
+ var list = this._pool[cid];
+ if (!list || list.length === 0) {
+ return false;
+ }
+ return true;
+ },
+
+ /**
+ * Remove the obj if you want to delete it.
+ * @method removeObject
+ */
+ removeObject: function (obj) {
+ var cid = cc.js._getClassId(obj.constructor);
+ if (cid) {
+ var list = this._pool[cid];
+ if (list) {
+ for (var i = 0; i < list.length; i++) {
+ if (obj === list[i]) {
+ // JSB release to avoid memory leak
+ obj.release && obj.release();
+ list.splice(i, 1);
+ }
+ }
+ }
+ }
+ },
+
+ /**
+ * Get the obj from pool.
+ * @method getFromPool
+ * @returns {*} Call the reuse function an return the obj.
+ */
+ getFromPool: function (objClass/*,args*/) {
+ if (this.hasObject(objClass)) {
+ var cid = cc.js._getClassId(objClass);
+ var list = this._pool[cid];
+ var args = Array.prototype.slice.call(arguments);
+ args.shift();
+ var obj = list.pop();
+ // User implementation for re-enable the object
+ obj.reuse && obj.reuse.apply(obj, args);
+ // JSB release to avoid memory leak
+ cc.sys.isNative && obj.release && this._autoRelease(obj);
+ return obj;
+ }
+ },
+
+ /**
+ * Remove all objs in pool and reset the pool.
+ * @method drainAllPools
+ */
+ drainAllPools: function () {
+ for (var i in this._pool) {
+ for (var j = 0; j < this._pool[i].length; j++) {
+ var obj = this._pool[i][j];
+ // JSB release to avoid memory leak
+ obj.release && obj.release();
+ }
+ }
+ this._pool = {};
+ }
+};
\ No newline at end of file
diff --git a/extensions/ccui/base-classes/CCProtectedNode.js b/extensions/ccui/base-classes/CCProtectedNode.js
new file mode 100644
index 0000000000..e3b1d976f0
--- /dev/null
+++ b/extensions/ccui/base-classes/CCProtectedNode.js
@@ -0,0 +1,305 @@
+/****************************************************************************
+ 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 class inhert from cc.Node, use for saving some protected children in other list.
+ * @class
+ * @extends cc.Node
+ */
+cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{
+ _protectedChildren: null,
+ _reorderProtectedChildDirty: false,
+
+ _insertProtectedChild: function(child, z){
+ this._reorderProtectedChildDirty = true;
+ this._protectedChildren.push(child);
+ child._setLocalZOrder(z);
+ },
+
+ /**
+ * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
+ * @function
+ */
+ ctor: function(){
+ cc.Node.prototype.ctor.call(this);
+ this._protectedChildren = [];
+ },
+
+ /**
+ *
+ * Adds a child to the container with z order and tag
+ * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately.
+ *
+ * @param {cc.Node} child A child node
+ * @param {Number} [localZOrder] Z order for drawing priority. Please refer to `setLocalZOrder(int)`
+ * @param {Number} [tag] An integer to identify the node easily. Please refer to `setTag(int)`
+ */
+ addProtectedChild: function(child, localZOrder, tag){
+ cc.assert(child != null, "child must be non-nil");
+ cc.assert(!child.parent, "child already added. It can't be added again");
+
+ localZOrder = localZOrder || child.getLocalZOrder();
+ if(tag)
+ child.setTag(tag);
+
+ this._insertProtectedChild(child, localZOrder);
+ child.setParent(this);
+ child.setOrderOfArrival(cc.s_globalOrderOfArrival);
+
+ if(this._running){
+ child.onEnter();
+ // prevent onEnterTransitionDidFinish to be called twice when a node is added in onEnter
+ if(this._isTransitionFinished)
+ child.onEnterTransitionDidFinish();
+ }
+ if(this._cascadeColorEnabled)
+ this._renderCmd.setCascadeColorEnabledDirty();
+ if (this._cascadeOpacityEnabled)
+ this._renderCmd.setCascadeOpacityEnabledDirty();
+ },
+
+ /**
+ * Gets a child from the container with its tag
+ * @param {Number} tag An identifier to find the child node.
+ * @return {cc.Node} a Node object whose tag equals to the input parameter
+ */
+ getProtectedChildByTag: function(tag){
+ cc.assert(tag !== cc.NODE_TAG_INVALID, "Invalid tag");
+ var locChildren = this._protectedChildren;
+ for(var i = 0, len = locChildren.length; i < len; i++)
+ if(locChildren.getTag() === tag)
+ return locChildren[i];
+ return null;
+ },
+
+ /**
+ * Removes a child from the container. It will also cleanup all running actions depending on the cleanup parameter.
+ * @param {cc.Node} child The child node which will be removed.
+ * @param {Boolean} [cleanup=true] true if all running actions and callbacks on the child node will be cleanup, false otherwise.
+ */
+ removeProtectedChild: function(child, cleanup){
+ if(cleanup == null)
+ cleanup = true;
+ var locChildren = this._protectedChildren;
+ if(locChildren.length === 0)
+ return;
+ var idx = locChildren.indexOf(child);
+ if(idx > -1){
+ if(this._running){
+ child.onExitTransitionDidStart();
+ child.onExit();
+ }
+
+ // If you don't do cleanup, the child's actions will not get removed and the
+ // its scheduledSelectors_ dict will not get released!
+ if (cleanup)
+ child.cleanup();
+
+ // set parent nil at the end
+ child.setParent(null);
+ locChildren.splice(idx, 1);
+ }
+ },
+
+ /**
+ * Removes a child from the container by tag value.
+ * It will also cleanup all running actions depending on the cleanup parameter
+ * @param {Number} tag
+ * @param {Boolean} [cleanup=true]
+ */
+ removeProtectedChildByTag: function(tag, cleanup){
+ cc.assert( tag !== cc.NODE_TAG_INVALID, "Invalid tag");
+
+ if(cleanup == null)
+ cleanup = true;
+
+ var child = this.getProtectedChildByTag(tag);
+
+ if (child == null)
+ cc.log("cocos2d: removeChildByTag(tag = %d): child not found!", tag);
+ else
+ this.removeProtectedChild(child, cleanup);
+ },
+
+ /**
+ * Removes all children from the container with a cleanup.
+ * @see cc.ProtectedNode#removeAllProtectedChildrenWithCleanup
+ */
+ removeAllProtectedChildren: function(){
+ this.removeAllProtectedChildrenWithCleanup(true);
+ },
+
+ /**
+ * Removes all children from the container, and do a cleanup to all running actions depending on the cleanup parameter.
+ * @param {Boolean} [cleanup=true] true if all running actions on all children nodes should be cleanup, false otherwise.
+ */
+ removeAllProtectedChildrenWithCleanup: function(cleanup){
+ if(cleanup == null)
+ cleanup = true;
+ var locChildren = this._protectedChildren;
+ // not using detachChild improves speed here
+ for (var i = 0, len = locChildren.length; i< len; i++) {
+ var child = locChildren[i];
+ // IMPORTANT:
+ // -1st do onExit
+ // -2nd cleanup
+ if(this._running){
+ child.onExitTransitionDidStart();
+ child.onExit();
+ }
+
+ if (cleanup)
+ child.cleanup();
+ // set parent nil at the end
+ child.setParent(null);
+ }
+ locChildren.length = 0;
+ },
+
+ /**
+ * Reorders a child according to a new z value.
+ * @param {cc.Node} child An already added child node. It MUST be already added.
+ * @param {Number} localZOrder Z order for drawing priority. Please refer to setLocalZOrder(int)
+ */
+ reorderProtectedChild: function(child, localZOrder){
+ cc.assert( child != null, "Child must be non-nil");
+ this._reorderProtectedChildDirty = true;
+ child.setOrderOfArrival(cc.s_globalOrderOfArrival++);
+ child._setLocalZOrder(localZOrder);
+ },
+
+ /**
+ *
+ * Sorts the children array once before drawing, instead of every time when a child is added or reordered.
+ * This approach can improves the performance massively.
+ * @note Don't call this manually unless a child added needs to be removed in the same frame
+ *
+ */
+ sortAllProtectedChildren: function(){
+ if (this._reorderProtectedChildDirty) {
+ var _children = this._protectedChildren;
+
+ // insertion sort
+ var len = _children.length, i, j, tmp;
+ for(i=1; i= 0){
+ if(tmp._localZOrder < _children[j]._localZOrder){
+ _children[j+1] = _children[j];
+ }else if(tmp._localZOrder === _children[j]._localZOrder && tmp.arrivalOrder < _children[j].arrivalOrder){
+ _children[j+1] = _children[j];
+ }else
+ break;
+ j--;
+ }
+ _children[j+1] = tmp;
+ }
+
+ //don't need to check children recursively, that's done in visit of each child
+ this._reorderProtectedChildDirty = false;
+ }
+ },
+
+ _changePosition: function(){},
+
+ /**
+ * Stops itself and its children and protected children's all running actions and schedulers
+ * @override
+ */
+ cleanup: function(){
+ cc.Node.prototype.cleanup.call(this);
+ var locChildren = this._protectedChildren;
+ for(var i = 0 , len = locChildren.length; i < len; i++)
+ locChildren[i].cleanup();
+ },
+
+ /**
+ * Calls its parent's onEnter and calls its protected children's onEnter
+ * @override
+ */
+ onEnter: function(){
+ cc.Node.prototype.onEnter.call(this);
+ var locChildren = this._protectedChildren;
+ for(var i = 0, len = locChildren.length;i< len;i++)
+ locChildren[i].onEnter();
+ },
+
+ /**
+ *
+ * Event callback that is invoked when the Node enters in the 'stage'.
+ * If the Node enters the 'stage' with a transition, this event is called when the transition finishes.
+ * If you override onEnterTransitionDidFinish, you shall call its parent's one, e.g. Node::onEnterTransitionDidFinish()
+ *
+ * @override
+ */
+ onEnterTransitionDidFinish: function(){
+ cc.Node.prototype.onEnterTransitionDidFinish.call(this);
+ var locChildren = this._protectedChildren;
+ for(var i = 0, len = locChildren.length;i< len;i++)
+ locChildren[i].onEnterTransitionDidFinish();
+ },
+
+ /**
+ * Calls its parent's onExit and calls its protected children's onExit
+ * @override
+ */
+ onExit:function(){
+ cc.Node.prototype.onExit.call(this);
+ var locChildren = this._protectedChildren;
+ for(var i = 0, len = locChildren.length;i< len;i++)
+ locChildren[i].onExit();
+ },
+
+ /**
+ *
+ * Event callback that is called every time the Node leaves the 'stage'.
+ * If the Node leaves the 'stage' with a transition, this callback is called when the transition starts.
+ *
+ */
+ onExitTransitionDidStart: function(){
+ cc.Node.prototype.onExitTransitionDidStart.call(this);
+ var locChildren = this._protectedChildren;
+ for(var i = 0, len = locChildren.length;i< len;i++)
+ locChildren[i].onExitTransitionDidStart();
+ },
+
+ _createRenderCmd: function(){
+ if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ return new cc.ProtectedNode.CanvasRenderCmd(this);
+ else
+ return new cc.ProtectedNode.WebGLRenderCmd(this);
+ }
+});
+
+/**
+ * create a cc.ProtectedNode object;
+ * @deprecated since v3.0, please use new cc.ProtectedNode() instead.
+ * @return cc.ProtectedNode
+ */
+cc.ProtectedNode.create = function(){
+ return new cc.ProtectedNode();
+};
\ No newline at end of file
diff --git a/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js b/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js
new file mode 100644
index 0000000000..351438ae36
--- /dev/null
+++ b/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js
@@ -0,0 +1,240 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+(function(){
+ cc.ProtectedNode.RenderCmd = {
+ _updateDisplayColor: function (parentColor) {
+ var node = this._node;
+ var locDispColor = this._displayedColor, locRealColor = node._realColor;
+ var i, len, selChildren, item;
+ if (this._cascadeColorEnabledDirty && !node._cascadeColorEnabled) {
+ locDispColor.r = locRealColor.r;
+ locDispColor.g = locRealColor.g;
+ locDispColor.b = locRealColor.b;
+ var whiteColor = new cc.Color(255, 255, 255, 255);
+ selChildren = node._children;
+ for (i = 0, len = selChildren.length; i < len; i++) {
+ item = selChildren[i];
+ if (item && item._renderCmd)
+ item._renderCmd._updateDisplayColor(whiteColor);
+ }
+ this._cascadeColorEnabledDirty = false;
+ } else {
+ if (parentColor === undefined) {
+ var locParent = node._parent;
+ if (locParent && locParent._cascadeColorEnabled)
+ parentColor = locParent.getDisplayedColor();
+ else
+ parentColor = cc.Color.WHITE;
+ }
+ locDispColor.r = 0 | (locRealColor.r * parentColor.r / 255.0);
+ locDispColor.g = 0 | (locRealColor.g * parentColor.g / 255.0);
+ locDispColor.b = 0 | (locRealColor.b * parentColor.b / 255.0);
+ if (node._cascadeColorEnabled) {
+ selChildren = node._children;
+ for (i = 0, len = selChildren.length; i < len; i++) {
+ item = selChildren[i];
+ if (item && item._renderCmd){
+ item._renderCmd._updateDisplayColor(locDispColor);
+ item._renderCmd._updateColor();
+ }
+ }
+ }
+ selChildren = node._protectedChildren;
+ for(i = 0, len = selChildren.length;i < len; i++){
+ item = selChildren[i];
+ if(item && item._renderCmd){
+ item._renderCmd._updateDisplayColor(locDispColor);
+ item._renderCmd._updateColor();
+ }
+ }
+ }
+ this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.colorDirty ^ this._dirtyFlag;
+ },
+
+ _updateDisplayOpacity: function (parentOpacity) {
+ var node = this._node;
+ var i, len, selChildren, item;
+ if (this._cascadeOpacityEnabledDirty && !node._cascadeOpacityEnabled) {
+ this._displayedOpacity = node._realOpacity;
+ selChildren = node._children;
+ for (i = 0, len = selChildren.length; i < len; i++) {
+ item = selChildren[i];
+ if (item && item._renderCmd)
+ item._renderCmd._updateDisplayOpacity(255);
+ }
+ this._cascadeOpacityEnabledDirty = false;
+ } else {
+ if (parentOpacity === undefined) {
+ var locParent = node._parent;
+ parentOpacity = 255;
+ if (locParent && locParent._cascadeOpacityEnabled)
+ parentOpacity = locParent.getDisplayedOpacity();
+ }
+ this._displayedOpacity = node._realOpacity * parentOpacity / 255.0;
+ if (node._cascadeOpacityEnabled) {
+ selChildren = node._children;
+ for (i = 0, len = selChildren.length; i < len; i++) {
+ item = selChildren[i];
+ if (item && item._renderCmd){
+ item._renderCmd._updateDisplayOpacity(this._displayedOpacity);
+ item._renderCmd._updateColor();
+ }
+ }
+ }
+ selChildren = node._protectedChildren;
+ for(i = 0, len = selChildren.length;i < len; i++){
+ item = selChildren[i];
+ if(item && item._renderCmd){
+ item._renderCmd._updateDisplayOpacity(this._displayedOpacity);
+ item._renderCmd._updateColor();
+ }
+ }
+ }
+ this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.opacityDirty ^ this._dirtyFlag;
+ },
+
+ _changeProtectedChild: function (child) {
+ var cmd = child._renderCmd,
+ dirty = cmd._dirtyFlag,
+ flags = cc.Node._dirtyFlags;
+
+ if (this._dirtyFlag & flags.colorDirty)
+ dirty |= flags.colorDirty;
+
+ if (this._dirtyFlag & flags.opacityDirty)
+ dirty |= flags.opacityDirty;
+
+ var colorDirty = dirty & flags.colorDirty,
+ opacityDirty = dirty & flags.opacityDirty;
+
+ if (colorDirty)
+ cmd._updateDisplayColor(this._displayedColor);
+ if (opacityDirty)
+ cmd._updateDisplayOpacity(this._displayedOpacity);
+ if (colorDirty || opacityDirty)
+ cmd._updateColor();
+ }
+ };
+
+ cc.ProtectedNode.CanvasRenderCmd = function (renderable) {
+ cc.Node.CanvasRenderCmd.call(this, renderable);
+ this._cachedParent = null;
+ this._cacheDirty = false;
+ };
+
+ var proto = cc.ProtectedNode.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
+ cc.js.mixin(proto, cc.ProtectedNode.RenderCmd);
+ proto.constructor = cc.ProtectedNode.CanvasRenderCmd;
+
+ proto.visit = function(parentCmd){
+ var node = this._node;
+ // quick return if not visible
+ if (!node._visible)
+ return;
+
+ //visit for canvas
+ var i, j;
+ var children = node._children, child;
+ var locChildren = node._children, locProtectedChildren = node._protectedChildren;
+ var childLen = locChildren.length, pLen = locProtectedChildren.length;
+
+ this._syncStatus(parentCmd);
+
+ node.sortAllChildren();
+ node.sortAllProtectedChildren();
+
+ var pChild;
+ // draw children zOrder < 0
+ for (i = 0; i < childLen; i++) {
+ child = children[i];
+ if (child._localZOrder < 0)
+ child.visit(this);
+ else
+ break;
+ }
+ for (j = 0; j < pLen; j++) {
+ pChild = locProtectedChildren[j];
+ if (pChild && pChild._localZOrder < 0){
+ this._changeProtectedChild(pChild);
+ pChild.visit(this);
+ }
+ else
+ break;
+ }
+
+ cc.renderer.pushRenderCommand(this);
+
+ for (; i < childLen; i++)
+ children[i] && children[i].visit(this);
+ for (; j < pLen; j++){
+ pChild = locProtectedChildren[j];
+ if(!pChild) continue;
+ this._changeProtectedChild(pChild);
+ pChild.visit(this);
+ }
+
+ this._dirtyFlag = 0;
+ this._cacheDirty = false;
+ };
+
+ proto.transform = function(parentCmd, recursive){
+ var node = this._node;
+
+ if(node._changePosition)
+ node._changePosition();
+
+ var t = node.getNodeToParentTransform(), worldT = this._worldTransform;
+ if (parentCmd) {
+ var pt = parentCmd._worldTransform;
+ // cc.AffineTransformConcat is incorrect at get world transform
+ worldT.a = t.a * pt.a + t.b * pt.c; //a
+ worldT.b = t.a * pt.b + t.b * pt.d; //b
+ worldT.c = t.c * pt.a + t.d * pt.c; //c
+ worldT.d = t.c * pt.b + t.d * pt.d; //d
+
+ worldT.tx = pt.a * t.tx + pt.c * t.ty + pt.tx;
+ worldT.ty = pt.d * t.ty + pt.ty + pt.b * t.tx;
+ } else {
+ worldT.a = t.a;
+ worldT.b = t.b;
+ worldT.c = t.c;
+ worldT.d = t.d;
+ worldT.tx = t.tx;
+ worldT.ty = t.ty;
+ }
+ var i, len, locChildren = node._children;
+ if(recursive && locChildren && locChildren.length !== 0){
+ for(i = 0, len = locChildren.length; i< len; i++){
+ locChildren[i]._renderCmd.transform(this, recursive);
+ }
+ }
+ locChildren = node._protectedChildren;
+ if(recursive && locChildren && locChildren.length !== 0){
+ for(i = 0, len = locChildren.length; i< len; i++){
+ locChildren[i]._renderCmd.transform(this, recursive);
+ }
+ }
+ };
+})();
\ No newline at end of file
diff --git a/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js b/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js
new file mode 100644
index 0000000000..deb34b2227
--- /dev/null
+++ b/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js
@@ -0,0 +1,135 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+(function(){
+ if(!cc.Node.WebGLRenderCmd)
+ return;
+ cc.ProtectedNode.WebGLRenderCmd = function (renderable) {
+ cc.Node.WebGLRenderCmd.call(this, renderable);
+ };
+
+ var proto = cc.ProtectedNode.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
+ cc.js.mixin(proto, cc.ProtectedNode.RenderCmd);
+ proto.constructor = cc.ProtectedNode.WebGLRenderCmd;
+
+ proto.visit = function(parentCmd){
+ var node = this._node;
+ // quick return if not visible
+ if (!node._visible)
+ return;
+ var i, j, currentStack = cc.current_stack;
+
+ //optimize performance for javascript
+ currentStack.stack.push(currentStack.top);
+ this._syncStatus(parentCmd);
+ currentStack.top = this._stackMatrix;
+
+ var locGrid = node.grid;
+ if (locGrid && locGrid._active)
+ locGrid.beforeDraw();
+
+ //node.transform(node._parent && node._parent._renderCmd);
+
+ var locChildren = node._children, locProtectedChildren = node._protectedChildren;
+ var childLen = locChildren.length, pLen = locProtectedChildren.length;
+ node.sortAllChildren();
+ node.sortAllProtectedChildren();
+
+ var pChild;
+ // draw children zOrder < 0
+ for (i = 0; i < childLen; i++) {
+ if (locChildren[i] && locChildren[i]._localZOrder < 0)
+ locChildren[i].visit(this);
+ else
+ break;
+ }
+ for(j = 0; j < pLen; j++){
+ pChild = locProtectedChildren[j];
+ if (pChild && pChild._localZOrder < 0){
+ this._changeProtectedChild(pChild);
+ pChild.visit(this);
+ }else
+ break;
+ }
+
+ cc.renderer.pushRenderCommand(this);
+
+ // draw children zOrder >= 0
+ for (; i < childLen; i++) {
+ locChildren[i] && locChildren[i].visit(this);
+ }
+ for (; j < pLen; j++) {
+ pChild = locProtectedChildren[j];
+ if(!pChild) continue;
+ this._changeProtectedChild(pChild);
+ pChild.visit(this);
+ }
+
+ if (locGrid && locGrid._active)
+ locGrid.afterDraw(node);
+
+ this._dirtyFlag = 0;
+ //optimize performance for javascript
+ currentStack.top = currentStack.stack.pop();
+ };
+
+ proto.transform = function(parentCmd, recursive){
+ var node = this._node;
+ var t4x4 = this._transform4x4, stackMatrix = this._stackMatrix,
+ parentMatrix = parentCmd ? parentCmd._stackMatrix : cc.current_stack.top;
+
+ // Convert 3x3 into 4x4 matrix
+ var trans = node.getNodeToParentTransform();
+
+ if(node._changePosition)
+ node._changePosition();
+
+ var t4x4Mat = t4x4.mat;
+ t4x4Mat[0] = trans.a;
+ t4x4Mat[4] = trans.c;
+ t4x4Mat[12] = trans.tx;
+ t4x4Mat[1] = trans.b;
+ t4x4Mat[5] = trans.d;
+ t4x4Mat[13] = trans.ty;
+
+ // Update Z vertex manually
+ t4x4Mat[14] = node._vertexZ;
+
+ //optimize performance for Javascript
+ cc.kmMat4Multiply(stackMatrix, parentMatrix, t4x4);
+
+ var i, len, locChildren = node._children;
+ if(recursive && locChildren && locChildren.length !== 0){
+ for(i = 0, len = locChildren.length; i< len; i++){
+ locChildren[i]._renderCmd.transform(this, recursive);
+ }
+ }
+ locChildren = node._protectedChildren;
+ if(recursive && locChildren && locChildren.length !== 0){
+ for(i = 0, len = locChildren.length; i< len; i++){
+ locChildren[i]._renderCmd.transform(this, recursive);
+ }
+ }
+ };
+})();
\ No newline at end of file
diff --git a/extensions/ccui/base-classes/UIScale9Sprite.js b/extensions/ccui/base-classes/UIScale9Sprite.js
new file mode 100644
index 0000000000..ff2d12c913
--- /dev/null
+++ b/extensions/ccui/base-classes/UIScale9Sprite.js
@@ -0,0 +1,1118 @@
+/****************************************************************************
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2012 Neofect. All rights reserved.
+
+ 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.
+
+ Created by Jung Sang-Taik on 2012-03-16
+ ****************************************************************************/
+
+EventTarget = require("../cocos2d/core/event/event-target");
+
+/**
+ *
+ * A 9-slice sprite for cocos2d UI.
+ *
+ * 9-slice scaling allows you to specify how scaling is applied
+ * to specific areas of a sprite. With 9-slice scaling (3x3 grid),
+ * you can ensure that the sprite does not become distorted when
+ * scaled.
+ * @note: it will refactor in v3.1
+ * @see http://yannickloriot.com/library/ios/cccontrolextension/Classes/CCScale9Sprite.html
+ *
+ * @class
+ * @extends cc.Node
+ *
+ * @property {cc.Size} preferredSize - The preferred size of the 9-slice sprite
+ * @property {cc.Rect} capInsets - The cap insets of the 9-slice sprite
+ * @property {Number} insetLeft - The left inset of the 9-slice sprite
+ * @property {Number} insetTop - The top inset of the 9-slice sprite
+ * @property {Number} insetRight - The right inset of the 9-slice sprite
+ * @property {Number} insetBottom - The bottom inset of the 9-slice sprite
+ */
+
+ccui.Scale9Sprite = cc.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{
+
+ _textureInited:false,
+ _spriteRect: null,
+ _spriteFrameRotated:false,
+
+ //To keep backward compatibility
+ //this member is just used for secondary usage, instead, insetTop/Bottom/Left/right is the key value.
+ _derivedCapInsets:null,
+
+ _scale9Image: null, //the original sprite
+
+ _scale9Enabled: true,
+ _blendFunc:null,
+
+ /** Original sprite's size. */
+ _originalSize:null,
+ /** Preferred sprite's size. By default the preferred size is the original size. */
+
+ //if the preferredSize component is given as -1, it is ignored
+ _preferredSize:null,
+
+ /** Sets the left side inset */
+ _insetLeft: 0.0,
+ /** Sets the top side inset */
+ _insetTop:0.0,
+ /** Sets the right side inset */
+ _insetRight:0.0,
+ /** Sets the bottom side inset */
+ _insetBottom:0.0,
+
+ _flippedX: false,
+ _flippedY: false,
+ _isPatch9: false,
+ _brightState: 0,
+ _nonSliceSpriteAnchor: null,
+ _textureLoaded:false,
+ _renderingType:1,
+
+ _quads:[],
+ _quadsDirty : true,
+
+ ctor: function(file, rect, capInsets) {
+ cc.Node.prototype.ctor.call(this);
+ this._nonSliceSpriteAnchor = cc.p(0.5,0.5);
+ this._originalSize = cc.size(0,0);
+ this._preferredSize = cc.rect(0,0,0,0);
+ this._spriteRect = cc.rect(0,0,0,0);
+ this._blendFunc = cc.BlendFunc._disable();
+ this.setAnchorPoint(cc.p(0.5,0.5));
+
+ if(file != undefined)
+ {
+ if(file instanceof cc.SpriteFrame) {
+ this.initWithSpriteFrame(file, rect);
+ }
+ else{
+ var frame = cc.spriteFrameCache.getSpriteFrame(file);
+ if(frame){
+ this.initWithSpriteFrame(frame, rect);
+ }
+ else
+ this.initWithFile(file,rect,capInsets);
+ }
+ }
+ else
+ {
+ this.init();
+ }
+ },
+
+ textureLoaded:function(){
+ return this._textureLoaded;
+ },
+
+ /**
+ * Initializes a 9-slice sprite with a texture file, a delimitation zone and
+ * with the specified cap insets.
+ * Once the sprite is created, you can then call its "setContentSize:" method
+ * to resize the sprite will all it's 9-slice goodness intract.
+ * It respects the anchorPoint too.
+ *
+ * @param file The name of the texture file.
+ * @param rect The rectangle that describes the sub-part of the texture that
+ * is the whole image. If the shape is the whole texture, set this to the
+ * texture's full rect.
+ * @param capInsets The values to use for the cap insets.
+ * @return True if initialize success, false otherwise.
+ */
+ initWithFile : function(file, rect, capInsets){
+ if(file instanceof cc.Rect) {
+ capInsets = file;
+ file = rect;
+ }
+ rect = rect || cc.rect(0,0,0,0);
+
+ if(!file){
+ throw new Error("ccui.Scale9Sprite.initWithFile(): file should be non-null");
+ }
+
+ var sprite = cc.Sprite.create(file,rect);
+
+ this.init(sprite, rect, capInsets);
+ },
+
+ /**
+ * Initializes a 9-slice sprite with an sprite frame and with the specified
+ * cap insets.
+ * Once the sprite is created, you can then call its "setContentSize:" method
+ * to resize the sprite will all it's 9-slice goodness intract.
+ * It respects the anchorPoint too.
+ *
+ * @param spriteFrame The sprite frame object.
+ * @param capInsets The values to use for the cap insets.
+ * @return True if initializes success, false otherwise.
+ */
+ initWithSpriteFrame : function(spriteFrame, capInsets){
+ if(!spriteFrame || !spriteFrame.getTexture())
+ throw new Error("ccui.Scale9Sprite.initWithSpriteFrame(): spriteFrame should be non-null and its texture should be non-null");
+
+ var locLoaded = spriteFrame.textureLoaded();
+
+ if(capInsets!== undefined) this._derivedCapInsets = capInsets;
+ this._textureLoaded = false;
+ var _onTextureLoadedCallback = function () {
+ var sprite = cc.Sprite.createWithSpriteFrame(spriteFrame);
+ this._onScale9ResourcesLoaded(sprite,spriteFrame.isRotated(),spriteFrame.getRect(),spriteFrame.getOriginalSize());
+ };
+
+ if (!locLoaded) {
+
+ spriteFrame.once("load", _onTextureLoadedCallback, this);
+ }
+ else {
+ _onTextureLoadedCallback.call(this);
+ }
+ },
+
+ /**
+ * Initializes a 9-slice sprite with an sprite frame name and with the specified
+ * cap insets.
+ * Once the sprite is created, you can then call its "setContentSize:" method
+ * to resize the sprite will all it's 9-slice goodness intract.
+ * It respects the anchorPoint too.
+ *
+ * @param spriteFrameName The sprite frame name.
+ * @param capInsets The values to use for the cap insets.
+ * @return True if initializes success, false otherwise.
+ */
+ initWithSpriteFrameName : function(spriteFrameName, capInsets){
+ if(!spriteFrameName)
+ throw new Error("ccui.Scale9Sprite.initWithSpriteFrameName(): spriteFrameName should be non-null");
+
+ var frame = cc.spriteFrameCache.getSpriteFrame(spriteFrameName);
+
+ if (!frame) {
+ cc.log("ccui.Scale9Sprite.initWithSpriteFrameName(): can't find the sprite frame by spriteFrameName");
+ return false;
+ }
+
+ return this.initWithSpriteFrame(frame, capInsets);
+ },
+
+ /**
+ * @brief Initializes a 9-slice sprite with an sprite instance.
+ * Once the sprite is created, you can then call its "setContentSize:" method
+ * to resize the sprite will all it's 9-slice goodness intract.
+ * It respects the anchorPoint too.
+ *
+ * @param sprite The sprite instance.
+ * @param rect A delimitation zone.
+ * @param rotated Whether the sprite is rotated or not.
+ * @param offset The offset when slice the sprite.
+ * @param originalSize The original size of sprite.
+ * @param capInsets The values to use for the cap insets.
+ * @return True if initializes success, false otherwise.
+ */
+ init : function(sprite,rect,rotated,offset,originalSize,capInsets){
+ if(sprite === null) return true;
+
+ sprite = sprite || null;
+ rect = rect || cc.rect(0,0,0,0);
+ rotated = rotated || false;
+ offset = offset || cc.p(0,0);
+ originalSize = originalSize || cc.size(rect.width, rect.height);
+
+ if(rotated instanceof cc.Rect)
+ {
+ capInsets = arguments[2];
+ rotated = false;
+ }
+ if(offset instanceof cc.Rect)
+ {
+ capInsets = arguments[3];
+ offset = cc.p(0,0);
+ }
+
+ this.updateWithSprite(sprite, rect, rotated, offset, originalSize, capInsets);
+
+ return true;
+ },
+
+ /**
+ * Sets the source blending function.
+ *
+ * @param blendFunc A structure with source and destination factor to specify pixel arithmetic. e.g. {GL_ONE, GL_ONE}, {GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA}.
+ * @js NA
+ * @lua NA
+ */
+ setBlendFunc : function(blendFunc){
+ this._blendFunc.src = blendFunc.src;
+ this._blendFunc.dst = blendFunc.dst;
+ this._applyBlendFunc();
+ },
+
+ /**
+ * Returns the blending function that is currently being used.
+ *
+ * @return A BlendFunc structure with source and destination factor which specified pixel arithmetic.
+ * @js NA
+ * @lua NA
+ */
+ getBlendFunc : function(){
+ return new cc.BlendFunc(this._blendFunc.src, this._blendFunc.dst);
+ },
+
+ /**
+ * Creates and returns a new sprite object with the specified cap insets.
+ * You use this method to add cap insets to a sprite or to change the existing
+ * cap insets of a sprite. In both cases, you get back a new image and the
+ * original sprite remains untouched.
+ *
+ * @param capInsets The values to use for the cap insets.
+ * @return A Scale9Sprite instance.
+ */
+ resizableSpriteWithCapInsets : function(capInsets){
+ result = new cc.Scale9Sprite();
+ result.init(this._scale9Image, this._spriteRect, this._spriteFrameRotated, cc.rect(0,0,0,0), this._originalSize, capInsets);
+ return result;
+ },
+
+
+ _onScale9ResourcesLoaded: function (sprite, rotated, rect, size) {
+ this._spriteFrameRotated = rotated;
+ this._textureLoaded = true;
+ var opacity = this.getOpacity();
+ var color = this.getColor();
+ this._updateBlendFunc(sprite.getTexture());
+ this._scale9Image = sprite;
+ this._scale9Image.setAnchorPoint(cc.p(0, 0));
+ this._scale9Image.setPosition(cc.p(0, 0));
+ if (this._spriteRect.equals(cc.rect(0, 0, 0, 0))) {
+ this._spriteRect = cc.rect(rect);
+ }
+ if (cc.sizeEqualToSize(this._originalSize, cc.size(0, 0))) {
+ this._originalSize = cc.size(size);
+ }
+ if (cc.sizeEqualToSize(this._preferredSize, cc.size(0, 0))) {
+ this.setPreferredSize(this._originalSize);
+ }
+
+ if (!this._scale9Enabled) {
+ this.addChild(this._scale9Image);
+ this._adjustScale9ImagePosition();
+ }
+
+ this._applyBlendFunc();
+ this.setState(this._brightState);
+ if (this._textureInited) {
+ // Restore color and opacity
+ this.setOpacity(opacity);
+ this.setColor(color);
+ }
+ this._textureInited = true;
+
+ if(this._derivedCapInsets)
+ {
+ this._insetLeft = this._derivedCapInsets.x;
+ this._insetTop = this._derivedCapInsets.y;
+ this._insetRight = this._originalSize.width-this._insetLeft-this._derivedCapInsets.width;
+ this._insetBottom = this._originalSize.height-this._insetTop-this._derivedCapInsets.height;
+ this._derivedCapInsets = null;
+ }
+
+ this._quadsDirty = true;
+ }, /**
+ * @brief Update Scale9Sprite with a specified sprite.
+ *
+ * @param sprite A sprite pointer.
+ * @param rect A delimitation zone.
+ * @param rotated Whether the sprite is rotated or not.
+ * @param offset The offset when slice the sprite.
+ * @param originalSize The origial size of the sprite.
+ * @param capInsets The Values to use for the cap insets.
+ * @return True if update success, false otherwise.
+ * @js NA
+ */
+ updateWithSprite : function(sprite,textureRect,rotated,offset,originalSize,capInsets) {
+ if (offset instanceof cc.Rect) {
+ capInsets = arguments[3];
+ offset = cc.size(0, 0);
+ originalSize = cc.size(textureRect.width, textureRect.height);
+ }
+
+ this._spriteRect = cc.rect(textureRect);
+ this._spriteFrameRotated = rotated;
+ this._originalSize = originalSize;
+ if(capInsets !== undefined) this._derivedCapInsets = capInsets;
+ this._textureLoaded = false;
+
+ if(sprite === null){
+ this._quadsDirty = true;
+ return true;
+ }
+
+ var textureloaded = sprite.textureLoaded();
+ var _onTextureLoadedCallback = function() {
+ //do
+ var textureSize = sprite.getTexture().getContentSize();
+ this._onScale9ResourcesLoaded(sprite,rotated,cc.rect(0, 0, textureSize.width, textureSize.height),textureSize);
+ };
+
+ if(textureloaded) {
+ _onTextureLoadedCallback.call(this);
+ }
+ else {
+ var texture = sprite.getTexture();
+ if(texture)
+ texture.once("load",_onTextureLoadedCallback, this);
+ }
+
+ return true;
+
+ },
+
+
+ /**
+ * @brief Change inner sprite's sprite frame.
+ *
+ * @param spriteFrame A sprite frame pointer.
+ * @param capInsets The values to use for the cap insets.
+ */
+ setSpriteFrame : function(spriteFrame, capInsets){
+ var sprite = cc.Sprite.createWithTexture(spriteFrame.getTexture());
+ this.updateWithSprite(sprite,
+ spriteFrame.getRect(),
+ spriteFrame.isRotated(),
+ spriteFrame.getOffset(),
+ spriteFrame.getOriginalSize(),
+ capInsets);
+ },
+
+ // overrides
+ setContentSize : function(size){
+ if (cc.sizeEqualToSize(this._contentSize,size))
+ {
+ return;
+ }
+ cc.Node.prototype.setContentSize.call(this, size);
+ this._preferredSize = size;
+ this._quadsDirty = true;
+ this._adjustScale9ImagePosition();
+ },
+
+ setAnchorPoint : function(anchorPoint){
+ cc.Node.prototype.setAnchorPoint.call(this, anchorPoint);
+ if (!this._scale9Enabled)
+ {
+ if (this._scale9Image !== null)
+ {
+ this._nonSliceSpriteAnchor = anchorPoint;
+ this._scale9Image.setAnchorPoint(anchorPoint);
+ this._adjustScale9ImagePosition();
+ }
+ }
+ },
+
+ /**
+ * Change the state of 9-slice sprite.
+ * @see `State`
+ * @param state A enum value in State.
+ * @since v3.4
+ */
+ setState : function(state){
+ this._brightState = state;
+ this._renderCmd.setState(state);
+ },
+
+ /**
+ * Query the current bright state.
+ * @return @see `State`
+ * @since v3.7
+ */
+ getState : function(){
+ return this._brightState;
+ },
+
+ /**
+ * @brief Query the sprite's original size.
+ *
+ * @return Sprite size.
+ */
+ getOriginalSize : function(){
+ return cc.size(this._originalSize);
+ },
+
+ /**
+ * @brief Change the preferred size of Scale9Sprite.
+ *
+ * @param size A delimitation zone.
+ */
+ setPreferredSize : function(size)
+ {
+ return this.setContentSize(size);
+ },
+
+ /**
+ * @brief Query the Scale9Sprite's preferred size.
+ *
+ * @return Scale9Sprite's preferred size.
+ */
+ getPreferredSize : function(){
+ return cc.size(this._preferredSize);
+ },
+
+
+ setRenderingType: function(type) {
+ if(this._renderingType == type) return;
+ this._renderingType = type;
+ this._quadsDirty = true;
+ },
+
+ /**
+ * @brief Change the cap inset size.
+ *
+ * @param rect A delimitation zone.
+ */
+ setCapInsets : function(capInsets){
+ if(this._textureLoaded) {
+ this._quadsDirty = true;
+ this._insetLeft = capInsets.x;
+ this._insetTop = capInsets.y;
+ this._insetRight = this._originalSize.width - this._insetLeft - capInsets.width;
+ this._insetBottom = this._originalSize.height - this._insetTop - capInsets.height;
+ } else {
+ cc.log("Can not set capinset when resource is loading");
+ }
+ },
+
+ /**
+ * @brief Query the Scale9Sprite's preferred size.
+ *
+ * @return Scale9Sprite's cap inset.
+ */
+ getCapInsets : function(){
+
+ return cc.rect(this._insetLeft, this._insetTop, this._originalSize.width - this._insetLeft - this._insetRight,
+ this._originalSize.height - this._insetTop - this._insetBottom);
+ },
+
+ /**
+ * @brief Change the left sprite's cap inset.
+ *
+ * @param leftInset The values to use for the cap inset.
+ */
+ setInsetLeft : function(insetLeft){
+ this._insetLeft = insetLeft;
+ this._quadsDirty = true;
+ },
+
+ /**
+ * @brief Query the left sprite's cap inset.
+ *
+ * @return The left sprite's cap inset.
+ */
+ getInsetLeft : function(){
+ return this._insetLeft;
+ },
+
+ /**
+ * @brief Change the top sprite's cap inset.
+ *
+ * @param topInset The values to use for the cap inset.
+ */
+ setInsetTop : function(insetTop){
+ this._insetTop = insetTop;
+ this._quadsDirty = true;
+ },
+
+ /**
+ * @brief Query the top sprite's cap inset.
+ *
+ * @return The top sprite's cap inset.
+ */
+ getInsetTop : function(){
+ return this._insetTop;
+ },
+
+ /**
+ * @brief Change the right sprite's cap inset.
+ *
+ * @param rightInset The values to use for the cap inset.
+ */
+ setInsetRight : function(insetRight){
+ this._insetRight = insetRight;
+ this._quadsDirty = true;
+ },
+
+ /**
+ * @brief Query the right sprite's cap inset.
+ *
+ * @return The right sprite's cap inset.
+ */
+ getInsetRight : function(){
+ return this._insetRight;
+ },
+
+ /**
+ * @brief Change the bottom sprite's cap inset.
+ *
+ * @param bottomInset The values to use for the cap inset.
+
+ */
+ setInsetBottom : function(insetBottom)
+ {
+ this._insetBottom = insetBottom;
+ this._quadsDirty = true;
+ },
+
+ /**
+ * @brief Query the bottom sprite's cap inset.
+ *
+ * @return The bottom sprite's cap inset.
+ */
+ getInsetBottom : function(){
+ return this._insetBottom;
+ },
+
+ /**
+ * @brief Toggle 9-slice feature.
+ * If Scale9Sprite is 9-slice disabled, the Scale9Sprite will rendered as a normal sprite.
+ * @param enabled True to enable 9-slice, false otherwise.
+ * @js NA
+ */
+ setScale9Enabled : function(enabled){
+ if (this._scale9Enabled == enabled) {
+ return;
+ }
+ this._scale9Enabled = enabled;
+ if(this._scale9Image) {
+ if (!this._scale9Enabled) {
+ this.addChild(this._scale9Image);
+ this._adjustScale9ImagePosition();
+ }
+ else {
+ this.removeChild(this._scale9Image);
+ }
+
+ }
+
+ this._quadsDirty = true;
+ },
+
+ /**
+ * @brief Query whether the Scale9Sprite is enable 9-slice or not.
+ *
+ * @return True if 9-slice is enabled, false otherwise.
+ * @js NA
+ */
+ isScale9Enabled : function(){
+ return this._scale9Enabled;
+ },
+
+ /**
+ * @brief Get the original no 9-sliced sprite
+ *
+ * @return A sprite instance.
+ */
+ getSprite : function(){
+ return this._scale9Image;
+ },
+
+ /**
+ * Sets whether the widget should be flipped horizontally or not.
+ *
+ * @param flippedX true if the widget should be flipped horizontally, false otherwise.
+ */
+ setFlippedX : function(flippedX){
+ var realScale = this.getScaleX();
+ this._flippedX = flippedX;
+ this.setScaleX(realScale);
+ },
+
+ /**
+ * Returns the flag which indicates whether the widget is flipped horizontally or not.
+ *
+ * It only flips the texture of the widget, and not the texture of the widget's children.
+ * Also, flipping the texture doesn't alter the anchorPoint.
+ * If you want to flip the anchorPoint too, and/or to flip the children too use:
+ * widget->setScaleX(sprite->getScaleX() * -1);
+ *
+ * @return true if the widget is flipped horizontally, false otherwise.
+ */
+ isFlippedX: function() {
+ return this._flippedX;
+ },
+
+ /**
+ * Sets whether the widget should be flipped vertically or not.
+ *
+ * @param flippedY true if the widget should be flipped vertically, false otherwise.
+ */
+ setFlippedY : function(flippedY){
+ var realScale = this.getScaleY();
+ this._flippedY = flippedY;
+ this.setScaleY(realScale);
+ },
+
+ /**
+ * Return the flag which indicates whether the widget is flipped vertically or not.
+ *
+ * It only flips the texture of the widget, and not the texture of the widget's children.
+ * Also, flipping the texture doesn't alter the anchorPoint.
+ * If you want to flip the anchorPoint too, and/or to flip the children too use:
+ * widget->setScaleY(widget->getScaleY() * -1);
+ *
+ * @return true if the widget is flipped vertically, false otherwise.
+ */
+ isFlippedY : function(){
+ return this._flippedY;
+ },
+
+ //override the setScale function of Node
+ setScaleX : function(scaleX){
+ if (this._flippedX) {
+ scaleX = scaleX * -1;
+ }
+ cc.Node.prototype.setScaleX.call(this,scaleX);
+ },
+
+ setScaleY : function(scaleY){
+ if (this._flippedY) {
+ scaleY = scaleY * -1;
+ }
+ cc.Node.prototype.setScaleY.call(this,scaleY);
+ },
+
+ setScale : function(scaleX, scaleY){
+ if(scaleY === undefined) scaleY = scaleX;
+ this.setScaleX(scaleX);
+ this.setScaleY(scaleY);
+ },
+
+ getScaleX : function(){
+ var originalScale = cc.Node.prototype.getScaleX.call(this);
+ if (this._flippedX)
+ {
+ originalScale = originalScale * -1.0;
+ }
+ return originalScale;
+ },
+
+ getScaleY : function() {
+ var originalScale = cc.Node.prototype.getScaleY.call(this);
+ if (this._flippedY)
+ {
+ originalScale = originalScale * -1.0;
+ }
+ return originalScale;
+ },
+
+ getScale : function(){
+ return this.getScaleX();
+ },
+
+ setCameraMask : function(mask,applyChildren/** = true**/){
+ cc.Node.prototype.setCameraMask.call(this,mask,applyChildren);
+ if(this._scale9Image)
+ this._scale9Image.setCameraMask(mask,applyChildren);
+ },
+
+ //_updateCapInset : function() {
+ // var insets = cc.rect(this._insetLeft,
+ // this._insetTop,
+ // this._originalSize.width-this._insetLeft-this._insetRight,
+ // this._originalSize.height-this._insetTop-this._insetBottom);
+ // this.setCapInsets(insets);
+ //},
+
+ _adjustScale9ImagePosition : function(){
+ if (this._scale9Image)
+ {
+ if (!this._scale9Enabled) {
+ this._scale9Image.setAnchorPoint(this._nonSliceSpriteAnchor);
+ this._scale9Image.setPosition(this._contentSize.width * this._scale9Image.getAnchorPoint().x,
+ this._contentSize.height * this._scale9Image.getAnchorPoint().y);
+
+ }
+ }
+ },
+
+ _applyBlendFunc : function(){
+ if(this._scale9Image != null)
+ this._scale9Image.setBlendFunc(this._blendFunc);
+ },
+
+ _updateBlendFunc : function(texture){
+ if (! texture || ! texture.hasPremultipliedAlpha())
+ {
+ this._blendFunc = cc.BlendFunc._alphaNonPremultiplied();
+ this.setOpacityModifyRGB(false);
+ }
+ else
+ {
+ this._blendFunc = cc.BlendFunc._alphaPremultiplied();
+ this.setOpacityModifyRGB(true);
+ }
+ },
+
+ //calculate the quads used for scale 9 rendering.
+
+ _buildQuads : function(){
+ if (this._scale9Enabled)
+ {
+ var tex = null;
+ if(this._scale9Image != null)
+ {
+ tex = this._scale9Image.getTexture();
+ }
+
+ if (tex == null)
+ {
+ return;
+ }
+
+ var capInsets = cc.rectPointsToPixels(this.getCapInsets());
+ var textureRect = cc.rectPointsToPixels(this._spriteRect);
+ var spriteRectSize = cc.sizePointsToPixels(this._originalSize);
+
+ //handle .9.png
+ if (this._isPatch9)
+ {
+ spriteRectSize = cc.size(spriteRectSize.width - 2, spriteRectSize.height-2);
+ }
+
+ if(capInsets.equals(cc.rect(0,0,0,0)))
+ {
+ capInsets = cc.rect(spriteRectSize.width/3, spriteRectSize.height/3,
+ spriteRectSize.width/3, spriteRectSize.height/3);
+ }
+ //
+
+ this._calculateQuads(this._calculateUV(tex, capInsets, spriteRectSize),
+ this._calculateVertices(capInsets, spriteRectSize));
+ }
+ },
+
+ _cleanupQuads : function(){
+ this._quads = [];
+ },
+
+ _calculateUV : function(texture, capInsets, spriteRectSize){
+ var atlasWidth = texture.getPixelWidth();
+ var atlasHeight = texture.getPixelHeight();
+
+ //caculate texture coordinate
+ var leftWidth = 0, centerWidth = 0, rightWidth = 0;
+ var topHeight = 0, centerHeight = 0, bottomHeight = 0;
+
+ if (this._spriteFrameRotated)
+ {
+ rightWidth = capInsets.y;
+ centerWidth = capInsets.height;
+ leftWidth = spriteRectSize.height - centerWidth - rightWidth;
+
+ topHeight = capInsets.x;
+ centerHeight = capInsets.width;
+ bottomHeight = spriteRectSize.width - (topHeight + centerHeight);
+ }
+ else
+ {
+ leftWidth = capInsets.x;
+ centerWidth = capInsets.width;
+ rightWidth = spriteRectSize.width - (leftWidth + centerWidth);
+
+ topHeight = capInsets.y;
+ centerHeight = capInsets.height;
+ bottomHeight =spriteRectSize.height - (topHeight + centerHeight);
+ }
+
+ var textureRect = cc.rectPointsToPixels(this._spriteRect);
+ //handle .9.png
+ if (this._isPatch9)
+ {
+ //This magic number is used to avoiding artifact with .9.png format.
+ var offset = 1.3;
+ textureRect = cc.rect(textureRect.origin.x + offset,
+ textureRect.origin.y + offset,
+ textureRect.size.width - 2,
+ textureRect.size.height - 2);
+ }
+
+ //uv computation should take spritesheet into account.
+ var u0, u1, u2, u3;
+ var v0, v1, v2, v3;
+ if (this._spriteFrameRotated)
+ {
+ u0 = textureRect.x / atlasWidth;
+ u1 = (leftWidth + textureRect.x) / atlasWidth;
+ u2 = (leftWidth + centerWidth + textureRect.x) / atlasWidth;
+ u3 = (textureRect.x + textureRect.height) / atlasWidth;
+
+ v3 = textureRect.y / atlasHeight;
+ v2 = (topHeight + textureRect.y) / atlasHeight;
+ v1 = (topHeight + centerHeight + textureRect.y) / atlasHeight;
+ v0 = (textureRect.y + textureRect.width) / atlasHeight;
+ }
+ else
+ {
+ u0 = textureRect.x / atlasWidth;
+ u1 = (leftWidth + textureRect.x) / atlasWidth;
+ u2 = (leftWidth + centerWidth + textureRect.x) / atlasWidth;
+ u3 = (textureRect.x + textureRect.width) / atlasWidth;
+
+ v0 = textureRect.y / atlasHeight;
+ v1 = (topHeight + textureRect.y) / atlasHeight;
+ v2 = (topHeight + centerHeight + textureRect.y) / atlasHeight;
+ v3 = (textureRect.y + textureRect.height) / atlasHeight;
+ }
+
+ var uvCoordinates = [];
+ uvCoordinates.push(cc.p(u0,v3));
+ uvCoordinates.push(cc.p(u1,v2));
+ uvCoordinates.push(cc.p(u2,v1));
+ uvCoordinates.push(cc.p(u3,v0));
+
+ return uvCoordinates;
+ },
+
+ _calculateVertices : function(capInsets,spriteRectSize){
+ var leftWidth = 0, centerWidth = 0, rightWidth = 0;
+ var topHeight = 0, centerHeight = 0, bottomHeight = 0;
+
+ leftWidth = capInsets.x;
+ centerWidth = capInsets.width;
+ rightWidth = spriteRectSize.width - (leftWidth + centerWidth);
+
+ topHeight = capInsets.y;
+ centerHeight = capInsets.height;
+ bottomHeight = spriteRectSize.height - (topHeight + centerHeight);
+
+
+ leftWidth = leftWidth / cc.contentScaleFactor();
+ rightWidth = rightWidth / cc.contentScaleFactor();
+ topHeight = topHeight / cc.contentScaleFactor();
+ bottomHeight = bottomHeight / cc.contentScaleFactor();
+ var preferSize = this.getPreferredSize();
+ var sizableWidth = preferSize.width - leftWidth - rightWidth;
+ var sizableHeight = preferSize.height - topHeight - bottomHeight;
+ var x0,x1,x2,x3;
+ var y0,y1,y2,y3;
+ if(sizableWidth >= 0)
+ {
+ x0 = 0;
+ x1 = leftWidth;
+ x2 = leftWidth + sizableWidth;
+ x3 = preferSize.width;
+ }
+ else
+ {
+ var xScale = preferSize.width / (leftWidth + rightWidth);
+ x0 = 0;
+ x1 = x2 = leftWidth * xScale;
+ x3 = (leftWidth + rightWidth) * xScale;
+ }
+
+ if(sizableHeight >= 0)
+ {
+ y0 = 0;
+ y1 = bottomHeight;
+ y2 = bottomHeight + sizableHeight;
+ y3 = preferSize.height;
+ }
+ else
+ {
+ var yScale = preferSize.height / (topHeight + bottomHeight);
+ y0 = 0;
+ y1 = y2= bottomHeight * yScale;
+ y3 = (bottomHeight + topHeight) * yScale;
+ }
+
+ var vertices = [];
+ vertices.push(cc.p(x0,y0));
+ vertices.push(cc.p(x1,y1));
+ vertices.push(cc.p(x2,y2));
+ vertices.push(cc.p(x3,y3));
+
+ return vertices;
+ },
+
+ _onColorOpacityDirty : function() {
+ var color = this.getDisplayedColor();
+ color.a = this.getDisplayedOpacity();
+ var index;
+ var quadLength = this._quads.length;
+ for(index = 0; index < quadLength; ++index) {
+ //svar quad = this._quads[index];
+ this._quads[index]._bl.colors = color;
+ this._quads[index]._br.colors = color;
+ this._quads[index]._tl.colors = color;
+ this._quads[index]._tr.colors = color;
+ }
+ },
+
+ _calculateQuads : function(uv, vertices){
+ var color = this.getDisplayedColor();
+ color.a = this.getDisplayedOpacity() ;
+ if(this._renderingType == ccui.Scale9Sprite.RenderingType.SIMPLE)
+ {
+ var quad = new cc.V3F_C4B_T2F_Quad();
+ quad._bl.colors = color;
+ quad._br.colors = color;
+ quad._tl.colors = color;
+ quad._tr.colors = color;
+
+ quad._bl.vertices = new cc.Vertex3F(vertices[0].x,vertices[0].y,0);
+ quad._br.vertices = new cc.Vertex3F(vertices[3].x,vertices[0].y,0);
+ quad._tl.vertices = new cc.Vertex3F(vertices[0].x,vertices[3].y,0);
+ quad._tr.vertices = new cc.Vertex3F(vertices[3].x,vertices[3].y,0);
+
+ if (this._spriteFrameRotated)
+ {
+ quad._bl.texCoords = new cc.Tex2F(uv[0].x,uv[0].y);
+ quad._br.texCoords = new cc.Tex2F(uv[0].x,uv[3].y);
+ quad._tl.texCoords = new cc.Tex2F(uv[3].x,uv[0].y);
+ quad._tr.texCoords = new cc.Tex2F(uv[3].x,uv[3].y);
+ }
+ else
+ {
+ quad._bl.texCoords = new cc.Tex2F(uv[0].x,uv[0].y);
+ quad._br.texCoords = new cc.Tex2F(uv[3].x,uv[0].y);
+ quad._tl.texCoords = new cc.Tex2F(uv[0].x,uv[3].y);
+ quad._tr.texCoords = new cc.Tex2F(uv[3].x,uv[3].y);
+
+ }
+ this._quads.push(quad);
+
+ return;
+ }
+
+ for(var j = 0; j < 3; ++j) { //row
+ for(var i = 0; i < 3; ++i){ //column
+ var quad = new cc.V3F_C4B_T2F_Quad();
+ quad._bl.colors = color;
+ quad._br.colors = color;
+ quad._tl.colors = color;
+ quad._tr.colors = color;
+
+ quad._bl.vertices = new cc.Vertex3F(vertices[i].x,vertices[j].y,0);
+ quad._br.vertices = new cc.Vertex3F(vertices[i+1].x,vertices[j].y,0);
+ quad._tl.vertices = new cc.Vertex3F(vertices[i].x,vertices[j+1].y,0);
+ quad._tr.vertices = new cc.Vertex3F(vertices[i+1].x,vertices[j+1].y,0);
+
+ if (this._spriteFrameRotated)
+ {
+ quad._bl.texCoords = new cc.Tex2F(uv[j].x,uv[i].y);
+ quad._br.texCoords = new cc.Tex2F(uv[j].x,uv[i+1].y);
+ quad._tl.texCoords = new cc.Tex2F(uv[j+1].x,uv[i].y);
+ quad._tr.texCoords = new cc.Tex2F(uv[i+1].x,uv[j+1].y);
+ }
+ else
+ {
+ quad._bl.texCoords = new cc.Tex2F(uv[i].x,uv[j].y);
+ quad._br.texCoords = new cc.Tex2F(uv[i+1].x,uv[j].y);
+ quad._tl.texCoords = new cc.Tex2F(uv[i].x,uv[j+1].y);
+ quad._tr.texCoords = new cc.Tex2F(uv[i+1].x,uv[j+1].y);
+
+ }
+ this._quads.push(quad);
+ }
+ }
+ },
+
+ _createRenderCmd: function(){
+ if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ return new ccui.Scale9Sprite.CanvasRenderCmd(this);
+ else
+ return new ccui.Scale9Sprite.WebGLRenderCmd(this);
+ },
+});
+
+var _p = ccui.Scale9Sprite.prototype;
+EventTarget.polyfill(_p);
+
+// Extended properties
+/** @expose */
+_p.preferredSize;
+cc.defineGetterSetter(_p, "preferredSize", _p.getPreferredSize, _p.setPreferredSize);
+/** @expose */
+_p.capInsets;
+cc.defineGetterSetter(_p, "capInsets", _p.getCapInsets, _p.setCapInsets);
+/** @expose */
+_p.insetLeft;
+cc.defineGetterSetter(_p, "insetLeft", _p.getInsetLeft, _p.setInsetLeft);
+/** @expose */
+_p.insetTop;
+cc.defineGetterSetter(_p, "insetTop", _p.getInsetTop, _p.setInsetTop);
+/** @expose */
+_p.insetRight;
+cc.defineGetterSetter(_p, "insetRight", _p.getInsetRight, _p.setInsetRight);
+/** @expose */
+_p.insetBottom;
+cc.defineGetterSetter(_p, "insetBottom", _p.getInsetBottom, _p.setInsetBottom);
+
+_p = null;
+
+/**
+ * Creates a 9-slice sprite with a texture file, a delimitation zone and
+ * with the specified cap insets.
+ * @deprecated since v3.0, please use new ccui.Scale9Sprite(file, rect, capInsets) instead.
+ * @param {String|cc.SpriteFrame} file file name of texture or a cc.Sprite object
+ * @param {cc.Rect} rect the rect of the texture
+ * @param {cc.Rect} capInsets the cap insets of ccui.Scale9Sprite
+ * @returns {ccui.Scale9Sprite}
+ */
+ccui.Scale9Sprite.create = function (file, rect, capInsets) {
+ return new ccui.Scale9Sprite(file, rect, capInsets);
+};
+
+/**
+ * create a ccui.Scale9Sprite with Sprite frame.
+ * @deprecated since v3.0, please use "new ccui.Scale9Sprite(spriteFrame, capInsets)" instead.
+ * @param {cc.SpriteFrame} spriteFrame
+ * @param {cc.Rect} capInsets
+ * @returns {ccui.Scale9Sprite}
+ */
+ccui.Scale9Sprite.createWithSpriteFrame = function (spriteFrame, capInsets) {
+ return new ccui.Scale9Sprite(spriteFrame, capInsets);
+};
+
+/**
+ * create a ccui.Scale9Sprite with a Sprite frame name
+ * @deprecated since v3.0, please use "new ccui.Scale9Sprite(spriteFrameName, capInsets)" instead.
+ * @param {string} spriteFrameName
+ * @param {cc.Rect} capInsets
+ * @returns {Scale9Sprite}
+ */
+ccui.Scale9Sprite.createWithSpriteFrameName = function (spriteFrameName, capInsets) {
+ return new ccui.Scale9Sprite(spriteFrameName, capInsets);
+};
+
+/**
+ * @ignore
+ */
+ccui.Scale9Sprite.POSITIONS_CENTRE = 0;
+ccui.Scale9Sprite.POSITIONS_TOP = 1;
+ccui.Scale9Sprite.POSITIONS_LEFT = 2;
+ccui.Scale9Sprite.POSITIONS_RIGHT = 3;
+ccui.Scale9Sprite.POSITIONS_BOTTOM = 4;
+ccui.Scale9Sprite.POSITIONS_TOPRIGHT = 5;
+ccui.Scale9Sprite.POSITIONS_TOPLEFT = 6;
+ccui.Scale9Sprite.POSITIONS_BOTTOMRIGHT = 7;
+
+ccui.Scale9Sprite.state = {NORMAL: 0, GRAY: 1};
+ccui.Scale9Sprite.RenderingType = {SIMPLE: 0, SLICE: 1};
diff --git a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js
new file mode 100644
index 0000000000..2aa45819a9
--- /dev/null
+++ b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js
@@ -0,0 +1,141 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+(function() {
+ ccui.Scale9Sprite.CanvasRenderCmd = function (renderable) {
+ cc.Node.CanvasRenderCmd.call(this, renderable);
+ this._needDraw = true;
+ this._state = ccui.Scale9Sprite.state.NORMAL;
+ this._textureToRender = null;
+ };
+
+ var proto = ccui.Scale9Sprite.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
+ proto.constructor = ccui.Scale9Sprite.CanvasRenderCmd;
+
+ proto._updateDisplayOpacity = function(parentOpacity){
+ cc.Node.WebGLRenderCmd.prototype._updateDisplayOpacity.call(this, parentOpacity);
+ var node = this._node;
+ var scale9Image = node._scale9Image;
+ if(scale9Image) {
+ var opacity = 255;
+ if (node._cascadeOpacityEnabled) opacity = this._displayedOpacity;
+ scale9Image._renderCmd._updateDisplayOpacity(opacity);
+ }
+ };
+
+ proto._updateDisplayColor = function(parentColor){
+ cc.Node.WebGLRenderCmd.prototype._updateDisplayColor.call(this, parentColor);
+ var node = this._node;
+ var scale9Image = node._scale9Image;
+ if(scale9Image){
+ var color = cc.Color.WHITE;
+ if(this._cascadeColorEnabled) color = node._displayedColor;
+ scale9Image._renderCmd._updateDisplayColor(color);
+ scale9Image._renderCmd._updateColor();
+ }
+ this._textureToRender = null;
+ };
+
+ proto.setState = function(state){
+ if(this._state === state) return;
+
+ var locScale9Image = this._node._scale9Image;
+ if(!locScale9Image)
+ return;
+ this._state = state;
+ this._textureToRender = null;
+ };
+
+ proto.rendering = function (ctx, scaleX, scaleY) {
+ var node = this._node;
+ if(!node._scale9Enabled)
+ return;
+ var locDisplayOpacity = this._displayedOpacity;
+ var alpha = locDisplayOpacity/ 255;
+ var locTexture = null;
+ if(node.getSprite()) locTexture = node.getSprite()._texture;
+ if (!node._textureLoaded || locDisplayOpacity === 0)
+ return;
+ if(this._textureToRender === null){
+ this._textureToRender = locTexture;
+ if (cc.Scale9Sprite.state.GRAY === this._state) {
+ this._textureToRender = this._textureToRender._generateGrayTexture();
+ }
+ var color = node.getDisplayedColor();
+ if(locTexture && (color.r !== 255 || color.g !==255 || color.b !== 255))
+ this._textureToRender = locTexture._generateColorTexture(color.r,color.g,color.b);
+ }
+
+ var wrapper = ctx || cc._renderContext, context = wrapper.getContext();
+ wrapper.setTransform(this._worldTransform, scaleX, scaleY);
+ wrapper.setCompositeOperation(node._blendFunc);
+ wrapper.setGlobalAlpha(alpha);
+
+ if(this._textureToRender) {
+ if(node._quadsDirty){
+ node._cleanupQuads();
+ node._buildQuads();
+ node._quadsDirty = false;
+ }
+
+ var quads = node._quads;
+ for( var i = 0; i < quads.length; ++i)
+ {
+ var sx,sy,sw,sh;
+ var x, y, w,h;
+
+ x = quads[i]._bl.vertices.x;
+ y = quads[i]._bl.vertices.y;
+ w = quads[i]._tr.vertices.x - quads[i]._bl.vertices.x;
+ h = quads[i]._tr.vertices.y - quads[i]._bl.vertices.y;
+ y = - y - h;
+
+ var textureWidth = this._textureToRender.getPixelWidth();
+ var textureHeight = this._textureToRender.getPixelHeight();
+
+ sx = quads[i]._bl.texCoords.u * textureWidth;
+ sy = quads[i]._bl.texCoords.v * textureHeight;
+ sw = (quads[i]._tr.texCoords.u - quads[i]._bl.texCoords.u) * textureWidth;
+ sh = (quads[i]._tr.texCoords.v - quads[i]._bl.texCoords.v) * textureHeight;
+
+ x = x * scaleX;
+ y = y * scaleY;
+ w = w * scaleX;
+ h = h * scaleY;
+
+ var image = this._textureToRender._htmlElementObj;
+ if (this._textureToRender._pattern !== "") {
+ wrapper.setFillStyle(context.createPattern(image, this._textureToRender._pattern));
+ context.fillRect(x, y, w, h);
+ } else {
+ context.drawImage(image,
+ sx, sy, sw, sh,
+ x, y, w, h);
+ }
+ }
+
+ }
+ cc.g_NumberOfDraws = cc.g_NumberOfDraws + 9;
+ }
+})();
\ No newline at end of file
diff --git a/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js b/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js
new file mode 100644
index 0000000000..cbf1aa0d41
--- /dev/null
+++ b/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js
@@ -0,0 +1,180 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+(function() {
+ if(!cc.Node.WebGLRenderCmd)
+ return;
+ ccui.Scale9Sprite.WebGLRenderCmd = function (renderable) {
+ cc.Node.WebGLRenderCmd.call(this, renderable);
+ this._needDraw = true;
+ this._cachedParent = null;
+ this._cacheDirty = false;
+ this._quadWebBuffer = cc._renderContext.createBuffer();
+ this._colorOpacityDirty = false;
+ };
+
+ var proto = ccui.Scale9Sprite.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
+ proto.constructor = ccui.Scale9Sprite.WebGLRenderCmd;
+
+ proto.rendering = function (ctx){
+ var node = this._node;
+ if(!node._scale9Enabled)
+ return;
+
+ var locTexture = null;
+ if(node.getSprite()) locTexture = node.getSprite()._texture;
+ if (!node.textureLoaded() || this._displayedOpacity === 0)
+ return;
+ var needRebuildWebBuffer = false;
+ if(node._quadsDirty){
+ node._cleanupQuads();
+ node._buildQuads();
+ node._quadsDirty = false;
+ this._colorOpacityDirty = false;
+ needRebuildWebBuffer = true;
+ }
+ if(this._colorOpacityDirty) {
+ node._onColorOpacityDirty();
+ this._colorOpacityDirty = false;
+ needRebuildWebBuffer = true;
+ }
+ var gl = ctx || cc._renderContext ;
+
+ if(locTexture != null)
+ {
+ this._shaderProgram.use();
+ this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix);
+
+ cc.glBlendFunc(node._blendFunc.src, node._blendFunc.dst);
+ //optimize performance for javascript
+ cc.glBindTexture2DN(0, locTexture); // = cc.glBindTexture2D(locTexture);
+ cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POS_COLOR_TEX);
+
+ gl.bindBuffer(gl.ARRAY_BUFFER, this._quadWebBuffer);
+
+ var quads = node._quads;
+ var bufferOffset = 0;
+ var quadsLength = quads.length;
+ if(quadsLength == 0) return;
+ if (needRebuildWebBuffer)
+ {
+ gl.bufferData(gl.ARRAY_BUFFER,quads[0].arrayBuffer.byteLength * quads.length, gl.DYNAMIC_DRAW);
+ for(var i = 0; i < quads.length; ++i){
+ gl.bufferSubData(gl.ARRAY_BUFFER, bufferOffset,quads[i].arrayBuffer);
+ bufferOffset = bufferOffset + quads[i].arrayBuffer.byteLength;
+ }
+ }
+ bufferOffset = 0;
+ for(var i = 0; i < quads.length; ++i)
+ {
+ gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 24, bufferOffset); //cc.VERTEX_ATTRIB_POSITION
+ gl.vertexAttribPointer(1, 4, gl.UNSIGNED_BYTE, true, 24, 12 + bufferOffset); //cc.VERTEX_ATTRIB_COLOR
+ gl.vertexAttribPointer(2, 2, gl.FLOAT, false, 24, 16 + bufferOffset); //cc.VERTEX_ATTRIB_TEX_COORDS
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
+ bufferOffset = bufferOffset + quads[i].arrayBuffer.byteLength;
+ }
+
+ cc.g_NumberOfDraws += quads.length;
+
+ }
+
+ };
+
+ proto._updateDisplayOpacity = function(parentOpacity){
+ cc.Node.WebGLRenderCmd.prototype._updateDisplayOpacity.call(this, parentOpacity);
+ var node = this._node;
+ var scale9Image = node._scale9Image;
+ if(scale9Image) {
+ var opacity = 255;
+ if (node._cascadeOpacityEnabled) opacity = this._displayedOpacity;
+ scale9Image._renderCmd._updateDisplayOpacity(opacity);
+ }
+
+ this._colorOpacityDirty = true;
+ };
+
+ proto._updateDisplayColor = function(parentColor){
+ cc.Node.WebGLRenderCmd.prototype._updateDisplayColor.call(this, parentColor);
+ var node = this._node;
+ var scale9Image = node._scale9Image;
+ if(scale9Image){
+ var color = cc.Color.WHITE;
+ if(this._cascadeColorEnabled) color = node._displayedColor;
+ scale9Image._renderCmd._updateDisplayColor(color);
+ scale9Image._renderCmd._updateColor();
+ }
+
+ this._colorOpacityDirty = true;
+ };
+
+ proto.setState = function (state) {
+ var node = this._node;
+ var scale9Image = this._node._scale9Image;
+ if(!node.isScale9Enabled)
+ {
+ if (state === ccui.Scale9Sprite.state.NORMAL) {
+ scale9Image.setShaderProgram(cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURECOLOR));
+ } else if (state === ccui.Scale9Sprite.state.GRAY) {
+ scale9Image.setShaderProgram(ccui.Scale9Sprite.WebGLRenderCmd._getGrayShaderProgram());
+ }
+ }
+ else
+ {
+ if (state === ccui.Scale9Sprite.state.NORMAL) {
+ node.setShaderProgram(cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURECOLOR));
+ } else if (state === ccui.Scale9Sprite.state.GRAY) {
+ node.setShaderProgram(ccui.Scale9Sprite.WebGLRenderCmd._getGrayShaderProgram());
+ }
+ }
+ };
+
+ ccui.Scale9Sprite.WebGLRenderCmd._grayShaderProgram = null;
+ ccui.Scale9Sprite.WebGLRenderCmd._getGrayShaderProgram = function(){
+ var grayShader = ccui.Scale9Sprite.WebGLRenderCmd._grayShaderProgram;
+ if(grayShader)
+ return grayShader;
+
+ grayShader = new cc.GLProgram();
+ grayShader.initWithVertexShaderByteArray(cc.SHADER_POSITION_TEXTURE_COLOR_VERT, ccui.Scale9Sprite.WebGLRenderCmd._grayShaderFragment);
+ grayShader.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
+ grayShader.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR);
+ grayShader.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
+ grayShader.link();
+ grayShader.updateUniforms();
+
+ ccui.Scale9Sprite.WebGLRenderCmd._grayShaderProgram = grayShader;
+ return grayShader;
+ };
+
+ ccui.Scale9Sprite.WebGLRenderCmd._grayShaderFragment =
+ "precision lowp float;\n"
+ + "varying vec4 v_fragmentColor; \n"
+ + "varying vec2 v_texCoord; \n"
+ + "void main() \n"
+ + "{ \n"
+ + " vec4 c = texture2D(CC_Texture0, v_texCoord); \n"
+ + " gl_FragColor.xyz = vec3(0.2126*c.r + 0.7152*c.g + 0.0722*c.b); \n"
+ +" gl_FragColor.w = c.w ; \n"
+ + "}";
+})();
\ No newline at end of file
diff --git a/extensions/ccui/base-classes/UIWidget.js b/extensions/ccui/base-classes/UIWidget.js
new file mode 100644
index 0000000000..d46cdaa8e6
--- /dev/null
+++ b/extensions/ccui/base-classes/UIWidget.js
@@ -0,0 +1,2069 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+EventTarget = require("../cocos2d/core/event/event-target");
+
+ccui._FocusNavigationController = cc._Class.extend({
+ _keyboardListener: null,
+ _firstFocusedWidget: null,
+ _enableFocusNavigation: false,
+ _keyboardEventPriority: 1,
+
+ enableFocusNavigation: function(flag){
+ if (this._enableFocusNavigation === flag)
+ return;
+
+ this._enableFocusNavigation = flag;
+ if (flag)
+ this._addKeyboardEventListener();
+ else
+ this._removeKeyboardEventListener();
+ },
+
+ _setFirstFocsuedWidget: function(widget){
+ this._firstFocusedWidget = widget;
+ },
+
+ _onKeyPressed: function(keyCode, event){
+ if (this._enableFocusNavigation && this._firstFocusedWidget) {
+ if (keyCode === cc.KEY.dpadDown) {
+ this._firstFocusedWidget = this._firstFocusedWidget.findNextFocusedWidget(ccui.Widget.DOWN, this._firstFocusedWidget);
+ }
+ if (keyCode === cc.KEY.dpadUp){
+ this._firstFocusedWidget = this._firstFocusedWidget.findNextFocusedWidget(ccui.Widget.UP, this._firstFocusedWidget);
+ }
+ if (keyCode === cc.KEY.dpadLeft) {
+ this._firstFocusedWidget = this._firstFocusedWidget.findNextFocusedWidget(ccui.Widget.LEFT, this._firstFocusedWidget);
+ }
+ if (keyCode === cc.KEY.dpadRight) {
+ this._firstFocusedWidget = this._firstFocusedWidget.findNextFocusedWidget(ccui.Widget.RIGHT, this._firstFocusedWidget);
+ }
+ }
+ },
+
+ _addKeyboardEventListener: function(){
+ if (!this._keyboardListener) {
+ this._keyboardListener = cc.EventListener.create({
+ event: cc.EventListener.KEYBOARD,
+ onKeyReleased: this._onKeyPressed.bind(this)
+ });
+ cc.eventManager.addListener(this._keyboardListener, this._keyboardEventPriority);
+ }
+ },
+
+ _removeKeyboardEventListener: function(){
+ if (this._keyboardListener) {
+ cc.eventManager.removeEventListener(this._keyboardListener);
+ this._keyboardListener = null;
+ }
+ }
+});
+
+ccui.__LAYOUT_COMPONENT_NAME = "__ui_layout";
+
+/**
+ * The base class for ccui controls and layout
+ * @sample
+ * var uiWidget = new ccui.Widget();
+ * this.addChild(uiWidget);
+ * @class
+ * @extends ccui.ProtectedNode
+ *
+ * @property {Number} xPercent - Position x in percentage of width
+ * @property {Number} yPercent - Position y in percentage of height
+ * @property {Number} widthPercent - Width in percentage of parent width
+ * @property {Number} heightPercent - Height in percentage of parent height
+ * @property {ccui.Widget} widgetParent - <@readonly> The direct parent when it's a widget also, otherwise equals null
+ * @property {Boolean} enabled - Indicate whether the widget is enabled
+ * @property {Boolean} focused - Indicate whether the widget is focused
+ * @property {ccui.Widget.SIZE_ABSOLUTE|ccui.Widget.SIZE_PERCENT} sizeType - The size type of the widget
+ * @property {ccui.Widget.TYPE_WIDGET|ccui.Widget.TYPE_CONTAINER} widgetType - <@readonly> The type of the widget
+ * @property {Boolean} touchEnabled - Indicate whether touch events are enabled
+ * @property {Boolean} updateEnabled - Indicate whether the update function is scheduled
+ * @property {Boolean} bright - Indicate whether the widget is bright
+ * @property {String} name - The name of the widget
+ * @property {Number} actionTag - The action tag of the widget
+ */
+ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
+ _enabled: true, ///< Highest control of widget
+ _bright: true, ///< is this widget bright
+ _touchEnabled: false, ///< is this widget touch endabled
+
+ _brightStyle: null, ///< bright style
+
+ _touchBeganPosition: null, ///< touch began point
+ _touchMovePosition: null, ///< touch moved point
+ _touchEndPosition: null, ///< touch ended point
+
+ _touchEventListener: null,
+ _touchEventSelector: null,
+
+ _name: "default",
+ _widgetType: null,
+ _actionTag: 0,
+ _customSize: null,
+ _layoutParameterDictionary: null,
+ _layoutParameterType:0,
+
+ _focused: false,
+ _focusEnabled: true,
+
+ _ignoreSize: false,
+ _affectByClipping: false,
+
+ _sizeType: null,
+ _sizePercent: null,
+ _positionType: null,
+ _positionPercent: null,
+ _hit: false,
+ _nodes: null,
+ _touchListener: null,
+ _className: "Widget",
+ _flippedX: false,
+ _flippedY: false,
+ _opacity: 255,
+ _highlight: false,
+
+ _touchEventCallback: null,
+ _clickEventListener: null,
+
+ _propagateTouchEvents: true,
+ _unifySize: false,
+
+ _callbackName: null,
+ _callbackType: null,
+ _usingLayoutComponent: false,
+ _inViewRect: true,
+
+ /**
+ * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
+ * @function
+ */
+ ctor: function () {
+ cc.ProtectedNode.prototype.ctor.call(this);
+ this._brightStyle = ccui.Widget.BRIGHT_STYLE_NONE;
+ this._touchBeganPosition = cc.p(0, 0);
+ this._touchMovePosition = cc.p(0, 0);
+ this._touchEndPosition = cc.p(0, 0);
+ this._widgetType = ccui.Widget.TYPE_WIDGET;
+ this._customSize = cc.size(0, 0);
+ this._layoutParameterDictionary = {};
+ this._sizeType = ccui.Widget.SIZE_ABSOLUTE;
+ this._sizePercent = cc.p(0, 0);
+ this._positionType = ccui.Widget.POSITION_ABSOLUTE;
+ this._positionPercent = cc.p(0, 0);
+ this._nodes = [];
+ this._layoutParameterType = ccui.LayoutParameter.NONE;
+ this.init(); //TODO
+ },
+
+ /**
+ * initializes state of widget. please do not call this function by yourself, you should pass the parameters to constructor to initialize it.
+ * @returns {boolean}
+ */
+ init: function () {
+ if (cc.ProtectedNode.prototype.init.call(this)) {
+ this._layoutParameterDictionary = {};
+ this._initRenderer();
+ this.setBright(true);
+
+ this.onFocusChanged = this.onFocusChange.bind(this);
+ this.onNextFocusedWidget = null;
+ this.setAnchorPoint(cc.p(0.5, 0.5));
+
+ this.ignoreContentAdaptWithSize(true);
+ return true;
+ }
+ return false;
+ },
+
+ /**
+ * Calls updateSizeAndPosition and its parent's onEnter
+ * @override
+ */
+ onEnter: function () {
+ var locListener = this._touchListener;
+ if (locListener && !locListener._isRegistered() && this._touchEnabled)
+ cc.eventManager.addListener(locListener, this);
+ if(!this._usingLayoutComponent)
+ this.updateSizeAndPosition();
+ cc.ProtectedNode.prototype.onEnter.call(this);
+ },
+
+ /**
+ * Calls unscheduleUpdate and its parent's onExit
+ * @override
+ */
+ onExit: function(){
+ this.unscheduleUpdate();
+ cc.ProtectedNode.prototype.onExit.call(this);
+ },
+
+ _getOrCreateLayoutComponent: function(){
+ var layoutComponent = this.getComponent(ccui.__LAYOUT_COMPONENT_NAME);
+ if (null == layoutComponent){
+ layoutComponent = new ccui.LayoutComponent();
+ this.addComponent(layoutComponent);
+ }
+ return layoutComponent;
+ },
+
+ /**
+ * The direct parent when it's a widget also, otherwise equals null
+ * @returns {ccui.Widget|null}
+ */
+ getWidgetParent: function () {
+ var widget = this.getParent();
+ if (widget instanceof ccui.Widget)
+ return widget;
+ return null;
+ },
+
+ _updateContentSizeWithTextureSize: function(size){
+ if(this._unifySize){
+ this.setContentSize(size);
+ return;
+ }
+ this.setContentSize(this._ignoreSize ? size : this._customSize);
+ },
+
+ _isAncestorsEnabled: function(){
+ var parentWidget = this._getAncensterWidget(this);
+ if (parentWidget == null)
+ return true;
+ if (parentWidget && !parentWidget.isEnabled())
+ return false;
+
+ return parentWidget._isAncestorsEnabled();
+ },
+
+ /**
+ * Allow widget touch events to propagate to its parents. Set false will disable propagation
+ * @since v3.2
+ * @param {Boolean} isPropagate
+ */
+ setPropagateTouchEvents: function(isPropagate){
+ this._propagateTouchEvents = isPropagate;
+ },
+
+ /**
+ * Return whether the widget is propagate touch events to its parents or not
+ * @since v3.2
+ * @returns {boolean}
+ */
+ isPropagateTouchEvents: function(){
+ return this._propagateTouchEvents;
+ },
+
+ /**
+ * Specify widget to swallow touches or not
+ * @since v3.2
+ * @param {Boolean} swallow
+ */
+ setSwallowTouches: function(swallow){
+ if (this._touchListener)
+ this._touchListener.setSwallowTouches(swallow);
+ },
+
+ /**
+ * Return whether the widget is swallowing touch or not
+ * @since v3.2
+ * @returns {boolean}
+ */
+ isSwallowTouches: function(){
+ if (this._touchListener){
+ //return true; //todo need test
+ return this._touchListener.isSwallowTouches();
+ }
+ return false;
+ },
+
+ _getAncensterWidget: function(node){
+ if (null == node)
+ return null;
+
+ var parent = node.getParent();
+ if (null == parent)
+ return null;
+
+ if (parent instanceof ccui.Widget)
+ return parent;
+ else
+ return this._getAncensterWidget(parent.getParent());
+ },
+
+ _isAncestorsVisible: function(node){
+ if (null == node)
+ return true;
+
+ var parent = node.getParent();
+
+ if (parent && !parent.isVisible())
+ return false;
+ return this._isAncestorsVisible(parent);
+ },
+
+ _cleanupWidget: function(){
+ //clean up _touchListener
+ this._eventDispatcher.removeEventListener(this._touchListener);
+ this._touchEnabled = false;
+ this._touchListener = null;
+
+ //cleanup focused widget and focus navigation controller
+ if (ccui.Widget._focusedWidget === this){
+ ccui.Widget._focusedWidget = null;
+ ccui.Widget._focusNavigationController = null;
+ }
+ },
+
+ /**
+ *
+ * Sets whether the widget is enabled
+ * true if the widget is enabled, widget may be touched , false if the widget is disabled, widget cannot be touched.
+ * The default value is true, a widget is default to enabled
+ *
+ * @param {Boolean} enabled
+ */
+ setEnabled: function (enabled) {
+ this._enabled = enabled;
+ },
+
+ /**
+ * initializes renderer of widget.
+ */
+ _initRenderer: function () {},
+
+ /**
+ * Sets _customSize of ccui.Widget, if ignoreSize is true, the content size is its renderer's contentSize, otherwise the content size is parameter.
+ * and updates size percent by parent content size. At last, updates its children's size and position.
+ * @param {cc.Size|Number} contentSize content size or width of content size
+ * @param {Number} [height]
+ * @override
+ */
+ setContentSize: function(contentSize, height){
+ var locWidth = (height === undefined) ? contentSize.width : contentSize;
+ var locHeight = (height === undefined) ? contentSize.height : height;
+ cc.Node.prototype.setContentSize.call(this, locWidth, locHeight);
+
+ this._customSize.width = locWidth;
+ this._customSize.height = locHeight;
+ if(this._unifySize){
+ //unify size logic
+ } else if (this._ignoreSize){
+ this._contentSize = this.getVirtualRendererSize();
+ }
+ if (!this._usingLayoutComponent && this._running) {
+ var widgetParent = this.getWidgetParent();
+ var pSize = widgetParent ? widgetParent.getContentSize() : this._parent.getContentSize();
+ this._sizePercent.x = (pSize.width > 0.0) ? locWidth / pSize.width : 0.0;
+ this._sizePercent.y = (pSize.height > 0.0) ? locHeight / pSize.height : 0.0;
+ }
+ this._onSizeChanged();
+ },
+
+ _setWidth: function (w) {
+ cc.Node.prototype._setWidth.call(this, w);
+ this._customSize.width = w;
+ if(this._unifySize){
+ //unify size logic
+ } else if (this._ignoreSize){
+ this._contentSize = this.getVirtualRendererSize();
+ }
+
+ if (!this._usingLayoutComponent && this._running) {
+ var widgetParent = this.getWidgetParent();
+ var locWidth = widgetParent ? widgetParent.width : this._parent.width;
+ this._sizePercent.x = locWidth > 0 ? this._customSize.width / locWidth : 0;
+ }
+ this._onSizeChanged();
+ },
+ _setHeight: function (h) {
+ cc.Node.prototype._setHeight.call(this, h);
+ this._customSize.height = h;
+ if(this._unifySize){
+ //unify size logic
+ } else if (this._ignoreSize){
+ this._contentSize = this.getVirtualRendererSize();
+ }
+
+ if (!this._usingLayoutComponent && this._running) {
+ var widgetParent = this.getWidgetParent();
+ var locH = widgetParent ? widgetParent.height : this._parent.height;
+ this._sizePercent.y = locH > 0 ? this._customSize.height / locH : 0;
+ }
+ this._onSizeChanged();
+ },
+
+ /**
+ * Changes the percent that is widget's percent size
+ * @param {cc.Vec2} percent that is widget's percent size, width and height value from 0 to 1.
+ */
+ setSizePercent: function (percent) {
+ if(this._usingLayoutComponent){
+ var component = this._getOrCreateLayoutComponent();
+ component.setUsingPercentContentSize(true);
+ component.setPercentContentSize(percent);
+ component.refreshLayout();
+ return;
+ }
+
+ this._sizePercent.x = percent.x;
+ this._sizePercent.y = percent.y;
+ var width = this._customSize.width, height = this._customSize.height;
+ if (this._running) {
+ var widgetParent = this.getWidgetParent();
+ if (widgetParent) {
+ width = widgetParent.width * percent.x;
+ height = widgetParent.height * percent.y;
+ } else {
+ width = this._parent.width * percent.x;
+ height = this._parent.height * percent.y;
+ }
+ }
+ if (this._ignoreSize)
+ this.setContentSize(this.getVirtualRendererSize());
+ else
+ this.setContentSize(width, height);
+
+ this._customSize.width = width;
+ this._customSize.height = height;
+ },
+
+ _setWidthPercent: function (percent) {
+ this._sizePercent.x = percent;
+ var width = this._customSize.width;
+ if (this._running) {
+ var widgetParent = this.getWidgetParent();
+ width = (widgetParent ? widgetParent.width : this._parent.width) * percent;
+ }
+ if (this._ignoreSize)
+ this._setWidth(this.getVirtualRendererSize().width);
+ else
+ this._setWidth(width);
+ this._customSize.width = width;
+ },
+ _setHeightPercent: function (percent) {
+ this._sizePercent.y = percent;
+ var height = this._customSize.height;
+ if (this._running) {
+ var widgetParent = this.getWidgetParent();
+ height = (widgetParent ? widgetParent.height : this._parent.height) * percent;
+ }
+ if (this._ignoreSize)
+ this._setHeight(this.getVirtualRendererSize().height);
+ else
+ this._setHeight(height);
+ this._customSize.height = height;
+ },
+
+ /**
+ * updates its size by size type and its position by position type.
+ * @param {cc.Size} [parentSize] parent size
+ */
+ updateSizeAndPosition: function (parentSize) {
+ if(!parentSize){
+ var widgetParent = this.getWidgetParent();
+ if(widgetParent)
+ parentSize = widgetParent.getLayoutSize();
+ else
+ parentSize = this._parent.getContentSize();
+ }
+
+ switch (this._sizeType) {
+ case ccui.Widget.SIZE_ABSOLUTE:
+ if(this._ignoreSize)
+ this.setContentSize(this.getVirtualRendererSize());
+ else
+ this.setContentSize(this._customSize);
+ this._sizePercent.x = (parentSize.width > 0) ? this._customSize.width / parentSize.width : 0;
+ this._sizePercent.y = (parentSize.height > 0) ? this._customSize.height / parentSize.height : 0;
+ break;
+ case ccui.Widget.SIZE_PERCENT:
+ var cSize = cc.size(parentSize.width * this._sizePercent.x , parentSize.height * this._sizePercent.y);
+ if(this._ignoreSize)
+ this.setContentSize(this.getVirtualRendererSize());
+ else
+ this.setContentSize(cSize);
+ this._customSize.width = cSize.width;
+ this._customSize.height = cSize.height;
+ break;
+ default:
+ break;
+ }
+ this._onSizeChanged();
+ var absPos = this.getPosition();
+ switch (this._positionType) {
+ case ccui.Widget.POSITION_ABSOLUTE:
+ if (parentSize.width <= 0 || parentSize.height <= 0) {
+ this._positionPercent.x = this._positionPercent.y = 0;
+ } else {
+ this._positionPercent.x = absPos.x / parentSize.width;
+ this._positionPercent.y = absPos.y / parentSize.height;
+ }
+ break;
+ case ccui.Widget.POSITION_PERCENT:
+ absPos = cc.p(parentSize.width * this._positionPercent.x, parentSize.height * this._positionPercent.y);
+ break;
+ default:
+ break;
+ }
+ if(this._parent instanceof ccui.ImageView){
+ var renderer = this._parent._imageRenderer;
+ if(renderer && !renderer._textureLoaded)
+ return;
+ }
+ this.setPosition(absPos);
+ },
+
+ /**TEXTURE_RES_TYPE
+ * Changes the size type of widget.
+ * @param {ccui.Widget.SIZE_ABSOLUTE|ccui.Widget.SIZE_PERCENT} type that is widget's size type
+ */
+ setSizeType: function (type) {
+ this._sizeType = type;
+ if (this._usingLayoutComponent) {
+ var component = this._getOrCreateLayoutComponent();
+ component.setUsingPercentContentSize(this._sizeType === ccui.SIZE_PERCENT);
+ }
+ },
+
+ /**
+ * Gets the size type of widget.
+ * @returns {ccui.Widget.SIZE_ABSOLUTE|ccui.Widget.SIZE_PERCENT} that is widget's size type
+ */
+ getSizeType: function () {
+ return this._sizeType;
+ },
+
+ /**
+ * Ignore the widget size
+ * @param {Boolean} ignore true that widget will ignore it's size, use texture size, false otherwise. Default value is true.
+ */
+ ignoreContentAdaptWithSize: function (ignore) {
+ if(this._unifySize){
+ this.setContentSize(this._customSize);
+ return;
+ }
+
+ if(this._ignoreSize === ignore)
+ return;
+
+ this._ignoreSize = ignore;
+ this.setContentSize( ignore ? this.getVirtualRendererSize() : this._customSize );
+ //this._onSizeChanged();
+ },
+
+ /**
+ * Gets whether ignore the content size (custom size)
+ * @returns {boolean} true that widget will ignore it's size, use texture size, false otherwise.
+ */
+ isIgnoreContentAdaptWithSize: function () {
+ return this._ignoreSize;
+ },
+
+ /**
+ * Get custom size of ccui.Widget
+ * @returns {cc.Size}
+ */
+ getCustomSize: function () {
+ return cc.size(this._customSize);
+ },
+
+ /**
+ * Gets layout size of ccui.Widget.
+ * @returns {cc.Size}
+ */
+ getLayoutSize: function(){
+ return cc.size(this._contentSize);
+ },
+
+ /**
+ * Returns size percent of ccui.Widget
+ * @returns {cc.Vec2}
+ */
+ getSizePercent: function () {
+ if(this._usingLayoutComponent){
+ var component = this._getOrCreateLayoutComponent();
+ this._sizePercent = component.getPercentContentSize();
+ }
+ return this._sizePercent;
+ },
+ _getWidthPercent: function () {
+ return this._sizePercent.x;
+ },
+ _getHeightPercent: function () {
+ return this._sizePercent.y;
+ },
+
+ /**
+ * Gets world position of ccui.Widget.
+ * @returns {cc.Vec2} world position of ccui.Widget.
+ */
+ getWorldPosition: function () {
+ return this.convertToWorldSpace(cc.p(this._anchorPoint.x * this._contentSize.width, this._anchorPoint.y * this._contentSize.height));
+ },
+
+ /**
+ * Gets the Virtual Renderer of widget.
+ * @returns {ccui.Widget}
+ */
+ getVirtualRenderer: function () {
+ return this;
+ },
+
+ /**
+ * Gets the content size of widget. Content size is widget's texture size.
+ */
+ getVirtualRendererSize:function(){
+ return cc.size(this._contentSize);
+ },
+
+ /**
+ * call back function called when size changed.
+ */
+ _onSizeChanged: function () {
+ if(!this._usingLayoutComponent){
+ var locChildren = this.getChildren();
+ for (var i = 0, len = locChildren.length; i < len; i++) {
+ var child = locChildren[i];
+ if(child instanceof ccui.Widget)
+ child.updateSizeAndPosition();
+ }
+ }
+ },
+
+ /**
+ * Sets whether the widget is touch enabled. The default value is false, a widget is default to touch disabled
+ * @param {Boolean} enable true if the widget is touch enabled, false if the widget is touch disabled.
+ */
+ setTouchEnabled: function (enable) {
+ if (this._touchEnabled === enable)
+ return;
+
+ this._touchEnabled = enable; //TODO need consider remove and re-add.
+ if (this._touchEnabled) {
+ if(!this._touchListener)
+ this._touchListener = cc.EventListener.create({
+ event: cc.EventListener.TOUCH_ONE_BY_ONE,
+ swallowTouches: true,
+ onTouchBegan: this.onTouchBegan.bind(this),
+ onTouchMoved: this.onTouchMoved.bind(this),
+ onTouchEnded: this.onTouchEnded.bind(this)
+ });
+ cc.eventManager.addListener(this._touchListener, this);
+ } else {
+ cc.eventManager.removeListener(this._touchListener);
+ }
+ },
+
+ /**
+ * Returns whether or not touch is enabled.
+ * @returns {boolean} true if the widget is touch enabled, false if the widget is touch disabled.
+ */
+ isTouchEnabled: function () {
+ return this._touchEnabled;
+ },
+
+ /**
+ * Determines if the widget is highlighted
+ * @returns {boolean} true if the widget is highlighted, false if the widget is not highlighted .
+ */
+ isHighlighted: function(){
+ return this._highlight;
+ },
+
+ /**
+ * Sets whether the widget is highlighted. The default value is false, a widget is default to not highlighted
+ * @param highlight true if the widget is highlighted, false if the widget is not highlighted.
+ */
+ setHighlighted:function(highlight){
+ if (highlight === this._highlight)
+ return;
+ this._highlight = highlight;
+ if (this._bright) {
+ if (this._highlight)
+ this.setBrightStyle(ccui.Widget.BRIGHT_STYLE_HIGH_LIGHT);
+ else
+ this.setBrightStyle(ccui.Widget.BRIGHT_STYLE_NORMAL);
+ } else
+ this._onPressStateChangedToDisabled();
+ },
+
+ /**
+ * Determines if the widget is on focused
+ * @returns {boolean} whether the widget is focused or not
+ */
+ isFocused: function () {
+ return this._focused;
+ },
+
+ /**
+ * Sets whether the widget is on focused
+ * The default value is false, a widget is default to not on focused
+ * @param {boolean} focus pass true to let the widget get focus or pass false to let the widget lose focus
+ */
+ setFocused: function (focus) {
+ this._focused = focus;
+ //make sure there is only one focusedWidget
+ if (focus){
+ ccui.Widget._focusedWidget = this;
+ if(ccui.Widget._focusNavigationController)
+ ccui.Widget._focusNavigationController._setFirstFocsuedWidget(this);
+ }
+ },
+
+ /**
+ * returns whether the widget could accept focus.
+ * @returns {boolean} true represent the widget could accept focus, false represent the widget couldn't accept focus
+ */
+ isFocusEnabled: function(){
+ return this._focusEnabled;
+ },
+
+ /**
+ * sets whether the widget could accept focus.
+ * @param {Boolean} enable true represent the widget could accept focus, false represent the widget couldn't accept focus
+ */
+ setFocusEnabled: function(enable){
+ this._focusEnabled = enable;
+ },
+
+ /**
+ *
+ * When a widget is in a layout, you could call this method to get the next focused widget within a specified direction.
+ * If the widget is not in a layout, it will return itself
+ *
+ * @param direction the direction to look for the next focused widget in a layout
+ * @param current the current focused widget
+ * @return the next focused widget in a layout
+ */
+ findNextFocusedWidget: function( direction, current){
+ if (null === this.onNextFocusedWidget || null == this.onNextFocusedWidget(direction) ) {
+ var isLayout = current instanceof ccui.Layout;
+ if (this.isFocused() || isLayout) {
+ var layout = this.getParent();
+ if (null === layout || !(layout instanceof ccui.Layout)){
+ //the outer layout's default behaviour is : loop focus
+ if (isLayout)
+ return current.findNextFocusedWidget(direction, current);
+ return current;
+ } else
+ return layout.findNextFocusedWidget(direction, current);
+ } else
+ return current;
+ } else {
+ var getFocusWidget = this.onNextFocusedWidget(direction);
+ this.dispatchFocusEvent(this, getFocusWidget);
+ return getFocusWidget;
+ }
+ },
+
+ /**
+ * when a widget calls this method, it will get focus immediately.
+ */
+ requestFocus: function(){
+ if (this === ccui.Widget._focusedWidget)
+ return;
+ this.dispatchFocusEvent(ccui.Widget._focusedWidget, this);
+ },
+
+ /**
+ * no matter what widget object you call this method on , it will return you the exact one focused widget
+ */
+ getCurrentFocusedWidget: function(){
+ return ccui.Widget._focusedWidget;
+ },
+
+ /**
+ *
+ * When a widget lose/get focus, this method will be called. Be Caution when you provide your own version,
+ * you must call widget.setFocused(true/false) to change the focus state of the current focused widget;
+ *
+ */
+ onFocusChanged: null,
+
+ /**
+ * use this function to manually specify the next focused widget regards to each direction
+ */
+ onNextFocusedWidget: null,
+
+ /**
+ * This method is called when a focus change event happens
+ * @param {ccui.Widget} widgetLostFocus
+ * @param {ccui.Widget} widgetGetFocus
+ */
+ onFocusChange: function(widgetLostFocus, widgetGetFocus){
+ //only change focus when there is indeed a get&lose happens
+ if (widgetLostFocus)
+ widgetLostFocus.setFocused(false);
+ if (widgetGetFocus)
+ widgetGetFocus.setFocused(true);
+ },
+
+ /**
+ * Dispatch a EventFocus through a EventDispatcher
+ * @param {ccui.Widget} widgetLostFocus
+ * @param {ccui.Widget} widgetGetFocus
+ */
+ dispatchFocusEvent: function(widgetLostFocus, widgetGetFocus){
+ //if the widgetLoseFocus doesn't get focus, it will use the previous focused widget instead
+ if (widgetLostFocus && !widgetLostFocus.isFocused())
+ widgetLostFocus = ccui.Widget._focusedWidget;
+
+ if (widgetGetFocus !== widgetLostFocus){
+ if (widgetGetFocus && widgetGetFocus.onFocusChanged)
+ widgetGetFocus.onFocusChanged(widgetLostFocus, widgetGetFocus);
+ if (widgetLostFocus && widgetGetFocus.onFocusChanged)
+ widgetLostFocus.onFocusChanged(widgetLostFocus, widgetGetFocus);
+ cc.eventManager.dispatchEvent(new cc.Event.EventFocus(widgetLostFocus, widgetGetFocus));
+ }
+ },
+
+ /**
+ * Sets whether the widget is bright. The default value is true, a widget is default to bright
+ * @param {Boolean} bright true if the widget is bright, false if the widget is dark.
+ */
+ setBright: function (bright) {
+ this._bright = bright;
+ if (this._bright) {
+ this._brightStyle = ccui.Widget.BRIGHT_STYLE_NONE;
+ this.setBrightStyle(ccui.Widget.BRIGHT_STYLE_NORMAL);
+ } else
+ this._onPressStateChangedToDisabled();
+ },
+
+ /**
+ * To set the bright style of ccui.Widget.
+ * @param {Number} style BRIGHT_NORMAL the widget is normal state, BRIGHT_HIGHLIGHT the widget is height light state.
+ */
+ setBrightStyle: function (style) {
+ if (this._brightStyle === style)
+ return;
+
+ style = style || ccui.Widget.BRIGHT_STYLE_NORMAL;
+ this._brightStyle = style;
+ switch (this._brightStyle) {
+ case ccui.Widget.BRIGHT_STYLE_NORMAL:
+ this._onPressStateChangedToNormal();
+ break;
+ case ccui.Widget.BRIGHT_STYLE_HIGH_LIGHT:
+ this._onPressStateChangedToPressed();
+ break;
+ default:
+ break;
+ }
+ },
+
+ _onPressStateChangedToNormal: function () {},
+
+ _onPressStateChangedToPressed: function () {},
+
+ _onPressStateChangedToDisabled: function () {},
+
+ _updateChildrenDisplayedRGBA: function(){
+ this.setColor(this.getColor());
+ this.setOpacity(this.getOpacity());
+ },
+
+ /**
+ * A call back function when widget lost of focus.
+ */
+ didNotSelectSelf: function () {},
+
+ _isTargetActive: function (type) {
+ if (type === cc.Event.TOUCH)
+ return this._enabled && this._touchEnabled;
+ else if (type === cc.Event.FOCUS)
+ return this._enabled && this._focusEnabled;
+ else
+ return this._enabled;
+ },
+
+ // Store all bubbling parents that are listening to the same event in the array
+ _getBubblingTargets: function (type, array) {
+ var parent = this.getWidgetParent();
+ while (parent) {
+ if (parent.hasEventListener(type)) {
+ array.push(parent);
+ }
+ parent = parent.getWidgetParent();
+ }
+ },
+
+ /**
+ *
+ * The callback of touch began event.
+ * If the bounding box of ccui.Widget contains the touch point, it will do the following things:
+ * 1. sets highlight state,
+ * 2. sends event to parent widget by dispatchEvent
+ * 3. calls the callback of touch began event.
+ * 4. returns true,
+ * otherwise returns false directly.
+ *
+ * @override
+ * @param {cc.Touch} touch
+ * @param {cc.Event} event
+ * @returns {boolean}
+ */
+ onTouchBegan: function (touch, event) {
+ this._hit = false;
+ if (this.isVisible() && this.isEnabled() && this._isAncestorsEnabled() && this._isAncestorsVisible(this) ){
+ var touchPoint = touch.getLocation();
+ this._touchBeganPosition.x = touchPoint.x;
+ this._touchBeganPosition.y = touchPoint.y;
+ if(this.hitTest(this._touchBeganPosition) && this.isClippingParentContainsPoint(this._touchBeganPosition))
+ this._hit = true;
+ }
+ if (!this._hit) {
+ return false;
+ }
+ this.setHighlighted(true);
+ /*
+ * Propagate touch events to its parents
+ */
+ if (this._propagateTouchEvents) {
+ event._widgetEventType = ccui.Widget.TOUCH_BEGAN;
+ this.dispatchEvent(event);
+ }
+
+ this._pushDownEvent();
+ return true;
+ },
+
+ /**
+ *
+ * The callback of touch moved event.
+ * It sets the highlight state by touch, sends event to parent widget by dispatchEvent and calls the callback of touch moved event.
+ *
+ * @param {cc.Touch} touch
+ * @param {cc.Event} event
+ */
+ onTouchMoved: function (touch, event) {
+ var touchPoint = touch.getLocation();
+ this._touchMovePosition.x = touchPoint.x;
+ this._touchMovePosition.y = touchPoint.y;
+ this.setHighlighted(this.hitTest(touchPoint));
+ /*
+ * Propagate touch events to its parents
+ */
+ if (this._propagateTouchEvents) {
+ event._widgetEventType = ccui.Widget.TOUCH_MOVED;
+ this.dispatchEvent(event);
+ }
+ this._moveEvent();
+ },
+
+ /**
+ *
+ * The callback of touch end event
+ * It sends event to parent widget by dispatchEvent,
+ * calls the callback of touch end event (highlight= true) or touch canceled event (highlight= false).
+ * sets the highlight state to false ,
+ *
+ * @param touch
+ * @param event
+ */
+ onTouchEnded: function (touch, event) {
+ var touchPoint = touch.getLocation();
+ this._touchEndPosition.x = touchPoint.x;
+ this._touchEndPosition.y = touchPoint.y;
+ /*
+ * Propagate touch events to its parents
+ */
+ if (this._propagateTouchEvents) {
+ event._widgetEventType = ccui.Widget.TOUCH_ENDED;
+ this.dispatchEvent(event);
+ }
+
+ var highlight = this._highlight;
+ this.setHighlighted(false);
+ if (highlight)
+ this._releaseUpEvent();
+ else
+ this._cancelUpEvent();
+ },
+
+ /**
+ * A call back function called when widget is selected, and on touch canceled.
+ * @param {cc.Vec2} touchPoint
+ */
+ onTouchCancelled: function (touchPoint) {
+ this.setHighlighted(false);
+ this._cancelUpEvent();
+ },
+
+ /**
+ * A call back function called when widget is selected, and on touch long clicked.
+ * @param {cc.Vec2} touchPoint
+ */
+ onTouchLongClicked: function (touchPoint) {
+ this.longClickEvent();
+ },
+
+ //call back function called widget's state changed to dark.
+ _pushDownEvent: function () {
+ if (this._touchEventCallback)
+ this._touchEventCallback(this, ccui.Widget.TOUCH_BEGAN);
+ if (this._touchEventListener && this._touchEventSelector)
+ this._touchEventSelector.call(this._touchEventListener, this, ccui.Widget.TOUCH_BEGAN);
+ },
+
+ _moveEvent: function () {
+ if (this._touchEventCallback)
+ this._touchEventCallback(this, ccui.Widget.TOUCH_MOVED);
+ if (this._touchEventListener && this._touchEventSelector)
+ this._touchEventSelector.call(this._touchEventListener, this, ccui.Widget.TOUCH_MOVED);
+ },
+
+ _releaseUpEvent: function () {
+ if (this._touchEventCallback)
+ this._touchEventCallback(this, ccui.Widget.TOUCH_ENDED);
+ if (this._touchEventListener && this._touchEventSelector)
+ this._touchEventSelector.call(this._touchEventListener, this, ccui.Widget.TOUCH_ENDED);
+ if (this._clickEventListener)
+ this._clickEventListener(this);
+ },
+
+ _cancelUpEvent: function () {
+ if (this._touchEventCallback)
+ this._touchEventCallback(this, ccui.Widget.TOUCH_CANCELED);
+ if (this._touchEventListener && this._touchEventSelector)
+ this._touchEventSelector.call(this._touchEventListener, this, ccui.Widget.TOUCH_CANCELED);
+ },
+
+ longClickEvent: function () {
+ //TODO it will implement in v3.1
+ },
+
+ /**
+ * Sets the touch event target/selector of the ccui.Widget
+ * @param {Function} selector
+ * @param {Object} target
+ */
+ addTouchEventListener: function (selector, target) {
+ if(target === undefined)
+ this._touchEventCallback = selector;
+ else {
+ this._touchEventSelector = selector;
+ this._touchEventListener = target;
+ }
+ },
+
+ addClickEventListener: function(callback){
+ this._clickEventListener = callback;
+ },
+
+ /**
+ * Checks a point if is in widget's space
+ * @param {cc.Vec2} pt
+ * @returns {boolean} true if the point is in widget's space, false otherwise.
+ */
+ hitTest: function (pt) {
+ var bb = cc.rect(0,0, this._contentSize.width, this._contentSize.height);
+ return cc.rectContainsPoint(bb, this.convertToNodeSpace(pt));
+ },
+
+ /**
+ * returns whether clipping parent widget contains point.
+ * @param {cc.Vec2} pt location point
+ * @returns {Boolean}
+ */
+ isClippingParentContainsPoint: function(pt){
+ this._affectByClipping = false;
+ var parent = this.getParent();
+ var clippingParent = null;
+ while (parent) {
+ if (parent instanceof ccui.Layout) {
+ if (parent.isClippingEnabled()) {
+ this._affectByClipping = true;
+ clippingParent = parent;
+ break;
+ }
+ }
+ parent = parent.getParent();
+ }
+
+ if (!this._affectByClipping)
+ return true;
+
+ if (clippingParent) {
+ if (clippingParent.hitTest(pt))
+ return clippingParent.isClippingParentContainsPoint(pt);
+ return false;
+ }
+ return true;
+ },
+
+ /**
+ * Calls the checkChildInfo of widget's parent, its subclass will override it.
+ * @param {number} handleState
+ * @param {ccui.Widget} sender
+ * @param {cc.Vec2} touchPoint
+ */
+ checkChildInfo: function (handleState, sender, touchPoint) {
+ var widgetParent = this.getWidgetParent();
+ if (widgetParent)
+ widgetParent.checkChildInfo(handleState, sender, touchPoint);
+ },
+
+ /**
+ * Changes the position (x,y) of the widget .
+ * The original point (0,0) is at the left-bottom corner of screen.
+ * @override
+ * @param {cc.Vec2|Number} pos
+ * @param {Number} [posY]
+ */
+ setPosition: function (pos, posY) {
+ if (!this._usingLayoutComponent && this._running) {
+ var widgetParent = this.getWidgetParent();
+ if (widgetParent) {
+ var pSize = widgetParent.getContentSize();
+ if (pSize.width <= 0 || pSize.height <= 0) {
+ this._positionPercent.x = 0;
+ this._positionPercent.y = 0;
+ } else {
+ if (posY === undefined) {
+ this._positionPercent.x = pos.x / pSize.width;
+ this._positionPercent.y = pos.y / pSize.height;
+ } else {
+ this._positionPercent.x = pos / pSize.width;
+ this._positionPercent.y = posY / pSize.height;
+ }
+ }
+ }
+ }
+
+ cc.Node.prototype.setPosition.call(this, pos, posY);
+ //this._positionType = ccui.Widget.POSITION_ABSOLUTE;
+ },
+
+ setPositionX: function (x) {
+ if (this._running) {
+ var widgetParent = this.getWidgetParent();
+ if (widgetParent) {
+ var pw = widgetParent.width;
+ if (pw <= 0)
+ this._positionPercent.x = 0;
+ else
+ this._positionPercent.x = x / pw;
+ }
+ }
+
+ cc.Node.prototype.setPositionX.call(this, x);
+ },
+ setPositionY: function (y) {
+ if (this._running) {
+ var widgetParent = this.getWidgetParent();
+ if (widgetParent) {
+ var ph = widgetParent.height;
+ if (ph <= 0)
+ this._positionPercent.y = 0;
+ else
+ this._positionPercent.y = y / ph;
+ }
+ }
+
+ cc.Node.prototype.setPositionY.call(this, y);
+ },
+
+ /**
+ * Changes the position (x,y) of the widget
+ * @param {cc.Vec2} percent
+ */
+ setPositionPercent: function (percent) {
+ if (this._usingLayoutComponent){
+ var component = this._getOrCreateLayoutComponent();
+ component.setPositionPercentX(percent.x);
+ component.setPositionPercentY(percent.y);
+ component.refreshLayout();
+ return;
+ }else{
+ this._setXPercent(percent.x);
+ this._setYPercent(percent.y);
+ }
+ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
+ },
+ _setXPercent: function (percent) {
+ if (this._usingLayoutComponent){
+ var component = this._getOrCreateLayoutComponent();
+ component.setPositionPercentX(percent.x);
+ component.refreshLayout();
+ return;
+ }
+ this._positionPercent.x = percent;
+ },
+ _setYPercent: function (percent) {
+ if (this._usingLayoutComponent){
+ var component = this._getOrCreateLayoutComponent();
+ component.setPositionPercentY(percent.x);
+ component.refreshLayout();
+ return;
+ }
+ this._positionPercent.y = percent;
+ },
+
+ /**
+ * Gets the percent (x,y) of the widget
+ * @returns {cc.Vec2} The percent (x,y) of the widget in OpenGL coordinates
+ */
+ getPositionPercent: function () {
+ if (this._usingLayoutComponent) {
+ var component = this._getOrCreateLayoutComponent();
+ this._positionPercent.x = component.getPositionPercentX();
+ this._positionPercent.y = component.getPositionPercentY();
+ }
+ return cc.p(this._positionPercent);
+ },
+
+ _getXPercent: function () {
+ if (this._usingLayoutComponent) {
+ var component = this._getOrCreateLayoutComponent();
+ this._positionPercent.x = component.getPositionPercentX();
+ this._positionPercent.y = component.getPositionPercentY();
+ }
+ return this._positionPercent.x;
+ },
+ _getYPercent: function () {
+ if (this._usingLayoutComponent) {
+ var component = this._getOrCreateLayoutComponent();
+ this._positionPercent.x = component.getPositionPercentX();
+ this._positionPercent.y = component.getPositionPercentY();
+ }
+ return this._positionPercent.y;
+ },
+
+ /**
+ * Changes the position type of the widget
+ * @param {Number} type the position type of widget
+ */
+ setPositionType: function (type) {
+ this._positionType = type;
+ if(this._usingLayoutComponent){
+ var component = this._getOrCreateLayoutComponent();
+ if (type === ccui.POSITION_ABSOLUTE){
+ component.setPositionPercentXEnabled(false);
+ component.setPositionPercentYEnabled(false);
+ } else {
+ component.setPositionPercentXEnabled(true);
+ component.setPositionPercentYEnabled(true);
+ }
+ }
+ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
+ },
+
+ /**
+ * Gets the position type of the widget
+ * @returns {Number} the position type of widget
+ */
+ getPositionType: function () {
+ return this._positionType;
+ },
+
+ /**
+ * Sets whether the widget should be flipped horizontally or not.
+ * @param {Boolean} flipX true if the widget should be flipped horizontally, false otherwise.
+ */
+ setFlippedX: function (flipX) {
+ var realScale = this.getScaleX();
+ this._flippedX = flipX;
+ this.setScaleX(realScale);
+ },
+
+ /**
+ *
+ * Returns the flag which indicates whether the widget is flipped horizontally or not.
+ * It only flips the texture of the widget, and not the texture of the widget's children.
+ * Also, flipping the texture doesn't alter the anchorPoint.
+ * If you want to flip the anchorPoint too, and/or to flip the children too use:
+ * widget.setScaleX(sprite.getScaleX() * -1);
+ *
+ * @returns {Boolean} true if the widget is flipped horizontally, false otherwise.
+ */
+ isFlippedX: function () {
+ return this._flippedX;
+ },
+
+ /**
+ * Sets whether the widget should be flipped vertically or not.
+ * @param {Boolean} flipY true if the widget should be flipped vertically, false otherwise.
+ */
+ setFlippedY: function (flipY) {
+ var realScale = this.getScaleY();
+ this._flippedY = flipY;
+ this.setScaleY(realScale);
+ },
+
+ /**
+ *
+ * Return the flag which indicates whether the widget is flipped vertically or not.
+ * It only flips the texture of the widget, and not the texture of the widget's children.
+ * Also, flipping the texture doesn't alter the anchorPoint.
+ * If you want to flip the anchorPoint too, and/or to flip the children too use:
+ * widget.setScaleY(widget.getScaleY() * -1);
+ *
+ * @returns {Boolean} true if the widget is flipped vertically, false otherwise.
+ */
+ isFlippedY: function () {
+ return this._flippedY;
+ },
+
+ _adaptRenderers: function(){},
+
+ /**
+ * Determines if the widget is bright
+ * @returns {boolean} true if the widget is bright, false if the widget is dark.
+ */
+ isBright: function () {
+ return this._bright;
+ },
+
+ /**
+ * Determines if the widget is enabled
+ * @returns {boolean}
+ */
+ isEnabled: function () {
+ return this._enabled;
+ },
+
+ /**
+ * Gets the left boundary position of this widget.
+ * @returns {number}
+ */
+ getLeftBoundary: function () {
+ return this.getPositionX() - this._getAnchorX() * this._contentSize.width;
+ },
+
+ /**
+ * Gets the bottom boundary position of this widget.
+ * @returns {number}
+ */
+ getBottomBoundary: function () {
+ return this.getPositionY() - this._getAnchorY() * this._contentSize.height;
+ },
+
+ /**
+ * Gets the right boundary position of this widget.
+ * @returns {number}
+ */
+ getRightBoundary: function () {
+ return this.getLeftBoundary() + this._contentSize.width;
+ },
+
+ /**
+ * Gets the top boundary position of this widget.
+ * @returns {number}
+ */
+ getTopBoundary: function () {
+ return this.getBottomBoundary() + this._contentSize.height;
+ },
+
+ /**
+ * Gets the position of touch began event.
+ * @returns {cc.Vec2}
+ */
+ getTouchBeganPosition: function(){
+ return cc.p(this._touchBeganPosition);
+ },
+
+ /**
+ * Gets the position of touch moved event
+ * @returns {cc.Vec2}
+ */
+ getTouchMovePosition: function(){
+ return cc.p(this._touchMovePosition);
+ },
+
+ /**
+ * Gets the position of touch end event
+ * @returns {cc.Vec2}
+ */
+ getTouchEndPosition:function(){
+ return cc.p(this._touchEndPosition);
+ },
+
+ /**
+ * get widget type
+ * @returns {ccui.Widget.TYPE_WIDGET|ccui.Widget.TYPE_CONTAINER}
+ */
+ getWidgetType: function () {
+ return this._widgetType;
+ },
+
+ /**
+ * Gets LayoutParameter of widget.
+ * @param {ccui.LayoutParameter} parameter
+ */
+ setLayoutParameter: function (parameter) {
+ if(!parameter)
+ return;
+ this._layoutParameterDictionary[parameter.getLayoutType()] = parameter;
+ this._layoutParameterType = parameter.getLayoutType();
+ },
+
+ /**
+ * Gets layout parameter
+ * @param {ccui.LayoutParameter.NONE|ccui.LayoutParameter.LINEAR|ccui.LayoutParameter.RELATIVE} type
+ * @returns {ccui.LayoutParameter}
+ */
+ getLayoutParameter: function (type) {
+ type = type || this._layoutParameterType;
+ return this._layoutParameterDictionary[type];
+ },
+
+ /**
+ * Returns the "class name" of widget.
+ * @returns {string}
+ */
+ getDescription: function () {
+ return "Widget";
+ },
+
+ /**
+ * Clones a new widget.
+ * @returns {ccui.Widget}
+ */
+ clone: function () {
+ var clonedWidget = this._createCloneInstance();
+ clonedWidget._copyProperties(this);
+ clonedWidget._copyClonedWidgetChildren(this);
+ return clonedWidget;
+ },
+
+ _createCloneInstance: function () {
+ return new ccui.Widget();
+ },
+
+ _copyClonedWidgetChildren: function (model) {
+ var widgetChildren = model.getChildren();
+ for (var i = 0; i < widgetChildren.length; i++) {
+ var locChild = widgetChildren[i];
+ if (locChild instanceof ccui.Widget)
+ this.addChild(locChild.clone());
+ }
+ },
+
+ _copySpecialProperties: function (model) {},
+
+ _copyProperties: function (widget) {
+ this.setEnabled(widget.isEnabled());
+ this.setVisible(widget.isVisible());
+ this.setBright(widget.isBright());
+ this.setTouchEnabled(widget.isTouchEnabled());
+ this.setLocalZOrder(widget.getLocalZOrder());
+ this.setTag(widget.getTag());
+ this.setName(widget.getName());
+ this.setActionTag(widget.getActionTag());
+
+ this._ignoreSize = widget._ignoreSize;
+
+ this.setContentSize(widget._contentSize);
+ this._customSize.width = widget._customSize.width;
+ this._customSize.height = widget._customSize.height;
+
+ this._copySpecialProperties(widget);
+ this._sizeType = widget.getSizeType();
+ this._sizePercent.x = widget._sizePercent.x;
+ this._sizePercent.y = widget._sizePercent.y;
+
+ this._positionType = widget._positionType;
+ this._positionPercent.x = widget._positionPercent.x;
+ this._positionPercent.y = widget._positionPercent.y;
+
+ this.setPosition(widget.getPosition());
+ this.setAnchorPoint(widget.getAnchorPoint());
+ this.setScaleX(widget.getScaleX());
+ this.setScaleY(widget.getScaleY());
+ this.setRotation(widget.getRotation());
+ this.setRotationX(widget.getRotationX());
+ this.setRotationY(widget.getRotationY());
+ this.setFlippedX(widget.isFlippedX());
+ this.setFlippedY(widget.isFlippedY());
+ this.setColor(widget.getColor());
+ this.setOpacity(widget.getOpacity());
+
+ this._touchEventCallback = widget._touchEventCallback;
+ this._touchEventListener = widget._touchEventListener;
+ this._touchEventSelector = widget._touchEventSelector;
+ this._clickEventListener = widget._clickEventListener;
+ this._focused = widget._focused;
+ this._focusEnabled = widget._focusEnabled;
+ this._propagateTouchEvents = widget._propagateTouchEvents;
+
+ for (var key in widget._layoutParameterDictionary) {
+ var parameter = widget._layoutParameterDictionary[key];
+ if (parameter)
+ this.setLayoutParameter(parameter.clone());
+ }
+ this._onSizeChanged();
+ },
+
+ /*temp action*/
+ setActionTag: function (tag) {
+ this._actionTag = tag;
+ },
+
+ getActionTag: function () {
+ return this._actionTag;
+ },
+
+ /**
+ * Gets the left boundary position of this widget.
+ * @deprecated since v3.0, please use getLeftBoundary instead.
+ * @returns {number}
+ */
+ getLeftInParent: function(){
+ cc.log("getLeftInParent is deprecated. Please use getLeftBoundary instead.");
+ return this.getLeftBoundary();
+ },
+
+ /**
+ * Gets the bottom boundary position of this widget.
+ * @deprecated since v3.0, please use getBottomBoundary instead.
+ * @returns {number}
+ */
+ getBottomInParent: function(){
+ cc.log("getBottomInParent is deprecated. Please use getBottomBoundary instead.");
+ return this.getBottomBoundary();
+ },
+
+ /**
+ * Gets the right boundary position of this widget.
+ * @deprecated since v3.0, please use getRightBoundary instead.
+ * @returns {number}
+ */
+ getRightInParent: function(){
+ cc.log("getRightInParent is deprecated. Please use getRightBoundary instead.");
+ return this.getRightBoundary();
+ },
+
+ /**
+ * Gets the top boundary position of this widget.
+ * @deprecated since v3.0, please use getTopBoundary instead.
+ * @returns {number}
+ */
+ getTopInParent: function(){
+ cc.log("getTopInParent is deprecated. Please use getTopBoundary instead.");
+ return this.getTopBoundary();
+ },
+
+ /**
+ * Gets the touch end point of widget when widget is selected.
+ * @deprecated since v3.0, please use getTouchEndPosition instead.
+ * @returns {cc.Vec2} the touch end point.
+ */
+ getTouchEndPos: function () {
+ cc.log("getTouchEndPos is deprecated. Please use getTouchEndPosition instead.");
+ return this.getTouchEndPosition();
+ },
+
+ /**
+ *Gets the touch move point of widget when widget is selected.
+ * @deprecated since v3.0, please use getTouchMovePosition instead.
+ * @returns {cc.Vec2} the touch move point.
+ */
+ getTouchMovePos: function () {
+ cc.log("getTouchMovePos is deprecated. Please use getTouchMovePosition instead.");
+ return this.getTouchMovePosition();
+ },
+
+ /**
+ * Checks a point if in parent's area.
+ * @deprecated since v3.0, please use isClippingParentContainsPoint instead.
+ * @param {cc.Vec2} pt
+ * @returns {Boolean}
+ */
+ clippingParentAreaContainPoint: function (pt) {
+ cc.log("clippingParentAreaContainPoint is deprecated. Please use isClippingParentContainsPoint instead.");
+ this.isClippingParentContainsPoint(pt);
+ },
+
+ /**
+ * Gets the touch began point of widget when widget is selected.
+ * @deprecated since v3.0, please use getTouchBeganPosition instead.
+ * @returns {cc.Vec2} the touch began point.
+ */
+ getTouchStartPos: function () {
+ cc.log("getTouchStartPos is deprecated. Please use getTouchBeganPosition instead.");
+ return this.getTouchBeganPosition();
+ },
+
+ /**
+ * Changes the size that is widget's size
+ * @deprecated since v3.0, please use setContentSize instead.
+ * @param {cc.Size} size that is widget's size
+ */
+ setSize: function (size) {
+ this.setContentSize(size);
+ },
+
+ /**
+ * Returns size of widget
+ * @deprecated since v3.0, please use getContentSize instead.
+ * @returns {cc.Size}
+ */
+ getSize: function () {
+ return this.getContentSize();
+ },
+
+ /**
+ * Adds a node for widget (this function is deleted in -x)
+ * @param {cc.Node} node
+ * @param {Number} zOrder
+ * @param {Number} tag
+ * @deprecated since v3.0, please use addChild instead.
+ */
+ addNode: function (node, zOrder, tag) {
+ if (node instanceof ccui.Widget) {
+ cc.log("Please use addChild to add a Widget.");
+ return;
+ }
+ cc.Node.prototype.addChild.call(this, node, zOrder, tag);
+ this._nodes.push(node);
+ },
+
+ /**
+ * Gets node by tag
+ * @deprecated since v3.0, please use getChildByTag instead.
+ * @param {Number} tag
+ * @returns {cc.Node}
+ */
+ getNodeByTag: function (tag) {
+ var _nodes = this._nodes;
+ for (var i = 0; i < _nodes.length; i++) {
+ var node = _nodes[i];
+ if (node && node.getTag() === tag) {
+ return node;
+ }
+ }
+ return null;
+ },
+
+ /**
+ * Returns all children.
+ * @deprecated since v3.0, please use getChildren instead.
+ * @returns {Array}
+ */
+ getNodes: function () {
+ return this._nodes;
+ },
+
+ /**
+ * Removes a node from ccui.Widget
+ * @deprecated since v3.0, please use removeChild instead.
+ * @param {cc.Node} node
+ * @param {Boolean} cleanup
+ */
+ removeNode: function (node, cleanup) {
+ cc.Node.prototype.removeChild.call(this, node, cleanup);
+ cc.js.array.remove(this._nodes, node);
+ },
+
+ /**
+ * Removes node by tag
+ * @deprecated since v3.0, please use removeChildByTag instead.
+ * @param {Number} tag
+ * @param {Boolean} [cleanup]
+ */
+ removeNodeByTag: function (tag, cleanup) {
+ var node = this.getChildByTag(tag);
+ if (!node)
+ cc.log("cocos2d: removeNodeByTag(tag = %d): child not found!", tag);
+ else
+ this.removeChild(node, cleanup);
+ },
+
+ /**
+ * Removes all node
+ * @deprecated since v3.0, please use removeAllChildren instead.
+ */
+ removeAllNodes: function () {
+ for (var i = 0; i < this._nodes.length; i++) {
+ var node = this._nodes[i];
+ cc.Node.prototype.removeChild.call(this, node);
+ }
+ this._nodes.length = 0;
+ },
+
+ _findLayout: function(){
+ cc.renderer.childrenOrderDirty = true;
+ var layout = this._parent;
+ while(layout){
+ if(layout._doLayout){
+ layout._doLayoutDirty = true;
+ break;
+ }else
+ layout = layout._parent;
+ }
+ },
+
+ /**
+ * @since v3.2
+ * @returns {boolean} true represent the widget use Unify Size, false represent the widget couldn't use Unify Size
+ */
+ isUnifySizeEnabled: function(){
+ return this._unifySize;
+ },
+
+ /**
+ * @since v3.2
+ * @param {Boolean} enable enable Unify Size of a widget
+ */
+ setUnifySizeEnabled: function(enable){
+ this._unifySize = enable;
+ },
+
+ //v3.3
+ _ccEventCallback: null,
+ /**
+ * Set a event handler to the widget in order to use cocostudio editor and framework
+ * @since v3.3
+ * @param {function} callback
+ */
+ addCCSEventListener: function(callback){
+ this._ccEventCallback = callback;
+ },
+
+ //override the scale functions.
+ setScaleX: function(scaleX){
+ if (this._flippedX)
+ scaleX = scaleX * -1;
+ cc.Node.prototype.setScaleX.call(this, scaleX);
+ },
+ setScaleY: function(scaleY){
+ if (this._flippedY)
+ scaleY = scaleY * -1;
+ cc.Node.prototype.setScaleY.call(this, scaleY);
+ },
+ setScale: function(scaleX, scaleY){
+ if(scaleY === undefined)
+ scaleY = scaleX;
+ this.setScaleX(scaleX);
+ this.setScaleY(scaleY);
+ },
+
+ getScaleX: function(){
+ var originalScale = cc.Node.prototype.getScaleX.call(this);
+ if (this._flippedX)
+ originalScale = originalScale * -1.0;
+ return originalScale;
+ },
+ getScaleY: function(){
+ var originalScale = cc.Node.prototype.getScaleY.call(this);
+ if (this._flippedY)
+ originalScale = originalScale * -1.0;
+ return originalScale;
+ },
+ getScale: function(){
+ if(this.getScaleX() !== this.getScaleY())
+ cc.log("Widget#scale. ScaleX != ScaleY. Don't know which one to return");
+ return this.getScaleX();
+ },
+
+ /**
+ * Sets callback name to widget.
+ * @since v3.3
+ * @param {String} callbackName
+ */
+ setCallbackName: function(callbackName){
+ this._callbackName = callbackName;
+ },
+
+ /**
+ * Gets callback name of widget
+ * @since v3.3
+ * @returns {String|Null}
+ */
+ getCallbackName: function(){
+ return this._callbackName;
+ },
+
+ /**
+ * Sets callback type to widget
+ * @since v3.3
+ * @param {String} callbackType
+ */
+ setCallbackType: function(callbackType){
+ this._callbackType = callbackType;
+ },
+
+ /**
+ * Gets callback type of widget
+ * @since v3.3
+ * @returns {String|null}
+ */
+ getCallbackType: function(){
+ return this._callbackType;
+ },
+
+ /**
+ * Whether enable layout component of a widget
+ * @since v3.3
+ * @param {Boolean} enable enable layout Component of a widget
+ */
+ setLayoutComponentEnabled: function(enable){
+ this._usingLayoutComponent = enable;
+ },
+
+ /**
+ * Returns whether enable layout component of a widget
+ * @return {Boolean} true represent the widget use Layout Component, false represent the widget couldn't use Layout Component.
+ */
+ isLayoutComponentEnabled: function(){
+ return this._usingLayoutComponent;
+ },
+
+
+ _createRenderCmd: function(){
+ if(cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ return new ccui.Widget.WebGLRenderCmd(this);
+ else
+ return new ccui.Widget.CanvasRenderCmd(this);
+ }
+});
+
+var _p = ccui.Widget.prototype;
+
+// Extended properties
+/** @expose */
+_p.xPercent;
+cc.defineGetterSetter(_p, "xPercent", _p._getXPercent, _p._setXPercent);
+/** @expose */
+_p.yPercent;
+cc.defineGetterSetter(_p, "yPercent", _p._getYPercent, _p._setYPercent);
+/** @expose */
+_p.widthPercent;
+cc.defineGetterSetter(_p, "widthPercent", _p._getWidthPercent, _p._setWidthPercent);
+/** @expose */
+_p.heightPercent;
+cc.defineGetterSetter(_p, "heightPercent", _p._getHeightPercent, _p._setHeightPercent);
+/** @expose */
+_p.widgetParent;
+cc.defineGetterSetter(_p, "widgetParent", _p.getWidgetParent);
+/** @expose */
+_p.enabled;
+cc.defineGetterSetter(_p, "enabled", _p.isEnabled, _p.setEnabled);
+/** @expose */
+_p.focused;
+cc.defineGetterSetter(_p, "focused", _p.isFocused, _p.setFocused);
+/** @expose */
+_p.sizeType;
+cc.defineGetterSetter(_p, "sizeType", _p.getSizeType, _p.setSizeType);
+/** @expose */
+_p.widgetType;
+cc.defineGetterSetter(_p, "widgetType", _p.getWidgetType);
+/** @expose */
+_p.touchEnabled;
+cc.defineGetterSetter(_p, "touchEnabled", _p.isTouchEnabled, _p.setTouchEnabled);
+/** @expose */
+_p.updateEnabled;
+cc.defineGetterSetter(_p, "updateEnabled", _p.isUpdateEnabled, _p.setUpdateEnabled);
+/** @expose */
+_p.bright;
+cc.defineGetterSetter(_p, "bright", _p.isBright, _p.setBright);
+/** @expose */
+_p.name;
+cc.defineGetterSetter(_p, "name", _p.getName, _p.setName);
+/** @expose */
+_p.actionTag;
+cc.defineGetterSetter(_p, "actionTag", _p.getActionTag, _p.setActionTag);
+/** @expose */
+_p.opacity;
+cc.defineGetterSetter(_p, "opacity", _p.getOpacity, _p.setOpacity);
+
+_p = null;
+
+/**
+ * allocates and initializes a UIWidget.
+ * @deprecated
+ * @return {ccui.Widget}
+ */
+ccui.Widget.create = function () {
+ return new ccui.Widget();
+};
+
+EventTarget.polyfill(ccui.Widget.prototype);
+
+ccui.Widget._focusedWidget = null; //both layout & widget will be stored in this variable
+ccui.Widget._focusNavigationController = null;
+
+/**
+ * call this method with parameter true to enable the Android Dpad focus navigation feature
+ * @note it doesn't implemented on Web
+ * @param {Boolean} enable set true to enable dpad focus navigation, otherwise disable dpad focus navigation
+ */
+ccui.Widget.enableDpadNavigation = function(enable){
+ if (enable){
+ if (null == ccui.Widget._focusNavigationController) {
+ ccui.Widget._focusNavigationController = new ccui._FocusNavigationController();
+ if (ccui.Widget._focusedWidget) {
+ ccui.Widget._focusNavigationController._setFirstFocsuedWidget(ccui.Widget._focusedWidget);
+ }
+ }
+ ccui.Widget._focusNavigationController.enableFocusNavigation(true);
+ } else {
+ if(ccui.Widget._focusNavigationController){
+ ccui.Widget._focusNavigationController.enableFocusNavigation(false);
+ ccui.Widget._focusNavigationController = null;
+ }
+ }
+};
+
+/**
+ * Gets the focused widget of current stage.
+ * @function
+ * @returns {null|ccui.Widget}
+ */
+ccui.Widget.getCurrentFocusedWidget = function(){
+ return ccui.Widget._focusedWidget;
+};
+
+// Constants
+//bright style
+/**
+ * None bright style of ccui.Widget.
+ * @constant
+ * @type {number}
+ */
+ccui.Widget.BRIGHT_STYLE_NONE = -1;
+/**
+ * Normal bright style of ccui.Widget.
+ * @constant
+ * @type {number}
+ */
+ccui.Widget.BRIGHT_STYLE_NORMAL = 0;
+/**
+ * Light bright style of ccui.Widget.
+ * @constant
+ * @type {number}
+ */
+ccui.Widget.BRIGHT_STYLE_HIGH_LIGHT = 1;
+
+//widget type
+/**
+ * The type code of Widget for ccui controls.
+ * @constant
+ * @type {number}
+ */
+ccui.Widget.TYPE_WIDGET = 0;
+/**
+ * The type code of Container for ccui controls.
+ * @constant
+ * @type {number}
+ */
+ccui.Widget.TYPE_CONTAINER = 1;
+
+//Focus Direction
+/**
+ * The left of Focus direction for ccui.Widget
+ * @constant
+ * @type {number}
+ */
+ccui.Widget.LEFT = 0;
+/**
+ * The right of Focus direction for ccui.Widget
+ * @constant
+ * @type {number}
+ */
+ccui.Widget.RIGHT = 1;
+/**
+ * The up of Focus direction for ccui.Widget
+ * @constant
+ * @type {number}
+ */
+ccui.Widget.UP = 2;
+/**
+ * The down of Focus direction for ccui.Widget
+ * @constant
+ * @type {number}
+ */
+ccui.Widget.DOWN = 3;
+
+//texture resource type
+/**
+ * The image file texture type of ccui.Widget loads.
+ * @constant
+ * @type {number}
+ */
+ccui.Widget.LOCAL_TEXTURE = 0;
+/**
+ * The sprite frame texture type of ccui.Widget loads.
+ * @constant
+ * @type {number}
+ */
+ccui.Widget.PLIST_TEXTURE = 1;
+
+//touch event type
+/**
+ * The touch began type of ccui.Widget's touch event
+ * @constant
+ * @type {string}
+ */
+ccui.Widget.TOUCH_BEGAN = 'widget_touch_began';
+/**
+ * The touch moved type of ccui.Widget's touch event
+ * @constant
+ * @type {string}
+ */
+ccui.Widget.TOUCH_MOVED = 'widget_touch_moved';
+/**
+ * The touch end type of ccui.Widget's touch event
+ * @constant
+ * @type {string}
+ */
+ccui.Widget.TOUCH_ENDED = 'widget_touch_ended';
+/**
+ * The touch canceled type of ccui.Widget's touch event
+ * @constant
+ * @type {string}
+ */
+ccui.Widget.TOUCH_CANCELED = 'widget_touch_canceled';
+
+//size type
+/**
+ * The absolute of ccui.Widget's size type.
+ * @constant
+ * @type {number}
+ */
+ccui.Widget.SIZE_ABSOLUTE = 0;
+/**
+ * The percent of ccui.Widget's size type.
+ * @constant
+ * @type {number}
+ */
+ccui.Widget.SIZE_PERCENT = 1;
+
+//position type
+/**
+ * The absolute of ccui.Widget's position type.
+ * @constant
+ * @type {number}
+ */
+ccui.Widget.POSITION_ABSOLUTE = 0;
+/**
+ * The percent of ccui.Widget's position type.
+ * @constant
+ * @type {number}
+ */
+ccui.Widget.POSITION_PERCENT = 1;
diff --git a/extensions/ccui/base-classes/UIWidgetRenderCmd.js b/extensions/ccui/base-classes/UIWidgetRenderCmd.js
new file mode 100644
index 0000000000..f01b12d5c9
--- /dev/null
+++ b/extensions/ccui/base-classes/UIWidgetRenderCmd.js
@@ -0,0 +1,97 @@
+/****************************************************************************
+ 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.once(cc.game.EVENT_RENDERER_INITED, function () {
+ if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
+ ccui.Widget.CanvasRenderCmd = function (renderable) {
+ cc.ProtectedNode.CanvasRenderCmd.call(this, renderable);
+ this._needDraw = false;
+ };
+
+ var proto = ccui.Widget.CanvasRenderCmd.prototype = Object.create(cc.ProtectedNode.CanvasRenderCmd.prototype);
+ proto.constructor = ccui.Widget.CanvasRenderCmd;
+
+ proto.visit = function (parentCmd) {
+ var node = this._node;
+ if (node._visible) {
+ node._adaptRenderers();
+ cc.ProtectedNode.CanvasRenderCmd.prototype.visit.call(this, parentCmd);
+ }
+ };
+
+ proto.transform = function (parentCmd, recursive) {
+ var node = this._node;
+
+ if (node._visible) {
+ node._adaptRenderers();
+ if(!this._usingLayoutComponent){
+ var widgetParent = node.getWidgetParent();
+ if (widgetParent) {
+ var parentSize = widgetParent.getContentSize();
+ if (parentSize.width !== 0 && parentSize.height !== 0) {
+ node._position.x = parentSize.width * node._positionPercent.x;
+ node._position.y = parentSize.height * node._positionPercent.y;
+ }
+ }
+ }
+ cc.ProtectedNode.CanvasRenderCmd.prototype.transform.call(this, parentCmd, recursive);
+ }
+ };
+ } else {
+ ccui.Widget.WebGLRenderCmd = function (renderable) {
+ cc.ProtectedNode.WebGLRenderCmd.call(this, renderable);
+ this._needDraw = false;
+ };
+
+ var proto = ccui.Widget.WebGLRenderCmd.prototype = Object.create(cc.ProtectedNode.WebGLRenderCmd.prototype);
+ proto.constructor = ccui.Widget.WebGLRenderCmd;
+
+ proto.visit = function (parentCmd) {
+ var node = this._node;
+ if (node._visible) {
+ node._adaptRenderers();
+ cc.ProtectedNode.WebGLRenderCmd.prototype.visit.call(this, parentCmd);
+ }
+ };
+
+ proto.transform = function(parentCmd, recursive){
+ var node = this._node;
+ if (node._visible) {
+ node._adaptRenderers();
+
+ if(!this._usingLayoutComponent) {
+ var widgetParent = node.getWidgetParent();
+ if (widgetParent) {
+ var parentSize = widgetParent.getContentSize();
+ if (parentSize.width !== 0 && parentSize.height !== 0) {
+ node._position.x = parentSize.width * node._positionPercent.x;
+ node._position.y = parentSize.height * node._positionPercent.y;
+ }
+ }
+ }
+ cc.ProtectedNode.WebGLRenderCmd.prototype.transform.call(this, parentCmd, recursive);
+ }
+ };
+ }
+});
diff --git a/extensions/ccui/layouts/UIHBox.js b/extensions/ccui/layouts/UIHBox.js
new file mode 100644
index 0000000000..69657952ed
--- /dev/null
+++ b/extensions/ccui/layouts/UIHBox.js
@@ -0,0 +1,80 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+/**
+ * The horizontal box of Cocos UI. Its layout type is ccui.Layout.Type.LINEAR_HORIZONTAL.
+ * @class
+ * @extends ccui.Layout
+ */
+ccui.HBox = ccui.Layout.extend(/** @lends ccui.HBox# */{
+ /**
+ * The constructor of ccui.HBox
+ * @function
+ * @param {cc.Size} [size]
+ */
+ ctor: function(size){
+ ccui.Layout.prototype.ctor.call(this, size);
+ if(size !== undefined)
+ this.initWithSize(size);
+ else
+ this.init();
+ },
+
+ /**
+ * Initialize a HBox. please do not call this function by yourself, you should pass the parameters to constructor to initialize it.
+ * @override
+ * @returns {boolean}
+ */
+ init: function(){
+ if(ccui.Layout.prototype.init.call(this)){
+ this.setLayoutType(ccui.Layout.Type.LINEAR_HORIZONTAL);
+ return true;
+ }
+ return false;
+ },
+
+ /**
+ * Initializes a HBox with size.
+ * @param size
+ * @returns {boolean}
+ */
+ initWithSize: function(size){
+ if(this.init()){
+ this.setContentSize(size);
+ return true;
+ }
+ return false;
+ }
+});
+
+/**
+ * Creates a HBox object
+ * @deprecated since v3.0, please use new ccui.HBox(size) instead.
+ * @param {cc.Size} size
+ * @returns {ccui.HBox}
+ */
+ccui.HBox.create = function(size){
+ return new ccui.HBox(size);
+};
\ No newline at end of file
diff --git a/extensions/ccui/layouts/UILayout.js b/extensions/ccui/layouts/UILayout.js
new file mode 100644
index 0000000000..77eb4f9fb7
--- /dev/null
+++ b/extensions/ccui/layouts/UILayout.js
@@ -0,0 +1,1555 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+/**
+ * ccui.Layout is the base class of ccui.PageView and ccui.ScrollView, it does layout by layout manager
+ * and clips area by its _clippingStencil when clippingEnabled is true.
+ * @class
+ * @extends ccui.Widget
+ *
+ * @property {Boolean} clippingEnabled - Indicate whether clipping is enabled
+ * @property {ccui.Layout.CLIPPING_STENCIL|ccui.Layout.CLIPPING_SCISSOR} clippingType
+ * @property {ccui.Layout.Type} layoutType
+ */
+ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
+ _clippingEnabled: false,
+ _backGroundScale9Enabled: null,
+ _backGroundImage: null,
+ _backGroundImageFileName: null,
+ _backGroundImageCapInsets: null,
+ _colorType: null,
+ _bgImageTexType: ccui.Widget.LOCAL_TEXTURE,
+ _colorRender: null,
+ _gradientRender: null,
+ _color: null,
+ _startColor: null,
+ _endColor: null,
+ _alongVector: null,
+ _opacity: 255,
+ _backGroundImageTextureSize: null,
+ _layoutType: null,
+ _doLayoutDirty: true,
+ _clippingRectDirty: true,
+ _clippingType: null,
+ _clippingStencil: null,
+ _scissorRectDirty: false,
+ _clippingRect: null,
+ _clippingParent: null,
+ _className: "Layout",
+ _backGroundImageColor: null,
+ _finalPositionX: 0,
+ _finalPositionY: 0,
+
+ _backGroundImageOpacity:0,
+
+ _loopFocus: false, //whether enable loop focus or not
+ __passFocusToChild: true, //on default, it will pass the focus to the next nearest widget
+ _isFocusPassing:false, //when finding the next focused widget, use this variable to pass focus between layout & widget
+ _isInterceptTouch: false,
+
+ /**
+ * Allocates and initializes an UILayout.
+ * Constructor of ccui.Layout
+ * @function
+ * @example
+ * // example
+ * var uiLayout = new ccui.Layout();
+ */
+ ctor: function () {
+ this._layoutType = ccui.Layout.Type.ABSOLUTE;
+ this._widgetType = ccui.Widget.TYPE_CONTAINER;
+ this._clippingType = ccui.Layout.CLIPPING_STENCIL;
+ this._colorType = ccui.Layout.BG_COLOR_NONE;
+
+ ccui.Widget.prototype.ctor.call(this);
+ this._backGroundImageCapInsets = cc.rect(0, 0, 0, 0);
+
+ this._color = cc.color(255, 255, 255, 255);
+ this._startColor = cc.color(255, 255, 255, 255);
+ this._endColor = cc.color(255, 255, 255, 255);
+ this._alongVector = cc.p(0, -1);
+ this._backGroundImageTextureSize = cc.size(0, 0);
+
+ this._clippingRect = cc.rect(0, 0, 0, 0);
+ this._backGroundImageColor = cc.color(255, 255, 255, 255);
+ },
+
+ /**
+ * Calls its parent's onEnter, and calls its clippingStencil's onEnter if clippingStencil isn't null.
+ * @override
+ */
+ onEnter: function(){
+ ccui.Widget.prototype.onEnter.call(this);
+ if (this._clippingStencil)
+ this._clippingStencil.onEnter();
+ this._doLayoutDirty = true;
+ this._clippingRectDirty = true;
+ },
+
+ /**
+ * Calls its parent's onExit, and calls its clippingStencil's onExit if clippingStencil isn't null.
+ * @override
+ */
+ onExit: function(){
+ ccui.Widget.prototype.onExit.call(this);
+ if (this._clippingStencil)
+ this._clippingStencil.onExit();
+ },
+
+ /**
+ * If a layout is loop focused which means that the focus movement will be inside the layout
+ * @param {Boolean} loop pass true to let the focus movement loop inside the layout
+ */
+ setLoopFocus: function(loop){
+ this._loopFocus = loop;
+ },
+
+ /**
+ * Gets whether enable focus loop
+ * @returns {boolean} If focus loop is enabled, then it will return true, otherwise it returns false. The default value is false.
+ */
+ isLoopFocus: function(){
+ return this._loopFocus;
+ },
+
+ /**
+ * Specifies whether the layout pass its focus to its child
+ * @param pass To specify whether the layout pass its focus to its child
+ */
+ setPassFocusToChild: function(pass){
+ this.__passFocusToChild = pass;
+ },
+
+ /**
+ * Returns whether the layout will pass the focus to its children or not. The default value is true
+ * @returns {boolean} To query whether the layout will pass the focus to its children or not. The default value is true
+ */
+ isPassFocusToChild: function(){
+ return this.__passFocusToChild;
+ },
+
+ /**
+ * When a widget is in a layout, you could call this method to get the next focused widget within a specified direction.
+ * If the widget is not in a layout, it will return itself
+ * @param {Number} direction the direction to look for the next focused widget in a layout
+ * @param {ccui.Widget} current the current focused widget
+ * @returns {ccui.Widget} return the index of widget in the layout
+ */
+ findNextFocusedWidget: function(direction, current){
+ if (this._isFocusPassing || this.isFocused()) {
+ var parent = this.getParent();
+ this._isFocusPassing = false;
+ if (this.__passFocusToChild) {
+ var w = this._passFocusToChild(direction, current);
+ if (w instanceof ccui.Layout && parent) {
+ parent._isFocusPassing = true;
+ return parent.findNextFocusedWidget(direction, this);
+ }
+ return w;
+ }
+
+ if (null == parent || !(parent instanceof ccui.Layout))
+ return this;
+ parent._isFocusPassing = true;
+ return parent.findNextFocusedWidget(direction, this);
+ } else if(current.isFocused() || current instanceof ccui.Layout) {
+ if (this._layoutType === ccui.Layout.Type.LINEAR_HORIZONTAL) {
+ switch (direction){
+ case ccui.Widget.LEFT:
+ return this._getPreviousFocusedWidget(direction, current);
+ break;
+ case ccui.Widget.RIGHT:
+ return this._getNextFocusedWidget(direction, current);
+ break;
+ case ccui.Widget.DOWN:
+ case ccui.Widget.UP:
+ if (this._isLastWidgetInContainer(this, direction)){
+ if (this._isWidgetAncestorSupportLoopFocus(current, direction))
+ return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, this);
+ return current;
+ } else {
+ return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, this);
+ }
+ break;
+ default:
+ cc.assert(0, "Invalid Focus Direction");
+ return current;
+ }
+ } else if (this._layoutType === ccui.Layout.Type.LINEAR_VERTICAL) {
+ switch (direction){
+ case ccui.Widget.LEFT:
+ case ccui.Widget.RIGHT:
+ if (this._isLastWidgetInContainer(this, direction)) {
+ if (this._isWidgetAncestorSupportLoopFocus(current, direction))
+ return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, this);
+ return current;
+ }
+ else
+ return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, this);
+ break;
+ case ccui.Widget.DOWN:
+ return this._getNextFocusedWidget(direction, current);
+ break;
+ case ccui.Widget.UP:
+ return this._getPreviousFocusedWidget(direction, current);
+ break;
+ default:
+ cc.assert(0, "Invalid Focus Direction");
+ return current;
+ }
+ } else {
+ cc.assert(0, "Un Supported Layout type, please use VBox and HBox instead!!!");
+ return current;
+ }
+ } else
+ return current;
+ },
+
+ /**
+ * To specify a user-defined functor to decide which child widget of the layout should get focused
+ * @function
+ * @param {Number} direction
+ * @param {ccui.Widget} current
+ */
+ onPassFocusToChild: null,
+
+ /**
+ * override "init" method of widget. please do not call this function by yourself, you should pass the parameters to constructor to initialize it.
+ * @returns {boolean}
+ * @override
+ */
+ init: function () {
+ if (ccui.Widget.prototype.init.call(this)) {
+ this.ignoreContentAdaptWithSize(false);
+ this.setContentSize(cc.size(0, 0));
+ this.setAnchorPoint(0, 0);
+ this.onPassFocusToChild = this._findNearestChildWidgetIndex.bind(this);
+ return true;
+ }
+ return false;
+ },
+
+ /**
+ * Adds a widget to the container.
+ * @param {ccui.Widget} widget
+ * @param {Number} [zOrder]
+ * @param {Number|string} [tag] tag or name
+ * @override
+ */
+ addChild: function (widget, zOrder, tag) {
+ if ((widget instanceof ccui.Widget)) {
+ this._supplyTheLayoutParameterLackToChild(widget);
+ }
+ ccui.Widget.prototype.addChild.call(this, widget, zOrder, tag);
+ this._doLayoutDirty = true;
+ },
+
+ /**
+ * Removes child widget from ccui.Layout, and sets the layout dirty flag to true.
+ * @param {ccui.Widget} widget
+ * @param {Boolean} [cleanup=true]
+ * @override
+ */
+ removeChild: function (widget, cleanup) {
+ ccui.Widget.prototype.removeChild.call(this, widget, cleanup);
+ this._doLayoutDirty = true;
+ },
+
+ /**
+ * Removes all children from the container with a cleanup, and sets the layout dirty flag to true.
+ * @param {Boolean} cleanup
+ */
+ removeAllChildren: function (cleanup) {
+ ccui.Widget.prototype.removeAllChildren.call(this, cleanup);
+ this._doLayoutDirty = true;
+ },
+
+ /**
+ * Removes all children from the container, do a cleanup to all running actions depending on the cleanup parameter,
+ * and sets the layout dirty flag to true.
+ * @param {Boolean} cleanup true if all running actions on all children nodes should be cleanup, false otherwise.
+ */
+ removeAllChildrenWithCleanup: function(cleanup){
+ ccui.Widget.prototype.removeAllChildrenWithCleanup.call(this, cleanup);
+ this._doLayoutDirty = true;
+ },
+
+ /**
+ * Gets if layout is clipping enabled.
+ * @returns {Boolean} if layout is clipping enabled.
+ */
+ isClippingEnabled: function () {
+ return this._clippingEnabled;
+ },
+
+ /**
+ *
+ * Calls adaptRenderers (its subclass will override it.) and do layout.
+ * If clippingEnabled is true, it will clip/scissor area.
+ *
+ * @override
+ * @param {cc.Node.RenderCmd} [parentCmd]
+ */
+ visit: function (parentCmd) {
+ if (!this._visible)
+ return;
+ this._adaptRenderers();
+ this._doLayout();
+
+ if (this._clippingEnabled) {
+ switch (this._clippingType) {
+ case ccui.Layout.CLIPPING_STENCIL:
+ this._renderCmd.stencilClippingVisit(parentCmd);
+ break;
+ case ccui.Layout.CLIPPING_SCISSOR:
+ this._renderCmd.scissorClippingVisit(parentCmd);
+ break;
+ default:
+ break;
+ }
+ } else
+ ccui.Widget.prototype.visit.call(this, parentCmd);
+ },
+
+ /**
+ * Changes if layout can clip it's content and locChild.
+ * If you really need this, please enable it. But it would reduce the rendering efficiency.
+ * @param {Boolean} able clipping enabled.
+ */
+ setClippingEnabled: function (able) {
+ if (able === this._clippingEnabled)
+ return;
+ this._clippingEnabled = able;
+ switch (this._clippingType) {
+ case ccui.Layout.CLIPPING_STENCIL:
+ if (able){
+ this._clippingStencil = new cc.DrawNode();
+ this._renderCmd.rebindStencilRendering(this._clippingStencil);
+ if (this._running)
+ this._clippingStencil.onEnter();
+ this._setStencilClippingSize(this._contentSize);
+ } else {
+ if (this._running && this._clippingStencil)
+ this._clippingStencil.onExit();
+ this._clippingStencil = null;
+ }
+ break;
+ default:
+ break;
+ }
+ },
+
+ /**
+ * Sets clipping type to ccui.Layout
+ * @param {ccui.Layout.CLIPPING_STENCIL|ccui.Layout.CLIPPING_SCISSOR} type
+ */
+ setClippingType: function (type) {
+ if (type === this._clippingType)
+ return;
+ if(cc._renderType === cc.game.RENDER_TYPE_CANVAS && type === ccui.Layout.CLIPPING_SCISSOR){
+ cc.log("Only supports STENCIL on canvas mode.");
+ return;
+ }
+ var clippingEnabled = this.isClippingEnabled();
+ this.setClippingEnabled(false);
+ this._clippingType = type;
+ this.setClippingEnabled(clippingEnabled);
+ },
+
+ /**
+ * Gets clipping type of ccui.Layout
+ * @returns {ccui.Layout.CLIPPING_STENCIL|ccui.Layout.CLIPPING_SCISSOR}
+ */
+ getClippingType: function () {
+ return this._clippingType;
+ },
+
+ _setStencilClippingSize: function (size) {
+ if (this._clippingEnabled && this._clippingType === ccui.Layout.CLIPPING_STENCIL) {
+ var rect = [];
+ rect[0] = cc.p(0, 0);
+ rect[1] = cc.p(size.width, 0);
+ rect[2] = cc.p(size.width, size.height);
+ rect[3] = cc.p(0, size.height);
+ var green = cc.Color.GREEN;
+ this._clippingStencil.clear();
+ this._clippingStencil.drawPoly(rect, 4, green, 0, green);
+ }
+ },
+
+ _getClippingRect: function () {
+ if (this._clippingRectDirty) {
+ var worldPos = this.convertToWorldSpace(cc.p(0, 0));
+ var t = this.getNodeToWorldTransform();
+ var scissorWidth = this._contentSize.width * t.a;
+ var scissorHeight = this._contentSize.height * t.d;
+ var parentClippingRect;
+ var parent = this;
+
+ while (parent) {
+ parent = parent.getParent();
+ if (parent && parent instanceof ccui.Layout && parent.isClippingEnabled()) {
+ this._clippingParent = parent;
+ break;
+ }
+ }
+
+ if (this._clippingParent) {
+ parentClippingRect = this._clippingParent._getClippingRect();
+ var finalX = worldPos.x - (scissorWidth * this._anchorPoint.x);
+ var finalY = worldPos.y - (scissorHeight * this._anchorPoint.y);
+ var finalWidth = scissorWidth;
+ var finalHeight = scissorHeight;
+
+ var leftOffset = worldPos.x - parentClippingRect.x;
+ if (leftOffset < 0) {
+ finalX = parentClippingRect.x;
+ finalWidth += leftOffset;
+ }
+ var rightOffset = (worldPos.x + scissorWidth) - (parentClippingRect.x + parentClippingRect.width);
+ if (rightOffset > 0)
+ finalWidth -= rightOffset;
+ var topOffset = (worldPos.y + scissorHeight) - (parentClippingRect.y + parentClippingRect.height);
+ if (topOffset > 0)
+ finalHeight -= topOffset;
+ var bottomOffset = worldPos.y - parentClippingRect.y;
+ if (bottomOffset < 0) {
+ finalY = parentClippingRect.x;
+ finalHeight += bottomOffset;
+ }
+ if (finalWidth < 0)
+ finalWidth = 0;
+ if (finalHeight < 0)
+ finalHeight = 0;
+ this._clippingRect.x = finalX;
+ this._clippingRect.y = finalY;
+ this._clippingRect.width = finalWidth;
+ this._clippingRect.height = finalHeight;
+ } else {
+ this._clippingRect.x = worldPos.x - (scissorWidth * this._anchorPoint.x);
+ this._clippingRect.y = worldPos.y - (scissorHeight * this._anchorPoint.y);
+ this._clippingRect.width = scissorWidth;
+ this._clippingRect.height = scissorHeight;
+ }
+ this._clippingRectDirty = false;
+ }
+ return this._clippingRect;
+ },
+
+ _onSizeChanged: function () {
+ ccui.Widget.prototype._onSizeChanged.call(this);
+ var locContentSize = this._contentSize;
+ this._setStencilClippingSize(locContentSize);
+ this._doLayoutDirty = true;
+ this._clippingRectDirty = true;
+ if (this._backGroundImage) {
+ this._backGroundImage.setPosition(locContentSize.width * 0.5, locContentSize.height * 0.5);
+ if (this._backGroundScale9Enabled && this._backGroundImage instanceof ccui.Scale9Sprite)
+ this._backGroundImage.setPreferredSize(locContentSize);
+ }
+ if (this._colorRender)
+ this._colorRender.setContentSize(locContentSize);
+ if (this._gradientRender)
+ this._gradientRender.setContentSize(locContentSize);
+ },
+
+ /**
+ * Sets background image use scale9 renderer.
+ * @param {Boolean} able true that use scale9 renderer, false otherwise.
+ */
+ setBackGroundImageScale9Enabled: function (able) {
+ if (this._backGroundScale9Enabled === able)
+ return;
+ this.removeProtectedChild(this._backGroundImage);
+ this._backGroundImage = null;
+ this._backGroundScale9Enabled = able;
+ this._addBackGroundImage();
+ this.setBackGroundImage(this._backGroundImageFileName, this._bgImageTexType);
+ this.setBackGroundImageCapInsets(this._backGroundImageCapInsets);
+ },
+
+ /**
+ * Get whether background image is use scale9 renderer.
+ * @returns {Boolean}
+ */
+ isBackGroundImageScale9Enabled: function () {
+ return this._backGroundScale9Enabled;
+ },
+
+ /**
+ * Sets a background image for layout
+ * @param {String} fileName
+ * @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType
+ */
+ setBackGroundImage: function (fileName, texType) {
+ if (!fileName)
+ return;
+ texType = texType || ccui.Widget.LOCAL_TEXTURE;
+ if (this._backGroundImage === null){
+ this._addBackGroundImage();
+ this.setBackGroundImageScale9Enabled(this._backGroundScale9Enabled);
+ }
+ this._backGroundImageFileName = fileName;
+ this._bgImageTexType = texType;
+ var locBackgroundImage = this._backGroundImage;
+ switch (this._bgImageTexType) {
+ case ccui.Widget.LOCAL_TEXTURE:
+ locBackgroundImage.initWithFile(fileName);
+ break;
+ case ccui.Widget.PLIST_TEXTURE:
+ locBackgroundImage.initWithSpriteFrameName(fileName);
+ break;
+ default:
+ break;
+ }
+ if (this._backGroundScale9Enabled)
+ locBackgroundImage.setPreferredSize(this._contentSize);
+
+ this._backGroundImageTextureSize = locBackgroundImage.getContentSize();
+ locBackgroundImage.setPosition(this._contentSize.width * 0.5, this._contentSize.height * 0.5);
+ this._updateBackGroundImageColor();
+ },
+
+ /**
+ * Sets a background image CapInsets for layout, if the background image is a scale9 render.
+ * @param {cc.Rect} capInsets capinsets of background image.
+ */
+ setBackGroundImageCapInsets: function (capInsets) {
+ if(!capInsets)
+ return;
+ var locInsets = this._backGroundImageCapInsets;
+ locInsets.x = capInsets.x;
+ locInsets.y = capInsets.y;
+ locInsets.width = capInsets.width;
+ locInsets.height = capInsets.height;
+ if (this._backGroundScale9Enabled)
+ this._backGroundImage.setCapInsets(capInsets);
+ },
+
+ /**
+ * Gets background image capinsets of ccui.Layout.
+ * @returns {cc.Rect}
+ */
+ getBackGroundImageCapInsets: function () {
+ return cc.rect(this._backGroundImageCapInsets);
+ },
+
+ _supplyTheLayoutParameterLackToChild: function (locChild) {
+ if (!locChild) {
+ return;
+ }
+ switch (this._layoutType) {
+ case ccui.Layout.Type.ABSOLUTE:
+ break;
+ case ccui.Layout.Type.LINEAR_HORIZONTAL:
+ case ccui.Layout.Type.LINEAR_VERTICAL:
+ var layoutParameter = locChild.getLayoutParameter(ccui.LayoutParameter.LINEAR);
+ if (!layoutParameter)
+ locChild.setLayoutParameter(new ccui.LinearLayoutParameter());
+ break;
+ case ccui.Layout.Type.RELATIVE:
+ var layoutParameter = locChild.getLayoutParameter(ccui.LayoutParameter.RELATIVE);
+ if (!layoutParameter)
+ locChild.setLayoutParameter(new ccui.RelativeLayoutParameter());
+ break;
+ default:
+ break;
+ }
+ },
+
+ _addBackGroundImage: function () {
+ var contentSize = this._contentSize;
+ if (this._backGroundScale9Enabled) {
+ this._backGroundImage = new ccui.Scale9Sprite();
+ this._backGroundImage.setPreferredSize(contentSize);
+ } else
+ this._backGroundImage = new cc.Sprite();
+ this.addProtectedChild(this._backGroundImage, ccui.Layout.BACKGROUND_IMAGE_ZORDER, -1);
+ this._backGroundImage.setPosition(contentSize.width * 0.5, contentSize.height * 0.5);
+ },
+
+ /**
+ * Remove the background image of ccui.Layout.
+ */
+ removeBackGroundImage: function () {
+ if (!this._backGroundImage)
+ return;
+ this.removeProtectedChild(this._backGroundImage);
+ this._backGroundImage = null;
+ this._backGroundImageFileName = "";
+ this._backGroundImageTextureSize.width = 0;
+ this._backGroundImageTextureSize.height = 0;
+ },
+
+ /**
+ * Sets Color Type for ccui.Layout.
+ * @param {ccui.Layout.BG_COLOR_NONE|ccui.Layout.BG_COLOR_SOLID|ccui.Layout.BG_COLOR_GRADIENT} type
+ */
+ setBackGroundColorType: function (type) {
+ if (this._colorType === type)
+ return;
+ switch (this._colorType) {
+ case ccui.Layout.BG_COLOR_NONE:
+ if (this._colorRender) {
+ this.removeProtectedChild(this._colorRender);
+ this._colorRender = null;
+ }
+ if (this._gradientRender) {
+ this.removeProtectedChild(this._gradientRender);
+ this._gradientRender = null;
+ }
+ break;
+ case ccui.Layout.BG_COLOR_SOLID:
+ if (this._colorRender) {
+ this.removeProtectedChild(this._colorRender);
+ this._colorRender = null;
+ }
+ break;
+ case ccui.Layout.BG_COLOR_GRADIENT:
+ if (this._gradientRender) {
+ this.removeProtectedChild(this._gradientRender);
+ this._gradientRender = null;
+ }
+ break;
+ default:
+ break;
+ }
+ this._colorType = type;
+ switch (this._colorType) {
+ case ccui.Layout.BG_COLOR_NONE:
+ break;
+ case ccui.Layout.BG_COLOR_SOLID:
+ this._colorRender = new cc.LayerColor();
+ this._colorRender.setContentSize(this._contentSize);
+ this._colorRender.setOpacity(this._opacity);
+ this._colorRender.setColor(this._color);
+ this.addProtectedChild(this._colorRender, ccui.Layout.BACKGROUND_RENDERER_ZORDER, -1);
+ break;
+ case ccui.Layout.BG_COLOR_GRADIENT:
+ this._gradientRender = new cc.LayerGradient(cc.color(255, 0, 0, 255), cc.color(0, 255, 0, 255));
+ this._gradientRender.setContentSize(this._contentSize);
+ this._gradientRender.setOpacity(this._opacity);
+ this._gradientRender.setStartColor(this._startColor);
+ this._gradientRender.setEndColor(this._endColor);
+ this._gradientRender.setVector(this._alongVector);
+ this.addProtectedChild(this._gradientRender, ccui.Layout.BACKGROUND_RENDERER_ZORDER, -1);
+ break;
+ default:
+ break;
+ }
+ },
+
+ /**
+ * Get background color type of ccui.Layout.
+ * @returns {ccui.Layout.BG_COLOR_NONE|ccui.Layout.BG_COLOR_SOLID|ccui.Layout.BG_COLOR_GRADIENT}
+ */
+ getBackGroundColorType: function () {
+ return this._colorType;
+ },
+
+ /**
+ * Sets background color for layout, if color type is Layout.COLOR_SOLID
+ * @param {cc.Color} color
+ * @param {cc.Color} [endColor]
+ */
+ setBackGroundColor: function (color, endColor) {
+ if (!endColor) {
+ this._color.r = color.r;
+ this._color.g = color.g;
+ this._color.b = color.b;
+ if (this._colorRender)
+ this._colorRender.setColor(color);
+ } else {
+ this._startColor.r = color.r;
+ this._startColor.g = color.g;
+ this._startColor.b = color.b;
+ if (this._gradientRender)
+ this._gradientRender.setStartColor(color);
+
+ this._endColor.r = endColor.r;
+ this._endColor.g = endColor.g;
+ this._endColor.b = endColor.b;
+ if (this._gradientRender)
+ this._gradientRender.setEndColor(endColor);
+ }
+ },
+
+ /**
+ * Gets background color of ccui.Layout, if color type is Layout.COLOR_SOLID.
+ * @returns {cc.Color}
+ */
+ getBackGroundColor: function () {
+ var tmpColor = this._color;
+ return cc.color(tmpColor.r, tmpColor.g, tmpColor.b, tmpColor.a);
+ },
+
+ /**
+ * Gets background start color of ccui.Layout
+ * @returns {cc.Color}
+ */
+ getBackGroundStartColor: function () {
+ var tmpColor = this._startColor;
+ return cc.color(tmpColor.r, tmpColor.g, tmpColor.b, tmpColor.a);
+ },
+
+ /**
+ * Gets background end color of ccui.Layout
+ * @returns {cc.Color}
+ */
+ getBackGroundEndColor: function () {
+ var tmpColor = this._endColor;
+ return cc.color(tmpColor.r, tmpColor.g, tmpColor.b, tmpColor.a);
+ },
+
+ /**
+ * Sets background opacity to ccui.Layout.
+ * @param {number} opacity
+ */
+ setBackGroundColorOpacity: function (opacity) {
+ this._opacity = opacity;
+ switch (this._colorType) {
+ case ccui.Layout.BG_COLOR_NONE:
+ break;
+ case ccui.Layout.BG_COLOR_SOLID:
+ this._colorRender.setOpacity(opacity);
+ break;
+ case ccui.Layout.BG_COLOR_GRADIENT:
+ this._gradientRender.setOpacity(opacity);
+ break;
+ default:
+ break;
+ }
+ },
+
+ /**
+ * Get background opacity value of ccui.Layout.
+ * @returns {Number}
+ */
+ getBackGroundColorOpacity: function () {
+ return this._opacity;
+ },
+
+ /**
+ * Sets background color vector for layout, if color type is Layout.COLOR_GRADIENT
+ * @param {cc.Vec2} vector
+ */
+ setBackGroundColorVector: function (vector) {
+ this._alongVector.x = vector.x;
+ this._alongVector.y = vector.y;
+ if (this._gradientRender) {
+ this._gradientRender.setVector(vector);
+ }
+ },
+
+ /**
+ * Gets background color vector of ccui.Layout, if color type is Layout.COLOR_GRADIENT
+ * @returns {cc.Vec2}
+ */
+ getBackGroundColorVector: function () {
+ return this._alongVector;
+ },
+
+ /**
+ * Sets backGround image color
+ * @param {cc.Color} color
+ */
+ setBackGroundImageColor: function (color) {
+ this._backGroundImageColor.r = color.r;
+ this._backGroundImageColor.g = color.g;
+ this._backGroundImageColor.b = color.b;
+
+ this._updateBackGroundImageColor();
+ },
+
+ /**
+ * Sets backGround image Opacity
+ * @param {Number} opacity
+ */
+ setBackGroundImageOpacity: function (opacity) {
+ this._backGroundImageColor.a = opacity;
+ this.getBackGroundImageColor();
+ },
+
+ /**
+ * Gets backGround image color
+ * @returns {cc.Color}
+ */
+ getBackGroundImageColor: function () {
+ var color = this._backGroundImageColor;
+ return cc.color(color.r, color.g, color.b, color.a);
+ },
+
+ /**
+ * Gets backGround image opacity
+ * @returns {Number}
+ */
+ getBackGroundImageOpacity: function () {
+ return this._backGroundImageColor.a;
+ },
+
+ _updateBackGroundImageColor: function () {
+ if(this._backGroundImage)
+ this._backGroundImage.setColor(this._backGroundImageColor);
+ },
+
+ /**
+ * Gets background image texture size.
+ * @returns {cc.Size}
+ */
+ getBackGroundImageTextureSize: function () {
+ return this._backGroundImageTextureSize;
+ },
+
+ /**
+ * Sets LayoutType to ccui.Layout, LayoutManager will do layout by layout type..
+ * @param {ccui.Layout.Type} type
+ */
+ setLayoutType: function (type) {
+ this._layoutType = type;
+ var layoutChildrenArray = this._children;
+ var locChild = null;
+ for (var i = 0; i < layoutChildrenArray.length; i++) {
+ locChild = layoutChildrenArray[i];
+ if(locChild instanceof ccui.Widget)
+ this._supplyTheLayoutParameterLackToChild(locChild);
+ }
+ this._doLayoutDirty = true;
+ },
+
+ /**
+ * Gets LayoutType of ccui.Layout.
+ * @returns {null}
+ */
+ getLayoutType: function () {
+ return this._layoutType;
+ },
+
+ /**
+ * request to refresh widget layout, it will do layout at visit calls
+ */
+ requestDoLayout: function () {
+ this._doLayoutDirty = true;
+ },
+
+ _doLayout: function () {
+ if (!this._doLayoutDirty)
+ return;
+
+ this.sortAllChildren();
+
+ var executant = ccui.getLayoutManager(this._layoutType);
+ if (executant)
+ executant._doLayout(this);
+ this._doLayoutDirty = false;
+ },
+
+ _getLayoutContentSize: function(){
+ return this.getContentSize();
+ },
+
+ _getLayoutElements: function(){
+ return this.getChildren();
+ },
+
+ _updateBackGroundImageOpacity: function(){
+ if (this._backGroundImage)
+ this._backGroundImage.setOpacity(this._backGroundImageOpacity);
+ },
+
+ _updateBackGroundImageRGBA: function(){
+ if (this._backGroundImage) {
+ this._backGroundImage.setColor(this._backGroundImageColor);
+ this._backGroundImage.setOpacity(this._backGroundImageOpacity);
+ }
+ },
+
+ /**
+ * Gets the content size of the layout, it will accumulate all its children's content size
+ * @returns {cc.Size}
+ * @private
+ */
+ _getLayoutAccumulatedSize: function(){
+ var children = this.getChildren();
+ var layoutSize = cc.size(0, 0);
+ var widgetCount = 0, locSize;
+ for(var i = 0, len = children.length; i < len; i++) {
+ var layout = children[i];
+ if (null !== layout && layout instanceof ccui.Layout){
+ locSize = layout._getLayoutAccumulatedSize();
+ layoutSize.width += locSize.width;
+ layoutSize.height += locSize.height;
+ } else {
+ if (layout instanceof ccui.Widget) {
+ widgetCount++;
+ var m = layout.getLayoutParameter().getMargin();
+ locSize = layout.getContentSize();
+ layoutSize.width += locSize.width + (m.right + m.left) * 0.5;
+ layoutSize.height += locSize.height + (m.top + m.bottom) * 0.5;
+ }
+ }
+ }
+
+ //substract extra size
+ var type = this.getLayoutType();
+ if (type === ccui.Layout.Type.LINEAR_HORIZONTAL)
+ layoutSize.height = layoutSize.height - layoutSize.height/widgetCount * (widgetCount-1);
+
+ if (type === ccui.Layout.Type.LINEAR_VERTICAL)
+ layoutSize.width = layoutSize.width - layoutSize.width/widgetCount * (widgetCount-1);
+ return layoutSize;
+ },
+
+ /**
+ * When the layout get focused, it the layout pass the focus to its child, it will use this method to determine which child
+ * will get the focus. The current algorithm to determine which child will get focus is nearest-distance-priority algorithm
+ * @param {Number} direction next focused widget direction
+ * @param {ccui.Widget} baseWidget
+ * @returns {Number}
+ * @private
+ */
+ _findNearestChildWidgetIndex: function(direction, baseWidget){
+ if (baseWidget == null || baseWidget === this)
+ return this._findFirstFocusEnabledWidgetIndex();
+
+ var index = 0, locChildren = this.getChildren();
+ var count = locChildren.length, widgetPosition;
+
+ var distance = cc.FLT_MAX, found = 0;
+ if (direction === ccui.Widget.LEFT || direction === ccui.Widget.RIGHT || direction === ccui.Widget.DOWN || direction === ccui.Widget.UP) {
+ widgetPosition = this._getWorldCenterPoint(baseWidget);
+ while (index < count) {
+ var w = locChildren[index];
+ if (w && w instanceof ccui.Widget && w.isFocusEnabled()) {
+ var length = (w instanceof ccui.Layout)? w._calculateNearestDistance(baseWidget)
+ : cc.pLength(cc.pSub(this._getWorldCenterPoint(w), widgetPosition));
+ if (length < distance){
+ found = index;
+ distance = length;
+ }
+ }
+ index++;
+ }
+ return found;
+ }
+ cc.log("invalid focus direction!");
+ return 0;
+ },
+
+ /**
+ * When the layout get focused, it the layout pass the focus to its child, it will use this method to determine which child
+ * will get the focus. The current algorithm to determine which child will get focus is farthest-distance-priority algorithm
+ * @param {Number} direction next focused widget direction
+ * @param {ccui.Widget} baseWidget
+ * @returns {Number} The index of child widget in the container
+ * @private
+ */
+ _findFarthestChildWidgetIndex: function(direction, baseWidget){
+ if (baseWidget == null || baseWidget === this)
+ return this._findFirstFocusEnabledWidgetIndex();
+
+ var index = 0, locChildren = this.getChildren();
+ var count = locChildren.length;
+
+ var distance = -cc.FLT_MAX, found = 0;
+ if (direction === ccui.Widget.LEFT || direction === ccui.Widget.RIGHT || direction === ccui.Widget.DOWN || direction === ccui.Widget.UP) {
+ var widgetPosition = this._getWorldCenterPoint(baseWidget);
+ while (index < count) {
+ var w = locChildren[index];
+ if (w && w instanceof ccui.Widget && w.isFocusEnabled()) {
+ var length = (w instanceof ccui.Layout)?w._calculateFarthestDistance(baseWidget)
+ : cc.pLength(cc.pSub(this._getWorldCenterPoint(w), widgetPosition));
+ if (length > distance){
+ found = index;
+ distance = length;
+ }
+ }
+ index++;
+ }
+ return found;
+ }
+ cc.log("invalid focus direction!!!");
+ return 0;
+ },
+
+ /**
+ * calculate the nearest distance between the baseWidget and the children of the layout
+ * @param {ccui.Widget} baseWidget the base widget which will be used to calculate the distance between the layout's children and itself
+ * @returns {Number} return the nearest distance between the baseWidget and the layout's children
+ * @private
+ */
+ _calculateNearestDistance: function(baseWidget){
+ var distance = cc.FLT_MAX;
+ var widgetPosition = this._getWorldCenterPoint(baseWidget);
+ var locChildren = this._children;
+
+ for (var i = 0, len = locChildren.length; i < len; i++) {
+ var widget = locChildren[i], length;
+ if (widget instanceof ccui.Layout)
+ length = widget._calculateNearestDistance(baseWidget);
+ else {
+ if (widget instanceof ccui.Widget && widget.isFocusEnabled())
+ length = cc.pLength(cc.pSub(this._getWorldCenterPoint(widget), widgetPosition));
+ else
+ continue;
+ }
+ if (length < distance)
+ distance = length;
+ }
+ return distance;
+ },
+
+ /**
+ * calculate the farthest distance between the baseWidget and the children of the layout
+ * @param baseWidget
+ * @returns {number}
+ * @private
+ */
+ _calculateFarthestDistance:function(baseWidget){
+ var distance = -cc.FLT_MAX;
+ var widgetPosition = this._getWorldCenterPoint(baseWidget);
+ var locChildren = this._children;
+
+ for (var i = 0, len = locChildren.length; i < len; i++) {
+ var layout = locChildren[i];
+ var length;
+ if (layout instanceof ccui.Layout)
+ length = layout._calculateFarthestDistance(baseWidget);
+ else {
+ if (layout instanceof ccui.Widget && layout.isFocusEnabled()) {
+ var wPosition = this._getWorldCenterPoint(layout);
+ length = cc.pLength(cc.pSub(wPosition, widgetPosition));
+ } else
+ continue;
+ }
+
+ if (length > distance)
+ distance = length;
+ }
+ return distance;
+ },
+
+ /**
+ * when a layout pass the focus to it's child, use this method to determine which algorithm to use, nearest or farthest distance algorithm or not
+ * @param direction
+ * @param baseWidget
+ * @private
+ */
+ _findProperSearchingFunctor: function(direction, baseWidget){
+ if (baseWidget == null)
+ return;
+
+ var previousWidgetPosition = this._getWorldCenterPoint(baseWidget);
+ var widgetPosition = this._getWorldCenterPoint(this._findFirstNonLayoutWidget());
+ if (direction === ccui.Widget.LEFT) {
+ this.onPassFocusToChild = (previousWidgetPosition.x > widgetPosition.x) ? this._findNearestChildWidgetIndex.bind(this)
+ : this._findFarthestChildWidgetIndex.bind(this);
+ } else if (direction === ccui.Widget.RIGHT) {
+ this.onPassFocusToChild = (previousWidgetPosition.x > widgetPosition.x) ? this._findFarthestChildWidgetIndex.bind(this)
+ : this._findNearestChildWidgetIndex.bind(this);
+ }else if(direction === ccui.Widget.DOWN) {
+ this.onPassFocusToChild = (previousWidgetPosition.y > widgetPosition.y) ? this._findNearestChildWidgetIndex.bind(this)
+ : this._findFarthestChildWidgetIndex.bind(this);
+ }else if(direction === ccui.Widget.UP) {
+ this.onPassFocusToChild = (previousWidgetPosition.y < widgetPosition.y) ? this._findNearestChildWidgetIndex.bind(this)
+ : this._findFarthestChildWidgetIndex.bind(this);
+ }else
+ cc.log("invalid direction!");
+ },
+
+ /**
+ * find the first non-layout widget in this layout
+ * @returns {ccui.Widget}
+ * @private
+ */
+ _findFirstNonLayoutWidget:function(){
+ var locChildren = this._children;
+ for(var i = 0, len = locChildren.length; i < len; i++) {
+ var child = locChildren[i];
+ if (child instanceof ccui.Layout){
+ var widget = child._findFirstNonLayoutWidget();
+ if(widget)
+ return widget;
+ } else{
+ if (child instanceof ccui.Widget)
+ return child;
+ }
+ }
+ return null;
+ },
+
+ /**
+ * find the first focus enabled widget index in the layout, it will recursive searching the child widget
+ * @returns {number}
+ * @private
+ */
+ _findFirstFocusEnabledWidgetIndex: function(){
+ var index = 0, locChildren = this.getChildren();
+ var count = locChildren.length;
+ while (index < count) {
+ var w = locChildren[index];
+ if (w && w instanceof ccui.Widget && w.isFocusEnabled())
+ return index;
+ index++;
+ }
+ return 0;
+ },
+
+ /**
+ * find a focus enabled child Widget in the layout by index
+ * @param index
+ * @returns {*}
+ * @private
+ */
+ _findFocusEnabledChildWidgetByIndex: function(index){
+ var widget = this._getChildWidgetByIndex(index);
+ if (widget){
+ if (widget.isFocusEnabled())
+ return widget;
+ index = index + 1;
+ return this._findFocusEnabledChildWidgetByIndex(index);
+ }
+ return null;
+ },
+
+ /**
+ * get the center point of a widget in world space
+ * @param {ccui.Widget} widget
+ * @returns {cc.Vec2}
+ * @private
+ */
+ _getWorldCenterPoint: function(widget){
+ //FIXEDME: we don't need to calculate the content size of layout anymore
+ var widgetSize = widget instanceof ccui.Layout ? widget._getLayoutAccumulatedSize() : widget.getContentSize();
+ return widget.convertToWorldSpace(cc.p(widgetSize.width /2, widgetSize.height /2));
+ },
+
+ /**
+ * this method is called internally by nextFocusedWidget. When the dir is Right/Down, then this method will be called
+ * @param {Number} direction
+ * @param {ccui.Widget} current the current focused widget
+ * @returns {ccui.Widget} the next focused widget
+ * @private
+ */
+ _getNextFocusedWidget: function(direction, current){
+ var nextWidget = null, locChildren = this._children;
+ var previousWidgetPos = locChildren.indexOf(current);
+ previousWidgetPos = previousWidgetPos + 1;
+ if (previousWidgetPos < locChildren.length) {
+ nextWidget = this._getChildWidgetByIndex(previousWidgetPos);
+ //handle widget
+ if (nextWidget) {
+ if (nextWidget.isFocusEnabled()) {
+ if (nextWidget instanceof ccui.Layout) {
+ nextWidget._isFocusPassing = true;
+ return nextWidget.findNextFocusedWidget(direction, nextWidget);
+ } else {
+ this.dispatchFocusEvent(current, nextWidget);
+ return nextWidget;
+ }
+ } else
+ return this._getNextFocusedWidget(direction, nextWidget);
+ } else
+ return current;
+ } else {
+ if (this._loopFocus) {
+ if (this._checkFocusEnabledChild()) {
+ previousWidgetPos = 0;
+ nextWidget = this._getChildWidgetByIndex(previousWidgetPos);
+ if (nextWidget.isFocusEnabled()) {
+ if (nextWidget instanceof ccui.Layout) {
+ nextWidget._isFocusPassing = true;
+ return nextWidget.findNextFocusedWidget(direction, nextWidget);
+ } else {
+ this.dispatchFocusEvent(current, nextWidget);
+ return nextWidget;
+ }
+ } else
+ return this._getNextFocusedWidget(direction, nextWidget);
+ } else
+ return (current instanceof ccui.Layout) ? current : ccui.Widget._focusedWidget;
+ } else{
+ if (this._isLastWidgetInContainer(current, direction)){
+ if (this._isWidgetAncestorSupportLoopFocus(this, direction))
+ return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, this);
+ return (current instanceof ccui.Layout) ? current : ccui.Widget._focusedWidget;
+ } else
+ return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, this);
+ }
+ }
+ },
+
+ /**
+ * this method is called internally by nextFocusedWidget. When the dir is Left/Up, then this method will be called
+ * @param direction
+ * @param {ccui.Widget} current the current focused widget
+ * @returns {ccui.Widget} the next focused widget
+ * @private
+ */
+ _getPreviousFocusedWidget: function(direction, current){
+ var nextWidget = null, locChildren = this._children;
+ var previousWidgetPos = locChildren.indexOf(current);
+ previousWidgetPos = previousWidgetPos - 1;
+ if (previousWidgetPos >= 0){
+ nextWidget = this._getChildWidgetByIndex(previousWidgetPos);
+ if (nextWidget.isFocusEnabled()) {
+ if (nextWidget instanceof ccui.Layout){
+ nextWidget._isFocusPassing = true;
+ return nextWidget.findNextFocusedWidget(direction, nextWidget);
+ }
+ this.dispatchFocusEvent(current, nextWidget);
+ return nextWidget;
+ } else
+ return this._getPreviousFocusedWidget(direction, nextWidget); //handling the disabled widget, there is no actual focus lose or get, so we don't need any envet
+ }else {
+ if (this._loopFocus){
+ if (this._checkFocusEnabledChild()) {
+ previousWidgetPos = locChildren.length -1;
+ nextWidget = this._getChildWidgetByIndex(previousWidgetPos);
+ if (nextWidget.isFocusEnabled()){
+ if (nextWidget instanceof ccui.Layout){
+ nextWidget._isFocusPassing = true;
+ return nextWidget.findNextFocusedWidget(direction, nextWidget);
+ } else {
+ this.dispatchFocusEvent(current, nextWidget);
+ return nextWidget;
+ }
+ } else
+ return this._getPreviousFocusedWidget(direction, nextWidget);
+ } else
+ return (current instanceof ccui.Layout) ? current : ccui.Widget._focusedWidget;
+ } else {
+ if (this._isLastWidgetInContainer(current, direction)) {
+ if (this._isWidgetAncestorSupportLoopFocus(this, direction))
+ return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, this);
+ return (current instanceof ccui.Layout) ? current : ccui.Widget._focusedWidget;
+ } else
+ return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, this);
+ }
+ }
+ },
+
+ /**
+ * find the nth element in the _children array. Only the Widget descendant object will be returned
+ * @param {Number} index
+ * @returns {ccui.Widget}
+ * @private
+ */
+ _getChildWidgetByIndex: function (index) {
+ var locChildren = this._children;
+ var size = locChildren.length, count = 0, oldIndex = index;
+ while (index < size) {
+ var firstChild = locChildren[index];
+ if (firstChild && firstChild instanceof ccui.Widget)
+ return firstChild;
+ count++;
+ index++;
+ }
+
+ var begin = 0;
+ while (begin < oldIndex) {
+ var child = locChildren[begin];
+ if (child && child instanceof ccui.Widget)
+ return child;
+ count++;
+ begin++;
+ }
+ return null;
+ },
+
+ /**
+ * whether it is the last element according to all their parents
+ * @param {ccui.Widget} widget
+ * @param {Number} direction
+ * @returns {Boolean}
+ * @private
+ */
+ _isLastWidgetInContainer:function(widget, direction){
+ var parent = widget.getParent();
+ if (parent == null || !(parent instanceof ccui.Layout))
+ return true;
+
+ var container = parent.getChildren();
+ var index = container.indexOf(widget);
+ if (parent.getLayoutType() === ccui.Layout.Type.LINEAR_HORIZONTAL) {
+ if (direction === ccui.Widget.LEFT) {
+ if (index === 0)
+ return this._isLastWidgetInContainer(parent, direction);
+ else
+ return false;
+ }
+ if (direction === ccui.Widget.RIGHT) {
+ if (index === container.length - 1)
+ return this._isLastWidgetInContainer(parent, direction);
+ else
+ return false;
+ }
+ if (direction === ccui.Widget.DOWN)
+ return this._isLastWidgetInContainer(parent, direction);
+
+ if (direction === ccui.Widget.UP)
+ return this._isLastWidgetInContainer(parent, direction);
+ } else if(parent.getLayoutType() === ccui.Layout.Type.LINEAR_VERTICAL){
+ if (direction === ccui.Widget.UP){
+ if (index === 0)
+ return this._isLastWidgetInContainer(parent, direction);
+ else
+ return false;
+ }
+ if (direction === ccui.Widget.DOWN) {
+ if (index === container.length - 1)
+ return this._isLastWidgetInContainer(parent, direction);
+ else
+ return false;
+ }
+ if (direction === ccui.Widget.LEFT)
+ return this._isLastWidgetInContainer(parent, direction);
+
+ if (direction === ccui.Widget.RIGHT)
+ return this._isLastWidgetInContainer(parent, direction);
+ } else {
+ cc.log("invalid layout Type");
+ return false;
+ }
+ },
+
+ /**
+ * Lookup any parent widget with a layout type as the direction, if the layout is loop focused, then return true, otherwise it returns false.
+ * @param {ccui.Widget} widget
+ * @param {Number} direction
+ * @returns {Boolean}
+ * @private
+ */
+ _isWidgetAncestorSupportLoopFocus: function(widget, direction){
+ var parent = widget.getParent();
+ if (parent == null || !(parent instanceof ccui.Layout))
+ return false;
+ if (parent.isLoopFocus()) {
+ var layoutType = parent.getLayoutType();
+ if (layoutType === ccui.Layout.Type.LINEAR_HORIZONTAL) {
+ if (direction === ccui.Widget.LEFT || direction === ccui.Widget.RIGHT)
+ return true;
+ else
+ return this._isWidgetAncestorSupportLoopFocus(parent, direction);
+ }
+ if (layoutType === ccui.Layout.Type.LINEAR_VERTICAL){
+ if (direction === ccui.Widget.DOWN || direction === ccui.Widget.UP)
+ return true;
+ else
+ return this._isWidgetAncestorSupportLoopFocus(parent, direction);
+ } else{
+ cc.assert(0, "invalid layout type");
+ return false;
+ }
+ } else
+ return this._isWidgetAncestorSupportLoopFocus(parent, direction);
+ },
+
+ /**
+ * pass the focus to the layout's next focus enabled child
+ * @param {Number} direction
+ * @param {ccui.Widget} current
+ * @returns {ccui.Widget}
+ * @private
+ */
+ _passFocusToChild: function(direction, current){
+ if (this._checkFocusEnabledChild()) {
+ var previousWidget = ccui.Widget.getCurrentFocusedWidget();
+ this._findProperSearchingFunctor(direction, previousWidget);
+ var index = this.onPassFocusToChild(direction, previousWidget);
+
+ var widget = this._getChildWidgetByIndex(index);
+ if (widget instanceof ccui.Layout) {
+ widget._isFocusPassing = true;
+ return widget.findNextFocusedWidget(direction, widget);
+ } else {
+ this.dispatchFocusEvent(current, widget);
+ return widget;
+ }
+ }else
+ return this;
+ },
+
+ /**
+ * If there are no focus enabled child in the layout, it will return false, otherwise it returns true
+ * @returns {boolean}
+ * @private
+ */
+ _checkFocusEnabledChild: function(){
+ var locChildren = this._children;
+ for(var i = 0, len = locChildren.length; i < len; i++){
+ var widget = locChildren[i];
+ if (widget && widget instanceof ccui.Widget && widget.isFocusEnabled())
+ return true;
+ }
+ return false;
+ },
+
+ /**
+ * Returns the "class name" of widget.
+ * @returns {string}
+ */
+ getDescription: function () {
+ return "Layout";
+ },
+
+ _createCloneInstance: function () {
+ return new ccui.Layout();
+ },
+
+ _copyClonedWidgetChildren: function (model) {
+ ccui.Widget.prototype._copyClonedWidgetChildren.call(this, model);
+ },
+
+ _copySpecialProperties: function (layout) {
+ if(!(layout instanceof ccui.Layout))
+ return;
+ this.setBackGroundImageScale9Enabled(layout._backGroundScale9Enabled);
+ this.setBackGroundImage(layout._backGroundImageFileName, layout._bgImageTexType);
+ this.setBackGroundImageCapInsets(layout._backGroundImageCapInsets);
+ this.setBackGroundColorType(layout._colorType);
+ this.setBackGroundColor(layout._color);
+ this.setBackGroundColor(layout._startColor, layout._endColor);
+ this.setBackGroundColorOpacity(layout._opacity);
+ this.setBackGroundColorVector(layout._alongVector);
+ this.setLayoutType(layout._layoutType);
+ this.setClippingEnabled(layout._clippingEnabled);
+ this.setClippingType(layout._clippingType);
+ this._loopFocus = layout._loopFocus;
+ this.__passFocusToChild = layout.__passFocusToChild;
+ this._isInterceptTouch = layout._isInterceptTouch;
+ },
+
+ /**
+ * force refresh widget layout
+ */
+ forceDoLayout: function(){
+ this.requestDoLayout();
+ this._doLayout();
+ },
+
+ _createRenderCmd: function(){
+ if(cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ return new ccui.Layout.WebGLRenderCmd(this);
+ else
+ return new ccui.Layout.CanvasRenderCmd(this);
+ }
+});
+
+var _p = ccui.Layout.prototype;
+
+// Extended properties
+/** @expose */
+_p.clippingEnabled;
+cc.defineGetterSetter(_p, "clippingEnabled", _p.isClippingEnabled, _p.setClippingEnabled);
+/** @expose */
+_p.clippingType;
+cc.defineGetterSetter(_p, "clippingType", null, _p.setClippingType);
+/** @expose */
+_p.layoutType;
+cc.defineGetterSetter(_p, "layoutType", _p.getLayoutType, _p.setLayoutType);
+
+_p = null;
+
+/**
+ * allocates and initializes a UILayout.
+ * @deprecated since v3.0, please use new ccui.Layout() instead.
+ * @return {ccui.Layout}
+ */
+ccui.Layout.create = function () {
+ return new ccui.Layout();
+};
+
+// Constants
+
+//layoutBackGround color type
+/**
+ * The None of ccui.Layout's background color type
+ * @constant
+ * @type {number}
+ */
+ccui.Layout.BG_COLOR_NONE = 0;
+/**
+ * The solid of ccui.Layout's background color type, it will use a LayerColor to draw the background.
+ * @constant
+ * @type {number}
+ */
+ccui.Layout.BG_COLOR_SOLID = 1;
+/**
+ * The gradient of ccui.Layout's background color type, it will use a LayerGradient to draw the background.
+ * @constant
+ * @type {number}
+ */
+ccui.Layout.BG_COLOR_GRADIENT = 2;
+
+/**
+ * Enum for layout type
+ * @readonly
+ * @enum {number}
+ */
+ccui.Layout.Type = cc.Enum({
+ /**
+ * The absolute of ccui.Layout's layout type.
+ */
+ ABSOLUTE: 0,
+ /**
+ * The vertical of ccui.Layout's layout type.
+ */
+ LINEAR_VERTICAL: 1,
+ /**
+ * The horizontal of ccui.Layout's layout type.
+ */
+ LINEAR_HORIZONTAL: 2,
+ /**
+ * The relative of ccui.Layout's layout type.
+ */
+ RELATIVE: 3
+});
+
+//Layout clipping type
+/**
+ * The stencil of ccui.Layout's clipping type.
+ * @type {number}
+ * @constant
+ */
+ccui.Layout.CLIPPING_STENCIL = 0;
+/**
+ * The scissor of ccui.Layout's clipping type.
+ * @type {number}
+ * @constant
+ */
+ccui.Layout.CLIPPING_SCISSOR = 1;
+
+/**
+ * The zOrder value of ccui.Layout's image background.
+ * @type {number}
+ * @constant
+ */
+ccui.Layout.BACKGROUND_IMAGE_ZORDER = -1;
+/**
+ * The zOrder value of ccui.Layout's color background.
+ * @type {number}
+ * @constant
+ */
+ccui.Layout.BACKGROUND_RENDERER_ZORDER = -2;
\ No newline at end of file
diff --git a/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js b/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js
new file mode 100644
index 0000000000..df53a60560
--- /dev/null
+++ b/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js
@@ -0,0 +1,179 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+(function(){
+ ccui.Layout.CanvasRenderCmd = function(renderable){
+ ccui.ProtectedNode.CanvasRenderCmd.call(this, renderable);
+ this._needDraw = false;
+
+ this._clipElemType = false;
+ this._locCache = null;
+ this._rendererSaveCmd = new cc.CustomRenderCmd(this, this._onRenderSaveCmd);
+ this._rendererSaveCmdSprite = new cc.CustomRenderCmd(this, this._onRenderSaveSpriteCmd);
+ this._rendererClipCmd = new cc.CustomRenderCmd(this, this._onRenderClipCmd);
+ this._rendererRestoreCmd = new cc.CustomRenderCmd(this, this._onRenderRestoreCmd);
+ };
+
+ var proto = ccui.Layout.CanvasRenderCmd.prototype = Object.create(ccui.ProtectedNode.CanvasRenderCmd.prototype);
+ proto.constructor = ccui.Layout.CanvasRenderCmd;
+
+ proto.visit = function(parentCmd){
+ var node = this._node;
+ if (!node._visible)
+ return;
+ node._adaptRenderers();
+ node._doLayout();
+
+ if (node._clippingEnabled) {
+ switch (node._clippingType) {
+ case ccui.Layout.CLIPPING_STENCIL:
+ this.stencilClippingVisit(parentCmd);
+ break;
+ case ccui.Layout.CLIPPING_SCISSOR:
+ this.scissorClippingVisit(parentCmd);
+ break;
+ default:
+ break;
+ }
+ } else
+ ccui.Widget.CanvasRenderCmd.prototype.visit.call(this, parentCmd);
+ };
+
+ proto._onRenderSaveCmd = function(ctx, scaleX, scaleY){
+ var wrapper = ctx || cc._renderContext, context = wrapper.getContext();
+ if (this._clipElemType) {
+ var canvas = context.canvas;
+ this._locCache = ccui.Layout.CanvasRenderCmd._getSharedCache();
+ this._locCache.width = canvas.width;
+ this._locCache.height = canvas.height;
+ var locCacheCtx = this._locCache.getContext("2d");
+ locCacheCtx.drawImage(canvas, 0, 0);
+ } else {
+ wrapper.save();
+ wrapper.save();
+ wrapper.setTransform(this._worldTransform, scaleX, scaleY);
+ }
+ };
+
+ proto._onRenderSaveSpriteCmd = function(ctx){
+ var wrapper = ctx || cc._renderContext;
+ //var node = this._node;
+ if (this._clipElemType) {
+ wrapper.setCompositeOperation("destination-in");
+ }
+ };
+
+ proto._onRenderClipCmd = function(ctx){
+ var wrapper = ctx || cc._renderContext, context = wrapper.getContext();
+ if (!this._clipElemType) {
+ wrapper.restore();
+ context.clip();
+ }
+ };
+
+ proto._onRenderRestoreCmd = function(ctx){
+ var wrapper = ctx || cc._renderContext, context = wrapper.getContext();
+
+ if (this._clipElemType) {
+ // Redraw the cached canvas, so that the cliped area shows the background etc.
+ context.save();
+ context.setTransform(1, 0, 0, 1, 0, 0);
+ context.globalCompositeOperation = "destination-over";
+ context.drawImage(this._locCache, 0, 0);
+ context.restore();
+ }else{
+ wrapper.restore(); //use for restore clip operation
+ }
+ };
+
+ proto.rebindStencilRendering = function(stencil){
+ stencil._renderCmd.rendering = this.__stencilDraw;
+ };
+
+ proto.__stencilDraw = function(ctx,scaleX, scaleY){ //Only for Canvas
+ var wrapper = ctx || cc._renderContext, locContext = wrapper.getContext(), buffer = this._buffer;
+
+ for (var i = 0, bufLen = buffer.length; i < bufLen; i++) {
+ var element = buffer[i], vertices = element.verts;
+ var firstPoint = vertices[0];
+ locContext.beginPath();
+ locContext.moveTo(firstPoint.x * scaleX, -firstPoint.y * scaleY);
+ for (var j = 1, len = vertices.length; j < len; j++)
+ locContext.lineTo(vertices[j].x * scaleX, -vertices[j].y * scaleY);
+ locContext.closePath();
+ }
+ };
+
+ proto.stencilClippingVisit = proto.scissorClippingVisit = function(parentCmd){
+ var node = this._node;
+ if (!node._clippingStencil || !node._clippingStencil.isVisible())
+ return;
+
+ this._clipElemType = node._stencil instanceof cc.Sprite;
+ this._syncStatus(parentCmd);
+
+ cc.renderer.pushRenderCommand(this._rendererSaveCmd);
+ if (this._clipElemType) {
+ cc.ProtectedNode.prototype.visit.call(node, parentCmd);
+ cc.renderer.pushRenderCommand(this._rendererSaveCmdSprite);
+ }
+ node._clippingStencil.visit(this);
+
+ cc.renderer.pushRenderCommand(this._rendererClipCmd);
+ if (!this._clipElemType) {
+ node.sortAllChildren();
+ node.sortAllProtectedChildren();
+
+ var children = node._children;
+ var j=0, locProtectChildren = node._protectedChildren, i = 0, locChild;
+ var iLen = children.length, jLen = locProtectChildren.length;
+
+ for( ; i < iLen; i++ ){
+ locChild = children[i];
+ if ( locChild && locChild.getLocalZOrder() < 0 )
+ locChild.visit(this);
+ else
+ break;
+ }
+ for( ; j < jLen; j++ ) {
+ locChild = locProtectChildren[j];
+ if ( locChild && locChild.getLocalZOrder() < 0 )
+ locChild.visit(this);
+ else
+ break;
+ }
+ for (; i < iLen; i++)
+ children[i].visit(this);
+ for (; j < jLen; j++)
+ locProtectChildren[j].visit(this);
+ cc.renderer.pushRenderCommand(this._rendererRestoreCmd);
+ }
+ this._dirtyFlag = 0;
+ };
+
+ ccui.Layout.CanvasRenderCmd._getSharedCache = function () {
+ return (cc.ClippingNode._sharedCache) || (cc.ClippingNode._sharedCache = document.createElement("canvas"));
+ };
+})();
\ No newline at end of file
diff --git a/extensions/ccui/layouts/UILayoutComponent.js b/extensions/ccui/layouts/UILayoutComponent.js
new file mode 100644
index 0000000000..6ff48dbfcd
--- /dev/null
+++ b/extensions/ccui/layouts/UILayoutComponent.js
@@ -0,0 +1,594 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+ccui.LayoutComponent_ReferencePoint = {
+ BOTTOM_LEFT: 0,
+ TOP_LEFT: 1,
+ BOTTOM_RIGHT: 2,
+ TOP_RIGHT: 3
+};
+ccui.LayoutComponent_PositionType = {
+ Position: 0,
+ RelativePosition: 1,
+ PreRelativePosition: 2,
+ PreRelativePositionEnable: 3
+};
+ccui.LayoutComponent_SizeType = {
+ Size: 0,
+ PreSize: 1,
+ PreSizeEnable: 2
+};
+
+//refactor since v3.3
+ccui.LayoutComponent = cc._Component.extend({
+ _horizontalEdge: 0,
+ _verticalEdge: 0,
+
+ _leftMargin: 0,
+ _rightMargin: 0,
+ _bottomMargin: 0,
+ _topMargin: 0,
+
+ _usingPositionPercentX: false,
+ _positionPercentX: 0,
+ _usingPositionPercentY: false,
+ _positionPercentY: 0,
+
+ _usingStretchWidth: false,
+ _usingStretchHeight: false,
+
+ _percentWidth: 0,
+ _usingPercentWidth: false,
+
+ _percentHeight: 0,
+ _usingPercentHeight: false,
+
+ _actived: true,
+ _isPercentOnly: false,
+
+ ctor: function () {
+ this._name = ccui.LayoutComponent.NAME;
+ },
+
+ init: function () {
+ var ret = true;
+
+ if (!cc._Component.prototype.init.call(this)) {
+ return false;
+ }
+
+ //put layout component initalized code here
+
+ return ret;
+ },
+
+ getPercentContentSize: function () {
+ return cc.p(this._percentWidth, this._percentHeight);
+ },
+ setPercentContentSize: function (percent) {
+ this.setPercentWidth(percent.x);
+ this.setPercentHeight(percent.y);
+ },
+
+ setUsingPercentContentSize: function (isUsed) {
+ this._usingPercentWidth = this._usingPercentHeight = isUsed;
+ },
+
+ //old
+ SetActiveEnable: function (enable) {
+ this._actived = enable;
+ },
+
+ //v3.3
+ getUsingPercentContentSize: function () {
+ return this._usingPercentWidth && this._usingPercentHeight;
+ },
+
+ //position & margin
+ getAnchorPosition: function () {
+ return this._owner.getAnchorPoint();
+ },
+
+ setAnchorPosition: function (point, y) {
+ var oldRect = this._owner.getBoundingBox();
+ this._owner.setAnchorPoint(point, y);
+ var newRect = this._owner.getBoundingBox();
+ var offSetX = oldRect.x - newRect.x, offSetY = oldRect.y - newRect.y;
+
+ var ownerPosition = this._owner.getPosition();
+ ownerPosition.x += offSetX;
+ ownerPosition.y += offSetY;
+ this.setPosition(ownerPosition);
+ },
+
+ getPosition: function () {
+ return this._owner.getPosition();
+ },
+
+ setPosition: function (position, y) {
+ var parent = this._getOwnerParent(), x;
+ if (parent != null) {
+ if (y === undefined) {
+ x = position.x;
+ y = position.y;
+ } else
+ x = position;
+ var parentSize = parent.getContentSize();
+
+ if (parentSize.width !== 0)
+ this._positionPercentX = x / parentSize.width;
+ else {
+ this._positionPercentX = 0;
+ if (this._usingPositionPercentX)
+ x = 0;
+ }
+
+ if (parentSize.height !== 0)
+ this._positionPercentY = y / parentSize.height;
+ else {
+ this._positionPercentY = 0;
+ if (this._usingPositionPercentY)
+ y = 0;
+ }
+
+ this._owner.setPosition(x, y);
+ this._refreshHorizontalMargin();
+ this._refreshVerticalMargin();
+ } else
+ this._owner.setPosition(position, y);
+ },
+
+ isPositionPercentXEnabled: function () {
+ return this._usingPositionPercentX;
+ },
+ setPositionPercentXEnabled: function (isUsed) {
+ this._usingPositionPercentX = isUsed;
+ if (this._usingPositionPercentX)
+ this._horizontalEdge = ccui.LayoutComponent.horizontalEdge.NONE;
+ },
+
+ getPositionPercentX: function () {
+ return this._positionPercentX;
+ },
+ setPositionPercentX: function (percentMargin) {
+ this._positionPercentX = percentMargin;
+
+ var parent = this._getOwnerParent();
+ if (parent !== null) {
+ this._owner.setPositionX(parent.width * this._positionPercentX);
+ this._refreshHorizontalMargin();
+ }
+ },
+
+ isPositionPercentYEnabled: function () {
+ return this._usingPositionPercentY;
+ },
+ setPositionPercentYEnabled: function (isUsed) {
+ this._usingPositionPercentY = isUsed;
+ if (this._usingPositionPercentY)
+ this._verticalEdge = ccui.LayoutComponent.verticalEdge.NONE;
+ },
+
+ getPositionPercentY: function () {
+ return this._positionPercentY;
+ },
+ setPositionPercentY: function (percentMargin) {
+ this._positionPercentY = percentMargin;
+
+ var parent = this._getOwnerParent();
+ if (parent !== null) {
+ this._owner.setPositionY(parent.height * this._positionPercentY);
+ this._refreshVerticalMargin();
+ }
+ },
+
+ getHorizontalEdge: function () {
+ return this._horizontalEdge;
+ },
+ setHorizontalEdge: function (hEdge) {
+ this._horizontalEdge = hEdge;
+ if (this._horizontalEdge !== ccui.LayoutComponent.horizontalEdge.NONE)
+ this._usingPositionPercentX = false;
+
+ var parent = this._getOwnerParent();
+ if (parent !== null) {
+ var ownerPoint = this._owner.getPosition();
+ var parentSize = parent.getContentSize();
+ if (parentSize.width !== 0)
+ this._positionPercentX = ownerPoint.x / parentSize.width;
+ else {
+ this._positionPercentX = 0;
+ ownerPoint.x = 0;
+ if (this._usingPositionPercentX)
+ this._owner.setPosition(ownerPoint);
+ }
+ this._refreshHorizontalMargin();
+ }
+ },
+
+ getVerticalEdge: function () {
+ return this._verticalEdge;
+ },
+ setVerticalEdge: function (vEdge) {
+ this._verticalEdge = vEdge;
+ if (this._verticalEdge !== ccui.LayoutComponent.verticalEdge.NONE)
+ this._usingPositionPercentY = false;
+
+ var parent = this._getOwnerParent();
+ if (parent !== null) {
+ var ownerPoint = this._owner.getPosition();
+ var parentSize = parent.getContentSize();
+ if (parentSize.height !== 0)
+ this._positionPercentY = ownerPoint.y / parentSize.height;
+ else {
+ this._positionPercentY = 0;
+ ownerPoint.y = 0;
+ if (this._usingPositionPercentY)
+ this._owner.setPosition(ownerPoint);
+ }
+ this._refreshVerticalMargin();
+ }
+ },
+
+ getLeftMargin: function () {
+ return this._leftMargin;
+ },
+ setLeftMargin: function (margin) {
+ this._leftMargin = margin;
+ },
+
+ getRightMargin: function () {
+ return this._rightMargin;
+ },
+ setRightMargin: function (margin) {
+ this._rightMargin = margin;
+ },
+
+ getTopMargin: function () {
+ return this._topMargin;
+ },
+ setTopMargin: function (margin) {
+ this._topMargin = margin;
+ },
+
+ getBottomMargin: function () {
+ return this._bottomMargin;
+ },
+ setBottomMargin: function (margin) {
+ this._bottomMargin = margin;
+ },
+
+ //size &
+ getSize: function () {
+ return this.getOwner().getContentSize();
+ },
+ setSize: function (size) {
+ var parent = this._getOwnerParent();
+ if (parent !== null) {
+ var ownerSize = size, parentSize = parent.getContentSize();
+
+ if (parentSize.width !== 0)
+ this._percentWidth = ownerSize.width / parentSize.width;
+ else {
+ this._percentWidth = 0;
+ if (this._usingPercentWidth)
+ ownerSize.width = 0;
+ }
+
+ if (parentSize.height !== 0)
+ this._percentHeight = ownerSize.height / parentSize.height;
+ else {
+ this._percentHeight = 0;
+ if (this._usingPercentHeight)
+ ownerSize.height = 0;
+ }
+
+ this._owner.setContentSize(ownerSize);
+
+ this._refreshHorizontalMargin();
+ this._refreshVerticalMargin();
+ }
+ else
+ this._owner.setContentSize(size);
+ },
+
+ isPercentWidthEnabled: function () {
+ return this._usingPercentWidth;
+ },
+ setPercentWidthEnabled: function (isUsed) {
+ this._usingPercentWidth = isUsed;
+ if (this._usingPercentWidth)
+ this._usingStretchWidth = false;
+ },
+
+ getSizeWidth: function () {
+ return this._owner.width;
+ },
+ setSizeWidth: function (width) {
+ var ownerSize = this._owner.getContentSize();
+ ownerSize.width = width;
+
+ var parent = this._getOwnerParent();
+ if (parent !== null) {
+ var parentSize = parent.getContentSize();
+ if (parentSize.width !== 0)
+ this._percentWidth = ownerSize.width / parentSize.width;
+ else {
+ this._percentWidth = 0;
+ if (this._usingPercentWidth)
+ ownerSize.width = 0;
+ }
+ this._owner.setContentSize(ownerSize);
+ this._refreshHorizontalMargin();
+ } else
+ this._owner.setContentSize(ownerSize);
+ },
+
+ getPercentWidth: function () {
+ return this._percentWidth;
+ },
+ setPercentWidth: function (percentWidth) {
+ this._percentWidth = percentWidth;
+
+ var parent = this._getOwnerParent();
+ if (parent !== null) {
+ var ownerSize = this._owner.getContentSize();
+ ownerSize.width = parent.width * this._percentWidth;
+ this._owner.setContentSize(ownerSize);
+ this._refreshHorizontalMargin();
+ }
+ },
+
+ isPercentHeightEnabled: function () {
+ return this._usingPercentHeight;
+ },
+ setPercentHeightEnabled: function (isUsed) {
+ this._usingPercentHeight = isUsed;
+ if (this._usingPercentHeight)
+ this._usingStretchHeight = false;
+ },
+
+ getSizeHeight: function () {
+ return this._owner.height;
+ },
+ setSizeHeight: function (height) {
+ var ownerSize = this._owner.getContentSize();
+ ownerSize.height = height;
+
+ var parent = this._getOwnerParent();
+ if (parent !== null) {
+ var parentSize = parent.getContentSize();
+ if (parentSize.height !== 0)
+ this._percentHeight = ownerSize.height / parentSize.height;
+ else {
+ this._percentHeight = 0;
+ if (this._usingPercentHeight)
+ ownerSize.height = 0;
+ }
+ this._owner.setContentSize(ownerSize);
+ this._refreshVerticalMargin();
+ }
+ else
+ this._owner.setContentSize(ownerSize);
+ },
+
+ getPercentHeight: function () {
+ return this._percentHeight;
+ },
+ setPercentHeight: function (percentHeight) {
+ this._percentHeight = percentHeight;
+
+ var parent = this._getOwnerParent();
+ if (parent !== null) {
+ var ownerSize = this._owner.getContentSize();
+ ownerSize.height = parent.height * this._percentHeight;
+ this._owner.setContentSize(ownerSize);
+ this._refreshVerticalMargin();
+ }
+ },
+
+ isStretchWidthEnabled: function () {
+ return this._usingStretchWidth;
+ },
+ setStretchWidthEnabled: function (isUsed) {
+ this._usingStretchWidth = isUsed;
+ if (this._usingStretchWidth)
+ this._usingPercentWidth = false;
+ },
+
+ isStretchHeightEnabled: function () {
+ return this._usingStretchHeight;
+ },
+ setStretchHeightEnabled: function (isUsed) {
+ this._usingStretchHeight = isUsed;
+ if (this._usingStretchHeight)
+ this._usingPercentHeight = false;
+ },
+
+ setPercentOnlyEnabled: function(enable){
+ this._isPercentOnly = enable;
+ },
+
+ setActiveEnabled: function (enable) {
+ this._actived = enable;
+ },
+ refreshLayout: function () {
+ if(!this._actived)
+ return;
+
+ var parent = this._getOwnerParent();
+ if (parent === null)
+ return;
+
+ var parentSize = parent.getContentSize(), locOwner = this._owner;
+ var ownerAnchor = locOwner.getAnchorPoint(), ownerSize = locOwner.getContentSize();
+ var ownerPosition = locOwner.getPosition();
+
+ switch (this._horizontalEdge) {
+ case ccui.LayoutComponent.horizontalEdge.NONE:
+ if (this._usingStretchWidth && !this._isPercentOnly) {
+ ownerSize.width = parentSize.width * this._percentWidth;
+ ownerPosition.x = this._leftMargin + ownerAnchor.x * ownerSize.width;
+ } else {
+ if (this._usingPositionPercentX)
+ ownerPosition.x = parentSize.width * this._positionPercentX;
+ if (this._usingPercentWidth)
+ ownerSize.width = parentSize.width * this._percentWidth;
+ }
+ break;
+ case ccui.LayoutComponent.horizontalEdge.LEFT:
+ if(this._isPercentOnly)
+ break;
+ if (this._usingPercentWidth || this._usingStretchWidth)
+ ownerSize.width = parentSize.width * this._percentWidth;
+ ownerPosition.x = this._leftMargin + ownerAnchor.x * ownerSize.width;
+ break;
+ case ccui.LayoutComponent.horizontalEdge.RIGHT:
+ if(this._isPercentOnly)
+ break;
+ if (this._usingPercentWidth || this._usingStretchWidth)
+ ownerSize.width = parentSize.width * this._percentWidth;
+ ownerPosition.x = parentSize.width - (this._rightMargin + (1 - ownerAnchor.x) * ownerSize.width);
+ break;
+ case ccui.LayoutComponent.horizontalEdge.CENTER:
+ if(this._isPercentOnly)
+ break;
+ if (this._usingStretchWidth) {
+ ownerSize.width = parentSize.width - this._leftMargin - this._rightMargin;
+ if (ownerSize.width < 0)
+ ownerSize.width = 0;
+ ownerPosition.x = this._leftMargin + ownerAnchor.x * ownerSize.width;
+ } else {
+ if (this._usingPercentWidth)
+ ownerSize.width = parentSize.width * this._percentWidth;
+ ownerPosition.x = parentSize.width * this._positionPercentX;
+ }
+ break;
+ default:
+ break;
+ }
+
+ switch (this._verticalEdge) {
+ case ccui.LayoutComponent.verticalEdge.NONE:
+ if (this._usingStretchHeight && !this._isPercentOnly) {
+ ownerSize.height = parentSize.height * this._percentHeight;
+ ownerPosition.y = this._bottomMargin + ownerAnchor.y * ownerSize.height;
+ } else {
+ if (this._usingPositionPercentY)
+ ownerPosition.y = parentSize.height * this._positionPercentY;
+ if (this._usingPercentHeight)
+ ownerSize.height = parentSize.height * this._percentHeight;
+ }
+ break;
+ case ccui.LayoutComponent.verticalEdge.BOTTOM:
+ if(this._isPercentOnly)
+ break;
+ if (this._usingPercentHeight || this._usingStretchHeight)
+ ownerSize.height = parentSize.height * this._percentHeight;
+ ownerPosition.y = this._bottomMargin + ownerAnchor.y * ownerSize.height;
+ break;
+ case ccui.LayoutComponent.verticalEdge.TOP:
+ if(this._isPercentOnly)
+ break;
+ if (this._usingPercentHeight || this._usingStretchHeight)
+ ownerSize.height = parentSize.height * this._percentHeight;
+ ownerPosition.y = parentSize.height - (this._topMargin + (1 - ownerAnchor.y) * ownerSize.height);
+ break;
+ case ccui.LayoutComponent.verticalEdge.CENTER:
+ if(this._isPercentOnly)
+ break;
+ if (this._usingStretchHeight) {
+ ownerSize.height = parentSize.height - this._topMargin - this._bottomMargin;
+ if (ownerSize.height < 0)
+ ownerSize.height = 0;
+ ownerPosition.y = this._bottomMargin + ownerAnchor.y * ownerSize.height;
+ } else {
+ if(this._usingPercentHeight)
+ ownerSize.height = parentSize.height * this._percentHeight;
+ ownerPosition.y = parentSize.height * this._positionPercentY;
+ }
+ break;
+ default:
+ break;
+ }
+
+ locOwner.setPosition(ownerPosition);
+ locOwner.setContentSize(ownerSize);
+
+ if(locOwner instanceof ccui.PageView){
+ locOwner.forceDoLayout();
+
+ var layoutVector = locOwner.getPages();
+ for(var i=0; i 0) {
+ for (var i = 0, len = locChildren.length; i < len; i++) {
+ this._widget = locChildren[i];
+
+ var layoutParameter = this._widget.getLayoutParameter();
+ if (layoutParameter){
+ if (layoutParameter._put)
+ continue;
+
+ var ret = this._calculateFinalPositionWithRelativeWidget(layout);
+ if (!ret)
+ continue;
+
+ this._calculateFinalPositionWithRelativeAlign();
+
+ this._widget.setPosition(this._finalPositionX, this._finalPositionY);
+ layoutParameter._put = true;
+ }
+ }
+ this._unlayoutChildCount--;
+ }
+ this._widgetChildren.length = 0;
+ },
+
+ _getAllWidgets: function(layout){
+ var container = layout._getLayoutElements();
+ var locWidgetChildren = this._widgetChildren;
+ locWidgetChildren.length = 0;
+ for (var i = 0, len = container.length; i < len; i++){
+ var child = container[i];
+ if (child) {
+ var layoutParameter = child.getLayoutParameter();
+ layoutParameter._put = false;
+ this._unlayoutChildCount++;
+ locWidgetChildren.push(child);
+ }
+ }
+ return locWidgetChildren;
+ },
+
+ _getRelativeWidget: function(widget){
+ var relativeWidget = null;
+ var layoutParameter = widget.getLayoutParameter();
+ var relativeName = layoutParameter.getRelativeToWidgetName();
+
+ if (relativeName && relativeName.length !== 0) {
+ var locChildren = this._widgetChildren;
+ for(var i = 0, len = locChildren.length; i < len; i++){
+ var child = locChildren[i];
+ if (child){
+ var rlayoutParameter = child.getLayoutParameter();
+ if (rlayoutParameter && rlayoutParameter.getRelativeName() === relativeName) {
+ relativeWidget = child;
+ this._relativeWidgetLP = rlayoutParameter;
+ break;
+ }
+ }
+ }
+ }
+ return relativeWidget;
+ },
+
+ _calculateFinalPositionWithRelativeWidget: function(layout){
+ var locWidget = this._widget;
+ var ap = locWidget.getAnchorPoint();
+ var cs = locWidget.getContentSize();
+
+ this._finalPositionX = 0.0;
+ this._finalPositionY = 0.0;
+
+ var relativeWidget = this._getRelativeWidget(locWidget);
+ var layoutParameter = locWidget.getLayoutParameter();
+ var align = layoutParameter.getAlign();
+ var layoutSize = layout._getLayoutContentSize();
+
+ switch (align) {
+ case ccui.RelativeLayoutParameter.Type.NONE:
+ case ccui.RelativeLayoutParameter.Type.PARENT_TOP_LEFT:
+ this._finalPositionX = ap.x * cs.width;
+ this._finalPositionY = layoutSize.height - ((1.0 - ap.y) * cs.height);
+ break;
+ case ccui.RelativeLayoutParameter.Type.PARENT_TOP_CENTER_HORIZONTAL:
+ this._finalPositionX = layoutSize.width * 0.5 - cs.width * (0.5 - ap.x);
+ this._finalPositionY = layoutSize.height - ((1.0 - ap.y) * cs.height);
+ break;
+ case ccui.RelativeLayoutParameter.Type.PARENT_TOP_RIGHT:
+ this._finalPositionX = layoutSize.width - ((1.0 - ap.x) * cs.width);
+ this._finalPositionY = layoutSize.height - ((1.0 - ap.y) * cs.height);
+ break;
+ case ccui.RelativeLayoutParameter.Type.PARENT_LEFT_CENTER_VERTICAL:
+ this._finalPositionX = ap.x * cs.width;
+ this._finalPositionY = layoutSize.height * 0.5 - cs.height * (0.5 - ap.y);
+ break;
+ case ccui.RelativeLayoutParameter.Type.CENTER_IN_PARENT:
+ this._finalPositionX = layoutSize.width * 0.5 - cs.width * (0.5 - ap.x);
+ this._finalPositionY = layoutSize.height * 0.5 - cs.height * (0.5 - ap.y);
+ break;
+ case ccui.RelativeLayoutParameter.Type.PARENT_RIGHT_CENTER_VERTICAL:
+ this._finalPositionX = layoutSize.width - ((1.0 - ap.x) * cs.width);
+ this._finalPositionY = layoutSize.height * 0.5 - cs.height * (0.5 - ap.y);
+ break;
+ case ccui.RelativeLayoutParameter.Type.PARENT_LEFT_BOTTOM:
+ this._finalPositionX = ap.x * cs.width;
+ this._finalPositionY = ap.y * cs.height;
+ break;
+ case ccui.RelativeLayoutParameter.Type.PARENT_BOTTOM_CENTER_HORIZONTAL:
+ this._finalPositionX = layoutSize.width * 0.5 - cs.width * (0.5 - ap.x);
+ this._finalPositionY = ap.y * cs.height;
+ break;
+ case ccui.RelativeLayoutParameter.Type.PARENT_RIGHT_BOTTOM:
+ this._finalPositionX = layoutSize.width - ((1.0 - ap.x) * cs.width);
+ this._finalPositionY = ap.y * cs.height;
+ break;
+
+ case ccui.RelativeLayoutParameter.Type.LOCATION_ABOVE_LEFTALIGN:
+ if (relativeWidget){
+ if (this._relativeWidgetLP && !this._relativeWidgetLP._put)
+ return false;
+ this._finalPositionY = relativeWidget.getTopBoundary() + ap.y * cs.height;
+ this._finalPositionX = relativeWidget.getLeftBoundary() + ap.x * cs.width;
+ }
+ break;
+ case ccui.RelativeLayoutParameter.Type.LOCATION_ABOVE_CENTER:
+ if (relativeWidget){
+ if (this._relativeWidgetLP && !this._relativeWidgetLP._put)
+ return false;
+ var rbs = relativeWidget.getContentSize();
+ this._finalPositionY = relativeWidget.getTopBoundary() + ap.y * cs.height;
+ this._finalPositionX = relativeWidget.getLeftBoundary() + rbs.width * 0.5 + ap.x * cs.width - cs.width * 0.5;
+ }
+ break;
+ case ccui.RelativeLayoutParameter.Type.LOCATION_ABOVE_RIGHTALIGN:
+ if (relativeWidget) {
+ if (this._relativeWidgetLP && !this._relativeWidgetLP._put)
+ return false;
+ this._finalPositionY = relativeWidget.getTopBoundary() + ap.y * cs.height;
+ this._finalPositionX = relativeWidget.getRightBoundary() - (1.0 - ap.x) * cs.width;
+ }
+ break;
+ case ccui.RelativeLayoutParameter.Type.LOCATION_LEFT_OF_TOPALIGN:
+ if (relativeWidget){
+ if (this._relativeWidgetLP && !this._relativeWidgetLP._put)
+ return false;
+ this._finalPositionY = relativeWidget.getTopBoundary() - (1.0 - ap.y) * cs.height;
+ this._finalPositionX = relativeWidget.getLeftBoundary() - (1.0 - ap.x) * cs.width;
+ }
+ break;
+ case ccui.RelativeLayoutParameter.Type.LOCATION_LEFT_OF_CENTER:
+ if (relativeWidget) {
+ if (this._relativeWidgetLP && !this._relativeWidgetLP._put)
+ return false;
+ var rbs = relativeWidget.getContentSize();
+ this._finalPositionX = relativeWidget.getLeftBoundary() - (1.0 - ap.x) * cs.width;
+ this._finalPositionY = relativeWidget.getBottomBoundary() + rbs.height * 0.5 + ap.y * cs.height - cs.height * 0.5;
+ }
+ break;
+ case ccui.RelativeLayoutParameter.Type.LOCATION_LEFT_OF_BOTTOMALIGN:
+ if (relativeWidget) {
+ if (this._relativeWidgetLP && !this._relativeWidgetLP._put)
+ return false;
+ this._finalPositionY = relativeWidget.getBottomBoundary() + ap.y * cs.height;
+ this._finalPositionX = relativeWidget.getLeftBoundary() - (1.0 - ap.x) * cs.width;
+ }
+ break;
+ case ccui.RelativeLayoutParameter.Type.LOCATION_RIGHT_OF_TOPALIGN:
+ if (relativeWidget){
+ if (this._relativeWidgetLP && !this._relativeWidgetLP._put)
+ return false;
+ this._finalPositionY = relativeWidget.getTopBoundary() - (1.0 - ap.y) * cs.height;
+ this._finalPositionX = relativeWidget.getRightBoundary() + ap.x * cs.width;
+ }
+ break;
+ case ccui.RelativeLayoutParameter.Type.LOCATION_RIGHT_OF_CENTER:
+ if (relativeWidget){
+ if (this._relativeWidgetLP && !this._relativeWidgetLP._put)
+ return false;
+ var rbs = relativeWidget.getContentSize();
+ var locationRight = relativeWidget.getRightBoundary();
+ this._finalPositionX = locationRight + ap.x * cs.width;
+ this._finalPositionY = relativeWidget.getBottomBoundary() + rbs.height * 0.5 + ap.y * cs.height - cs.height * 0.5;
+ }
+ break;
+ case ccui.RelativeLayoutParameter.Type.LOCATION_RIGHT_OF_BOTTOMALIGN:
+ if (relativeWidget){
+ if (this._relativeWidgetLP && !this._relativeWidgetLP._put)
+ return false;
+ this._finalPositionY = relativeWidget.getBottomBoundary() + ap.y * cs.height;
+ this._finalPositionX = relativeWidget.getRightBoundary() + ap.x * cs.width;
+ }
+ break;
+ case ccui.RelativeLayoutParameter.Type.LOCATION_BELOW_LEFTALIGN:
+ if (relativeWidget){
+ if (this._relativeWidgetLP && !this._relativeWidgetLP._put)
+ return false;
+ this._finalPositionY = relativeWidget.getBottomBoundary() - (1.0 - ap.y) * cs.height;
+ this._finalPositionX = relativeWidget.getLeftBoundary() + ap.x * cs.width;
+ }
+ break;
+ case ccui.RelativeLayoutParameter.Type.LOCATION_BELOW_CENTER:
+ if (relativeWidget) {
+ if (this._relativeWidgetLP && !this._relativeWidgetLP._put)
+ return false;
+ var rbs = relativeWidget.getContentSize();
+ this._finalPositionY = relativeWidget.getBottomBoundary() - (1.0 - ap.y) * cs.height;
+ this._finalPositionX = relativeWidget.getLeftBoundary() + rbs.width * 0.5 + ap.x * cs.width - cs.width * 0.5;
+ }
+ break;
+ case ccui.RelativeLayoutParameter.Type.LOCATION_BELOW_RIGHTALIGN:
+ if (relativeWidget) {
+ if (this._relativeWidgetLP && !this._relativeWidgetLP._put)
+ return false;
+ this._finalPositionY = relativeWidget.getBottomBoundary() - (1.0 - ap.y) * cs.height;
+ this._finalPositionX = relativeWidget.getRightBoundary() - (1.0 - ap.x) * cs.width;
+ }
+ break;
+ default:
+ break;
+ }
+ return true;
+ },
+
+ _calculateFinalPositionWithRelativeAlign: function(){
+ var layoutParameter = this._widget.getLayoutParameter();
+
+ var mg = layoutParameter.getMargin();
+ var align = layoutParameter.getAlign();
+
+ //handle margin
+ switch (align) {
+ case ccui.RelativeLayoutParameter.Type.NONE:
+ case ccui.RelativeLayoutParameter.Type.PARENT_TOP_LEFT:
+ this._finalPositionX += mg.left;
+ this._finalPositionY -= mg.top;
+ break;
+ case ccui.RelativeLayoutParameter.Type.PARENT_TOP_CENTER_HORIZONTAL:
+ this._finalPositionY -= mg.top;
+ break;
+ case ccui.RelativeLayoutParameter.Type.PARENT_TOP_RIGHT:
+ this._finalPositionX -= mg.right;
+ this._finalPositionY -= mg.top;
+ break;
+ case ccui.RelativeLayoutParameter.Type.PARENT_LEFT_CENTER_VERTICAL:
+ this._finalPositionX += mg.left;
+ break;
+ case ccui.RelativeLayoutParameter.Type.CENTER_IN_PARENT:
+ break;
+ case ccui.RelativeLayoutParameter.Type.PARENT_RIGHT_CENTER_VERTICAL:
+ this._finalPositionX -= mg.right;
+ break;
+ case ccui.RelativeLayoutParameter.Type.PARENT_LEFT_BOTTOM:
+ this._finalPositionX += mg.left;
+ this._finalPositionY += mg.bottom;
+ break;
+ case ccui.RelativeLayoutParameter.Type.PARENT_BOTTOM_CENTER_HORIZONTAL:
+ this._finalPositionY += mg.bottom;
+ break;
+ case ccui.RelativeLayoutParameter.Type.PARENT_RIGHT_BOTTOM:
+ this._finalPositionX -= mg.right;
+ this._finalPositionY += mg.bottom;
+ break;
+ case ccui.RelativeLayoutParameter.Type.LOCATION_ABOVE_LEFTALIGN:
+ this._finalPositionY += mg.bottom;
+ this._finalPositionX += mg.left;
+ break;
+ case ccui.RelativeLayoutParameter.Type.LOCATION_ABOVE_RIGHTALIGN:
+ this._finalPositionY += mg.bottom;
+ this._finalPositionX -= mg.right;
+ break;
+ case ccui.RelativeLayoutParameter.Type.LOCATION_ABOVE_CENTER:
+ this._finalPositionY += mg.bottom;
+ break;
+ case ccui.RelativeLayoutParameter.Type.LOCATION_LEFT_OF_TOPALIGN:
+ this._finalPositionX -= mg.right;
+ this._finalPositionY -= mg.top;
+ break;
+ case ccui.RelativeLayoutParameter.Type.LOCATION_LEFT_OF_BOTTOMALIGN:
+ this._finalPositionX -= mg.right;
+ this._finalPositionY += mg.bottom;
+ break;
+ case ccui.RelativeLayoutParameter.Type.LOCATION_LEFT_OF_CENTER:
+ this._finalPositionX -= mg.right;
+ break;
+ case ccui.RelativeLayoutParameter.Type.LOCATION_RIGHT_OF_TOPALIGN:
+ this._finalPositionX += mg.left;
+ this._finalPositionY -= mg.top;
+ break;
+ case ccui.RelativeLayoutParameter.Type.LOCATION_RIGHT_OF_BOTTOMALIGN:
+ this._finalPositionX += mg.left;
+ this._finalPositionY += mg.bottom;
+ break;
+ case ccui.RelativeLayoutParameter.Type.LOCATION_RIGHT_OF_CENTER:
+ this._finalPositionX += mg.left;
+ break;
+ case ccui.RelativeLayoutParameter.Type.LOCATION_BELOW_LEFTALIGN:
+ this._finalPositionY -= mg.top;
+ this._finalPositionX += mg.left;
+ break;
+ case ccui.RelativeLayoutParameter.Type.LOCATION_BELOW_RIGHTALIGN:
+ this._finalPositionY -= mg.top;
+ this._finalPositionX -= mg.right;
+ break;
+ case ccui.RelativeLayoutParameter.Type.LOCATION_BELOW_CENTER:
+ this._finalPositionY -= mg.top;
+ break;
+ default:
+ break;
+ }
+ }
+};
\ No newline at end of file
diff --git a/extensions/ccui/layouts/UILayoutParameter.js b/extensions/ccui/layouts/UILayoutParameter.js
new file mode 100644
index 0000000000..e66580f958
--- /dev/null
+++ b/extensions/ccui/layouts/UILayoutParameter.js
@@ -0,0 +1,539 @@
+/****************************************************************************
+ 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 ccui.Margin
+ * @class
+ * @extends ccui.Class
+ *
+ * @property {Number} left - Left of margin
+ * @property {Number} top - Top of margin
+ * @property {Number} right - right of margin
+ * @property {Number} bottom - bottom of margin
+ */
+ccui.Margin = ccui.Class.extend(/** @lends ccui.Margin# */{
+ left: 0,
+ top: 0,
+ right: 0,
+ bottom: 0,
+ /**
+ * Constructor of ccui.Margin.
+ * @param {Number|ccui.Margin} margin a margin or left
+ * @param {Number} [top]
+ * @param {Number} [right]
+ * @param {Number} [bottom]
+ */
+ ctor: function (margin, top, right, bottom) {
+ if (margin !== undefined && top === undefined) {
+ this.left = margin.left;
+ this.top = margin.top;
+ this.right = margin.right;
+ this.bottom = margin.bottom;
+ }
+ if (bottom !== undefined) {
+ this.left = margin;
+ this.top = top;
+ this.right = right;
+ this.bottom = bottom;
+ }
+ },
+ /**
+ * Sets boundary of margin
+ * @param {Number} l left
+ * @param {Number} t top
+ * @param {Number} r right
+ * @param {Number} b bottom
+ */
+ setMargin: function (l, t, r, b) {
+ this.left = l;
+ this.top = t;
+ this.right = r;
+ this.bottom = b;
+ },
+ /**
+ * Checks target whether equals itself.
+ * @param {ccui.Margin} target
+ * @returns {boolean}
+ */
+ equals: function (target) {
+ return (this.left === target.left && this.top === target.top && this.right === target.right && this.bottom === target.bottom);
+ }
+});
+
+/**
+ * Gets a zero margin object
+ * @function
+ * @returns {ccui.Margin}
+ */
+ccui.MarginZero = function(){
+ return new ccui.Margin(0,0,0,0);
+};
+
+/**
+ * Layout parameter contains a margin and layout parameter type. It uses for ccui.LayoutManager.
+ * @class
+ * @extends ccui.Class
+ */
+ccui.LayoutParameter = ccui.Class.extend(/** @lends ccui.LayoutParameter# */{
+ _margin: null,
+ _layoutParameterType: null,
+
+ /**
+ * The constructor of ccui.LayoutParameter.
+ * @function
+ */
+ ctor: function () {
+ this._margin = new ccui.Margin();
+ this._layoutParameterType = ccui.LayoutParameter.NONE;
+ },
+
+ /**
+ * Sets Margin to LayoutParameter.
+ * @param {ccui.Margin} margin
+ */
+ setMargin: function (margin) {
+ if(cc.js.isObject(margin)){
+ this._margin.left = margin.left;
+ this._margin.top = margin.top;
+ this._margin.right = margin.right;
+ this._margin.bottom = margin.bottom;
+ }else{
+ this._margin.left = arguments[0];
+ this._margin.top = arguments[1];
+ this._margin.right = arguments[2];
+ this._margin.bottom = arguments[3];
+ }
+ },
+
+ /**
+ * Gets Margin of LayoutParameter.
+ * @returns {ccui.Margin}
+ */
+ getMargin: function () {
+ return this._margin;
+ },
+
+ /**
+ * Gets LayoutParameterType of LayoutParameter.
+ * @returns {Number}
+ */
+ getLayoutType: function () {
+ return this._layoutParameterType;
+ },
+
+ /**
+ * Clones a ccui.LayoutParameter object from itself.
+ * @returns {ccui.LayoutParameter}
+ */
+ clone:function(){
+ var parameter = this._createCloneInstance();
+ parameter._copyProperties(this);
+ return parameter;
+ },
+
+ /**
+ * create clone instance.
+ * @returns {ccui.LayoutParameter}
+ */
+ _createCloneInstance:function(){
+ return new ccui.LayoutParameter();
+ },
+
+ /**
+ * copy properties from model.
+ * @param {ccui.LayoutParameter} model
+ */
+ _copyProperties:function(model){
+ this._margin.bottom = model._margin.bottom;
+ this._margin.left = model._margin.left;
+ this._margin.right = model._margin.right;
+ this._margin.top = model._margin.top;
+ }
+});
+
+/**
+ * allocates and initializes a LayoutParameter.
+ * @constructs
+ * @return {ccui.LayoutParameter}
+ */
+ccui.LayoutParameter.create = function () {
+ return new ccui.LayoutParameter();
+};
+
+// Constants
+//layout parameter type
+/**
+ * The none of ccui.LayoutParameter's type.
+ * @constant
+ * @type {number}
+ */
+ccui.LayoutParameter.NONE = 0;
+/**
+ * The linear of ccui.LayoutParameter's type.
+ * @constant
+ * @type {number}
+ */
+ccui.LayoutParameter.LINEAR = 1;
+/**
+ * The relative of ccui.LayoutParameter's type.
+ * @constant
+ * @type {number}
+ */
+ccui.LayoutParameter.RELATIVE = 2;
+
+/**
+ * The linear of Layout parameter. its parameter type is ccui.LayoutParameter.LINEAR.
+ * @class
+ * @extends ccui.LayoutParameter
+ */
+ccui.LinearLayoutParameter = ccui.LayoutParameter.extend(/** @lends ccui.LinearLayoutParameter# */{
+ _linearGravity: null,
+ /**
+ * The constructor of ccui.LinearLayoutParameter.
+ * @function
+ */
+ ctor: function () {
+ ccui.LayoutParameter.prototype.ctor.call(this);
+ this._linearGravity = ccui.LinearLayoutParameter.NONE;
+ this._layoutParameterType = ccui.LayoutParameter.LINEAR;
+ },
+
+ /**
+ * Sets LinearGravity to LayoutParameter.
+ * @param {Number} gravity
+ */
+ setGravity: function (gravity) {
+ this._linearGravity = gravity;
+ },
+
+ /**
+ * Gets LinearGravity of LayoutParameter.
+ * @returns {Number}
+ */
+ getGravity: function () {
+ return this._linearGravity;
+ },
+
+ _createCloneInstance: function () {
+ return new ccui.LinearLayoutParameter();
+ },
+
+ _copyProperties: function (model) {
+ ccui.LayoutParameter.prototype._copyProperties.call(this, model);
+ if (model instanceof ccui.LinearLayoutParameter)
+ this.setGravity(model._linearGravity);
+ }
+});
+
+/**
+ * allocates and initializes a LinearLayoutParameter.
+ * @constructs
+ * @return {ccui.LinearLayoutParameter}
+ * @deprecated since v3.0, please use new construction instead
+ */
+ccui.LinearLayoutParameter.create = function () {
+ return new ccui.LinearLayoutParameter();
+};
+
+// Constants
+//Linear layout parameter LinearGravity
+/**
+ * The none of ccui.LinearLayoutParameter's linear gravity.
+ * @constant
+ * @type {number}
+ */
+ccui.LinearLayoutParameter.NONE = 0;
+
+/**
+ * The left of ccui.LinearLayoutParameter's linear gravity.
+ * @constant
+ * @type {number}
+ */
+ccui.LinearLayoutParameter.LEFT = 1;
+/**
+ * The top of ccui.LinearLayoutParameter's linear gravity.
+ * @constant
+ * @type {number}
+ */
+ccui.LinearLayoutParameter.TOP = 2;
+/**
+ * The right of ccui.LinearLayoutParameter's linear gravity.
+ * @constant
+ * @type {number}
+ */
+ccui.LinearLayoutParameter.RIGHT = 3;
+/**
+ * The bottom of ccui.LinearLayoutParameter's linear gravity.
+ * @constant
+ * @type {number}
+ */
+ccui.LinearLayoutParameter.BOTTOM = 4;
+/**
+ * The center vertical of ccui.LinearLayoutParameter's linear gravity.
+ * @constant
+ * @type {number}
+ */
+ccui.LinearLayoutParameter.CENTER_VERTICAL = 5;
+/**
+ * The center horizontal of ccui.LinearLayoutParameter's linear gravity.
+ * @constant
+ * @type {number}
+ */
+ccui.LinearLayoutParameter.CENTER_HORIZONTAL = 6;
+
+/**
+ * The relative of layout parameter. Its layout parameter type is ccui.LayoutParameter.RELATIVE.
+ * @class
+ * @extends ccui.LayoutParameter
+ */
+ccui.RelativeLayoutParameter = ccui.LayoutParameter.extend(/** @lends ccui.RelativeLayoutParameter# */{
+ _relativeAlign: null,
+ _relativeWidgetName: "",
+ _relativeLayoutName: "",
+ _put:false,
+ /**
+ * The constructor of ccui.RelativeLayoutParameter
+ * @function
+ */
+ ctor: function () {
+ ccui.LayoutParameter.prototype.ctor.call(this);
+ this._relativeAlign = ccui.RelativeLayoutParameter.Type.NONE;
+ this._relativeWidgetName = "";
+ this._relativeLayoutName = "";
+ this._put = false;
+ this._layoutParameterType = ccui.LayoutParameter.RELATIVE;
+ },
+
+ /**
+ * Sets RelativeAlign parameter for LayoutParameter.
+ * @param {Number} align
+ */
+ setAlign: function (align) {
+ this._relativeAlign = align;
+ },
+
+ /**
+ * Gets RelativeAlign parameter for LayoutParameter.
+ * @returns {Number}
+ */
+ getAlign: function () {
+ return this._relativeAlign;
+ },
+
+ /**
+ * Sets a key for LayoutParameter. Witch widget named this is relative to.
+ * @param {String} name
+ */
+ setRelativeToWidgetName: function (name) {
+ this._relativeWidgetName = name;
+ },
+
+ /**
+ * Gets the key of LayoutParameter. Witch widget named this is relative to.
+ * @returns {string}
+ */
+ getRelativeToWidgetName: function () {
+ return this._relativeWidgetName;
+ },
+
+ /**
+ * Sets a name in Relative Layout for LayoutParameter.
+ * @param {String} name
+ */
+ setRelativeName: function (name) {
+ this._relativeLayoutName = name;
+ },
+
+ /**
+ * Gets a name in Relative Layout of LayoutParameter.
+ * @returns {string}
+ */
+ getRelativeName: function () {
+ return this._relativeLayoutName;
+ },
+
+ _createCloneInstance:function(){
+ return new ccui.RelativeLayoutParameter();
+ },
+
+ _copyProperties:function(model){
+ ccui.LayoutParameter.prototype._copyProperties.call(this, model);
+ if (model instanceof ccui.RelativeLayoutParameter) {
+ this.setAlign(model._relativeAlign);
+ this.setRelativeToWidgetName(model._relativeWidgetName);
+ this.setRelativeName(model._relativeLayoutName);
+ }
+ }
+});
+
+/**
+ * Allocates and initializes a RelativeLayoutParameter.
+ * @function
+ * @deprecated since v3.0, please use new ccui.RelativeLayoutParameter() instead.
+ * @return {ccui.RelativeLayoutParameter}
+ */
+ccui.RelativeLayoutParameter.create = function () {
+ return new ccui.RelativeLayoutParameter();
+};
+
+// Constants
+
+/**
+ * Enum for Relative layout parameter RelativeAlign
+ * @readonly
+ * @enum {number}
+ */
+ccui.RelativeLayoutParameter.Type = cc.Enum({
+ /**
+ * The none of ccui.RelativeLayoutParameter's relative align.
+ */
+ NONE: 0,
+ /**
+ * The parent's top left of ccui.RelativeLayoutParameter's relative align.
+ */
+ PARENT_TOP_LEFT: 1,
+ /**
+ * The parent's top center horizontal of ccui.RelativeLayoutParameter's relative align.
+ */
+ PARENT_TOP_CENTER_HORIZONTAL: 2,
+ /**
+ * The parent's top right of ccui.RelativeLayoutParameter's relative align.
+ */
+ PARENT_TOP_RIGHT: 3,
+ /**
+ * The parent's left center vertical of ccui.RelativeLayoutParameter's relative align.
+ */
+ PARENT_LEFT_CENTER_VERTICAL: 4,
+
+ /**
+ * The center in parent of ccui.RelativeLayoutParameter's relative align.
+ */
+ CENTER_IN_PARENT: 5,
+
+ /**
+ * The parent's right center vertical of ccui.RelativeLayoutParameter's relative align.
+ */
+ PARENT_RIGHT_CENTER_VERTICAL: 6,
+ /**
+ * The parent's left bottom of ccui.RelativeLayoutParameter's relative align.
+ */
+ PARENT_LEFT_BOTTOM: 7,
+ /**
+ * The parent's bottom center horizontal of ccui.RelativeLayoutParameter's relative align.
+ */
+ PARENT_BOTTOM_CENTER_HORIZONTAL: 8,
+ /**
+ * The parent's right bottom of ccui.RelativeLayoutParameter's relative align.
+ */
+ PARENT_RIGHT_BOTTOM: 9,
+
+ /**
+ * The location above left align of ccui.RelativeLayoutParameter's relative align.
+ */
+ LOCATION_ABOVE_LEFTALIGN: 10,
+ /**
+ * The location above center of ccui.RelativeLayoutParameter's relative align.
+ */
+ LOCATION_ABOVE_CENTER: 11,
+ /**
+ * The location above right align of ccui.RelativeLayoutParameter's relative align.
+ */
+ LOCATION_ABOVE_RIGHTALIGN: 12,
+ /**
+ * The location left of top align of ccui.RelativeLayoutParameter's relative align.
+ */
+ LOCATION_LEFT_OF_TOPALIGN: 13,
+ /**
+ * The location left of center of ccui.RelativeLayoutParameter's relative align.
+ */
+ LOCATION_LEFT_OF_CENTER: 14,
+ /**
+ * The location left of bottom align of ccui.RelativeLayoutParameter's relative align.
+ */
+ LOCATION_LEFT_OF_BOTTOMALIGN: 15,
+ /**
+ * The location right of top align of ccui.RelativeLayoutParameter's relative align.
+ */
+ LOCATION_RIGHT_OF_TOPALIGN: 16,
+ /**
+ * The location right of center of ccui.RelativeLayoutParameter's relative align.
+ */
+ LOCATION_RIGHT_OF_CENTER: 17,
+ /**
+ * The location right of bottom align of ccui.RelativeLayoutParameter's relative align.
+ */
+ LOCATION_RIGHT_OF_BOTTOMALIGN: 18,
+ /**
+ * The location below left align of ccui.RelativeLayoutParameter's relative align.
+ */
+ LOCATION_BELOW_LEFTALIGN: 19,
+ /**
+ * The location below center of ccui.RelativeLayoutParameter's relative align.
+ */
+ LOCATION_BELOW_CENTER: 20,
+ /**
+ * The location below right align of ccui.RelativeLayoutParameter's relative align.
+ */
+ LOCATION_BELOW_RIGHTALIGN: 21
+});
+
+/**
+ * @ignore
+ */
+ccui.LINEAR_GRAVITY_NONE = 0;
+ccui.LINEAR_GRAVITY_LEFT = 1;
+ccui.LINEAR_GRAVITY_TOP = 2;
+ccui.LINEAR_GRAVITY_RIGHT = 3;
+ccui.LINEAR_GRAVITY_BOTTOM = 4;
+ccui.LINEAR_GRAVITY_CENTER_VERTICAL = 5;
+ccui.LINEAR_GRAVITY_CENTER_HORIZONTAL = 6;
+
+//RelativeAlign
+ccui.RELATIVE_ALIGN_NONE = 0;
+ccui.RELATIVE_ALIGN_PARENT_TOP_LEFT = 1;
+ccui.RELATIVE_ALIGN_PARENT_TOP_CENTER_HORIZONTAL = 2;
+ccui.RELATIVE_ALIGN_PARENT_TOP_RIGHT = 3;
+ccui.RELATIVE_ALIGN_PARENT_LEFT_CENTER_VERTICAL = 4;
+ccui.RELATIVE_ALIGN_PARENT_CENTER = 5;
+ccui.RELATIVE_ALIGN_PARENT_RIGHT_CENTER_VERTICAL = 6;
+ccui.RELATIVE_ALIGN_PARENT_LEFT_BOTTOM = 7;
+ccui.RELATIVE_ALIGN_PARENT_BOTTOM_CENTER_HORIZONTAL = 8;
+ccui.RELATIVE_ALIGN_PARENT_RIGHT_BOTTOM = 9;
+
+ccui.RELATIVE_ALIGN_LOCATION_ABOVE_LEFT = 10;
+ccui.RELATIVE_ALIGN_LOCATION_ABOVE_CENTER = 11;
+ccui.RELATIVE_ALIGN_LOCATION_ABOVE_RIGHT = 12;
+
+ccui.RELATIVE_ALIGN_LOCATION_LEFT_TOP = 13;
+ccui.RELATIVE_ALIGN_LOCATION_LEFT_CENTER = 14;
+ccui.RELATIVE_ALIGN_LOCATION_LEFT_BOTTOM = 15;
+
+ccui.RELATIVE_ALIGN_LOCATION_RIGHT_TOP = 16;
+ccui.RELATIVE_ALIGN_LOCATION_RIGHT_CENTER = 17;
+ccui.RELATIVE_ALIGN_LOCATION_RIGHT_BOTTOM = 18;
+
+ccui.RELATIVE_ALIGN_LOCATION_BELOW_TOP = 19;
+ccui.RELATIVE_ALIGN_LOCATION_BELOW_CENTER = 20;
+ccui.RELATIVE_ALIGN_LOCATION_BELOW_BOTTOM = 21;
\ No newline at end of file
diff --git a/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js b/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js
new file mode 100644
index 0000000000..baf4773fca
--- /dev/null
+++ b/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js
@@ -0,0 +1,242 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+(function(){
+ if(!ccui.ProtectedNode.WebGLRenderCmd)
+ return;
+ ccui.Layout.WebGLRenderCmd = function(renderable){
+ ccui.ProtectedNode.WebGLRenderCmd.call(this, renderable);
+ this._needDraw = false;
+
+ this._currentStencilEnabled = 0;
+ this._currentStencilWriteMask = 0;
+ this._currentStencilFunc = 0;
+ this._currentStencilRef = 0;
+ this._currentStencilValueMask = 0;
+ this._currentStencilFail = 0;
+ this._currentStencilPassDepthFail = 0;
+ this._currentStencilPassDepthPass = 0;
+ this._currentDepthWriteMask = false;
+
+ this._mask_layer_le = 0;
+
+ this._beforeVisitCmdStencil = new cc.CustomRenderCmd(this, this._onBeforeVisitStencil);
+ this._afterDrawStencilCmd = new cc.CustomRenderCmd(this, this._onAfterDrawStencil);
+ this._afterVisitCmdStencil = new cc.CustomRenderCmd(this, this._onAfterVisitStencil);
+ this._beforeVisitCmdScissor = new cc.CustomRenderCmd(this, this._onBeforeVisitScissor);
+ this._afterVisitCmdScissor = new cc.CustomRenderCmd(this, this._onAfterVisitScissor);
+ };
+
+ var proto = ccui.Layout.WebGLRenderCmd.prototype = Object.create(ccui.ProtectedNode.WebGLRenderCmd.prototype);
+ proto.constructor = ccui.Layout.WebGLRenderCmd;
+
+ proto.visit = function(parentCmd){
+ var node = this._node;
+ if (!node._visible)
+ return;
+ node._adaptRenderers();
+ node._doLayout();
+
+ if (node._clippingEnabled) {
+ switch (node._clippingType) {
+ case ccui.Layout.CLIPPING_STENCIL:
+ this.stencilClippingVisit(parentCmd);
+ break;
+ case ccui.Layout.CLIPPING_SCISSOR:
+ this.scissorClippingVisit(parentCmd);
+ break;
+ default:
+ break;
+ }
+ } else
+ ccui.Widget.WebGLRenderCmd.prototype.visit.call(this, parentCmd);
+ };
+
+ proto._onBeforeVisitStencil = function(ctx){
+ var gl = ctx || cc._renderContext;
+
+ ccui.Layout.WebGLRenderCmd._layer++;
+
+ var mask_layer = 0x1 << ccui.Layout.WebGLRenderCmd._layer;
+ var mask_layer_l = mask_layer - 1;
+ 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.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(gl.ZERO, gl.KEEP, gl.KEEP);
+
+ // draw a fullscreen solid rectangle to clear the stencil buffer
+ this._drawFullScreenQuadClearStencil();
+
+ gl.stencilFunc(gl.NEVER, mask_layer, mask_layer);
+ gl.stencilOp(gl.REPLACE, gl.KEEP, gl.KEEP);
+ };
+
+ 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.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
+ };
+
+ proto._onAfterVisitStencil = function(ctx){
+ var gl = ctx || cc._renderContext;
+ // manually restore the stencil state
+ gl.stencilFunc(this._currentStencilFunc, this._currentStencilRef, this._currentStencilValueMask);
+ gl.stencilOp(this._currentStencilFail, this._currentStencilPassDepthFail, this._currentStencilPassDepthPass);
+ gl.stencilMask(this._currentStencilWriteMask);
+ if (!this._currentStencilEnabled)
+ gl.disable(gl.STENCIL_TEST);
+ ccui.Layout.WebGLRenderCmd._layer--;
+ };
+
+ proto._onBeforeVisitScissor = function(ctx){
+ var clippingRect = this._getClippingRect();
+ var gl = ctx || cc._renderContext;
+ gl.enable(gl.SCISSOR_TEST);
+
+ cc.view.setScissorInPoints(clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
+ };
+
+ proto._onAfterVisitScissor = function(ctx){
+ var gl = ctx || cc._renderContext;
+ gl.disable(gl.SCISSOR_TEST);
+ };
+
+ 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.rebindStencilRendering = function(stencil){};
+
+ proto.transform = function(parentCmd, recursive){
+ var node = this._node;
+ ccui.ProtectedNode.WebGLRenderCmd.prototype.transform.call(this, parentCmd, recursive);
+ if(node._clippingStencil)
+ node._clippingStencil._renderCmd.transform(this, recursive);
+ };
+
+ proto.stencilClippingVisit = function (parentCmd) {
+ var node = this._node;
+ if (!node._clippingStencil || !node._clippingStencil.isVisible())
+ return;
+
+ // all the _stencilBits are in use?
+ if (ccui.Layout.WebGLRenderCmd._layer + 1 === cc.stencilBits) {
+ // warn once
+ ccui.Layout.WebGLRenderCmd._visit_once = true;
+ if (ccui.Layout.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 childs.");
+ ccui.Layout.WebGLRenderCmd._visit_once = false;
+ }
+ // draw everything, as if there where no stencil
+ cc.Node.prototype.visit.call(node, parentCmd);
+ return;
+ }
+
+ cc.renderer.pushRenderCommand(this._beforeVisitCmdStencil);
+
+ //optimize performance for javascript
+ var currentStack = cc.current_stack;
+ currentStack.stack.push(currentStack.top);
+ this._syncStatus(parentCmd);
+ this._dirtyFlag = 0;
+ currentStack.top = this._stackMatrix;
+
+ node._clippingStencil.visit(this);
+
+ cc.renderer.pushRenderCommand(this._afterDrawStencilCmd);
+
+ // draw (according to the stencil test func) this node and its childs
+ var i = 0; // used by _children
+ var j = 0; // used by _protectedChildren
+
+ node.sortAllChildren();
+ node.sortAllProtectedChildren();
+ var locChildren = node._children, locProtectChildren = node._protectedChildren;
+ var iLen = locChildren.length, jLen = locProtectChildren.length, child;
+ for( ; i < iLen; i++ ){
+ child = locChildren[i];
+ if ( child && child.getLocalZOrder() < 0 )
+ child.visit(this);
+ else
+ break;
+ }
+ for( ; j < jLen; j++ ) {
+ child = locProtectChildren[j];
+ if ( child && child.getLocalZOrder() < 0 )
+ child.visit(this);
+ else
+ break;
+ }
+
+ for (; i < iLen; i++)
+ locChildren[i].visit(this);
+ for (; j < jLen; j++)
+ locProtectChildren[j].visit(this);
+
+ cc.renderer.pushRenderCommand(this._afterVisitCmdStencil);
+
+ //optimize performance for javascript
+ currentStack.top = currentStack.stack.pop();
+ };
+
+ proto.scissorClippingVisit = function(parentCmd){
+ cc.renderer.pushRenderCommand(this._beforeVisitCmdScissor);
+ cc.ProtectedNode.prototype.visit.call(this._node, parentCmd);
+ cc.renderer.pushRenderCommand(this._afterVisitCmdScissor);
+ };
+
+ ccui.Layout.WebGLRenderCmd._layer = -1;
+ ccui.Layout.WebGLRenderCmd._visit_once = null;
+})();
diff --git a/extensions/ccui/layouts/UIRelativeBox.js b/extensions/ccui/layouts/UIRelativeBox.js
new file mode 100644
index 0000000000..14a357853e
--- /dev/null
+++ b/extensions/ccui/layouts/UIRelativeBox.js
@@ -0,0 +1,79 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+/**
+ * The Relative box for Cocos UI layout. Its layout type is ccui.Layout.Type.RELATIVE.
+ * @class
+ * @extends ccui.Layout
+ */
+ccui.RelativeBox = ccui.Layout.extend(/** @lends ccui.RelativeBox# */{
+ /**
+ * The constructor of ccui.RelativeBox
+ * @function
+ * @param {cc.Size} [size]
+ */
+ ctor: function(size){
+ if(size)
+ this.initWithSize(size);
+ else
+ this.init();
+ },
+
+ /**
+ * Initializes a relative box. please do not call this function by yourself, you should pass the parameters to constructor to initialize it.
+ * @override
+ * @returns {boolean}
+ */
+ init: function(){
+ if(ccui.Layout.prototype.init.call(this)){
+ this.setLayoutType(ccui.Layout.Type.RELATIVE);
+ return true;
+ }
+ return false;
+ },
+
+ /**
+ * Initializes a relative box with size
+ * @param {cc.Size} [size]
+ * @returns {boolean}
+ */
+ initWithSize: function(size){
+ if(this.init()){
+ this.setContentSize(size);
+ return true;
+ }
+ return false;
+ }
+});
+
+/**
+ * Creates a relative box
+ * @deprecated since v3.0, please use new ccui.RelativeBox(size) instead.
+ * @param {cc.Size} size
+ * @returns {ccui.RelativeBox}
+ */
+ccui.RelativeBox.create = function(size){
+ return new ccui.RelativeBox(size);
+};
\ No newline at end of file
diff --git a/extensions/ccui/layouts/UIVBox.js b/extensions/ccui/layouts/UIVBox.js
new file mode 100644
index 0000000000..352d21bafe
--- /dev/null
+++ b/extensions/ccui/layouts/UIVBox.js
@@ -0,0 +1,79 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+/**
+ * The vertical box of Cocos UI. Its layout type is ccui.Layout.Type.LINEAR_VERTICAL.
+ * @class
+ * @extends ccui.Layout
+ */
+ccui.VBox = ccui.Layout.extend(/** @lends ccui.VBox# */{
+ /**
+ * The constructor of ccui.VBox
+ * @function
+ * @param {cc.Size} size
+ */
+ ctor: function(size){
+ ccui.Layout.prototype.ctor.call(this, size);
+ if(size !== undefined)
+ this.initWithSize(size);
+ else
+ this.init();
+ },
+
+ /**
+ * Initializes a VBox. please do not call this function by yourself, you should pass the parameters to constructor to initialize it.
+ * @override
+ * @returns {boolean}
+ */
+ init: function(){
+ if(ccui.Layout.prototype.init.call(this)){
+ this.setLayoutType(ccui.Layout.Type.LINEAR_VERTICAL);
+ return true;
+ }
+ return false;
+ },
+
+ /**
+ * Initializes a VBox with size.
+ * @param {cc.Size} size
+ * @returns {boolean}
+ */
+ initWithSize: function(size){
+ if(this.init()){
+ this.setContentSize(size);
+ return true;
+ }
+ return false;
+ }
+});
+
+/**
+ * Creates a VBox
+ * @param {cc.Size} size
+ * @returns {ccui.VBox}
+ */
+ccui.VBox.create = function(size){
+ return new ccui.VBox(size);
+};
\ No newline at end of file
diff --git a/extensions/ccui/system/CocosGUI.js b/extensions/ccui/system/CocosGUI.js
new file mode 100644
index 0000000000..022c32430a
--- /dev/null
+++ b/extensions/ccui/system/CocosGUI.js
@@ -0,0 +1,62 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+/**
+ * The namespace of Cocos UI
+ * @namespace
+ * @name ccui
+ */
+var ccui = ccui || {};
+
+//These classes defines are use for jsDoc
+/**
+ * The same as cc._Class
+ * @class
+ */
+ccui.Class = ccui.Class || cc._Class;
+ccui.Class.extend = ccui.Class.extend || cc._Class.extend;
+
+/**
+ * that same as cc.Node
+ * @class
+ * @extends ccui.Class
+ */
+ccui.Node = ccui.Node || cc.Node;
+ccui.Node.extend = ccui.Node.extend || cc.Node.extend;
+
+
+/**
+ * that same as cc.Node
+ * @class
+ * @extends ccui.Node
+ */
+ccui.ProtectedNode = ccui.ProtectedNode || cc.ProtectedNode;
+ccui.ProtectedNode.extend = ccui.ProtectedNode.extend || cc.ProtectedNode.extend;
+
+/**
+ * Cocos UI version
+ * @type {String}
+ */
+ccui.cocosGUIVersion = "CocosGUI v1.0.0.0";
\ No newline at end of file
diff --git a/extensions/ccui/system/UIHelper.js b/extensions/ccui/system/UIHelper.js
new file mode 100644
index 0000000000..70d82c9b84
--- /dev/null
+++ b/extensions/ccui/system/UIHelper.js
@@ -0,0 +1,164 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+//todo maybe need change here
+
+
+/**
+ * ccui.helper is the singleton object which is the Helper object contains some functions for seek widget
+ * @class
+ * @name ccui.helper
+ */
+ccui.helper = {
+ /**
+ * Finds a widget whose tag equals to param tag from root widget.
+ * @param {ccui.Widget} root
+ * @param {number} tag
+ * @returns {ccui.Widget}
+ */
+ seekWidgetByTag: function (root, tag) {
+ if (!root)
+ return null;
+ if (root.getTag() === tag)
+ return root;
+
+ var arrayRootChildren = root.getChildren();
+ var length = arrayRootChildren.length;
+ for (var i = 0; i < length; i++) {
+ var child = arrayRootChildren[i];
+ var res = ccui.helper.seekWidgetByTag(child, tag);
+ if (res !== null)
+ return res;
+ }
+ return null;
+ },
+
+ /**
+ * Finds a widget whose name equals to param name from root widget.
+ * @param {ccui.Widget} root
+ * @param {String} name
+ * @returns {ccui.Widget}
+ */
+ seekWidgetByName: function (root, name) {
+ if (!root)
+ return null;
+ if (root.getName() === name)
+ return root;
+ var arrayRootChildren = root.getChildren();
+ var length = arrayRootChildren.length;
+ for (var i = 0; i < length; i++) {
+ var child = arrayRootChildren[i];
+ var res = ccui.helper.seekWidgetByName(child, name);
+ if (res !== null)
+ return res;
+ }
+ return null;
+ },
+
+ /**
+ * Finds a widget whose name equals to param name from root widget.
+ * RelativeLayout will call this method to find the widget witch is needed.
+ * @param {ccui.Widget} root
+ * @param {String} name
+ * @returns {ccui.Widget}
+ */
+ seekWidgetByRelativeName: function (root, name) {
+ if (!root)
+ return null;
+ var arrayRootChildren = root.getChildren();
+ var length = arrayRootChildren.length;
+ for (var i = 0; i < length; i++) {
+ var child = arrayRootChildren[i];
+ var layoutParameter = child.getLayoutParameter(ccui.LayoutParameter.RELATIVE);
+ if (layoutParameter && layoutParameter.getRelativeName() === name)
+ return child;
+ }
+ return null;
+ },
+
+ /**
+ * Finds a widget whose action tag equals to param name from root widget.
+ * @param {ccui.Widget} root
+ * @param {Number} tag
+ * @returns {ccui.Widget}
+ */
+ seekActionWidgetByActionTag: function (root, tag) {
+ if (!root)
+ return null;
+ if (root.getActionTag() === tag)
+ return root;
+ var arrayRootChildren = root.getChildren();
+ for (var i = 0; i < arrayRootChildren.length; i++) {
+ var child = arrayRootChildren[i];
+ var res = ccui.helper.seekActionWidgetByActionTag(child, tag);
+ if (res !== null)
+ return res;
+ }
+ return null;
+ } ,
+
+ _activeLayout: true,
+ /**
+ * Refresh object and it's children layout state
+ * @param {cc.Node} rootNode
+ */
+ doLayout: function(rootNode){
+ if(!this._activeLayout)
+ return;
+ var children = rootNode.getChildren(), node;
+ for(var i = 0, len = children.length;i < len; i++) {
+ node = children[i];
+ var com = node.getComponent(ccui.LayoutComponent.NAME);
+ var parent = node.getParent();
+ if (null != com && null !== parent && com.refreshLayout)
+ com.refreshLayout();
+ }
+ },
+
+ changeLayoutSystemActiveState: function(active){
+ this._activeLayout = active;
+ },
+
+ /**
+ * restrict capInsetSize, when the capInsets' width is larger than the textureSize, it will restrict to 0,
+ * the height goes the same way as width.
+ * @param {cc.Rect} capInsets
+ * @param {cc.Size} textureSize
+ */
+ restrictCapInsetRect: function (capInsets, textureSize) {
+ var x = capInsets.x, y = capInsets.y;
+ var width = capInsets.width, height = capInsets.height;
+
+ if (textureSize.width < width) {
+ x = 0.0;
+ width = 0.0;
+ }
+ if (textureSize.height < height) {
+ y = 0.0;
+ height = 0.0;
+ }
+ return cc.rect(x, y, width, height);
+ }
+};
diff --git a/extensions/ccui/uiwidgets/UIButton.js b/extensions/ccui/uiwidgets/UIButton.js
new file mode 100644
index 0000000000..e857e86b68
--- /dev/null
+++ b/extensions/ccui/uiwidgets/UIButton.js
@@ -0,0 +1,973 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+/**
+ * The button controls of Cocos UI.
+ * @class
+ * @extends ccui.Widget
+ *
+ * @property {String} titleText - The content string of the button title
+ * @property {String} titleFont - The content string font of the button title
+ * @property {Number} titleFontSize - The content string font size of the button title
+ * @property {String} titleFontName - The content string font name of the button title
+ * @property {cc.Color} titleFontColor - The content string font color of the button title
+ * @property {Boolean} pressedActionEnabled - Indicate whether button has zoom effect when clicked
+ */
+ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
+ _buttonNormalRenderer: null,
+ _buttonClickedRenderer: null,
+ _buttonDisableRenderer: null,
+ _titleRenderer: null,
+
+ _normalFileName: "",
+ _clickedFileName: "",
+ _disabledFileName: "",
+
+ _prevIgnoreSize: true,
+ _scale9Enabled: false,
+
+ _capInsetsNormal: null,
+ _capInsetsPressed: null,
+ _capInsetsDisabled: null,
+
+ _normalTexType: ccui.Widget.LOCAL_TEXTURE,
+ _pressedTexType: ccui.Widget.LOCAL_TEXTURE,
+ _disabledTexType: ccui.Widget.LOCAL_TEXTURE,
+
+ _normalTextureSize: null,
+ _pressedTextureSize: null,
+ _disabledTextureSize: null,
+
+ pressedActionEnabled: false,
+ _titleColor: null,
+ _normalTextureScaleXInSize: 1,
+ _normalTextureScaleYInSize: 1,
+ _pressedTextureScaleXInSize: 1,
+ _pressedTextureScaleYInSize: 1,
+
+ _zoomScale: 0.1,
+
+ _normalTextureLoaded: false,
+ _pressedTextureLoaded: false,
+ _disabledTextureLoaded: false,
+
+ _className: "Button",
+ _normalTextureAdaptDirty: true,
+ _pressedTextureAdaptDirty: true,
+ _disabledTextureAdaptDirty: true,
+
+ _fontName: "Thonburi",
+ _fontSize: 12,
+ _type: 0,
+
+ /**
+ * Allocates and initializes a UIButton.
+ * Constructor of ccui.Button. override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
+ * @param {String} normalImage
+ * @param {String} [selectedImage=""]
+ * @param {String} [disableImage=""]
+ * @param {Number} [texType=ccui.Widget.LOCAL_TEXTURE]
+ * @example
+ * // example
+ * var uiButton = new ccui.Button();
+ */
+ ctor: function (normalImage, selectedImage, disableImage, texType) {
+ this._capInsetsNormal = cc.rect(0, 0, 0, 0);
+ this._capInsetsPressed = cc.rect(0, 0, 0, 0);
+ this._capInsetsDisabled = cc.rect(0, 0, 0, 0);
+ this._normalTextureSize = cc.size(0, 0);
+ this._pressedTextureSize = cc.size(0, 0);
+ this._disabledTextureSize = cc.size(0, 0);
+ this._titleColor = cc.Color.WHITE;
+ ccui.Widget.prototype.ctor.call(this);
+ this.setTouchEnabled(true);
+ this.init(normalImage, selectedImage, disableImage, texType);
+ },
+
+ /**
+ * Initializes a button. please do not call this function by yourself, you should pass the parameters to constructor to initialize it.
+ * @param {String} normalImage
+ * @param {String} [selectedImage=""]
+ * @param {String} [disableImage=""]
+ * @param {Number} [texType=ccui.Widget.LOCAL_TEXTURE]
+ * @returns {boolean}
+ * @override
+ */
+ init: function (normalImage, selectedImage,disableImage, texType) {
+ if (ccui.Widget.prototype.init.call(this)) {
+ if(normalImage === undefined)
+ return true;
+ this.loadTextures(normalImage, selectedImage,disableImage, texType);
+ }
+ return false;
+ },
+
+ _initRenderer: function () {
+ //todo create Scale9Sprite
+ this._buttonNormalRenderer = new cc.Sprite();
+ this._buttonClickedRenderer = new cc.Sprite();
+ this._buttonDisableRenderer = new cc.Sprite();
+ this._titleRenderer = new cc.LabelTTF("");
+ this._titleRenderer.setAnchorPoint(0.5, 0.5);
+
+ this.addProtectedChild(this._buttonNormalRenderer, ccui.Button.NORMAL_RENDERER_ZORDER, -1);
+ this.addProtectedChild(this._buttonClickedRenderer, ccui.Button.PRESSED_RENDERER_ZORDER, -1);
+ this.addProtectedChild(this._buttonDisableRenderer, ccui.Button.DISABLED_RENDERER_ZORDER, -1);
+ this.addProtectedChild(this._titleRenderer, ccui.Button.TITLE_RENDERER_ZORDER, -1);
+ },
+
+ /**
+ * Sets if button is using scale9 renderer.
+ * @param {Boolean} able true that using scale9 renderer, false otherwise.
+ */
+ setScale9Enabled: function (able) {
+ //todo create Scale9Sprite
+ if (this._scale9Enabled === able)
+ return;
+
+ this._brightStyle = ccui.Widget.BRIGHT_STYLE_NONE;
+ this._scale9Enabled = able;
+
+ this.removeProtectedChild(this._buttonNormalRenderer);
+ this.removeProtectedChild(this._buttonClickedRenderer);
+ this.removeProtectedChild(this._buttonDisableRenderer);
+
+ if (this._scale9Enabled) {
+ this._buttonNormalRenderer = new ccui.Scale9Sprite();
+ this._buttonClickedRenderer = new ccui.Scale9Sprite();
+ this._buttonDisableRenderer = new ccui.Scale9Sprite();
+ } else {
+ this._buttonNormalRenderer = new cc.Sprite();
+ this._buttonClickedRenderer = new cc.Sprite();
+ this._buttonDisableRenderer = new cc.Sprite();
+ }
+
+ this._buttonClickedRenderer.setVisible(false);
+ this._buttonDisableRenderer.setVisible(false);
+
+ this.loadTextureNormal(this._normalFileName, this._normalTexType);
+ this.loadTexturePressed(this._clickedFileName, this._pressedTexType);
+ this.loadTextureDisabled(this._disabledFileName, this._disabledTexType);
+
+ this.addProtectedChild(this._buttonNormalRenderer, ccui.Button.NORMAL_RENDERER_ZORDER, -1);
+ this.addProtectedChild(this._buttonClickedRenderer, ccui.Button.PRESSED_RENDERER_ZORDER, -1);
+ this.addProtectedChild(this._buttonDisableRenderer, ccui.Button.DISABLED_RENDERER_ZORDER, -1);
+ if (this._scale9Enabled) {
+ var ignoreBefore = this._ignoreSize;
+ this.ignoreContentAdaptWithSize(false);
+ this._prevIgnoreSize = ignoreBefore;
+ } else {
+ this.ignoreContentAdaptWithSize(this._prevIgnoreSize);
+ }
+ this.setCapInsetsNormalRenderer(this._capInsetsNormal);
+ this.setCapInsetsPressedRenderer(this._capInsetsPressed);
+ this.setCapInsetsDisabledRenderer(this._capInsetsDisabled);
+ this.setBright(this._bright);
+
+ this._normalTextureAdaptDirty = true;
+ this._pressedTextureAdaptDirty = true;
+ this._disabledTextureAdaptDirty = true;
+ },
+
+ /**
+ * Returns button is using scale9 renderer or not.
+ * @returns {Boolean}
+ */
+ isScale9Enabled: function () {
+ return this._scale9Enabled;
+ },
+
+ /**
+ * Sets whether ignore the widget size
+ * @param {Boolean} ignore true that widget will ignore it's size, use texture size, false otherwise. Default value is true.
+ * @override
+ */
+ ignoreContentAdaptWithSize: function (ignore) {
+ if(this._unifySize){
+ this._updateContentSize();
+ return;
+ }
+ if (!this._scale9Enabled || (this._scale9Enabled && !ignore)) {
+ ccui.Widget.prototype.ignoreContentAdaptWithSize.call(this, ignore);
+ this._prevIgnoreSize = ignore;
+ }
+ },
+
+ /**
+ * Returns the renderer size.
+ * @returns {cc.Size}
+ */
+ getVirtualRendererSize: function(){
+ if (this._unifySize)
+ return this._getNormalSize();
+
+ if (!this._normalTextureLoaded && this._titleRenderer.getString().length > 0) {
+ return this._titleRenderer.getContentSize();
+ }
+ return cc.size(this._normalTextureSize);
+ },
+
+ /**
+ * Load textures for button.
+ * @param {String} normal normal state of texture's filename.
+ * @param {String} selected selected state of texture's filename.
+ * @param {String} disabled disabled state of texture's filename.
+ * @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType
+ */
+ loadTextures: function (normal, selected, disabled, texType) {
+ this.loadTextureNormal(normal, texType);
+ this.loadTexturePressed(selected, texType);
+ this.loadTextureDisabled(disabled, texType);
+ },
+
+ /**
+ * Load normal state texture for button.
+ * @param {String} normal normal state of texture's filename.
+ * @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType
+ */
+ loadTextureNormal: function (normal, texType) {
+ if (!normal)
+ return;
+ texType = texType || ccui.Widget.LOCAL_TEXTURE;
+ this._normalFileName = normal;
+ this._normalTexType = texType;
+
+ var self = this;
+ var normalRenderer = this._buttonNormalRenderer;
+ if(!normalRenderer._textureLoaded){
+ normalRenderer.once("load", function () {
+ self.loadTextureNormal(self._normalFileName, self._normalTexType);
+ });
+ }
+ switch (this._normalTexType){
+ case ccui.Widget.LOCAL_TEXTURE:
+ //SetTexture cannot load resource
+ normalRenderer.initWithFile(normal);
+ break;
+ case ccui.Widget.PLIST_TEXTURE:
+ //SetTexture cannot load resource
+ normalRenderer.initWithSpriteFrameName(normal);
+ break;
+ default:
+ break;
+ }
+
+ this._normalTextureLoaded = normalRenderer._textureLoaded;
+
+ this._normalTextureSize = this._buttonNormalRenderer.getContentSize();
+ this._updateChildrenDisplayedRGBA();
+ if (this._unifySize){
+ if (this._scale9Enabled){
+ normalRenderer.setCapInsets(this._capInsetsNormal);
+ this._updateContentSizeWithTextureSize(this._getNormalSize());
+ }
+ }else
+ this._updateContentSizeWithTextureSize(this._normalTextureSize);
+
+ this._normalTextureAdaptDirty = true;
+ this._findLayout();
+ },
+
+ /**
+ * Load selected state texture for button.
+ * @param {String} selected selected state of texture's filename.
+ * @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType
+ */
+ loadTexturePressed: function (selected, texType) {
+ if (!selected)
+ return;
+ texType = texType || ccui.Widget.LOCAL_TEXTURE;
+ this._clickedFileName = selected;
+ this._pressedTexType = texType;
+
+ var self = this;
+ var clickedRenderer = this._buttonClickedRenderer;
+ if(!clickedRenderer._textureLoaded){
+ clickedRenderer.once("load", function () {
+ self.loadTexturePressed(self._clickedFileName, self._pressedTexType);
+ });
+ }
+
+ switch (this._pressedTexType) {
+ case ccui.Widget.LOCAL_TEXTURE:
+ //SetTexture cannot load resource
+ clickedRenderer.initWithFile(selected);
+ break;
+ case ccui.Widget.PLIST_TEXTURE:
+ //SetTexture cannot load resource
+ clickedRenderer.initWithSpriteFrameName(selected);
+ break;
+ default:
+ break;
+ }
+
+ if (this._scale9Enabled)
+ clickedRenderer.setCapInsets(this._capInsetsPressed);
+
+ this._pressedTextureSize = this._buttonClickedRenderer.getContentSize();
+ this._updateChildrenDisplayedRGBA();
+
+ this._pressedTextureLoaded = true;
+ this._pressedTextureAdaptDirty = true;
+ this._findLayout();
+ },
+
+ /**
+ * Load dark state texture for button.
+ * @param {String} disabled disabled state of texture's filename.
+ * @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType
+ */
+ loadTextureDisabled: function (disabled, texType) {
+ if (!disabled)
+ return;
+
+ texType = texType || ccui.Widget.LOCAL_TEXTURE;
+ this._disabledFileName = disabled;
+ this._disabledTexType = texType;
+
+ var self = this;
+ var disabledRenderer = this._buttonDisableRenderer;
+ if(!disabledRenderer._textureLoaded){
+ disabledRenderer.once("load", function () {
+ self.loadTextureDisabled(self._disabledFileName, self._disabledTexType);
+ });
+ }
+
+ switch (this._disabledTexType) {
+ case ccui.Widget.LOCAL_TEXTURE:
+ //SetTexture cannot load resource
+ disabledRenderer.initWithFile(disabled);
+ break;
+ case ccui.Widget.PLIST_TEXTURE:
+ //SetTexture cannot load resource
+ disabledRenderer.initWithSpriteFrameName(disabled);
+ break;
+ default:
+ break;
+ }
+
+ if (this._scale9Enabled)
+ disabledRenderer.setCapInsets(this._capInsetsDisabled);
+
+ this._disabledTextureSize = this._buttonDisableRenderer.getContentSize();
+ this._updateChildrenDisplayedRGBA();
+
+ this._disabledTextureLoaded = true;
+ this._disabledTextureAdaptDirty = true;
+ this._findLayout();
+ },
+
+ /**
+ * Sets capinsets for button, if button is using scale9 renderer.
+ * @param {cc.Rect} capInsets
+ */
+ setCapInsets: function (capInsets) {
+ this.setCapInsetsNormalRenderer(capInsets);
+ this.setCapInsetsPressedRenderer(capInsets);
+ this.setCapInsetsDisabledRenderer(capInsets);
+ },
+
+ /**
+ * Sets capinsets for button, if button is using scale9 renderer.
+ * @param {cc.Rect} capInsets
+ */
+ setCapInsetsNormalRenderer: function (capInsets) {
+ if(!capInsets)
+ return;
+
+ var x = capInsets.x, y = capInsets.y;
+ var width = capInsets.width, height = capInsets.height;
+ if (this._normalTextureSize.width < width){
+ x = 0;
+ width = 0;
+ }
+ if (this._normalTextureSize.height < height){
+ y = 0;
+ height = 0;
+ }
+
+ var locInsets = this._capInsetsNormal;
+ locInsets.x = x;
+ locInsets.y = y;
+ locInsets.width = width;
+ locInsets.height = height;
+
+ if (!this._scale9Enabled)
+ return;
+ this._buttonNormalRenderer.setCapInsets(locInsets);
+ },
+
+ /**
+ * Returns normal renderer cap insets.
+ * @returns {cc.Rect}
+ */
+ getCapInsetsNormalRenderer:function(){
+ return cc.rect(this._capInsetsNormal);
+ },
+
+ /**
+ * Sets capinsets for button, if button is using scale9 renderer.
+ * @param {cc.Rect} capInsets
+ */
+ setCapInsetsPressedRenderer: function (capInsets) {
+ if(!capInsets || !this._scale9Enabled)
+ return;
+
+ var x = capInsets.x, y = capInsets.y;
+ var width = capInsets.width, height = capInsets.height;
+
+ if (this._pressedTextureSize.width < width) {
+ x = 0;
+ width = 0;
+ }
+ if (this._pressedTextureSize.height < height) {
+ y = 0;
+ height = 0;
+ }
+
+ var locInsets = this._capInsetsPressed;
+ locInsets.x = x;
+ locInsets.y = y;
+ locInsets.width = width;
+ locInsets.height = height;
+
+ this._buttonClickedRenderer.setCapInsets(locInsets);
+ },
+
+ /**
+ * Returns pressed renderer cap insets.
+ * @returns {cc.Rect}
+ */
+ getCapInsetsPressedRenderer: function () {
+ return cc.rect(this._capInsetsPressed);
+ },
+
+ /**
+ * Sets capinsets for button, if button is using scale9 renderer.
+ * @param {cc.Rect} capInsets
+ */
+ setCapInsetsDisabledRenderer: function (capInsets) {
+ if(!capInsets || !this._scale9Enabled)
+ return;
+
+ var x = capInsets.x, y = capInsets.y;
+ var width = capInsets.width, height = capInsets.height;
+
+ if (this._disabledTextureSize.width < width) {
+ x = 0;
+ width = 0;
+ }
+ if (this._disabledTextureSize.height < height) {
+ y = 0;
+ height = 0;
+ }
+
+ var locInsets = this._capInsetsDisabled;
+ locInsets.x = x;
+ locInsets.y = y;
+ locInsets.width = width;
+ locInsets.height = height;
+
+ this._buttonDisableRenderer.setCapInsets(locInsets);
+ },
+
+ /**
+ * Returns disable renderer cap insets.
+ * @returns {cc.Rect}
+ */
+ getCapInsetsDisabledRenderer: function () {
+ return cc.rect(this._capInsetsDisabled);
+ },
+
+ _onPressStateChangedToNormal: function () {
+ this._buttonNormalRenderer.setVisible(true);
+ this._buttonClickedRenderer.setVisible(false);
+ this._buttonDisableRenderer.setVisible(false);
+ if (this._scale9Enabled)
+ this._buttonNormalRenderer.setState( ccui.Scale9Sprite.state.NORMAL);
+ if (this._pressedTextureLoaded) {
+ if (this.pressedActionEnabled){
+ this._buttonNormalRenderer.stopAllActions();
+ this._buttonClickedRenderer.stopAllActions();
+ //var zoomAction = cc.scaleTo(ccui.Button.ZOOM_ACTION_TIME_STEP, this._normalTextureScaleXInSize, this._normalTextureScaleYInSize);
+ //fixme: the zoomAction will run in the next frame which will cause the _buttonNormalRenderer to a wrong scale
+ //this._buttonNormalRenderer.runAction(zoomAction);
+ this._buttonNormalRenderer.setScale(this._normalTextureScaleXInSize, this._normalTextureScaleYInSize);
+ this._buttonClickedRenderer.setScale(this._pressedTextureScaleXInSize, this._pressedTextureScaleYInSize);
+
+ this._titleRenderer.stopAllActions();
+ if (this._unifySize){
+ var zoomTitleAction = cc.scaleTo(ccui.Button.ZOOM_ACTION_TIME_STEP, 1, 1);
+ this._titleRenderer.runAction(zoomTitleAction);
+ }else{
+ this._titleRenderer.setScaleX(1);
+ this._titleRenderer.setScaleY(1);
+ }
+ }
+ } else {
+ this._buttonNormalRenderer.stopAllActions();
+ this._buttonNormalRenderer.setScale(this._normalTextureScaleXInSize, this._normalTextureScaleYInSize);
+
+ this._titleRenderer.stopAllActions();
+ if (this._scale9Enabled)
+ this._buttonNormalRenderer.setColor(cc.Color.WHITE);
+
+ this._titleRenderer.setScaleX(1);
+ this._titleRenderer.setScaleY(1);
+ }
+ },
+
+ _onPressStateChangedToPressed: function () {
+ var locNormalRenderer = this._buttonNormalRenderer;
+ if (this._scale9Enabled)
+ locNormalRenderer.setState(ccui.Scale9Sprite.state.NORMAL);
+
+ if (this._pressedTextureLoaded) {
+ locNormalRenderer.setVisible(false);
+ this._buttonClickedRenderer.setVisible(true);
+ this._buttonDisableRenderer.setVisible(false);
+ if (this.pressedActionEnabled) {
+ locNormalRenderer.stopAllActions();
+ this._buttonClickedRenderer.stopAllActions();
+ var zoomAction = cc.scaleTo(ccui.Button.ZOOM_ACTION_TIME_STEP, this._pressedTextureScaleXInSize + this._zoomScale,
+ this._pressedTextureScaleYInSize + this._zoomScale);
+ this._buttonClickedRenderer.runAction(zoomAction);
+ locNormalRenderer.setScale(this._pressedTextureScaleXInSize + this._zoomScale, this._pressedTextureScaleYInSize + this._zoomScale);
+
+ this._titleRenderer.stopAllActions();
+ this._titleRenderer.runAction(cc.scaleTo(ccui.Button.ZOOM_ACTION_TIME_STEP, 1 + this._zoomScale, 1 + this._zoomScale));
+ }
+ } else {
+ locNormalRenderer.setVisible(true);
+ this._buttonClickedRenderer.setVisible(true);
+ this._buttonDisableRenderer.setVisible(false);
+ locNormalRenderer.stopAllActions();
+ locNormalRenderer.setScale(this._normalTextureScaleXInSize + this._zoomScale, this._normalTextureScaleYInSize + this._zoomScale);
+
+ this._titleRenderer.stopAllActions();
+ this._titleRenderer.setScaleX(1 + this._zoomScale);
+ this._titleRenderer.setScaleY(1 + this._zoomScale);
+ }
+ },
+
+ _onPressStateChangedToDisabled: function () {
+ //if disable resource is null
+ if (!this._disabledTextureLoaded){
+ if (this._normalTextureLoaded && this._scale9Enabled)
+ this._buttonNormalRenderer.setState(ccui.Scale9Sprite.state.GRAY);
+ }else{
+ this._buttonNormalRenderer.setVisible(false);
+ this._buttonDisableRenderer.setVisible(true);
+ }
+
+ this._buttonClickedRenderer.setVisible(false);
+ this._buttonNormalRenderer.setScale(this._normalTextureScaleXInSize, this._normalTextureScaleYInSize);
+ this._buttonClickedRenderer.setScale(this._pressedTextureScaleXInSize, this._pressedTextureScaleYInSize);
+ },
+
+ _updateContentSize: function(){
+ if (this._unifySize){
+ if (this._scale9Enabled)
+ ccui.ProtectedNode.setContentSize(this._customSize);
+ else{
+ var s = this._getNormalSize();
+ ccui.ProtectedNode.setContentSize(s);
+ }
+ this._onSizeChanged();
+ return;
+ }
+
+ if (this._ignoreSize)
+ this.setContentSize(this.getVirtualRendererSize());
+ },
+
+ _onSizeChanged: function () {
+ ccui.Widget.prototype._onSizeChanged.call(this);
+ this._updateTitleLocation();
+ this._normalTextureAdaptDirty = true;
+ this._pressedTextureAdaptDirty = true;
+ this._disabledTextureAdaptDirty = true;
+ },
+
+ /**
+ * Gets the Virtual Renderer of widget.
+ * @returns {cc.Node}
+ */
+ getVirtualRenderer: function () {
+ if (this._bright) {
+ switch (this._brightStyle) {
+ case ccui.Widget.BRIGHT_STYLE_NORMAL:
+ return this._buttonNormalRenderer;
+ case ccui.Widget.BRIGHT_STYLE_HIGH_LIGHT:
+ return this._buttonClickedRenderer;
+ default:
+ return null;
+ }
+ } else
+ return this._buttonDisableRenderer;
+ },
+
+ _normalTextureScaleChangedWithSize: function () {
+ if(this._ignoreSize && !this._unifySize){
+ if(!this._scale9Enabled){
+ this._buttonNormalRenderer.setScale(1);
+ this._normalTextureScaleXInSize = this._normalTextureScaleYInSize = 1;
+ }
+ }else{
+ if (this._scale9Enabled){
+ this._buttonNormalRenderer.setPreferredSize(this._contentSize);
+ this._normalTextureScaleXInSize = this._normalTextureScaleYInSize = 1;
+ this._buttonNormalRenderer.setScale(this._normalTextureScaleXInSize, this._normalTextureScaleYInSize);
+ }else{
+ var textureSize = this._normalTextureSize;
+ if (textureSize.width <= 0 || textureSize.height <= 0)
+ {
+ this._buttonNormalRenderer.setScale(1);
+ return;
+ }
+ var scaleX = this._contentSize.width / textureSize.width;
+ var scaleY = this._contentSize.height / textureSize.height;
+ this._buttonNormalRenderer.setScaleX(scaleX);
+ this._buttonNormalRenderer.setScaleY(scaleY);
+ this._normalTextureScaleXInSize = scaleX;
+ this._normalTextureScaleYInSize = scaleY;
+ }
+ }
+ this._buttonNormalRenderer.setPosition(this._contentSize.width / 2, this._contentSize.height / 2);
+ },
+
+ _pressedTextureScaleChangedWithSize: function () {
+ if (this._ignoreSize && !this._unifySize) {
+ if (!this._scale9Enabled) {
+ this._buttonClickedRenderer.setScale(1);
+ this._pressedTextureScaleXInSize = this._pressedTextureScaleYInSize = 1;
+ }
+ } else {
+ if (this._scale9Enabled) {
+ this._buttonClickedRenderer.setPreferredSize(this._contentSize);
+ this._pressedTextureScaleXInSize = this._pressedTextureScaleYInSize = 1;
+ this._buttonClickedRenderer.setScale(this._pressedTextureScaleXInSize, this._pressedTextureScaleYInSize);
+ } else {
+ var textureSize = this._pressedTextureSize;
+ if (textureSize.width <= 0 || textureSize.height <= 0) {
+ this._buttonClickedRenderer.setScale(1);
+ return;
+ }
+ var scaleX = this._contentSize.width / textureSize.width;
+ var scaleY = this._contentSize.height / textureSize.height;
+ this._buttonClickedRenderer.setScaleX(scaleX);
+ this._buttonClickedRenderer.setScaleY(scaleY);
+ this._pressedTextureScaleXInSize = scaleX;
+ this._pressedTextureScaleYInSize = scaleY;
+ }
+ }
+ this._buttonClickedRenderer.setPosition(this._contentSize.width / 2, this._contentSize.height / 2);
+ },
+
+ _disabledTextureScaleChangedWithSize: function () {
+ if(this._ignoreSize && !this._unifySize){
+ if (this._scale9Enabled)
+ this._buttonDisableRenderer.setScale(1);
+ }else {
+ if (this._scale9Enabled){
+ this._buttonDisableRenderer.setScale(1);
+ this._buttonDisableRenderer.setPreferredSize(this._contentSize);
+ }else{
+ var textureSize = this._disabledTextureSize;
+ if (textureSize.width <= 0 || textureSize.height <= 0) {
+ this._buttonDisableRenderer.setScale(1);
+ return;
+ }
+ var scaleX = this._contentSize.width / textureSize.width;
+ var scaleY = this._contentSize.height / textureSize.height;
+ this._buttonDisableRenderer.setScaleX(scaleX);
+ this._buttonDisableRenderer.setScaleY(scaleY);
+ }
+ }
+ this._buttonDisableRenderer.setPosition(this._contentSize.width / 2, this._contentSize.height / 2);
+ },
+
+ _adaptRenderers: function(){
+ if (this._normalTextureAdaptDirty) {
+ this._normalTextureScaleChangedWithSize();
+ this._normalTextureAdaptDirty = false;
+ }
+ if (this._pressedTextureAdaptDirty) {
+ this._pressedTextureScaleChangedWithSize();
+ this._pressedTextureAdaptDirty = false;
+ }
+ if (this._disabledTextureAdaptDirty) {
+ this._disabledTextureScaleChangedWithSize();
+ this._disabledTextureAdaptDirty = false;
+ }
+ },
+
+ _updateTitleLocation: function(){
+ this._titleRenderer.setPosition(this._contentSize.width * 0.5, this._contentSize.height * 0.5);
+ },
+
+ /**
+ * Changes if button can be clicked zoom effect.
+ * @param {Boolean} enabled
+ */
+ setPressedActionEnabled: function (enabled) {
+ this.pressedActionEnabled = enabled;
+ },
+
+ /**
+ * Sets title text to ccui.Button
+ * @param {String} text
+ */
+ setTitleText: function (text) {
+ if(text === this.getTitleText())
+ return;
+ this._titleRenderer.setString(text);
+ if (this._ignoreSize){
+ var s = this.getVirtualRendererSize();
+ this.setContentSize(s);
+ }else{
+ this._titleRenderer._renderCmd._updateTTF();
+ }
+ },
+
+ /**
+ * Returns title text of ccui.Button
+ * @returns {String} text
+ */
+ getTitleText: function () {
+ return this._titleRenderer.getString();
+ },
+
+ /**
+ * Sets title color to ccui.Button.
+ * @param {cc.Color} color
+ */
+ setTitleColor: function (color) {
+ this._titleRenderer.setFontFillColor(color);
+ },
+
+ /**
+ * Returns title color of ccui.Button
+ * @returns {cc.Color}
+ */
+ getTitleColor: function () {
+ return this._titleRenderer._getFillStyle();
+ },
+
+ /**
+ * Sets title fontSize to ccui.Button
+ * @param {cc.Size} size
+ */
+ setTitleFontSize: function (size) {
+ this._titleRenderer.setFontSize(size);
+ this._fontSize = size;
+ },
+
+ /**
+ * Returns title fontSize of ccui.Button.
+ * @returns {Number}
+ */
+ getTitleFontSize: function () {
+ return this._titleRenderer.getFontSize();
+ },
+
+ /**
+ * When user pressed the button, the button will zoom to a scale.
+ * The final scale of the button equals (button original scale + _zoomScale)
+ * @since v3.2
+ * @param scale
+ */
+ setZoomScale: function(scale){
+ this._zoomScale = scale;
+ },
+
+ /**
+ * Returns a zoom scale
+ * @since v3.2
+ * @returns {number}
+ */
+ getZoomScale: function(){
+ return this._zoomScale;
+ },
+
+ /**
+ * Returns the normalize of texture size
+ * @since v3.3
+ * @returns {cc.Size}
+ */
+ getNormalTextureSize: function(){
+ return this._normalTextureSize;
+ },
+
+ /**
+ * Sets title fontName to ccui.Button.
+ * @param {String} fontName
+ */
+ setTitleFontName: function (fontName) {
+ this._titleRenderer.setFontName(fontName);
+ this._fontName = fontName;
+ },
+
+ /**
+ * Get the title renderer.
+ * title ttf object.
+ * @returns {cc.LabelTTF}
+ */
+ getTitleRenderer: function(){
+ return this._titleRenderer;
+ },
+
+ /**
+ * Gets title fontName of ccui.Button.
+ * @returns {String}
+ */
+ getTitleFontName: function () {
+ return this._titleRenderer.getFontName();
+ },
+
+ _setTitleFont: function (font) {
+ this._titleRenderer.font = font;
+ },
+ _getTitleFont: function () {
+ return this._titleRenderer.font;
+ },
+
+ /**
+ * Returns the "class name" of widget.
+ * @override
+ * @returns {string}
+ */
+ getDescription: function () {
+ return "Button";
+ },
+
+ _createCloneInstance: function () {
+ return new ccui.Button();
+ },
+
+ _copySpecialProperties: function (uiButton) {
+ this._prevIgnoreSize = uiButton._prevIgnoreSize;
+ this.setScale9Enabled(uiButton._scale9Enabled);
+ this.loadTextureNormal(uiButton._normalFileName, uiButton._normalTexType);
+ this.loadTexturePressed(uiButton._clickedFileName, uiButton._pressedTexType);
+ this.loadTextureDisabled(uiButton._disabledFileName, uiButton._disabledTexType);
+ this.setCapInsetsNormalRenderer(uiButton._capInsetsNormal);
+ this.setCapInsetsPressedRenderer(uiButton._capInsetsPressed);
+ this.setCapInsetsDisabledRenderer(uiButton._capInsetsDisabled);
+ this.setTitleText(uiButton.getTitleText());
+ this.setTitleFontName(uiButton.getTitleFontName());
+ this.setTitleFontSize(uiButton.getTitleFontSize());
+ this.setTitleColor(uiButton.getTitleColor());
+ this.setPressedActionEnabled(uiButton.pressedActionEnabled);
+ this.setZoomScale(uiButton._zoomScale);
+ },
+
+ _getNormalSize: function(){
+ var titleSize;
+ if (this._titleRenderer !== null)
+ titleSize = this._titleRenderer.getContentSize();
+
+ var imageSize;
+ if (this._buttonNormalRenderer !== null)
+ imageSize = this._buttonNormalRenderer.getContentSize();
+ var width = titleSize.width > imageSize.width ? titleSize.width : imageSize.width;
+ var height = titleSize.height > imageSize.height ? titleSize.height : imageSize.height;
+
+ return cc.size(width,height);
+ }
+});
+
+var _p = ccui.Button.prototype;
+
+// Extended properties
+/** @expose */
+_p.titleText;
+cc.defineGetterSetter(_p, "titleText", _p.getTitleText, _p.setTitleText);
+/** @expose */
+_p.titleFont;
+cc.defineGetterSetter(_p, "titleFont", _p._getTitleFont, _p._setTitleFont);
+/** @expose */
+_p.titleFontSize;
+cc.defineGetterSetter(_p, "titleFontSize", _p.getTitleFontSize, _p.setTitleFontSize);
+/** @expose */
+_p.titleFontName;
+cc.defineGetterSetter(_p, "titleFontName", _p.getTitleFontName, _p.setTitleFontName);
+/** @expose */
+_p.titleColor;
+cc.defineGetterSetter(_p, "titleColor", _p.getTitleColor, _p.setTitleColor);
+
+_p = null;
+
+/**
+ * allocates and initializes a UIButton.
+ * @deprecated since v3.0, please use new ccui.Button() instead.
+ * @param {string} [normalImage] normal state texture name
+ * @param {string} [selectedImage] selected state texture name
+ * @param {string} [disableImage] disabled state texture name
+ * @param {string} [texType]
+ * @return {ccui.Button}
+ */
+ccui.Button.create = function (normalImage, selectedImage, disableImage, texType) {
+ return new ccui.Button(normalImage, selectedImage, disableImage, texType);
+};
+
+// Constants
+/**
+ * The normal renderer's zOrder value of ccui.Button.
+ * @constant
+ * @type {number}
+ */
+ccui.Button.NORMAL_RENDERER_ZORDER = -2;
+/**
+ * The pressed renderer's zOrder value ccui.Button.
+ * @constant
+ * @type {number}
+ */
+ccui.Button.PRESSED_RENDERER_ZORDER = -2;
+/**
+ * The disabled renderer's zOrder value of ccui.Button.
+ * @constant
+ * @type {number}
+ */
+ccui.Button.DISABLED_RENDERER_ZORDER = -2;
+/**
+ * The title renderer's zOrder value of ccui.Button.
+ * @constant
+ * @type {number}
+ */
+ccui.Button.TITLE_RENDERER_ZORDER = -1;
+
+/**
+ * the zoom action time step of ccui.Button
+ * @constant
+ * @type {number}
+ */
+ccui.Button.ZOOM_ACTION_TIME_STEP = 0.05;
+
+/**
+ * @ignore
+ */
+ccui.Button.SYSTEM = 0;
+ccui.Button.TTF = 1;
diff --git a/extensions/ccui/uiwidgets/UICheckBox.js b/extensions/ccui/uiwidgets/UICheckBox.js
new file mode 100644
index 0000000000..d5240daaff
--- /dev/null
+++ b/extensions/ccui/uiwidgets/UICheckBox.js
@@ -0,0 +1,740 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+/**
+ * The CheckBox control of Cocos UI.
+ * @class
+ * @extends ccui.Widget
+ *
+ * @property {Boolean} selected - Indicate whether the check box has been selected
+ */
+ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{
+ _backGroundBoxRenderer: null,
+ _backGroundSelectedBoxRenderer: null,
+ _frontCrossRenderer: null,
+ _backGroundBoxDisabledRenderer: null,
+ _frontCrossDisabledRenderer: null,
+
+ _isSelected: true,
+
+ _checkBoxEventListener: null,
+ _checkBoxEventSelector:null,
+
+ _backGroundTexType: ccui.Widget.LOCAL_TEXTURE,
+ _backGroundSelectedTexType: ccui.Widget.LOCAL_TEXTURE,
+ _frontCrossTexType: ccui.Widget.LOCAL_TEXTURE,
+ _backGroundDisabledTexType: ccui.Widget.LOCAL_TEXTURE,
+ _frontCrossDisabledTexType: ccui.Widget.LOCAL_TEXTURE,
+
+ _backGroundFileName: "",
+ _backGroundSelectedFileName: "",
+ _frontCrossFileName: "",
+ _backGroundDisabledFileName: "",
+ _frontCrossDisabledFileName: "",
+ _className: "CheckBox",
+
+ _zoomScale: 0.1,
+ _backgroundTextureScaleX: 0.1,
+ _backgroundTextureScaleY: 0.1,
+
+ _backGroundBoxRendererAdaptDirty:true,
+ _backGroundSelectedBoxRendererAdaptDirty:true,
+ _frontCrossRendererAdaptDirty: true,
+ _backGroundBoxDisabledRendererAdaptDirty: true,
+ _frontCrossDisabledRendererAdaptDirty: true,
+
+ /**
+ * allocates and initializes a UICheckBox.
+ * Constructor of ccui.CheckBox, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
+ * @param {String} backGround
+ * @param {String} backGroundSelected
+ * @param {String} cross
+ * @param {String} backGroundDisabled
+ * @param {String} frontCrossDisabled
+ * @param {Number} [texType=ccui.Widget.LOCAL_TEXTURE]
+ * @example
+ * // example
+ * var uiCheckBox = new ccui.CheckBox();
+ */
+ ctor: function (backGround, backGroundSelected,cross,backGroundDisabled,frontCrossDisabled,texType) {
+ ccui.Widget.prototype.ctor.call(this);
+ this.setTouchEnabled(true);
+ var strNum = 0;
+ for(var i=0; i
+ * Constructor of ccui.LoadingBar, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
+ * @param {string} textureName
+ * @param {Number} percentage
+ * @example
+ * // example
+ * var uiLoadingBar = new ccui.LoadingBar;
+ */
+ ctor: function (textureName, percentage) {
+ this._direction = ccui.LoadingBar.Type.LEFT;
+ this._barRendererTextureSize = cc.size(0, 0);
+ this._capInsets = cc.rect(0, 0, 0, 0);
+ ccui.Widget.prototype.ctor.call(this);
+
+ if(textureName !== undefined)
+ this.loadTexture(textureName);
+ if(percentage !== undefined)
+ this.setPercent(percentage);
+ },
+
+ _initRenderer: function () {
+ //todo use Scale9Sprite
+ this._barRenderer = new cc.Sprite();
+ this.addProtectedChild(this._barRenderer, ccui.LoadingBar.RENDERER_ZORDER, -1);
+ this._barRenderer.setAnchorPoint(0.0, 0.5);
+ },
+
+ /**
+ * Changes the progress direction of LoadingBar.
+ * LoadingBarTypeLeft means progress left to right, LoadingBarTypeRight otherwise.
+ * @param {ccui.LoadingBar.Type} dir
+ */
+ setDirection: function (dir) {
+ if (this._direction === dir)
+ return;
+ this._direction = dir;
+ switch (this._direction) {
+ case ccui.LoadingBar.Type.LEFT:
+ this._barRenderer.setAnchorPoint(0, 0.5);
+ this._barRenderer.setPosition(0, this._contentSize.height*0.5);
+ if (!this._scale9Enabled)
+ this._barRenderer.setFlippedX(false);
+ break;
+ case ccui.LoadingBar.Type.RIGHT:
+ this._barRenderer.setAnchorPoint(1, 0.5);
+ this._barRenderer.setPosition(this._totalLength,this._contentSize.height*0.5);
+ if (!this._scale9Enabled)
+ this._barRenderer.setFlippedX(true);
+ break;
+ }
+ },
+
+ /**
+ * Returns the progress direction of LoadingBar.
+ * LoadingBarTypeLeft means progress left to right, LoadingBarTypeRight otherwise.
+ * @returns {ccui.LoadingBar.Type}
+ */
+ getDirection: function () {
+ return this._direction;
+ },
+
+ /**
+ * Loads texture for LoadingBar.
+ * @param {String} texture
+ * @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType
+ */
+ loadTexture: function (texture, texType) {
+ if (!texture)
+ return;
+ texType = texType || ccui.Widget.LOCAL_TEXTURE;
+ this._renderBarTexType = texType;
+ this._textureFile = texture;
+ var barRenderer = this._barRenderer;
+
+ var self = this;
+ if(!barRenderer._textureLoaded){
+ barRenderer.once("load", function () {
+ self.loadTexture(self._textureFile, self._renderBarTexType);
+ self._setPercent(self._percent);
+ });
+ }
+
+ switch (this._renderBarTexType) {
+ case ccui.Widget.LOCAL_TEXTURE:
+ barRenderer.initWithFile(texture);
+ break;
+ case ccui.Widget.PLIST_TEXTURE:
+ barRenderer.initWithSpriteFrameName(texture);
+ break;
+ default:
+ break;
+ }
+
+ var bz = barRenderer.getContentSize();
+ this._barRendererTextureSize.width = bz.width;
+ this._barRendererTextureSize.height = bz.height;
+
+ switch (this._direction) {
+ case ccui.LoadingBar.Type.LEFT:
+ barRenderer.setAnchorPoint(0,0.5);
+ if (!this._scale9Enabled)
+ barRenderer.setFlippedX(false);
+ break;
+ case ccui.LoadingBar.Type.RIGHT:
+ barRenderer.setAnchorPoint(1,0.5);
+ if (!this._scale9Enabled)
+ barRenderer.setFlippedX(true);
+ break;
+ }
+ if (this._scale9Enabled)
+ barRenderer.setCapInsets(this._capInsets);
+
+ this._updateChildrenDisplayedRGBA();
+ this._barRendererScaleChangedWithSize();
+ this._updateContentSizeWithTextureSize(this._barRendererTextureSize);
+ this._barRendererAdaptDirty = true;
+ this._findLayout();
+ },
+
+ /**
+ * Sets if LoadingBar is using scale9 renderer.
+ * @param {Boolean} enabled
+ */
+ setScale9Enabled: function (enabled) {
+ //todo use setScale9Enabled
+ if (this._scale9Enabled === enabled)
+ return;
+ this._scale9Enabled = enabled;
+ this.removeProtectedChild(this._barRenderer);
+
+ this._barRenderer = this._scale9Enabled ? new ccui.Scale9Sprite() : new cc.Sprite();
+
+ this.loadTexture(this._textureFile, this._renderBarTexType);
+ this.addProtectedChild(this._barRenderer, ccui.LoadingBar.RENDERER_ZORDER, -1);
+ if (this._scale9Enabled) {
+ var ignoreBefore = this._ignoreSize;
+ this.ignoreContentAdaptWithSize(false);
+ this._prevIgnoreSize = ignoreBefore;
+ } else
+ this.ignoreContentAdaptWithSize(this._prevIgnoreSize);
+ this.setCapInsets(this._capInsets);
+ this.setPercent(this._percent);
+ this._barRendererAdaptDirty = true;
+ },
+
+ /**
+ * Returns LoadingBar is using scale9 renderer or not..
+ * @returns {Boolean}
+ */
+ isScale9Enabled: function () {
+ return this._scale9Enabled;
+ },
+
+ /**
+ * Sets capinsets for LoadingBar, if LoadingBar is using scale9 renderer.
+ * @param {cc.Rect} capInsets
+ */
+ setCapInsets: function (capInsets) {
+ if(!capInsets)
+ return;
+ var locInsets = this._capInsets;
+ locInsets.x = capInsets.x;
+ locInsets.y = capInsets.y;
+ locInsets.width = capInsets.width;
+ locInsets.height = capInsets.height;
+
+ if (this._scale9Enabled)
+ this._barRenderer.setCapInsets(capInsets);
+ },
+
+ /**
+ * Returns cap insets for loadingBar.
+ * @returns {cc.Rect}
+ */
+ getCapInsets: function () {
+ return cc.rect(this._capInsets);
+ },
+
+ /**
+ * The current progress of loadingBar
+ * @param {number} percent percent value from 1 to 100.
+ */
+ setPercent: function (percent) {
+ if(percent > 100)
+ percent = 100;
+ if(percent < 0)
+ percent = 0;
+ if (percent === this._percent)
+ return;
+ this._percent = percent;
+ this._setPercent(percent);
+ },
+
+ _setPercent: function(){
+ var res, rect, spriteRenderer, spriteTextureRect;
+
+ if (this._totalLength <= 0)
+ return;
+ res = this._percent / 100.0;
+
+ if (this._scale9Enabled)
+ this._setScale9Scale();
+ else {
+ spriteRenderer = this._barRenderer;
+ spriteTextureRect = this._barRendererTextureSize;
+ rect = spriteRenderer.getTextureRect();
+ rect.width = spriteTextureRect.width * res;
+ spriteRenderer.setTextureRect(
+ cc.rect(
+ rect.x,
+ rect.y,
+ spriteTextureRect.width * res,
+ spriteTextureRect.height
+ ),
+ spriteRenderer._rectRotated
+ );
+ }
+ },
+
+ /**
+ * Sets the contentSize of ccui.LoadingBar
+ * @override
+ * @param {Number|cc.Size} contentSize
+ * @param {Number} [height]
+ */
+ setContentSize: function(contentSize, height){
+ ccui.Widget.prototype.setContentSize.call(this, contentSize, height);
+ this._totalLength = (height === undefined) ? contentSize.width : contentSize;
+ },
+
+ /**
+ * Returns the progress direction of LoadingBar.
+ * @returns {number} percent value from 1 to 100.
+ */
+ getPercent: function () {
+ return this._percent;
+ },
+
+ _onSizeChanged: function () {
+ ccui.Widget.prototype._onSizeChanged.call(this);
+ this._barRendererAdaptDirty = true;
+ },
+
+ _adaptRenderers: function(){
+ if (this._barRendererAdaptDirty){
+ this._barRendererScaleChangedWithSize();
+ this._barRendererAdaptDirty = false;
+ }
+ },
+
+ /**
+ * Ignore the LoadingBar's custom size, if ignore is true that LoadingBar will ignore it's custom size, use renderer's content size, false otherwise.
+ * @override
+ * @param {Boolean}ignore
+ */
+ ignoreContentAdaptWithSize: function (ignore) {
+ if (!this._scale9Enabled || (this._scale9Enabled && !ignore)) {
+ ccui.Widget.prototype.ignoreContentAdaptWithSize.call(this, ignore);
+ this._prevIgnoreSize = ignore;
+ }
+ },
+
+ /**
+ * Returns the texture size of renderer.
+ * @returns {cc.Size|*}
+ */
+ getVirtualRendererSize:function(){
+ return cc.size(this._barRendererTextureSize);
+ },
+
+ /**
+ * Returns the renderer of ccui.LoadingBar
+ * @override
+ * @returns {cc.Node}
+ */
+ getVirtualRenderer: function () {
+ return this._barRenderer;
+ },
+
+ _barRendererScaleChangedWithSize: function () {
+ var locBarRender = this._barRenderer, locContentSize = this._contentSize;
+ if(this._unifySize){
+ this._totalLength = this._contentSize.width;
+ this.setPercent(this._percent);
+ }else if (this._ignoreSize) {
+ if (!this._scale9Enabled) {
+ this._totalLength = this._barRendererTextureSize.width;
+ locBarRender.setScale(1.0);
+ }
+ } else {
+ this._totalLength = locContentSize.width;
+ if (this._scale9Enabled){
+ this._setScale9Scale();
+ locBarRender.setScale(1.0);
+ } else {
+ var textureSize = this._barRendererTextureSize;
+ if (textureSize.width <= 0.0 || textureSize.height <= 0.0) {
+ locBarRender.setScale(1.0);
+ return;
+ }
+ var scaleX = locContentSize.width / textureSize.width;
+ var scaleY = locContentSize.height / textureSize.height;
+ locBarRender.setScaleX(scaleX);
+ locBarRender.setScaleY(scaleY);
+ }
+ }
+ switch (this._direction) {
+ case ccui.LoadingBar.Type.LEFT:
+ locBarRender.setPosition(0, locContentSize.height * 0.5);
+ break;
+ case ccui.LoadingBar.Type.RIGHT:
+ locBarRender.setPosition(this._totalLength, locContentSize.height * 0.5);
+ break;
+ default:
+ break;
+ }
+ },
+
+ _setScale9Scale: function () {
+ var width = (this._percent) / 100 * this._totalLength;
+ this._barRenderer.setPreferredSize(cc.size(width, this._contentSize.height));
+ },
+
+ /**
+ * Returns the "class name" of widget.
+ * @returns {string}
+ */
+ getDescription: function () {
+ return "LoadingBar";
+ },
+
+ _createCloneInstance: function () {
+ return new ccui.LoadingBar();
+ },
+
+ _copySpecialProperties: function (loadingBar) {
+ if(loadingBar instanceof ccui.LoadingBar){
+ this._prevIgnoreSize = loadingBar._prevIgnoreSize;
+ this.setScale9Enabled(loadingBar._scale9Enabled);
+ this.loadTexture(loadingBar._textureFile, loadingBar._renderBarTexType);
+ this.setCapInsets(loadingBar._capInsets);
+ this.setPercent(loadingBar._percent);
+ this.setDirection(loadingBar._direction);
+ }
+ }
+});
+
+var _p = ccui.LoadingBar.prototype;
+
+// Extended properties
+/** @expose */
+_p.direction;
+cc.defineGetterSetter(_p, "direction", _p.getDirection, _p.setDirection);
+/** @expose */
+_p.percent;
+cc.defineGetterSetter(_p, "percent", _p.getPercent, _p.setPercent);
+
+_p = null;
+
+/**
+ * Allocates and initializes a UILoadingBar.
+ * @deprecated since v3.0, please use new ccui.LoadingBar() instead.
+ * @param {string} textureName
+ * @param {Number} percentage
+ * @return {ccui.LoadingBar}
+ */
+ccui.LoadingBar.create = function (textureName, percentage) {
+ return new ccui.LoadingBar(textureName, percentage);
+};
+
+// Constants
+
+/**
+ * Enum for loadingBar Type
+ * @readonly
+ * @enum {number}
+ */
+ccui.LoadingBar.Type = cc.Enum({
+ /**
+ * The left direction of ccui.LoadingBar.
+ */
+ LEFT: 0,
+ /**
+ * The right direction of ccui.LoadingBar.
+ */
+ RIGHT: 1
+});
+
+/**
+ * The zOrder value of ccui.LoadingBar's renderer.
+ * @constant
+ * @type {number}
+ */
+ccui.LoadingBar.RENDERER_ZORDER = -1;
\ No newline at end of file
diff --git a/extensions/ccui/uiwidgets/UIRichText.js b/extensions/ccui/uiwidgets/UIRichText.js
new file mode 100644
index 0000000000..fd3d57853f
--- /dev/null
+++ b/extensions/ccui/uiwidgets/UIRichText.js
@@ -0,0 +1,742 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+/**
+ * ccui.RichElement is the base class of RichElementText, RichElementImage etc. It has type, tag, color and opacity attributes.
+ * @class
+ * @extends ccui.Class
+ */
+ccui.RichElement = ccui.Class.extend(/** @lends ccui.RichElement# */{
+ _type: 0,
+ _tag: 0,
+ _color: null,
+ _opacity:0,
+ /**
+ * Constructor of ccui.RichElement
+ */
+ ctor: function () {
+ this._type = 0;
+ this._tag = 0;
+ this._color = cc.color(255, 255, 255, 255);
+ },
+
+ /**
+ * Initializes a richElement.
+ * @param {Number} tag
+ * @param {cc.Color} color
+ * @param {Number} opacity
+ */
+ init: function (tag, color, opacity) {
+ this._tag = tag;
+ this._color.r = color.r;
+ this._color.g = color.g;
+ this._color.b = color.b;
+ this._opacity = opacity;
+ if(opacity === undefined)
+ this._color.a = color.a;
+ else
+ this._color.a = opacity;
+ }
+});
+
+/**
+ * The text element for RichText, it has text, fontName, fontSize attributes.
+ * @class
+ * @extends ccui.RichElement
+ */
+ccui.RichElementText = ccui.RichElement.extend(/** @lends ccui.RichElementText# */{
+ _text: "",
+ _fontName: "",
+ _fontSize: 0,
+ /** @type cc.FontDefinition */
+ _fontDefinition: null,
+ /**
+ * Usage Example using FontDefinition:
+ *
+ * var rtEl = new ccui.RichElementText("tag", new cc.FontDefinition({
+ * fillStyle: cc.Color.BLACK,
+ * fontName: "Arial",
+ * fontSize: 12,
+ * fontWeight: "bold",
+ * fontStyle: "normal",
+ * lineHeight: 14
+ * }), 255, "Some Text");
+ *
+ * Constructor of ccui.RichElementText
+ * @param {Number} tag
+ * @param {cc.Color|cc.FontDefinition} colorOrFontDef
+ * @param {Number} opacity
+ * @param {String} text
+ * @param {String} fontName
+ * @param {Number} fontSize
+ */
+ ctor: function (tag, colorOrFontDef, opacity, text, fontName, fontSize) {
+ ccui.RichElement.prototype.ctor.call(this);
+ this._type = ccui.RichElement.TEXT;
+ this._text = "";
+ this._fontName = "";
+ this._fontSize = 0;
+
+ if( colorOrFontDef && colorOrFontDef instanceof cc.FontDefinition)
+ this.initWithStringAndTextDefinition(tag, text, colorOrFontDef, opacity);
+ else
+ fontSize && this.init(tag, colorOrFontDef, opacity, text, fontName, fontSize);
+ },
+
+ /**
+ * Initializes a ccui.RichElementText.
+ * @param {Number} tag
+ * @param {cc.Color} color
+ * @param {Number} opacity
+ * @param {String} text
+ * @param {String} fontName
+ * @param {Number} fontSize
+ * @override
+ */
+ init: function (tag, color, opacity, text, fontName, fontSize) {
+ ccui.RichElement.prototype.init.call(this, tag, color, opacity);
+ this._text = text;
+ this._fontName = fontName;
+ this._fontSize = fontSize;
+ },
+ initWithStringAndTextDefinition: function(tag, text, fontDef, opacity){
+
+ ccui.RichElement.prototype.init.call(this, tag, fontDef.fillStyle, opacity);
+ this._fontDefinition = fontDef;
+ this._text = text;
+ this._fontName = fontDef.fontName;
+ this._fontSize = fontDef.fontSize;
+
+ }
+});
+
+/**
+ * Create a richElementText
+ * @deprecated since v3.0, please use new ccui.RichElementText() instead.
+ * @param {Number} tag
+ * @param {cc.Color} color
+ * @param {Number} opacity
+ * @param {String} text
+ * @param {String} fontName
+ * @param {Number} fontSize
+ * @returns {ccui.RichElementText}
+ */
+ccui.RichElementText.create = function (tag, color, opacity, text, fontName, fontSize) {
+ return new ccui.RichElementText(tag, color, opacity, text, fontName, fontSize);
+};
+
+/**
+ * The image element for RichText, it has filePath, textureRect, textureType attributes.
+ * @class
+ * @extends ccui.RichElement
+ */
+ccui.RichElementImage = ccui.RichElement.extend(/** @lends ccui.RichElementImage# */{
+ _filePath: "",
+ _textureRect: null,
+ _textureType: 0,
+
+ /**
+ * Constructor of ccui.RichElementImage
+ * @param {Number} tag
+ * @param {cc.Color} color
+ * @param {Number} opacity
+ * @param {String} filePath
+ */
+ ctor: function (tag, color, opacity, filePath) {
+ ccui.RichElement.prototype.ctor.call(this);
+ this._type = ccui.RichElement.IMAGE;
+ this._filePath = "";
+ this._textureRect = cc.rect(0, 0, 0, 0);
+ this._textureType = 0;
+
+ filePath !== undefined && this.init(tag, color, opacity, filePath);
+ },
+
+ /**
+ * Initializes a ccui.RichElementImage
+ * @param {Number} tag
+ * @param {cc.Color} color
+ * @param {Number} opacity
+ * @param {String} filePath
+ * @override
+ */
+ init: function (tag, color, opacity, filePath) {
+ ccui.RichElement.prototype.init.call(this, tag, color, opacity);
+ this._filePath = filePath;
+ }
+});
+
+/**
+ * Create a richElementImage
+ * @deprecated since v3.0, please use new ccui.RichElementImage() instead.
+ * @param {Number} tag
+ * @param {cc.Color} color
+ * @param {Number} opacity
+ * @param {String} filePath
+ * @returns {ccui.RichElementImage}
+ */
+ccui.RichElementImage.create = function (tag, color, opacity, filePath) {
+ return new ccui.RichElementImage(tag, color, opacity, filePath);
+};
+
+/**
+ * The custom node element for RichText.
+ * @class
+ * @extends ccui.RichElement
+ */
+ccui.RichElementCustomNode = ccui.RichElement.extend(/** @lends ccui.RichElementCustomNode# */{
+ _customNode: null,
+
+ /**
+ * Constructor of ccui.RichElementCustomNode
+ * @param {Number} tag
+ * @param {cc.Color} color
+ * @param {Number} opacity
+ * @param {cc.Node} customNode
+ */
+ ctor: function (tag, color, opacity, customNode) {
+ ccui.RichElement.prototype.ctor.call(this);
+ this._type = ccui.RichElement.CUSTOM;
+ this._customNode = null;
+
+ customNode !== undefined && this.init(tag, color, opacity, customNode);
+ },
+
+ /**
+ * Initializes a ccui.RichElementCustomNode
+ * @param {Number} tag
+ * @param {cc.Color} color
+ * @param {Number} opacity
+ * @param {cc.Node} customNode
+ * @override
+ */
+ init: function (tag, color, opacity, customNode) {
+ ccui.RichElement.prototype.init.call(this, tag, color, opacity);
+ this._customNode = customNode;
+ }
+});
+
+/**
+ * Create a richElementCustomNode
+ * @deprecated since v3.0, please use new ccui.RichElementCustomNode() instead.
+ * @param {Number} tag
+ * @param {Number} color
+ * @param {Number} opacity
+ * @param {cc.Node} customNode
+ * @returns {ccui.RichElementCustomNode}
+ */
+ccui.RichElementCustomNode.create = function (tag, color, opacity, customNode) {
+ return new ccui.RichElementCustomNode(tag, color, opacity, customNode);
+};
+
+/**
+ * The rich text control of Cocos UI. It receives text, image, and custom node as its children to display.
+ * @class
+ * @extends ccui.Widget
+ */
+ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{
+ _formatTextDirty: false,
+ _richElements: null,
+ _elementRenders: null,
+ _leftSpaceWidth: 0,
+ _verticalSpace: 0,
+ _elementRenderersContainer: null,
+ _lineBreakOnSpace: false,
+ _textHorizontalAlignment: null,
+ _textVerticalAlignment: null,
+
+ /**
+ * create a rich text
+ * Constructor of ccui.RichText. override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
+ * @example
+ * var uiRichText = new ccui.RichTex();
+ */
+ ctor: function () {
+ ccui.Widget.prototype.ctor.call(this);
+ this._formatTextDirty = false;
+ this._richElements = [];
+ this._elementRenders = [];
+ this._leftSpaceWidth = 0;
+ this._verticalSpace = 0;
+ this._textHorizontalAlignment = cc.TextAlignment.LEFT;
+ this._textVerticalAlignment = cc.VerticalTextAlignment.TOP;
+ },
+
+ _initRenderer: function () {
+ this._elementRenderersContainer = new cc.Node();
+ this._elementRenderersContainer.setAnchorPoint(0.5, 0.5);
+ this.addProtectedChild(this._elementRenderersContainer, 0, -1);
+ },
+
+ /**
+ * Insert a element
+ * @param {ccui.RichElement} element
+ * @param {Number} index
+ */
+ insertElement: function (element, index) {
+ this._richElements.splice(index, 0, element);
+ this._formatTextDirty = true;
+ },
+
+ /**
+ * Push a element
+ * @param {ccui.RichElement} element
+ */
+ pushBackElement: function (element) {
+ this._richElements.push(element);
+ this._formatTextDirty = true;
+ },
+
+ /**
+ * Remove element
+ * @param {ccui.RichElement} element
+ */
+ removeElement: function (element) {
+ if (cc.js.isNumber(element))
+ this._richElements.splice(element, 1);
+ else
+ cc.js.array.remove(this._richElements, element);
+ this._formatTextDirty = true;
+ },
+
+ /**
+ * Formats the richText's content.
+ */
+ formatText: function () {
+ if (this._formatTextDirty) {
+ this._elementRenderersContainer.removeAllChildren();
+ this._elementRenders.length = 0;
+ var i, element, locRichElements = this._richElements;
+ if (this._ignoreSize) {
+ this._addNewLine();
+ for (i = 0; i < locRichElements.length; i++) {
+ element = locRichElements[i];
+ var elementRenderer = null;
+ switch (element._type) {
+ case ccui.RichElement.TEXT:
+ if( element._fontDefinition)
+ elementRenderer = new cc.LabelTTF(element._text, element._fontDefinition);
+ else //todo: There may be ambiguous
+ elementRenderer = new cc.LabelTTF(element._text, element._fontName, element._fontSize);
+ break;
+ case ccui.RichElement.IMAGE:
+ elementRenderer = new cc.Sprite(element._filePath);
+ break;
+ case ccui.RichElement.CUSTOM:
+ elementRenderer = element._customNode;
+ break;
+ default:
+ break;
+ }
+ elementRenderer.setColor(element._color);
+ elementRenderer.setOpacity(element._color.a);
+ this._pushToContainer(elementRenderer);
+ }
+ } else {
+ this._addNewLine();
+ for (i = 0; i < locRichElements.length; i++) {
+ element = locRichElements[i];
+ switch (element._type) {
+ case ccui.RichElement.TEXT:
+ if( element._fontDefinition)
+ this._handleTextRenderer(element._text, element._fontDefinition, element._fontDefinition.fontSize, element._fontDefinition.fillStyle);
+ else
+ this._handleTextRenderer(element._text, element._fontName, element._fontSize, element._color);
+ break;
+ case ccui.RichElement.IMAGE:
+ this._handleImageRenderer(element._filePath, element._color, element._color.a);
+ break;
+ case ccui.RichElement.CUSTOM:
+ this._handleCustomRenderer(element._customNode);
+ break;
+ default:
+ break;
+ }
+ }
+ }
+ this.formatRenderers();
+ this._formatTextDirty = false;
+ }
+ },
+ /**
+ * Prepare the child LabelTTF based on line breaking
+ * @param {String} text
+ * @param {String|cc.FontDefinition} fontNameOrFontDef
+ * @param {Number} fontSize
+ * @param {cc.Color} color
+ * @private
+ */
+ _handleTextRenderer: function (text, fontNameOrFontDef, fontSize, color) {
+ if(text === "")
+ return;
+
+ if(text === "\n"){ //Force Line Breaking
+ this._addNewLine();
+ return;
+ }
+
+ var textRenderer = fontNameOrFontDef instanceof cc.FontDefinition ? new cc.LabelTTF(text, fontNameOrFontDef) : new cc.LabelTTF(text, fontNameOrFontDef, fontSize);
+ var textRendererWidth = textRenderer.getContentSize().width;
+ this._leftSpaceWidth -= textRendererWidth;
+ if (this._leftSpaceWidth < 0) {
+ var overstepPercent = (-this._leftSpaceWidth) / textRendererWidth;
+ var curText = text;
+ var stringLength = curText.length;
+ var leftLength = stringLength * (1 - overstepPercent);
+ var leftWords = curText.substr(0, leftLength);
+ var cutWords = curText.substr(leftLength, curText.length - 1);
+ var validLeftLength = leftLength > 0;
+
+ if(this._lineBreakOnSpace){
+ var lastSpaceIndex = leftWords.lastIndexOf(' ');
+ leftLength = lastSpaceIndex === -1 ? leftLength : lastSpaceIndex+1 ;
+ cutWords = curText.substr(leftLength, curText.length - 1);
+ validLeftLength = leftLength > 0 && cutWords !== " ";
+ }
+
+ if (validLeftLength) {
+ var leftRenderer = null;
+ if( fontNameOrFontDef instanceof cc.FontDefinition)
+ {
+ leftRenderer = new cc.LabelTTF(leftWords.substr(0, leftLength), fontNameOrFontDef);
+ leftRenderer.setOpacity(fontNameOrFontDef.fillStyle.a); //TODO: Verify that might not be needed...
+ }else{
+ leftRenderer = new cc.LabelTTF(leftWords.substr(0, leftLength), fontNameOrFontDef, fontSize);
+ leftRenderer.setColor(color);
+ leftRenderer.setOpacity(color.a);
+ }
+ this._pushToContainer(leftRenderer);
+ }
+
+ this._addNewLine();
+ this._handleTextRenderer(cutWords, fontNameOrFontDef, fontSize, color);
+ } else {
+ if( fontNameOrFontDef instanceof cc.FontDefinition) {
+ textRenderer.setOpacity(fontNameOrFontDef.fillStyle.a); //TODO: Verify that might not be needed...
+ }else {
+ textRenderer.setColor(color);
+ textRenderer.setOpacity(color.a);
+ }
+ this._pushToContainer(textRenderer);
+ }
+ },
+
+ _handleImageRenderer: function (filePath, color, opacity) {
+ var imageRenderer = new cc.Sprite(filePath);
+ this._handleCustomRenderer(imageRenderer);
+ },
+
+ _handleCustomRenderer: function (renderer) {
+ var imgSize = renderer.getContentSize();
+ this._leftSpaceWidth -= imgSize.width;
+ if (this._leftSpaceWidth < 0) {
+ this._addNewLine();
+ this._pushToContainer(renderer);
+ this._leftSpaceWidth -= imgSize.width;
+ } else
+ this._pushToContainer(renderer);
+ },
+
+ _addNewLine: function () {
+ this._leftSpaceWidth = this._customSize.width;
+ this._elementRenders.push([]);
+ },
+
+ /**
+ * Formats richText's renderer.
+ */
+ formatRenderers: function () {
+ var newContentSizeHeight = 0, locRenderersContainer = this._elementRenderersContainer;
+ var locElementRenders = this._elementRenders;
+ var i, j, row, nextPosX, l;
+ var lineHeight, offsetX;
+ if (this._ignoreSize) {
+ var newContentSizeWidth = 0;
+ row = locElementRenders[0];
+ nextPosX = 0;
+
+ for (j = 0; j < row.length; j++) {
+ l = row[j];
+ l.setAnchorPoint(cc.p(0, 0));
+ l.setPosition(nextPosX, 0);
+ locRenderersContainer.addChild(l, 1, j);
+
+ lineHeight = l.getLineHeight ? l.getLineHeight() : newContentSizeHeight;
+
+ var iSize = l.getContentSize();
+ newContentSizeWidth += iSize.width;
+ newContentSizeHeight = Math.max(Math.min(newContentSizeHeight, lineHeight), iSize.height);
+ nextPosX += iSize.width;
+ }
+
+ //Text flow horizontal alignment:
+ if(this._textHorizontalAlignment !== cc.TextAlignment.LEFT) {
+ offsetX = 0;
+ if (this._textHorizontalAlignment === cc.TextAlignment.RIGHT)
+ offsetX = this._contentSize.width - nextPosX;
+ else if (this._textHorizontalAlignment === cc.TextAlignment.CENTER)
+ offsetX = (this._contentSize.width - nextPosX) / 2;
+
+ for (j = 0; j < row.length; j++)
+ row[j].x += offsetX;
+ }
+
+ locRenderersContainer.setContentSize(newContentSizeWidth, newContentSizeHeight);
+ } else {
+ var maxHeights = [];
+ for (i = 0; i < locElementRenders.length; i++) {
+ row = locElementRenders[i];
+ var maxHeight = 0;
+ for (j = 0; j < row.length; j++) {
+ l = row[j];
+ lineHeight = l.getLineHeight ? l.getLineHeight() : l.getContentSize().height;
+ maxHeight = Math.max(Math.min(l.getContentSize().height, lineHeight), maxHeight);
+ }
+ maxHeights[i] = maxHeight;
+ newContentSizeHeight += maxHeights[i];
+ }
+
+ var nextPosY = this._customSize.height;
+
+ for (i = 0; i < locElementRenders.length; i++) {
+ row = locElementRenders[i];
+ nextPosX = 0;
+ nextPosY -= (maxHeights[i] + this._verticalSpace);
+
+ for (j = 0; j < row.length; j++) {
+ l = row[j];
+ l.setAnchorPoint(cc.p(0, 0));
+ l.setPosition(cc.p(nextPosX, nextPosY));
+ locRenderersContainer.addChild(l, 1);
+ nextPosX += l.getContentSize().width;
+ }
+ //Text flow alignment(s)
+ if( this._textHorizontalAlignment !== cc.TextAlignment.LEFT || this._textVerticalAlignment !== cc.VerticalTextAlignment.TOP) {
+ offsetX = 0;
+ if (this._textHorizontalAlignment === cc.TextAlignment.RIGHT)
+ offsetX = this._contentSize.width - nextPosX;
+ else if (this._textHorizontalAlignment === cc.TextAlignment.CENTER)
+ offsetX = (this._contentSize.width - nextPosX) / 2;
+
+ var offsetY = 0;
+ if (this._textVerticalAlignment === cc.VerticalTextAlignment.BOTTOM)
+ offsetY = this._customSize.height - newContentSizeHeight;
+ else if (this._textVerticalAlignment === cc.VerticalTextAlignment.CENTER)
+ offsetY = (this._customSize.height - newContentSizeHeight) / 2;
+
+ for (j = 0; j < row.length; j++) {
+ l = row[j];
+ l.x += offsetX;
+ l.y -= offsetY;
+ }
+ }
+ }
+
+ locRenderersContainer.setContentSize(this._contentSize);
+ }
+
+ var length = locElementRenders.length;
+ for (i = 0; i 100)
+ percent = 100;
+ if (percent < 0)
+ percent = 0;
+ this._percent = percent;
+ var res = percent / 100.0;
+ var dis = this._barLength * res;
+ this._slidBallRenderer.setPosition(dis, this._contentSize.height / 2);
+ if (this._scale9Enabled)
+ this._progressBarRenderer.setPreferredSize(cc.size(dis, this._contentSize.height));
+ else {
+ var spriteRenderer = this._progressBarRenderer;
+ var rect = spriteRenderer.getTextureRect();
+ spriteRenderer.setTextureRect(
+ cc.rect(rect.x, rect.y, dis / spriteRenderer._scaleX, rect.height),
+ spriteRenderer.isTextureRectRotated()
+ );
+ }
+ },
+
+ /**
+ * test the point whether location in loadingBar's bounding box.
+ * @override
+ * @param {cc.Vec2} pt
+ * @returns {boolean}
+ */
+ hitTest: function(pt){
+ var nsp = this._slidBallNormalRenderer.convertToNodeSpace(pt);
+ var ballSize = this._slidBallNormalRenderer.getContentSize();
+ var ballRect = cc.rect(0,0, ballSize.width, ballSize.height);
+// if (ballRect.containsPoint(nsp)) {
+ return (nsp.x >= ballRect.x &&
+ nsp.x <= (ballRect.x + ballRect.width) &&
+ nsp.y >= ballRect.y &&
+ nsp.y <= (ballRect.y +ballRect.height));
+ },
+
+ onTouchBegan: function (touch, event) {
+ var pass = ccui.Widget.prototype.onTouchBegan.call(this, touch, event);
+ if (this._hit) {
+ var nsp = this.convertToNodeSpace(this._touchBeganPosition);
+ this.setPercent(this._getPercentWithBallPos(nsp.x));
+ this._percentChangedEvent();
+ }
+ return pass;
+ },
+
+ onTouchMoved: function (touch, event) {
+ var touchPoint = touch.getLocation();
+ var nsp = this.convertToNodeSpace(touchPoint);
+ this.setPercent(this._getPercentWithBallPos(nsp.x));
+ this._percentChangedEvent();
+ },
+
+ onTouchEnded: function (touch, event) {
+ ccui.Widget.prototype.onTouchEnded.call(this, touch, event);
+ },
+
+ onTouchCancelled: function (touch, event) {
+ ccui.Widget.prototype.onTouchCancelled.call(this, touch, event);
+ },
+
+ /**
+ * Returns percent with ball's position.
+ * @param {cc.Vec2} px
+ * @returns {number}
+ */
+ _getPercentWithBallPos: function (px) {
+ return ((px/this._barLength)*100);
+ },
+
+ /**
+ * add event listener
+ * @param {Function} selector
+ * @param {Object} [target=]
+ * @deprecated since v3.0, please use addEventListener instead.
+ */
+ addEventListenerSlider: function (selector, target) {
+ this.addEventListener(selector, target);
+ },
+
+ /**
+ * Adds a callback
+ * @param {Function} selector
+ * @param {Object} [target=]
+ */
+ addEventListener: function(selector, target){
+ this._sliderEventSelector = selector; //when target is undefined, _sliderEventSelector = _eventCallback
+ this._sliderEventListener = target;
+ },
+
+ _percentChangedEvent: function () {
+ if(this._sliderEventSelector){
+ if (this._sliderEventListener)
+ this._sliderEventSelector.call(this._sliderEventListener, this, ccui.Slider.EVENT_PERCENT_CHANGED);
+ else
+ this._sliderEventSelector(this, ccui.Slider.EVENT_PERCENT_CHANGED); // _eventCallback
+ }
+ if (this._ccEventCallback)
+ this._ccEventCallback(this, ccui.Slider.EVENT_PERCENT_CHANGED);
+ },
+
+ /**
+ * Gets the progress direction of slider.
+ * @returns {number}
+ */
+ getPercent: function () {
+ return this._percent;
+ },
+
+ _onSizeChanged: function () {
+ ccui.Widget.prototype._onSizeChanged.call(this);
+ this._barRendererAdaptDirty = true;
+ this._progressBarRendererDirty = true;
+ },
+
+ _adaptRenderers: function(){
+ if (this._barRendererAdaptDirty)
+ {
+ this._barRendererScaleChangedWithSize();
+ this._barRendererAdaptDirty = false;
+ }
+ if (this._progressBarRendererDirty)
+ {
+ this._progressBarRendererScaleChangedWithSize();
+ this._progressBarRendererDirty = false;
+ }
+ },
+
+ /**
+ * Returns the content size of bar renderer.
+ * @returns {cc.Size}
+ */
+ getVirtualRendererSize: function(){
+ return this._barRenderer.getContentSize();
+ },
+
+ /**
+ * Returns the bar renderer.
+ * @returns {cc.Node}
+ */
+ getVirtualRenderer: function () {
+ return this._barRenderer;
+ },
+
+ _barRendererScaleChangedWithSize: function () {
+ if (this._unifySize){
+ this._barLength = this._contentSize.width;
+ this._barRenderer.setPreferredSize(this._contentSize);
+ }else if(this._ignoreSize) {
+ this._barRenderer.setScale(1.0);
+ this._barLength = this._contentSize.width;
+ }else {
+ this._barLength = this._contentSize.width;
+ if (this._scale9Enabled) {
+ this._barRenderer.setPreferredSize(this._contentSize);
+ this._barRenderer.setScale(1.0);
+ } else {
+ var btextureSize = this._barTextureSize;
+ if (btextureSize.width <= 0.0 || btextureSize.height <= 0.0) {
+ this._barRenderer.setScale(1.0);
+ }else{
+ var bscaleX = this._contentSize.width / btextureSize.width;
+ var bscaleY = this._contentSize.height / btextureSize.height;
+ this._barRenderer.setScaleX(bscaleX);
+ this._barRenderer.setScaleY(bscaleY);
+ }
+ }
+ }
+ this._barRenderer.setPosition(this._contentSize.width / 2.0, this._contentSize.height / 2.0);
+ this.setPercent(this._percent);
+ },
+
+ _progressBarRendererScaleChangedWithSize: function () {
+ if(this._unifySize){
+ this._progressBarRenderer.setPreferredSize(this._contentSize);
+ }else if(this._ignoreSize) {
+ if (!this._scale9Enabled) {
+ var ptextureSize = this._progressBarTextureSize;
+ var pscaleX = this._contentSize.width / ptextureSize.width;
+ var pscaleY = this._contentSize.height / ptextureSize.height;
+ this._progressBarRenderer.setScaleX(pscaleX);
+ this._progressBarRenderer.setScaleY(pscaleY);
+ }
+ }
+ else {
+ if (this._scale9Enabled) {
+ this._progressBarRenderer.setPreferredSize(this._contentSize);
+ this._progressBarRenderer.setScale(1);
+ }
+ else {
+ var ptextureSize = this._progressBarTextureSize;
+ if (ptextureSize.width <= 0.0 || ptextureSize.height <= 0.0) {
+ this._progressBarRenderer.setScale(1.0);
+ return;
+ }
+ var pscaleX = this._contentSize.width / ptextureSize.width;
+ var pscaleY = this._contentSize.height / ptextureSize.height;
+ this._progressBarRenderer.setScaleX(pscaleX);
+ this._progressBarRenderer.setScaleY(pscaleY);
+ }
+ }
+ this._progressBarRenderer.setPosition(0.0, this._contentSize.height / 2.0);
+ this.setPercent(this._percent);
+ },
+
+ _onPressStateChangedToNormal: function () {
+ this._slidBallNormalRenderer.setVisible(true);
+ this._slidBallPressedRenderer.setVisible(false);
+ this._slidBallDisabledRenderer.setVisible(false);
+
+ this._slidBallNormalRenderer.setScale(this._sliderBallNormalTextureScaleX, this._sliderBallNormalTextureScaleY);
+ },
+
+ _onPressStateChangedToPressed: function () {
+ if (!this._slidBallPressedTextureFile){
+ this._slidBallNormalRenderer.setScale(this._sliderBallNormalTextureScaleX + this._zoomScale, this._sliderBallNormalTextureScaleY + this._zoomScale);
+ }else{
+ this._slidBallNormalRenderer.setVisible(false);
+ this._slidBallPressedRenderer.setVisible(true);
+ this._slidBallDisabledRenderer.setVisible(false);
+ }
+ },
+
+ _onPressStateChangedToDisabled: function () {
+ if (this._slidBallDisabledTextureFile){
+ this._slidBallNormalRenderer.setVisible(false);
+ this._slidBallDisabledRenderer.setVisible(true);
+ }
+ this._slidBallNormalRenderer.setScale(this._sliderBallNormalTextureScaleX, this._sliderBallNormalTextureScaleY);
+ this._slidBallPressedRenderer.setVisible(false);
+ },
+
+ setZoomScale: function(scale){
+ this._zoomScale = scale;
+ },
+
+ getZoomScale: function(){
+ return this._zoomScale;
+ },
+
+ /**
+ * Returns the "class name" of ccui.LoadingBar.
+ * @returns {string}
+ */
+ getDescription: function () {
+ return "Slider";
+ },
+
+ _createCloneInstance: function () {
+ return new ccui.Slider();
+ },
+
+ _copySpecialProperties: function (slider) {
+ this._prevIgnoreSize = slider._prevIgnoreSize;
+ this.setScale9Enabled(slider._scale9Enabled);
+ this.loadBarTexture(slider._textureFile, slider._barTexType);
+ this.loadProgressBarTexture(slider._progressBarTextureFile, slider._progressBarTexType);
+ this.loadSlidBallTextureNormal(slider._slidBallNormalTextureFile, slider._ballNTexType);
+ this.loadSlidBallTexturePressed(slider._slidBallPressedTextureFile, slider._ballPTexType);
+ this.loadSlidBallTextureDisabled(slider._slidBallDisabledTextureFile, slider._ballDTexType);
+ this.setPercent(slider.getPercent());
+ this._sliderEventListener = slider._sliderEventListener;
+ this._sliderEventSelector = slider._sliderEventSelector;
+ this._zoomScale = slider._zoomScale;
+ this._ccEventCallback = slider._ccEventCallback;
+
+ }
+});
+
+var _p = ccui.Slider.prototype;
+
+// Extended properties
+/** @expose */
+_p.percent;
+cc.defineGetterSetter(_p, "percent", _p.getPercent, _p.setPercent);
+
+_p = null;
+
+/**
+ * allocates and initializes a UISlider.
+ * @deprecated since v3.0, please use new ccui.Slider() instead.
+ * @return {ccui.Slider}
+ */
+ccui.Slider.create = function (barTextureName, normalBallTextureName, resType) {
+ return new ccui.Slider(barTextureName, normalBallTextureName, resType);
+};
+
+// Constant
+//Slider event type
+/**
+ * The percent change event flag of ccui.Slider.
+ * @constant
+ * @type {number}
+ */
+ccui.Slider.EVENT_PERCENT_CHANGED = 0;
+
+//Render zorder
+/**
+ * The zOrder value of ccui.Slider's base bar renderer.
+ * @constant
+ * @type {number}
+ */
+ccui.Slider.BASEBAR_RENDERER_ZORDER = -3;
+/**
+ * The zOrder value of ccui.Slider's progress bar renderer.
+ * @constant
+ * @type {number}
+ */
+ccui.Slider.PROGRESSBAR_RENDERER_ZORDER = -2;
+/**
+ * The zOrder value of ccui.Slider's ball renderer.
+ * @constant
+ * @type {number}
+ */
+ccui.Slider.BALL_RENDERER_ZORDER = -1;
\ No newline at end of file
diff --git a/extensions/ccui/uiwidgets/UIText.js b/extensions/ccui/uiwidgets/UIText.js
new file mode 100644
index 0000000000..a6033364c0
--- /dev/null
+++ b/extensions/ccui/uiwidgets/UIText.js
@@ -0,0 +1,515 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+/**
+ * The text control of Cocos UI.
+ * @class
+ * @extends ccui.Widget
+ *
+ * @property {Number} boundingWidth - Width of the bounding area of label, the real content width is limited by boundingWidth
+ * @property {Number} boundingHeight - Height of the bounding area of label, the real content height is limited by boundingHeight
+ * @property {String} string - The content string of the label
+ * @property {Number} stringLength - <@readonly> The content string length of the label
+ * @property {String} font - The label font with a style string: e.g. "18px Verdana"
+ * @property {String} fontName - The label font name
+ * @property {Number} fontSize - The label font size
+ * @property {cc.TextAlignment} textAlign - Horizontal Alignment of label
+ * @property {cc.VerticalTextAlignment} verticalAlign - Vertical Alignment of label
+ * @property {Boolean} touchScaleEnabled - Indicate whether the label will scale when touching
+ */
+ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
+ _touchScaleChangeEnabled: false,
+ _normalScaleValueX: 1,
+ _normalScaleValueY: 1,
+ _fontName: "Thonburi",
+ _fontSize: 10,
+ _onSelectedScaleOffset:0.5,
+ _labelRenderer: "",
+ _textAreaSize: null,
+ _textVerticalAlignment: 0,
+ _textHorizontalAlignment: 0,
+ _className: "Text",
+ _type: null,
+ _labelRendererAdaptDirty: true,
+
+ /**
+ * allocates and initializes a UILabel.
+ * Constructor of ccui.Text. override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
+ * @param {String} textContent
+ * @param {String} fontName
+ * @param {Number} fontSize
+ * @example
+ * // example
+ * var uiLabel = new ccui.Text();
+ */
+ ctor: function (textContent, fontName, fontSize) {
+ this._type = ccui.Text.Type.SYSTEM;
+ this._textAreaSize = cc.size(0, 0);
+ ccui.Widget.prototype.ctor.call(this);
+
+ fontSize !== undefined && this.init(textContent, fontName, fontSize);
+
+ },
+
+ /**
+ * Initializes a ccui.Text. Please do not call this function by yourself, you should pass the parameters to constructor to initialize it.
+ * @param {String} textContent
+ * @param {String} fontName
+ * @param {Number} fontSize
+ * @returns {boolean}
+ * @override
+ */
+ init: function (textContent, fontName, fontSize) {
+ if (ccui.Widget.prototype.init.call(this)) {
+ if(arguments.length > 0){
+ this.setFontName(fontName);
+ this.setFontSize(fontSize);
+ this.setString(textContent);
+ }else{
+ this.setFontName(this._fontName);
+ }
+ return true;
+ }
+ return false;
+ },
+
+ _initRenderer: function () {
+ this._labelRenderer = new cc.LabelTTF();
+ this.addProtectedChild(this._labelRenderer, ccui.Text.RENDERER_ZORDER, -1);
+ },
+
+ /**
+ * Changes the value of ccui.Text.
+ * @deprecated since v3.0, please use setString() instead.
+ * @param {String} text
+ */
+ setText: function (text) {
+ cc.log("Please use the setString");
+ this.setString(text);
+ },
+
+ /**
+ * Changes the value of ccui.Text.
+ * @param {String} text
+ */
+ setString: function (text) {
+ if(text === this._labelRenderer.getString())
+ return;
+ this._labelRenderer.setString(text);
+ this._updateContentSizeWithTextureSize(this._labelRenderer.getContentSize());
+ this._labelRendererAdaptDirty = true;
+ },
+
+ /**
+ * Gets the string value of ccui.Text.
+ * @deprecated since v3.0, please use getString instead.
+ * @returns {String}
+ */
+ getStringValue: function () {
+ cc.log("Please use the getString");
+ return this._labelRenderer.getString();
+ },
+
+ /**
+ * Gets the string value of ccui.Text.
+ * @returns {String}
+ */
+ getString: function () {
+ return this._labelRenderer.getString();
+ },
+
+ /**
+ * Gets the string length of ccui.Text.
+ * @returns {Number}
+ */
+ getStringLength: function () {
+ return this._labelRenderer.getStringLength();
+ },
+
+ /**
+ * Sets fontSize
+ * @param {Number} size
+ */
+ setFontSize: function (size) {
+ this._labelRenderer.setFontSize(size);
+ this._fontSize = size;
+ this._updateContentSizeWithTextureSize(this._labelRenderer.getContentSize());
+ this._labelRendererAdaptDirty = true;
+ },
+
+ /**
+ * Returns font Size of ccui.Text
+ * @returns {Number}
+ */
+ getFontSize: function () {
+ return this._fontSize;
+ },
+
+ /**
+ * Sets font name
+ * @return {String} name
+ */
+ setFontName: function (name) {
+ this._fontName = name;
+ this._labelRenderer.setFontName(name);
+ this._updateContentSizeWithTextureSize(this._labelRenderer.getContentSize());
+ this._labelRendererAdaptDirty = true;
+ },
+
+ /**
+ * Returns font name of ccui.Text.
+ * @returns {string}
+ */
+ getFontName: function () {
+ return this._fontName;
+ },
+
+ _setFont: function (font) {
+ var res = cc.LabelTTF._fontStyleRE.exec(font);
+ if (res) {
+ this._fontSize = parseInt(res[1]);
+ this._fontName = res[2];
+ this._labelRenderer._setFont(font);
+ this._labelScaleChangedWithSize();
+ }
+ },
+ _getFont: function () {
+ return this._labelRenderer._getFont();
+ },
+
+ /**
+ * Returns the type of ccui.Text.
+ * @returns {null}
+ */
+ getType: function(){
+ return this._type;
+ },
+
+ /**
+ * Sets text Area Size
+ * @param {cc.Size} size
+ */
+ setTextAreaSize: function (size) {
+ this._labelRenderer.setDimensions(size);
+ if (!this._ignoreSize){
+ this._customSize = size;
+ }
+ this._updateContentSizeWithTextureSize(this._labelRenderer.getContentSize());
+ this._labelRendererAdaptDirty = true;
+ },
+
+ /**
+ * Returns renderer's dimension.
+ * @returns {cc.Size}
+ */
+ getTextAreaSize: function(){
+ return this._labelRenderer.getDimensions();
+ },
+
+ /**
+ * Sets Horizontal Alignment of cc.LabelTTF
+ * @param {cc.TextAlignment} alignment Horizontal Alignment
+ */
+ setTextHorizontalAlignment: function (alignment) {
+ this._labelRenderer.setHorizontalAlignment(alignment);
+ this._updateContentSizeWithTextureSize(this._labelRenderer.getContentSize());
+ this._labelRendererAdaptDirty = true;
+ },
+
+ /**
+ * Returns Horizontal Alignment of label
+ * @returns {cc.TextAlignment}
+ */
+ getTextHorizontalAlignment: function () {
+ return this._labelRenderer.getHorizontalAlignment();
+ },
+
+ /**
+ * Sets Vertical Alignment of label
+ * @param {cc.VerticalTextAlignment} alignment
+ */
+ setTextVerticalAlignment: function (alignment) {
+ this._labelRenderer.setVerticalAlignment(alignment);
+ this._updateContentSizeWithTextureSize(this._labelRenderer.getContentSize());
+ this._labelRendererAdaptDirty = true;
+ },
+
+ /**
+ * Gets text vertical alignment.
+ * @returns {cc.VerticalTextAlignment}
+ */
+ getTextVerticalAlignment: function () {
+ return this._labelRenderer.getVerticalAlignment();
+ },
+
+ /**
+ * Sets the touch scale enabled of label.
+ * @param {Boolean} enable
+ */
+ setTouchScaleChangeEnabled: function (enable) {
+ this._touchScaleChangeEnabled = enable;
+ },
+
+ /**
+ * Gets the touch scale enabled of label.
+ * @returns {Boolean}
+ */
+ isTouchScaleChangeEnabled: function () {
+ return this._touchScaleChangeEnabled;
+ },
+
+ _onPressStateChangedToNormal: function () {
+ if (!this._touchScaleChangeEnabled)
+ return;
+ this._labelRenderer.setScaleX(this._normalScaleValueX);
+ this._labelRenderer.setScaleY(this._normalScaleValueY);
+ },
+
+ _onPressStateChangedToPressed: function () {
+ if (!this._touchScaleChangeEnabled)
+ return;
+ this._labelRenderer.setScaleX(this._normalScaleValueX + this._onSelectedScaleOffset);
+ this._labelRenderer.setScaleY(this._normalScaleValueY + this._onSelectedScaleOffset);
+ },
+
+ _onPressStateChangedToDisabled: function () {
+ },
+
+ _onSizeChanged: function () {
+ ccui.Widget.prototype._onSizeChanged.call(this);
+ this._labelRendererAdaptDirty = true;
+ },
+
+ _adaptRenderers: function(){
+ if (this._labelRendererAdaptDirty) {
+ this._labelScaleChangedWithSize();
+ this._labelRendererAdaptDirty = false;
+ }
+ },
+
+ /**
+ * Returns the renderer's content size.
+ * @override
+ * @returns {cc.Size}
+ */
+ getVirtualRendererSize: function(){
+ return this._labelRenderer.getContentSize();
+ },
+
+ /**
+ * Returns the renderer of ccui.Text.
+ * @returns {cc.Node}
+ */
+ getVirtualRenderer: function () {
+ return this._labelRenderer;
+ },
+
+ //@since v3.3
+ getAutoRenderSize: function(){
+ var virtualSize = this._labelRenderer.getContentSize();
+ if (!this._ignoreSize) {
+ this._labelRenderer.setDimensions(0, 0);
+ virtualSize = this._labelRenderer.getContentSize();
+ this._labelRenderer.setDimensions(this._contentSize.width, this._contentSize.height);
+ }
+ return virtualSize;
+ },
+
+ _labelScaleChangedWithSize: function () {
+ var locContentSize = this._contentSize;
+ if (this._ignoreSize) {
+ this._labelRenderer.setDimensions(0,0);
+ this._labelRenderer.setScale(1.0);
+ this._normalScaleValueX = this._normalScaleValueY = 1;
+ } else {
+ this._labelRenderer.setDimensions(cc.size(locContentSize.width, locContentSize.height));
+ var textureSize = this._labelRenderer.getContentSize();
+ if (textureSize.width <= 0.0 || textureSize.height <= 0.0) {
+ this._labelRenderer.setScale(1.0);
+ return;
+ }
+ var scaleX = locContentSize.width / textureSize.width;
+ var scaleY = locContentSize.height / textureSize.height;
+ this._labelRenderer.setScaleX(scaleX);
+ this._labelRenderer.setScaleY(scaleY);
+ this._normalScaleValueX = scaleX;
+ this._normalScaleValueY = scaleY;
+ }
+ this._labelRenderer.setPosition(locContentSize.width / 2.0, locContentSize.height / 2.0);
+ },
+
+ /**
+ * Returns the "class name" of ccui.Text.
+ * @returns {string}
+ */
+ getDescription: function () {
+ return "Label";
+ },
+
+ /**
+ * Enables shadow style and sets color, offset and blur radius styles.
+ * @param {cc.Color} shadowColor
+ * @param {cc.Size} offset
+ * @param {Number} blurRadius
+ */
+ enableShadow: function(shadowColor, offset, blurRadius){
+ this._labelRenderer.enableShadow(shadowColor, offset, blurRadius);
+ },
+
+ /**
+ * Enables outline style and sets outline's color and size.
+ * @param {cc.Color} outlineColor
+ * @param {cc.Size} outlineSize
+ */
+ enableOutline: function(outlineColor, outlineSize){
+ this._labelRenderer.enableStroke(outlineColor, outlineSize);
+ },
+
+ /**
+ * Enables glow color
+ * @param glowColor
+ */
+ enableGlow: function(glowColor){
+ if (this._type === ccui.Text.Type.TTF)
+ this._labelRenderer.enableGlow(glowColor);
+ },
+
+ /**
+ * Disables renderer's effect.
+ */
+ disableEffect: function(){
+ if(this._labelRenderer.disableEffect)
+ this._labelRenderer.disableEffect();
+ },
+
+ _createCloneInstance: function () {
+ return new ccui.Text();
+ },
+
+ _copySpecialProperties: function (uiLabel) {
+ if(uiLabel instanceof ccui.Text){
+ this.setFontName(uiLabel._fontName);
+ this.setFontSize(uiLabel.getFontSize());
+ this.setString(uiLabel.getString());
+ this.setTouchScaleChangeEnabled(uiLabel.touchScaleEnabled);
+ this.setTextAreaSize(uiLabel._textAreaSize);
+ this.setTextHorizontalAlignment(uiLabel._labelRenderer.getHorizontalAlignment());
+ this.setTextVerticalAlignment(uiLabel._labelRenderer.getVerticalAlignment());
+ this.setContentSize(uiLabel.getContentSize());
+ this.setTextColor(uiLabel.getTextColor());
+ }
+ },
+
+ _setBoundingWidth: function (value) {
+ this._textAreaSize.width = value;
+ this._labelRenderer._setBoundingWidth(value);
+ this._labelScaleChangedWithSize();
+ },
+ _setBoundingHeight: function (value) {
+ this._textAreaSize.height = value;
+ this._labelRenderer._setBoundingHeight(value);
+ this._labelScaleChangedWithSize();
+ },
+ _getBoundingWidth: function () {
+ return this._textAreaSize.width;
+ },
+ _getBoundingHeight: function () {
+ return this._textAreaSize.height;
+ },
+
+ _changePosition: function(){
+ this._adaptRenderers();
+ },
+
+ setColor: function(color){
+ cc.ProtectedNode.prototype.setColor.call(this, color);
+ this._labelRenderer.setColor(color);
+ },
+
+ setTextColor: function(color){
+ this._labelRenderer.setFontFillColor(color);
+ },
+
+ getTextColor: function(){
+ return this._labelRenderer._getFillStyle();
+ }
+});
+
+var _p = ccui.Text.prototype;
+
+// Extended properties
+/** @expose */
+_p.boundingWidth;
+cc.defineGetterSetter(_p, "boundingWidth", _p._getBoundingWidth, _p._setBoundingWidth);
+/** @expose */
+_p.boundingHeight;
+cc.defineGetterSetter(_p, "boundingHeight", _p._getBoundingHeight, _p._setBoundingHeight);
+/** @expose */
+_p.string;
+cc.defineGetterSetter(_p, "string", _p.getString, _p.setString);
+/** @expose */
+_p.stringLength;
+cc.defineGetterSetter(_p, "stringLength", _p.getStringLength);
+/** @expose */
+_p.font;
+cc.defineGetterSetter(_p, "font", _p._getFont, _p._setFont);
+/** @expose */
+_p.fontSize;
+cc.defineGetterSetter(_p, "fontSize", _p.getFontSize, _p.setFontSize);
+/** @expose */
+_p.fontName;
+cc.defineGetterSetter(_p, "fontName", _p.getFontName, _p.setFontName);
+/** @expose */
+_p.textAlign;
+cc.defineGetterSetter(_p, "textAlign", _p.getTextHorizontalAlignment, _p.setTextHorizontalAlignment);
+/** @expose */
+_p.verticalAlign;
+cc.defineGetterSetter(_p, "verticalAlign", _p.getTextVerticalAlignment, _p.setTextVerticalAlignment);
+
+_p = null;
+
+/**
+ * allocates and initializes a UILabel.
+ * @deprecated since v3.0, please use new ccui.Text() instead.
+ * @return {ccui.Text}
+ */
+ccui.Label = ccui.Text.create = function (textContent, fontName, fontSize) {
+ return new ccui.Text(textContent, fontName, fontSize);
+};
+
+/**
+ * The zOrder value of ccui.Text's renderer.
+ * @constant
+ * @type {number}
+ */
+ccui.Text.RENDERER_ZORDER = -1;
+
+/**
+ * @ignore
+ */
+ccui.Text.Type = {
+ SYSTEM: 0,
+ TTF: 1
+};
\ No newline at end of file
diff --git a/extensions/ccui/uiwidgets/UITextAtlas.js b/extensions/ccui/uiwidgets/UITextAtlas.js
new file mode 100644
index 0000000000..bb7e0d27ca
--- /dev/null
+++ b/extensions/ccui/uiwidgets/UITextAtlas.js
@@ -0,0 +1,229 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+/**
+ * The text atlas control of Cocos UI.
+ * @class
+ * @extends ccui.Widget
+ *
+ * @property {String} string - Content string of the label
+ */
+ccui.TextAtlas = ccui.Widget.extend(/** @lends ccui.TextAtlas# */{
+ _labelAtlasRenderer: null,
+ _stringValue: "",
+ _charMapFileName: "",
+ _itemWidth: 0,
+ _itemHeight: 0,
+ _startCharMap: "",
+ _className: "TextAtlas",
+ _labelAtlasRendererAdaptDirty: null,
+
+ /**
+ * Allocates and initializes a UILabelAtlas.
+ * Constructor of ccui.TextAtlas, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
+ * @param {String} stringValue
+ * @param {String} charMapFile
+ * @param {number} itemWidth
+ * @param {number} itemHeight
+ * @param {String} startCharMap
+ * @example
+ * // example
+ * var uiLabelAtlas = new ccui.TextAtlas();
+ */
+ ctor: function (stringValue, charMapFile, itemWidth, itemHeight, startCharMap) {
+ ccui.Widget.prototype.ctor.call(this);
+ startCharMap !== undefined && this.setProperty(stringValue, charMapFile, itemWidth, itemHeight, startCharMap);
+ },
+
+ _initRenderer: function () {
+ this._labelAtlasRenderer = new cc.LabelAtlas();
+ this._labelAtlasRenderer.setAnchorPoint(cc.p(0.5, 0.5));
+ this.addProtectedChild(this._labelAtlasRenderer, ccui.TextAtlas.RENDERER_ZORDER, -1);
+ },
+
+ /**
+ * initializes the UILabelAtlas with a string, a char map file(the atlas), the width and height of each element and the starting char of the atlas
+ * @param {String} stringValue
+ * @param {String} charMapFile
+ * @param {number} itemWidth
+ * @param {number} itemHeight
+ * @param {String} startCharMap
+ */
+ setProperty: function (stringValue, charMapFile, itemWidth, itemHeight, startCharMap) {
+ this._stringValue = stringValue;
+ this._charMapFileName = charMapFile;
+ this._itemWidth = itemWidth;
+ this._itemHeight = itemHeight;
+ this._startCharMap = startCharMap;
+
+ this._labelAtlasRenderer.initWithString(
+ stringValue,
+ this._charMapFileName,
+ this._itemWidth,
+ this._itemHeight,
+ this._startCharMap[0]
+ );
+
+ this._updateContentSizeWithTextureSize(this._labelAtlasRenderer.getContentSize());
+ this._labelAtlasRendererAdaptDirty = true;
+ },
+
+ /**
+ * Sets string value for ui text atlas.
+ * @param {String} value
+ */
+ setString: function (value) {
+ if(value === this._labelAtlasRenderer.getString())
+ return;
+ this._stringValue = value;
+ this._labelAtlasRenderer.setString(value);
+ this._updateContentSizeWithTextureSize(this._labelAtlasRenderer.getContentSize());
+ this._labelAtlasRendererAdaptDirty = true;
+ },
+
+ /**
+ * Sets string value for text atlas.
+ * @deprecated since v3.0, please use setString instead.
+ * @param {String} value
+ */
+ setStringValue: function (value) {
+ cc.log("Please use the setString");
+ this.setString(value);
+ },
+
+ /**
+ * get string value for text atlas.
+ * @deprecated since v3.0, please use getString instead.
+ * @returns {String}
+ */
+ getStringValue: function () {
+ cc.log("Please use the getString");
+ return this.getString();
+ },
+
+ /**
+ * get string value for ui text atlas.
+ * @returns {String}
+ */
+ getString: function () {
+ return this._labelAtlasRenderer.getString();
+ },
+
+ /**
+ * Returns the length of string.
+ * @returns {*|Number|long|int}
+ */
+ getStringLength: function(){
+ return this._labelAtlasRenderer.getStringLength();
+ },
+
+ _onSizeChanged: function () {
+ ccui.Widget.prototype._onSizeChanged.call(this);
+ this._labelAtlasRendererAdaptDirty = true;
+ },
+
+ _adaptRenderers: function(){
+ if (this._labelAtlasRendererAdaptDirty){
+ this._labelAtlasScaleChangedWithSize();
+ this._labelAtlasRendererAdaptDirty = false;
+ }
+ },
+
+ /**
+ * Returns the renderer's content size
+ * @overrider
+ * @returns {cc.Size}
+ */
+ getVirtualRendererSize: function(){
+ return this._labelAtlasRenderer.getContentSize();
+ },
+
+ /**
+ * Returns the renderer of ccui.TextAtlas.
+ * @returns {cc.Node}
+ */
+ getVirtualRenderer: function () {
+ return this._labelAtlasRenderer;
+ },
+
+ _labelAtlasScaleChangedWithSize: function () {
+ var locRenderer = this._labelAtlasRenderer;
+ if (this._ignoreSize) {
+ locRenderer.setScale(1.0);
+ } else {
+ var textureSize = locRenderer.getContentSize();
+ if (textureSize.width <= 0.0 || textureSize.height <= 0.0) {
+ locRenderer.setScale(1.0);
+ return;
+ }
+ locRenderer.setScaleX(this._contentSize.width / textureSize.width);
+ locRenderer.setScaleY(this._contentSize.height / textureSize.height);
+ }
+ locRenderer.setPosition(this._contentSize.width / 2.0, this._contentSize.height / 2.0);
+ },
+
+ /**
+ * Returns the "class name" of ccui.TextAtlas.
+ * @returns {string}
+ */
+ getDescription: function () {
+ return "LabelAtlas";
+ },
+
+ _copySpecialProperties: function (labelAtlas) {
+ if (labelAtlas){
+ this.setProperty(labelAtlas._stringValue, labelAtlas._charMapFileName, labelAtlas._itemWidth, labelAtlas._itemHeight, labelAtlas._startCharMap);
+ }
+ },
+
+ _createCloneInstance: function () {
+ return new ccui.TextAtlas();
+ }
+});
+
+var _p = ccui.TextAtlas.prototype;
+
+// Extended properties
+/** @expose */
+_p.string;
+cc.defineGetterSetter(_p, "string", _p.getString, _p.setString);
+
+_p = null;
+
+/**
+ * allocates and initializes a UILabelAtlas.
+ * @deprecated since v3.0, please use new ccui.TextAtlas() instead.
+ * @return {ccui.TextAtlas}
+ */
+ccui.TextAtlas.create = function (stringValue, charMapFile, itemWidth, itemHeight, startCharMap) {
+ return new ccui.TextAtlas(stringValue, charMapFile, itemWidth, itemHeight, startCharMap);
+};
+
+// Constants
+/**
+ * The zOrder value of ccui.TextAtlas's renderer.
+ * @type {number}
+ */
+ccui.TextAtlas.RENDERER_ZORDER = -1;
\ No newline at end of file
diff --git a/extensions/ccui/uiwidgets/UITextBMFont.js b/extensions/ccui/uiwidgets/UITextBMFont.js
new file mode 100644
index 0000000000..09d965a18e
--- /dev/null
+++ b/extensions/ccui/uiwidgets/UITextBMFont.js
@@ -0,0 +1,216 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+/**
+ * The TextBMFont control of Cocos UI, it rendered by LabelBMFont.
+ * @class
+ * @extends ccui.Widget
+ *
+ * @property {String} string - Content string of the label
+ */
+ccui.LabelBMFont = ccui.TextBMFont = ccui.Widget.extend(/** @lends ccui.TextBMFont# */{
+ _labelBMFontRenderer: null,
+ _fntFileHasInit: false,
+ _fntFileName: "",
+ _stringValue: "",
+ _className: "TextBMFont",
+ _labelBMFontRendererAdaptDirty: true,
+
+ /**
+ * Allocates and initializes a TextBMFont.
+ * Constructor of ccui.TextBMFont. override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
+ * @param {String} text
+ * @param {String} filename
+ * @example
+ * // example
+ * var uiLabelBMFont = new ccui.TextBMFont();
+ */
+ ctor: function (text, filename) {
+ ccui.Widget.prototype.ctor.call(this);
+
+ if(filename != undefined){
+ this.setFntFile(filename);
+ this.setString(text);
+ }
+ },
+
+ _initRenderer: function () {
+ this._labelBMFontRenderer = new cc.LabelBMFont();
+ this.addProtectedChild(this._labelBMFontRenderer, ccui.TextBMFont.RENDERER_ZORDER, -1);
+ },
+
+ /**
+ * Initializes a bitmap font atlas with an initial string and the FNT file
+ * @param {String} fileName
+ */
+ setFntFile: function (fileName) {
+ if (!fileName)
+ return;
+ this._fntFileName = fileName;
+
+ this._fntFileHasInit = true;
+ this._labelBMFontRenderer.initWithString(this._stringValue, fileName);
+ this._updateContentSizeWithTextureSize(this._labelBMFontRenderer.getContentSize());
+ this._labelBMFontRendererAdaptDirty = true;
+
+ var _self = this;
+ var locRenderer = _self._labelBMFontRenderer;
+ if(!locRenderer._textureLoaded){
+ locRenderer.once("load", function () {
+ _self.setFntFile(_self._fntFileName);
+ });
+ }
+ },
+
+ /**
+ * Sets string value for TextBMFont
+ * @deprecated since v3.0, please use setString instead.
+ * @param {String} value
+ */
+ setText: function (value) {
+ cc.log("Please use the setString");
+ this.setString(value);
+ },
+
+ /**
+ * Sets string value for TextBMFont
+ * @param {String} value
+ */
+ setString: function (value) {
+ if(value === this._labelBMFontRenderer.getString())
+ return;
+ this._stringValue = value;
+ this._labelBMFontRenderer.setString(value);
+ if (!this._fntFileHasInit)
+ return;
+ this._updateContentSizeWithTextureSize(this._labelBMFontRenderer.getContentSize());
+ this._labelBMFontRendererAdaptDirty = true;
+ },
+
+ /**
+ * Returns string value for TextBMFont.
+ * @returns {String}
+ */
+ getString: function () {
+ return this._stringValue;
+ },
+
+ /**
+ * Returns the length of TextBMFont's string.
+ * @returns {Number}
+ */
+ getStringLength: function(){
+ return this._labelBMFontRenderer.getStringLength();
+ },
+
+ _onSizeChanged: function () {
+ ccui.Widget.prototype._onSizeChanged.call(this);
+ this._labelBMFontRendererAdaptDirty = true;
+ },
+
+ _adaptRenderers: function(){
+ if (this._labelBMFontRendererAdaptDirty){
+ this._labelBMFontScaleChangedWithSize();
+ this._labelBMFontRendererAdaptDirty = false;
+ }
+ },
+
+ /**
+ * Returns TextBMFont's content size
+ * @override
+ * @returns {cc.Size}
+ */
+ getVirtualRendererSize: function(){
+ return this._labelBMFontRenderer.getContentSize();
+ },
+
+ /**
+ * Returns the renderer of TextBMFont
+ * @override
+ * @returns {cc.Node}
+ */
+ getVirtualRenderer: function () {
+ return this._labelBMFontRenderer;
+ },
+
+ _labelBMFontScaleChangedWithSize: function () {
+ var locRenderer = this._labelBMFontRenderer;
+ if (this._ignoreSize)
+ locRenderer.setScale(1.0);
+ else {
+ var textureSize = locRenderer.getContentSize();
+ if (textureSize.width <= 0.0 || textureSize.height <= 0.0) {
+ locRenderer.setScale(1.0);
+ return;
+ }
+ locRenderer.setScaleX(this._contentSize.width / textureSize.width);
+ locRenderer.setScaleY(this._contentSize.height / textureSize.height);
+ }
+ locRenderer.setPosition(this._contentSize.width / 2.0, this._contentSize.height / 2.0);
+ },
+
+ /**
+ * Returns the "class name" of ccui.TextBMFont.
+ * @returns {string}
+ */
+ getDescription: function () {
+ return "TextBMFont";
+ },
+
+ _createCloneInstance: function () {
+ return new ccui.TextBMFont();
+ },
+
+ _copySpecialProperties: function (labelBMFont) {
+ this.setFntFile(labelBMFont._fntFileName);
+ this.setString(labelBMFont._stringValue);
+ }
+});
+
+var _p = ccui.TextBMFont.prototype;
+
+// Extended properties
+/** @expose */
+_p.string;
+cc.defineGetterSetter(_p, "string", _p.getString, _p.setString);
+
+_p = null;
+
+/**
+ * allocates and initializes a UILabelBMFont.
+ * @deprecated since v3.0, please use new ccui.TextBMFont() instead.
+ * @return {ccui.TextBMFont}
+ */
+ccui.TextBMFont.create = function (text, filename) {
+ return new ccui.TextBMFont(text, filename);
+};
+
+// Constants
+/**
+ * The zOrder value of TextBMFont's renderer.
+ * @constant
+ * @type {number}
+ */
+ccui.TextBMFont.RENDERER_ZORDER = -1;
diff --git a/extensions/ccui/uiwidgets/UITextField.js b/extensions/ccui/uiwidgets/UITextField.js
new file mode 100644
index 0000000000..e50884f6f6
--- /dev/null
+++ b/extensions/ccui/uiwidgets/UITextField.js
@@ -0,0 +1,915 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+/**
+ * @ignore
+ */
+//it's a private class, it's a renderer of ccui.TextField.
+ccui._TextFieldRenderer = cc.TextFieldTTF.extend({
+ _maxLengthEnabled: false,
+ _maxLength: 0,
+ _passwordEnabled: false,
+ _passwordStyleText: "",
+ _attachWithIME: false,
+ _detachWithIME: false,
+ _insertText: false,
+ _deleteBackward: false,
+ _className: "_TextFieldRenderer",
+
+ ctor: function () {
+ cc.TextFieldTTF.prototype.ctor.call(this);
+ this._maxLengthEnabled = false;
+ this._maxLength = 0;
+ this._passwordEnabled = false;
+ this._passwordStyleText = "*";
+ this._attachWithIME = false;
+ this._detachWithIME = false;
+ this._insertText = false;
+ this._deleteBackward = false;
+ },
+
+ onEnter: function () {
+ cc.TextFieldTTF.prototype.onEnter.call(this);
+ cc.TextFieldTTF.prototype.setDelegate.call(this, this);
+ },
+
+ onTextFieldAttachWithIME: function (sender) {
+ this.setAttachWithIME(true);
+ return false;
+ },
+
+ onTextFieldInsertText: function (sender, text, len) {
+ if (len === 1 && text === "\n")
+ return false;
+
+ this.setInsertText(true);
+ return (this._maxLengthEnabled) && (cc.TextFieldTTF.prototype.getCharCount.call(this) >= this._maxLength);
+ },
+
+ onTextFieldDeleteBackward: function (sender, delText, nLen) {
+ this.setDeleteBackward(true);
+ return false;
+ },
+
+ onTextFieldDetachWithIME: function (sender) {
+ this.setDetachWithIME(true);
+ return false;
+ },
+
+ insertText: function (text, len) {
+ var input_text = text;
+
+ if (text !== "\n"){
+ if (this._maxLengthEnabled){
+ var text_count = this.getString().length;
+ if (text_count >= this._maxLength){
+ // password
+ if (this._passwordEnabled)
+ this.setPasswordText(this.getString());
+ return;
+ }
+ }
+ }
+ cc.TextFieldTTF.prototype.insertText.call(this, input_text, len);
+
+ // password
+ if (this._passwordEnabled && cc.TextFieldTTF.prototype.getCharCount.call(this) > 0)
+ this.setPasswordText(this.getString());
+ },
+
+ deleteBackward: function () {
+ cc.TextFieldTTF.prototype.deleteBackward.call(this);
+
+ if (cc.TextFieldTTF.prototype.getCharCount.call(this) > 0 && this._passwordEnabled)
+ this.setPasswordText(this._inputText);
+ },
+
+ openIME: function () {
+ cc.TextFieldTTF.prototype.attachWithIME.call(this);
+ },
+
+ closeIME: function () {
+ cc.TextFieldTTF.prototype.detachWithIME.call(this);
+ },
+
+ setMaxLengthEnabled: function (enable) {
+ this._maxLengthEnabled = enable;
+ },
+
+ isMaxLengthEnabled: function () {
+ return this._maxLengthEnabled;
+ },
+
+ setMaxLength: function (length) {
+ this._maxLength = length;
+ },
+
+ getMaxLength: function () {
+ return this._maxLength;
+ },
+
+ getCharCount: function () {
+ return cc.TextFieldTTF.prototype.getCharCount.call(this);
+ },
+
+ setPasswordEnabled: function (enable) {
+ this._passwordEnabled = enable;
+ },
+
+ isPasswordEnabled: function () {
+ return this._passwordEnabled;
+ },
+
+ setPasswordStyleText: function (styleText) {
+ if (styleText.length > 1)
+ return;
+ var header = styleText.charCodeAt(0);
+ if (header < 33 || header > 126)
+ return;
+ this._passwordStyleText = styleText;
+ },
+
+ setPasswordText: function (text) {
+ var tempStr = "";
+ var text_count = text.length;
+ var max = text_count;
+
+ if (this._maxLengthEnabled && text_count > this._maxLength)
+ max = this._maxLength;
+
+ for (var i = 0; i < max; ++i)
+ tempStr += this._passwordStyleText;
+
+ cc.LabelTTF.prototype.setString.call(this, tempStr);
+ },
+
+ setAttachWithIME: function (attach) {
+ this._attachWithIME = attach;
+ },
+
+ getAttachWithIME: function () {
+ return this._attachWithIME;
+ },
+
+ setDetachWithIME: function (detach) {
+ this._detachWithIME = detach;
+ },
+
+ getDetachWithIME: function () {
+ return this._detachWithIME;
+ },
+
+ setInsertText: function (insert) {
+ this._insertText = insert;
+ },
+
+ getInsertText: function () {
+ return this._insertText;
+ },
+
+ setDeleteBackward: function (deleteBackward) {
+ this._deleteBackward = deleteBackward;
+ },
+
+ getDeleteBackward: function () {
+ return this._deleteBackward;
+ },
+
+ onDraw: function (sender) {
+ return false;
+ }
+});
+
+ccui._TextFieldRenderer.create = function (placeholder, fontName, fontSize) {
+ var ret = new ccui._TextFieldRenderer();
+ if (ret && ret.initWithString("", fontName, fontSize)) {
+ if (placeholder)
+ ret.setPlaceHolder(placeholder);
+ return ret;
+ }
+ return null;
+};
+
+/**
+ *
+ * @class
+ * @extends ccui.Widget
+ *
+ * @property {String} string - The content string of the label
+ * @property {String} placeHolder - The place holder of the text field
+ * @property {String} font - The text field font with a style string: e.g. "18px Verdana"
+ * @property {String} fontName - The text field font name
+ * @property {Number} fontSize - The text field font size
+ * @property {Boolean} maxLengthEnabled - Indicate whether max length limit is enabled
+ * @property {Number} maxLength - The max length of the text field
+ * @property {Boolean} passwordEnabled - Indicate whether the text field is for entering password
+ */
+ccui.TextField = ccui.Widget.extend(/** @lends ccui.TextField# */{
+ _textFieldRenderer: null,
+ _touchWidth: 0,
+ _touchHeight: 0,
+ _useTouchArea: false,
+ _textFieldEventListener: null,
+ _textFieldEventSelector: null,
+ _passwordStyleText: "",
+ _textFieldRendererAdaptDirty: true,
+ _fontName: "",
+ _fontSize: 12,
+
+ _ccEventCallback: null,
+
+ /**
+ * allocates and initializes a UITextField.
+ * Constructor of ccui.TextField. override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
+ * @param {string} placeholder
+ * @param {string} fontName
+ * @param {Number} fontSize
+ * @example
+ * // example
+ * var uiTextField = new ccui.TextField();
+ */
+ ctor: function (placeholder, fontName, fontSize) {
+ ccui.Widget.prototype.ctor.call(this);
+ if (fontName)
+ this.setFontName(fontName);
+ if (fontSize)
+ this.setFontSize(fontSize);
+ if (placeholder)
+ this.setPlaceHolder(placeholder);
+ },
+
+ /**
+ * Initializes a ccui.TextField. Please do not call this function by yourself, you should pass the parameters to constructor to initialize it.
+ * @returns {boolean}
+ * @override
+ */
+ init: function(){
+ if(ccui.Widget.prototype.init.call(this)){
+ this.setTouchEnabled(true);
+ return true;
+ }
+ return false;
+ },
+
+ /**
+ * Calls parent class' onEnter and schedules update function.
+ * @override
+ */
+ onEnter: function () {
+ ccui.Widget.prototype.onEnter.call(this);
+ this.scheduleUpdate();
+ },
+
+ _initRenderer: function () {
+ this._textFieldRenderer = ccui._TextFieldRenderer.create("input words here", "Thonburi", 20);
+ this.addProtectedChild(this._textFieldRenderer, ccui.TextField.RENDERER_ZORDER, -1);
+ },
+
+ /**
+ * Sets touch size of ccui.TextField.
+ * @param {cc.Size} size
+ */
+ setTouchSize: function (size) {
+ this._touchWidth = size.width;
+ this._touchHeight = size.height;
+ },
+
+ /**
+ * Sets whether use touch area.
+ * @param enable
+ */
+ setTouchAreaEnabled: function(enable){
+ this._useTouchArea = enable;
+ },
+
+ /**
+ * Checks a point if is in ccui.TextField's space
+ * @param {cc.Vec2} pt
+ * @returns {boolean}
+ */
+ hitTest: function(pt){
+ if (this._useTouchArea) {
+ var nsp = this.convertToNodeSpace(pt);
+ var bb = cc.rect(
+ -this._touchWidth * this._anchorPoint.x,
+ -this._touchHeight * this._anchorPoint.y,
+ this._touchWidth, this._touchHeight
+ );
+
+ return ( nsp.x >= bb.x && nsp.x <= bb.x + bb.width &&
+ nsp.y >= bb.y && nsp.y <= bb.y + bb.height );
+ } else
+ return ccui.Widget.prototype.hitTest.call(this, pt);
+ },
+
+ /**
+ * Returns touch size of ccui.TextField.
+ * @returns {cc.Size}
+ */
+ getTouchSize: function () {
+ return cc.size(this._touchWidth, this._touchHeight);
+ },
+
+ /**
+ * Changes the string value of textField.
+ * @deprecated since v3.0, please use setString instead.
+ * @param {String} text
+ */
+ setText: function (text) {
+ cc.log("Please use the setString");
+ this.setString(text);
+ },
+
+ /**
+ * Changes the string value of textField.
+ * @param {String} text
+ */
+ setString: function (text) {
+ if (text == null)
+ return;
+
+ text = String(text);
+ if (this.isMaxLengthEnabled())
+ text = text.substr(0, this.getMaxLength());
+ if (this.isPasswordEnabled()) {
+ this._textFieldRenderer.setPasswordText(text);
+ this._textFieldRenderer.setString("");
+ this._textFieldRenderer.insertText(text, text.length);
+ } else
+ this._textFieldRenderer.setString(text);
+ this._textFieldRendererAdaptDirty = true;
+ this._updateContentSizeWithTextureSize(this._textFieldRenderer.getContentSize());
+ },
+
+ /**
+ * Sets the placeholder string.
+ * display this string if string equal "".
+ * @param {String} value
+ */
+ setPlaceHolder: function (value) {
+ this._textFieldRenderer.setPlaceHolder(value);
+ this._textFieldRendererAdaptDirty = true;
+ this._updateContentSizeWithTextureSize(this._textFieldRenderer.getContentSize());
+ },
+
+ /**
+ * Returns the placeholder string.
+ * @returns {String}
+ */
+ getPlaceHolder: function () {
+ return this._textFieldRenderer.getPlaceHolder();
+ },
+
+ /**
+ * Returns the color of ccui.TextField's place holder.
+ * @returns {cc.Color}
+ */
+ getPlaceHolderColor: function(){
+ return this._textFieldRenderer.getPlaceHolderColor();
+ },
+
+ /**
+ * Sets the place holder color to ccui.TextField.
+ * @param color
+ */
+ setPlaceHolderColor: function(color){
+ this._textFieldRenderer.setColorSpaceHolder(color);
+ },
+
+ /**
+ * Sets the text color to ccui.TextField
+ * @param textColor
+ */
+ setTextColor: function(textColor){
+ this._textFieldRenderer.setTextColor(textColor);
+ },
+
+ /**
+ * Sets font size for ccui.TextField.
+ * @param {Number} size
+ */
+ setFontSize: function (size) {
+ this._textFieldRenderer.setFontSize(size);
+ this._fontSize = size;
+ this._textFieldRendererAdaptDirty = true;
+ this._updateContentSizeWithTextureSize(this._textFieldRenderer.getContentSize());
+ },
+
+ /**
+ * Gets font size of ccui.TextField.
+ * @return {Number} size
+ */
+ getFontSize: function () {
+ return this._fontSize;
+ },
+
+ /**
+ * Sets font name for ccui.TextField
+ * @param {String} name
+ */
+ setFontName: function (name) {
+ this._textFieldRenderer.setFontName(name);
+ this._fontName = name;
+ this._textFieldRendererAdaptDirty = true;
+ this._updateContentSizeWithTextureSize(this._textFieldRenderer.getContentSize());
+ },
+
+ /**
+ * Returns font name of ccui.TextField.
+ * @return {String} font name
+ */
+ getFontName: function () {
+ return this._fontName;
+ },
+
+ /**
+ * detach with IME
+ */
+ didNotSelectSelf: function () {
+ this._textFieldRenderer.detachWithIME();
+ },
+
+ /**
+ * Returns textField string value
+ * @deprecated since v3.0, please use getString instead.
+ * @returns {String}
+ */
+ getStringValue: function () {
+ cc.log("Please use the getString");
+ return this.getString();
+ },
+
+ /**
+ * Returns string value of ccui.TextField.
+ * @returns {String}
+ */
+ getString: function () {
+ return this._textFieldRenderer.getString();
+ },
+
+ /**
+ * Returns the length of ccui.TextField.
+ * @returns {Number}
+ */
+ getStringLength: function(){
+ return this._textFieldRenderer.getStringLength();
+ },
+
+ /**
+ * The touch began event callback handler.
+ * @param {cc.Vec2} touchPoint
+ */
+ onTouchBegan: function (touchPoint, unusedEvent) {
+ var self = this;
+ var pass = ccui.Widget.prototype.onTouchBegan.call(self, touchPoint, unusedEvent);
+ if (self._hit) {
+ setTimeout(function(){
+ self._textFieldRenderer.attachWithIME();
+ }, 0);
+ }else{
+ setTimeout(function(){
+ self._textFieldRenderer.detachWithIME();
+ }, 0);
+ }
+ return pass;
+ },
+
+ /**
+ * Sets Whether to open string length limit for ccui.TextField.
+ * @param {Boolean} enable
+ */
+ setMaxLengthEnabled: function (enable) {
+ this._textFieldRenderer.setMaxLengthEnabled(enable);
+ },
+
+ /**
+ * Returns Whether to open string length limit.
+ * @returns {Boolean}
+ */
+ isMaxLengthEnabled: function () {
+ return this._textFieldRenderer.isMaxLengthEnabled();
+ },
+
+ /**
+ * Sets the max length of ccui.TextField. Only when you turn on the string length limit, it is valid.
+ * @param {number} length
+ */
+ setMaxLength: function (length) {
+ this._textFieldRenderer.setMaxLength(length);
+ this.setString(this.getString());
+ },
+
+ /**
+ * Returns the max length of ccui.TextField.
+ * @returns {number} length
+ */
+ getMaxLength: function () {
+ return this._textFieldRenderer.getMaxLength();
+ },
+
+ /**
+ * Sets whether to open setting string as password character.
+ * @param {Boolean} enable
+ */
+ setPasswordEnabled: function (enable) {
+ this._textFieldRenderer.setPasswordEnabled(enable);
+ },
+
+ /**
+ * Returns whether to open setting string as password character.
+ * @returns {Boolean}
+ */
+ isPasswordEnabled: function () {
+ return this._textFieldRenderer.isPasswordEnabled();
+ },
+
+ /**
+ * Sets the password style character, Only when you turn on setting string as password character, it is valid.
+ * @param styleText
+ */
+ setPasswordStyleText: function(styleText){
+ this._textFieldRenderer.setPasswordStyleText(styleText);
+ this._passwordStyleText = styleText;
+
+ this.setString(this.getString());
+ },
+
+ /**
+ * Returns the password style character.
+ * @returns {String}
+ */
+ getPasswordStyleText: function () {
+ return this._passwordStyleText;
+ },
+
+ update: function (dt) {
+ if (this.getDetachWithIME()) {
+ this._detachWithIMEEvent();
+ this.setDetachWithIME(false);
+ }
+ if (this.getAttachWithIME()) {
+ this._attachWithIMEEvent();
+ this.setAttachWithIME(false);
+ }
+ if (this.getInsertText()) {
+ this._textFieldRendererAdaptDirty = true;
+ this._updateContentSizeWithTextureSize(this._textFieldRenderer.getContentSize());
+
+ this._insertTextEvent();
+ this.setInsertText(false);
+ }
+ if (this.getDeleteBackward()) {
+ this._textFieldRendererAdaptDirty = true;
+ this._updateContentSizeWithTextureSize(this._textFieldRenderer.getContentSize());
+
+ this._deleteBackwardEvent();
+ this.setDeleteBackward(false);
+ }
+ },
+
+ /**
+ * Returns whether attach with IME.
+ * @returns {Boolean}
+ */
+ getAttachWithIME: function () {
+ return this._textFieldRenderer.getAttachWithIME();
+ },
+
+ /**
+ * Sets attach with IME.
+ * @param {Boolean} attach
+ */
+ setAttachWithIME: function (attach) {
+ this._textFieldRenderer.setAttachWithIME(attach);
+ },
+
+ /**
+ * Returns whether detach with IME.
+ * @returns {Boolean}
+ */
+ getDetachWithIME: function () {
+ return this._textFieldRenderer.getDetachWithIME();
+ },
+
+ /**
+ * Sets detach with IME.
+ * @param {Boolean} detach
+ */
+ setDetachWithIME: function (detach) {
+ this._textFieldRenderer.setDetachWithIME(detach);
+ },
+
+ /**
+ * Returns insertText string of ccui.TextField.
+ * @returns {String}
+ */
+ getInsertText: function () {
+ return this._textFieldRenderer.getInsertText();
+ },
+
+ /**
+ * Sets insertText string to ccui.TextField.
+ * @param {String} insertText
+ */
+ setInsertText: function (insertText) {
+ this._textFieldRenderer.setInsertText(insertText);
+ },
+
+ /**
+ * Returns the delete backward of ccui.TextField.
+ * @returns {Boolean}
+ */
+ getDeleteBackward: function () {
+ return this._textFieldRenderer.getDeleteBackward();
+ },
+
+ /**
+ * Sets the delete backward of ccui.TextField.
+ * @param {Boolean} deleteBackward
+ */
+ setDeleteBackward: function (deleteBackward) {
+ this._textFieldRenderer.setDeleteBackward(deleteBackward);
+ },
+
+ _attachWithIMEEvent: function () {
+ if(this._textFieldEventSelector){
+ if (this._textFieldEventListener)
+ this._textFieldEventSelector.call(this._textFieldEventListener, this, ccui.TextField.EVENT_ATTACH_WITH_IME);
+ else
+ this._textFieldEventSelector(this, ccui.TextField.EVENT_ATTACH_WITH_IME);
+ }
+ if (this._ccEventCallback){
+ this._ccEventCallback(this, ccui.TextField.EVENT_ATTACH_WITH_IME);
+ }
+ },
+
+ _detachWithIMEEvent: function () {
+ if(this._textFieldEventSelector){
+ if (this._textFieldEventListener)
+ this._textFieldEventSelector.call(this._textFieldEventListener, this, ccui.TextField.EVENT_DETACH_WITH_IME);
+ else
+ this._textFieldEventSelector(this, ccui.TextField.EVENT_DETACH_WITH_IME);
+ }
+ if (this._ccEventCallback)
+ this._ccEventCallback(this, ccui.TextField.EVENT_DETACH_WITH_IME);
+ },
+
+ _insertTextEvent: function () {
+ if(this._textFieldEventSelector){
+ if (this._textFieldEventListener)
+ this._textFieldEventSelector.call(this._textFieldEventListener, this, ccui.TextField.EVENT_INSERT_TEXT);
+ else
+ this._textFieldEventSelector(this, ccui.TextField.EVENT_INSERT_TEXT); //eventCallback
+ }
+ if (this._ccEventCallback)
+ this._ccEventCallback(this, ccui.TextField.EVENT_INSERT_TEXT);
+ },
+
+ _deleteBackwardEvent: function () {
+ if(this._textFieldEventSelector){
+ if (this._textFieldEventListener)
+ this._textFieldEventSelector.call(this._textFieldEventListener, this, ccui.TextField.EVENT_DELETE_BACKWARD);
+ else
+ this._textFieldEventSelector(this, ccui.TextField.EVENT_DELETE_BACKWARD); //eventCallback
+ }
+ if (this._ccEventCallback)
+ this._ccEventCallback(this, ccui.TextField.EVENT_DELETE_BACKWARD);
+ },
+
+ /**
+ * Adds event listener to cuci.TextField.
+ * @param {Object} [target=]
+ * @param {Function} selector
+ * @deprecated since v3.0, please use addEventListener instead.
+ */
+ addEventListenerTextField: function (selector, target) {
+ this.addEventListener(selector, target);
+ },
+
+ /**
+ * Adds event listener callback.
+ * @param {Object} [target=]
+ * @param {Function} selector
+ */
+ addEventListener: function(selector, target){
+ this._textFieldEventSelector = selector; //when target is undefined, _textFieldEventSelector is ccEventCallback.
+ this._textFieldEventListener = target;
+ },
+
+ _onSizeChanged: function () {
+ ccui.Widget.prototype._onSizeChanged.call(this);
+ this._textFieldRendererAdaptDirty = true;
+ },
+
+ _adaptRenderers: function(){
+ if (this._textFieldRendererAdaptDirty) {
+ this._textfieldRendererScaleChangedWithSize();
+ this._textFieldRendererAdaptDirty = false;
+ }
+ },
+
+ _textfieldRendererScaleChangedWithSize: function () {
+ if (!this._ignoreSize)
+ this._textFieldRenderer.setDimensions(this._contentSize);
+ this._textFieldRenderer.setPosition(this._contentSize.width / 2, this._contentSize.height / 2);
+ },
+
+ //@since v3.3
+ getAutoRenderSize: function(){
+ var virtualSize = this._textFieldRenderer.getContentSize();
+ if (!this._ignoreSize) {
+ this._textFieldRenderer.setDimensions(0, 0);
+ virtualSize = this._textFieldRenderer.getContentSize();
+ this._textFieldRenderer.setDimensions(this._contentSize.width, this._contentSize.height);
+ }
+ return virtualSize;
+ },
+
+ /**
+ * Returns the ccui.TextField's content size.
+ * @returns {cc.Size}
+ */
+ getVirtualRendererSize: function(){
+ return this._textFieldRenderer.getContentSize();
+ },
+
+ /**
+ * Returns the renderer of ccui.TextField.
+ * @returns {cc.Node}
+ */
+ getVirtualRenderer: function () {
+ return this._textFieldRenderer;
+ },
+
+ /**
+ * Returns the "class name" of ccui.TextField.
+ * @returns {string}
+ */
+ getDescription: function () {
+ return "TextField";
+ },
+
+ /**
+ * Open keyboard and receive input text.
+ * @return {Boolean}
+ */
+ attachWithIME: function () {
+ this._textFieldRenderer.attachWithIME();
+ },
+
+ _createCloneInstance: function () {
+ return new ccui.TextField();
+ },
+
+ _copySpecialProperties: function (textField) {
+ this.setString(textField._textFieldRenderer.getString());
+ this.setPlaceHolder(textField.getString());
+ this.setFontSize(textField._textFieldRenderer.getFontSize());
+ this.setFontName(textField._textFieldRenderer.getFontName());
+ this.setMaxLengthEnabled(textField.isMaxLengthEnabled());
+ this.setMaxLength(textField.getMaxLength());
+ this.setPasswordEnabled(textField.isPasswordEnabled());
+ this.setPasswordStyleText(textField._passwordStyleText);
+ this.setAttachWithIME(textField.getAttachWithIME());
+ this.setDetachWithIME(textField.getDetachWithIME());
+ this.setInsertText(textField.getInsertText());
+ this.setDeleteBackward(textField.getDeleteBackward());
+ this._ccEventCallback = textField._ccEventCallback;
+ this._textFieldEventListener = textField._textFieldEventListener;
+ this._textFieldEventSelector = textField._textFieldEventSelector;
+ },
+
+ /**
+ * Sets the text area size to ccui.TextField.
+ * @param {cc.Size} size
+ */
+ setTextAreaSize: function(size){
+ this.setContentSize(size);
+ },
+
+ /**
+ * Sets the text horizontal alignment of ccui.TextField.
+ * @param alignment
+ */
+ setTextHorizontalAlignment: function(alignment){
+ this._textFieldRenderer.setHorizontalAlignment(alignment);
+ },
+
+ /**
+ * Sets the text vertical alignment of ccui.TextField.
+ * @param alignment
+ */
+ setTextVerticalAlignment: function(alignment){
+ this._textFieldRenderer.setVerticalAlignment(alignment);
+ },
+ _setFont: function (font) {
+ this._textFieldRenderer._setFont(font);
+ this._textFieldRendererAdaptDirty = true;
+ },
+
+ _getFont: function () {
+ return this._textFieldRenderer._getFont();
+ },
+
+ _changePosition: function(){
+ this._adaptRenderers();
+ }
+});
+
+/**
+ * Creates a ccui.TextField.
+ * @deprecated since v3.0, please use new ccui.TextField() instead.
+ * @param {String} placeholder
+ * @param {String} fontName
+ * @param {Number} fontSize
+ * @returns {ccui.TextField}
+ */
+ccui.TextField.create = function(placeholder, fontName, fontSize){
+ return new ccui.TextField(placeholder, fontName, fontSize);
+};
+
+var _p = ccui.TextField.prototype;
+
+// Extended properties
+/** @expose */
+_p.string;
+cc.defineGetterSetter(_p, "string", _p.getString, _p.setString);
+/** @expose */
+_p.placeHolder;
+cc.defineGetterSetter(_p, "placeHolder", _p.getPlaceHolder, _p.setPlaceHolder);
+/** @expose */
+_p.font;
+cc.defineGetterSetter(_p, "font", _p._getFont, _p._setFont);
+/** @expose */
+_p.fontSize;
+cc.defineGetterSetter(_p, "fontSize", _p.getFontSize, _p.setFontSize);
+/** @expose */
+_p.fontName;
+cc.defineGetterSetter(_p, "fontName", _p.getFontName, _p.setFontName);
+/** @expose */
+_p.maxLengthEnabled;
+cc.defineGetterSetter(_p, "maxLengthEnabled", _p.isMaxLengthEnabled, _p.setMaxLengthEnabled);
+/** @expose */
+_p.maxLength;
+cc.defineGetterSetter(_p, "maxLength", _p.getMaxLength, _p.setMaxLength);
+/** @expose */
+_p.passwordEnabled;
+cc.defineGetterSetter(_p, "passwordEnabled", _p.isPasswordEnabled, _p.setPasswordEnabled);
+
+_p = null;
+
+// Constants
+//TextField event
+/**
+ * The attach with IME event flag of ccui.TextField
+ * @constant
+ * @type {number}
+ */
+ccui.TextField.EVENT_ATTACH_WITH_IME = 0;
+/**
+ * The detach with IME event flag of ccui.TextField
+ * @constant
+ * @type {number}
+ */
+ccui.TextField.EVENT_DETACH_WITH_IME = 1;
+/**
+ * The insert text event flag of ccui.TextField
+ * @constant
+ * @type {number}
+ */
+ccui.TextField.EVENT_INSERT_TEXT = 2;
+/**
+ * The delete backward event flag of ccui.TextField
+ * @constant
+ * @type {number}
+ */
+ccui.TextField.EVENT_DELETE_BACKWARD = 3;
+
+/**
+ * The zOrder value of ccui.TextField's renderer.
+ * @constant
+ * @type {number}
+ */
+ccui.TextField.RENDERER_ZORDER = -1;
\ No newline at end of file
diff --git a/extensions/ccui/uiwidgets/UIVideoPlayer.js b/extensions/ccui/uiwidgets/UIVideoPlayer.js
new file mode 100644
index 0000000000..3ba773d6aa
--- /dev/null
+++ b/extensions/ccui/uiwidgets/UIVideoPlayer.js
@@ -0,0 +1,543 @@
+/****************************************************************************
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+/**
+ * @class
+ * @extends ccui.Widget
+ * @brief Displays a video file.
+ *
+ * @note VideoPlayer displays a video file based on DOM element
+ * VideoPlayer will be rendered above all other graphical elements.
+ *
+ * @property {String} path - The video path
+ */
+ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{
+
+ _played: false,
+ _playing: false,
+ _stopped: true,
+
+ ctor: function(path){
+ ccui.Widget.prototype.ctor.call(this);
+ this._EventList = {};
+ if(path)
+ this.setURL(path);
+ },
+
+ _createRenderCmd: function(){
+ return new ccui.VideoPlayer.RenderCmd(this);
+ },
+
+ /**
+ * Set the video address
+ * Automatically replace extname
+ * All supported video formats will be added to the video
+ * @param {String} address
+ */
+ setURL: function(address){
+ this._renderCmd.updateURL(address);
+ },
+
+ /**
+ * Get the video path
+ * @returns {String}
+ */
+ getURL: function() {
+ return this._renderCmd._url;
+ },
+
+ /**
+ * Play the video
+ */
+ play: function(){
+ var self = this,
+ video = this._renderCmd._video;
+ if(video){
+ this._played = true;
+ video.pause();
+ if(this._stopped !== false || this._playing !== false || this._played !== true)
+ video.currentTime = 0;
+ if(ccui.VideoPlayer._polyfill.autoplayAfterOperation){
+ setTimeout(function(){
+ video.play();
+ self._playing = true;
+ self._stopped = false;
+ }, 20);
+ }else{
+ video.play();
+ this._playing = true;
+ this._stopped = false;
+ }
+ }
+ },
+
+ /**
+ * Pause the video
+ */
+ pause: function(){
+ var video = this._renderCmd._video;
+ if(video && this._playing === true && this._stopped === false){
+ video.pause();
+ this._playing = false;
+ }
+ },
+
+ /**
+ * Resume the video
+ */
+ resume: function(){
+ if(this._stopped === false && this._playing === false && this._played === true){
+ this.play();
+ }
+ },
+
+ /**
+ * Stop the video
+ */
+ stop: function(){
+ var self = this,
+ video = this._renderCmd._video;
+ if(video){
+ video.pause();
+ video.currentTime = 0;
+ this._playing = false;
+ this._stopped = true;
+ }
+
+ setTimeout(function(){
+ self._dispatchEvent(ccui.VideoPlayer.EventType.STOPPED);
+ }, 0);
+ },
+ /**
+ * Jump to the specified point in time
+ * @param {Number} sec
+ */
+ seekTo: function(sec){
+ var video = this._renderCmd._video;
+ if(video){
+ video.currentTime = sec;
+ if(ccui.VideoPlayer._polyfill.autoplayAfterOperation && this.isPlaying()){
+ setTimeout(function(){
+ video.play();
+ }, 20);
+ }
+ }
+ },
+
+ /**
+ * Whether the video is playing
+ * @returns {boolean}
+ */
+ isPlaying: function(){
+ if(ccui.VideoPlayer._polyfill.autoplayAfterOperation && this._playing){
+ setTimeout(function(){
+ video.play();
+ }, 20);
+ }
+ return this._playing;
+ },
+
+ /**
+ * Whether to keep the aspect ratio
+ */
+ setKeepAspectRatioEnabled: function(enable){
+ cc.log("On the web is always keep the aspect ratio");
+ },
+ isKeepAspectRatioEnabled: function(){
+ return false;
+ },
+
+ /**
+ * Set whether the full screen
+ * May appear inconsistent in different browsers
+ * @param {boolean} enable
+ */
+ setFullScreenEnabled: function(enable){
+ var video = this._renderCmd._video;
+ if(video){
+ if(enable)
+ cc.screen.requestFullScreen(video);
+ else
+ cc.screen.exitFullScreen(video);
+ }
+ },
+
+ /**
+ * Determine whether already full screen
+ */
+ isFullScreenEnabled: function(){
+ cc.log("Can't know status");
+ },
+
+ /**
+ * The binding event
+ * @param {ccui.VideoPlayer.EventType} event
+ * @param {Function} callback
+ */
+ setEventListener: function(event, callback){
+ this._EventList[event] = callback;
+ },
+
+ /**
+ * Delete events
+ * @param {ccui.VideoPlayer.EventType} event
+ */
+ removeEventListener: function(event){
+ this._EventList[event] = null;
+ },
+
+ _dispatchEvent: function(event) {
+ var callback = this._EventList[event];
+ if (callback)
+ callback.call(this, this, this._renderCmd._video.src);
+ },
+
+ /**
+ * Trigger playing events
+ */
+ onPlayEvent: function(){
+ var list = this._EventList[ccui.VideoPlayer.EventType.PLAYING];
+ if(list)
+ for(var i=0; i -1)
+ this._items.splice(index, 1);
+ ccui.ScrollView.prototype.removeChild.call(this, widget, cleanup);
+ }
+ },
+
+ /**
+ * Removes all children from ccui.ListView.
+ */
+ removeAllChildren: function(){
+ this.removeAllChildrenWithCleanup(true);
+ },
+
+ /**
+ * Removes all children from ccui.ListView and do a cleanup all running actions depending on the cleanup parameter.
+ * @param {Boolean} cleanup
+ */
+ removeAllChildrenWithCleanup: function(cleanup){
+ ccui.ScrollView.prototype.removeAllChildrenWithCleanup.call(this, cleanup);
+ this._items = [];
+ },
+
+ /**
+ * Push back custom item into ccui.ListView.
+ * @param {ccui.Widget} item
+ * @param {Number} index
+ */
+ insertCustomItem: function (item, index) {
+ this._items.splice(index, 0, item);
+ ccui.ScrollView.prototype.addChild.call(this, item);
+ this._remedyLayoutParameter(item);
+ this._refreshViewDirty = true;
+ },
+
+ /**
+ * Removes a item whose index is same as the parameter.
+ * @param {Number} index
+ */
+ removeItem: function (index) {
+ var item = this.getItem(index);
+ if (item == null)
+ return;
+ this.removeChild(item, true);
+ this._refreshViewDirty = true;
+ },
+
+ /**
+ * Removes the last item of ccui.ListView.
+ */
+ removeLastItem: function () {
+ this.removeItem(this._items.length - 1);
+ },
+
+ /**
+ * Removes all items from ccui.ListView.
+ */
+ removeAllItems: function(){
+ this.removeAllChildren();
+ },
+
+ /**
+ * Returns a item whose index is same as the parameter.
+ * @param {Number} index
+ * @returns {ccui.Widget}
+ */
+ getItem: function (index) {
+ if (index < 0 || index >= this._items.length)
+ return null;
+ return this._items[index];
+ },
+
+ /**
+ * Returns the item container.
+ * @returns {Array}
+ */
+ getItems: function () {
+ return this._items;
+ },
+
+ /**
+ * Returns the index of item.
+ * @param {ccui.Widget} item the item which need to be checked.
+ * @returns {Number} the index of item.
+ */
+ getIndex: function (item) {
+ if(item == null)
+ return -1;
+ return this._items.indexOf(item);
+ },
+
+ /**
+ * Changes the gravity of ListView.
+ * @param {ccui.ListView.GRAVITY_LEFT|ccui.ListView.GRAVITY_RIGHT|ccui.ListView.GRAVITY_CENTER_HORIZONTAL|ccui.ListView.GRAVITY_BOTTOM|ccui.ListView.GRAVITY_CENTER_VERTICAL} gravity
+ */
+ setGravity: function (gravity) {
+ if (this._gravity === gravity)
+ return;
+ this._gravity = gravity;
+ this._refreshViewDirty = true;
+ },
+
+ /**
+ * Changes the margin between each item.
+ * @param {Number} margin
+ */
+ setItemsMargin: function (margin) {
+ if (this._itemsMargin === margin)
+ return;
+ this._itemsMargin = margin;
+ this._refreshViewDirty = true;
+ },
+
+ /**
+ * Returns the margin between each item.
+ * @returns {Number}
+ */
+ getItemsMargin:function(){
+ return this._itemsMargin;
+ },
+
+ /**
+ * Changes scroll direction of ccui.ListView.
+ * @param {ccui.ScrollView.Dir} dir
+ */
+ setDirection: function (dir) {
+ switch (dir) {
+ case ccui.ScrollView.Dir.VERTICAL:
+ this.setLayoutType(ccui.Layout.Type.LINEAR_VERTICAL);
+ break;
+ case ccui.ScrollView.Dir.HORIZONTAL:
+ this.setLayoutType(ccui.Layout.Type.LINEAR_HORIZONTAL);
+ break;
+ case ccui.ScrollView.Dir.BOTH:
+ return;
+ default:
+ return;
+ break;
+ }
+ ccui.ScrollView.prototype.setDirection.call(this, dir);
+ },
+
+ /**
+ * Requests refresh list view.
+ */
+ requestRefreshView: function () {
+ this._refreshViewDirty = true;
+ },
+
+ /**
+ * Refreshes list view.
+ */
+ refreshView: function () {
+ var locItems = this._items;
+ for (var i = 0; i < locItems.length; i++) {
+ var item = locItems[i];
+ item.setLocalZOrder(i);
+ this._remedyLayoutParameter(item);
+ }
+ this._updateInnerContainerSize();
+ },
+
+ /**
+ * provides a public _doLayout function for Editor. it calls _doLayout.
+ */
+ doLayout: function(){
+ this._doLayout();
+ },
+
+ _doLayout: function(){
+ ccui.Layout.prototype._doLayout.call(this);
+ if (this._refreshViewDirty) {
+ this.refreshView();
+ this._refreshViewDirty = false;
+ }
+ },
+
+ /**
+ * Adds event listener to ccui.ListView.
+ * @param {Function} selector
+ * @param {Object} [target=]
+ * @deprecated since v3.0, please use addEventListener instead.
+ */
+ addEventListenerListView: function (selector, target) {
+ this.addEventListener(selector, target);
+ },
+
+ /**
+ * Adds event listener to ccui.ListView.
+ * @param {Function} selector
+ * @param {Object} [target=]
+ */
+ addEventListener: function(selector, target){
+ this._listViewEventListener = target;
+ this._listViewEventSelector = selector;
+ },
+
+ _selectedItemEvent: function (event) {
+ var eventEnum = (event === ccui.Widget.TOUCH_BEGAN) ? ccui.ListView.ON_SELECTED_ITEM_START : ccui.ListView.ON_SELECTED_ITEM_END;
+ if(this._listViewEventSelector){
+ if (this._listViewEventListener)
+ this._listViewEventSelector.call(this._listViewEventListener, this, eventEnum);
+ else
+ this._listViewEventSelector(this, eventEnum);
+ }
+ if(this._ccEventCallback)
+ this._ccEventCallback(this, eventEnum);
+ },
+
+ /**
+ * Intercept touch event, handle its child's touch event.
+ * @param {cc.Event} event
+ */
+ interceptTouchEvent: function (event) {
+ var eventType = event._widgetEventType,
+ touch = event.currentTouch,
+ parent;
+ ccui.ScrollView.prototype.interceptTouchEvent.call(this, event);
+ if (!this._touchEnabled)
+ return;
+
+ if (eventType !== ccui.Widget.TOUCH_MOVED) {
+ parent = event.target;
+ while (parent) {
+ if (parent && parent.getParent() === this._innerContainer) {
+ this._curSelectedIndex = this.getIndex(parent);
+ break;
+ }
+ parent = parent.getParent();
+ }
+ if (event.target.isHighlighted())
+ this._selectedItemEvent(eventType);
+ }
+ },
+
+ /**
+ * Returns current selected index
+ * @returns {number}
+ */
+ getCurSelectedIndex: function () {
+ return this._curSelectedIndex;
+ },
+
+ _onSizeChanged: function () {
+ ccui.ScrollView.prototype._onSizeChanged.call(this);
+ this._refreshViewDirty = true;
+ },
+
+ /**
+ * Returns the "class name" of ccui.ListView.
+ * @returns {string}
+ */
+ getDescription: function () {
+ return "ListView";
+ },
+
+ _createCloneInstance: function () {
+ return new ccui.ListView();
+ },
+
+ _copyClonedWidgetChildren: function (model) {
+ var arrayItems = model.getItems();
+ for (var i = 0; i < arrayItems.length; i++) {
+ var item = arrayItems[i];
+ this.pushBackCustomItem(item.clone());
+ }
+ },
+
+ _copySpecialProperties: function (listView) {
+ if(listView instanceof ccui.ListView){
+ ccui.ScrollView.prototype._copySpecialProperties.call(this, listView);
+ this.setItemModel(listView._model);
+ this.setItemsMargin(listView._itemsMargin);
+ this.setGravity(listView._gravity);
+
+ this._listViewEventListener = listView._listViewEventListener;
+ this._listViewEventSelector = listView._listViewEventSelector;
+ }
+ },
+
+ //v3.3
+ forceDoLayout: function(){
+ if (this._refreshViewDirty) {
+ this.refreshView();
+ this._refreshViewDirty = false;
+ }
+ this._innerContainer.forceDoLayout();
+ }
+});
+
+/**
+ * allocates and initializes a UIListView.
+ * @deprecated since v3.0, please use new ccui.ListView() instead.
+ */
+ccui.ListView.create = function () {
+ return new ccui.ListView();
+};
+
+// Constants
+//listView event type
+/**
+ * The flag selected item of ccui.ListView's event.
+ * @constant
+ * @type {number}
+ */
+ccui.ListView.EVENT_SELECTED_ITEM = 0;
+
+/**
+ * The flag selected item start of ccui.ListView's event.
+ * @constant
+ * @type {number}
+ */
+ccui.ListView.ON_SELECTED_ITEM_START = 0;
+/**
+ * The flag selected item end of ccui.ListView's event.
+ * @constant
+ * @type {number}
+ */
+ccui.ListView.ON_SELECTED_ITEM_END = 1;
+
+//listView gravity
+/**
+ * The left flag of ccui.ListView's gravity.
+ * @constant
+ * @type {number}
+ */
+ccui.ListView.GRAVITY_LEFT = 0;
+/**
+ * The right flag of ccui.ListView's gravity.
+ * @constant
+ * @type {number}
+ */
+ccui.ListView.GRAVITY_RIGHT = 1;
+/**
+ * The center horizontal flag of ccui.ListView's gravity.
+ * @constant
+ * @type {number}
+ */
+ccui.ListView.GRAVITY_CENTER_HORIZONTAL = 2;
+/**
+ * The top flag of ccui.ListView's gravity.
+ * @constant
+ * @type {number}
+ */
+ccui.ListView.GRAVITY_TOP = 3;
+/**
+ * The bottom flag of ccui.ListView's gravity.
+ * @constant
+ * @type {number}
+ */
+ccui.ListView.GRAVITY_BOTTOM = 4;
+/**
+ * The center vertical flag of ccui.ListView's gravity.
+ * @constant
+ * @type {number}
+ */
+ccui.ListView.GRAVITY_CENTER_VERTICAL = 5;
\ No newline at end of file
diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js b/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js
new file mode 100644
index 0000000000..de376e8219
--- /dev/null
+++ b/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js
@@ -0,0 +1,663 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+/**
+ * The PageView control of Cocos UI.
+ * @class
+ * @extends ccui.Layout
+ * @exmaple
+ * var pageView = new ccui.PageView();
+ * pageView.setTouchEnabled(true);
+ * pageView.addPage(new ccui.Layout());
+ * this.addChild(pageView);
+ */
+ccui.PageView = ccui.Layout.extend(/** @lends ccui.PageView# */{
+ _curPageIdx: 0,
+ _pages: null,
+ _touchMoveDirection: null,
+ _touchStartLocation: 0,
+ _touchMoveStartLocation: 0,
+ _movePagePoint: null,
+ _leftBoundaryChild: null,
+ _rightBoundaryChild: null,
+ _leftBoundary: 0,
+ _rightBoundary: 0,
+
+ _isAutoScrolling: false,
+ _autoScrollDistance: 0,
+ _autoScrollSpeed: 0,
+ _autoScrollDirection: 0,
+
+ _childFocusCancelOffset: 0,
+ _pageViewEventListener: null,
+ _pageViewEventSelector: null,
+ _className:"PageView",
+ //v3.2
+ _customScrollThreshold: 0,
+ _usingCustomScrollThreshold: false,
+
+ /**
+ * Allocates and initializes a UIPageView.
+ * Constructor of ccui.PageView. please do not call this function by yourself, you should pass the parameters to constructor to initialize it.
+ * @example
+ * // example
+ * var uiPageView = new ccui.PageView();
+ */
+ ctor: function () {
+ ccui.Layout.prototype.ctor.call(this);
+ this._pages = [];
+ this._touchMoveDirection = ccui.PageView.TOUCH_DIR_LEFT;
+
+ this._movePagePoint = null;
+ this._leftBoundaryChild = null;
+ this._rightBoundaryChild = null;
+
+ this._childFocusCancelOffset = 5;
+ this._pageViewEventListener = null;
+ this._pageViewEventSelector = null;
+ this.setTouchEnabled(true);
+
+ // For propagation
+ this.on(cc.Event.TOUCH, this.interceptTouchEvent);
+ },
+
+ /**
+ * Initializes a ccui.PageView. Please do not call this function by yourself, you should pass the parameters to constructor to initialize it.
+ * @returns {boolean}
+ */
+ init: function () {
+ if (ccui.Layout.prototype.init.call(this)) {
+ this.setClippingEnabled(true);
+ return true;
+ }
+ return false;
+ },
+
+ /**
+ * Calls the parent class' onEnter and schedules update function.
+ * @override
+ */
+ onEnter:function(){
+ ccui.Layout.prototype.onEnter.call(this);
+ this.scheduleUpdate(true);
+ },
+
+ /**
+ * Add a widget to a page of PageView.
+ * @param {ccui.Widget} widget widget to be added to PageView.
+ * @param {number} pageIdx index of page.
+ * @param {Boolean} forceCreate if force create and there is no page exist, PageView would create a default page for adding widget.
+ */
+ addWidgetToPage: function (widget, pageIdx, forceCreate) {
+ if (!widget || pageIdx < 0)
+ return;
+
+ var pageCount = this._getPageCount();
+ if (pageIdx < 0 || pageIdx >= pageCount) {
+ if (forceCreate) {
+ if (pageIdx > pageCount)
+ cc.log("pageIdx is %d, it will be added as page id [%d]", pageIdx, pageCount);
+ var newPage = this._createPage();
+ newPage.addChild(widget);
+ this.addPage(newPage);
+ }
+ } else {
+ var page = this._pages[pageIdx];
+ if (page)
+ page.addChild(widget);
+ }
+ },
+
+ _createPage: function () {
+ var newPage = new ccui.Layout();
+ newPage.setContentSize(this.getContentSize());
+ return newPage;
+ },
+
+ /**
+ * Adds a page to ccui.PageView.
+ * @param {ccui.Layout} page
+ */
+ addPage: function (page) {
+ if (!page || this._pages.indexOf(page) !== -1)
+ return;
+
+ this.addChild(page);
+ this._pages.push(page);
+ this._doLayoutDirty = true;
+ },
+
+ /**
+ * Inserts a page in the specified location.
+ * @param {ccui.Layout} page page to be added to PageView.
+ * @param {Number} idx index
+ */
+ insertPage: function (page, idx) {
+ if (idx < 0 || !page || this._pages.indexOf(page) !== -1)
+ return;
+
+ var pageCount = this._getPageCount();
+ if (idx >= pageCount)
+ this.addPage(page);
+ else {
+ this._pages[idx] = page;
+ this.addChild(page);
+ }
+ this._doLayoutDirty = true;
+ },
+
+ /**
+ * Removes a page from PageView.
+ * @param {ccui.Layout} page
+ */
+ removePage: function (page) {
+ if (!page)
+ return;
+ this.removeChild(page);
+ var index = this._pages.indexOf(page);
+ if(index > -1)
+ this._pages.splice(index, 1);
+ this._doLayoutDirty = true;
+ },
+
+ /**
+ * Removes a page at index of PageView.
+ * @param {number} index
+ */
+ removePageAtIndex: function (index) {
+ if (index < 0 || index >= this._pages.length)
+ return;
+ var page = this._pages[index];
+ if (page)
+ this.removePage(page);
+ },
+
+ /**
+ * Removes all pages from PageView
+ */
+ removeAllPages: function(){
+ var locPages = this._pages;
+ for(var i = 0, len = locPages.length; i < len; i++)
+ this.removeChild(locPages[i]);
+ this._pages.length = 0;
+ },
+
+ _updateBoundaryPages: function () {
+ var locPages = this._pages;
+ if (locPages.length <= 0) {
+ this._leftBoundaryChild = null;
+ this._rightBoundaryChild = null;
+ return;
+ }
+ this._leftBoundaryChild = locPages[0];
+ this._rightBoundaryChild = locPages[locPages.length - 1];
+ },
+
+ _getPageCount: function(){
+ return this._pages.length;
+ },
+
+ /**
+ * Get x position by index
+ * @param {number} idx
+ * @returns {number}
+ */
+ _getPositionXByIndex: function (idx) {
+ return (this.getContentSize().width * (idx - this._curPageIdx));
+ },
+
+ _onSizeChanged: function () {
+ ccui.Layout.prototype._onSizeChanged.call(this);
+ this._rightBoundary = this.getContentSize().width;
+ this._doLayoutDirty = true;
+ },
+
+ _updateAllPagesSize: function(){
+ var selfSize = this.getContentSize();
+ var locPages = this._pages;
+ for (var i = 0, len = locPages.length; i < len; i++)
+ locPages[i].setContentSize(selfSize);
+ },
+
+ _updateAllPagesPosition: function(){
+ var pageCount = this._getPageCount();
+ if (pageCount <= 0) {
+ this._curPageIdx = 0;
+ return;
+ }
+
+ if (this._curPageIdx >= pageCount)
+ this._curPageIdx = pageCount-1;
+
+ var pageWidth = this.getContentSize().width;
+ var locPages = this._pages;
+ for (var i=0; i< pageCount; i++)
+ locPages[i].setPosition(cc.p((i - this._curPageIdx) * pageWidth, 0));
+ },
+
+ /**
+ * scroll PageView to index.
+ * @param {number} idx index of page.
+ */
+ scrollToPage: function (idx) {
+ if (idx < 0 || idx >= this._pages.length)
+ return;
+ this._curPageIdx = idx;
+ var curPage = this._pages[idx];
+ this._autoScrollDistance = -(curPage.getPosition().x);
+ this._autoScrollSpeed = Math.abs(this._autoScrollDistance) / 0.2;
+ this._autoScrollDirection = this._autoScrollDistance > 0 ? ccui.PageView.DIRECTION_RIGHT : ccui.PageView.DIRECTION_LEFT;
+ this._isAutoScrolling = true;
+ },
+
+ /**
+ * Called once per frame. Time is the number of seconds of a frame interval.
+ * @override
+ * @param {Number} dt
+ */
+ update: function (dt) {
+ if (this._isAutoScrolling)
+ this._autoScroll(dt);
+ },
+
+ /**
+ * Does nothing. ccui.PageView's layout type is ccui.Layout.Type.ABSOLUTE.
+ * @override
+ * @param {Number} type
+ */
+ setLayoutType:function(type){
+ },
+
+ /**
+ * Returns the layout type of ccui.PageView. it's always ccui.Layout.Type.ABSOLUTE.
+ * @returns {number}
+ */
+ getLayoutType: function(){
+ return ccui.Layout.Type.ABSOLUTE;
+ },
+
+ _autoScroll: function(dt){
+ var step;
+ switch (this._autoScrollDirection) {
+ case ccui.PageView.DIRECTION_LEFT:
+ step = this._autoScrollSpeed * dt;
+ if (this._autoScrollDistance + step >= 0.0) {
+ step = -this._autoScrollDistance;
+ this._autoScrollDistance = 0.0;
+ this._isAutoScrolling = false;
+ } else
+ this._autoScrollDistance += step;
+ this._scrollPages(-step);
+ if(!this._isAutoScrolling)
+ this._pageTurningEvent();
+ break;
+ break;
+ case ccui.PageView.DIRECTION_RIGHT:
+ step = this._autoScrollSpeed * dt;
+ if (this._autoScrollDistance - step <= 0.0) {
+ step = this._autoScrollDistance;
+ this._autoScrollDistance = 0.0;
+ this._isAutoScrolling = false;
+ } else
+ this._autoScrollDistance -= step;
+ this._scrollPages(step);
+ if(!this._isAutoScrolling)
+ this._pageTurningEvent();
+ break;
+ default:
+ break;
+ }
+ },
+
+ /**
+ * The touch moved event callback handler of ccui.PageView.
+ * @override
+ * @param {cc.Touch} touch
+ * @param {cc.Event} event
+ */
+ onTouchMoved: function (touch, event) {
+ ccui.Layout.prototype.onTouchMoved.call(this, touch, event);
+ if (!this._isInterceptTouch)
+ this._handleMoveLogic(touch);
+ },
+
+ /**
+ * The touch ended event callback handler of ccui.PageView.
+ * @override
+ * @param {cc.Touch} touch
+ * @param {cc.Event} event
+ */
+ onTouchEnded: function (touch, event) {
+ ccui.Layout.prototype.onTouchEnded.call(this, touch, event);
+ if (!this._isInterceptTouch)
+ this._handleReleaseLogic(touch);
+ this._isInterceptTouch = false;
+ },
+
+ /**
+ * The touch canceled event callback handler of ccui.PageView.
+ * @param {cc.Touch} touch
+ * @param {cc.Event} event
+ */
+ onTouchCancelled: function (touch, event) {
+ ccui.Layout.prototype.onTouchCancelled.call(this, touch, event);
+ if (!this._isInterceptTouch)
+ this._handleReleaseLogic(touch);
+ this._isInterceptTouch = false;
+ },
+
+ _doLayout: function(){
+ if (!this._doLayoutDirty)
+ return;
+
+ this._updateAllPagesPosition();
+ this._updateAllPagesSize();
+ this._updateBoundaryPages();
+ this._doLayoutDirty = false;
+ },
+
+ _movePages: function (offset) {
+ var arrayPages = this._pages;
+ var length = arrayPages.length;
+ for (var i = 0; i < length; i++) {
+ var child = arrayPages[i];
+ //var pos = child.getPosition();
+ //child.setPosition(pos.x + offset, pos.y);
+ child.setPositionX(child.getPositionX() + offset);
+ }
+ },
+
+ _scrollPages: function (touchOffset) {
+ if (this._pages.length <= 0)
+ return false;
+ if (!this._leftBoundaryChild || !this._rightBoundaryChild)
+ return false;
+
+ var realOffset = touchOffset;
+ switch (this._touchMoveDirection) {
+ case ccui.PageView.TOUCH_DIR_LEFT: // left
+ var rightBoundary = this._rightBoundaryChild.getRightBoundary();
+ if (rightBoundary + touchOffset <= this._rightBoundary) {
+ realOffset = this._rightBoundary - rightBoundary;
+ this._movePages(realOffset);
+ return false;
+ }
+ break;
+ case ccui.PageView.TOUCH_DIR_RIGHT: // right
+ var leftBoundary = this._leftBoundaryChild.getLeftBoundary();
+ if (leftBoundary + touchOffset >= this._leftBoundary) {
+ realOffset = this._leftBoundary - leftBoundary;
+ this._movePages(realOffset);
+ return false;
+ }
+ break;
+ default:
+ break;
+ }
+
+ this._movePages(realOffset);
+ return true;
+ },
+
+ _handleMoveLogic: function (touch) {
+ var offset = touch.getLocation().x - touch.getPreviousLocation().x;
+ if (offset < 0)
+ this._touchMoveDirection = ccui.PageView.TOUCH_DIR_LEFT;
+ else if (offset > 0)
+ this._touchMoveDirection = ccui.PageView.TOUCH_DIR_RIGHT;
+ this._scrollPages(offset);
+ },
+
+ /**
+ * Set custom scroll threshold to page view. If you don't specify the value, the pageView will scroll when half page view width reached.
+ * @since v3.2
+ * @param threshold
+ */
+ setCustomScrollThreshold: function(threshold){
+ cc.assert(threshold>0, "Invalid threshold!");
+ this._customScrollThreshold = threshold;
+ this.setUsingCustomScrollThreshold(true);
+ },
+
+ /**
+ * Returns user defined scroll page threshold.
+ * @since v3.2
+ */
+ getCustomScrollThreshold: function(){
+ return this._customScrollThreshold;
+ },
+
+ /**
+ * Set using user defined scroll page threshold or not. If you set it to false, then the default scroll threshold is pageView.width / 2.
+ * @since v3.2
+ */
+ setUsingCustomScrollThreshold: function(flag){
+ this._usingCustomScrollThreshold = flag;
+ },
+
+ /**
+ * Queries whether we are using user defined scroll page threshold or not
+ */
+ isUsingCustomScrollThreshold: function(){
+ return this._usingCustomScrollThreshold;
+ },
+
+ _handleReleaseLogic: function (touchPoint) {
+ if (this._pages.length <= 0)
+ return;
+ var curPage = this._pages[this._curPageIdx];
+ if (curPage) {
+ var curPagePos = curPage.getPosition();
+ var pageCount = this._pages.length;
+ var curPageLocation = curPagePos.x;
+ var pageWidth = this.getSize().width;
+ if (!this._usingCustomScrollThreshold)
+ this._customScrollThreshold = pageWidth / 2.0;
+ var boundary = this._customScrollThreshold;
+ if (curPageLocation <= -boundary) {
+ if (this._curPageIdx >= pageCount - 1)
+ this._scrollPages(-curPageLocation);
+ else
+ this.scrollToPage(this._curPageIdx + 1);
+ } else if (curPageLocation >= boundary) {
+ if (this._curPageIdx <= 0)
+ this._scrollPages(-curPageLocation);
+ else
+ this.scrollToPage(this._curPageIdx - 1);
+ } else
+ this.scrollToPage(this._curPageIdx);
+ }
+ },
+
+ /**
+ * Intercept touch event, handle its child's touch event.
+ * @param {cc.Event} event
+ */
+ interceptTouchEvent: function (event) {
+ var eventType = event._widgetEventType,
+ touch = event.currentTouch,
+ touchPoint, offset = 0;
+ if (!this._touchEnabled)
+ return;
+
+ touchPoint = touch.getLocation();
+ switch (eventType) {
+ case ccui.Widget.TOUCH_BEGAN:
+ this._touchBeganPosition.x = touchPoint.x;
+ this._touchBeganPosition.y = touchPoint.y;
+ this._isInterceptTouch = true;
+ break;
+ case ccui.Widget.TOUCH_MOVED:
+ this._touchMovePosition.x = touchPoint.x;
+ this._touchMovePosition.y = touchPoint.y;
+ offset = Math.abs(event.target.getTouchBeganPosition().x - touchPoint.x);
+ if (offset > this._childFocusCancelOffset) {
+ event.target.setHighlighted(false);
+ this._handleMoveLogic(touch);
+ }
+ break;
+ case ccui.Widget.TOUCH_ENDED:
+ case ccui.Widget.TOUCH_CANCELED:
+ this._touchEndPosition.x = touchPoint.x;
+ this._touchEndPosition.y = touchPoint.y;
+ this._handleReleaseLogic(touch);
+ if (event.target.isSwallowTouches())
+ this._isInterceptTouch = false;
+ break;
+ }
+ },
+
+ _pageTurningEvent: function () {
+ if(this._pageViewEventSelector){
+ if (this._pageViewEventListener)
+ this._pageViewEventSelector.call(this._pageViewEventListener, this, ccui.PageView.EVENT_TURNING);
+ else
+ this._pageViewEventSelector(this, ccui.PageView.EVENT_TURNING);
+ }
+ if(this._ccEventCallback)
+ this._ccEventCallback(this, ccui.PageView.EVENT_TURNING);
+ },
+
+ /**
+ * Adds event listener to ccui.PageView.
+ * @param {Function} selector
+ * @param {Object} [target=]
+ * @deprecated since v3.0, please use addEventListener instead.
+ */
+ addEventListenerPageView: function (selector, target) {
+ this.addEventListener(selector, target);
+ },
+
+ /**
+ * Adds event listener to ccui.PageView.
+ * @param {Function} selector
+ * @param {Object} [target=]
+ */
+ addEventListener: function(selector, target){
+ this._pageViewEventSelector = selector;
+ this._pageViewEventListener = target;
+ },
+
+ /**
+ * Returns current page index
+ * @returns {number}
+ */
+ getCurPageIndex: function () {
+ return this._curPageIdx;
+ },
+
+ /**
+ * Returns all pages of PageView
+ * @returns {Array}
+ */
+ getPages:function(){
+ return this._pages;
+ },
+
+ /**
+ * Returns a page from PageView by index
+ * @param {Number} index
+ * @returns {ccui.Layout}
+ */
+ getPage: function(index){
+ if (index < 0 || index >= this._pages.length)
+ return null;
+ return this._pages[index];
+ },
+
+ /**
+ * Returns the "class name" of ccui.PageView.
+ * @returns {string}
+ */
+ getDescription: function () {
+ return "PageView";
+ },
+
+ _createCloneInstance: function () {
+ return new ccui.PageView();
+ },
+
+ _copyClonedWidgetChildren: function (model) {
+ var arrayPages = model.getPages();
+ for (var i = 0; i < arrayPages.length; i++) {
+ var page = arrayPages[i];
+ this.addPage(page.clone());
+ }
+ },
+
+ _copySpecialProperties: function (pageView) {
+ ccui.Layout.prototype._copySpecialProperties.call(this, pageView);
+ this._ccEventCallback = pageView._ccEventCallback;
+ this._pageViewEventListener = pageView._pageViewEventListener;
+ this._pageViewEventSelector = pageView._pageViewEventSelector;
+ this._usingCustomScrollThreshold = pageView._usingCustomScrollThreshold;
+ this._customScrollThreshold = pageView._customScrollThreshold;
+ }
+});
+/**
+ * allocates and initializes a UIPageView.
+ * @deprecated since v3.0, please use new ccui.PageView() instead.
+ * @return {ccui.PageView}
+ */
+ccui.PageView.create = function () {
+ return new ccui.PageView();
+};
+
+// Constants
+//PageView event
+/**
+ * The turning flag of ccui.PageView's event.
+ * @constant
+ * @type {number}
+ */
+ccui.PageView.EVENT_TURNING = 0;
+
+//PageView touch direction
+/**
+ * The left flag of ccui.PageView's touch direction.
+ * @constant
+ * @type {number}
+ */
+ccui.PageView.TOUCH_DIR_LEFT = 0;
+/**
+ * The right flag of ccui.PageView's touch direction.
+ * @constant
+ * @type {number}
+ */
+ccui.PageView.TOUCH_DIR_RIGHT = 1;
+
+//PageView auto scroll direction
+/**
+ * The right flag of ccui.PageView's auto scroll direction.
+ * @constant
+ * @type {number}
+ */
+ccui.PageView.DIRECTION_LEFT = 0;
+/**
+ * The right flag of ccui.PageView's auto scroll direction.
+ * @constant
+ * @type {number}
+ */
+ccui.PageView.DIRECTION_RIGHT = 1;
diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js
new file mode 100644
index 0000000000..46c9356f20
--- /dev/null
+++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js
@@ -0,0 +1,1921 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+/**
+ * The ScrollView control of Cocos UI
+ * @class
+ * @extends ccui.Layout
+ *
+ * @property {Number} innerWidth - Inner container width of the scroll view
+ * @property {Number} innerHeight - Inner container height of the scroll view
+ * @property {ccui.ScrollView.Dir} direction - Scroll direction of the scroll view
+ * @property {Boolean} bounceEnabled - Indicate whether bounce is enabled
+ * @property {Boolean} inertiaScrollEnabled - Indicate whether inertiaScroll is enabled
+ */
+ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
+ _innerContainer: null,
+ direction: null,
+ _autoScrollDir: null,
+
+ _topBoundary: 0,
+ _bottomBoundary: 0,
+ _leftBoundary: 0,
+ _rightBoundary: 0,
+
+ _bounceTopBoundary: 0,
+ _bounceBottomBoundary: 0,
+ _bounceLeftBoundary: 0,
+ _bounceRightBoundary: 0,
+
+ _autoScroll: false,
+ _autoScrollAddUpTime: 0,
+
+ _autoScrollOriginalSpeed: 0,
+ _autoScrollAcceleration: 0,
+ _isAutoScrollSpeedAttenuated: false,
+ _needCheckAutoScrollDestination: false,
+ _autoScrollDestination: null,
+
+ _bePressed: false,
+ _slidTime: 0,
+ _moveChildPoint: null,
+ _childFocusCancelOffset: 0,
+
+ _leftBounceNeeded: false,
+ _topBounceNeeded: false,
+ _rightBounceNeeded: false,
+ _bottomBounceNeeded: false,
+
+ bounceEnabled: false,
+ _bouncing: false,
+ _bounceDir: null,
+ _bounceOriginalSpeed: 0,
+ inertiaScrollEnabled: false,
+
+ _scrollViewEventListener: null,
+ _scrollViewEventSelector: null,
+ _className: "ScrollView",
+
+ /**
+ * Allocates and initializes a UIScrollView.
+ * Constructor of ccui.ScrollView. override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
+ * @example
+ * // example
+ * var uiScrollView = new ccui.ScrollView();
+ */
+ ctor: function () {
+ ccui.Layout.prototype.ctor.call(this);
+ this.direction = ccui.ScrollView.Dir.NONE;
+ this._autoScrollDir = cc.p(0, 0);
+
+ this._autoScrollAcceleration = -1000;
+ this._autoScrollDestination = cc.p(0, 0);
+ this._slidTime = 0;
+ this._moveChildPoint = cc.p(0, 0);
+ this._childFocusCancelOffset = 5;
+ this._bounceDir = cc.p(0, 0);
+ this._bounceOriginalSpeed = 0;
+ this.inertiaScrollEnabled = true;
+ this.setTouchEnabled(true);
+
+ // For propagation
+ this.on(cc.Event.TOUCH, this.interceptTouchEvent);
+ },
+
+ /**
+ * Initializes a ccui.ScrollView. Please do not call this function by yourself, you should pass the parameters to constructor to initialize it.
+ * @returns {boolean}
+ */
+ init: function () {
+ if (ccui.Layout.prototype.init.call(this)) {
+ this.setClippingEnabled(true);
+ this._innerContainer.setTouchEnabled(false);
+ return true;
+ }
+ return false;
+ },
+
+ /**
+ * Calls the parent class' onEnter and schedules update function.
+ * @override
+ */
+ onEnter: function () {
+ ccui.Layout.prototype.onEnter.call(this);
+ this.scheduleUpdate(true);
+ },
+
+ /**
+ * When a widget is in a layout, you could call this method to get the next focused widget within a specified direction.
+ * If the widget is not in a layout, it will return itself
+ *
+ * @param {Number} direction the direction to look for the next focused widget in a layout
+ * @param {ccui.Widget} current the current focused widget
+ * @returns {ccui.Widget}
+ */
+ findNextFocusedWidget: function(direction, current){
+ if (this.getLayoutType() === ccui.Layout.Type.LINEAR_VERTICAL
+ || this.getLayoutType() === ccui.Layout.Type.LINEAR_HORIZONTAL) {
+ return this._innerContainer.findNextFocusedWidget(direction, current);
+ } else
+ return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, current);
+ },
+
+ _initRenderer: function () {
+ ccui.Layout.prototype._initRenderer.call(this);
+
+ this._innerContainer = new ccui.Layout();
+ this._innerContainer.setColor(cc.color(255,255,255));
+ this._innerContainer.setOpacity(255);
+ this._innerContainer.setCascadeColorEnabled(true);
+ this._innerContainer.setCascadeOpacityEnabled(true);
+
+ this.addProtectedChild(this._innerContainer, 1, 1);
+ },
+
+ _createRenderCmd: function(){
+ if(cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ return new ccui.ScrollView.WebGLRenderCmd(this);
+ else
+ return new ccui.ScrollView.CanvasRenderCmd(this);
+ },
+
+ _onSizeChanged: function () {
+ ccui.Layout.prototype._onSizeChanged.call(this);
+ var locSize = this._contentSize;
+ this._topBoundary = locSize.height;
+ this._rightBoundary = locSize.width;
+ var bounceBoundaryParameterX = locSize.width / 3;
+ var bounceBoundaryParameterY = locSize.height / 3;
+ this._bounceTopBoundary = locSize.height - bounceBoundaryParameterY;
+ this._bounceBottomBoundary = bounceBoundaryParameterY;
+ this._bounceLeftBoundary = bounceBoundaryParameterX;
+ this._bounceRightBoundary = locSize.width - bounceBoundaryParameterX;
+ var innerSize = this._innerContainer.getContentSize();
+ this._innerContainer.setContentSize(cc.size(Math.max(innerSize.width, locSize.width), Math.max(innerSize.height, locSize.height)));
+ this._innerContainer.setPosition(0, locSize.height - this._innerContainer.getContentSize().height);
+ },
+
+ /**
+ * Changes inner container size of ScrollView.
+ * Inner container size must be larger than or equal the size of ScrollView.
+ * @param {cc.Size} size inner container size.
+ */
+ setInnerContainerSize: function (size) {
+ var innerContainer = this._innerContainer;
+ var locSize = this._contentSize;
+ var innerSizeWidth = locSize.width, innerSizeHeight = locSize.height;
+ var originalInnerSize = innerContainer.getContentSize();
+ if (size.width < locSize.width)
+ cc.log("Inner width <= ScrollView width, it will be force sized!");
+ else
+ innerSizeWidth = size.width;
+
+ if (size.height < locSize.height)
+ cc.log("Inner height <= ScrollView height, it will be force sized!");
+ else
+ innerSizeHeight = size.height;
+
+ innerContainer.setContentSize(cc.size(innerSizeWidth, innerSizeHeight));
+ var newInnerSize, offset;
+ switch (this.direction) {
+ case ccui.ScrollView.Dir.VERTICAL:
+ newInnerSize = innerContainer.getContentSize();
+ offset = originalInnerSize.height - newInnerSize.height;
+ this._scrollChildren(0, offset);
+ break;
+ case ccui.ScrollView.Dir.HORIZONTAL:
+ if (innerContainer.getRightBoundary() <= locSize.width) {
+ newInnerSize = innerContainer.getContentSize();
+ offset = originalInnerSize.width - newInnerSize.width;
+ this._scrollChildren(offset, 0);
+ }
+ break;
+ case ccui.ScrollView.Dir.BOTH:
+ newInnerSize = innerContainer.getContentSize();
+ var offsetY = originalInnerSize.height - newInnerSize.height;
+ var offsetX = (innerContainer.getRightBoundary() <= locSize.width) ? originalInnerSize.width - newInnerSize.width : 0;
+ this._scrollChildren(offsetX, offsetY);
+ break;
+ default:
+ break;
+ }
+
+ var innerSize = innerContainer.getContentSize();
+ var innerPos = innerContainer.getPosition();
+ var innerAP = innerContainer.getAnchorPoint();
+ if (innerContainer.getLeftBoundary() > 0.0)
+ innerContainer.setPosition(innerAP.x * innerSize.width, innerPos.y);
+ if (innerContainer.getRightBoundary() < locSize.width)
+ innerContainer.setPosition(locSize.width - ((1.0 - innerAP.x) * innerSize.width), innerPos.y);
+ if (innerPos.y > 0.0)
+ innerContainer.setPosition(innerPos.x, innerAP.y * innerSize.height);
+ if (innerContainer.getTopBoundary() < locSize.height)
+ innerContainer.setPosition(innerPos.x, locSize.height - (1.0 - innerAP.y) * innerSize.height);
+ },
+
+ _setInnerWidth: function (width) {
+ var locW = this._contentSize.width,
+ innerWidth = locW,
+ container = this._innerContainer,
+ oldInnerWidth = container.width;
+ if (width < locW)
+ cc.log("Inner width <= scrollview width, it will be force sized!");
+ else
+ innerWidth = width;
+ container.width = innerWidth;
+
+ switch (this.direction) {
+ case ccui.ScrollView.Dir.HORIZONTAL:
+ case ccui.ScrollView.Dir.BOTH:
+ if (container.getRightBoundary() <= locW) {
+ var newInnerWidth = container.width;
+ var offset = oldInnerWidth - newInnerWidth;
+ this._scrollChildren(offset, 0);
+ }
+ break;
+ }
+ var innerAX = container.anchorX;
+ if (container.getLeftBoundary() > 0.0)
+ container.x = innerAX * innerWidth;
+ if (container.getRightBoundary() < locW)
+ container.x = locW - ((1.0 - innerAX) * innerWidth);
+ },
+
+ _setInnerHeight: function (height) {
+ var locH = this._contentSize.height,
+ innerHeight = locH,
+ container = this._innerContainer,
+ oldInnerHeight = container.height;
+ if (height < locH)
+ cc.log("Inner height <= scrollview height, it will be force sized!");
+ else
+ innerHeight = height;
+ container.height = innerHeight;
+
+ switch (this.direction) {
+ case ccui.ScrollView.Dir.VERTICAL:
+ case ccui.ScrollView.Dir.BOTH:
+ var newInnerHeight = innerHeight;
+ var offset = oldInnerHeight - newInnerHeight;
+ this._scrollChildren(0, offset);
+ break;
+ }
+ var innerAY = container.anchorY;
+ if (container.getLeftBoundary() > 0.0)
+ container.y = innerAY * innerHeight;
+ if (container.getRightBoundary() < locH)
+ container.y = locH - ((1.0 - innerAY) * innerHeight);
+ },
+
+ /**
+ * Returns inner container size of ScrollView.
+ * Inner container size must be larger than or equal ScrollView's size.
+ *
+ * @return {cc.Size} inner container size.
+ */
+ getInnerContainerSize: function () {
+ return this._innerContainer.getContentSize();
+ },
+ _getInnerWidth: function () {
+ return this._innerContainer.width;
+ },
+ _getInnerHeight: function () {
+ return this._innerContainer.height;
+ },
+
+ _isInContainer: function (widget) {
+ var wPos = widget._position,
+ wSize = widget._contentSize,
+ wAnchor = widget._anchorPoint,
+ size = this._customSize,
+ pos = this._innerContainer._position,
+ bottom = 0, left = 0;
+ if (
+ // Top
+ (bottom = wPos.y - wAnchor.y * wSize.height) >= size.height - pos.y ||
+ // Bottom
+ bottom + wSize.height <= -pos.y ||
+ // right
+ (left = wPos.x - wAnchor.x * wSize.width) >= size.width - pos.x ||
+ // left
+ left + wSize.width <= -pos.x
+ )
+ return false;
+ else return true;
+ },
+
+ updateChildren: function () {
+ var child;
+ var childrenArray = this._innerContainer._children;
+ for(var i = 0; i < childrenArray.length; i++) {
+ child = childrenArray[i];
+ if(child._inViewRect === true && this._isInContainer(child) === false)
+ child._inViewRect = false;
+ else if (child._inViewRect === false && this._isInContainer(child) === true)
+ child._inViewRect = true;
+ }
+ },
+ /**
+ * Add child to ccui.ScrollView.
+ * @param {cc.Node} widget
+ * @param {Number} [zOrder]
+ * @param {Number|string} [tag] tag or name
+ * @returns {boolean}
+ */
+ addChild: function (widget, zOrder, tag) {
+ if(!widget)
+ return false;
+ if(this._clippingEnabled && this._isInContainer(widget) === false)
+ widget._inViewRect = false;
+ zOrder = zOrder || widget.getLocalZOrder();
+ tag = tag || widget.getTag();
+ return this._innerContainer.addChild(widget, zOrder, tag);
+ },
+
+ /**
+ * Removes all children.
+ */
+ removeAllChildren: function () {
+ this.removeAllChildrenWithCleanup(true);
+ },
+
+ /**
+ * Removes all children.
+ * @param {Boolean} cleanup
+ */
+ removeAllChildrenWithCleanup: function(cleanup){
+ this._innerContainer.removeAllChildrenWithCleanup(cleanup);
+ },
+
+ /**
+ * Removes widget child
+ * @override
+ * @param {ccui.Widget} child
+ * @param {Boolean} cleanup
+ * @returns {boolean}
+ */
+ removeChild: function (child, cleanup) {
+ return this._innerContainer.removeChild(child, cleanup);
+ },
+
+ /**
+ * Returns inner container's children
+ * @returns {Array}
+ */
+ getChildren: function () {
+ return this._innerContainer.getChildren();
+ },
+
+ /**
+ * Gets the count of inner container's children
+ * @returns {Number}
+ */
+ getChildrenCount: function () {
+ return this._innerContainer.getChildrenCount();
+ },
+
+ /**
+ * Gets a child from the container given its tag
+ * @param {Number} tag
+ * @returns {ccui.Widget}
+ */
+ getChildByTag: function (tag) {
+ return this._innerContainer.getChildByTag(tag);
+ },
+
+ /**
+ * Gets a child from the container given its name
+ * @param {String} name
+ * @returns {ccui.Widget}
+ */
+ getChildByName: function (name) {
+ return this._innerContainer.getChildByName(name);
+ },
+
+ _moveChildren: function (offsetX, offsetY) {
+ var locContainer = this._innerContainer;
+ //var pos = this._innerContainer.getPosition();
+ this._moveChildPoint.x = locContainer.x + offsetX;
+ this._moveChildPoint.y = locContainer.y + offsetY;
+ this._innerContainer.setPosition(this._moveChildPoint);
+ if(this._clippingEnabled && this._innerContainer._children.length !== 0 )
+ this.updateChildren();
+ },
+
+ _autoScrollChildren: function (dt) {
+ var lastTime = this._autoScrollAddUpTime;
+ this._autoScrollAddUpTime += dt;
+ if (this._isAutoScrollSpeedAttenuated) {
+ var nowSpeed = this._autoScrollOriginalSpeed + this._autoScrollAcceleration * this._autoScrollAddUpTime;
+ if (nowSpeed <= 0) {
+ this._stopAutoScrollChildren();
+ this._checkNeedBounce();
+ } else {
+ var timeParam = lastTime * 2 + dt;
+ var offset = (this._autoScrollOriginalSpeed + this._autoScrollAcceleration * timeParam * 0.5) * dt;
+ var offsetX = offset * this._autoScrollDir.x;
+ var offsetY = offset * this._autoScrollDir.y;
+ if (!this._scrollChildren(offsetX, offsetY)) {
+ this._stopAutoScrollChildren();
+ this._checkNeedBounce();
+ }
+ }
+ } else {
+ if (this._needCheckAutoScrollDestination) {
+ var xOffset = this._autoScrollDir.x * dt * this._autoScrollOriginalSpeed;
+ var yOffset = this._autoScrollDir.y * dt * this._autoScrollOriginalSpeed;
+ var notDone = this._checkCustomScrollDestination(xOffset, yOffset);
+ var scrollCheck = this._scrollChildren(xOffset, yOffset);
+ if (!notDone || !scrollCheck) {
+ this._stopAutoScrollChildren();
+ this._checkNeedBounce();
+ }
+ } else {
+ if (!this._scrollChildren(this._autoScrollDir.x * dt * this._autoScrollOriginalSpeed,
+ this._autoScrollDir.y * dt * this._autoScrollOriginalSpeed)) {
+ this._stopAutoScrollChildren();
+ this._checkNeedBounce();
+ }
+ }
+ }
+ },
+
+ _bounceChildren: function (dt) {
+ var locSpeed = this._bounceOriginalSpeed;
+ var locBounceDir = this._bounceDir;
+ if (locSpeed <= 0.0)
+ this._stopBounceChildren();
+ if (!this._bounceScrollChildren(locBounceDir.x * dt * locSpeed, locBounceDir.y * dt * locSpeed))
+ this._stopBounceChildren();
+ },
+
+ _checkNeedBounce: function () {
+ if (!this.bounceEnabled)
+ return false;
+ this._checkBounceBoundary();
+ var locTopBounceNeeded = this._topBounceNeeded, locBottomBounceNeeded = this._bottomBounceNeeded,
+ locLeftBounceNeeded = this._leftBounceNeeded, locRightBounceNeeded = this._rightBounceNeeded;
+
+ if (locTopBounceNeeded || locBottomBounceNeeded || locLeftBounceNeeded || locRightBounceNeeded) {
+ var scrollVector, orSpeed;
+ var locContentSize = this._contentSize, locInnerContainer = this._innerContainer;
+ if (locTopBounceNeeded && locLeftBounceNeeded) {
+ scrollVector = cc.pSub(cc.p(0.0, locContentSize.height), cc.p(locInnerContainer.getLeftBoundary(), locInnerContainer.getTopBoundary()));
+ orSpeed = cc.pLength(scrollVector) / 0.2;
+ this._bounceDir = cc.pNormalize(scrollVector);
+ this._startBounceChildren(orSpeed);
+ } else if (locTopBounceNeeded && locRightBounceNeeded) {
+ scrollVector = cc.pSub(cc.p(locContentSize.width, locContentSize.height), cc.p(locInnerContainer.getRightBoundary(), locInnerContainer.getTopBoundary()));
+ orSpeed = cc.pLength(scrollVector) / 0.2;
+ this._bounceDir = cc.pNormalize(scrollVector);
+ this._startBounceChildren(orSpeed);
+ } else if (locBottomBounceNeeded && locLeftBounceNeeded) {
+ scrollVector = cc.pSub(cc.p(0, 0), cc.p(locInnerContainer.getLeftBoundary(), locInnerContainer.getBottomBoundary()));
+ orSpeed = cc.pLength(scrollVector) / 0.2;
+ this._bounceDir = cc.pNormalize(scrollVector);
+ this._startBounceChildren(orSpeed);
+ } else if (locBottomBounceNeeded && locRightBounceNeeded) {
+ scrollVector = cc.pSub(cc.p(locContentSize.width, 0.0), cc.p(locInnerContainer.getRightBoundary(), locInnerContainer.getBottomBoundary()));
+ orSpeed = cc.pLength(scrollVector) / 0.2;
+ this._bounceDir = cc.pNormalize(scrollVector);
+ this._startBounceChildren(orSpeed);
+ } else if (locTopBounceNeeded) {
+ scrollVector = cc.pSub(cc.p(0, locContentSize.height), cc.p(0.0, locInnerContainer.getTopBoundary()));
+ orSpeed = cc.pLength(scrollVector) / 0.2;
+ this._bounceDir = cc.pNormalize(scrollVector);
+ this._startBounceChildren(orSpeed);
+ } else if (locBottomBounceNeeded) {
+ scrollVector = cc.pSub(cc.p(0, 0), cc.p(0.0, locInnerContainer.getBottomBoundary()));
+ orSpeed = cc.pLength(scrollVector) / 0.2;
+ this._bounceDir = cc.pNormalize(scrollVector);
+ this._startBounceChildren(orSpeed);
+ } else if (locLeftBounceNeeded) {
+ scrollVector = cc.pSub(cc.p(0, 0), cc.p(locInnerContainer.getLeftBoundary(), 0.0));
+ orSpeed = cc.pLength(scrollVector) / 0.2;
+ this._bounceDir = cc.pNormalize(scrollVector);
+ this._startBounceChildren(orSpeed);
+ } else if (locRightBounceNeeded) {
+ scrollVector = cc.pSub(cc.p(locContentSize.width, 0), cc.p(locInnerContainer.getRightBoundary(), 0.0));
+ orSpeed = cc.pLength(scrollVector) / 0.2;
+ this._bounceDir = cc.pNormalize(scrollVector);
+ this._startBounceChildren(orSpeed);
+ }
+ return true;
+ }
+ return false;
+ },
+
+ _checkBounceBoundary: function () {
+ var locContainer = this._innerContainer;
+ var icBottomPos = locContainer.getBottomBoundary();
+ if (icBottomPos > this._bottomBoundary) {
+ this._scrollToBottomEvent();
+ this._bottomBounceNeeded = true;
+ } else
+ this._bottomBounceNeeded = false;
+
+ var icTopPos = locContainer.getTopBoundary();
+ if (icTopPos < this._topBoundary) {
+ this._scrollToTopEvent();
+ this._topBounceNeeded = true;
+ } else
+ this._topBounceNeeded = false;
+
+ var icRightPos = locContainer.getRightBoundary();
+ if (icRightPos < this._rightBoundary) {
+ this._scrollToRightEvent();
+ this._rightBounceNeeded = true;
+ } else
+ this._rightBounceNeeded = false;
+
+ var icLeftPos = locContainer.getLeftBoundary();
+ if (icLeftPos > this._leftBoundary) {
+ this._scrollToLeftEvent();
+ this._leftBounceNeeded = true;
+ } else
+ this._leftBounceNeeded = false;
+ },
+
+ _startBounceChildren: function (v) {
+ this._bounceOriginalSpeed = v;
+ this._bouncing = true;
+ },
+
+ _stopBounceChildren: function () {
+ this._bouncing = false;
+ this._bounceOriginalSpeed = 0.0;
+ this._leftBounceNeeded = false;
+ this._rightBounceNeeded = false;
+ this._topBounceNeeded = false;
+ this._bottomBounceNeeded = false;
+ },
+
+ _startAutoScrollChildrenWithOriginalSpeed: function (dir, v, attenuated, acceleration) {
+ this._stopAutoScrollChildren();
+ this._autoScrollDir.x = dir.x;
+ this._autoScrollDir.y = dir.y;
+ this._isAutoScrollSpeedAttenuated = attenuated;
+ this._autoScrollOriginalSpeed = v;
+ this._autoScroll = true;
+ this._autoScrollAcceleration = acceleration;
+ },
+
+ _startAutoScrollChildrenWithDestination: function (des, time, attenuated) {
+ this._needCheckAutoScrollDestination = false;
+ this._autoScrollDestination = des;
+ var dis = cc.pSub(des, this._innerContainer.getPosition());
+ var dir = cc.pNormalize(dis);
+ var orSpeed = 0.0;
+ var acceleration = -1000.0;
+ var disLength = cc.pLength(dis);
+ if (attenuated) {
+ acceleration = -(2 * disLength) / (time * time);
+ orSpeed = 2 * disLength / time;
+ } else {
+ this._needCheckAutoScrollDestination = true;
+ orSpeed = disLength / time;
+ }
+ this._startAutoScrollChildrenWithOriginalSpeed(dir, orSpeed, attenuated, acceleration);
+ },
+
+ _jumpToDestination: function (dstX, dstY) {
+ if (dstX.x !== undefined) {
+ dstY = dstX.y;
+ dstX = dstX.x;
+ }
+ var finalOffsetX = dstX;
+ var finalOffsetY = dstY;
+ switch (this.direction) {
+ case ccui.ScrollView.Dir.VERTICAL:
+ if (dstY <= 0)
+ finalOffsetY = Math.max(dstY, this._contentSize.height - this._innerContainer.getContentSize().height);
+ break;
+ case ccui.ScrollView.Dir.HORIZONTAL:
+ if (dstX <= 0)
+ finalOffsetX = Math.max(dstX, this._contentSize.width - this._innerContainer.getContentSize().width);
+ break;
+ case ccui.ScrollView.Dir.BOTH:
+ if (dstY <= 0)
+ finalOffsetY = Math.max(dstY, this._contentSize.height - this._innerContainer.getContentSize().height);
+ if (dstX <= 0)
+ finalOffsetX = Math.max(dstX, this._contentSize.width - this._innerContainer.getContentSize().width);
+ break;
+ default:
+ break;
+ }
+ this._innerContainer.setPosition(finalOffsetX, finalOffsetY);
+ },
+
+ _stopAutoScrollChildren: function () {
+ this._autoScroll = false;
+ this._autoScrollOriginalSpeed = 0;
+ this._autoScrollAddUpTime = 0;
+ },
+
+ _bounceScrollChildren: function (touchOffsetX, touchOffsetY) {
+ var scrollEnabled = true;
+ var realOffsetX, realOffsetY, icRightPos, icTopPos, icBottomPos;
+ var locContainer = this._innerContainer;
+ if (touchOffsetX > 0.0 && touchOffsetY > 0.0){ //first quadrant //bounce to top-right
+ realOffsetX = touchOffsetX;
+ realOffsetY = touchOffsetY;
+ icRightPos = locContainer.getRightBoundary();
+ if (icRightPos + realOffsetX >= this._rightBoundary) {
+ realOffsetX = this._rightBoundary - icRightPos;
+ this._bounceRightEvent();
+ scrollEnabled = false;
+ }
+ icTopPos = locContainer.getTopBoundary();
+ if (icTopPos + touchOffsetY >= this._topBoundary) {
+ realOffsetY = this._topBoundary - icTopPos;
+ this._bounceTopEvent();
+ scrollEnabled = false;
+ }
+ this._moveChildren(realOffsetX, realOffsetY);
+ } else if (touchOffsetX < 0.0 && touchOffsetY > 0.0){ //second quadrant //bounce to top-left
+ realOffsetX = touchOffsetX;
+ realOffsetY = touchOffsetY;
+ icLefrPos = locContainer.getLeftBoundary();
+ if (icLefrPos + realOffsetX <= this._leftBoundary) {
+ realOffsetX = this._leftBoundary - icLefrPos;
+ this._bounceLeftEvent();
+ scrollEnabled = false;
+ }
+ icTopPos = locContainer.getTopBoundary();
+ if (icTopPos + touchOffsetY >= this._topBoundary) {
+ realOffsetY = this._topBoundary - icTopPos;
+ this._bounceTopEvent();
+ scrollEnabled = false;
+ }
+ this._moveChildren(realOffsetX, realOffsetY);
+ }else if (touchOffsetX < 0.0 && touchOffsetY < 0.0){ //third quadrant //bounce to bottom-left
+ realOffsetX = touchOffsetX;
+ realOffsetY = touchOffsetY;
+ var icLefrPos = locContainer.getLeftBoundary();
+ if (icLefrPos + realOffsetX <= this._leftBoundary) {
+ realOffsetX = this._leftBoundary - icLefrPos;
+ this._bounceLeftEvent();
+ scrollEnabled = false;
+ }
+ icBottomPos = locContainer.getBottomBoundary();
+ if (icBottomPos + touchOffsetY <= this._bottomBoundary) {
+ realOffsetY = this._bottomBoundary - icBottomPos;
+ this._bounceBottomEvent();
+ scrollEnabled = false;
+ }
+ this._moveChildren(realOffsetX, realOffsetY);
+ } else if (touchOffsetX > 0.0 && touchOffsetY < 0.0){ //forth quadrant //bounce to bottom-right
+ realOffsetX = touchOffsetX;
+ realOffsetY = touchOffsetY;
+ icRightPos = locContainer.getRightBoundary();
+ if (icRightPos + realOffsetX >= this._rightBoundary) {
+ realOffsetX = this._rightBoundary - icRightPos;
+ this._bounceRightEvent();
+ scrollEnabled = false;
+ }
+ icBottomPos = locContainer.getBottomBoundary();
+ if (icBottomPos + touchOffsetY <= this._bottomBoundary) {
+ realOffsetY = this._bottomBoundary - icBottomPos;
+ this._bounceBottomEvent();
+ scrollEnabled = false;
+ }
+ this._moveChildren(realOffsetX, realOffsetY);
+ } else if (touchOffsetX === 0.0 && touchOffsetY > 0.0){ // bounce to top
+ realOffsetY = touchOffsetY;
+ icTopPos = locContainer.getTopBoundary();
+ if (icTopPos + touchOffsetY >= this._topBoundary) {
+ realOffsetY = this._topBoundary - icTopPos;
+ this._bounceTopEvent();
+ scrollEnabled = false;
+ }
+ this._moveChildren(0.0, realOffsetY);
+ } else if (touchOffsetX === 0.0 && touchOffsetY < 0.0) {//bounce to bottom
+ realOffsetY = touchOffsetY;
+ icBottomPos = locContainer.getBottomBoundary();
+ if (icBottomPos + touchOffsetY <= this._bottomBoundary) {
+ realOffsetY = this._bottomBoundary - icBottomPos;
+ this._bounceBottomEvent();
+ scrollEnabled = false;
+ }
+ this._moveChildren(0.0, realOffsetY);
+ } else if (touchOffsetX > 0.0 && touchOffsetY === 0.0){ //bounce to right
+ realOffsetX = touchOffsetX;
+ icRightPos = locContainer.getRightBoundary();
+ if (icRightPos + realOffsetX >= this._rightBoundary) {
+ realOffsetX = this._rightBoundary - icRightPos;
+ this._bounceRightEvent();
+ scrollEnabled = false;
+ }
+ this._moveChildren(realOffsetX, 0.0);
+ }else if (touchOffsetX < 0.0 && touchOffsetY === 0.0){ //bounce to left
+ realOffsetX = touchOffsetX;
+ var icLeftPos = locContainer.getLeftBoundary();
+ if (icLeftPos + realOffsetX <= this._leftBoundary) {
+ realOffsetX = this._leftBoundary - icLeftPos;
+ this._bounceLeftEvent();
+ scrollEnabled = false;
+ }
+ this._moveChildren(realOffsetX, 0.0);
+ }
+ return scrollEnabled;
+ },
+
+ _checkCustomScrollDestination: function (touchOffsetX, touchOffsetY) {
+ var scrollEnabled = true;
+ var icBottomPos, icLeftPos, icRightPos, icTopPos;
+ var locContainer = this._innerContainer, locDestination = this._autoScrollDestination;
+ switch (this.direction) {
+ case ccui.ScrollView.Dir.VERTICAL:
+ if (this._autoScrollDir.y > 0) {
+ icBottomPos = locContainer.getBottomBoundary();
+ if (icBottomPos + touchOffsetY >= locDestination.y) {
+ touchOffsetY = locDestination.y - icBottomPos;
+ scrollEnabled = false;
+ }
+ } else {
+ icBottomPos = locContainer.getBottomBoundary();
+ if (icBottomPos + touchOffsetY <= locDestination.y) {
+ touchOffsetY = locDestination.y - icBottomPos;
+ scrollEnabled = false;
+ }
+ }
+ break;
+ case ccui.ScrollView.Dir.HORIZONTAL:
+ if (this._autoScrollDir.x > 0) {
+ icLeftPos = locContainer.getLeftBoundary();
+ if (icLeftPos + touchOffsetX >= locDestination.x) {
+ touchOffsetX = locDestination.x - icLeftPos;
+ scrollEnabled = false;
+ }
+ } else {
+ icLeftPos = locContainer.getLeftBoundary();
+ if (icLeftPos + touchOffsetX <= locDestination.x) {
+ touchOffsetX = locDestination.x - icLeftPos;
+ scrollEnabled = false;
+ }
+ }
+ break;
+ case ccui.ScrollView.Dir.BOTH:
+ if (touchOffsetX > 0.0 && touchOffsetY > 0.0){ // up right
+ icLeftPos = locContainer.getLeftBoundary();
+ if (icLeftPos + touchOffsetX >= locDestination.x) {
+ touchOffsetX = locDestination.x - icLeftPos;
+ scrollEnabled = false;
+ }
+ icBottomPos = locContainer.getBottomBoundary();
+ if (icBottomPos + touchOffsetY >= locDestination.y) {
+ touchOffsetY = locDestination.y - icBottomPos;
+ scrollEnabled = false;
+ }
+ } else if (touchOffsetX < 0.0 && touchOffsetY > 0.0){ // up left
+ icRightPos = locContainer.getRightBoundary();
+ if (icRightPos + touchOffsetX <= locDestination.x) {
+ touchOffsetX = locDestination.x - icRightPos;
+ scrollEnabled = false;
+ }
+ icBottomPos = locContainer.getBottomBoundary();
+ if (icBottomPos + touchOffsetY >= locDestination.y) {
+ touchOffsetY = locDestination.y - icBottomPos;
+ scrollEnabled = false;
+ }
+ } else if (touchOffsetX < 0.0 && touchOffsetY < 0.0){ // down left
+ icRightPos = locContainer.getRightBoundary();
+ if (icRightPos + touchOffsetX <= locDestination.x) {
+ touchOffsetX = locDestination.x - icRightPos;
+ scrollEnabled = false;
+ }
+ icTopPos = locContainer.getTopBoundary();
+ if (icTopPos + touchOffsetY <= locDestination.y) {
+ touchOffsetY = locDestination.y - icTopPos;
+ scrollEnabled = false;
+ }
+ } else if (touchOffsetX > 0.0 && touchOffsetY < 0.0){ // down right
+ icLeftPos = locContainer.getLeftBoundary();
+ if (icLeftPos + touchOffsetX >= locDestination.x) {
+ touchOffsetX = locDestination.x - icLeftPos;
+ scrollEnabled = false;
+ }
+ icTopPos = locContainer.getTopBoundary();
+ if (icTopPos + touchOffsetY <= locDestination.y) {
+ touchOffsetY = locDestination.y - icTopPos;
+ scrollEnabled = false;
+ }
+ } else if (touchOffsetX === 0.0 && touchOffsetY > 0.0){ // up
+ icBottomPos = locContainer.getBottomBoundary();
+ if (icBottomPos + touchOffsetY >= locDestination.y) {
+ touchOffsetY = locDestination.y - icBottomPos;
+ scrollEnabled = false;
+ }
+ } else if (touchOffsetX < 0.0 && touchOffsetY === 0.0){ // left
+ icRightPos = locContainer.getRightBoundary();
+ if (icRightPos + touchOffsetX <= locDestination.x) {
+ touchOffsetX = locDestination.x - icRightPos;
+ scrollEnabled = false;
+ }
+ } else if (touchOffsetX === 0.0 && touchOffsetY < 0.0){ // down
+ icTopPos = locContainer.getTopBoundary();
+ if (icTopPos + touchOffsetY <= locDestination.y) {
+ touchOffsetY = locDestination.y - icTopPos;
+ scrollEnabled = false;
+ }
+ } else if (touchOffsetX > 0.0 && touchOffsetY === 0.0){ // right
+ icLeftPos = locContainer.getLeftBoundary();
+ if (icLeftPos + touchOffsetX >= locDestination.x) {
+ touchOffsetX = locDestination.x - icLeftPos;
+ scrollEnabled = false;
+ }
+ }
+ break;
+ default:
+ break;
+ }
+ return scrollEnabled;
+ },
+
+ _scrollChildren: function (touchOffsetX, touchOffsetY) {
+ var scrollEnabled = true;
+ this._scrollingEvent();
+ switch (this.direction) {
+ case ccui.ScrollView.Dir.VERTICAL: // vertical
+ scrollEnabled = this._scrollChildrenVertical(touchOffsetX, touchOffsetY);
+ break;
+ case ccui.ScrollView.Dir.HORIZONTAL: // horizontal
+ scrollEnabled = this._scrollChildrenHorizontal(touchOffsetX, touchOffsetY);
+ break;
+ case ccui.ScrollView.Dir.BOTH:
+ scrollEnabled = this._scrollChildrenBoth(touchOffsetX, touchOffsetY);
+ break;
+ default:
+ break;
+ }
+ return scrollEnabled;
+ },
+
+ _scrollChildrenVertical: function(touchOffsetX, touchOffsetY){
+ var realOffset = touchOffsetY;
+ var scrollEnabled = true;
+ var icBottomPos, icTopPos, locContainer = this._innerContainer;
+ if (this.bounceEnabled) {
+ icBottomPos = locContainer.getBottomBoundary();
+ if (icBottomPos + touchOffsetY >= this._bounceBottomBoundary) {
+ realOffset = this._bounceBottomBoundary - icBottomPos;
+ this._scrollToBottomEvent();
+ scrollEnabled = false;
+ }
+ icTopPos = locContainer.getTopBoundary();
+ if (icTopPos + touchOffsetY <= this._bounceTopBoundary) {
+ realOffset = this._bounceTopBoundary - icTopPos;
+ this._scrollToTopEvent();
+ scrollEnabled = false;
+
+ }
+ } else {
+ icBottomPos = locContainer.getBottomBoundary();
+ if (icBottomPos + touchOffsetY >= this._bottomBoundary){
+ realOffset = this._bottomBoundary - icBottomPos;
+ this._scrollToBottomEvent();
+ scrollEnabled = false;
+ }
+ icTopPos = locContainer.getTopBoundary();
+ if (icTopPos + touchOffsetY <= this._topBoundary) {
+ realOffset = this._topBoundary - icTopPos;
+ this._scrollToTopEvent();
+ scrollEnabled = false;
+ }
+ }
+ this._moveChildren(0.0, realOffset);
+ return scrollEnabled;
+ },
+
+ _scrollChildrenHorizontal: function(touchOffsetX, touchOffestY){
+ var scrollEnabled = true;
+ var realOffset = touchOffsetX;
+ var icRightPos, icLeftPos, locContainer = this._innerContainer;
+ if (this.bounceEnabled){
+ icRightPos = locContainer.getRightBoundary();
+ if (icRightPos + touchOffsetX <= this._bounceRightBoundary) {
+ realOffset = this._bounceRightBoundary - icRightPos;
+ this._scrollToRightEvent();
+ scrollEnabled = false;
+ }
+ icLeftPos = locContainer.getLeftBoundary();
+ if (icLeftPos + touchOffsetX >= this._bounceLeftBoundary) {
+ realOffset = this._bounceLeftBoundary - icLeftPos;
+ this._scrollToLeftEvent();
+ scrollEnabled = false;
+ }
+ } else {
+ icRightPos = locContainer.getRightBoundary();
+ if (icRightPos + touchOffsetX <= this._rightBoundary) {
+ realOffset = this._rightBoundary - icRightPos;
+ this._scrollToRightEvent();
+ scrollEnabled = false;
+ }
+ icLeftPos = locContainer.getLeftBoundary();
+ if (icLeftPos + touchOffsetX >= this._leftBoundary) {
+ realOffset = this._leftBoundary - icLeftPos;
+ this._scrollToLeftEvent();
+ scrollEnabled = false;
+ }
+ }
+ this._moveChildren(realOffset, 0.0);
+ return scrollEnabled;
+ },
+
+ _scrollChildrenBoth: function (touchOffsetX, touchOffsetY) {
+ var scrollEnabled = true;
+ var realOffsetX = touchOffsetX;
+ var realOffsetY = touchOffsetY;
+ var icLeftPos, icBottomPos, icRightPos, icTopPos;
+ var locContainer = this._innerContainer;
+ if (this.bounceEnabled) {
+ if (touchOffsetX > 0.0 && touchOffsetY > 0.0) { // up right
+ icLeftPos = locContainer.getLeftBoundary();
+ if (icLeftPos + touchOffsetX >= this._bounceLeftBoundary) {
+ realOffsetX = this._bounceLeftBoundary - icLeftPos;
+ this._scrollToLeftEvent();
+ scrollEnabled = false;
+ }
+ icBottomPos = locContainer.getBottomBoundary();
+ if (icBottomPos + touchOffsetY >= this._bounceBottomBoundary) {
+ realOffsetY = this._bounceBottomBoundary - icBottomPos;
+ this._scrollToBottomEvent();
+ scrollEnabled = false;
+ }
+ } else if (touchOffsetX < 0.0 && touchOffsetY > 0.0) { // up left
+ icRightPos = locContainer.getRightBoundary();
+ if (icRightPos + touchOffsetX <= this._bounceRightBoundary) {
+ realOffsetX = this._bounceRightBoundary - icRightPos;
+ this._scrollToRightEvent();
+ scrollEnabled = false;
+ }
+ icBottomPos = locContainer.getBottomBoundary();
+ if (icBottomPos + touchOffsetY >= this._bounceBottomBoundary) {
+ realOffsetY = this._bounceBottomBoundary - icBottomPos;
+ this._scrollToBottomEvent();
+ scrollEnabled = false;
+ }
+ } else if (touchOffsetX < 0.0 && touchOffsetY < 0.0) { // down left
+ icRightPos = locContainer.getRightBoundary();
+ if (icRightPos + touchOffsetX <= this._bounceRightBoundary) {
+ realOffsetX = this._bounceRightBoundary - icRightPos;
+ this._scrollToRightEvent();
+ scrollEnabled = false;
+ }
+ icTopPos = locContainer.getTopBoundary();
+ if (icTopPos + touchOffsetY <= this._bounceTopBoundary) {
+ realOffsetY = this._bounceTopBoundary - icTopPos;
+ this._scrollToTopEvent();
+ scrollEnabled = false;
+ }
+ } else if (touchOffsetX > 0.0 && touchOffsetY < 0.0){ // down right
+ icLeftPos = locContainer.getLeftBoundary();
+ if (icLeftPos + touchOffsetX >= this._bounceLeftBoundary) {
+ realOffsetX = this._bounceLeftBoundary - icLeftPos;
+ this._scrollToLeftEvent();
+ scrollEnabled = false;
+ }
+ icTopPos = locContainer.getTopBoundary();
+ if (icTopPos + touchOffsetY <= this._bounceTopBoundary) {
+ realOffsetY = this._bounceTopBoundary - icTopPos;
+ this._scrollToTopEvent();
+ scrollEnabled = false;
+ }
+ } else if (touchOffsetX === 0.0 && touchOffsetY > 0.0){ // up
+ icBottomPos = locContainer.getBottomBoundary();
+ if (icBottomPos + touchOffsetY >= this._bounceBottomBoundary) {
+ realOffsetY = this._bounceBottomBoundary - icBottomPos;
+ this._scrollToBottomEvent();
+ scrollEnabled = false;
+ }
+ } else if (touchOffsetX < 0.0 && touchOffsetY === 0.0){ // left
+ icRightPos = locContainer.getRightBoundary();
+ if (icRightPos + touchOffsetX <= this._bounceRightBoundary) {
+ realOffsetX = this._bounceRightBoundary - icRightPos;
+ this._scrollToRightEvent();
+ scrollEnabled = false;
+ }
+ } else if (touchOffsetX === 0.0 && touchOffsetY < 0.0){ // down
+ icTopPos = locContainer.getTopBoundary();
+ if (icTopPos + touchOffsetY <= this._bounceTopBoundary) {
+ realOffsetY = this._bounceTopBoundary - icTopPos;
+ this._scrollToTopEvent();
+ scrollEnabled = false;
+ }
+ } else if (touchOffsetX > 0.0 && touchOffsetY === 0.0){ // right
+ icLeftPos = locContainer.getLeftBoundary();
+ if (icLeftPos + touchOffsetX >= this._bounceLeftBoundary) {
+ realOffsetX = this._bounceLeftBoundary - icLeftPos;
+ this._scrollToLeftEvent();
+ scrollEnabled = false;
+ }
+ }
+ } else {
+ if (touchOffsetX > 0.0 && touchOffsetY > 0.0){ // up right
+ icLeftPos = locContainer.getLeftBoundary();
+ if (icLeftPos + touchOffsetX >= this._leftBoundary) {
+ realOffsetX = this._leftBoundary - icLeftPos;
+ this._scrollToLeftEvent();
+ scrollEnabled = false;
+ }
+ icBottomPos = locContainer.getBottomBoundary();
+ if (icBottomPos + touchOffsetY >= this._bottomBoundary) {
+ realOffsetY = this._bottomBoundary - icBottomPos;
+ this._scrollToBottomEvent();
+ scrollEnabled = false;
+ }
+ } else if (touchOffsetX < 0.0 && touchOffsetY > 0.0){ // up left
+ icRightPos = locContainer.getRightBoundary();
+ if (icRightPos + touchOffsetX <= this._rightBoundary) {
+ realOffsetX = this._rightBoundary - icRightPos;
+ this._scrollToRightEvent();
+ scrollEnabled = false;
+ }
+ icBottomPos = locContainer.getBottomBoundary();
+ if (icBottomPos + touchOffsetY >= this._bottomBoundary) {
+ realOffsetY = this._bottomBoundary - icBottomPos;
+ this._scrollToBottomEvent();
+ scrollEnabled = false;
+ }
+ } else if (touchOffsetX < 0.0 && touchOffsetY < 0.0){ // down left
+ icRightPos = locContainer.getRightBoundary();
+ if (icRightPos + touchOffsetX <= this._rightBoundary) {
+ realOffsetX = this._rightBoundary - icRightPos;
+ this._scrollToRightEvent();
+ scrollEnabled = false;
+ }
+ icTopPos = locContainer.getTopBoundary();
+ if (icTopPos + touchOffsetY <= this._topBoundary) {
+ realOffsetY = this._topBoundary - icTopPos;
+ this._scrollToTopEvent();
+ scrollEnabled = false;
+ }
+ } else if (touchOffsetX > 0.0 && touchOffsetY < 0.0){ // down right
+ icLeftPos = locContainer.getLeftBoundary();
+ if (icLeftPos + touchOffsetX >= this._leftBoundary) {
+ realOffsetX = this._leftBoundary - icLeftPos;
+ this._scrollToLeftEvent();
+ scrollEnabled = false;
+ }
+ icTopPos = this._innerContainer.getTopBoundary();
+ if (icTopPos + touchOffsetY <= this._topBoundary) {
+ realOffsetY = this._topBoundary - icTopPos;
+ this._scrollToTopEvent();
+ scrollEnabled = false;
+ }
+ } else if (touchOffsetX === 0.0 && touchOffsetY > 0.0) { // up
+ icBottomPos = this._innerContainer.getBottomBoundary();
+ if (icBottomPos + touchOffsetY >= this._bottomBoundary) {
+ realOffsetY = this._bottomBoundary - icBottomPos;
+ this._scrollToBottomEvent();
+ scrollEnabled = false;
+ }
+ } else if (touchOffsetX < 0.0 && touchOffsetY === 0.0){ // left
+ icRightPos = this._innerContainer.getRightBoundary();
+ if (icRightPos + touchOffsetX <= this._rightBoundary) {
+ realOffsetX = this._rightBoundary - icRightPos;
+ this._scrollToRightEvent();
+ scrollEnabled = false;
+ }
+ } else if (touchOffsetX === 0.0 && touchOffsetY < 0.0){ // down
+ icTopPos = this._innerContainer.getTopBoundary();
+ if (icTopPos + touchOffsetY <= this._topBoundary) {
+ realOffsetY = this._topBoundary - icTopPos;
+ this._scrollToTopEvent();
+ scrollEnabled = false;
+ }
+ } else if (touchOffsetX > 0.0 && touchOffsetY === 0.0){ // right
+ icLeftPos = this._innerContainer.getLeftBoundary();
+ if (icLeftPos + touchOffsetX >= this._leftBoundary) {
+ realOffsetX = this._leftBoundary - icLeftPos;
+ this._scrollToLeftEvent();
+ scrollEnabled = false;
+ }
+ }
+ }
+ this._moveChildren(realOffsetX, realOffsetY);
+ return scrollEnabled;
+ },
+
+ /**
+ * Scroll inner container to bottom boundary of ScrollView.
+ * @param {Number} time
+ * @param {Boolean} attenuated
+ */
+ scrollToBottom: function (time, attenuated) {
+ this._startAutoScrollChildrenWithDestination(cc.p(this._innerContainer.getPositionX(), 0), time, attenuated);
+ },
+
+ /**
+ * Scroll inner container to top boundary of ScrollView.
+ * @param {Number} time
+ * @param {Boolean} attenuated
+ */
+ scrollToTop: function (time, attenuated) {
+ this._startAutoScrollChildrenWithDestination(
+ cc.p(this._innerContainer.getPositionX(), this._contentSize.height - this._innerContainer.getContentSize().height), time, attenuated);
+ },
+
+ /**
+ * Scroll inner container to left boundary of ScrollView.
+ * @param {Number} time
+ * @param {Boolean} attenuated
+ */
+ scrollToLeft: function (time, attenuated) {
+ this._startAutoScrollChildrenWithDestination(cc.p(0, this._innerContainer.getPositionY()), time, attenuated);
+ },
+
+ /**
+ * Scroll inner container to right boundary of ScrollView.
+ * @param {Number} time
+ * @param {Boolean} attenuated
+ */
+ scrollToRight: function (time, attenuated) {
+ this._startAutoScrollChildrenWithDestination(
+ cc.p(this._contentSize.width - this._innerContainer.getContentSize().width, this._innerContainer.getPositionY()), time, attenuated);
+ },
+
+ /**
+ * Scroll inner container to top and left boundary of ScrollView.
+ * @param {Number} time
+ * @param {Boolean} attenuated
+ */
+ scrollToTopLeft: function (time, attenuated) {
+ if (this.direction !== ccui.ScrollView.Dir.BOTH) {
+ cc.log("Scroll direction is not both!");
+ return;
+ }
+ this._startAutoScrollChildrenWithDestination(cc.p(0, this._contentSize.height - this._innerContainer.getContentSize().height), time, attenuated);
+ },
+
+ /**
+ * Scroll inner container to top and right boundary of ScrollView.
+ * @param {Number} time
+ * @param {Boolean} attenuated
+ */
+ scrollToTopRight: function (time, attenuated) {
+ if (this.direction !== ccui.ScrollView.Dir.BOTH) {
+ cc.log("Scroll direction is not both!");
+ return;
+ }
+ var inSize = this._innerContainer.getContentSize();
+ this._startAutoScrollChildrenWithDestination(cc.p(this._contentSize.width - inSize.width,
+ this._contentSize.height - inSize.height), time, attenuated);
+ },
+
+ /**
+ * Scroll inner container to bottom and left boundary of ScrollView.
+ * @param {Number} time
+ * @param {Boolean} attenuated
+ */
+ scrollToBottomLeft: function (time, attenuated) {
+ if (this.direction !== ccui.ScrollView.Dir.BOTH) {
+ cc.log("Scroll direction is not both!");
+ return;
+ }
+ this._startAutoScrollChildrenWithDestination(cc.p(0, 0), time, attenuated);
+ },
+
+ /**
+ * Scroll inner container to bottom and right boundary of ScrollView.
+ * @param {Number} time
+ * @param {Boolean} attenuated
+ */
+ scrollToBottomRight: function (time, attenuated) {
+ if (this.direction !== ccui.ScrollView.Dir.BOTH) {
+ cc.log("Scroll direction is not both!");
+ return;
+ }
+ this._startAutoScrollChildrenWithDestination(cc.p(this._contentSize.width - this._innerContainer.getContentSize().width, 0), time, attenuated);
+ },
+
+ /**
+ * Scroll inner container to vertical percent position of ScrollView.
+ * @param {Number} percent
+ * @param {Number} time
+ * @param {Boolean} attenuated
+ */
+ scrollToPercentVertical: function (percent, time, attenuated) {
+ var minY = this._contentSize.height - this._innerContainer.getContentSize().height;
+ var h = -minY;
+ this._startAutoScrollChildrenWithDestination(cc.p(this._innerContainer.getPositionX(), minY + percent * h / 100), time, attenuated);
+ },
+
+ /**
+ * Scroll inner container to horizontal percent position of ScrollView.
+ * @param {Number} percent
+ * @param {Number} time
+ * @param {Boolean} attenuated
+ */
+ scrollToPercentHorizontal: function (percent, time, attenuated) {
+ var w = this._innerContainer.getContentSize().width - this._contentSize.width;
+ this._startAutoScrollChildrenWithDestination(cc.p(-(percent * w / 100), this._innerContainer.getPositionY()), time, attenuated);
+ },
+
+ /**
+ * Scroll inner container to both direction percent position of ScrollView.
+ * @param {cc.Vec2} percent
+ * @param {Number} time
+ * @param {Boolean} attenuated
+ */
+ scrollToPercentBothDirection: function (percent, time, attenuated) {
+ if (this.direction !== ccui.ScrollView.Dir.BOTH)
+ return;
+ var minY = this._contentSize.height - this._innerContainer.getContentSize().height;
+ var h = -minY;
+ var w = this._innerContainer.getContentSize().width - this._contentSize.width;
+ this._startAutoScrollChildrenWithDestination(cc.p(-(percent.x * w / 100), minY + percent.y * h / 100), time, attenuated);
+ },
+
+ /**
+ * Move inner container to bottom boundary of ScrollView.
+ */
+ jumpToBottom: function () {
+ this._jumpToDestination(this._innerContainer.getPositionX(), 0);
+ },
+
+ /**
+ * Move inner container to top boundary of ScrollView.
+ */
+ jumpToTop: function () {
+ this._jumpToDestination(this._innerContainer.getPositionX(), this._contentSize.height - this._innerContainer.getContentSize().height);
+ },
+
+ /**
+ * Move inner container to left boundary of ScrollView.
+ */
+ jumpToLeft: function () {
+ this._jumpToDestination(0, this._innerContainer.getPositionY());
+ },
+
+ /**
+ * Move inner container to right boundary of ScrollView.
+ */
+ jumpToRight: function () {
+ this._jumpToDestination(this._contentSize.width - this._innerContainer.getContentSize().width, this._innerContainer.getPositionY());
+ },
+
+ /**
+ * Move inner container to top and left boundary of ScrollView.
+ */
+ jumpToTopLeft: function () {
+ if (this.direction !== ccui.ScrollView.Dir.BOTH) {
+ cc.log("Scroll direction is not both!");
+ return;
+ }
+ this._jumpToDestination(0, this._contentSize.height - this._innerContainer.getContentSize().height);
+ },
+
+ /**
+ * Move inner container to top and right boundary of ScrollView.
+ */
+ jumpToTopRight: function () {
+ if (this.direction !== ccui.ScrollView.Dir.BOTH) {
+ cc.log("Scroll direction is not both!");
+ return;
+ }
+ var inSize = this._innerContainer.getContentSize();
+ this._jumpToDestination(this._contentSize.width - inSize.width, this._contentSize.height - inSize.height);
+ },
+
+ /**
+ * Move inner container to bottom and left boundary of ScrollView.
+ */
+ jumpToBottomLeft: function () {
+ if (this.direction !== ccui.ScrollView.Dir.BOTH) {
+ cc.log("Scroll direction is not both!");
+ return;
+ }
+ this._jumpToDestination(0, 0);
+ },
+
+ /**
+ * Move inner container to bottom and right boundary of ScrollView.
+ */
+ jumpToBottomRight: function () {
+ if (this.direction !== ccui.ScrollView.Dir.BOTH) {
+ cc.log("Scroll direction is not both!");
+ return;
+ }
+ this._jumpToDestination(this._contentSize.width - this._innerContainer.getContentSize().width, 0);
+ },
+
+ /**
+ * Move inner container to vertical percent position of ScrollView.
+ * @param {Number} percent The destination vertical percent, accept value between 0 - 100
+ */
+ jumpToPercentVertical: function (percent) {
+ var minY = this._contentSize.height - this._innerContainer.getContentSize().height;
+ var h = -minY;
+ this._jumpToDestination(this._innerContainer.getPositionX(), minY + percent * h / 100);
+ },
+
+ /**
+ * Move inner container to horizontal percent position of ScrollView.
+ * @param {Number} percent The destination vertical percent, accept value between 0 - 100
+ */
+ jumpToPercentHorizontal: function (percent) {
+ var w = this._innerContainer.getContentSize().width - this._contentSize.width;
+ this._jumpToDestination(-(percent * w / 100), this._innerContainer.getPositionY());
+ },
+
+ /**
+ * Move inner container to both direction percent position of ScrollView.
+ * @param {cc.Vec2} percent The destination vertical percent, accept value between 0 - 100
+ */
+ jumpToPercentBothDirection: function (percent) {
+ if (this.direction !== ccui.ScrollView.Dir.BOTH)
+ return;
+ var inSize = this._innerContainer.getContentSize();
+ var minY = this._contentSize.height - inSize.height;
+ var h = -minY;
+ var w = inSize.width - this._contentSize.width;
+ this._jumpToDestination(-(percent.x * w / 100), minY + percent.y * h / 100);
+ },
+
+ _startRecordSlidAction: function () {
+ if (this._autoScroll)
+ this._stopAutoScrollChildren();
+ if (this._bouncing)
+ this._stopBounceChildren();
+ this._slidTime = 0.0;
+ },
+
+ _endRecordSlidAction: function () {
+ if (!this._checkNeedBounce() && this.inertiaScrollEnabled) {
+ if (this._slidTime <= 0.016)
+ return;
+ var totalDis = 0, dir;
+ var touchEndPositionInNodeSpace = this.convertToNodeSpace(this._touchEndPosition);
+ var touchBeganPositionInNodeSpace = this.convertToNodeSpace(this._touchBeganPosition);
+ switch (this.direction) {
+ case ccui.ScrollView.Dir.VERTICAL :
+ totalDis = touchEndPositionInNodeSpace.y - touchBeganPositionInNodeSpace.y;
+ dir = (totalDis < 0) ? ccui.ScrollView.SCROLLDIR_DOWN : ccui.ScrollView.SCROLLDIR_UP;
+ break;
+ case ccui.ScrollView.Dir.HORIZONTAL:
+ totalDis = touchEndPositionInNodeSpace.x - touchBeganPositionInNodeSpace.x;
+ dir = totalDis < 0 ? ccui.ScrollView.SCROLLDIR_LEFT : ccui.ScrollView.SCROLLDIR_RIGHT;
+ break;
+ case ccui.ScrollView.Dir.BOTH :
+ var subVector = cc.pSub(touchEndPositionInNodeSpace, touchBeganPositionInNodeSpace);
+ totalDis = cc.pLength(subVector);
+ dir = cc.pNormalize(subVector);
+ break;
+ default:
+ dir = cc.p(0,0);
+ break;
+ }
+ var orSpeed = Math.min(Math.abs(totalDis) / (this._slidTime), ccui.ScrollView.AUTO_SCROLL_MAX_SPEED);
+ this._startAutoScrollChildrenWithOriginalSpeed(dir, orSpeed, true, -1000);
+ this._slidTime = 0;
+ }
+ },
+
+ _handlePressLogic: function (touch) {
+ this._startRecordSlidAction();
+ this._bePressed = true;
+ },
+
+ _handleMoveLogic: function (touch) {
+ var touchPositionInNodeSpace = this.convertToNodeSpace(touch.getLocation()),
+ previousTouchPositionInNodeSpace = this.convertToNodeSpace(touch.getPreviousLocation());
+ var delta = cc.pSub(touchPositionInNodeSpace, previousTouchPositionInNodeSpace);
+ switch (this.direction) {
+ case ccui.ScrollView.Dir.VERTICAL: // vertical
+ this._scrollChildren(0.0, delta.y);
+ break;
+ case ccui.ScrollView.Dir.HORIZONTAL: // horizontal
+ this._scrollChildren(delta.x, 0);
+ break;
+ case ccui.ScrollView.Dir.BOTH: // both
+ this._scrollChildren(delta.x, delta.y);
+ break;
+ default:
+ break;
+ }
+ },
+
+ _handleReleaseLogic: function (touch) {
+ this._endRecordSlidAction();
+ this._bePressed = false;
+ },
+
+ /**
+ * The touch began event callback handler of ccui.ScrollView.
+ * @param {cc.Touch} touch
+ * @param {cc.Event} event
+ * @returns {boolean}
+ */
+ onTouchBegan: function (touch, event) {
+ var pass = ccui.Layout.prototype.onTouchBegan.call(this, touch, event);
+ if(!this._isInterceptTouch){
+ if (this._hit)
+ this._handlePressLogic(touch);
+ }
+ return pass;
+ },
+
+ /**
+ * The touch moved event callback handler of ccui.ScrollView.
+ * @param {cc.Touch} touch
+ * @param {cc.Event} event
+ */
+ onTouchMoved: function (touch, event) {
+ ccui.Layout.prototype.onTouchMoved.call(this, touch, event);
+ if(!this._isInterceptTouch)
+ this._handleMoveLogic(touch);
+ },
+
+ /**
+ * The touch ended event callback handler of ccui.ScrollView.
+ * @param {cc.Touch} touch
+ * @param {cc.Event} event
+ */
+ onTouchEnded: function (touch, event) {
+ ccui.Layout.prototype.onTouchEnded.call(this, touch, event);
+ if(!this._isInterceptTouch)
+ this._handleReleaseLogic(touch);
+ this._isInterceptTouch = false;
+ },
+
+ /**
+ * The touch canceled event callback of ccui.ScrollView.
+ * @param {cc.Touch} touch
+ * @param {cc.Event} event
+ */
+ onTouchCancelled: function (touch, event) {
+ ccui.Layout.prototype.onTouchCancelled.call(this, touch, event);
+ if (!this._isInterceptTouch)
+ this.handleReleaseLogic(touch);
+ this._isInterceptTouch = false;
+ },
+
+ /**
+ * The update callback handler.
+ * @param {Number} dt
+ */
+ update: function (dt) {
+ if (this._autoScroll)
+ this._autoScrollChildren(dt);
+ if (this._bouncing)
+ this._bounceChildren(dt);
+ this._recordSlidTime(dt);
+ },
+
+ _recordSlidTime: function (dt) {
+ if (this._bePressed)
+ this._slidTime += dt;
+ },
+
+ /**
+ * Intercept touch event, handle its child's touch event.
+ * @override
+ * @param {cc.Event} event
+ */
+ interceptTouchEvent: function (event) {
+ var eventType = event._widgetEventType,
+ touch = event.currentTouch,
+ touchPoint, offset;
+ if (!this._touchEnabled)
+ return;
+
+ touchPoint = touch.getLocation();
+ switch (eventType) {
+ case ccui.Widget.TOUCH_BEGAN:
+ this._isInterceptTouch = true;
+ this._touchBeganPosition.x = touchPoint.x;
+ this._touchBeganPosition.y = touchPoint.y;
+ this._handlePressLogic(touch);
+ break;
+ case ccui.Widget.TOUCH_MOVED:
+ offset = cc.pLength(cc.pSub(event.target.getTouchBeganPosition(), touchPoint));
+ this._touchMovePosition.x = touchPoint.x;
+ this._touchMovePosition.y = touchPoint.y;
+ if (offset > this._childFocusCancelOffset) {
+ event.target.setHighlighted(false);
+ this._handleMoveLogic(touch);
+ }
+ break;
+ case ccui.Widget.TOUCH_CANCELED:
+ case ccui.Widget.TOUCH_ENDED:
+ this._touchEndPosition.x = touchPoint.x;
+ this._touchEndPosition.y = touchPoint.y;
+ this._handleReleaseLogic(touch);
+ if (event.target.isSwallowTouches())
+ this._isInterceptTouch = false;
+ break;
+ }
+ },
+
+ _scrollToTopEvent: function () {
+ if(this._scrollViewEventSelector){
+ if (this._scrollViewEventListener)
+ this._scrollViewEventSelector.call(this._scrollViewEventListener, this, ccui.ScrollView.Event.SCROLL_TO_TOP);
+ else
+ this._scrollViewEventSelector(this, ccui.ScrollView.Event.SCROLL_TO_TOP);
+ }
+ if(this._ccEventCallback)
+ this._ccEventCallback(this, ccui.ScrollView.Event.SCROLL_TO_TOP);
+ },
+
+ _scrollToBottomEvent: function () {
+ if(this._scrollViewEventSelector){
+ if (this._scrollViewEventListener)
+ this._scrollViewEventSelector.call(this._scrollViewEventListener, this, ccui.ScrollView.Event.SCROLL_TO_BOTTOM);
+ else
+ this._scrollViewEventSelector(this, ccui.ScrollView.Event.SCROLL_TO_BOTTOM);
+ }
+ if(this._ccEventCallback)
+ this._ccEventCallback(this, ccui.ScrollView.Event.SCROLL_TO_BOTTOM);
+ },
+
+ _scrollToLeftEvent: function () {
+ if(this._scrollViewEventSelector){
+ if (this._scrollViewEventListener)
+ this._scrollViewEventSelector.call(this._scrollViewEventListener, this, ccui.ScrollView.Event.SCROLL_TO_LEFT);
+ else
+ this._scrollViewEventSelector(this, ccui.ScrollView.Event.SCROLL_TO_LEFT);
+ }
+ if(this._ccEventCallback)
+ this._ccEventCallback(this, ccui.ScrollView.Event.SCROLL_TO_LEFT);
+ },
+
+ _scrollToRightEvent: function () {
+ if(this._scrollViewEventSelector){
+ if (this._scrollViewEventListener)
+ this._scrollViewEventSelector.call(this._scrollViewEventListener, this, ccui.ScrollView.Event.SCROLL_TO_RIGHT);
+ else
+ this._scrollViewEventSelector(this, ccui.ScrollView.Event.SCROLL_TO_RIGHT);
+ }
+ if(this._ccEventCallback)
+ this._ccEventCallback(this, ccui.ScrollView.Event.SCROLL_TO_RIGHT);
+ },
+
+ _scrollingEvent: function () {
+ if(this._scrollViewEventSelector){
+ if (this._scrollViewEventListener)
+ this._scrollViewEventSelector.call(this._scrollViewEventListener, this, ccui.ScrollView.Event.SCROLLING);
+ else
+ this._scrollViewEventSelector(this, ccui.ScrollView.Event.SCROLLING);
+ }
+ if(this._ccEventCallback)
+ this._ccEventCallback(this, ccui.ScrollView.Event.SCROLLING);
+ },
+
+ _bounceTopEvent: function () {
+ if(this._scrollViewEventSelector){
+ if (this._scrollViewEventListener)
+ this._scrollViewEventSelector.call(this._scrollViewEventListener, this, ccui.ScrollView.Event.BOUNCE_TOP);
+ else
+ this._scrollViewEventSelector(this, ccui.ScrollView.Event.BOUNCE_TOP);
+ }
+ if(this._ccEventCallback)
+ this._ccEventCallback(this, ccui.ScrollView.Event.BOUNCE_TOP);
+ },
+
+ _bounceBottomEvent: function () {
+ if(this._scrollViewEventSelector){
+ if (this._scrollViewEventListener)
+ this._scrollViewEventSelector.call(this._scrollViewEventListener, this, ccui.ScrollView.Event.BOUNCE_BOTTOM);
+ else
+ this._scrollViewEventSelector(this, ccui.ScrollView.Event.BOUNCE_BOTTOM);
+ }
+ if(this._ccEventCallback)
+ this._ccEventCallback(this, ccui.ScrollView.Event.BOUNCE_BOTTOM);
+ },
+
+ _bounceLeftEvent: function () {
+ if(this._scrollViewEventSelector){
+ if (this._scrollViewEventListener)
+ this._scrollViewEventSelector.call(this._scrollViewEventListener, this, ccui.ScrollView.Event.BOUNCE_LEFT);
+ else
+ this._scrollViewEventSelector(this, ccui.ScrollView.Event.BOUNCE_LEFT);
+ }
+ if(this._ccEventCallback)
+ this._ccEventCallback(this, ccui.ScrollView.Event.BOUNCE_LEFT);
+ },
+
+ _bounceRightEvent: function () {
+ if(this._scrollViewEventSelector){
+ if (this._scrollViewEventListener)
+ this._scrollViewEventSelector.call(this._scrollViewEventListener, this, ccui.ScrollView.Event.BOUNCE_RIGHT);
+ else
+ this._scrollViewEventSelector(this, ccui.ScrollView.Event.BOUNCE_RIGHT);
+ }
+ if(this._ccEventCallback)
+ this._ccEventCallback(this, ccui.ScrollView.Event.BOUNCE_RIGHT);
+ },
+
+ /**
+ * Adds callback function called ScrollView event triggered
+ * @param {Function} selector
+ * @param {Object} [target=]
+ * @deprecated since v3.0, please use addEventListener instead.
+ */
+ addEventListenerScrollView: function (selector, target) {
+ this.addEventListener(selector, target);
+ },
+
+ /**
+ * Adds callback function called ScrollView event triggered
+ * @param {Function} selector
+ * @param {Object} [target=]
+ */
+ addEventListener: function(selector, target){
+ this._scrollViewEventSelector = selector;
+ this._scrollViewEventListener = target;
+ },
+
+ /**
+ * Changes scroll direction of ScrollView.
+ * @param {ccui.ScrollView.Dir} dir
+ * Direction::VERTICAL means vertical scroll, Direction::HORIZONTAL means horizontal scroll
+ */
+ setDirection: function (dir) {
+ this.direction = dir;
+ },
+
+ /**
+ * Returns scroll direction of ScrollView.
+ * @returns {ccui.ScrollView.Dir}
+ */
+ getDirection: function () {
+ return this.direction;
+ },
+
+ /**
+ * Sets bounce enabled
+ * @param {Boolean} enabled
+ */
+ setBounceEnabled: function (enabled) {
+ this.bounceEnabled = enabled;
+ },
+
+ /**
+ * Returns whether bounce is enabled
+ * @returns {boolean}
+ */
+ isBounceEnabled: function () {
+ return this.bounceEnabled;
+ },
+
+ /**
+ * Sets inertiaScroll enabled
+ * @param {boolean} enabled
+ */
+ setInertiaScrollEnabled: function (enabled) {
+ this.inertiaScrollEnabled = enabled;
+ },
+
+ /**
+ * Returns whether inertiaScroll is enabled
+ * @returns {boolean}
+ */
+ isInertiaScrollEnabled: function () {
+ return this.inertiaScrollEnabled;
+ },
+
+ /**
+ * Gets inner container of ScrollView. Inner container is the container of ScrollView's children.
+ * @returns {ccui.Layout}
+ */
+ getInnerContainer: function () {
+ return this._innerContainer;
+ },
+
+ /**
+ * Sets LayoutType of ccui.ScrollView.
+ * @param {ccui.Layout.Type} type
+ */
+ setLayoutType: function (type) {
+ this._innerContainer.setLayoutType(type);
+ },
+
+ /**
+ * Returns the layout type of ccui.ScrollView.
+ * @returns {ccui.Layout.Type}
+ */
+ getLayoutType: function () {
+ return this._innerContainer.getLayoutType();
+ },
+
+ _doLayout: function () {
+ if (!this._doLayoutDirty)
+ return;
+ this._doLayoutDirty = false;
+ },
+
+ /**
+ * Returns the "class name" of ccui.ScrollView.
+ * @returns {string}
+ */
+ getDescription: function () {
+ return "ScrollView";
+ },
+
+ _createCloneInstance: function(){
+ return new ccui.ScrollView();
+ },
+
+ _copyClonedWidgetChildren: function (model) {
+ ccui.Layout.prototype._copyClonedWidgetChildren.call(this, model);
+ },
+
+ _copySpecialProperties: function (scrollView) {
+ if(scrollView instanceof ccui.ScrollView) {
+ ccui.Layout.prototype._copySpecialProperties.call(this, scrollView);
+ this.setInnerContainerSize(scrollView.getInnerContainerSize());
+ this.setDirection(scrollView.direction);
+ this.setBounceEnabled(scrollView.bounceEnabled);
+ this.setInertiaScrollEnabled(scrollView.inertiaScrollEnabled);
+ this._scrollViewEventListener = scrollView._scrollViewEventListener;
+ this._scrollViewEventSelector = scrollView._scrollViewEventSelector;
+ this._ccEventCallback = scrollView._ccEventCallback;
+ }
+ },
+
+ /**
+ * Returns a node by tag
+ * @param {Number} tag
+ * @returns {cc.Node}
+ * @deprecated since v3.0, please use getChildByTag instead.
+ */
+ getNodeByTag: function (tag) {
+ return this._innerContainer.getNodeByTag(tag);
+ },
+
+ /**
+ * Returns all nodes of inner container
+ * @returns {Array}
+ * @deprecated since v3.0, please use getChildren instead.
+ */
+ getNodes: function () {
+ return this._innerContainer.getNodes();
+ },
+
+ /**
+ * Removes a node from ccui.ScrollView.
+ * @param {cc.Node} node
+ * @deprecated since v3.0, please use removeChild instead.
+ */
+ removeNode: function (node) {
+ this._innerContainer.removeNode(node);
+ },
+
+ /**
+ * Removes a node by tag
+ * @param {Number} tag
+ * @deprecated since v3.0, please use removeChildByTag instead.
+ */
+ removeNodeByTag: function (tag) {
+ this._innerContainer.removeNodeByTag(tag);
+ },
+
+ /**
+ * Remove all node from ccui.ScrollView.
+ * @deprecated since v3.0, please use removeAllChildren instead.
+ */
+ removeAllNodes: function () {
+ this._innerContainer.removeAllNodes();
+ },
+
+ /**
+ * Add node for scrollView
+ * @param {cc.Node} node
+ * @param {Number} zOrder
+ * @param {Number} tag
+ * @deprecated since v3.0, please use addChild instead.
+ */
+ addNode: function (node, zOrder, tag) {
+ this._innerContainer.addNode(node, zOrder, tag);
+ }
+});
+
+var _p = ccui.ScrollView.prototype;
+
+// Extended properties
+/** @expose */
+_p.innerWidth;
+cc.defineGetterSetter(_p, "innerWidth", _p._getInnerWidth, _p._setInnerWidth);
+/** @expose */
+_p.innerHeight;
+cc.defineGetterSetter(_p, "innerHeight", _p._getInnerHeight, _p._setInnerHeight);
+
+_p = null;
+
+/**
+ * allocates and initializes a UIScrollView.
+ * @deprecated since v3.0, please use new ccui.ScrollView() instead.
+ * @return {ccui.ScrollView}
+ */
+ccui.ScrollView.create = function () {
+ return new ccui.ScrollView();
+};
+
+// Constants
+
+/**
+ * Enum for ScrollView direction
+ * @readonly
+ * @enum {number}
+ */
+ccui.ScrollView.Dir = cc.Enum({
+ /**
+ * The none flag of ccui.ScrollView's direction.
+ */
+ NONE: 0,
+ /**
+ * The vertical flag of ccui.ScrollView's direction.
+ */
+ VERTICAL: 1,
+ /**
+ * The horizontal flag of ccui.ScrollView's direction.
+ */
+ HORIZONTAL: 2,
+ /**
+ * The both flag of ccui.ScrollView's direction.
+ */
+ BOTH: 3
+});
+
+/**
+ * The event types of ccui.ScrollView.
+ * @readonly
+ * @enum {number}
+ */
+ccui.ScrollView.Event = cc.Enum({
+ /**
+ * The flag scroll to top of ccui.ScrollView's event.
+ */
+ SCROLL_TO_TOP: 0,
+ /**
+ * The flag scroll to bottom of ccui.ScrollView's event.
+ */
+ SCROLL_TO_BOTTOM: 1,
+ /**
+ * The flag scroll to left of ccui.ScrollView's event.
+ */
+ SCROLL_TO_LEFT: 2,
+ /**
+ * The flag scroll to right of ccui.ScrollView's event.
+ */
+ SCROLL_TO_RIGHT: 3,
+ /**
+ * The scrolling flag of ccui.ScrollView's event.
+ */
+ SCROLLING: 4,
+ /**
+ * The flag bounce top of ccui.ScrollView's event.
+ */
+ BOUNCE_TOP: 5,
+ /**
+ * The flag bounce bottom of ccui.ScrollView's event.
+ */
+ BOUNCE_BOTTOM: 6,
+ /**
+ * The flag bounce left of ccui.ScrollView's event.
+ */
+ BOUNCE_LEFT: 7,
+ /**
+ * The flag bounce right of ccui.ScrollView's event.
+ */
+ BOUNCE_RIGHT: 8
+});
+
+/**
+ * The auto scroll max speed of ccui.ScrollView.
+ * @constant
+ * @type {number}
+ */
+ccui.ScrollView.AUTO_SCROLL_MAX_SPEED = 1000;
+
+/**
+ * @ignore
+ */
+ccui.ScrollView.SCROLLDIR_UP = cc.p(0, 1);
+ccui.ScrollView.SCROLLDIR_DOWN = cc.p(0, -1);
+ccui.ScrollView.SCROLLDIR_LEFT = cc.p(-1, 0);
+ccui.ScrollView.SCROLLDIR_RIGHT = cc.p(1, 0);
diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewCanvasRenderCmd.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewCanvasRenderCmd.js
new file mode 100644
index 0000000000..9cc0ed6cc6
--- /dev/null
+++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewCanvasRenderCmd.js
@@ -0,0 +1,43 @@
+(function(){
+ if(!ccui.ProtectedNode.CanvasRenderCmd)
+ return;
+ ccui.ScrollView.CanvasRenderCmd = function(renderable){
+ ccui.Layout.CanvasRenderCmd.call(this, renderable);
+ this._needDraw = true;
+ this._dirty = false;
+ };
+
+ var proto = ccui.ScrollView.CanvasRenderCmd.prototype = Object.create(ccui.Layout.CanvasRenderCmd.prototype);
+ proto.constructor = ccui.ScrollView.CanvasRenderCmd;
+
+ proto.visit = function(parentCmd) {
+ var node = this._node;
+ if (!node._visible)
+ return;
+ cc.renderer.pushRenderCommand(this);
+ var currentID = node.__instanceId;
+ cc.renderer._turnToCacheMode(currentID);
+
+ ccui.Layout.CanvasRenderCmd.prototype.visit.call(this, parentCmd);
+ this._dirtyFlag = 0;
+ cc.renderer._turnToNormalMode();
+ };
+
+ proto.rendering = function (ctx) {
+ var currentID = this._node.__instanceId;
+ var locCmds = cc.renderer._cacheToCanvasCmds[currentID], i, len,
+ scaleX = cc.view.getScaleX(),
+ scaleY = cc.view.getScaleY();
+ var context = ctx || cc._renderContext;
+ context.computeRealOffsetY();
+
+ for (i = 0, len = locCmds.length; i < len; i++) {
+ var checkNode = locCmds[i]._node;
+ if(checkNode instanceof ccui.ScrollView)
+ continue;
+ if(checkNode && checkNode._parent && checkNode._parent._inViewRect === false)
+ continue;
+ locCmds[i].rendering(context, scaleX, scaleY);
+ }
+ };
+})();
\ No newline at end of file
diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js
new file mode 100644
index 0000000000..2448972b7b
--- /dev/null
+++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js
@@ -0,0 +1,44 @@
+
+(function(){
+ if(!ccui.ProtectedNode.WebGLRenderCmd)
+ return;
+ ccui.ScrollView.WebGLRenderCmd = function(renderable){
+ ccui.Layout.WebGLRenderCmd.call(this, renderable);
+ this._needDraw = true;
+ this._dirty = false;
+ };
+
+ var proto = ccui.ScrollView.WebGLRenderCmd.prototype = Object.create(ccui.Layout.WebGLRenderCmd.prototype);
+ proto.constructor = ccui.ScrollView.WebGLRenderCmd;
+
+ proto.visit = function(parentCmd) {
+ var node = this._node;
+ if (!node._visible)
+ return;
+ var currentID = this._node.__instanceId;
+
+ cc.renderer.pushRenderCommand(this);
+ cc.renderer._turnToCacheMode(currentID);
+
+ ccui.Layout.WebGLRenderCmd.prototype.visit.call(this, parentCmd);
+
+ this._dirtyFlag = 0;
+ cc.renderer._turnToNormalMode();
+ };
+
+ proto.rendering = function(ctx){
+ var currentID = this._node.__instanceId;
+ var locCmds = cc.renderer._cacheToBufferCmds[currentID],
+ i,
+ len;
+ var context = ctx || cc._renderContext;
+ for (i = 0, len = locCmds.length; i < len; i++) {
+ var checkNode = locCmds[i]._node;
+ if(checkNode instanceof ccui.ScrollView)
+ continue;
+ if(checkNode && checkNode._parent && checkNode._parent._inViewRect === false)
+ continue;
+ locCmds[i].rendering(context);
+ }
+ }
+})();
\ No newline at end of file
diff --git a/extensions/cocostudio/CocoStudio.js b/extensions/cocostudio/CocoStudio.js
new file mode 100644
index 0000000000..07804f5283
--- /dev/null
+++ b/extensions/cocostudio/CocoStudio.js
@@ -0,0 +1,68 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+/**
+ * The main namespace of Cocostudio, all classes, functions, properties and constants of Spine are defined in this namespace
+ * @namespace
+ * @name ccs
+ */
+var ccs = ccs || {};
+
+/**
+ * The same as cc._Class
+ * @class
+ */
+ccs.Class = ccs.Class || cc._Class;
+ccs.Class.extend = ccs.Class.extend || cc._Class.extend;
+
+/**
+ * The same as cc.Node
+ * @class
+ * @extends ccs.Class
+ */
+ccs.Node = ccs.Node || cc.Node;
+ccs.Node.extend = ccs.Node.extend || cc.Node.extend;
+
+/**
+ * The same as cc.Sprite
+ * @class
+ * @extends ccs.Class
+ */
+ccs.Sprite = ccs.Sprite || cc.Sprite;
+ccs.Sprite.extend = ccs.Sprite.extend || cc.Sprite.extend;
+
+/**
+ * The same as cc._Component
+ * @class
+ * @extends ccs.Class
+ */
+ccs.Component = ccs.Component || cc._Component;
+ccs.Component.extend = ccs.Component.extend || cc._Component.extend;
+
+/**
+ * CocoStudio version
+ * @constant
+ * @type {string}
+ */
+ccs.cocostudioVersion = "v1.3.0.0";
\ No newline at end of file
diff --git a/extensions/cocostudio/action/CCActionFrame.js b/extensions/cocostudio/action/CCActionFrame.js
new file mode 100644
index 0000000000..401cd4a6e0
--- /dev/null
+++ b/extensions/cocostudio/action/CCActionFrame.js
@@ -0,0 +1,530 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+//Action frame type
+/**
+ * The flag move action type of Cocostudio frame.
+ * @constant
+ * @type {number}
+ */
+ccs.FRAME_TYPE_MOVE = 0;
+/**
+ * The flag scale action type of Cocostudio frame.
+ * @constant
+ * @type {number}
+ */
+ccs.FRAME_TYPE_SCALE = 1;
+/**
+ * The flag rotate action type of Cocostudio frame.
+ * @constant
+ * @type {number}
+ */
+ccs.FRAME_TYPE_ROTATE = 2;
+/**
+ * The flag tint action type of Cocostudio frame.
+ * @constant
+ * @type {number}
+ */
+ccs.FRAME_TYPE_TINT = 3;
+/**
+ * The flag fade action type of Cocostudio frame.
+ * @constant
+ * @type {number}
+ */
+ccs.FRAME_TYPE_FADE = 4;
+/**
+ * The max flag of Cocostudio frame.
+ * @constant
+ * @type {number}
+ */
+ccs.FRAME_TYPE_MAX = 5;
+
+/**
+ * The ease type of Cocostudio frame.
+ * @constant
+ * @type {Object}
+ */
+ccs.FrameEaseType = {
+ CUSTOM : -1,
+
+ LINEAR : 0,
+
+ SINE_EASEIN : 1,
+ SINE_EASEOUT : 2,
+ SINE_EASEINOUT : 3,
+
+ QUAD_EASEIN : 4,
+ QUAD_EASEOUT : 5,
+ QUAD_EASEINOUT : 6,
+
+ CUBIC_EASEIN : 7,
+ CUBIC_EASEOUT : 8,
+ CUBIC_EASEINOUT : 9,
+
+ QUART_EASEIN : 10,
+ QUART_EASEOUT : 11,
+ QUART_EASEINOUT : 12,
+
+ QUINT_EASEIN : 13,
+ QUINT_EASEOUT : 14,
+ QUINT_EASEINOUT : 15,
+
+ EXPO_EASEIN : 16,
+ EXPO_EASEOUT : 17,
+ EXPO_EASEINOUT : 18,
+
+ CIRC_EASEIN : 19,
+ CIRC_EASEOUT : 20,
+ CIRC_EASEINOUT : 21,
+
+ ELASTIC_EASEIN : 22,
+ ELASTIC_EASEOUT : 23,
+ ELASTIC_EASEINOUT : 24,
+
+ BACK_EASEIN : 25,
+ BACK_EASEOUT : 26,
+ BACK_EASEINOUT : 27,
+
+ BOUNCE_EASEIN : 28,
+ BOUNCE_EASEOUT : 29,
+ BOUNCE_EASEINOUT : 30,
+
+ TWEEN_EASING_MAX: 1000
+};
+
+
+/**
+ * The action frame of Cocostudio. It's the base class of ccs.ActionMoveFrame, ccs.ActionScaleFrame etc.
+ * @class
+ * @extends ccs.Class
+ *
+ * @property {Number} frameType - frame type of ccs.ActionFrame
+ * @property {Number} easingType - easing type of ccs.ActionFrame
+ * @property {Number} frameIndex - frame index of ccs.ActionFrame
+ * @property {Number} time - time of ccs.ActionFrame
+ */
+ccs.ActionFrame = ccs.Class.extend(/** @lends ccs.ActionFrame# */{
+ frameType: 0,
+ easingType: 0,
+ frameIndex: 0,
+ _Parameter: null,
+ time: 0,
+
+ /**
+ * The constructor of cc.ActionFrame.
+ */
+ ctor: function () {
+ this.frameType = 0;
+ this.easingType = ccs.FrameEaseType.LINEAR;
+ this.frameIndex = 0;
+ this.time = 0;
+ },
+
+ /**
+ * Returns the action of ActionFrame. its subClass need override it.
+ * @param {number} duration the duration time of ActionFrame
+ * @param {ccs.ActionFrame} srcFrame source frame.
+ * @returns {null}
+ */
+ getAction: function (duration, srcFrame) {
+ cc.log("Need a definition of for ActionFrame");
+ return null;
+ },
+
+ _getEasingAction : function (action) {
+ if (action === null) {
+ console.error("Action cannot be null!");
+ return null;
+ }
+
+ var resultAction;
+ switch (this.easingType) {
+ case ccs.FrameEaseType.CUSTOM:
+ break;
+ case ccs.FrameEaseType.LINEAR:
+ resultAction = action;
+ break;
+ case ccs.FrameEaseType.SINE_EASEIN:
+ resultAction = action.easing(cc.easeSineIn());
+ break;
+ case ccs.FrameEaseType.SINE_EASEOUT:
+ resultAction = action.easing(cc.easeSineOut());
+ break;
+ case ccs.FrameEaseType.SINE_EASEINOUT:
+ resultAction = action.easing(cc.easeSineInOut());
+ break;
+ case ccs.FrameEaseType.QUAD_EASEIN:
+ resultAction = action.easing(cc.easeQuadraticActionIn());
+ break;
+ case ccs.FrameEaseType.QUAD_EASEOUT:
+ resultAction = action.easing(cc.easeQuadraticActionOut());
+ break;
+ case ccs.FrameEaseType.QUAD_EASEINOUT:
+ resultAction = action.easing(cc.easeQuadraticActionInOut());
+ break;
+ case ccs.FrameEaseType.CUBIC_EASEIN:
+ resultAction = action.easing(cc.easeCubicActionIn());
+ break;
+ case ccs.FrameEaseType.CUBIC_EASEOUT:
+ resultAction = action.easing(cc.easeCubicActionOut());
+ break;
+ case ccs.FrameEaseType.CUBIC_EASEINOUT:
+ resultAction = action.easing(cc.easeCubicActionInOut());
+ break;
+ case ccs.FrameEaseType.QUART_EASEIN:
+ resultAction = action.easing(cc.easeQuarticActionIn());
+ break;
+ case ccs.FrameEaseType.QUART_EASEOUT:
+ resultAction = action.easing(cc.easeQuarticActionOut());
+ break;
+ case ccs.FrameEaseType.QUART_EASEINOUT:
+ resultAction = action.easing(cc.easeQuarticActionInOut());
+ break;
+ case ccs.FrameEaseType.QUINT_EASEIN:
+ resultAction = action.easing(cc.easeQuinticActionIn());
+ break;
+ case ccs.FrameEaseType.QUINT_EASEOUT:
+ resultAction = action.easing(cc.easeQuinticActionOut());
+ break;
+ case ccs.FrameEaseType.QUINT_EASEINOUT:
+ resultAction = action.easing(cc.easeQuinticActionInOut());
+ break;
+ case ccs.FrameEaseType.EXPO_EASEIN:
+ resultAction = action.easing(cc.easeExponentialIn());
+ break;
+ case ccs.FrameEaseType.EXPO_EASEOUT:
+ resultAction = action.easing(cc.easeExponentialOut());
+ break;
+ case ccs.FrameEaseType.EXPO_EASEINOUT:
+ resultAction = action.easing(cc.easeExponentialInOut());
+ break;
+ case ccs.FrameEaseType.CIRC_EASEIN:
+ resultAction = action.easing(cc.easeCircleActionIn());
+ break;
+ case ccs.FrameEaseType.CIRC_EASEOUT:
+ resultAction = action.easing(cc.easeCircleActionOut());
+ break;
+ case ccs.FrameEaseType.CIRC_EASEINOUT:
+ resultAction = action.easing(cc.easeCircleActionInOut());
+ break;
+ case ccs.FrameEaseType.ELASTIC_EASEIN:
+ resultAction = action.easing(cc.easeElasticIn());
+ break;
+ case ccs.FrameEaseType.ELASTIC_EASEOUT:
+ resultAction = action.easing(cc.easeElasticOut());
+ break;
+ case ccs.FrameEaseType.ELASTIC_EASEINOUT:
+ resultAction = action.easing(cc.easeElasticInOut());
+ break;
+ case ccs.FrameEaseType.BACK_EASEIN:
+ resultAction = action.easing(cc.easeBackIn());
+ break;
+ case ccs.FrameEaseType.BACK_EASEOUT:
+ resultAction = action.easing(cc.easeBackOut());
+ break;
+ case ccs.FrameEaseType.BACK_EASEINOUT:
+ resultAction = action.easing(cc.easeBackInOut());
+ break;
+ case ccs.FrameEaseType.BOUNCE_EASEIN:
+ resultAction = action.easing(cc.easeBounceIn());
+ break;
+ case ccs.FrameEaseType.BOUNCE_EASEOUT:
+ resultAction = action.easing(cc.easeBounceOut());
+ break;
+ case ccs.FrameEaseType.BOUNCE_EASEINOUT:
+ resultAction = action.easing(cc.easeBounceInOut());
+ break;
+ }
+
+ return resultAction;
+ },
+
+ /**
+ * Sets the easing parameter to action frame.
+ * @param {Array} parameter
+ */
+ setEasingParameter: function(parameter){
+ this._Parameter = [];
+ for(var i=0;i locFrameIndex ? locFrameIndex : locFrameindex;
+ }
+ if (!bFindFrame)
+ locFrameindex = 0;
+ return locFrameindex;
+ },
+
+ /**
+ * Returns the index of last ccs.ActionFrame.
+ * @returns {number}
+ */
+ getLastFrameIndex: function () {
+ var locFrameindex = -1;
+ var locIsFindFrame = false ,locFrameArray = this._frameArray;
+ for (var i = 0, len = this._frameArrayNum; i < len; i++) {
+ var locArray = locFrameArray[i];
+ if (locArray.length <= 0)
+ continue;
+ locIsFindFrame = true;
+ var locFrame = locArray[locArray.length - 1];
+ var locFrameIndex = locFrame.frameIndex;
+ locFrameindex = locFrameindex < locFrameIndex ? locFrameIndex : locFrameindex;
+ }
+ if (!locIsFindFrame)
+ locFrameindex = 0;
+ return locFrameindex;
+ },
+
+ /**
+ * Updates action states to some time.
+ * @param {Number} time
+ * @returns {boolean}
+ */
+ updateActionToTimeLine: function (time) {
+ var locIsFindFrame = false;
+ var locUnitTime = this.getUnitTime();
+ for (var i = 0; i < this._frameArrayNum; i++) {
+ var locArray = this._frameArray[i];
+ if (locArray === null)
+ continue;
+
+ for (var j = 0; j < locArray.length; j++) {
+ var locFrame = locArray[j];
+ if (locFrame.frameIndex * locUnitTime === time) {
+ this._easingToFrame(1.0, 1.0, locFrame);
+ locIsFindFrame = true;
+ break;
+ } else if (locFrame.frameIndex * locUnitTime > time) {
+ if (j === 0) {
+ this._easingToFrame(1.0, 1.0, locFrame);
+ locIsFindFrame = false;
+ } else {
+ var locSrcFrame = locArray[j - 1];
+ var locDuration = (locFrame.frameIndex - locSrcFrame.frameIndex) * locUnitTime;
+ var locDelaytime = time - locSrcFrame.frameIndex * locUnitTime;
+ this._easingToFrame(locDuration, 1.0, locSrcFrame);
+ this._easingToFrame(locDuration, locDelaytime / locDuration, locFrame);
+ locIsFindFrame = true;
+ }
+ break;
+ }
+ }
+ }
+ return locIsFindFrame;
+ },
+
+ _easingToFrame: function (duration, delayTime, destFrame) {
+ var action = destFrame.getAction(duration);
+ var node = this.getActionNode();
+ if (action == null || node == null)
+ return;
+ action.startWithTarget(node);
+ action.update(delayTime);
+ },
+
+ /**
+ * Returns if the action is done once time.
+ * @returns {Boolean} that if the action is done once time
+ */
+ isActionDoneOnce: function () {
+ if (this._action === null)
+ return true;
+ return this._action.isDone();
+ }
+});
diff --git a/extensions/cocostudio/action/CCActionObject.js b/extensions/cocostudio/action/CCActionObject.js
new file mode 100644
index 0000000000..d87e8f9e71
--- /dev/null
+++ b/extensions/cocostudio/action/CCActionObject.js
@@ -0,0 +1,263 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+/**
+ * The Cocostudio's action object.
+ * @class
+ * @extends ccs.Class
+ */
+ccs.ActionObject = ccs.Class.extend(/** @lends ccs.ActionObject# */{
+ _actionNodeList: null,
+ _name: "",
+ _loop: false,
+ _pause: false,
+ _playing: false,
+ _unitTime: 0,
+ _currentTime: 0,
+ _scheduler:null,
+ _callback: null,
+ _fTotalTime: 0,
+
+ /**
+ * Construction of ccs.ActionObject.
+ */
+ ctor: function () {
+ this._actionNodeList = [];
+ this._name = "";
+ this._loop = false;
+ this._pause = false;
+ this._playing = false;
+ this._unitTime = 0.1;
+ this._currentTime = 0;
+ this._fTotalTime = 0;
+ this._scheduler = cc.director.getScheduler();
+ },
+
+ /**
+ * Sets name to ccs.ActionObject
+ * @param {string} name
+ */
+ setName: function (name) {
+ this._name = name;
+ },
+
+ /**
+ * Returns name fo ccs.ActionObject
+ * @returns {string}
+ */
+ getName: function () {
+ return this._name;
+ },
+
+ /**
+ * Sets if the action will loop play.
+ * @param {boolean} loop
+ */
+ setLoop: function (loop) {
+ this._loop = loop;
+ },
+
+ /**
+ * Returns if the action will loop play.
+ * @returns {boolean}
+ */
+ getLoop: function () {
+ return this._loop;
+ },
+
+ /**
+ * Sets the time interval of frame.
+ * @param {number} time
+ */
+ setUnitTime: function (time) {
+ this._unitTime = time;
+ var frameNum = this._actionNodeList.length;
+ for (var i = 0; i < frameNum; i++) {
+ var locActionNode = this._actionNodeList[i];
+ locActionNode.setUnitTime(this._unitTime);
+ }
+ },
+
+ /**
+ * Returns the time interval of frame.
+ * @returns {number} the time interval of frame
+ */
+ getUnitTime: function () {
+ return this._unitTime;
+ },
+
+ /**
+ * Returns the current time of frame.
+ * @returns {number}
+ */
+ getCurrentTime: function () {
+ return this._currentTime;
+ },
+
+ /**
+ * Sets the current time of frame.
+ * @param {Number} time the current time of frame
+ */
+ setCurrentTime: function (time) {
+ this._currentTime = time;
+ },
+
+ /**
+ * Returns the total time of frame.
+ * @returns {number} the total time of frame
+ */
+ getTotalTime: function(){
+ return this._fTotalTime;
+ },
+
+ /**
+ * Returns if the action is playing.
+ * @returns {boolean} true if the action is playing, false the otherwise
+ */
+ isPlaying: function () {
+ return this._playing;
+ },
+
+ /**
+ * Init properties with a json dictionary
+ * @param {Object} dic
+ * @param {Object} root
+ */
+ initWithDictionary: function (dic, root) {
+ this.setName(dic["name"]);
+ this.setLoop(dic["loop"]);
+ this.setUnitTime(dic["unittime"]);
+ var actionNodeList = dic["actionnodelist"];
+ var maxLength = 0;
+ for (var i = 0; i < actionNodeList.length; i++) {
+ var actionNode = new ccs.ActionNode();
+
+ var actionNodeDic = actionNodeList[i];
+ actionNode.initWithDictionary(actionNodeDic, root);
+ actionNode.setUnitTime(this.getUnitTime());
+ this._actionNodeList.push(actionNode);
+ var length = actionNode.getLastFrameIndex() - actionNode.getFirstFrameIndex();
+ if(length > maxLength){
+ maxLength = length;
+ }
+ }
+ this._fTotalTime = maxLength * this._unitTime;
+ },
+
+ /**
+ * Adds a ActionNode to play the action.
+ * @param {ccs.ActionNode} node
+ */
+ addActionNode: function (node) {
+ if (!node)
+ return;
+ this._actionNodeList.push(node);
+ node.setUnitTime(this._unitTime);
+ },
+
+ /**
+ * Removes a ActionNode which play the action.
+ * @param {ccs.ActionNode} node
+ */
+ removeActionNode: function (node) {
+ if (node == null)
+ return;
+ cc.js.array.remove(this._actionNodeList, node);
+ },
+
+ /**
+ * Plays the action.
+ * @param {cc.CallFunc} [fun] Action Call Back
+ */
+ play: function (fun) {
+ this.stop();
+ this.updateToFrameByTime(0);
+ var locActionNodeList = this._actionNodeList;
+ var frameNum = locActionNodeList.length;
+ for (var i = 0; i < frameNum; i++) {
+ locActionNodeList[i].playAction(fun);
+ }
+ if (this._loop)
+ this._scheduler.schedule(this.simulationActionUpdate, this, 0, cc.REPEAT_FOREVER, 0, false, this.__instanceId + "");
+ if(fun !== undefined)
+ this._callback = fun;
+ },
+
+ /**
+ * Pauses the action.
+ */
+ pause: function () {
+ this._pause = true;
+ this._playing = false;
+ },
+
+ /**
+ * Stop the action.
+ */
+ stop: function () {
+ var locActionNodeList = this._actionNodeList;
+ for (var i = 0; i < locActionNodeList.length; i++)
+ locActionNodeList[i].stopAction();
+ this._scheduler.unschedule(this.simulationActionUpdate, this);
+ this._pause = false;
+ this._playing = false;
+ },
+
+ /**
+ * Updates frame by time.
+ */
+ updateToFrameByTime: function (time) {
+ this._currentTime = time;
+ for (var i = 0; i < this._actionNodeList.length; i++) {
+ var locActionNode = this._actionNodeList[i];
+ locActionNode.updateActionToTimeLine(time);
+ }
+ },
+
+ /**
+ * scheduler update function
+ * @param {Number} dt delta time
+ */
+ simulationActionUpdate: function (dt) {
+ var isEnd = true, locNodeList = this._actionNodeList;
+ for(var i = 0, len = locNodeList.length; i < len; i++) {
+ if (!locNodeList[i].isActionDoneOnce()){
+ isEnd = false;
+ break;
+ }
+ }
+
+ if (isEnd){
+ if (this._callback !== null)
+ this._callback.execute();
+ if (this._loop)
+ this.play();
+ else{
+ this._playing = false;
+ this._scheduler.unschedule(this.simulationActionUpdate, this);
+ }
+ }
+ }
+});
diff --git a/extensions/cocostudio/armature/CCArmature.js b/extensions/cocostudio/armature/CCArmature.js
new file mode 100644
index 0000000000..00c368bad4
--- /dev/null
+++ b/extensions/cocostudio/armature/CCArmature.js
@@ -0,0 +1,578 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+/**
+ * The main class of Armature, it plays armature animation, manages and updates bones' state.
+ * @class
+ * @extends ccs.Node
+ *
+ * @property {ccs.Bone} parentBone - The parent bone of the armature node
+ * @property {ccs.ArmatureAnimation} animation - The animation
+ * @property {ccs.ArmatureData} armatureData - The armature data
+ * @property {String} name - The name of the armature
+ * @property {cc.SpriteBatchNode} batchNode - The batch node of the armature
+ * @property {Number} version - The version
+ * @property {Object} body - The body of the armature
+ * @property {ccs.ColliderFilter} colliderFilter - <@writeonly> The collider filter of the armature
+ */
+ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{
+ animation: null,
+ armatureData: null,
+ batchNode: null,
+ _textureAtlas: null,
+ _parentBone: null,
+ _boneDic: null,
+ _topBoneList: null,
+ _armatureIndexDic: null,
+ _offsetPoint: null,
+ version: 0,
+ _armatureTransformDirty: true,
+ _body: null,
+ _blendFunc: null,
+ _className: "Armature",
+
+ /**
+ * Create a armature node.
+ * Constructor of ccs.Armature
+ * @param {String} name
+ * @param {ccs.Bone} parentBone
+ * @example
+ * var armature = new ccs.Armature();
+ */
+ ctor: function (name, parentBone) {
+ cc.Node.prototype.ctor.call(this);
+ this._name = "";
+ this._topBoneList = [];
+ this._armatureIndexDic = {};
+ this._offsetPoint = cc.p(0, 0);
+ this._armatureTransformDirty = true;
+ this._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST};
+ name && ccs.Armature.prototype.init.call(this, name, parentBone);
+ },
+
+ /**
+ * Initializes a CCArmature with the specified name and CCBone
+ * @param {String} [name]
+ * @param {ccs.Bone} [parentBone]
+ * @return {Boolean}
+ */
+ init: function (name, parentBone) {
+ cc.Node.prototype.init.call(this);
+ if (parentBone)
+ this._parentBone = parentBone;
+ this.removeAllChildren();
+ this.animation = new ccs.ArmatureAnimation();
+ this.animation.init(this);
+
+ this._boneDic = {};
+ this._topBoneList.length = 0;
+
+ //this._name = name || "";
+ var armatureDataManager = ccs.armatureDataManager;
+
+ var animationData;
+ if (name !== "") {
+ //animationData
+ animationData = armatureDataManager.getAnimationData(name);
+ cc.assert(animationData, "AnimationData not exist!");
+
+ this.animation.setAnimationData(animationData);
+
+ //armatureData
+ var armatureData = armatureDataManager.getArmatureData(name);
+ cc.assert(armatureData, "ArmatureData not exist!");
+
+ this.armatureData = armatureData;
+
+ //boneDataDic
+ var boneDataDic = armatureData.getBoneDataDic();
+ for (var key in boneDataDic) {
+ var bone = this.createBone(String(key));
+
+ //! init bone's Tween to 1st movement's 1st frame
+ do {
+ var movData = animationData.getMovement(animationData.movementNames[0]);
+ if (!movData) break;
+
+ var _movBoneData = movData.getMovementBoneData(bone.getName());
+ if (!_movBoneData || _movBoneData.frameList.length <= 0) break;
+
+ var frameData = _movBoneData.getFrameData(0);
+ if (!frameData) break;
+
+ bone.getTweenData().copy(frameData);
+ bone.changeDisplayWithIndex(frameData.displayIndex, false);
+ } while (0);
+ }
+
+ this.update(0);
+ this.updateOffsetPoint();
+ } else {
+ name = "new_armature";
+ this.armatureData = new ccs.ArmatureData();
+ this.armatureData.name = name;
+
+ animationData = new ccs.AnimationData();
+ animationData.name = name;
+
+ armatureDataManager.addArmatureData(name, this.armatureData);
+ armatureDataManager.addAnimationData(name, animationData);
+
+ this.animation.setAnimationData(animationData);
+ }
+
+ this._renderCmd.initShaderCache();
+
+ this.setCascadeOpacityEnabled(true);
+ this.setCascadeColorEnabled(true);
+ return true;
+ },
+
+ addChild: function (child, localZOrder, tag) {
+ if(child instanceof ccui.Widget){
+ cc.log("Armature doesn't support to add Widget as its child, it will be fix soon.");
+ return;
+ }
+ cc.Node.prototype.addChild.call(this, child, localZOrder, tag);
+ },
+
+ /**
+ * create a bone with name
+ * @param {String} boneName
+ * @return {ccs.Bone}
+ */
+ createBone: function (boneName) {
+ var existedBone = this.getBone(boneName);
+ if (existedBone)
+ return existedBone;
+
+ var boneData = this.armatureData.getBoneData(boneName);
+ var parentName = boneData.parentName;
+
+ var bone = null;
+ if (parentName) {
+ this.createBone(parentName);
+ bone = new ccs.Bone(boneName);
+ this.addBone(bone, parentName);
+ } else {
+ bone = new ccs.Bone(boneName);
+ this.addBone(bone, "");
+ }
+
+ bone.setBoneData(boneData);
+ bone.getDisplayManager().changeDisplayWithIndex(-1, false);
+ return bone;
+ },
+
+ /**
+ * Add a Bone to this Armature
+ * @param {ccs.Bone} bone The Bone you want to add to Armature
+ * @param {String} parentName The parent Bone's name you want to add to. If it's null, then set Armature to its parent
+ */
+ addBone: function (bone, parentName) {
+ cc.assert(bone, "Argument must be non-nil");
+ var locBoneDic = this._boneDic;
+ if(bone.getName())
+ cc.assert(!locBoneDic[bone.getName()], "bone already added. It can't be added again");
+
+ if (parentName) {
+ var boneParent = locBoneDic[parentName];
+ if (boneParent)
+ boneParent.addChildBone(bone);
+ else
+ this._topBoneList.push(bone);
+ } else
+ this._topBoneList.push(bone);
+ bone.setArmature(this);
+
+ locBoneDic[bone.getName()] = bone;
+ this.addChild(bone);
+ },
+
+ /**
+ * Remove a bone with the specified name. If recursion it will also remove child Bone recursively.
+ * @param {ccs.Bone} bone The bone you want to remove
+ * @param {Boolean} recursion Determine whether remove the bone's child recursion.
+ */
+ removeBone: function (bone, recursion) {
+ cc.assert(bone, "bone must be added to the bone dictionary!");
+
+ bone.setArmature(null);
+ bone.removeFromParent(recursion);
+ cc.js.array.remove(this._topBoneList, bone);
+
+ delete this._boneDic[bone.getName()];
+ this.removeChild(bone, true);
+ },
+
+ /**
+ * Gets a bone with the specified name
+ * @param {String} name The bone's name you want to get
+ * @return {ccs.Bone}
+ */
+ getBone: function (name) {
+ return this._boneDic[name];
+ },
+
+ /**
+ * Change a bone's parent with the specified parent name.
+ * @param {ccs.Bone} bone The bone you want to change parent
+ * @param {String} parentName The new parent's name
+ */
+ changeBoneParent: function (bone, parentName) {
+ cc.assert(bone, "bone must be added to the bone dictionary!");
+
+ var parentBone = bone.getParentBone();
+ if (parentBone) {
+ cc.js.array.remove(parentBone.getChildren(), bone);
+ bone.setParentBone(null);
+ }
+
+ if (parentName) {
+ var boneParent = this._boneDic[parentName];
+ if (boneParent) {
+ boneParent.addChildBone(bone);
+ cc.js.array.remove(this._topBoneList, bone);
+ } else
+ this._topBoneList.push(bone);
+ }
+ },
+
+ /**
+ * Get CCArmature's bone dictionary
+ * @return {Object} Armature's bone dictionary
+ */
+ getBoneDic: function () {
+ return this._boneDic;
+ },
+
+ /**
+ * Set contentSize and Calculate anchor point.
+ */
+ updateOffsetPoint: function () {
+ // Set contentsize and Calculate anchor point.
+ var rect = this.getBoundingBox();
+ this.setContentSize(rect);
+ var locOffsetPoint = this._offsetPoint;
+ locOffsetPoint.x = -rect.x;
+ locOffsetPoint.y = -rect.y;
+ if (rect.width !== 0 && rect.height !== 0)
+ this.setAnchorPoint(locOffsetPoint.x / rect.width, locOffsetPoint.y / rect.height);
+ },
+
+ getOffsetPoints: function(){
+ return {x: this._offsetPoint.x, y: this._offsetPoint.y};
+ },
+
+ /**
+ * Sets animation to this Armature
+ * @param {ccs.ArmatureAnimation} animation
+ */
+ setAnimation: function (animation) {
+ this.animation = animation;
+ },
+
+ /**
+ * Gets the animation of this Armature.
+ * @return {ccs.ArmatureAnimation}
+ */
+ getAnimation: function () {
+ return this.animation;
+ },
+
+ /**
+ * armatureTransformDirty getter
+ * @returns {Boolean}
+ */
+ getArmatureTransformDirty: function () {
+ return this._armatureTransformDirty;
+ },
+
+ /**
+ * The update callback of ccs.Armature, it updates animation's state and updates bone's state.
+ * @override
+ * @param {Number} dt
+ */
+ update: function (dt) {
+ this.animation.update(dt);
+ var locTopBoneList = this._topBoneList;
+ for (var i = 0; i < locTopBoneList.length; i++)
+ locTopBoneList[i].update(dt);
+ this._armatureTransformDirty = false;
+ },
+
+ /**
+ * The callback when ccs.Armature enter stage.
+ * @override
+ */
+ onEnter: function () {
+ cc.Node.prototype.onEnter.call(this);
+ this.scheduleUpdate();
+ },
+
+ /**
+ * The callback when ccs.Armature exit stage.
+ * @override
+ */
+ onExit: function () {
+ cc.Node.prototype.onExit.call(this);
+ this.unscheduleUpdate();
+ },
+
+ /**
+ * This boundingBox will calculate all bones' boundingBox every time
+ * @returns {cc.Rect}
+ */
+ getBoundingBox: function(){
+ var minX, minY, maxX, maxY = 0;
+ var first = true;
+
+ var boundingBox = cc.rect(0, 0, 0, 0), locChildren = this._children;
+
+ var len = locChildren.length;
+ for (var i=0; i boundingBox.x + boundingBox.width ?
+ r.x + r.width : boundingBox.x + boundingBox.width;
+ maxY = r.y + r.height > boundingBox.y + boundingBox.height ?
+ r.y + r.height : boundingBox.y + boundingBox.height;
+ }
+
+ boundingBox.x = minX;
+ boundingBox.y = minY;
+ boundingBox.width = maxX - minX;
+ boundingBox.height = maxY - minY;
+ }
+ }
+ return cc.rectApplyAffineTransform(boundingBox, this.getNodeToParentTransform());
+ },
+
+ /**
+ * when bone contain the point ,then return it.
+ * @param {Number} x
+ * @param {Number} y
+ * @returns {ccs.Bone}
+ */
+ getBoneAtPoint: function (x, y) {
+ var locChildren = this._children;
+ for (var i = locChildren.length - 1; i >= 0; i--) {
+ var child = locChildren[i];
+ if (child instanceof ccs.Bone && child.getDisplayManager().containPoint(x, y))
+ return child;
+ }
+ return null;
+ },
+
+ /**
+ * Sets parent bone of this Armature
+ * @param {ccs.Bone} parentBone
+ */
+ setParentBone: function (parentBone) {
+ this._parentBone = parentBone;
+ var locBoneDic = this._boneDic;
+ for (var key in locBoneDic) {
+ locBoneDic[key].setArmature(this);
+ }
+ },
+
+ /**
+ * Return parent bone of ccs.Armature.
+ * @returns {ccs.Bone}
+ */
+ getParentBone: function () {
+ return this._parentBone;
+ },
+
+ /**
+ * draw contour
+ */
+ drawContour: function () {
+ cc._drawingUtil.setDrawColor(255, 255, 255, 255);
+ cc._drawingUtil.setLineWidth(1);
+ var locBoneDic = this._boneDic;
+ for (var key in locBoneDic) {
+ var bone = locBoneDic[key];
+ var detector = bone.getColliderDetector();
+ if(!detector)
+ continue;
+ var bodyList = detector.getColliderBodyList();
+ for (var i = 0; i < bodyList.length; i++) {
+ var body = bodyList[i];
+ var vertexList = body.getCalculatedVertexList();
+ cc._drawingUtil.drawPoly(vertexList, vertexList.length, true);
+ }
+ }
+ },
+
+ setBody: function (body) {
+ if (this._body === body)
+ return;
+
+ this._body = body;
+ this._body.data = this;
+ var child, displayObject, locChildren = this._children;
+ for (var i = 0; i < locChildren.length; i++) {
+ child = locChildren[i];
+ if (child instanceof ccs.Bone) {
+ var displayList = child.getDisplayManager().getDecorativeDisplayList();
+ for (var j = 0; j < displayList.length; j++) {
+ displayObject = displayList[j];
+ var detector = displayObject.getColliderDetector();
+ if (detector)
+ detector.setBody(this._body);
+ }
+ }
+ }
+ },
+
+ getShapeList: function () {
+ if (this._body)
+ return this._body.shapeList;
+ return null;
+ },
+
+ getBody: function () {
+ return this._body;
+ },
+
+ /**
+ * Sets the blendFunc to ccs.Armature
+ * @param {cc.BlendFunc|Number} blendFunc
+ * @param {Number} [dst]
+ */
+ setBlendFunc: function (blendFunc, dst) {
+ if(dst === undefined){
+ this._blendFunc.src = blendFunc.src;
+ this._blendFunc.dst = blendFunc.dst;
+ } else {
+ this._blendFunc.src = blendFunc;
+ this._blendFunc.dst = dst;
+ }
+ },
+
+ /**
+ * Returns the blendFunc of ccs.Armature
+ * @returns {cc.BlendFunc}
+ */
+ getBlendFunc: function () {
+ return new cc.BlendFunc(this._blendFunc.src, this._blendFunc.dst);
+ },
+
+ /**
+ * set collider filter
+ * @param {ccs.ColliderFilter} filter
+ */
+ setColliderFilter: function (filter) {
+ var locBoneDic = this._boneDic;
+ for (var key in locBoneDic)
+ locBoneDic[key].setColliderFilter(filter);
+ },
+
+ /**
+ * Returns the armatureData of ccs.Armature
+ * @return {ccs.ArmatureData}
+ */
+ getArmatureData: function () {
+ return this.armatureData;
+ },
+
+ /**
+ * Sets armatureData to this Armature
+ * @param {ccs.ArmatureData} armatureData
+ */
+ setArmatureData: function (armatureData) {
+ this.armatureData = armatureData;
+ },
+
+ getBatchNode: function () {
+ return this.batchNode;
+ },
+
+ setBatchNode: function (batchNode) {
+ this.batchNode = batchNode;
+ },
+
+ /**
+ * version getter
+ * @returns {Number}
+ */
+ getVersion: function () {
+ return this.version;
+ },
+
+ /**
+ * version setter
+ * @param {Number} version
+ */
+ setVersion: function (version) {
+ this.version = version;
+ },
+
+ _createRenderCmd: function(){
+ if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ return new ccs.Armature.CanvasRenderCmd(this);
+ else
+ return new ccs.Armature.WebGLRenderCmd(this);
+ }
+});
+
+var _p = ccs.Armature.prototype;
+
+/** @expose */
+_p.parentBone;
+cc.defineGetterSetter(_p, "parentBone", _p.getParentBone, _p.setParentBone);
+/** @expose */
+_p.body;
+cc.defineGetterSetter(_p, "body", _p.getBody, _p.setBody);
+/** @expose */
+_p.colliderFilter;
+cc.defineGetterSetter(_p, "colliderFilter", null, _p.setColliderFilter);
+
+_p = null;
+
+/**
+ * Allocates an armature, and use the ArmatureData named name in ArmatureDataManager to initializes the armature.
+ * @param {String} [name] Bone name
+ * @param {ccs.Bone} [parentBone] the parent bone
+ * @return {ccs.Armature}
+ * @deprecated since v3.1, please use new construction instead
+ */
+ccs.Armature.create = function (name, parentBone) {
+ return new ccs.Armature(name, parentBone);
+};
diff --git a/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js b/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js
new file mode 100644
index 0000000000..f184205651
--- /dev/null
+++ b/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js
@@ -0,0 +1,190 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+(function(){
+ ccs.Armature.RenderCmd = {
+ _updateAnchorPointInPoint: function(){
+ var node = this._node;
+ var contentSize = node._contentSize, anchorPoint = node._anchorPoint, offsetPoint = node._offsetPoint;
+ this._anchorPointInPoints.x = contentSize.width * anchorPoint.x - offsetPoint.x;
+ this._anchorPointInPoints.y = contentSize.height * anchorPoint.y - offsetPoint.y;
+
+ this._realAnchorPointInPoints.x = contentSize.width * anchorPoint.x;
+ this._realAnchorPointInPoints.y = contentSize.height * anchorPoint.y;
+ this.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
+ },
+
+ getAnchorPointInPoints: function(){
+ return cc.p(this._realAnchorPointInPoints);
+ }
+ };
+})();
+
+(function(){
+ ccs.Armature.CanvasRenderCmd = function(renderableObject){
+ cc.Node.CanvasRenderCmd.call(this, renderableObject);
+ this._needDraw = true;
+
+ this._realAnchorPointInPoints = new cc.Vec2(0,0);
+ this._startRenderCmd = new cc.CustomRenderCmd(this, this._startCmdCallback);
+ this._RestoreRenderCmd = new cc.CustomRenderCmd(this, this._RestoreCmdCallback);
+ };
+
+ var proto = ccs.Armature.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
+ cc.js.mixin(proto, ccs.Armature.RenderCmd);
+ proto.constructor = ccs.Armature.CanvasRenderCmd;
+
+ proto._startCmdCallback = function(ctx, scaleX, scaleY){
+ var node = this._node, parent = node._parent;
+ this.transform(parent ? parent._renderCmd : null);
+
+ var wrapper = ctx || cc._renderContext;
+ wrapper.save();
+
+ //set to armature mode
+ wrapper._switchToArmatureMode(true, this._worldTransform, scaleX, scaleY);
+ };
+
+ proto.transform = function(parentCmd, recursive){
+ ccs.Node.CanvasRenderCmd.prototype.transform.call(this, parentCmd, recursive);
+
+ var locChildren = this._node._children;
+ for (var i = 0, len = locChildren.length; i< len; i++) {
+ var selBone = locChildren[i];
+ if (selBone && selBone.getDisplayRenderNode) {
+ var selNode = selBone.getDisplayRenderNode();
+ if (selNode && selNode._renderCmd){
+ var cmd = selNode._renderCmd;
+ cmd.transform(null); //must be null, use transform in armature mode
+
+ //update displayNode's color and opacity, because skin didn't call visit()
+ var parentColor = selBone._renderCmd._displayedColor, parentOpacity = selBone._renderCmd._displayedOpacity;
+ var flags = cc.Node._dirtyFlags, locFlag = cmd._dirtyFlag;
+ var colorDirty = locFlag & flags.colorDirty,
+ opacityDirty = locFlag & flags.opacityDirty;
+ if(colorDirty)
+ cmd._updateDisplayColor(parentColor);
+ if(opacityDirty)
+ cmd._updateDisplayOpacity(parentOpacity);
+ }
+ }
+ }
+ };
+
+ proto._RestoreCmdCallback = function(wrapper){
+ this._cacheDirty = false;
+ //wrapper.restore();
+ wrapper._switchToArmatureMode(false);
+ wrapper.restore();
+ };
+
+ proto.initShaderCache = function(){};
+ proto.setShaderProgram = function(){};
+ proto.updateChildPosition = function(ctx, dis){
+ //dis.visit(ctx);
+ cc.renderer.pushRenderCommand(dis._renderCmd);
+ };
+
+ proto.rendering = function(ctx, scaleX, scaleY){
+ var node = this._node;
+ var locChildren = node._children;
+ var alphaPremultiplied = cc.BlendFunc.ALPHA_PREMULTIPLIED, alphaNonPremultipled = cc.BlendFunc.ALPHA_NON_PREMULTIPLIED;
+ for (var i = 0, len = locChildren.length; i< len; i++) {
+ var selBone = locChildren[i];
+ if (selBone && selBone.getDisplayRenderNode) {
+ var selNode = selBone.getDisplayRenderNode();
+ if (null === selNode)
+ continue;
+
+ switch (selBone.getDisplayRenderNodeType()) {
+ case ccs.DISPLAY_TYPE_SPRITE:
+ if(selNode instanceof ccs.Skin)
+ this.updateChildPosition(ctx, selNode, selBone, alphaPremultiplied, alphaNonPremultipled);
+ break;
+ case ccs.DISPLAY_TYPE_ARMATURE:
+ selNode._renderCmd.rendering(ctx, scaleX, scaleY);
+ break;
+ default:
+ selNode.visit(this);
+ break;
+ }
+ } else if(selBone instanceof cc.Node) {
+ this._visitNormalChild(selBone);
+ //selBone.visit(this);
+ }
+ }
+ };
+
+ proto._visitNormalChild = function(childNode){
+ if(childNode == null)
+ return;
+
+ var cmd = childNode._renderCmd;
+ // quick return if not visible
+ if (!childNode._visible)
+ return;
+ cmd._curLevel = this._curLevel + 1;
+
+ //visit for canvas
+ var i, children = childNode._children, child;
+ cmd._syncStatus(this);
+ //because armature use transform, not setTransform
+ cmd.transform(null);
+
+ var len = children.length;
+ if (len > 0) {
+ childNode.sortAllChildren();
+ // draw children zOrder < 0
+ for (i = 0; i < len; i++) {
+ child = children[i];
+ if (child._localZOrder < 0)
+ child._renderCmd.visit(cmd);
+ else
+ break;
+ }
+ cc.renderer.pushRenderCommand(cmd);
+ for (; i < len; i++)
+ children[i]._renderCmd.visit(cmd);
+ } else {
+ cc.renderer.pushRenderCommand(cmd);
+ }
+ this._dirtyFlag = 0;
+ };
+
+ proto.visit = function(parentCmd){
+ var node = this._node;
+ // quick return if not visible. children won't be drawn.
+ if (!node._visible)
+ return;
+
+ this.updateStatus(parentCmd);
+ node.sortAllChildren();
+
+ cc.renderer.pushRenderCommand(this._startRenderCmd);
+ this.rendering();
+ cc.renderer.pushRenderCommand(this._RestoreRenderCmd);
+
+ this._cacheDirty = false;
+ };
+})();
\ No newline at end of file
diff --git a/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js b/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js
new file mode 100644
index 0000000000..baffdc3081
--- /dev/null
+++ b/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js
@@ -0,0 +1,167 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+(function(){
+
+ ccs.Armature.WebGLRenderCmd = function(renderableObject){
+ cc.Node.WebGLRenderCmd.call(this, renderableObject);
+ this._needDraw = true;
+
+ this._realAnchorPointInPoints = new cc.Vec2(0,0);
+ };
+
+ var proto = ccs.Armature.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
+ cc.js.mixin(proto, ccs.Armature.RenderCmd);
+ proto.constructor = ccs.Armature.WebGLRenderCmd;
+
+ proto.rendering = function (ctx, dontChangeMatrix) {
+ var node = this._node;
+
+ if(!dontChangeMatrix){
+ cc.kmGLMatrixMode(cc.KM_GL_MODELVIEW);
+ cc.kmGLPushMatrix();
+ cc.kmGLLoadMatrix(this._stackMatrix);
+ }
+
+ var locChildren = node._children;
+ var alphaPremultiplied = cc.BlendFunc.ALPHA_PREMULTIPLIED, alphaNonPremultipled = cc.BlendFunc.ALPHA_NON_PREMULTIPLIED;
+ for (var i = 0, len = locChildren.length; i < len; i++) {
+ var selBone = locChildren[i];
+ if (selBone && selBone.getDisplayRenderNode) {
+ var selNode = selBone.getDisplayRenderNode();
+ if (null === selNode)
+ continue;
+ selNode.setShaderProgram(this._shaderProgram);
+ switch (selBone.getDisplayRenderNodeType()) {
+ case ccs.DISPLAY_TYPE_SPRITE:
+ if (selNode instanceof ccs.Skin) {
+ this._updateColorAndOpacity(selNode._renderCmd, selBone); //because skin didn't call visit()
+ selNode.updateTransform();
+
+ var func = selBone.getBlendFunc();
+ if (func.src !== alphaPremultiplied.src || func.dst !== alphaPremultiplied.dst)
+ selNode.setBlendFunc(selBone.getBlendFunc());
+ else {
+ if ((node._blendFunc.src === alphaPremultiplied.src && node._blendFunc.dst === alphaPremultiplied.dst)
+ && !selNode.getTexture().hasPremultipliedAlpha())
+ selNode.setBlendFunc(alphaNonPremultipled);
+ else
+ selNode.setBlendFunc(node._blendFunc);
+ }
+ selNode._renderCmd.rendering(ctx);
+ }
+ break;
+ case ccs.DISPLAY_TYPE_ARMATURE:
+ selNode._renderCmd.rendering(ctx, true);
+ break;
+ default:
+ selNode._renderCmd.transform();
+ selNode._renderCmd.rendering(ctx);
+ break;
+ }
+ } else if (selBone instanceof cc.Node) {
+ selBone.setShaderProgram(this._shaderProgram);
+ selBone._renderCmd.transform();
+ if(selBone._renderCmd.rendering)
+ selBone._renderCmd.rendering(ctx);
+ }
+ }
+ if(!dontChangeMatrix)
+ cc.kmGLPopMatrix();
+ };
+
+ proto.initShaderCache = function(){
+ this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURECOLOR);
+ };
+
+ proto.setShaderProgram = function(shaderProgram){
+ this._shaderProgram = shaderProgram;
+ };
+
+ proto._updateColorAndOpacity = function(skinRenderCmd, bone){
+ //update displayNode's color and opacity
+ var parentColor = bone._renderCmd._displayedColor, parentOpacity = bone._renderCmd._displayedOpacity;
+ var flags = cc.Node._dirtyFlags, locFlag = skinRenderCmd._dirtyFlag;
+ var colorDirty = locFlag & flags.colorDirty,
+ opacityDirty = locFlag & flags.opacityDirty;
+ if(colorDirty)
+ skinRenderCmd._updateDisplayColor(parentColor);
+ if(opacityDirty)
+ skinRenderCmd._updateDisplayOpacity(parentOpacity);
+ if(colorDirty || opacityDirty)
+ skinRenderCmd._updateColor();
+ };
+
+ proto.updateChildPosition = function(ctx, dis, selBone, alphaPremultiplied, alphaNonPremultipled){
+ var node = this._node;
+ dis.updateTransform();
+
+ var func = selBone.getBlendFunc();
+ if (func.src !== alphaPremultiplied.src || func.dst !== alphaPremultiplied.dst)
+ dis.setBlendFunc(selBone.getBlendFunc());
+ else {
+ if ((node._blendFunc.src === alphaPremultiplied.src && node_blendFunc.dst === alphaPremultiplied.dst)
+ && !dis.getTexture().hasPremultipliedAlpha())
+ dis.setBlendFunc(alphaNonPremultipled);
+ else
+ dis.setBlendFunc(node._blendFunc);
+ }
+ dis.rendering(ctx);
+ };
+
+ proto.updateStatus = function () {
+ var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag;
+ var colorDirty = locFlag & flags.colorDirty,
+ opacityDirty = locFlag & flags.opacityDirty;
+ if(colorDirty)
+ this._updateDisplayColor();
+
+ if(opacityDirty)
+ this._updateDisplayOpacity();
+
+ if(colorDirty || opacityDirty)
+ this._updateColor();
+
+ //update the transform every visit, needn't dirty flag,
+ this.transform(this.getParentRenderCmd(), true);
+ };
+
+ proto.visit = function(parentCmd){
+ var node = this._node;
+ // quick return if not visible. children won't be drawn.
+ if (!node._visible)
+ return;
+
+ var currentStack = cc.current_stack;
+ currentStack.stack.push(currentStack.top);
+ this.updateStatus(parentCmd);
+ currentStack.top = this._stackMatrix;
+
+ node.sortAllChildren();
+ cc.renderer.pushRenderCommand(this);
+
+ this._dirtyFlag = 0;
+ currentStack.top = currentStack.stack.pop();
+ };
+})();
\ No newline at end of file
diff --git a/extensions/cocostudio/armature/CCBone.js b/extensions/cocostudio/armature/CCBone.js
new file mode 100644
index 0000000000..d0cf3bac0c
--- /dev/null
+++ b/extensions/cocostudio/armature/CCBone.js
@@ -0,0 +1,713 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+/**
+ * The Bone of Armature, it has bone data, display manager and transform data for armature.
+ * @class
+ * @extends ccs.Node
+ *
+ * @param {String} [name] The name of the bone
+ * @example
+ *
+ * var bone = new ccs.Bone("head");
+ *
+ * @property {ccs.BoneData} boneData - The bone data
+ * @property {ccs.Armature} armature - The armature
+ * @property {ccs.Bone} parentBone - The parent bone
+ * @property {ccs.Armature} childArmature - The child armature
+ * @property {Array} childrenBone - <@readonly> All children bones
+ * @property {ccs.Tween} tween - <@readonly> Tween
+ * @property {ccs.FrameData} tweenData - <@readonly> The tween data
+ * @property {ccs.ColliderFilter} colliderFilter - The collider filter
+ * @property {ccs.DisplayManager} displayManager - The displayManager
+ * @property {Boolean} ignoreMovementBoneData - Indicate whether force the bone to show When CCArmature play a animation and there isn't a CCMovementBoneData of this bone in this CCMovementData.
+ * @property {String} name - The name of the bone
+ * @property {Boolean} blendDirty - Indicate whether the blend is dirty
+ *
+ */
+ccs.Bone = ccs.Node.extend(/** @lends ccs.Bone# */{
+ _boneData: null,
+ _armature: null,
+ _childArmature: null,
+ _displayManager: null,
+ ignoreMovementBoneData: false,
+ _tween: null,
+ _tweenData: null,
+ _parentBone: null,
+ _boneTransformDirty: false,
+ _worldTransform: null,
+ _blendFunc: null,
+ blendDirty: false,
+ _worldInfo: null,
+ _armatureParentBone: null,
+ _dataVersion: 0,
+ _className: "Bone",
+
+ ctor: function (name) {
+ cc.Node.prototype.ctor.call(this);
+ this._tweenData = null;
+ this._parentBone = null;
+ this._armature = null;
+ this._childArmature = null;
+ this._boneData = null;
+ this._tween = null;
+ this._displayManager = null;
+ this.ignoreMovementBoneData = false;
+
+ this._worldTransform = cc.affineTransformMake(1, 0, 0, 1, 0, 0);
+ this._boneTransformDirty = true;
+ this._blendFunc = new cc.BlendFunc(cc.BLEND_SRC, cc.BLEND_DST);
+ this.blendDirty = false;
+ this._worldInfo = null;
+
+ this._armatureParentBone = null;
+ this._dataVersion = 0;
+
+ ccs.Bone.prototype.init.call(this, name);
+ },
+
+ /**
+ * Initializes a ccs.Bone with the specified name
+ * @param {String} name bone name
+ * @return {Boolean}
+ */
+ init: function (name) {
+// cc.Node.prototype.init.call(this);
+ if (name)
+ this._name = name;
+ this._tweenData = new ccs.FrameData();
+
+ this._tween = new ccs.Tween(this);
+
+ this._displayManager = new ccs.DisplayManager(this);
+
+ this._worldInfo = new ccs.BaseData();
+ this._boneData = new ccs.BaseData();
+
+ return true;
+ },
+
+ /**
+ * Sets the boneData to ccs.Bone.
+ * @param {ccs.BoneData} boneData
+ */
+ setBoneData: function (boneData) {
+ cc.assert(boneData, "_boneData must not be null");
+
+ if(this._boneData !== boneData)
+ this._boneData = boneData;
+
+ this.setName(this._boneData.name);
+ this._localZOrder = this._boneData.zOrder;
+ this._displayManager.initDisplayList(boneData);
+ },
+
+ /**
+ * Returns boneData of ccs.Bone.
+ * @return {ccs.BoneData}
+ */
+ getBoneData: function () {
+ return this._boneData;
+ },
+
+ /**
+ * Sets the armature reference to ccs.Bone.
+ * @param {ccs.Armature} armature
+ */
+ setArmature: function (armature) {
+ this._armature = armature;
+ if (armature) {
+ this._tween.setAnimation(this._armature.getAnimation());
+ this._dataVersion = this._armature.getArmatureData().dataVersion;
+ this._armatureParentBone = this._armature.getParentBone();
+ } else
+ this._armatureParentBone = null;
+ },
+
+ /**
+ * Returns the armature reference of ccs.Bone.
+ * @return {ccs.Armature}
+ */
+ getArmature: function () {
+ return this._armature;
+ },
+
+ /**
+ * Updates worldTransform by tween data and updates display state
+ * @param {Number} delta
+ */
+ update: function (delta) {
+ if (this._parentBone)
+ this._boneTransformDirty = this._boneTransformDirty || this._parentBone.isTransformDirty();
+
+ if (this._armatureParentBone && !this._boneTransformDirty)
+ this._boneTransformDirty = this._armatureParentBone.isTransformDirty();
+
+ if (this._boneTransformDirty){
+ var locTweenData = this._tweenData;
+ if (this._dataVersion >= ccs.CONST_VERSION_COMBINED){
+ ccs.TransformHelp.nodeConcat(locTweenData, this._boneData);
+ locTweenData.scaleX -= 1;
+ locTweenData.scaleY -= 1;
+ }
+
+ var locWorldInfo = this._worldInfo;
+ locWorldInfo.copy(locTweenData);
+ locWorldInfo.x = locTweenData.x + this._position.x;
+ locWorldInfo.y = locTweenData.y + this._position.y;
+ locWorldInfo.scaleX = locTweenData.scaleX * this._scaleX;
+ locWorldInfo.scaleY = locTweenData.scaleY * this._scaleY;
+ locWorldInfo.skewX = locTweenData.skewX + this._skewX + cc.degreesToRadians(this._rotationX);
+ locWorldInfo.skewY = locTweenData.skewY + this._skewY - cc.degreesToRadians(this._rotationY);
+
+ if(this._parentBone)
+ this._applyParentTransform(this._parentBone);
+ else {
+ if (this._armatureParentBone)
+ this._applyParentTransform(this._armatureParentBone);
+ }
+
+ ccs.TransformHelp.nodeToMatrix(locWorldInfo, this._worldTransform);
+ if (this._armatureParentBone)
+ this._worldTransform = cc.affineTransformConcat(this._worldTransform, this._armature.getNodeToParentTransform()); //TODO TransformConcat
+ }
+
+ ccs.displayFactory.updateDisplay(this, delta, this._boneTransformDirty || this._armature.getArmatureTransformDirty());
+ for(var i=0; i= ccs.CONST_VERSION_COMBINED) {
+ this.setLocalZOrder(this._tweenData.zOrder + this._boneData.zOrder);
+ } else {
+ this.setLocalZOrder(this._tweenData.zOrder);
+ }
+ },
+
+ /**
+ * Adds a child to this bone, and it will let this child call setParent(ccs.Bone) function to set self to it's parent
+ * @param {ccs.Bone} child
+ */
+ addChildBone: function (child) {
+ cc.assert(child, "Argument must be non-nil");
+ cc.assert(!child.parentBone, "child already added. It can't be added again");
+
+ if (this._children.indexOf(child) < 0) {
+ this._children.push(child);
+ child.setParentBone(this);
+ }
+ },
+
+ /**
+ * Removes a child bone
+ * @param {ccs.Bone} bone
+ * @param {Boolean} recursion
+ */
+ removeChildBone: function (bone, recursion) {
+ if (this._children.length > 0 && this._children.getIndex(bone) !== -1 ) {
+ if(recursion) {
+ var ccbones = bone._children;
+ for(var i=0; i
+ * Set IgnoreMovementBoneData to true, then this bone will also show.
+ * @param {Boolean} bool
+ */
+ setIgnoreMovementBoneData: function (bool) {
+ this._ignoreMovementBoneData = bool;
+ },
+
+ /**
+ * Returns whether is ignore movement bone data.
+ * @returns {Boolean}
+ */
+ isIgnoreMovementBoneData: function(){
+ return this._ignoreMovementBoneData;
+ },
+
+ /**
+ * Returns the blendFunc of ccs.Bone.
+ * @return {cc.BlendFunc}
+ */
+ getBlendFunc: function () {
+ return new cc.BlendFunc(this._blendFunc.src, this._blendFunc.dst);
+ },
+
+ /**
+ * Sets blend dirty flag
+ * @param {Boolean} dirty
+ */
+ setBlendDirty: function (dirty) {
+ this._blendDirty = dirty;
+ },
+
+ /**
+ * Returns the blend dirty flag whether is dirty.
+ * @returns {Boolean|*|ccs.Bone._blendDirty}
+ */
+ isBlendDirty: function () {
+ return this._blendDirty;
+ },
+
+ /**
+ * Returns the tweenData of ccs.Bone.
+ * @return {ccs.FrameData}
+ */
+ getTweenData: function () {
+ return this._tweenData;
+ },
+
+ /**
+ * Returns the world information of ccs.Bone.
+ * @returns {ccs.BaseData}
+ */
+ getWorldInfo: function(){
+ return this._worldInfo;
+ },
+
+ /**
+ * Returns the children of ccs.Bone
+ * @return {Array}
+ * @deprecated since v3.0, please use getChildren instead.
+ */
+ getChildrenBone: function () {
+ return this._children;
+ },
+
+ /**
+ * Returns the worldTransform of ccs.Bone.
+ * @return {cc.AffineTransform}
+ * @deprecated since v3.0, please use getNodeToArmatureTransform instead.
+ */
+ nodeToArmatureTransform: function () {
+ return this.getNodeToArmatureTransform();
+ },
+
+ /**
+ * @deprecated
+ * Returns the world affine transform matrix. The matrix is in Pixels.
+ * @returns {cc.AffineTransform}
+ */
+ nodeToWorldTransform: function () {
+ return this.getNodeToWorldTransform();
+ },
+
+ /**
+ * Returns the collider body list in this bone.
+ * @returns {Array|null}
+ * @deprecated since v3.0, please use getColliderDetector to get a delector, and calls its getColliderBodyList instead.
+ */
+ getColliderBodyList: function () {
+ var detector = this.getColliderDetector();
+ if(detector)
+ return detector.getColliderBodyList();
+ return null;
+ },
+
+ /**
+ * Returns whether is ignore movement bone data.
+ * @return {Boolean}
+ * @deprecated since v3.0, please isIgnoreMovementBoneData instead.
+ */
+ getIgnoreMovementBoneData: function () {
+ return this.isIgnoreMovementBoneData();
+ },
+
+ _createRenderCmd: function(){
+ if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ return new ccs.Bone.CanvasRenderCmd(this);
+ else
+ return new ccs.Bone.WebGLRenderCmd(this);
+ }
+});
+
+var _p = ccs.Bone.prototype;
+
+// Extended properties
+/** @expose */
+_p.boneData;
+cc.defineGetterSetter(_p, "boneData", _p.getBoneData, _p.setBoneData);
+/** @expose */
+_p.armature;
+cc.defineGetterSetter(_p, "armature", _p.getArmature, _p.setArmature);
+/** @expose */
+_p.childArmature;
+cc.defineGetterSetter(_p, "childArmature", _p.getChildArmature, _p.setChildArmature);
+/** @expose */
+_p.childrenBone;
+cc.defineGetterSetter(_p, "childrenBone", _p.getChildrenBone);
+/** @expose */
+_p.tween;
+cc.defineGetterSetter(_p, "tween", _p.getTween);
+/** @expose */
+_p.tweenData;
+cc.defineGetterSetter(_p, "tweenData", _p.getTweenData);
+/** @expose */
+_p.colliderFilter;
+cc.defineGetterSetter(_p, "colliderFilter", _p.getColliderFilter, _p.setColliderFilter);
+
+_p = null;
+
+/**
+ * Allocates and initializes a bone.
+ * @return {ccs.Bone}
+ * @deprecated since v3.1, please use new construction instead
+ */
+ccs.Bone.create = function (name) {
+ return new ccs.Bone(name);
+};
+
+ccs.Bone.RenderCmd = {
+ _updateColor: function(){
+ var node = this._node;
+ var display = node._displayManager.getDisplayRenderNode();
+ if (display !== null) {
+ var displayCmd = display._renderCmd;
+ display.setColor(cc.color( node._tweenData.r, node._tweenData.g, node._tweenData.g));
+ display.setOpacity(node._tweenData.a);
+ displayCmd._syncDisplayColor(this._displayedColor);
+ displayCmd._syncDisplayOpacity(this._displayedOpacity);
+ displayCmd._updateColor();
+ }
+ }
+};
+
+(function(){
+ ccs.Bone.CanvasRenderCmd = function(renderable){
+ cc.Node.CanvasRenderCmd.call(this, renderable);
+ this._needDraw = false;
+ };
+
+ var proto = ccs.Bone.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
+ cc.js.mixin(proto, ccs.Bone.RenderCmd);
+ proto.constructor = ccs.Bone.CanvasRenderCmd;
+})();
+
+(function(){
+ if(!cc.Node.WebGLRenderCmd)
+ return;
+ ccs.Bone.WebGLRenderCmd = function(renderable){
+ cc.Node.WebGLRenderCmd.call(this, renderable);
+ this._needDraw = false;
+ };
+
+ var proto = ccs.Bone.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
+ cc.js.mixin(proto, ccs.Bone.RenderCmd);
+ proto.constructor = ccs.Bone.WebGLRenderCmd;
+})();
diff --git a/extensions/cocostudio/armature/animation/CCArmatureAnimation.js b/extensions/cocostudio/armature/animation/CCArmatureAnimation.js
new file mode 100644
index 0000000000..870ba7ed0f
--- /dev/null
+++ b/extensions/cocostudio/armature/animation/CCArmatureAnimation.js
@@ -0,0 +1,669 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+/**
+ * movement event type enum
+ * @constant
+ * @type {Object}
+ */
+ccs.MovementEventType = {
+ start: 0,
+ complete: 1,
+ loopComplete: 2
+};
+
+/**
+ * The animation event class, it has the callback, target and arguments.
+ * @deprecated since v3.0.
+ * @class
+ * @extends ccs.Class
+ */
+ccs.AnimationEvent = ccs.Class.extend(/** @lends ccs.AnimationEvent# */{
+ _arguments: null,
+ _callFunc: null,
+ _selectorTarget: null,
+
+ /**
+ * Constructor of ccs.AnimationEvent
+ * @param {function} callFunc
+ * @param {object} target
+ * @param {object} [data]
+ */
+ ctor: function (callFunc,target, data) {
+ this._data = data;
+ this._callFunc = callFunc;
+ this._selectorTarget = target;
+ },
+ call: function () {
+ if (this._callFunc)
+ this._callFunc.apply(this._selectorTarget, this._arguments);
+ },
+ setArguments: function (args) {
+ this._arguments = args;
+ }
+});
+
+/**
+ * The movement event class for Armature.
+ * @constructor
+ *
+ * @property {ccs.Armature} armature - The armature reference of movement event.
+ * @property {Number} movementType - The type of movement.
+ * @property {String} movementID - The ID of movement.
+ */
+ccs.MovementEvent = function () {
+ this.armature = null;
+ this.movementType = ccs.MovementEventType.start;
+ this.movementID = "";
+};
+
+/**
+ * The frame event class for Armature.
+ * @constructor
+ *
+ * @property {ccs.Bone} bone - The bone reference of frame event.
+ * @property {String} frameEventName - The name of frame event.
+ * @property {Number} originFrameIndex - The index of origin frame.
+ * @property {Number} currentFrameIndex - The index of current frame.
+ */
+ccs.FrameEvent = function () {
+ this.bone = null;
+ this.frameEventName = "";
+ this.originFrameIndex = 0;
+ this.currentFrameIndex = 0;
+};
+
+/**
+ * The Animation class for Armature, it plays armature animation, and controls speed scale and manages animation frame.
+ * @class
+ * @extends ccs.ProcessBase
+ *
+ * @param {ccs.Armature} [armature] The armature
+ *
+ * @property {ccs.AnimationData} animationData - Animation data
+ * @property {Object} userObject - User custom object
+ * @property {Boolean} ignoreFrameEvent - Indicate whether the frame event is ignored
+ * @property {Number} speedScale - Animation play speed scale
+ * @property {Number} animationScale - Animation play speed scale
+ */
+ccs.ArmatureAnimation = ccs.ProcessBase.extend(/** @lends ccs.ArmatureAnimation# */{
+ _animationData: null,
+ _movementData: null,
+ _armature: null,
+ _movementID: "",
+ _toIndex: 0,
+ _tweenList: null,
+ _speedScale: 1,
+ _ignoreFrameEvent: false,
+ _frameEventQueue: null,
+ _movementEventQueue: null,
+ _movementList: null,
+ _onMovementList: false,
+ _movementListLoop: false,
+ _movementIndex: 0,
+ _movementListDurationTo: -1,
+
+ _movementEventCallFunc: null,
+ _frameEventCallFunc: null,
+ _movementEventTarget: null,
+ _frameEventTarget:null,
+ _movementEventListener: null,
+ _frameEventListener: null,
+
+ ctor: function (armature) {
+ ccs.ProcessBase.prototype.ctor.call(this);
+
+ this._tweenList = [];
+ this._movementList = [];
+ this._frameEventQueue = [];
+ this._movementEventQueue = [];
+ this._armature = null;
+
+ armature && ccs.ArmatureAnimation.prototype.init.call(this, armature);
+ },
+
+ /**
+ * Initializes with an armature object
+ * @param {ccs.Armature} armature
+ * @return {Boolean}
+ */
+ init: function (armature) {
+ this._armature = armature;
+ this._tweenList.length = 0;
+ return true;
+ },
+
+ /**
+ * Pauses armature animation.
+ */
+ pause: function () {
+ var locTweenList = this._tweenList;
+ for (var i = 0; i < locTweenList.length; i++)
+ locTweenList[i].pause();
+ ccs.ProcessBase.prototype.pause.call(this);
+ },
+
+ /**
+ * Resumes armature animation.
+ */
+ resume: function () {
+ var locTweenList = this._tweenList;
+ for (var i = 0; i < locTweenList.length; i++)
+ locTweenList[i].resume();
+ ccs.ProcessBase.prototype.resume.call(this);
+ },
+
+ /**
+ * Stops armature animation.
+ */
+ stop: function () {
+ var locTweenList = this._tweenList;
+ for (var i = 0; i < locTweenList.length; i++)
+ locTweenList[i].stop();
+ locTweenList.length = 0;
+ ccs.ProcessBase.prototype.stop.call(this);
+ },
+
+ /**
+ * Sets animation play speed scale.
+ * @deprecated since v3.0, please use setSpeedScale instead.
+ * @param {Number} animationScale
+ */
+ setAnimationScale: function (animationScale) {
+ this.setSpeedScale(animationScale);
+ },
+
+ /**
+ * Returns animation play speed scale.
+ * @deprecated since v3.0, please use getSpeedScale instead.
+ * @returns {Number}
+ */
+ getAnimationScale: function () {
+ return this.getSpeedScale();
+ },
+
+ /**
+ * Sets animation play speed scale.
+ * @param {Number} speedScale
+ */
+ setSpeedScale: function (speedScale) {
+ if (speedScale === this._speedScale)
+ return;
+ this._speedScale = speedScale;
+ this._processScale = !this._movementData ? this._speedScale : this._speedScale * this._movementData.scale;
+ var dict = this._armature.getBoneDic();
+ for (var key in dict) {
+ var bone = dict[key];
+ bone.getTween().setProcessScale(this._processScale);
+ if (bone.getChildArmature())
+ bone.getChildArmature().getAnimation().setSpeedScale(this._processScale);
+ }
+ },
+
+ /**
+ * Returns animation play speed scale.
+ * @returns {Number}
+ */
+ getSpeedScale: function () {
+ return this._speedScale;
+ },
+
+ /**
+ * play animation by animation name.
+ * @param {String} animationName The animation name you want to play
+ * @param {Number} [durationTo=-1]
+ * the frames between two animation changing-over.It's meaning is changing to this animation need how many frames
+ * -1 : use the value from CCMovementData get from flash design panel
+ * @param {Number} [loop=-1]
+ * Whether the animation is loop.
+ * loop < 0 : use the value from CCMovementData get from flash design panel
+ * loop = 0 : this animation is not loop
+ * loop > 0 : this animation is loop
+ * @example
+ * // example
+ * armature.getAnimation().play("run",-1,1);//loop play
+ * armature.getAnimation().play("run",-1,0);//not loop play
+ */
+ play: function (animationName, durationTo, loop) {
+ cc.assert(this._animationData, "this.animationData can not be null");
+
+ this._movementData = this._animationData.getMovement(animationName);
+ cc.assert(this._movementData, "this._movementData can not be null");
+
+ durationTo = (durationTo === undefined) ? -1 : durationTo;
+ loop = (loop === undefined) ? -1 : loop;
+
+ //! Get key frame count
+ this._rawDuration = this._movementData.duration;
+ this._movementID = animationName;
+ this._processScale = this._speedScale * this._movementData.scale;
+
+ //! Further processing parameters
+ durationTo = (durationTo === -1) ? this._movementData.durationTo : durationTo;
+ var durationTween = this._movementData.durationTween === 0 ? this._rawDuration : this._movementData.durationTween;
+
+ var tweenEasing = this._movementData.tweenEasing;
+ //loop = (!loop || loop < 0) ? this._movementData.loop : loop;
+ loop = (loop < 0) ? this._movementData.loop : loop;
+ this._onMovementList = false;
+
+ ccs.ProcessBase.prototype.play.call(this, durationTo, durationTween, loop, tweenEasing);
+
+ if (this._rawDuration === 0)
+ this._loopType = ccs.ANIMATION_TYPE_SINGLE_FRAME;
+ else {
+ this._loopType = loop ? ccs.ANIMATION_TYPE_TO_LOOP_FRONT : ccs.ANIMATION_TYPE_NO_LOOP;
+ this._durationTween = durationTween;
+ }
+
+ this._tweenList.length = 0;
+
+ var movementBoneData, map = this._armature.getBoneDic();
+ for(var element in map) {
+ var bone = map[element];
+ movementBoneData = this._movementData.movBoneDataDic[bone.getName()];
+
+ var tween = bone.getTween();
+ if(movementBoneData && movementBoneData.frameList.length > 0) {
+ this._tweenList.push(tween);
+ movementBoneData.duration = this._movementData.duration;
+ tween.play(movementBoneData, durationTo, durationTween, loop, tweenEasing);
+ tween.setProcessScale(this._processScale);
+
+ if (bone.getChildArmature())
+ bone.getChildArmature().getAnimation().setSpeedScale(this._processScale);
+ } else {
+ if(!bone.isIgnoreMovementBoneData()){
+ //! this bone is not include in this movement, so hide it
+ bone.getDisplayManager().changeDisplayWithIndex(-1, false);
+ tween.stop();
+ }
+ }
+ }
+ this._armature.update(0);
+ },
+
+ /**
+ * Plays animation with index, the other param is the same to play.
+ * @param {Number} animationIndex
+ * @param {Number} durationTo
+ * @param {Number} durationTween
+ * @param {Number} loop
+ * @param {Number} [tweenEasing]
+ * @deprecated since v3.0, please use playWithIndex instead.
+ */
+ playByIndex: function (animationIndex, durationTo, durationTween, loop, tweenEasing) {
+ cc.log("playByIndex is deprecated. Use playWithIndex instead.");
+ this.playWithIndex(animationIndex, durationTo, loop);
+ },
+
+ /**
+ * Plays animation with index, the other param is the same to play.
+ * @param {Number|Array} animationIndex
+ * @param {Number} durationTo
+ * @param {Number} loop
+ */
+ playWithIndex: function (animationIndex, durationTo, loop) {
+ var movName = this._animationData.movementNames;
+ cc.assert((animationIndex > -1) && (animationIndex < movName.length));
+
+ var animationName = movName[animationIndex];
+ this.play(animationName, durationTo, loop);
+ },
+
+ /**
+ * Plays animation with names
+ * @param {Array} movementNames
+ * @param {Number} durationTo
+ * @param {Boolean} loop
+ */
+ playWithNames: function (movementNames, durationTo, loop) {
+ durationTo = (durationTo === undefined) ? -1 : durationTo;
+ loop = (loop === undefined) ? true : loop;
+
+ this._movementListLoop = loop;
+ this._movementListDurationTo = durationTo;
+ this._onMovementList = true;
+ this._movementIndex = 0;
+ if(movementNames instanceof Array)
+ this._movementList = movementNames;
+ else
+ this._movementList.length = 0;
+ this.updateMovementList();
+ },
+
+ /**
+ * Plays animation by indexes
+ * @param {Array} movementIndexes
+ * @param {Number} durationTo
+ * @param {Boolean} loop
+ */
+ playWithIndexes: function (movementIndexes, durationTo, loop) {
+ durationTo = (durationTo === undefined) ? -1 : durationTo;
+ loop = (loop === undefined) ? true : loop;
+
+ this._movementList.length = 0;
+ this._movementListLoop = loop;
+ this._movementListDurationTo = durationTo;
+ this._onMovementList = true;
+ this._movementIndex = 0;
+
+ var movName = this._animationData.movementNames;
+
+ for (var i = 0; i < movementIndexes.length; i++) {
+ var name = movName[movementIndexes[i]];
+ this._movementList.push(name);
+ }
+
+ this.updateMovementList();
+ },
+
+ /**
+ *
+ * Goes to specified frame and plays current movement.
+ * You need first switch to the movement you want to play, then call this function.
+ *
+ * example : playByIndex(0);
+ * gotoAndPlay(0);
+ * playByIndex(1);
+ * gotoAndPlay(0);
+ * gotoAndPlay(15);
+ *
+ * @param {Number} frameIndex
+ */
+ gotoAndPlay: function (frameIndex) {
+ if (!this._movementData || frameIndex < 0 || frameIndex >= this._movementData.duration) {
+ cc.log("Please ensure you have played a movement, and the frameIndex is in the range.");
+ return;
+ }
+
+ var ignoreFrameEvent = this._ignoreFrameEvent;
+ this._ignoreFrameEvent = true;
+ this._isPlaying = true;
+ this._isComplete = this._isPause = false;
+
+ ccs.ProcessBase.prototype.gotoFrame.call(this, frameIndex);
+ this._currentPercent = this._curFrameIndex / (this._movementData.duration - 1);
+ this._currentFrame = this._nextFrameIndex * this._currentPercent;
+
+ var locTweenList = this._tweenList;
+ for (var i = 0; i < locTweenList.length; i++)
+ locTweenList[i].gotoAndPlay(frameIndex);
+ this._armature.update(0);
+ this._ignoreFrameEvent = ignoreFrameEvent;
+ },
+
+ /**
+ * Goes to specified frame and pauses current movement.
+ * @param {Number} frameIndex
+ */
+ gotoAndPause: function (frameIndex) {
+ this.gotoAndPlay(frameIndex);
+ this.pause();
+ },
+
+ /**
+ * Returns the length of armature's movements
+ * @return {Number}
+ */
+ getMovementCount: function () {
+ return this._animationData.getMovementCount();
+ },
+
+ /**
+ * Updates the state of ccs.Tween list, calls frame event's callback and calls movement event's callback.
+ * @param {Number} dt
+ */
+ update: function (dt) {
+ ccs.ProcessBase.prototype.update.call(this, dt);
+
+ var locTweenList = this._tweenList;
+ for (var i = 0; i < locTweenList.length; i++)
+ locTweenList[i].update(dt);
+
+ var frameEvents = this._frameEventQueue, event;
+ while (frameEvents.length > 0) {
+ event = frameEvents.shift();
+ this._ignoreFrameEvent = true;
+ if(this._frameEventCallFunc)
+ this._frameEventCallFunc.call(this._frameEventTarget, event.bone, event.frameEventName, event.originFrameIndex, event.currentFrameIndex);
+ if(this._frameEventListener)
+ this._frameEventListener(event.bone, event.frameEventName, event.originFrameIndex, event.currentFrameIndex);
+ this._ignoreFrameEvent = false;
+ }
+
+ var movementEvents = this._movementEventQueue;
+ while (movementEvents.length > 0) {
+ event = movementEvents.shift();
+ if(this._movementEventCallFunc)
+ this._movementEventCallFunc.call(this._movementEventTarget, event.armature, event.movementType, event.movementID);
+ if (this._movementEventListener)
+ this._movementEventListener(event.armature, event.movementType, event.movementID);
+ }
+ },
+
+ /**
+ * Updates will call this handler, you can handle your logic here
+ */
+ updateHandler: function () { //TODO set it to protected in v3.1
+ var locCurrentPercent = this._currentPercent;
+ if (locCurrentPercent >= 1) {
+ switch (this._loopType) {
+ case ccs.ANIMATION_TYPE_NO_LOOP:
+ this._loopType = ccs.ANIMATION_TYPE_MAX;
+ this._currentFrame = (locCurrentPercent - 1) * this._nextFrameIndex;
+ locCurrentPercent = this._currentFrame / this._durationTween;
+ if (locCurrentPercent < 1.0) {
+ this._nextFrameIndex = this._durationTween;
+ this.movementEvent(this._armature, ccs.MovementEventType.start, this._movementID);
+ break;
+ }
+ break;
+ case ccs.ANIMATION_TYPE_MAX:
+ case ccs.ANIMATION_TYPE_SINGLE_FRAME:
+ locCurrentPercent = 1;
+ this._isComplete = true;
+ this._isPlaying = false;
+
+ this.movementEvent(this._armature, ccs.MovementEventType.complete, this._movementID);
+
+ this.updateMovementList();
+ break;
+ case ccs.ANIMATION_TYPE_TO_LOOP_FRONT:
+ this._loopType = ccs.ANIMATION_TYPE_LOOP_FRONT;
+ locCurrentPercent = ccs.fmodf(locCurrentPercent, 1);
+ this._currentFrame = this._nextFrameIndex === 0 ? 0 : ccs.fmodf(this._currentFrame, this._nextFrameIndex);
+ this._nextFrameIndex = this._durationTween > 0 ? this._durationTween : 1;
+ this.movementEvent(this, ccs.MovementEventType.start, this._movementID);
+ break;
+ default:
+ //locCurrentPercent = ccs.fmodf(locCurrentPercent, 1);
+ this._currentFrame = ccs.fmodf(this._currentFrame, this._nextFrameIndex);
+ this._toIndex = 0;
+ this.movementEvent(this._armature, ccs.MovementEventType.loopComplete, this._movementID);
+ break;
+ }
+ this._currentPercent = locCurrentPercent;
+ }
+ },
+
+ /**
+ * Returns the Id of current movement
+ * @returns {String}
+ */
+ getCurrentMovementID: function () {
+ if (this._isComplete)
+ return "";
+ return this._movementID;
+ },
+
+ /**
+ * Sets movement event callback to animation.
+ * @param {function} callFunc
+ * @param {Object} target
+ */
+ setMovementEventCallFunc: function (callFunc, target) {
+ if(arguments.length === 1){
+ this._movementEventListener = callFunc;
+ }else if(arguments.length === 2){
+ this._movementEventTarget = target;
+ this._movementEventCallFunc = callFunc;
+ }
+ },
+
+ /**
+ * Sets frame event callback to animation.
+ * @param {function} callFunc
+ * @param {Object} target
+ */
+ setFrameEventCallFunc: function (callFunc, target) {
+ if(arguments.length === 1){
+ this._frameEventListener = callFunc;
+ }else if(arguments.length === 2){
+ this._frameEventTarget = target;
+ this._frameEventCallFunc = callFunc;
+ }
+ },
+
+ /**
+ * Sets user object to animation.
+ * @param {Object} userObject
+ */
+ setUserObject: function (userObject) {
+ this._userObject = userObject;
+ },
+
+ /**
+ * Emits a frame event
+ * @param {ccs.Bone} bone
+ * @param {String} frameEventName
+ * @param {Number} originFrameIndex
+ * @param {Number} currentFrameIndex
+ */
+ frameEvent: function (bone, frameEventName, originFrameIndex, currentFrameIndex) {
+ if ((this._frameEventTarget && this._frameEventCallFunc) || this._frameEventListener) {
+ var frameEvent = new ccs.FrameEvent();
+ frameEvent.bone = bone;
+ frameEvent.frameEventName = frameEventName;
+ frameEvent.originFrameIndex = originFrameIndex;
+ frameEvent.currentFrameIndex = currentFrameIndex;
+ this._frameEventQueue.push(frameEvent);
+ }
+ },
+
+ /**
+ * Emits a movement event
+ * @param {ccs.Armature} armature
+ * @param {Number} movementType
+ * @param {String} movementID
+ */
+ movementEvent: function (armature, movementType, movementID) {
+ if ((this._movementEventTarget && this._movementEventCallFunc) || this._movementEventListener) {
+ var event = new ccs.MovementEvent();
+ event.armature = armature;
+ event.movementType = movementType;
+ event.movementID = movementID;
+ this._movementEventQueue.push(event);
+ }
+ },
+
+ /**
+ * Updates movement list.
+ */
+ updateMovementList: function () {
+ if (this._onMovementList) {
+ var movementObj, locMovementList = this._movementList;
+ if (this._movementListLoop) {
+ movementObj = locMovementList[this._movementIndex];
+ this.play(movementObj, movementObj.durationTo, 0);
+ this._movementIndex++;
+ if (this._movementIndex >= locMovementList.length)
+ this._movementIndex = 0;
+ } else {
+ if (this._movementIndex < locMovementList.length) {
+ movementObj = locMovementList[this._movementIndex];
+ this.play(movementObj, movementObj.durationTo, 0);
+ this._movementIndex++;
+ } else
+ this._onMovementList = false;
+ }
+ this._onMovementList = true;
+ }
+ },
+
+ /**
+ * Sets animation data to animation.
+ * @param {ccs.AnimationData} data
+ */
+ setAnimationData: function (data) {
+ if(this._animationData !== data)
+ this._animationData = data;
+ },
+
+ /**
+ * Returns animation data of animation.
+ * @return {ccs.AnimationData}
+ */
+ getAnimationData: function () {
+ return this._animationData;
+ },
+
+ /**
+ * Returns the user object of animation.
+ * @return {Object}
+ */
+ getUserObject: function () {
+ return this._userObject;
+ },
+
+ /**
+ * Determines if the frame event is ignored
+ * @returns {boolean}
+ */
+ isIgnoreFrameEvent: function () {
+ return this._ignoreFrameEvent;
+ }
+});
+
+var _p = ccs.ArmatureAnimation.prototype;
+
+// Extended properties
+/** @expose */
+_p.speedScale;
+cc.defineGetterSetter(_p, "speedScale", _p.getSpeedScale, _p.setSpeedScale);
+/** @expose */
+_p.animationScale;
+cc.defineGetterSetter(_p, "animationScale", _p.getAnimationScale, _p.setAnimationScale);
+
+_p = null;
+
+/**
+ * Allocates and initializes a ArmatureAnimation.
+ * @return {ccs.ArmatureAnimation}
+ * @deprecated since v3.1, please use new construction instead
+ */
+ccs.ArmatureAnimation.create = function (armature) {
+ return new ccs.ArmatureAnimation(armature);
+};
diff --git a/extensions/cocostudio/armature/animation/CCProcessBase.js b/extensions/cocostudio/armature/animation/CCProcessBase.js
new file mode 100644
index 0000000000..a4707d3854
--- /dev/null
+++ b/extensions/cocostudio/armature/animation/CCProcessBase.js
@@ -0,0 +1,365 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+//animation type
+/**
+ * The animation just have one frame
+ * @constant
+ * @type {number}
+ */
+ccs.ANIMATION_TYPE_SINGLE_FRAME = -4;
+/**
+ * The animation isn't loop
+ * @constant
+ * @type {number}
+ */
+ccs.ANIMATION_TYPE_NO_LOOP = -3;
+/**
+ * The animation to loop from front
+ * @constant
+ * @type {number}
+ */
+ccs.ANIMATION_TYPE_TO_LOOP_FRONT = -2;
+/**
+ * The animation to loop from back
+ * @constant
+ * @type {number}
+ */
+ccs.ANIMATION_TYPE_TO_LOOP_BACK = -1;
+/**
+ * The animation loop from front
+ * @constant
+ * @type {number}
+ */
+ccs.ANIMATION_TYPE_LOOP_FRONT = 0;
+/**
+ * The animation loop from back
+ * @constant
+ * @type {number}
+ */
+ccs.ANIMATION_TYPE_LOOP_BACK = 1;
+/**
+ * The animation max
+ * @constant
+ * @type {number}
+ */
+ccs.ANIMATION_TYPE_MAX = 2;
+
+/**
+ * The Base Process class for Cocostudio.
+ * @class
+ * @extends ccs.Class
+ *
+ * @property {Number} currentFrameIndex - <@readonly> The current frame's index
+ * @property {Boolean} paused - <@readonly> Indicate whether the process is paused
+ * @property {Boolean} completed - <@readonly> Indicate whether the process is done
+ * @property {Number} currentPercent - <@readonly> The current percentage of the process
+ * @property {Number} rawDuration - <@readonly> The duration
+ * @property {Number} loop - <@readonly> The number of loop
+ * @property {Number} tweenEasing - <@readonly> The tween easing
+ * @property {Number} animationInterval - The animation internal
+ * @property {Number} processScale - The process scale
+ * @property {Boolean} playing - <@readonly> Indicate whether the process is playing
+ */
+ccs.ProcessBase = ccs.Class.extend(/** @lends ccs.ProcessBase# */{
+ _processScale: 1,
+ _isComplete: true,
+ _isPause: true,
+ _isPlaying: false,
+ _currentPercent: 0.0,
+ _rawDuration: 0,
+ _loopType: 0,
+ _tweenEasing: 0,
+ animationInternal: null,
+ _currentFrame: 0,
+ _durationTween: 0,
+ _nextFrameIndex: 0,
+ _curFrameIndex: null,
+ _isLoopBack: false,
+
+ /**
+ * Constructor of ccs.ProcessBase
+ */
+ ctor: function () {
+ this._processScale = 1;
+ this._isComplete = true;
+ this._isPause = true;
+ this._isPlaying = false;
+ this._currentFrame = 0;
+ this._currentPercent = 0.0;
+ this._durationTween = 0;
+ this._rawDuration = 0;
+ this._loopType = ccs.ANIMATION_TYPE_LOOP_BACK;
+ this._tweenEasing = ccs.TweenType.LINEAR;
+ this.animationInternal = 1 / 60;
+ this._curFrameIndex = 0;
+ this._durationTween = 0;
+ this._isLoopBack = false;
+ },
+
+ /**
+ * Pauses the Process
+ */
+ pause: function () {
+ this._isPause = true;
+ this._isPlaying = false;
+ },
+
+ /**
+ * Resumes the Process
+ */
+ resume: function () {
+ this._isPause = false;
+ this._isPlaying = true;
+ },
+
+ /**
+ * Stops the Process
+ */
+ stop: function () {
+ this._isComplete = true;
+ this._isPlaying = false;
+ },
+
+ /**
+ * Plays animation by animation name.
+ * @param {Number} durationTo The frames between two animation changing-over.
+ * It's meaning is changing to this animation need how many frames
+ * -1 : use the value from MovementData get from flash design panel
+ * @param {Number} durationTween The frame count you want to play in the game.
+ * if _durationTween is 80, then the animation will played 80 frames in a loop
+ * -1 : use the value from MovementData get from flash design panel
+ * @param {Number} loop Whether the animation is loop
+ * loop < 0 : use the value from MovementData get from flash design panel
+ * loop = 0 : this animation is not loop
+ * loop > 0 : this animation is loop
+ * @param {Number} tweenEasing Tween easing is used for calculate easing effect
+ * TWEEN_EASING_MAX : use the value from MovementData get from flash design panel
+ * -1 : fade out
+ * 0 : line
+ * 1 : fade in
+ * 2 : fade in and out
+ */
+ play: function (durationTo, durationTween, loop, tweenEasing) {
+ this._isComplete = false;
+ this._isPause = false;
+ this._isPlaying = true;
+ this._currentFrame = 0;
+ /*
+ * Set m_iTotalFrames to durationTo, it is used for change tween between two animation.
+ * When changing end, m_iTotalFrames will be set to _durationTween
+ */
+ this._nextFrameIndex = durationTo;
+ this._tweenEasing = tweenEasing;
+ },
+
+ /**
+ * Update process' state.
+ * @param {Number} dt
+ */
+ update: function (dt) {
+ if (this._isComplete || this._isPause)
+ return;
+
+ /*
+ * Fileter the m_iDuration <=0 and dt >1
+ * If dt>1, generally speaking the reason is the device is stuck.
+ */
+ if (this._rawDuration <= 0 || dt > 1)
+ return;
+
+ var locNextFrameIndex = this._nextFrameIndex === undefined ? 0 : this._nextFrameIndex;
+ var locCurrentFrame = this._currentFrame;
+ if (locNextFrameIndex <= 0) {
+ this._currentPercent = 1;
+ locCurrentFrame = 0;
+ } else {
+ /*
+ * update currentFrame, every update add the frame passed.
+ * dt/this.animationInternal determine it is not a frame animation. If frame speed changed, it will not make our
+ * animation speed slower or quicker.
+ */
+ locCurrentFrame += this._processScale * (dt / this.animationInternal);
+ this._currentPercent = locCurrentFrame / locNextFrameIndex;
+
+ /*
+ * if currentFrame is bigger or equal than this._nextFrameIndex, then reduce it util currentFrame is
+ * smaller than this._nextFrameIndex
+ */
+ locCurrentFrame = ccs.fmodf(locCurrentFrame, locNextFrameIndex);
+ }
+ this._currentFrame = locCurrentFrame;
+ this.updateHandler();
+ },
+
+ /**
+ * Goes to specified frame by frameIndex.
+ * @param {Number} frameIndex
+ */
+ gotoFrame: function (frameIndex) {
+ var locLoopType = this._loopType;
+ if (locLoopType === ccs.ANIMATION_TYPE_NO_LOOP)
+ locLoopType = ccs.ANIMATION_TYPE_MAX;
+ else if (locLoopType === ccs.ANIMATION_TYPE_TO_LOOP_FRONT)
+ locLoopType = ccs.ANIMATION_TYPE_LOOP_FRONT;
+ this._loopType = locLoopType;
+ this._curFrameIndex = frameIndex;
+ this._nextFrameIndex = this._durationTween;
+ },
+
+ /**
+ * Returns the index of current frame.
+ * @return {Number}
+ */
+ getCurrentFrameIndex: function () {
+ this._curFrameIndex = (this._rawDuration - 1) * this._currentPercent;
+ return this._curFrameIndex;
+ },
+
+ /**
+ * Updates will call this handler, you can handle your logic here
+ */
+ updateHandler: function () {
+ //override
+ },
+
+ /**
+ * Returns whether the animation is pause
+ * @returns {boolean}
+ */
+ isPause: function () {
+ return this._isPause;
+ },
+
+ /**
+ * Returns whether the animation is complete
+ * @returns {boolean}
+ */
+ isComplete: function () {
+ return this._isComplete;
+ },
+
+ /**
+ * Returns current percent of ccs.ProcessBase
+ * @returns {number}
+ */
+ getCurrentPercent: function () {
+ return this._currentPercent;
+ },
+
+ /**
+ * Returns the raw duration of ccs.ProcessBase
+ * @returns {number}
+ */
+ getRawDuration: function () {
+ return this._rawDuration;
+ },
+
+ /**
+ * Returns loop type of ccs.ProcessBase
+ * @returns {number}
+ */
+ getLoop: function () {
+ return this._loopType;
+ },
+
+ /**
+ * Returns tween easing of ccs.ProcessBase
+ * @returns {number}
+ */
+ getTweenEasing: function () {
+ return this._tweenEasing;
+ },
+
+ /**
+ * Returns animation interval of ccs.ProcessBase
+ * @returns {number}
+ */
+ getAnimationInternal: function () { //TODO rename getAnimationInternal to getAnimationInterval in v3.1
+ return this.animationInternal;
+ },
+
+ /**
+ * Sets animation interval to ccs.ProcessBase.
+ * @param animationInternal
+ */
+ setAnimationInternal: function (animationInternal) {
+ this.animationInternal = animationInternal;
+ },
+
+ /**
+ * Returns process scale
+ * @returns {number}
+ */
+ getProcessScale: function () {
+ return this._processScale;
+ },
+
+ /**
+ * Sets process scale
+ * @param processScale
+ */
+ setProcessScale: function (processScale) {
+ this._processScale = processScale;
+ },
+
+ /**
+ * Returns whether the animation is playing
+ * @returns {boolean}
+ */
+ isPlaying: function () {
+ return this._isPlaying;
+ }
+});
+
+var _p = ccs.ProcessBase.prototype;
+
+// Extended properties
+/** @expose */
+_p.currentFrameIndex;
+cc.defineGetterSetter(_p, "currentFrameIndex", _p.getCurrentFrameIndex);
+/** @expose */
+_p.paused;
+cc.defineGetterSetter(_p, "paused", _p.isPause);
+/** @expose */
+_p.completed;
+cc.defineGetterSetter(_p, "completed", _p.isComplete);
+/** @expose */
+_p.currentPercent;
+cc.defineGetterSetter(_p, "currentPercent", _p.getCurrentPercent);
+/** @expose */
+_p.rawDuration;
+cc.defineGetterSetter(_p, "rawDuration", _p.getRawDuration);
+/** @expose */
+_p.loop;
+cc.defineGetterSetter(_p, "loop", _p.getLoop);
+/** @expose */
+_p.tweenEasing;
+cc.defineGetterSetter(_p, "tweenEasing", _p.getTweenEasing);
+/** @expose */
+_p.playing;
+cc.defineGetterSetter(_p, "playing", _p.isPlaying);
+
+_p = null;
diff --git a/extensions/cocostudio/armature/animation/CCTween.js b/extensions/cocostudio/armature/animation/CCTween.js
new file mode 100644
index 0000000000..5706d1d595
--- /dev/null
+++ b/extensions/cocostudio/armature/animation/CCTween.js
@@ -0,0 +1,448 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+/**
+ * The tween class for Armature.
+ * @class
+ * @extends ccs.ProcessBase
+ *
+ * @param {ccs.Bone} The bone to be animated
+ *
+ * @property {ccs.ArmatureAnimation} animation - The animation
+ */
+ccs.Tween = ccs.ProcessBase.extend(/** @lends ccs.Tween# */{
+ _tweenData:null,
+ _to:null,
+ _from:null,
+ _between:null,
+ _movementBoneData:null,
+ _bone:null,
+ _frameTweenEasing:0,
+ _betweenDuration:0,
+ _totalDuration:0,
+ _toIndex:0,
+ _fromIndex:0,
+ _animation:null,
+ _passLastFrame:false,
+
+ ctor:function (bone) {
+ ccs.ProcessBase.prototype.ctor.call(this);
+ this._frameTweenEasing = ccs.TweenType.LINEAR;
+
+ ccs.Tween.prototype.init.call(this, bone);
+ },
+
+ /**
+ * initializes a ccs.Tween with a CCBone
+ * @param {ccs.Bone} bone
+ * @return {Boolean}
+ */
+ init:function (bone) {
+ this._from = new ccs.FrameData();
+ this._between = new ccs.FrameData();
+
+ this._bone = bone;
+ this._tweenData = this._bone.getTweenData();
+ this._tweenData.displayIndex = -1;
+
+ this._animation = (this._bone !== null && this._bone.getArmature() !== null) ?
+ this._bone.getArmature().getAnimation() :
+ null;
+ return true;
+ },
+
+ /**
+ * Plays the tween.
+ * @param {ccs.MovementBoneData} movementBoneData
+ * @param {Number} durationTo
+ * @param {Number} durationTween
+ * @param {Boolean} loop
+ * @param {ccs.TweenType} tweenEasing
+ */
+ play:function (movementBoneData, durationTo, durationTween, loop, tweenEasing) {
+ ccs.ProcessBase.prototype.play.call(this, durationTo, durationTween, loop, tweenEasing);
+ this._loopType = (loop)?ccs.ANIMATION_TYPE_TO_LOOP_FRONT:ccs.ANIMATION_TYPE_NO_LOOP;
+
+ this._totalDuration = 0;
+ this._betweenDuration = 0;
+ this._fromIndex = this._toIndex = 0;
+
+ var difMovement = movementBoneData !== this._movementBoneData;
+
+ this.setMovementBoneData(movementBoneData);
+ this._rawDuration = this._movementBoneData.duration;
+
+ var nextKeyFrame = this._movementBoneData.getFrameData(0);
+ this._tweenData.displayIndex = nextKeyFrame.displayIndex;
+
+ if (this._bone.getArmature().getArmatureData().dataVersion >= ccs.CONST_VERSION_COMBINED) {
+ ccs.TransformHelp.nodeSub(this._tweenData, this._bone.getBoneData());
+ this._tweenData.scaleX += 1;
+ this._tweenData.scaleY += 1;
+ }
+
+ if (this._rawDuration === 0) {
+ this._loopType = ccs.ANIMATION_TYPE_SINGLE_FRAME;
+ if (durationTo === 0)
+ this.setBetween(nextKeyFrame, nextKeyFrame);
+ else
+ this.setBetween(this._tweenData, nextKeyFrame);
+ this._frameTweenEasing = ccs.TweenType.LINEAR;
+ }
+ else if (this._movementBoneData.frameList.length > 1) {
+ this._durationTween = durationTween * this._movementBoneData.scale;
+ if (loop && this._movementBoneData.delay !== 0)
+ this.setBetween(this._tweenData, this.tweenNodeTo(this.updateFrameData(1 - this._movementBoneData.delay), this._between));
+ else {
+ if (!difMovement || durationTo === 0)
+ this.setBetween(nextKeyFrame, nextKeyFrame);
+ else
+ this.setBetween(this._tweenData, nextKeyFrame);
+ }
+ }
+ this.tweenNodeTo(0);
+ },
+
+ /**
+ * Goes to specified frame and plays frame.
+ * @param {Number} frameIndex
+ */
+ gotoAndPlay: function (frameIndex) {
+ ccs.ProcessBase.prototype.gotoFrame.call(this, frameIndex);
+
+ this._totalDuration = 0;
+ this._betweenDuration = 0;
+ this._fromIndex = this._toIndex = 0;
+
+ this._isPlaying = true;
+ this._isComplete = this._isPause = false;
+
+ this._currentPercent = this._curFrameIndex / (this._rawDuration-1);
+ this._currentFrame = this._nextFrameIndex * this._currentPercent;
+ },
+
+ /**
+ * Goes to specified frame and pauses frame.
+ * @param {Number} frameIndex
+ */
+ gotoAndPause: function (frameIndex) {
+ this.gotoAndPlay(frameIndex);
+ this.pause();
+ },
+
+ /**
+ * update will call this handler, you can handle your logic here
+ */
+ updateHandler:function () {
+ var locCurrentPercent = this._currentPercent == null ? 1 : this._currentPercent;
+ var locLoopType = this._loopType;
+ if (locCurrentPercent >= 1) {
+ switch (locLoopType) {
+ case ccs.ANIMATION_TYPE_SINGLE_FRAME:
+ locCurrentPercent = 1;
+ this._isComplete = true;
+ this._isPlaying = false;
+ break;
+ case ccs.ANIMATION_TYPE_NO_LOOP:
+ locLoopType = ccs.ANIMATION_TYPE_MAX;
+ if (this._durationTween <= 0)
+ locCurrentPercent = 1;
+ else
+ locCurrentPercent = (locCurrentPercent - 1) * this._nextFrameIndex / this._durationTween;
+ if (locCurrentPercent >= 1) {
+ locCurrentPercent = 1;
+ this._isComplete = true;
+ this._isPlaying = false;
+ break;
+ } else {
+ this._nextFrameIndex = this._durationTween;
+ this._currentFrame = locCurrentPercent * this._nextFrameIndex;
+ this._totalDuration = 0;
+ this._betweenDuration = 0;
+ this._fromIndex = this._toIndex = 0;
+ break;
+ }
+ case ccs.ANIMATION_TYPE_TO_LOOP_FRONT:
+ locLoopType = ccs.ANIMATION_TYPE_LOOP_FRONT;
+ this._nextFrameIndex = this._durationTween > 0 ? this._durationTween : 1;
+
+ if (this._movementBoneData.delay !== 0) {
+ this._currentFrame = (1 - this._movementBoneData.delay) * this._nextFrameIndex;
+ locCurrentPercent = this._currentFrame / this._nextFrameIndex;
+ } else {
+ locCurrentPercent = 0;
+ this._currentFrame = 0;
+ }
+
+ this._totalDuration = 0;
+ this._betweenDuration = 0;
+ this._fromIndex = this._toIndex = 0;
+ break;
+ case ccs.ANIMATION_TYPE_MAX:
+ locCurrentPercent = 1;
+ this._isComplete = true;
+ this._isPlaying = false;
+ break;
+ default:
+ this._currentFrame = ccs.fmodf(this._currentFrame, this._nextFrameIndex);
+ break;
+ }
+ }
+
+ if (locCurrentPercent < 1 && locLoopType < ccs.ANIMATION_TYPE_TO_LOOP_BACK)
+ locCurrentPercent = Math.sin(locCurrentPercent * cc.PI / 2);
+
+ this._currentPercent = locCurrentPercent;
+ this._loopType = locLoopType;
+
+ if (locLoopType > ccs.ANIMATION_TYPE_TO_LOOP_BACK)
+ locCurrentPercent = this.updateFrameData(locCurrentPercent);
+ if (this._frameTweenEasing !== ccs.TweenType.TWEEN_EASING_MAX)
+ this.tweenNodeTo(locCurrentPercent);
+ },
+
+ /**
+ * Calculate the between value of _from and _to, and give it to between frame data
+ * @param {ccs.FrameData} from
+ * @param {ccs.FrameData} to
+ * @param {Boolean} [limit=true]
+ */
+ setBetween:function (from, to, limit) { //TODO set tweenColorTo to protected in v3.1
+ if(limit === undefined)
+ limit = true;
+ do {
+ if (from.displayIndex < 0 && to.displayIndex >= 0) {
+ this._from.copy(to);
+ this._between.subtract(to, to, limit);
+ break;
+ }
+ if (to.displayIndex < 0 && from.displayIndex >= 0) {
+ this._from.copy(from);
+ this._between.subtract(to, to, limit);
+ break;
+ }
+ this._from.copy(from);
+ this._between.subtract(from, to, limit);
+ } while (0);
+ if (!from.isTween){
+ this._tweenData.copy(from);
+ this._tweenData.isTween = true;
+ }
+ this.arriveKeyFrame(from);
+ },
+
+ /**
+ * Update display index and process the key frame event when arrived a key frame
+ * @param {ccs.FrameData} keyFrameData
+ */
+ arriveKeyFrame:function (keyFrameData) { //TODO set tweenColorTo to protected in v3.1
+ if (keyFrameData) {
+ var locBone = this._bone;
+ var displayManager = locBone.getDisplayManager();
+
+ //! Change bone's display
+ var displayIndex = keyFrameData.displayIndex;
+
+ if (!displayManager.getForceChangeDisplay())
+ displayManager.changeDisplayWithIndex(displayIndex, false);
+
+ //! Update bone zorder, bone's zorder is determined by frame zorder and bone zorder
+ this._tweenData.zOrder = keyFrameData.zOrder;
+ locBone.updateZOrder();
+
+ //! Update blend type
+ this._bone.setBlendFunc(keyFrameData.blendFunc);
+
+ var childAramture = locBone.getChildArmature();
+ if (childAramture) {
+ if (keyFrameData.movement !== "")
+ childAramture.getAnimation().play(keyFrameData.movement);
+ }
+ }
+ },
+
+ /**
+ * According to the percent to calculate current CCFrameData with tween effect
+ * @param {Number} percent
+ * @param {ccs.FrameData} [node]
+ * @return {ccs.FrameData}
+ */
+ tweenNodeTo:function (percent, node) { //TODO set tweenColorTo to protected in v3.1
+ if (!node)
+ node = this._tweenData;
+
+ var locFrom = this._from;
+ var locBetween = this._between;
+ if (!locFrom.isTween)
+ percent = 0;
+ node.x = locFrom.x + percent * locBetween.x;
+ node.y = locFrom.y + percent * locBetween.y;
+ node.scaleX = locFrom.scaleX + percent * locBetween.scaleX;
+ node.scaleY = locFrom.scaleY + percent * locBetween.scaleY;
+ node.skewX = locFrom.skewX + percent * locBetween.skewX;
+ node.skewY = locFrom.skewY + percent * locBetween.skewY;
+
+ this._bone.setTransformDirty(true);
+ if (node && locBetween.isUseColorInfo)
+ this.tweenColorTo(percent, node);
+
+ return node;
+ },
+
+ /**
+ * According to the percent to calculate current color with tween effect
+ * @param {Number} percent
+ * @param {ccs.FrameData} node
+ */
+ tweenColorTo:function(percent,node){ //TODO set tweenColorTo to protected in v3.1
+ var locFrom = this._from;
+ var locBetween = this._between;
+ node.a = locFrom.a + percent * locBetween.a;
+ node.r = locFrom.r + percent * locBetween.r;
+ node.g = locFrom.g + percent * locBetween.g;
+ node.b = locFrom.b + percent * locBetween.b;
+ this._bone.updateColor();
+ },
+
+ /**
+ * Calculate which frame arrived, and if current frame have event, then call the event listener
+ * @param {Number} currentPercent
+ * @return {Number}
+ */
+ updateFrameData:function (currentPercent) { //TODO set tweenColorTo to protected in v3.1
+ if (currentPercent > 1 && this._movementBoneData.delay !== 0)
+ currentPercent = ccs.fmodf(currentPercent,1);
+
+ var playedTime = (this._rawDuration-1) * currentPercent;
+
+ var from, to;
+ var locTotalDuration = this._totalDuration,locBetweenDuration = this._betweenDuration, locToIndex = this._toIndex;
+ // if play to current frame's front or back, then find current frame again
+ if (playedTime < locTotalDuration || playedTime >= locTotalDuration + locBetweenDuration) {
+ /*
+ * get frame length, if this._toIndex >= _length, then set this._toIndex to 0, start anew.
+ * this._toIndex is next index will play
+ */
+ var frames = this._movementBoneData.frameList;
+ var length = frames.length;
+
+ if (playedTime < frames[0].frameID){
+ from = to = frames[0];
+ this.setBetween(from, to);
+ return this._currentPercent;
+ }
+
+ if (playedTime >= frames[length - 1].frameID) {
+ // If _passLastFrame is true and playedTime >= frames[length - 1]->frameID, then do not need to go on.
+ if (this._passLastFrame) {
+ from = to = frames[length - 1];
+ this.setBetween(from, to);
+ return this._currentPercent;
+ }
+ this._passLastFrame = true;
+ } else
+ this._passLastFrame = false;
+
+ do {
+ this._fromIndex = locToIndex;
+ from = frames[this._fromIndex];
+ locTotalDuration = from.frameID;
+
+ locToIndex = this._fromIndex + 1;
+ if (locToIndex >= length)
+ locToIndex = 0;
+ to = frames[locToIndex];
+
+ //! Guaranteed to trigger frame event
+ if(from.strEvent && !this._animation.isIgnoreFrameEvent())
+ this._animation.frameEvent(this._bone, from.strEvent,from.frameID, playedTime);
+
+ if (playedTime === from.frameID|| (this._passLastFrame && this._fromIndex === length-1))
+ break;
+ } while (playedTime < from.frameID || playedTime >= to.frameID);
+
+ locBetweenDuration = to.frameID - from.frameID;
+ this._frameTweenEasing = from.tweenEasing;
+ this.setBetween(from, to, false);
+
+ this._totalDuration = locTotalDuration;
+ this._betweenDuration = locBetweenDuration;
+ this._toIndex = locToIndex;
+ }
+ currentPercent = locBetweenDuration === 0 ? 0 : (playedTime - this._totalDuration) / this._betweenDuration;
+
+ /*
+ * if frame tween easing equal to TWEEN_EASING_MAX, then it will not do tween.
+ */
+ var tweenType = (this._frameTweenEasing !== ccs.TweenType.LINEAR) ? this._frameTweenEasing : this._tweenEasing;
+ if (tweenType !== ccs.TweenType.TWEEN_EASING_MAX && tweenType !== ccs.TweenType.LINEAR && !this._passLastFrame) {
+ currentPercent = ccs.TweenFunction.tweenTo(currentPercent, tweenType, this._from.easingParams);
+ }
+ return currentPercent;
+ },
+
+ /**
+ * Sets Armature animation to ccs.Tween.
+ * @param {ccs.ArmatureAnimation} animation
+ */
+ setAnimation:function (animation) {
+ this._animation = animation;
+ },
+
+ /**
+ * Returns Armature animation of ccs.Tween.
+ * @return {ccs.ArmatureAnimation}
+ */
+ getAnimation:function () {
+ return this._animation;
+ },
+
+ /**
+ * Sets movement bone data to ccs.Tween.
+ * @param data
+ */
+ setMovementBoneData: function(data){
+ this._movementBoneData = data;
+ }
+});
+
+var _p = ccs.Tween.prototype;
+
+// Extended properties
+/** @expose */
+_p.animation;
+cc.defineGetterSetter(_p, "animation", _p.getAnimation, _p.setAnimation);
+
+_p = null;
+
+/**
+ * Allocates and initializes a ArmatureAnimation.
+ * @param {ccs.Bone} bone
+ * @return {ccs.Tween}
+ * @deprecated since v3.1, please use new construction instead
+ */
+ccs.Tween.create = function (bone) {
+ return new ccs.Tween(bone);
+};
diff --git a/extensions/cocostudio/armature/datas/CCDatas.js b/extensions/cocostudio/armature/datas/CCDatas.js
new file mode 100644
index 0000000000..79c0de812a
--- /dev/null
+++ b/extensions/cocostudio/armature/datas/CCDatas.js
@@ -0,0 +1,807 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+//BlendType
+/**
+ * The value of the blend type of normal
+ * @constant
+ * @type Number
+ */
+ccs.BLEND_TYPE_NORMAL = 0;
+
+/**
+ * The value of the blend type of layer
+ * @constant
+ * @type Number
+ */
+ccs.BLEND_TYPE_LAYER = 1;
+
+/**
+ * The value of the blend type of darken
+ * @constant
+ * @type Number
+ */
+ccs.BLEND_TYPE_DARKEN = 2;
+
+/**
+ * The value of the blend type of multiply
+ * @constant
+ * @type Number
+ */
+ccs.BLEND_TYPE_MULTIPLY = 3;
+
+/**
+ * The value of the blend type of lighten
+ * @constant
+ * @type Number
+ */
+ccs.BLEND_TYPE_LIGHTEN = 4;
+
+/**
+ * The value of the blend type of screen
+ * @constant
+ * @type Number
+ */
+ccs.BLEND_TYPE_SCREEN = 5;
+
+/**
+ * The value of the blend type of overlay
+ * @constant
+ * @type Number
+ */
+ccs.BLEND_TYPE_OVERLAY = 6;
+
+/**
+ * The value of the blend type of highlight
+ * @constant
+ * @type Number
+ */
+ccs.BLEND_TYPE_HIGHLIGHT = 7;
+
+/**
+ * The value of the blend type of add
+ * @constant
+ * @type Number
+ */
+ccs.BLEND_TYPE_ADD = 8;
+
+/**
+ * The value of the blend type of subtract
+ * @constant
+ * @type Number
+ */
+ccs.BLEND_TYPE_SUBTRACT = 9;
+
+/**
+ * The value of the blend type of difference
+ * @constant
+ * @type Number
+ */
+ccs.BLEND_TYPE_DIFFERENCE = 10;
+
+/**
+ * The value of the blend type of invert
+ * @constant
+ * @type Number
+ */
+ccs.BLEND_TYPE_INVERT = 11;
+
+/**
+ * The value of the blend type of alpha
+ * @constant
+ * @type Number
+ */
+ccs.BLEND_TYPE_ALPHA = 12;
+
+/**
+ * The value of the blend type of erase
+ * @constant
+ * @type Number
+ */
+ccs.BLEND_TYPE_ERASE = 13;
+
+//DisplayType
+/**
+ * The Sprite flag of display render type.
+ * @constant
+ * @type Number
+ */
+ccs.DISPLAY_TYPE_SPRITE = 0;
+/**
+ * The Armature flag of display render type.
+ * @constant
+ * @type Number
+ */
+ccs.DISPLAY_TYPE_ARMATURE = 1;
+/**
+ * The Particle flag of display render type.
+ * @constant
+ * @type Number
+ */
+ccs.DISPLAY_TYPE_PARTICLE = 2;
+ccs.DISPLAY_TYPE_MAX = 3;
+
+/**
+ *
+ * The base data class for Armature. it contains position, zOrder, skew, scale, color datas.
+ * x y skewX skewY scaleX scaleY used to calculate transform matrix
+ * skewX, skewY can have rotation effect
+ * To get more matrix information, you can have a look at this pape : http://www.senocular.com/flash/tutorials/transformmatrix/
+ *
+ * @class
+ * @extends ccs.Class
+ *
+ * @property {Number} x - x
+ * @property {Number} y - y
+ * @property {Number} zOrder - zOrder
+ * @property {Number} skewX - skewX
+ * @property {Number} skewY - skewY
+ * @property {Number} scaleX - scaleX
+ * @property {Number} scaleY - scaleY
+ * @property {Number} tweenRotate - tween Rotate
+ * @property {Number} isUseColorInfo - is Use Color Info
+ * @property {Number} r - r of color
+ * @property {Number} g - g of color
+ * @property {Number} b - b of color
+ * @property {Number} a - a of color
+ */
+ccs.BaseData = ccs.Class.extend(/** @lends ccs.BaseData# */{
+ x:0,
+ y:0,
+ zOrder:0,
+ skewX:0,
+ skewY:0,
+ scaleX:1,
+ scaleY:1,
+ tweenRotate:0, //! SkewX, SkewY, and TweenRotate effect the rotation
+ isUseColorInfo:false, //! Whether or not this frame have the color changed Info
+ r:255,
+ g:255,
+ b:255,
+ a:255,
+
+ /**
+ * Construction of ccs.BaseData
+ */
+ ctor:function () {
+ this.x = 0;
+ this.y = 0;
+ this.zOrder = 0;
+ this.skewX = 0;
+ this.skewY = 0;
+ this.scaleX = 1;
+ this.scaleY = 1;
+ this.tweenRotate = 0;
+ this.isUseColorInfo = false;
+ this.r = 255;
+ this.g = 255;
+ this.b = 255;
+ this.a = 255;
+ },
+
+ /**
+ * Copy data from node
+ * @function
+ * @param {ccs.BaseData} node
+ */
+ copy:function (node) {
+ this.x = node.x;
+ this.y = node.y;
+ this.zOrder = node.zOrder;
+
+ this.scaleX = node.scaleX;
+ this.scaleY = node.scaleY;
+ this.skewX = node.skewX;
+ this.skewY = node.skewY;
+
+ this.tweenRotate = node.tweenRotate;
+
+ this.isUseColorInfo = node.isUseColorInfo;
+ this.r = node.r;
+ this.g = node.g;
+ this.b = node.b;
+ this.a = node.a;
+ },
+
+ /**
+ * Sets color to base data.
+ * @function
+ * @param {cc.Color} color
+ */
+ setColor:function(color){
+ this.r = color.r;
+ this.g = color.g;
+ this.b = color.b;
+ this.a = color.a;
+ },
+
+ /**
+ * Returns the color of ccs.BaseData
+ * @function
+ * @returns {cc.Color}
+ */
+ getColor:function(){
+ return cc.color(this.r, this.g, this.b, this.a);
+ },
+
+ /**
+ * Calculate two baseData's between value(to - from) and set to self
+ * @function
+ * @param {ccs.BaseData} from
+ * @param {ccs.BaseData} to
+ * @param {Boolean} limit
+ */
+ subtract:function (from, to, limit) {
+ this.x = to.x - from.x;
+ this.y = to.y - from.y;
+ this.scaleX = to.scaleX - from.scaleX;
+ this.scaleY = to.scaleY - from.scaleY;
+ this.skewX = to.skewX - from.skewX;
+ this.skewY = to.skewY - from.skewY;
+
+ if (this.isUseColorInfo || from.isUseColorInfo || to.isUseColorInfo) {
+ this.a = to.a - from.a;
+ this.r = to.r - from.r;
+ this.g = to.g - from.g;
+ this.b = to.b - from.b;
+ this.isUseColorInfo = true;
+ } else {
+ this.a = this.r = this.g = this.b = 0;
+ this.isUseColorInfo = false;
+ }
+
+ if (limit) {
+ if (this.skewX > ccs.M_PI)
+ this.skewX -= ccs.DOUBLE_PI;
+ if (this.skewX < -ccs.M_PI)
+ this.skewX += ccs.DOUBLE_PI;
+ if (this.skewY > ccs.M_PI)
+ this.skewY -= ccs.DOUBLE_PI;
+ if (this.skewY < -ccs.M_PI)
+ this.skewY += ccs.DOUBLE_PI;
+ }
+
+ if (to.tweenRotate) {
+ this.skewX += to.tweenRotate * ccs.PI * 2;
+ this.skewY -= to.tweenRotate * ccs.PI * 2;
+ }
+ }
+});
+
+/**
+ * The class use for save display data.
+ * @class
+ * @extends ccs.Class
+ *
+ * @property {Number} displayType - the display type
+ * @property {String} displayName - the display name
+ */
+ccs.DisplayData = ccs.Class.extend(/** @lends ccs.DisplayData# */{
+ displayType: ccs.DISPLAY_TYPE_MAX,
+ displayName: "",
+
+ /**
+ * Construction of ccs.DisplayData
+ */
+ ctor: function () {
+ this.displayType = ccs.DISPLAY_TYPE_MAX;
+ },
+ /**
+ * Changes display name to texture type
+ * @function
+ * @param {String} displayName
+ * @returns {String}
+ */
+ changeDisplayToTexture:function (displayName) {
+ // remove .xxx
+ var textureName = displayName;
+ var startPos = textureName.lastIndexOf(".");
+
+ if (startPos !== -1)
+ textureName = textureName.substring(0, startPos);
+ return textureName;
+ },
+
+ /**
+ * copy data
+ * @function
+ * @param {ccs.DisplayData} displayData
+ */
+ copy:function (displayData) {
+ this.displayName = displayData.displayName;
+ this.displayType = displayData.displayType;
+ }
+});
+
+/**
+ * The sprite display data class.
+ * @class
+ * @extends ccs.DisplayData
+ *
+ * @property {ccs.BaseData} skinData - the skin data
+ */
+ccs.SpriteDisplayData = ccs.DisplayData.extend(/** @lends ccs.SpriteDisplayData# */{
+ skinData:null,
+
+ /**
+ * Construction of ccs.SpriteDisplayData
+ */
+ ctor:function () {
+ this.skinData = new ccs.BaseData();
+ this.displayType = ccs.DISPLAY_TYPE_SPRITE;
+ },
+ /**
+ * copy data
+ * @function
+ * @param {ccs.SpriteDisplayData} displayData
+ */
+ copy:function (displayData) {
+ ccs.DisplayData.prototype.copy.call(this,displayData);
+ this.skinData = displayData.skinData;
+ }
+});
+
+/**
+ * The armature display data class
+ * @class ccs.ArmatureDisplayData
+ * @extends ccs.DisplayData
+ */
+ccs.ArmatureDisplayData = ccs.DisplayData.extend(/** @lends ccs.ArmatureDisplayData# */{
+ /**
+ * Construction of ccs.ArmatureDisplayData
+ */
+ ctor:function () {
+ this.displayName = "";
+ this.displayType = ccs.DISPLAY_TYPE_ARMATURE;
+ }
+});
+
+/**
+ * The particle display data class.
+ * @class ccs.ParticleDisplayData
+ * @extends ccs.DisplayData
+ */
+ccs.ParticleDisplayData = ccs.DisplayData.extend(/** @lends ccs.ParticleDisplayData# */{
+ /**
+ * Construction of ccs.ParticleDisplayData
+ */
+ ctor:function () {
+ this.displayType = ccs.DISPLAY_TYPE_PARTICLE;
+ }
+});
+
+/**
+ *
+ * BoneData used to init a Bone.
+ * BoneData keeps a DisplayData list, a Bone can have many display to change.
+ * The display information saved in the DisplayData
+ *
+ * @class ccs.BoneData
+ * @extends ccs.BaseData
+ *
+ * @property {Array} displayDataList - the display data list
+ * @property {String} name - the name of Bone
+ * @property {String} parentName - the parent name of bone
+ * @property {cc.AffineTransform} boneDataTransform - the bone transform data
+ */
+ccs.BoneData = ccs.BaseData.extend(/** @lends ccs.BoneData# */{
+ displayDataList: null,
+ name: "",
+ parentName: "",
+ boneDataTransform: null,
+
+ /**
+ * Construction of ccs.BoneData
+ */
+ ctor: function () {
+ this.displayDataList = [];
+ this.name = "";
+ this.parentName = "";
+ this.boneDataTransform = null;
+ },
+
+ /**
+ * Initializes a ccs.BoneData
+ * @returns {boolean}
+ */
+ init: function () {
+ this.displayDataList.length = 0;
+ return true;
+ },
+ /**
+ * Adds display data to list
+ * @function
+ * @param {ccs.DisplayData} displayData
+ */
+ addDisplayData:function (displayData) {
+ this.displayDataList.push(displayData);
+ },
+
+ /**
+ * Returns display data with index.
+ * @function
+ * @param {Number} index
+ * @returns {ccs.DisplayData}
+ */
+ getDisplayData:function (index) {
+ return this.displayDataList[index];
+ }
+});
+
+/**
+ *
+ * ArmatureData saved the Armature name and BoneData needed for the CCBones in this Armature
+ * When we create a Armature, we need to get each Bone's BoneData as it's init information.
+ * So we can get a BoneData from the Dictionary saved in the ArmatureData.
+ *
+ * @class ccs.ArmatureData
+ * @extends ccs.Class
+ *
+ * @property {Object} boneDataDic - the bone data dictionary
+ * @property {String} name - the name of armature data
+ * @property {Number} dataVersion - the data version of armature data
+ */
+ccs.ArmatureData = ccs.Class.extend(/** @lends ccs.ArmatureData# */{
+ boneDataDic:null,
+ name:"",
+ dataVersion:0.1,
+
+ /**
+ * Construction of ccs.ArmatureData
+ */
+ ctor:function () {
+ this.boneDataDic = {};
+ this.name = "";
+ this.dataVersion = 0.1;
+ },
+
+ /**
+ * Initializes a ccs.ArmatureData
+ * @returns {boolean}
+ */
+ init:function () {
+ return true;
+ },
+
+ /**
+ * Adds bone data to dictionary
+ * @param {ccs.BoneData} boneData
+ */
+ addBoneData:function (boneData) {
+ this.boneDataDic[boneData.name] = boneData;
+ },
+
+ /**
+ * Gets bone data dictionary
+ * @returns {Object}
+ */
+ getBoneDataDic:function () {
+ return this.boneDataDic;
+ },
+ /**
+ * Gets bone data by bone name
+ * @function
+ * @param {String} boneName
+ * @returns {ccs.BoneData}
+ */
+ getBoneData:function (boneName) {
+ return this.boneDataDic[boneName];
+ }
+});
+
+/**
+ * FrameData saved the frame data needed for armature animation in this Armature.
+ * @class ccs.FrameData
+ * @extends ccs.BaseData
+ *
+ * @property {Number} duration - the duration of frame
+ * @property {Number} tweenEasing - the easing type of frame
+ * @property {Number} easingParamNumber - the count of easing parameters.
+ * @property {Object} easingParams - the dictionary of easing parameters.
+ * @property {Number} displayIndex - the display renderer index.
+ * @property {String} movement - the movement name.
+ * @property {String} event - the event name
+ * @property {String} sound - the sound path.
+ * @property {String} soundEffect - the sound effect path.
+ * @property {Object} blendFunc - the blendFunc of frame.
+ * @property {Number} frameID - the frame ID of frame
+ * @property {Boolean} isTween - the flag which frame whether is tween.
+ */
+ccs.FrameData = ccs.BaseData.extend(/** @lends ccs.FrameData# */{
+ duration:0,
+ tweenEasing:0,
+ easingParamNumber: 0,
+ easingParams: null,
+ displayIndex:-1,
+ movement:"",
+ event:"",
+ sound:"",
+ soundEffect:"",
+ blendFunc:null,
+ frameID:0,
+ isTween:true,
+
+ /**
+ * Construction of ccs.FrameData.
+ */
+ ctor:function () {
+ ccs.BaseData.prototype.ctor.call(this);
+ this.duration = 1;
+ this.tweenEasing = ccs.TweenType.LINEAR;
+ this.easingParamNumber = 0;
+ this.easingParams = [];
+ this.displayIndex = 0;
+ this.movement = "";
+ this.event = "";
+ this.sound = "";
+ this.soundEffect = "";
+ this.blendFunc = new cc.BlendFunc(cc.BLEND_SRC, cc.BLEND_DST);
+ this.frameID = 0;
+ this.isTween = true;
+ },
+
+ /**
+ * copy data
+ * @function
+ * @param frameData
+ */
+ copy:function (frameData) {
+ ccs.BaseData.prototype.copy.call(this, frameData);
+ this.duration = frameData.duration;
+ this.displayIndex = frameData.displayIndex;
+
+ this.tweenEasing = frameData.tweenEasing;
+ this.easingParamNumber = frameData.easingParamNumber;
+
+// this.movement = frameData.movement;
+// this.event = frameData.event;
+// this.sound = frameData.sound;
+// this.soundEffect = frameData.soundEffect;
+// this.easingParams.length = 0;
+ if (this.easingParamNumber !== 0){
+ this.easingParams.length = 0;
+ for (var i = 0; i
+ * The animation data information of Cocos Armature. It include all movement information for the Armature.
+ * The struct is AnimationData -> MovementData -> MovementBoneData -> FrameData
+ * -> MovementFrameData
+ *
+ * @class ccs.AnimationData
+ * @extends ccs.Class
+ */
+ccs.AnimationData = function(){
+ this.movementDataDic = {};
+ this.movementNames = [];
+ this.name = "";
+};
+
+/**
+ * adds movement data to the movement data dictionary
+ * @param {ccs.MovementData} moveData
+ */
+ccs.AnimationData.prototype.addMovement = function(moveData){
+ this.movementDataDic[moveData.name] = moveData;
+ this.movementNames.push(moveData.name);
+};
+
+/**
+ * gets movement data from movement data dictionary
+ * @param {String} moveName
+ * @returns {ccs.MovementData}
+ */
+ccs.AnimationData.prototype.getMovement = function(moveName){
+ return this.movementDataDic[moveName];
+};
+
+/**
+ * gets the count of movement data dictionary
+ * @returns {Number}
+ */
+ccs.AnimationData.prototype.getMovementCount = function(){
+ return Object.keys(this.movementDataDic).length;
+};
+
+/**
+ * contour vertex
+ * @class ccs.ContourVertex2
+ * @param {Number} x
+ * @param {Number} y
+ * @constructor
+ */
+ccs.ContourVertex2 = function (x, y) {
+ this.x = x || 0;
+ this.y = y || 0;
+};
+
+/**
+ * The Contour data information of Cocos Armature.
+ * @class ccs.ContourData
+ * @constructor
+ */
+ccs.ContourData = function(){
+ this.vertexList = [];
+};
+
+ccs.ContourData.prototype.init = function(){
+ this.vertexList.length = 0;
+ return true;
+};
+
+/**
+ * add a vertex object to vertex list
+ * @param {cc.Vec2} p
+ */
+ccs.ContourData.prototype.addVertex = function(p){
+ //var v = new ccs.ContourVertex2(p.x, p.y); //ccs.ContourVertex2 is same as cc.Vec2, so we needn't create a ccs.ContourVertex2 object
+ this.vertexList.push(p);
+};
+
+/**
+ * The texture data information of Cocos Armature
+ * @class ccs.TextureData
+ */
+ccs.TextureData = function(){
+ this.height = 0;
+ this.width = 0;
+ this.pivotX = 0.5;
+ this.pivotY = 0.5;
+ this.name = "";
+ this.contourDataList = [];
+};
+
+ccs.TextureData.prototype.init = function(){
+ this.contourDataList.length = 0;
+};
+
+/**
+ * Adds a contourData to contourDataList
+ * @param {ccs.ContourData} contourData
+ */
+ccs.TextureData.prototype.addContourData = function(contourData){
+ this.contourDataList.push(contourData);
+};
+
+/**
+ * gets a contourData from contourDataList by index
+ * @param {Number} index
+ * @returns {ccs.ContourData}
+ */
+ccs.TextureData.prototype.getContourData = function(index){
+ return this.contourDataList[index];
+};
diff --git a/extensions/cocostudio/armature/display/CCBatchNode.js b/extensions/cocostudio/armature/display/CCBatchNode.js
new file mode 100644
index 0000000000..f20c238850
--- /dev/null
+++ b/extensions/cocostudio/armature/display/CCBatchNode.js
@@ -0,0 +1,114 @@
+/****************************************************************************
+ 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 batchNode to Armature
+ * @class ccs.BatchNode
+ * @extends cc.Node
+ */
+ccs.BatchNode = cc.Node.extend(/** @lends ccs.BatchNode# */{
+ _atlas:null,
+ _className:"BatchNode",
+
+ ctor:function () {
+ this._atlas = null;
+
+ ccs.BatchNode.prototype.init.call(this);
+ },
+
+ init:function () {
+ var ret = cc.Node.prototype.init.call(this);
+ this.setShaderProgram(cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURE_UCOLOR));
+ return ret;
+ },
+
+ addChild:function (child, zOrder, tag) {
+ cc.Node.prototype.addChild.call(this, child, zOrder, tag);
+ if (child instanceof cc.Armature){
+ child.setBatchNode(this);
+ }
+ },
+
+ removeChild: function(child, cleanup){
+ if (child instanceof cc.Armature)
+ child.setBatchNode(null);
+ cc.Node.prototype.removeChild.call(this, child, cleanup);
+ },
+
+ visit:function (renderer, parentTransform, parentTransformUpdated) {
+ // quick return if not visible. children won't be drawn.
+ if (!this._visible)
+ return;
+
+ var dirty = parentTransformUpdated || this._transformUpdated;
+ if(dirty)
+ this._modelViewTransform = this.transform(parentTransform);
+ this._transformUpdated = false;
+
+ // IMPORTANT:
+ // To ease the migration to v3.0, we still support the kmGL stack,
+ // but it is deprecated and your code should not rely on it
+ cc.kmGLPushMatrixWitMat4(this._stackMatrix);
+
+ if (this.grid && this.grid.isActive())
+ this.grid.beforeDraw();
+
+ this.sortAllChildren();
+ this.draw(renderer, this._modelViewTransform, dirty);
+
+ if (this.grid && this.grid.isActive())
+ this.grid.afterDraw(this);
+
+ cc.kmGLPopMatrix();
+ },
+
+ draw:function (renderer, transform, transformUpdated) {
+ var locChildren = this._children;
+ if(locChildren.length === 0)
+ return;
+
+ var child = null;
+ for (var i = 0, len = locChildren.length; i < len; i++) {
+ child = locChildren[i];
+ child.visit();
+ if (child instanceof cc.Armature) {
+ this._atlas = child.getTextureAtlas();
+ }
+ }
+ if (this._atlas) {
+ this._atlas.drawQuads();
+ this._atlas.removeAllQuads();
+ }
+ }
+});
+
+/**
+ *
+ * @returns {ccs.BatchNode}
+ * @deprecated since v3.1, please use new construction instead
+ */
+ccs.BatchNode.create = function () {
+ return new ccs.BatchNode();
+};
\ No newline at end of file
diff --git a/extensions/cocostudio/armature/display/CCDecorativeDisplay.js b/extensions/cocostudio/armature/display/CCDecorativeDisplay.js
new file mode 100644
index 0000000000..f7a7c3d4bf
--- /dev/null
+++ b/extensions/cocostudio/armature/display/CCDecorativeDisplay.js
@@ -0,0 +1,118 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+/**
+ * Decorative a display node for Cocos Armature
+ * @class
+ * @extends ccs.Class
+ */
+ccs.DecorativeDisplay = ccs.Class.extend(/** @lends ccs.DecorativeDisplay# */{
+ _display: null,
+ _colliderDetector: null,
+ _displayData: null,
+
+ ctor:function () {
+ this._display = null;
+ this._colliderDetector = null;
+ this._displayData = null;
+
+ //ccs.DecorativeDisplay.prototype.init.call(this);
+ },
+
+ /**
+ * Initializes a ccs.DecorativeDisplay
+ * @returns {boolean}
+ */
+ init:function () {
+ return true;
+ },
+
+ /**
+ * Sets display node to decorative
+ * @param {cc.Node} display
+ */
+ setDisplay:function (display) {
+ if(display._parent){
+ display._parent.removeChild(display);
+ delete display._parent;
+ }
+ this._display = display;
+ },
+
+ /**
+ * Returns the display node
+ * @returns {cc.Node}
+ */
+ getDisplay:function () {
+ return this._display;
+ },
+
+ /**
+ * Sets collide detector
+ * @param {ccs.ColliderDetector} colliderDetector
+ */
+ setColliderDetector:function (colliderDetector) {
+ this._colliderDetector = colliderDetector;
+ },
+
+ /**
+ * Returns collide detector
+ * @returns {ccs.ColliderDetector}
+ */
+ getColliderDetector:function () {
+ return this._colliderDetector;
+ },
+
+ /**
+ * Sets display data
+ * @param {ccs.DisplayData} displayData
+ */
+ setDisplayData:function (displayData) {
+ this._displayData = displayData;
+ },
+
+ /**
+ * Returns display data
+ * @returns {ccs.DisplayData}
+ */
+ getDisplayData:function () {
+ return this._displayData;
+ },
+
+ release:function () {
+ this._display = null;
+ this._displayData = null;
+ this._colliderDetector = null;
+ }
+});
+
+/**
+ * Allocates and initializes a decorative display.
+ * @return {ccs.DecorativeDisplay}
+ * @deprecated since v3.1, please use new construction instead
+ */
+ccs.DecorativeDisplay.create = function () {
+ return new ccs.DecorativeDisplay();
+};
\ No newline at end of file
diff --git a/extensions/cocostudio/armature/display/CCDisplayFactory.js b/extensions/cocostudio/armature/display/CCDisplayFactory.js
new file mode 100644
index 0000000000..da8f8601df
--- /dev/null
+++ b/extensions/cocostudio/armature/display/CCDisplayFactory.js
@@ -0,0 +1,217 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+/**
+ * @ignore
+ */
+ccs.displayFactory = {
+ addDisplay: function (bone, decoDisplay, displayData) {
+ switch (displayData.displayType) {
+ case ccs.DISPLAY_TYPE_SPRITE:
+ this.addSpriteDisplay(bone, decoDisplay, displayData);
+ break;
+ case ccs.DISPLAY_TYPE_PARTICLE:
+ this.addParticleDisplay(bone, decoDisplay, displayData);
+ break;
+ case ccs.DISPLAY_TYPE_ARMATURE:
+ this.addArmatureDisplay(bone, decoDisplay, displayData);
+ break;
+ default:
+ break;
+ }
+ },
+
+ createDisplay: function (bone, decoDisplay) {
+ switch (decoDisplay.getDisplayData().displayType) {
+ case ccs.DISPLAY_TYPE_SPRITE:
+ this.createSpriteDisplay(bone, decoDisplay);
+ break;
+ case ccs.DISPLAY_TYPE_PARTICLE:
+ this.createParticleDisplay(bone, decoDisplay);
+ break;
+ case ccs.DISPLAY_TYPE_ARMATURE:
+ this.createArmatureDisplay(bone, decoDisplay);
+ break;
+ default:
+ break;
+ }
+ },
+
+ _helpTransform: {a:1, b:0, c:0, d:1, tx:0, ty:0},
+ updateDisplay: function (bone,dt, dirty) {
+ var display = bone.getDisplayRenderNode();
+ if(!display)
+ return;
+
+ switch (bone.getDisplayRenderNodeType()) {
+ case ccs.DISPLAY_TYPE_SPRITE:
+ if (dirty)
+ display.updateArmatureTransform();
+ break;
+ case ccs.DISPLAY_TYPE_PARTICLE:
+ this.updateParticleDisplay(bone, display, dt);
+ break;
+ case ccs.DISPLAY_TYPE_ARMATURE:
+ this.updateArmatureDisplay(bone, display, dt);
+ break;
+ default:
+ var transform = bone.getNodeToArmatureTransform();
+ display.setAdditionalTransform(transform);
+ break;
+ }
+ if (ccs.ENABLE_PHYSICS_CHIPMUNK_DETECT || ccs.ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX) {
+ if (dirty) {
+ var decoDisplay = bone.getDisplayManager().getCurrentDecorativeDisplay();
+ var detector = decoDisplay.getColliderDetector();
+ if (detector) {
+ var node = decoDisplay.getDisplay();
+ var displayTransform = node.getNodeToParentTransform();
+ var helpTransform = this._helpTransform;
+ helpTransform.a = displayTransform.a;
+ helpTransform.b = displayTransform.b;
+ helpTransform.c = displayTransform.c;
+ helpTransform.d = displayTransform.d;
+ helpTransform.tx = displayTransform.tx;
+ helpTransform.ty = displayTransform.ty;
+ var anchorPoint = cc.pointApplyAffineTransform(node.getAnchorPointInPoints(), helpTransform);
+ helpTransform.tx = anchorPoint.x;
+ helpTransform.ty = anchorPoint.y;
+ var t = cc.affineTransformConcat(helpTransform, bone.getArmature().getNodeToParentTransform());
+ detector.updateTransform(t);
+ }
+ }
+ }
+ },
+
+ addSpriteDisplay: function (bone, decoDisplay, displayData) {
+ var sdp = new ccs.SpriteDisplayData();
+ sdp.copy(displayData);
+ decoDisplay.setDisplayData(sdp);
+ this.createSpriteDisplay(bone, decoDisplay);
+ },
+
+ createSpriteDisplay: function (bone, decoDisplay) {
+ var skin = null;
+ var displayData = decoDisplay.getDisplayData();
+ //! remove .xxx
+ var textureName = displayData.displayName;
+ var startPos = textureName.lastIndexOf(".");
+ if (startPos !== -1)
+ textureName = textureName.substring(0, startPos);
+ //! create display
+ if (textureName === "")
+ skin = new ccs.Skin();
+ else
+ skin = new ccs.Skin("#" + textureName + ".png");
+
+ decoDisplay.setDisplay(skin);
+
+ skin.setBone(bone);
+ this.initSpriteDisplay(bone, decoDisplay, displayData.displayName, skin);
+
+ var armature = bone.getArmature();
+ if (armature) {
+ if (armature.getArmatureData().dataVersion >= ccs.CONST_VERSION_COMBINED)
+ skin.setSkinData(displayData.skinData);
+ else
+ skin.setSkinData(bone.boneData);
+ }
+ },
+
+ initSpriteDisplay: function (bone, decoDisplay, displayName, skin) {
+ //! remove .xxx
+ var textureName = displayName;
+ var startPos = textureName.lastIndexOf(".");
+
+ if (startPos !== -1)
+ textureName = textureName.substring(0, startPos);
+
+ var textureData = ccs.armatureDataManager.getTextureData(textureName);
+ if (textureData) {
+ //! Init display anchorPoint, every Texture have a anchor point
+ skin.setAnchorPoint(cc.p(textureData.pivotX, textureData.pivotY));
+ }
+
+ if (ccs.ENABLE_PHYSICS_CHIPMUNK_DETECT || ccs.ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX) {
+ if (textureData && textureData.contourDataList.length > 0) {
+ //! create ContourSprite
+ var colliderDetector = new ccs.ColliderDetector(bone);
+ colliderDetector.addContourDataList(textureData.contourDataList);
+ decoDisplay.setColliderDetector(colliderDetector);
+ }
+ }
+ },
+
+ addArmatureDisplay: function (bone, decoDisplay, displayData) {
+ var adp = new ccs.ArmatureDisplayData();
+ adp.copy(displayData);
+ decoDisplay.setDisplayData(adp);
+
+ this.createArmatureDisplay(bone, decoDisplay);
+ },
+
+ createArmatureDisplay: function (bone, decoDisplay) {
+ var displayData = decoDisplay.getDisplayData();
+ var armature = new ccs.Armature(displayData.displayName, bone);
+ decoDisplay.setDisplay(armature);
+ },
+
+ updateArmatureDisplay: function (bone, armature, dt) {
+ if (armature) {
+ armature.sortAllChildren();
+ armature.update(dt);
+ }
+ },
+
+ addParticleDisplay: function (bone, decoDisplay, displayData) {
+ var adp = new ccs.ParticleDisplayData();
+ adp.copy(displayData);
+ decoDisplay.setDisplayData(adp);
+ this.createParticleDisplay(bone, decoDisplay);
+ },
+
+ createParticleDisplay: function (bone, decoDisplay) {
+ var displayData = decoDisplay.getDisplayData();
+ var system = new cc.ParticleSystem(displayData.displayName);
+
+ system.removeFromParent();
+ system.cleanup();
+
+ var armature = bone.getArmature();
+ if (armature)
+ system.setParent(bone.getArmature());
+
+ decoDisplay.setDisplay(system);
+ },
+
+ updateParticleDisplay: function (bone, particleSystem, dt) {
+ var node = new ccs.BaseData();
+ ccs.TransformHelp.matrixToNode(bone.nodeToArmatureTransform(), node);
+ particleSystem.setPosition(node.x, node.y);
+ particleSystem.setScaleX(node.scaleX);
+ particleSystem.setScaleY(node.scaleY);
+ particleSystem.update(dt);
+ }
+};
\ No newline at end of file
diff --git a/extensions/cocostudio/armature/display/CCDisplayManager.js b/extensions/cocostudio/armature/display/CCDisplayManager.js
new file mode 100644
index 0000000000..5c31dd15a3
--- /dev/null
+++ b/extensions/cocostudio/armature/display/CCDisplayManager.js
@@ -0,0 +1,465 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+/**
+ * The display manager for CocoStudio Armature bone.
+ * @Class ccs.DisplayManager
+ * @extend cc._Class
+ *
+ * @param {ccs.Bone} bone The bone for the display manager
+ */
+ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
+ _decoDisplayList:null,
+ _currentDecoDisplay:null,
+ _displayRenderNode:null,
+ _displayIndex: null,
+ _forceChangeDisplay:false,
+ _bone:null,
+ _visible:true,
+ _displayType: null,
+
+ ctor:function (bone) {
+ this._decoDisplayList = [];
+ this._currentDecoDisplay = null;
+ this._displayRenderNode = null;
+ this._displayIndex = null;
+ this._forceChangeDisplay = false;
+ this._bone = null;
+ this._visible = true;
+ this._displayType = ccs.DISPLAY_TYPE_MAX;
+
+ bone && ccs.DisplayManager.prototype.init.call(this, bone);
+ },
+
+ /**
+ * Initializes a ccs.DisplayManager.
+ * @param bone
+ * @returns {boolean}
+ */
+ init:function (bone) {
+ this._bone = bone;
+ this.initDisplayList(bone.getBoneData());
+ return true;
+ },
+
+ /**
+ *
+ * Add display and use _DisplayData init the display.
+ * If index already have a display, then replace it.
+ * If index is current display index, then also change display to _index
+ *
+ * @param {ccs.DisplayData|cc.Node} display it include the display information, like DisplayType. If you want to create a sprite display, then create a SpriteDisplayData param
+ * @param {Number} index the index of the display you want to replace or add to. -1 : append display from back
+ */
+ addDisplay: function (display, index) {
+ var decoDisplay, locDisplayList = this._decoDisplayList;
+ if( (index >= 0) && (index < locDisplayList.length) )
+ decoDisplay = locDisplayList[index];
+ else{
+ decoDisplay = new ccs.DecorativeDisplay();
+ locDisplayList.push(decoDisplay);
+ }
+
+ if(display instanceof ccs.DisplayData){
+ ccs.displayFactory.addDisplay(this._bone, decoDisplay, display);
+ //! if changed display index is current display index, then change current display to the new display
+ if(index === this._displayIndex) {
+ this._displayIndex = -1;
+ this.changeDisplayWithIndex(index, false);
+ }
+ return;
+ }
+
+ var displayData = null;
+ if (display instanceof ccs.Skin) {
+ display.setBone(this._bone);
+ displayData = new ccs.SpriteDisplayData();
+ ccs.displayFactory.initSpriteDisplay(this._bone, decoDisplay, display.getDisplayName(), display);
+
+ var spriteDisplayData = decoDisplay.getDisplayData();
+ if (spriteDisplayData instanceof ccs.SpriteDisplayData) {
+ display.setSkinData(spriteDisplayData.skinData);
+ displayData.skinData = spriteDisplayData.skinData;
+ } else {
+ var find = false;
+ for (var i = locDisplayList.length - 2; i >= 0; i--) {
+ var dd = locDisplayList[i];
+ var sdd = dd.getDisplayData();
+ if (sdd instanceof ccs.SpriteDisplayData) {
+ find = true;
+ display.setSkinData(sdd.skinData);
+ displayData.skinData = sdd.skinData;
+ break;
+ }
+ }
+ if (!find)
+ display.setSkinData(new ccs.BaseData());
+ }
+ } else if (display instanceof cc.ParticleSystem){
+ displayData = new ccs.ParticleDisplayData();
+ display.removeFromParent();
+ display.cleanup();
+ var armature = this._bone.getArmature();
+ if (armature)
+ display.setParent(armature);
+ } else if(display instanceof ccs.Armature) {
+ displayData = new ccs.ArmatureDisplayData();
+ displayData.displayName = display.getName();
+ display.setParentBone(this._bone);
+ } else
+ displayData = new ccs.DisplayData();
+ decoDisplay.setDisplay(display);
+ decoDisplay.setDisplayData(displayData);
+
+ //! if changed display index is current display index, then change current display to the new display
+ if(index === this._displayIndex) {
+ this._displayIndex = -1;
+ this.changeDisplayWithIndex(index, false);
+ }
+ },
+
+ _addDisplayOther:function(decoDisplay,display){
+ var displayData = null;
+ if (display instanceof ccs.Skin){
+ var skin = display;
+ skin.setBone(this._bone);
+ displayData = new ccs.SpriteDisplayData();
+ displayData.displayName = skin.getDisplayName();
+ ccs.displayFactory.initSpriteDisplay(this._bone, decoDisplay, skin.getDisplayName(), skin);
+ var spriteDisplayData = decoDisplay.getDisplayData();
+ if (spriteDisplayData instanceof ccs.SpriteDisplayData)
+ skin.setSkinData(spriteDisplayData.skinData);
+ else{
+ var find = false;
+ for (var i = this._decoDisplayList.length - 2; i >= 0; i--) {
+ var dd = this._decoDisplayList[i];
+ var sdd = dd.getDisplayData();
+ if (sdd) {
+ find = true;
+ skin.setSkinData(sdd.skinData);
+ displayData.skinData = sdd.skinData;
+ break;
+ }
+ }
+ if (!find) {
+ skin.setSkinData(new ccs.BaseData());
+ }
+ skin.setSkinData(new ccs.BaseData());
+ }
+
+ }
+ else if (display instanceof cc.ParticleSystem){
+ displayData = new ccs.ParticleDisplayData();
+ displayData.displayName = display._plistFile;
+ }
+ else if (display instanceof ccs.Armature){
+ displayData = new ccs.ArmatureDisplayData();
+ displayData.displayName = display.getName();
+ display.setParentBone(this._bone);
+ }
+ else {
+ displayData = new ccs.DisplayData();
+ }
+ decoDisplay.setDisplay(display);
+ decoDisplay.setDisplayData(displayData);
+ },
+
+ /**
+ * Removes display node from list.
+ * @param {Number} index
+ */
+ removeDisplay:function (index) {
+ this._decoDisplayList.splice(index, 1);
+ if (index === this._displayIndex) {
+ this.setCurrentDecorativeDisplay(null);
+ this._displayIndex = -1;
+ }
+ },
+
+ /**
+ * Returns the display node list.
+ * @returns {Array}
+ */
+ getDecorativeDisplayList:function(){
+ return this._decoDisplayList;
+ },
+
+ /**
+ *
+ * Change display by index. You can just use this method to change display in the display list.
+ * The display list is just used for this bone, and it is the displays you may use in every frame.
+ * Note : if index is the same with prev index, the method will not effect
+ *
+ * @param {Number} index The index of the display you want to change
+ * @param {Boolean} force If true, then force change display to specified display, or current display will set to display index edit in the flash every key frame.
+ */
+ changeDisplayWithIndex:function (index, force) {
+ if (index >= this._decoDisplayList.length) {
+ cc.log("the index value is out of range");
+ return;
+ }
+ this._forceChangeDisplay = force;
+
+ //if index is equal to current display index,then do nothing
+ if (this._displayIndex === index)
+ return;
+
+ this._displayIndex = index;
+
+ //! If displayIndex < 0, it means you want to hide you display
+ if (index < 0) {
+ if(this._displayRenderNode) {
+ this._displayRenderNode.removeFromParent(true);
+ this.setCurrentDecorativeDisplay(null);
+ }
+ return;
+ }
+ this.setCurrentDecorativeDisplay(this._decoDisplayList[index]);
+ },
+
+ /**
+ * Change display by name. @see changeDisplayWithIndex.
+ * @param {String} name
+ * @param {Boolean} force
+ */
+ changeDisplayWithName: function (name, force) {
+ var locDisplayList = this._decoDisplayList;
+ for (var i = 0; i < locDisplayList.length; i++) {
+ if (locDisplayList[i].getDisplayData().displayName === name) {
+ this.changeDisplayWithIndex(i, force);
+ break;
+ }
+ }
+ },
+
+ /**
+ * Sets current decorative display.
+ * @param {ccs.DecorativeDisplay} decoDisplay
+ */
+ setCurrentDecorativeDisplay:function (decoDisplay) {
+ var locCurrentDecoDisplay = this._currentDecoDisplay;
+ if (ccs.ENABLE_PHYSICS_CHIPMUNK_DETECT || ccs.ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX) {
+ if (locCurrentDecoDisplay && locCurrentDecoDisplay.getColliderDetector())
+ locCurrentDecoDisplay.getColliderDetector().setActive(false);
+ }
+
+ this._currentDecoDisplay = decoDisplay;
+ locCurrentDecoDisplay = this._currentDecoDisplay;
+ if (ccs.ENABLE_PHYSICS_CHIPMUNK_DETECT || ccs.ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX) {
+ if (locCurrentDecoDisplay && locCurrentDecoDisplay.getColliderDetector())
+ locCurrentDecoDisplay.getColliderDetector().setActive(true);
+ }
+
+ var displayRenderNode = (!locCurrentDecoDisplay) ? null : locCurrentDecoDisplay.getDisplay();
+
+ var locRenderNode = this._displayRenderNode, locBone = this._bone;
+ if (locRenderNode) {
+ if (locRenderNode instanceof ccs.Armature)
+ locBone.setChildArmature(null);
+ locRenderNode.removeFromParent(true);
+ }
+ this._displayRenderNode = displayRenderNode;
+
+ if (displayRenderNode) {
+ if (displayRenderNode instanceof ccs.Armature) {
+ this._bone.setChildArmature(displayRenderNode);
+ displayRenderNode.setParentBone(this._bone);
+ } else if (displayRenderNode instanceof cc.ParticleSystem) {
+ if (displayRenderNode instanceof ccs.Armature) {
+ locBone.setChildArmature(displayRenderNode);
+ displayRenderNode.setParentBone(locBone);
+ } else if (displayRenderNode instanceof cc.ParticleSystem)
+ displayRenderNode.resetSystem();
+ }
+
+ displayRenderNode.setColor(locBone.getDisplayedColor());
+ displayRenderNode.setOpacity(locBone.getDisplayedOpacity());
+
+ this._displayRenderNode.setVisible(this._visible);
+ this._displayType = this._currentDecoDisplay.getDisplayData().displayType;
+ }else
+ this._displayType = ccs.DISPLAY_TYPE_MAX;
+
+
+ cc.renderer.childrenOrderDirty = true;
+ },
+
+ /**
+ * Returns the current display render node.
+ * @returns {cc.Node}
+ */
+ getDisplayRenderNode:function () {
+ return this._displayRenderNode;
+ },
+
+ /**
+ * Returns the type of display render node.
+ * @returns {Number}
+ */
+ getDisplayRenderNodeType:function(){
+ return this._displayType;
+ },
+
+ /**
+ * Returns the index of display render node.
+ * @returns {Number}
+ */
+ getCurrentDisplayIndex:function () {
+ return this._displayIndex;
+ },
+
+ /**
+ * Returns the current decorative display
+ * @returns {ccs.DecorativeDisplay}
+ */
+ getCurrentDecorativeDisplay:function () {
+ return this._currentDecoDisplay;
+ },
+
+ /**
+ * Gets a decorative display by index.
+ * @param index
+ * @returns {ccs.DecorativeDisplay}
+ */
+ getDecorativeDisplayByIndex:function (index) {
+ return this._decoDisplayList[index];
+ },
+
+ /**
+ *
+ * Use BoneData to init the display list.
+ * If display is a sprite, and it have texture info in the TextureData, then use TextureData to init the display node's anchor point
+ * If the display is a Armature, then create a new Armature
+ *
+ * @param {ccs.BoneData} boneData
+ */
+ initDisplayList:function (boneData) {
+ this._decoDisplayList.length = 0;
+ if (!boneData)
+ return;
+ var displayList = boneData.displayDataList, decoList = this._decoDisplayList, locBone = this._bone;
+ for (var i = 0; i < displayList.length; i++) {
+ var displayData = displayList[i];
+ var decoDisplay = new ccs.DecorativeDisplay();
+ decoDisplay.setDisplayData(displayData);
+ ccs.displayFactory.createDisplay(locBone, decoDisplay);
+ decoList.push(decoDisplay);
+ }
+ },
+
+ /**
+ * Check if the position is inside the bone.
+ * @param {cc.Vec2|Number} point
+ * @param {Number} [y]
+ * @returns {boolean}
+ */
+ containPoint: function (point, y) {
+ if (!this._visible || this._displayIndex < 0)
+ return false;
+
+ if (y !== undefined)
+ point = cc.p(point, y);
+
+ if(this._currentDecoDisplay.getDisplayData().displayType === ccs.DISPLAY_TYPE_SPRITE){
+ /*
+ * First we first check if the point is in the sprite content rect. If false, then we continue to check
+ * the contour point. If this step is also false, then we can say the bone not contain this point.
+ *
+ */
+ var sprite = this._currentDecoDisplay.getDisplay();
+ sprite = sprite.getChildByTag(0);
+ return ccs.SPRITE_CONTAIN_POINT_WITH_RETURN(sprite, point);
+ }
+ return false;
+ },
+
+ /**
+ *
+ * Sets whether the display is visible
+ * The default value is true, a node is default to visible
+ *
+ * @param {boolean} visible
+ */
+ setVisible:function (visible) {
+ if (!this._displayRenderNode)
+ return;
+ this._visible = visible;
+ this._displayRenderNode.setVisible(visible);
+ },
+
+ /**
+ * Determines if the display is visible
+ * @returns {boolean} true if the node is visible, false if the node is hidden.
+ */
+ isVisible:function () {
+ return this._visible;
+ },
+
+ getContentSize:function () {
+ if (!this._displayRenderNode)
+ return cc.size(0, 0);
+ return this._displayRenderNode.getContentSize();
+ },
+
+ getBoundingBox:function () {
+ if (!this._displayRenderNode)
+ return cc.rect(0, 0, 0, 0);
+ return this._displayRenderNode.getBoundingBox();
+ },
+
+ getAnchorPoint:function () {
+ if (!this._displayRenderNode)
+ return cc.p(0, 0);
+ return this._displayRenderNode.getAnchorPoint();
+ },
+
+ getAnchorPointInPoints:function () {
+ if (!this._displayRenderNode)
+ return cc.p(0, 0);
+ return this._displayRenderNode.getAnchorPointInPoints();
+ },
+
+ getForceChangeDisplay:function () {
+ return this._forceChangeDisplay;
+ },
+
+ release:function () {
+ this._decoDisplayList = null;
+ if (this._displayRenderNode) {
+ this._displayRenderNode.removeFromParent(true);
+ this._displayRenderNode = null;
+ }
+ }
+});
+
+/**
+ * Allocates and initializes a display manager with ccs.Bone.
+ * @param {ccs.Bone} bone
+ * @returns {ccs.DisplayManager}
+ * @deprecated since v3.1, please use new construction instead
+ */
+ccs.DisplayManager.create = function (bone) {
+ return new ccs.DisplayManager(bone);
+};
\ No newline at end of file
diff --git a/extensions/cocostudio/armature/display/CCSkin.js b/extensions/cocostudio/armature/display/CCSkin.js
new file mode 100644
index 0000000000..4553cf568b
--- /dev/null
+++ b/extensions/cocostudio/armature/display/CCSkin.js
@@ -0,0 +1,215 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+/**
+ * ccs.Bone uses ccs.Skin to displays on screen.
+ * @class
+ * @extends ccs.Sprite
+ *
+ * @param {String} [fileName]
+ * @param {cc.Rect} [rect]
+ *
+ * @property {Object} skinData - The data of the skin
+ * @property {ccs.Bone} bone - The bone of the skin
+ * @property {String} displayName - <@readonly> The displayed name of skin
+ *
+ */
+ccs.Skin = ccs.Sprite.extend(/** @lends ccs.Skin# */{
+ _skinData: null,
+ bone: null,
+ _skinTransform: null,
+ _displayName: "",
+ _armature: null,
+ _className: "Skin",
+
+ ctor: function (fileName, rect) {
+ cc.Sprite.prototype.ctor.call(this);
+ this._skinData = null;
+ this.bone = null;
+ this._displayName = "";
+ this._skinTransform = cc.affineTransformIdentity();
+ this._armature = null;
+
+ if (fileName == null || fileName === "") {
+ ccs.Skin.prototype.init.call(this);
+ } else {
+ if(fileName[0] === "#"){
+ ccs.Skin.prototype.initWithSpriteFrameName.call(this, fileName.substr(1));
+ } else {
+ ccs.Skin.prototype.initWithFile.call(this, fileName, rect);
+ }
+ }
+ },
+
+ /**
+ * Initializes with sprite frame name
+ * @param {String} spriteFrameName
+ * @returns {Boolean}
+ */
+ initWithSpriteFrameName: function (spriteFrameName) {
+ if(spriteFrameName === "")
+ return false;
+ var pFrame = cc.spriteFrameCache.getSpriteFrame(spriteFrameName);
+ var ret = true;
+ if(pFrame)
+ this.initWithSpriteFrame(pFrame);
+ else{
+ cc.log("Can't find CCSpriteFrame with %s. Please check your .plist file", spriteFrameName);
+ ret = false;
+ }
+ this._displayName = spriteFrameName;
+ return ret;
+ },
+
+ /**
+ * Initializes with texture file name.
+ * @param {String} fileName
+ * @param {cc.Rect} rect
+ * @returns {Boolean}
+ */
+ initWithFile: function (fileName, rect) {
+ var ret = rect ? cc.Sprite.prototype.initWithFile.call(this, fileName, rect)
+ : cc.Sprite.prototype.initWithFile.call(this, fileName);
+ this._displayName = fileName;
+ return ret;
+ },
+
+ /**
+ * Sets skin data to ccs.Skin.
+ * @param {ccs.BaseData} skinData
+ */
+ setSkinData: function (skinData) {
+ this._skinData = skinData;
+ this.setScaleX(skinData.scaleX);
+ this.setScaleY(skinData.scaleY);
+ this.setRotationX(cc.radiansToDegrees(skinData.skewX));
+ this.setRotationY(cc.radiansToDegrees(-skinData.skewY));
+ this.setPosition(skinData.x, skinData.y);
+
+ var localTransform = this.getNodeToParentTransform ? this.getNodeToParentTransform() : this.nodeToParentTransform();
+ var skinTransform = this._skinTransform;
+ skinTransform.a = localTransform.a;
+ skinTransform.b = localTransform.b;
+ skinTransform.c = localTransform.c;
+ skinTransform.d = localTransform.d;
+ skinTransform.tx = localTransform.tx;
+ skinTransform.ty = localTransform.ty;
+ this.updateArmatureTransform();
+ },
+
+ /**
+ * Returns skin date of ccs.Skin.
+ * @returns {ccs.BaseData}
+ */
+ getSkinData: function () {
+ return this._skinData;
+ },
+
+ /**
+ * Updates armature skin's transform with skin transform and bone's transform.
+ */
+ updateArmatureTransform: function () {
+ this._renderCmd.updateArmatureTransform();
+ },
+
+ /**
+ * Returns skin's world transform.
+ * @returns {cc.AffineTransform}
+ */
+ getNodeToWorldTransform: function(){
+ return this._renderCmd.getNodeToWorldTransform();
+ },
+
+ getNodeToWorldTransformAR: function(){
+ return this._renderCmd.getNodeToWorldTransformAR();
+ },
+
+ /**
+ * Sets the bone reference to ccs.Skin.
+ * @param bone
+ */
+ setBone: function (bone) {
+ this.bone = bone;
+ var armature = this.bone.getArmature();
+ if(armature)
+ this._armature = armature;
+ },
+
+ /**
+ * Returns the bone reference of ccs.Skin.
+ * @returns {null}
+ */
+ getBone: function () {
+ return this.bone;
+ },
+
+ /**
+ * display name getter
+ * @returns {String}
+ */
+ getDisplayName: function () {
+ return this._displayName;
+ },
+
+ _createRenderCmd: function(){
+ if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ return new ccs.Skin.CanvasRenderCmd(this);
+ else
+ return new ccs.Skin.WebGLRenderCmd(this);
+ }
+});
+
+var _p = ccs.Skin.prototype;
+
+// Extended properties
+/** @expose */
+_p.skinData;
+cc.defineGetterSetter(_p, "skinData", _p.getSkinData, _p.setSkinData);
+/** @expose */
+_p.displayName;
+cc.defineGetterSetter(_p, "displayName", _p.getDisplayName);
+
+_p = null;
+
+/**
+ * allocates and initializes a skin.
+ * @param {String} [fileName] fileName or sprite frame name
+ * @param {cc.Rect} [rect]
+ * @returns {ccs.Skin}
+ * @deprecated since v3.1, please use new construction instead
+ */
+ccs.Skin.create = function (fileName, rect) {
+ return new ccs.Skin(fileName, rect);
+};
+
+/**
+ * allocates and initializes a skin.
+ * @param {String} spriteFrameName
+ * @returns {ccs.Skin}
+ * @deprecated since v3.1, please use new construction instead
+ */
+ccs.Skin.createWithSpriteFrameName = function (spriteFrameName) {
+ return new ccs.Skin("#" + spriteFrameName);
+};
diff --git a/extensions/cocostudio/armature/display/CCSkinCanvasRenderCmd.js b/extensions/cocostudio/armature/display/CCSkinCanvasRenderCmd.js
new file mode 100644
index 0000000000..4cde024fc8
--- /dev/null
+++ b/extensions/cocostudio/armature/display/CCSkinCanvasRenderCmd.js
@@ -0,0 +1,58 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+(function(){
+ ccs.Skin.RenderCmd = {
+ updateArmatureTransform: function () {
+ var node = this._node;
+ this._transform = cc.affineTransformConcat(
+ node._skinTransform,
+ node.bone.getNodeToArmatureTransform()
+ );
+ this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.transformDirty ^ this._dirtyFlag;
+ },
+
+ getNodeToWorldTransform: function () {
+ return cc.affineTransformConcat(this._transform, this._node.bone.getArmature().getNodeToWorldTransform());
+ },
+
+ getNodeToWorldTransformAR: function () {
+ var displayTransform = this._transform, node = this._node;
+ this._anchorPointInPoints = cc.pointApplyAffineTransform(this._anchorPointInPoints, displayTransform);
+ displayTransform.tx = this._anchorPointInPoints.x;
+ displayTransform.ty = this._anchorPointInPoints.y;
+ return cc.affineTransformConcat(displayTransform, node.bone.getArmature().getNodeToWorldTransform());
+ }
+ };
+
+ ccs.Skin.CanvasRenderCmd = function(renderable){
+ cc.Sprite.CanvasRenderCmd.call(this, renderable);
+ this._needDraw = true;
+ };
+
+ var proto = ccs.Skin.CanvasRenderCmd.prototype = Object.create(cc.Sprite.CanvasRenderCmd.prototype);
+ cc.js.mixin(proto, ccs.Skin.RenderCmd);
+ proto.constructor = ccs.Skin.CanvasRenderCmd;
+})();
diff --git a/extensions/cocostudio/armature/display/CCSkinWebGLRenderCmd.js b/extensions/cocostudio/armature/display/CCSkinWebGLRenderCmd.js
new file mode 100644
index 0000000000..f3d9e56f82
--- /dev/null
+++ b/extensions/cocostudio/armature/display/CCSkinWebGLRenderCmd.js
@@ -0,0 +1,146 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+(function(){
+ ccs.Skin.WebGLRenderCmd = function(renderable){
+ cc.Sprite.WebGLRenderCmd.call(this, renderable);
+ };
+
+ var proto = ccs.Skin.WebGLRenderCmd.prototype = Object.create(cc.Sprite.WebGLRenderCmd.prototype);
+ cc.js.mixin(proto, ccs.Skin.RenderCmd);
+ proto.constructor = ccs.Skin.WebGLRenderCmd;
+
+ proto.updateTransform = function(){
+ var node = this._node;
+ var locQuad = this._quad;
+ // If it is not visible, or one of its ancestors is not visible, then do nothing:
+ if( !node._visible)
+ locQuad.br.vertices = locQuad.tl.vertices = locQuad.tr.vertices = locQuad.bl.vertices = {x: 0, y: 0, z: 0};
+ else {
+ //
+ // calculate the Quad based on the Affine Matrix
+ //
+ var transform = this.getNodeToParentTransform(); //this._transform;
+ var size = node._rect;
+
+ var x1 = node._offsetPosition.x, y1 = node._offsetPosition.y;
+
+ var x2 = x1 + size.width, y2 = y1 + size.height;
+ var x = transform.tx, y = transform.ty;
+
+ var cr = transform.a, sr = transform.b;
+ var cr2 = transform.d, sr2 = -transform.c;
+ var ax = x1 * cr - y1 * sr2 + x;
+ var ay = x1 * sr + y1 * cr2 + y;
+
+ var bx = x2 * cr - y1 * sr2 + x;
+ var by = x2 * sr + y1 * cr2 + y;
+
+ var cx = x2 * cr - y2 * sr2 + x;
+ var cy = x2 * sr + y2 * cr2 + y;
+
+ var dx = x1 * cr - y2 * sr2 + x;
+ var dy = x1 * sr + y2 * cr2 + y;
+
+ var locVertexZ = node._vertexZ;
+ if(!cc.SPRITEBATCHNODE_RENDER_SUBPIXEL) {
+ ax = 0 | ax;
+ ay = 0 | ay;
+ bx = 0 | bx;
+ by = 0 | by;
+ cx = 0 | cx;
+ cy = 0 | cy;
+ dx = 0 | dx;
+ dy = 0 | dy;
+ }
+ this.SET_VERTEX3F(locQuad.bl.vertices,ax, ay,locVertexZ);
+ this.SET_VERTEX3F(locQuad.br.vertices,bx, by,locVertexZ);
+ this.SET_VERTEX3F(locQuad.tl.vertices,dx, dy,locVertexZ);
+ this.SET_VERTEX3F(locQuad.tr.vertices,cx, cy,locVertexZ);
+ }
+
+ // MARMALADE CHANGE: ADDED CHECK FOR nullptr, TO PERMIT SPRITES WITH NO BATCH NODE / TEXTURE ATLAS
+ if (node.textureAtlas)
+ node.textureAtlas.updateQuad(locQuad, node.textureAtlas.getTotalQuads());
+ this._quadDirty = true;
+ };
+
+ proto.SET_VERTEX3F = function(_v_, _x_, _y_, _z_){
+ (_v_).x = (_x_);
+ (_v_).y = (_y_);
+ (_v_).z = (_z_);
+ };
+
+ proto.rendering = function(ctx){
+ var node = this._node;
+ if (!node._textureLoaded)
+ return;
+
+ var gl = ctx || cc._renderContext, locTexture = node._texture;
+ if (locTexture && locTexture._textureLoaded) {
+ this._shaderProgram.use();
+ this._shaderProgram.setUniformForModelViewAndProjectionMatrixWithMat4();
+
+ cc.glBlendFunc(node._blendFunc.src, node._blendFunc.dst);
+ //optimize performance for javascript
+ cc.glBindTexture2DN(0, locTexture); // = cc.glBindTexture2D(locTexture);
+ cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POS_COLOR_TEX);
+
+ gl.bindBuffer(gl.ARRAY_BUFFER, this._quadWebBuffer);
+ if (this._quadDirty) {
+ gl.bufferData(gl.ARRAY_BUFFER, this._quad.arrayBuffer, gl.DYNAMIC_DRAW);
+ this._quadDirty = false;
+ }
+ gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 24, 0); //cc.VERTEX_ATTRIB_POSITION
+ gl.vertexAttribPointer(1, 4, gl.UNSIGNED_BYTE, true, 24, 12); //cc.VERTEX_ATTRIB_COLOR
+ gl.vertexAttribPointer(2, 2, gl.FLOAT, false, 24, 16); //cc.VERTEX_ATTRIB_TEX_COORDS
+
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
+ }
+
+ cc.g_NumberOfDraws++;
+ if (cc.SPRITE_DEBUG_DRAW === 0 && !node._showNode)
+ return;
+
+ if (cc.SPRITE_DEBUG_DRAW === 1 || node._showNode) {
+ // draw bounding box
+ var locQuad = this._quad;
+ var verticesG1 = [
+ cc.p(locQuad.tl.vertices.x, locQuad.tl.vertices.y),
+ cc.p(locQuad.bl.vertices.x, locQuad.bl.vertices.y),
+ cc.p(locQuad.br.vertices.x, locQuad.br.vertices.y),
+ cc.p(locQuad.tr.vertices.x, locQuad.tr.vertices.y)
+ ];
+ cc._drawingUtil.drawPoly(verticesG1, 4, true);
+ } else if (cc.SPRITE_DEBUG_DRAW === 2) {
+ // draw texture box
+ var drawRectG2 = node.getTextureRect();
+ var offsetPixG2 = node.getOffsetPosition();
+ var verticesG2 = [cc.p(offsetPixG2.x, offsetPixG2.y), cc.p(offsetPixG2.x + drawRectG2.width, offsetPixG2.y),
+ cc.p(offsetPixG2.x + drawRectG2.width, offsetPixG2.y + drawRectG2.height), cc.p(offsetPixG2.x, offsetPixG2.y + drawRectG2.height)];
+ cc._drawingUtil.drawPoly(verticesG2, 4, true);
+ } // CC_SPRITE_DEBUG_DRAW
+ };
+})();
\ No newline at end of file
diff --git a/extensions/cocostudio/armature/physics/CCColliderDetector.js b/extensions/cocostudio/armature/physics/CCColliderDetector.js
new file mode 100644
index 0000000000..73e58374d6
--- /dev/null
+++ b/extensions/cocostudio/armature/physics/CCColliderDetector.js
@@ -0,0 +1,397 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+/**
+ * @ignore
+ */
+ccs.PT_RATIO = 32;
+
+/**
+ * Base class for ccs.ColliderFilter
+ * @class
+ * @extends ccs.Class
+ */
+ccs.ColliderFilter = ccs.Class.extend(/** @lends ccs.ColliderFilter# */{
+ _collisionType: 0,
+ _group: 0,
+ _categoryBits: 0,
+ _groupIndex: 0,
+ _maskBits: 0,
+
+ ctor: function (collisionType, group) {
+ this._collisionType = collisionType || 0;
+ this._group = group || 0;
+ },
+
+ updateShape: function (shape) {
+ if(shape instanceof cp.Shape){
+ shape.collision_type = this._collisionType;
+ shape.group = this._group;
+ }else if(shape instanceof Box2D.b2FilterData){
+ var filter = new Box2D.b2FilterData();
+ filter.categoryBits = this._categoryBits;
+ filter.groupIndex = this._groupIndex;
+ filter.maskBits = this._maskBits;
+
+ shape.SetFilterData(filter);
+ }
+ }
+});
+
+/**
+ * Base class for ccs.ColliderBody
+ * @class
+ * @extends ccs.Class
+ *
+ * @property {ccs.ContourData} contourData - The contour data of collider body
+ * @property {ccs.Shape} shape - The shape of collider body
+ * @property {ccs.ColliderFilter} colliderFilter - The collider filter of collider body
+ *
+ */
+ccs.ColliderBody = ccs.Class.extend(/** @lends ccs.ColliderBody# */{
+ shape: null,
+ coutourData: null,
+ colliderFilter: null,
+ _calculatedVertexList: null,
+ ctor: function (contourData) {
+ this.shape = null;
+ this.coutourData = contourData;
+ this.colliderFilter = new ccs.ColliderFilter();
+ if (ccs.ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX) {
+ this._calculatedVertexList = [];
+ }
+ },
+
+ /**
+ * contourData getter
+ * @returns {ccs.ContourData}
+ */
+ getContourData: function () {
+ return this.coutourData;
+ },
+
+ /**
+ * colliderFilter setter
+ * @param {ccs.ColliderFilter} colliderFilter
+ */
+ setColliderFilter: function (colliderFilter) {
+ this.colliderFilter = colliderFilter;
+ },
+
+ /**
+ * get calculated vertex list
+ * @returns {Array}
+ */
+ getCalculatedVertexList: function () {
+ return this._calculatedVertexList;
+ },
+
+ setB2Fixture: function(fixture){
+ this._fixture = fixture;
+ },
+
+ getB2Fixture: function(){
+ return this._fixture;
+ },
+
+ /**
+ * shape getter
+ * @param {ccs.Shape} shape
+ */
+ setShape: function (shape) {
+ this.shape = shape;
+ },
+
+ /**
+ * shape setter
+ * @return {ccs.Shape}
+ */
+ getShape: function () {
+ return this.shape;
+ },
+
+ /**
+ * contourData setter
+ * @param {ccs.ContourData} contourData
+ */
+ setContourData: function (contourData) {
+ this.coutourData = contourData;
+ },
+
+ /**
+ * colliderFilter getter
+ * @returns {ccs.ColliderFilter}
+ */
+ getColliderFilter: function () {
+ return this.colliderFilter;
+ }
+});
+
+/**
+ * Base class for ccs.ColliderDetector
+ * @class
+ * @extends ccs.Class
+ *
+ * @param {ccs.Bone} [bone]
+ *
+ * @property {ccs.ColliderFilter} colliderFilter - The collider filter of the collider detector
+ * @property {Boolean} active - Indicate whether the collider detector is active
+ * @property {Object} body - The collider body
+ */
+ccs.ColliderDetector = ccs.Class.extend(/** @lends ccs.ColliderDetector# */{
+ _colliderBodyList: null,
+ _bone: null,
+ _body: null,
+ _active: false,
+ _filter: null,
+ helpPoint: cc.p(0, 0),
+
+ ctor: function (bone) {
+ this._colliderBodyList = [];
+ this._bone = null;
+ this._body = null;
+ this._active = false;
+ this._filter = null;
+
+ ccs.ColliderDetector.prototype.init.call(this, bone);
+ },
+ init: function (bone) {
+ this._colliderBodyList.length = 0;
+ if (bone)
+ this._bone = bone;
+ this._filter = new ccs.ColliderFilter();
+ return true;
+ },
+
+ /**
+ * add contourData
+ * @param {ccs.ContourData} contourData
+ */
+ addContourData: function (contourData) {
+ var colliderBody = new ccs.ColliderBody(contourData);
+ this._colliderBodyList.push(colliderBody);
+
+ if (ccs.ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX) {
+ var calculatedVertexList = colliderBody.getCalculatedVertexList();
+ var vertexList = contourData.vertexList;
+ for (var i = 0; i < vertexList.length; i++) {
+ var newVertex = new ccs.ContourVertex2(0, 0);
+ calculatedVertexList.push(newVertex);
+ }
+ }
+ },
+
+ /**
+ * add contourData
+ * @param {Array} contourDataList
+ */
+ addContourDataList: function (contourDataList) {
+ for (var i = 0; i < contourDataList.length; i++) {
+ this.addContourData(contourDataList[i]);
+ }
+ },
+
+ /**
+ * remove contourData
+ * @param contourData
+ */
+ removeContourData: function (contourData) {
+ var eraseList = [], i, locBodyList = this._colliderBodyList;
+ for (i = 0; i < locBodyList.length; i++) {
+ var body = locBodyList[i];
+ if (body && body.getContourData() === contourData)
+ eraseList.push(body);
+ }
+
+ for (i=0; igetB2Fixture()->GetShape();
+ shape = colliderBody.getShape();
+ }
+
+ var vs = contourData.vertexList;
+ var cvs = colliderBody.getCalculatedVertexList();
+
+ for (var j = 0; j < vs.length; j++) {
+ locHelpPoint.x = vs[j].x;
+ locHelpPoint.y = vs[j].y;
+ locHelpPoint = cc.pointApplyAffineTransform(locHelpPoint, t);
+
+ if (ccs.ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX) {
+ var v = cc.p(0, 0);
+ v.x = locHelpPoint.x;
+ v.y = locHelpPoint.y;
+ cvs[j] = v;
+ }
+
+ if (shape) {
+ shape.verts[j * 2] = locHelpPoint.x;
+ shape.verts[j * 2 + 1] = locHelpPoint.y;
+ }
+ }
+ if (shape) {
+ for (var j = 0; j < vs.length; j++) {
+ var b = shape.verts[(j + 1) % shape.verts.length];
+ var n = cp.v.normalize(cp.v.perp(cp.v.sub(b, shape.verts[j])));
+
+ if(shape.planes){
+ shape.planes[j].n = n;
+ shape.planes[j].d = cp.v.dot(n, shape.verts[j]);
+ }
+// var b = shape.verts[(i + 1) % shape.numVerts];
+// var n = cp.v.normalize(cp.v.perp(cp.v.sub(b, shape.verts[i])));
+//
+// shape.planes[i].n = n;
+// shape.planes[i].d = cp.v.dot(n, shape.verts[i]);
+ }
+ }
+ }
+ },
+
+ setBody: function (body) {
+ this._body = body;
+ var colliderBody, locBodyList = this._colliderBodyList;
+ for (var i = 0; i < locBodyList.length; i++) {
+ colliderBody = locBodyList[i];
+ var contourData = colliderBody.getContourData(), verts = [];
+ var vs = contourData.vertexList;
+ for (var j = 0; j < vs.length; j++) {
+ var v = vs[j];
+ verts.push(v.x);
+ verts.push(v.y);
+ }
+ var shape = new cp.PolyShape(this._body, verts, cp.vzero);
+ shape.sensor = true;
+ shape.data = this._bone;
+ if (this._active)
+ this._body.space.addShape(shape);
+ colliderBody.setShape(shape);
+ colliderBody.getColliderFilter().updateShape(shape);
+ }
+ },
+
+ getBody: function () {
+ return this._body;
+ }
+});
+
+var _p = ccs.ColliderDetector.prototype;
+
+// Extended properties
+/** @expose */
+_p.colliderFilter;
+cc.defineGetterSetter(_p, "colliderFilter", _p.getColliderFilter, _p.setColliderFilter);
+/** @expose */
+_p.active;
+cc.defineGetterSetter(_p, "active", _p.getActive, _p.setActive);
+/** @expose */
+_p.body;
+cc.defineGetterSetter(_p, "body", _p.getBody, _p.setBody);
+
+_p = null;
+
+ccs.ColliderDetector.create = function (bone) {
+ return new ccs.ColliderDetector(bone);
+};
diff --git a/extensions/cocostudio/armature/utils/CCArmatureDataManager.js b/extensions/cocostudio/armature/utils/CCArmatureDataManager.js
new file mode 100644
index 0000000000..89f06fb2d0
--- /dev/null
+++ b/extensions/cocostudio/armature/utils/CCArmatureDataManager.js
@@ -0,0 +1,325 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+/**
+ * RelativeData uses to save plist files, armature files, animations and textures for armature data manager.
+ * @constructor
+ */
+ccs.RelativeData = function(){
+ this.plistFiles=[];
+ this.armatures=[];
+ this.animations=[];
+ this.textures=[];
+};
+
+/**
+ * ccs.armatureDataManager is a singleton object which format and manage armature configuration and armature animation
+ * @class
+ * @name ccs.armatureDataManager
+ */
+ccs.armatureDataManager = /** @lends ccs.armatureDataManager# */{
+ _animationDatas: {},
+ _armatureDatas: {},
+ _textureDatas: {},
+ _autoLoadSpriteFile: false,
+ _relativeDatas: {},
+
+ s_sharedArmatureDataManager: null,
+
+ /**
+ * Removes armature cache data by configFilePath
+ * @param {String} configFilePath
+ */
+ removeArmatureFileInfo:function(configFilePath){
+ var data = this.getRelativeData(configFilePath);
+ if(data){
+ var i, obj;
+ for (i = 0; i < data.armatures.length; i++) {
+ obj = data.armatures[i];
+ this.removeArmatureData(obj);
+ }
+ for ( i = 0; i < data.animations.length; i++) {
+ obj = data.animations[i];
+ this.removeAnimationData(obj);
+ }
+ for ( i = 0; i < data.textures.length; i++) {
+ obj = data.textures[i];
+ this.removeTextureData(obj);
+ }
+ for ( i = 0; i < data.plistFiles.length; i++) {
+ obj = data.plistFiles[i];
+ cc.spriteFrameCache.removeSpriteFramesFromFile(obj);
+ }
+ delete this._relativeDatas[configFilePath];
+ ccs.dataReaderHelper.removeConfigFile(configFilePath);
+ }
+ },
+
+ /**
+ * Adds armature data
+ * @param {string} id The id of the armature data
+ * @param {ccs.ArmatureData} armatureData
+ */
+ addArmatureData:function (id, armatureData, configFilePath) {
+ var data = this.getRelativeData(configFilePath);
+ if (data){
+ data.armatures.push(id);
+ }
+ this._armatureDatas[id] = armatureData;
+ },
+
+ /**
+ * Gets armatureData by id
+ * @param {String} id
+ * @return {ccs.ArmatureData}
+ */
+ getArmatureData:function (id) {
+ var armatureData = null;
+ if (this._armatureDatas) {
+ armatureData = this._armatureDatas[id];
+ }
+ return armatureData;
+ },
+
+ /**
+ * Removes armature data from armature data manager.
+ * @param {string} id
+ */
+ removeArmatureData:function(id){
+ if (this._armatureDatas[id])
+ delete this._armatureDatas[id];
+ },
+
+ /**
+ * Adds animation data to armature data manager.
+ * @param {String} id
+ * @param {ccs.AnimationData} animationData
+ */
+ addAnimationData:function (id, animationData, configFilePath) {
+ var data = this.getRelativeData(configFilePath);
+ if(data)
+ data.animations.push(id);
+ this._animationDatas[id] = animationData;
+ },
+
+ /**
+ * Gets animationData by id
+ * @param {String} id
+ * @return {ccs.AnimationData}
+ */
+ getAnimationData:function (id) {
+ var animationData = null;
+ if (this._animationDatas[id]) {
+ animationData = this._animationDatas[id];
+ }
+ return animationData;
+ },
+
+ /**
+ * Removes animation data
+ * @param {string} id
+ */
+ removeAnimationData:function(id){
+ if (this._animationDatas[id])
+ delete this._animationDatas[id];
+ },
+
+ /**
+ * Adds texture data to Armature data manager.
+ * @param {String} id
+ * @param {ccs.TextureData} textureData
+ */
+ addTextureData:function (id, textureData, configFilePath) {
+ var data = this.getRelativeData(configFilePath);
+ if (data) {
+ data.textures.push(id);
+ }
+ this._textureDatas[id] = textureData;
+ },
+
+ /**
+ * Gets textureData by id
+ * @param {String} id
+ * @return {ccs.TextureData}
+ */
+ getTextureData:function (id) {
+ var textureData = null;
+ if (this._textureDatas) {
+ textureData = this._textureDatas[id];
+ }
+ return textureData;
+ },
+
+ /**
+ * Removes texture data by id
+ * @param {string} id
+ */
+ removeTextureData:function(id){
+ if (this._textureDatas[id])
+ delete this._textureDatas[id];
+ },
+
+ /**
+ * Adds ArmatureFileInfo, it is managed by CCArmatureDataManager.
+ * @param {String} imagePath
+ * @param {String} plistPath
+ * @param {String} configFilePath
+ * @example
+ * //example1
+ * ccs.armatureDataManager.addArmatureFileInfo("res/test.json");
+ * //example2
+ * ccs.armatureDataManager.addArmatureFileInfo("res/test.png","res/test.plist","res/test.json");
+ */
+ addArmatureFileInfo:function (/*imagePath, plistPath, configFilePath*/) {
+ var imagePath, plistPath, configFilePath;
+ switch(arguments.length){
+ case 1:
+ configFilePath = arguments[0];
+
+ this.addRelativeData(configFilePath);
+
+ this._autoLoadSpriteFile = true;
+ ccs.dataReaderHelper.addDataFromFile(configFilePath);
+ break;
+ case 3:
+ imagePath = arguments[0];
+ plistPath = arguments[1];
+ configFilePath = arguments[2];
+
+ this.addRelativeData(configFilePath);
+
+ this._autoLoadSpriteFile = false;
+ ccs.dataReaderHelper.addDataFromFile(configFilePath);
+ this.addSpriteFrameFromFile(plistPath, imagePath);
+ }
+ },
+
+ /**
+ * Adds ArmatureFileInfo, it is managed by CCArmatureDataManager.
+ * @param {String} imagePath
+ * @param {String} plistPath
+ * @param {String} configFilePath
+ * @param {Function} selector
+ * @param {Object} target
+ */
+ addArmatureFileInfoAsync:function (/*imagePath, plistPath, configFilePath, selector, target*/) {
+ var imagePath, plistPath, configFilePath, target, selector;
+ switch(arguments.length){
+ case 3:
+ configFilePath = arguments[0];
+ target = arguments[2];
+ selector = arguments[1];
+ this.addRelativeData(configFilePath);
+ this._autoLoadSpriteFile = true;
+ ccs.dataReaderHelper.addDataFromFileAsync("", "", configFilePath, selector,target);
+ break;
+ case 5:
+ imagePath = arguments[0];
+ plistPath = arguments[1];
+ configFilePath = arguments[2];
+ target = arguments[4];
+ selector = arguments[3];
+ this.addRelativeData(configFilePath);
+
+ this._autoLoadSpriteFile = false;
+ ccs.dataReaderHelper.addDataFromFileAsync(imagePath, plistPath, configFilePath, selector, target);
+ this.addSpriteFrameFromFile(plistPath, imagePath);
+ }
+ },
+
+ /**
+ * Add sprite frame to CCSpriteFrameCache, it will save display name and it's relative image name
+ * @param {String} plistPath
+ * @param {String} imagePath
+ * @param {String} configFilePath
+ */
+ addSpriteFrameFromFile:function (plistPath, imagePath, configFilePath) {
+ var data = this.getRelativeData(configFilePath);
+ if(data)
+ data.plistFiles.push(plistPath);
+ ccs.spriteFrameCacheHelper.addSpriteFrameFromFile(plistPath, imagePath);
+ },
+
+ /**
+ * Returns whether or not need auto load sprite file
+ * @returns {boolean}
+ */
+ isAutoLoadSpriteFile:function(){
+ return this._autoLoadSpriteFile;
+ },
+
+ /**
+ * Returns armature Data of Armature data manager.
+ * @return {Object}
+ */
+ getArmatureDatas:function () {
+ return this._armatureDatas;
+ },
+
+ /**
+ * Returns animation data of Armature data manager.
+ * @return {Object}
+ */
+ getAnimationDatas:function () {
+ return this._animationDatas;
+ },
+
+ /**
+ * Returns texture data of Armature data manager.
+ * @return {Object}
+ */
+ getTextureDatas:function () {
+ return this._textureDatas;
+ },
+
+ /**
+ * Adds Relative data of Armature data manager.
+ * @param {String} configFilePath
+ */
+ addRelativeData: function (configFilePath) {
+ if (!this._relativeDatas[configFilePath])
+ this._relativeDatas[configFilePath] = new ccs.RelativeData();
+ },
+
+ /**
+ * Gets RelativeData of Armature data manager.
+ * @param {String} configFilePath
+ * @returns {ccs.RelativeData}
+ */
+ getRelativeData: function (configFilePath) {
+ return this._relativeDatas[configFilePath];
+ },
+
+ /**
+ * Clear data
+ */
+ clear: function() {
+ this._animationDatas = {};
+ this._armatureDatas = {};
+ this._textureDatas = {};
+ ccs.spriteFrameCacheHelper.clear();
+ ccs.dataReaderHelper.clear();
+ }
+};
\ No newline at end of file
diff --git a/extensions/cocostudio/armature/utils/CCArmatureDefine.js b/extensions/cocostudio/armature/utils/CCArmatureDefine.js
new file mode 100644
index 0000000000..a7db1b9203
--- /dev/null
+++ b/extensions/cocostudio/armature/utils/CCArmatureDefine.js
@@ -0,0 +1,45 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+/**
+ * @ignore
+ */
+ccs.VERSION_COMBINED = 0.30;
+ccs.VERSION_CHANGE_ROTATION_RANGE = 1.0;
+ccs.VERSION_COLOR_READING = 1.1;
+ccs.MAX_VERTEXZ_VALUE = 5000000.0;
+ccs.ARMATURE_MAX_CHILD = 50.0;
+ccs.ARMATURE_MAX_ZORDER = 100;
+ccs.ARMATURE_MAX_COUNT = ((ccs.MAX_VERTEXZ_VALUE) / (ccs.ARMATURE_MAX_CHILD) / ccs.ARMATURE_MAX_ZORDER);
+ccs.AUTO_ADD_SPRITE_FRAME_NAME_PREFIX = false;
+ccs.ENABLE_PHYSICS_CHIPMUNK_DETECT = false;
+ccs.ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX = false;
+
+/**
+ * Returns the version of Armature.
+ * @returns {string}
+ */
+ccs.armatureVersion = function(){
+ return "v1.1.0.0";
+};
diff --git a/extensions/cocostudio/armature/utils/CCDataReaderHelper.js b/extensions/cocostudio/armature/utils/CCDataReaderHelper.js
new file mode 100644
index 0000000000..77cd0333c9
--- /dev/null
+++ b/extensions/cocostudio/armature/utils/CCDataReaderHelper.js
@@ -0,0 +1,1223 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+/**
+ * @ignore
+ */
+ccs.CONST_VERSION = "version";
+ccs.CONST_VERSION_2_0 = 2.0;
+ccs.CONST_VERSION_COMBINED = 0.3;
+
+ccs.CONST_ARMATURES = "armatures";
+ccs.CONST_ARMATURE = "armature";
+ccs.CONST_BONE = "b";
+ccs.CONST_DISPLAY = "d";
+
+ccs.CONST_ANIMATIONS = "animations";
+ccs.CONST_ANIMATION = "animation";
+ccs.CONST_MOVEMENT = "mov";
+ccs.CONST_FRAME = "f";
+
+ccs.CONST_TEXTURE_ATLAS = "TextureAtlas";
+ccs.CONST_SUB_TEXTURE = "SubTexture";
+
+ccs.CONST_SKELETON = "skeleton";
+
+ccs.CONST_A_NAME = "name";
+ccs.CONST_A_DURATION = "dr";
+ccs.CONST_A_FRAME_INDEX = "fi";
+ccs.CONST_A_DURATION_TO = "to";
+ccs.CONST_A_DURATION_TWEEN = "drTW";
+ccs.CONST_A_LOOP = "lp";
+ccs.CONST_A_MOVEMENT_SCALE = "sc";
+ccs.CONST_A_MOVEMENT_DELAY = "dl";
+ccs.CONST_A_DISPLAY_INDEX = "dI";
+
+ccs.CONST_A_PLIST = "plist";
+
+ccs.CONST_A_PARENT = "parent";
+ccs.CONST_A_SKEW_X = "kX";
+ccs.CONST_A_SKEW_Y = "kY";
+ccs.CONST_A_SCALE_X = "cX";
+ccs.CONST_A_SCALE_Y = "cY";
+ccs.CONST_A_Z = "z";
+ccs.CONST_A_EVENT = "evt";
+ccs.CONST_A_SOUND = "sd";
+ccs.CONST_A_SOUND_EFFECT = "sdE";
+ccs.CONST_A_TWEEN_EASING = "twE";
+ccs.CONST_A_EASING_PARAM = "twEP";
+ccs.CONST_A_TWEEN_ROTATE = "twR";
+ccs.CONST_A_IS_ARMATURE = "isArmature";
+ccs.CONST_A_DISPLAY_TYPE = "displayType";
+ccs.CONST_A_MOVEMENT = "mov";
+
+ccs.CONST_A_X = "x";
+ccs.CONST_A_Y = "y";
+
+ccs.CONST_A_COCOS2DX_X = "cocos2d_x";
+ccs.CONST_A_COCOS2DX_Y = "cocos2d_y";
+
+ccs.CONST_A_WIDTH = "width";
+ccs.CONST_A_HEIGHT = "height";
+ccs.CONST_A_PIVOT_X = "pX";
+ccs.CONST_A_PIVOT_Y = "pY";
+
+ccs.CONST_A_COCOS2D_PIVOT_X = "cocos2d_pX";
+ccs.CONST_A_COCOS2D_PIVOT_Y = "cocos2d_pY";
+
+ccs.CONST_A_BLEND_TYPE = "bd";
+ccs.CONST_A_BLEND_SRC = "bd_src";
+ccs.CONST_A_BLEND_DST = "bd_dst";
+
+ccs.CONST_A_ALPHA = "a";
+ccs.CONST_A_RED = "r";
+ccs.CONST_A_GREEN = "g";
+ccs.CONST_A_BLUE = "b";
+ccs.CONST_A_ALPHA_OFFSET = "aM";
+ccs.CONST_A_RED_OFFSET = "rM";
+ccs.CONST_A_GREEN_OFFSET = "gM";
+ccs.CONST_A_BLUE_OFFSET = "bM";
+ccs.CONST_A_COLOR_TRANSFORM = "colorTransform";
+ccs.CONST_A_TWEEN_FRAME = "tweenFrame";
+
+ccs.CONST_CONTOUR = "con";
+ccs.CONST_CONTOUR_VERTEX = "con_vt";
+
+ccs.CONST_FL_NAN = "NaN";
+
+ccs.CONST_FRAME_DATA = "frame_data";
+ccs.CONST_MOVEMENT_BONE_DATA = "mov_bone_data";
+ccs.CONST_MOVEMENT_DATA = "mov_data";
+ccs.CONST_ANIMATION_DATA = "animation_data";
+ccs.CONST_DISPLAY_DATA = "display_data";
+ccs.CONST_SKIN_DATA = "skin_data";
+ccs.CONST_BONE_DATA = "bone_data";
+ccs.CONST_ARMATURE_DATA = "armature_data";
+ccs.CONST_CONTOUR_DATA = "contour_data";
+ccs.CONST_TEXTURE_DATA = "texture_data";
+ccs.CONST_VERTEX_POINT = "vertex";
+ccs.CONST_COLOR_INFO = "color";
+
+ccs.CONST_CONFIG_FILE_PATH = "config_file_path";
+ccs.CONST_CONTENT_SCALE = "content_scale";
+
+/**
+ * @ignore
+ * @constructor
+ */
+ccs.DataInfo = function () {
+ this.asyncStruct = null;
+ this.configFileQueue = [];
+ this.contentScale = 1;
+ this.filename = "";
+ this.baseFilePath = "";
+ this.flashToolVersion = 0;
+ this.cocoStudioVersion = 0
+};
+
+/**
+ * ccs.dataReaderHelper is a singleton object for reading CocoStudio data
+ * @class
+ * @name ccs.dataReaderHelper
+ */
+ccs.dataReaderHelper = /** @lends ccs.dataReaderHelper# */{
+ ConfigType: {
+ DragonBone_XML: 0,
+ CocoStudio_JSON: 1,
+ CocoStudio_Binary: 2
+ },
+
+ _configFileList: [],
+ _flashToolVersion: ccs.CONST_VERSION_2_0,
+// _cocoStudioVersion: ccs.CONST_VERSION_COMBINED,
+ _positionReadScale: 1,
+ _asyncRefCount: 0,
+ _asyncRefTotalCount: 0,
+
+ _dataQueue: null,
+
+ //LoadData don't need
+
+ setPositionReadScale: function (scale) {
+ this._positionReadScale = scale;
+ },
+
+ getPositionReadScale: function () {
+ return this._positionReadScale;
+ },
+
+ /**
+ * Add armature data from file.
+ * @param {String} filePath
+ */
+ addDataFromFile: function (filePath) {
+ /*
+ * Check if file is already added to ArmatureDataManager, if then return.
+ */
+ if (this._configFileList.indexOf(filePath) !== -1)
+ return;
+ this._configFileList.push(filePath);
+
+ //! find the base file path
+ var basefilePath = this._initBaseFilePath(filePath);
+
+ // Read content from file
+ // Here the reader into the next process
+
+ var str = cc.path.extname(filePath).toLowerCase();
+
+ var dataInfo = new ccs.DataInfo();
+ dataInfo.filename = filePath;
+ dataInfo.basefilePath = basefilePath;
+ if (str === ".xml")
+ ccs.dataReaderHelper.addDataFromXML(filePath, dataInfo);
+ else if (str === ".json" || str === ".exportjson")
+ ccs.dataReaderHelper.addDataFromJson(filePath, dataInfo);
+ else if(str === ".csb")
+ ccs.dataReaderHelper.addDataFromBinaryCache(filePath, dataInfo);
+ },
+
+ /**
+ * Adds data from file with Async.
+ * @param {String} imagePath
+ * @param {String} plistPath
+ * @param {String} filePath
+ * @param {function} selector
+ * @param {Object} [target]
+ */
+ addDataFromFileAsync: function (imagePath, plistPath, filePath, selector, target) {
+ /*
+ * Check if file is already added to ArmatureDataManager, if then return.
+ */
+ if (this._configFileList.indexOf(filePath) !== -1) {
+ if (target && selector) {
+ if (this._asyncRefTotalCount === 0 && this._asyncRefCount === 0)
+ this._asyncCallBack(selector,target, 1);
+ else
+ this._asyncCallBack(selector, target, (this._asyncRefTotalCount - this._asyncRefCount) / this._asyncRefTotalCount);
+ }
+ return;
+ }
+// this._configFileList.push(filePath);
+
+ //! find the base file path
+// var basefilePath = this._initBaseFilePath(filePath);
+
+ this._asyncRefTotalCount++;
+ this._asyncRefCount++;
+ var self = this;
+ var fun = function () {
+ self.addDataFromFile(filePath);
+ self._asyncRefCount--;
+ self._asyncCallBack(selector,target, (self._asyncRefTotalCount - self._asyncRefCount) / self._asyncRefTotalCount);
+ };
+ cc.director.getScheduler().schedule(fun, this, 0.1, false, 0, false, "armatrueDataHelper");
+ },
+
+ /**
+ * Removes config file from config file list.
+ * @param {String} configFile
+ */
+ removeConfigFile: function (configFile) {
+// cc.js.array.remove(this._configFileList, configFile);
+ var locFileList = this._configFileList;
+ var len = locFileList.length;
+ var it = locFileList[len];
+ for (var i = 0;i " + ccs.CONST_ARMATURES + " > " + ccs.CONST_ARMATURE + "");
+ var armatureDataManager = ccs.armatureDataManager, i;
+ for (i = 0; i < armaturesXML.length; i++) {
+ var armatureData = this.decodeArmature(armaturesXML[i], dataInfo);
+ armatureDataManager.addArmatureData(armatureData.name, armatureData, dataInfo.filename);
+ }
+
+ /*
+ * Begin decode animation data from xml
+ */
+ var animationsXML = skeleton.querySelectorAll(ccs.CONST_SKELETON + " > " + ccs.CONST_ANIMATIONS + " > " + ccs.CONST_ANIMATION + "");
+ for (i = 0; i < animationsXML.length; i++) {
+ var animationData = this.decodeAnimation(animationsXML[i], dataInfo);
+ armatureDataManager.addAnimationData(animationData.name, animationData, dataInfo.filename);
+ }
+
+ var texturesXML = skeleton.querySelectorAll(ccs.CONST_SKELETON + " > " + ccs.CONST_TEXTURE_ATLAS + " > " + ccs.CONST_SUB_TEXTURE + "");
+ for (i = 0; i < texturesXML.length; i++) {
+ var textureData = this.decodeTexture(texturesXML[i], dataInfo);
+ armatureDataManager.addTextureData(textureData.name, textureData, dataInfo.filename);
+ }
+ },
+
+ /**
+ * decode xml armature data.
+ * @param {XMLDocument} armatureXML
+ * @param {ccs.DataInfo} dataInfo
+ * @returns {ccs.ArmatureData}
+ */
+ decodeArmature: function (armatureXML, dataInfo) {
+ var armatureData = new ccs.ArmatureData();
+ armatureData.init();
+ armatureData.name = armatureXML.getAttribute(ccs.CONST_A_NAME);
+
+ var bonesXML = armatureXML.querySelectorAll(ccs.CONST_ARMATURE + " > " + ccs.CONST_BONE);
+
+ for (var i = 0; i < bonesXML.length; i++) {
+ /*
+ * If this bone have parent, then get the parent bone xml
+ */
+ var boneXML = bonesXML[i];
+ var parentName = boneXML.getAttribute(ccs.CONST_A_PARENT);
+ var parentXML = null;
+ if (parentName) {
+ //parentXML = armatureXML.querySelectorAll(ccs.CONST_ARMATURE+" > "+ccs.CONST_BONE);
+ for (var j = 0; j < bonesXML.length; j++) {
+ parentXML = bonesXML[j];
+ if (parentName == bonesXML[j].getAttribute(ccs.CONST_A_NAME)) {
+ //todo
+ break;
+ }
+ }
+ }
+ var boneData = this.decodeBone(boneXML, parentXML, dataInfo);
+ armatureData.addBoneData(boneData);
+ }
+ return armatureData;
+ },
+
+ /**
+ * decode json armature data.
+ * @param {Object} json
+ * @param {ccs.DataInfo} dataInfo
+ * @returns {ccs.ArmatureData}
+ */
+ decodeArmatureFromJSON: function (json, dataInfo) {
+ var armatureData = new ccs.ArmatureData();
+ armatureData.init();
+
+ var name = json[ccs.CONST_A_NAME];
+ if (name) {
+ armatureData.name = name;
+ }
+
+ dataInfo.cocoStudioVersion = armatureData.dataVersion = json[ccs.CONST_VERSION] || 0.1;
+
+ var boneDataList = json[ccs.CONST_BONE_DATA];
+ for (var i = 0; i < boneDataList.length; i++) {
+ var boneData = this.decodeBoneFromJson(boneDataList[i], dataInfo);
+ armatureData.addBoneData(boneData);
+ }
+ return armatureData;
+ },
+
+ /**
+ * decode xml bone data.
+ * @param {XMLDocument} boneXML
+ * @param {XMLDocument} parentXML
+ * @param {ccs.DataInfo} dataInfo
+ * @returns {ccs.BoneData}
+ */
+ decodeBone: function (boneXML, parentXML, dataInfo) {
+ var boneData = new ccs.BoneData();
+ boneData.init();
+
+ boneData.name = boneXML.getAttribute(ccs.CONST_A_NAME);
+ boneData.parentName = boneXML.getAttribute(ccs.CONST_A_PARENT) || "";
+
+ boneData.zOrder = parseInt(boneXML.getAttribute(ccs.CONST_A_Z)) || 0;
+
+ var displaysXML = boneXML.querySelectorAll(ccs.CONST_BONE + " > " + ccs.CONST_DISPLAY);
+ for (var i = 0; i < displaysXML.length; i++) {
+ var displayXML = displaysXML[i];
+ var displayData = this.decodeBoneDisplay(displayXML, dataInfo);
+ boneData.addDisplayData(displayData);
+ }
+ return boneData;
+ },
+
+ /**
+ * decode json bone data.
+ * @param {Object} json json bone data.
+ * @param {ccs.DataInfo} dataInfo
+ * @returns {ccs.BoneData}
+ */
+ decodeBoneFromJson: function (json, dataInfo) {
+ var boneData = new ccs.BoneData();
+ boneData.init();
+
+ this.decodeNodeFromJson(boneData, json, dataInfo);
+
+ boneData.name = json[ccs.CONST_A_NAME] || "";
+
+ boneData.parentName = json[ccs.CONST_A_PARENT] || "";
+ var displayDataList = json[ccs.CONST_DISPLAY_DATA] || [];
+ for (var i = 0; i < displayDataList.length; i++) {
+ var locDisplayData = this.decodeBoneDisplayFromJson(displayDataList[i], dataInfo);
+ boneData.addDisplayData(locDisplayData);
+ }
+ return boneData;
+ },
+
+ /**
+ * decode xml display data of bone
+ * @param {XMLDocument} displayXML
+ * @param {ccs.DataInfo} dataInfo
+ * @returns {ccs.DisplayData}
+ */
+ decodeBoneDisplay: function (displayXML, dataInfo) {
+ var isArmature = parseFloat(displayXML.getAttribute(ccs.CONST_A_IS_ARMATURE)) || 0;
+ var displayData = null;
+
+ if (isArmature === 1) {
+ displayData = new ccs.ArmatureDisplayData();
+ displayData.displayType = ccs.DISPLAY_TYPE_ARMATURE;
+ } else {
+ displayData = new ccs.SpriteDisplayData();
+ displayData.displayType = ccs.DISPLAY_TYPE_SPRITE;
+ }
+
+ var displayName = displayXML.getAttribute(ccs.CONST_A_NAME) || "";
+ if (displayName) {
+ displayData.displayName = displayName;
+ }
+ return displayData;
+ },
+
+ /**
+ * Decodes json display data of bone.
+ * @param {Object} json
+ * @param {ccs.DataInfo} dataInfo
+ * @returns {ccs.DisplayData}
+ */
+ decodeBoneDisplayFromJson: function (json, dataInfo) {
+ var displayType = json[ccs.CONST_A_DISPLAY_TYPE] || ccs.DISPLAY_TYPE_SPRITE;
+ var displayData = null;
+
+ switch (displayType) {
+ case ccs.DISPLAY_TYPE_SPRITE:
+ displayData = new ccs.SpriteDisplayData();
+
+ var name = json[ccs.CONST_A_NAME];
+ if(name != null){
+ displayData.displayName = name;
+ }
+
+ var dicArray = json[ccs.CONST_SKIN_DATA] || [];
+ var dic = dicArray[0];
+ if (dic) {
+ var skinData = displayData.skinData;
+ skinData.x = dic[ccs.CONST_A_X] * this._positionReadScale;
+ skinData.y = dic[ccs.CONST_A_Y] * this._positionReadScale;
+ skinData.scaleX = dic[ccs.CONST_A_SCALE_X] == null ? 1 : dic[ccs.CONST_A_SCALE_X];
+ skinData.scaleY = dic[ccs.CONST_A_SCALE_Y] == null ? 1 : dic[ccs.CONST_A_SCALE_Y];
+ skinData.skewX = dic[ccs.CONST_A_SKEW_X] == null ? 1 : dic[ccs.CONST_A_SKEW_X];
+ skinData.skewY = dic[ccs.CONST_A_SKEW_Y] == null ? 1 : dic[ccs.CONST_A_SKEW_Y];
+
+ skinData.x *= dataInfo.contentScale;
+ skinData.y *= dataInfo.contentScale;
+ }
+ break;
+ case ccs.DISPLAY_TYPE_ARMATURE:
+ displayData = new ccs.ArmatureDisplayData();
+ var name = json[ccs.CONST_A_NAME];
+ if(name != null){
+ displayData.displayName = json[ccs.CONST_A_NAME];
+ }
+ break;
+ case ccs.DISPLAY_TYPE_PARTICLE:
+ displayData = new ccs.ParticleDisplayData();
+ var plist = json[ccs.CONST_A_PLIST];
+ if(plist != null){
+ if(dataInfo.asyncStruct){
+ displayData.displayName = dataInfo.asyncStruct.basefilePath + plist;
+ }else{
+ displayData.displayName = dataInfo.basefilePath + plist;
+ }
+ }
+ break;
+ default:
+ displayData = new ccs.SpriteDisplayData();
+ break;
+ }
+ displayData.displayType = displayType;
+ return displayData;
+ },
+
+ /**
+ * Decodes xml animation data.
+ * @param {XMLDocument} animationXML
+ * @param {ccs.DataInfo} dataInfo
+ * @returns {ccs.AnimationData}
+ */
+ decodeAnimation: function (animationXML, dataInfo) {
+ var aniData = new ccs.AnimationData();
+ var name = animationXML.getAttribute(ccs.CONST_A_NAME);
+ var armatureData = ccs.armatureDataManager.getArmatureData(name);
+ aniData.name = name;
+
+ var movementsXML = animationXML.querySelectorAll(ccs.CONST_ANIMATION + " > " + ccs.CONST_MOVEMENT);
+ var movementXML = null;
+
+ for (var i = 0; i < movementsXML.length; i++) {
+ movementXML = movementsXML[i];
+ var movementData = this.decodeMovement(movementXML, armatureData, dataInfo);
+ aniData.addMovement(movementData);
+ }
+ return aniData;
+ },
+
+ /**
+ * Decodes animation json data.
+ * @param {Object} json
+ * @param {ccs.DataInfo} dataInfo
+ * @returns {ccs.AnimationData}
+ */
+ decodeAnimationFromJson: function (json, dataInfo) {
+ var aniData = new ccs.AnimationData();
+ var name = json[ccs.CONST_A_NAME];
+ if(name){
+ aniData.name = json[ccs.CONST_A_NAME];
+ }
+
+ var movementDataList = json[ccs.CONST_MOVEMENT_DATA] || [];
+ for (var i = 0; i < movementDataList.length; i++) {
+ var locMovementData = this.decodeMovementFromJson(movementDataList[i], dataInfo);
+ aniData.addMovement(locMovementData);
+ }
+ return aniData;
+ },
+
+ /**
+ * Decodes xml movement data.
+ * @param {XMLDocument} movementXML
+ * @param {ccs.ArmatureData} armatureData
+ * @param {ccs.DataInfo} dataInfo
+ * @returns {ccs.MovementData}
+ */
+ decodeMovement: function (movementXML, armatureData, dataInfo) {
+ var movementData = new ccs.MovementData();
+ movementData.name = movementXML.getAttribute(ccs.CONST_A_NAME);
+
+ var duration, durationTo, durationTween, loop, tweenEasing = 0;
+
+ duration = movementXML.getAttribute(ccs.CONST_A_DURATION);
+ movementData.duration = duration == null ? 0 : parseFloat(duration);
+
+ durationTo = movementXML.getAttribute(ccs.CONST_A_DURATION_TO);
+ movementData.durationTo = durationTo == null ? 0 : parseFloat(durationTo);
+
+ durationTween = movementXML.getAttribute(ccs.CONST_A_DURATION_TWEEN);
+ movementData.durationTween = durationTween == null ? 0 : parseFloat(durationTween);
+
+ loop = movementXML.getAttribute(ccs.CONST_A_LOOP);
+ movementData.loop = loop ? Boolean(parseFloat(loop)) : true;
+
+ var easing = movementXML.getAttribute(ccs.CONST_A_TWEEN_EASING);
+ if (easing) {
+ if (easing != ccs.CONST_FL_NAN) {
+ tweenEasing = easing == null ? 0 : parseFloat(easing);
+ movementData.tweenEasing = tweenEasing === 2 ? ccs.TweenType.SINE_EASEINOUT : tweenEasing;
+ } else
+ movementData.tweenEasing = ccs.TweenType.LINEAR;
+ }
+
+ var movBonesXml = movementXML.querySelectorAll(ccs.CONST_MOVEMENT + " > " + ccs.CONST_BONE);
+ var movBoneXml = null;
+ for (var i = 0; i < movBonesXml.length; i++) {
+ movBoneXml = movBonesXml[i];
+ var boneName = movBoneXml.getAttribute(ccs.CONST_A_NAME);
+
+ if (movementData.getMovementBoneData(boneName))
+ continue;
+
+ var boneData = armatureData.getBoneData(boneName);
+ var parentName = boneData.parentName;
+
+ var parentXML = null;
+ if (parentName !== "") {
+ for (var j = 0; j < movBonesXml.length; j++) {
+ parentXML = movBonesXml[j];
+ if (parentName === parentXML.getAttribute(ccs.CONST_A_NAME))
+ break;
+ }
+ }
+ var moveBoneData = this.decodeMovementBone(movBoneXml, parentXML, boneData, dataInfo);
+ movementData.addMovementBoneData(moveBoneData);
+ }
+ return movementData;
+ },
+
+ /**
+ * Decodes json movement data.
+ * @param {Object} json
+ * @param {ccs.DataInfo} dataInfo
+ * @returns {ccs.MovementData}
+ */
+ decodeMovementFromJson: function (json, dataInfo) {
+ var movementData = new ccs.MovementData();
+
+ movementData.loop = json[ccs.CONST_A_LOOP] == null ? false : json[ccs.CONST_A_LOOP];
+ movementData.durationTween = json[ccs.CONST_A_DURATION_TWEEN] || 0;
+ movementData.durationTo = json[ccs.CONST_A_DURATION_TO] || 0;
+ movementData.duration = json[ccs.CONST_A_DURATION] || 0;
+
+ if(json[ccs.CONST_A_DURATION] == null){
+ movementData.scale = 1;
+ }else{
+ movementData.scale = json[ccs.CONST_A_MOVEMENT_SCALE] == null ? 1 : json[ccs.CONST_A_MOVEMENT_SCALE];
+ }
+
+ movementData.tweenEasing = json[ccs.CONST_A_TWEEN_EASING] == null ? ccs.TweenType.LINEAR : json[ccs.CONST_A_TWEEN_EASING];
+ var name = json[ccs.CONST_A_NAME];
+ if(name)
+ movementData.name = name;
+
+ var movementBoneList = json[ccs.CONST_MOVEMENT_BONE_DATA] || [];
+ for (var i = 0; i < movementBoneList.length; i++) {
+ var locMovementBoneData = this.decodeMovementBoneFromJson(movementBoneList[i], dataInfo);
+ movementData.addMovementBoneData(locMovementBoneData);
+ }
+ return movementData;
+ },
+
+ /**
+ * Decodes xml data of bone's movement.
+ * @param {XMLDocument} movBoneXml
+ * @param {XMLDocument} parentXml
+ * @param {ccs.BoneData} boneData
+ * @param {ccs.DataInfo} dataInfo
+ * @returns {ccs.MovementBoneData}
+ */
+ decodeMovementBone: function (movBoneXml, parentXml, boneData, dataInfo) {
+ var movBoneData = new ccs.MovementBoneData();
+ movBoneData.init();
+
+ var scale, delay;
+ if (movBoneXml) {
+ scale = parseFloat(movBoneXml.getAttribute(ccs.CONST_A_MOVEMENT_SCALE)) || 0;
+ movBoneData.scale = scale;
+
+ delay = parseFloat(movBoneXml.getAttribute(ccs.CONST_A_MOVEMENT_DELAY)) || 0;
+ if (delay > 0)
+ delay -= 1;
+ movBoneData.delay = delay;
+ }
+
+ var length = 0, parentTotalDuration = 0,currentDuration = 0;
+ var parentFrameXML = null,parentXMLList = [];
+
+ /*
+ * get the parent frame xml list, we need get the origin data
+ */
+ if (parentXml != null) {
+ var parentFramesXML = parentXml.querySelectorAll(ccs.CONST_BONE + " > " + ccs.CONST_FRAME);
+ for (var i = 0; i < parentFramesXML.length; i++)
+ parentXMLList.push(parentFramesXML[i]);
+ length = parentXMLList.length;
+ }
+
+ movBoneData.name = movBoneXml.getAttribute(ccs.CONST_A_NAME);
+
+ var framesXML = movBoneXml.querySelectorAll(ccs.CONST_BONE + " > " + ccs.CONST_FRAME);
+
+ var j = 0, totalDuration = 0;
+ for (var ii = 0; ii < framesXML.length; ii++) {
+ var frameXML = framesXML[ii];
+ if (parentXml) {
+ /*
+ * in this loop we get the corresponding parent frame xml
+ */
+ while (j < length && (parentFrameXML ? (totalDuration < parentTotalDuration || totalDuration >= parentTotalDuration + currentDuration) : true)) {
+ parentFrameXML = parentXMLList[j];
+ parentTotalDuration += currentDuration;
+ currentDuration = parseFloat(parentFrameXML.getAttribute(ccs.CONST_A_DURATION));
+ j++;
+ }
+ }
+ var boneFrameData = this.decodeFrame(frameXML, parentFrameXML, boneData, dataInfo);
+ movBoneData.addFrameData(boneFrameData);
+ boneFrameData.frameID = totalDuration;
+ totalDuration += boneFrameData.duration;
+ movBoneData.duration = totalDuration;
+ }
+
+ //Change rotation range from (-180 -- 180) to (-infinity -- infinity)
+ var frames = movBoneData.frameList, pi = Math.PI;
+ for (var i = frames.length - 1; i >= 0; i--) {
+ if (i > 0) {
+ var difSkewX = frames[i].skewX - frames[i - 1].skewX;
+ var difSkewY = frames[i].skewY - frames[i - 1].skewY;
+
+ if (difSkewX < -pi || difSkewX > pi) {
+ frames[i - 1].skewX = difSkewX < 0 ? frames[i - 1].skewX - 2 * pi : frames[i - 1].skewX + 2 * pi;
+ }
+
+ if (difSkewY < -pi || difSkewY > pi) {
+ frames[i - 1].skewY = difSkewY < 0 ? frames[i - 1].skewY - 2 * pi : frames[i - 1].skewY + 2 * pi;
+ }
+ }
+ }
+
+ var frameData = new ccs.FrameData();
+ frameData.copy(movBoneData.frameList[movBoneData.frameList.length - 1]);
+ frameData.frameID = movBoneData.duration;
+ movBoneData.addFrameData(frameData);
+ return movBoneData;
+ },
+
+ /**
+ * Decodes json data of bone's movement.
+ * @param {Object} json
+ * @param {ccs.DataInfo} dataInfo
+ * @returns {ccs.MovementBoneData}
+ */
+ decodeMovementBoneFromJson: function (json, dataInfo) {
+ var movementBoneData = new ccs.MovementBoneData();
+ movementBoneData.init();
+ movementBoneData.delay = json[ccs.CONST_A_MOVEMENT_DELAY] || 0;
+
+ var name = json[ccs.CONST_A_NAME];
+ if(name)
+ movementBoneData.name = name;
+
+ var framesData = json[ccs.CONST_FRAME_DATA] || [];
+ var length = framesData.length;
+ for (var i = 0; i < length; i++) {
+ var dic = json[ccs.CONST_FRAME_DATA][i];
+ var frameData = this.decodeFrameFromJson(dic, dataInfo);
+ movementBoneData.addFrameData(frameData);
+
+ if (dataInfo.cocoStudioVersion < ccs.CONST_VERSION_COMBINED){
+ frameData.frameID = movementBoneData.duration;
+ movementBoneData.duration += frameData.duration;
+ }
+ }
+
+ if (dataInfo.cocoStudioVersion < ccs.VERSION_CHANGE_ROTATION_RANGE) {
+ //! Change rotation range from (-180 -- 180) to (-infinity -- infinity)
+ var frames = movementBoneData.frameList;
+ var pi = Math.PI;
+ for (var i = frames.length - 1; i >= 0; i--) {
+ if (i > 0) {
+ var difSkewX = frames[i].skewX - frames[i - 1].skewX;
+ var difSkewY = frames[i].skewY - frames[i - 1].skewY;
+
+ if (difSkewX < -pi || difSkewX > pi) {
+ frames[i - 1].skewX = difSkewX < 0 ? frames[i - 1].skewX - 2 * pi : frames[i - 1].skewX + 2 * pi;
+ }
+
+ if (difSkewY < -pi || difSkewY > pi) {
+ frames[i - 1].skewY = difSkewY < 0 ? frames[i - 1].skewY - 2 * pi : frames[i - 1].skewY + 2 * pi;
+ }
+ }
+ }
+ }
+
+ if (dataInfo.cocoStudioVersion < ccs.CONST_VERSION_COMBINED) {
+ if (movementBoneData.frameList.length > 0) {
+ var frameData = new ccs.FrameData();
+ frameData.copy(movementBoneData.frameList[movementBoneData.frameList.length - 1]);
+ movementBoneData.addFrameData(frameData);
+ frameData.frameID = movementBoneData.duration;
+ }
+ }
+ return movementBoneData;
+ },
+
+ /**
+ * Decodes xml data of frame.
+ * @param {XMLDocument} frameXML
+ * @param {XMLDocument} parentFrameXml
+ * @param {ccs.BoneData} boneData
+ * @param {ccs.DataInfo} dataInfo
+ * @returns {ccs.FrameData}
+ */
+ decodeFrame: function (frameXML, parentFrameXml, boneData, dataInfo) {
+ var x = 0, y = 0, scale_x = 0, scale_y = 0, skew_x = 0, skew_y = 0, tweenRotate = 0;
+ var duration = 0, displayIndex = 0, zOrder = 0, tweenEasing = 0, blendType = 0;
+
+ var frameData = new ccs.FrameData();
+ frameData.strMovement = frameXML.getAttribute(ccs.CONST_A_MOVEMENT) || "";
+ frameData.movement = frameData.strMovement;
+ frameData.strEvent = frameXML.getAttribute(ccs.CONST_A_EVENT) || "";
+ frameData.event = frameData.strEvent;
+ frameData.strSound = frameXML.getAttribute(ccs.CONST_A_SOUND) || "";
+ frameData.sound = frameData.strSound;
+ frameData.strSoundEffect = frameXML.getAttribute(ccs.CONST_A_SOUND_EFFECT) || "";
+ frameData.soundEffect = frameData.strSoundEffect;
+
+ var isTween = frameXML.getAttribute(ccs.CONST_A_TWEEN_FRAME);
+ frameData.isTween = !(isTween != undefined && isTween === "false");
+
+ if (dataInfo.flashToolVersion >= ccs.CONST_VERSION_2_0) {
+ x = frameXML.getAttribute(ccs.CONST_A_COCOS2DX_X);
+ if(x){
+ frameData.x = parseFloat(x);
+ frameData.x *= this._positionReadScale;
+ }
+ y = frameXML.getAttribute(ccs.CONST_A_COCOS2DX_Y);
+ if(y){
+ frameData.y = -parseFloat(y);
+ frameData.y *= this._positionReadScale;
+ }
+ } else {
+ x = frameXML.getAttribute(ccs.CONST_A_X);
+ if(x) {
+ frameData.x = parseFloat(x);
+ frameData.x *= this._positionReadScale;
+ }
+ y = frameXML.getAttribute(ccs.CONST_A_Y);
+ if(y) {
+ frameData.y = -parseFloat(y);
+ frameData.y *= this._positionReadScale;
+ }
+ }
+
+ scale_x = frameXML.getAttribute(ccs.CONST_A_SCALE_X);
+ if( scale_x != null )
+ frameData.scaleX = parseFloat(scale_x);
+ scale_y = frameXML.getAttribute(ccs.CONST_A_SCALE_Y);
+ if( scale_y != null )
+ frameData.scaleY = parseFloat(scale_y);
+ skew_x = frameXML.getAttribute(ccs.CONST_A_SKEW_X);
+ if( skew_x != null )
+ frameData.skewX = cc.degreesToRadians(parseFloat(skew_x));
+ skew_y = frameXML.getAttribute(ccs.CONST_A_SKEW_Y);
+ if( skew_y != null )
+ frameData.skewY = cc.degreesToRadians(-parseFloat(skew_y));
+
+ duration = frameXML.getAttribute(ccs.CONST_A_DURATION);
+ if( duration != null )
+ frameData.duration = parseFloat(duration);
+ displayIndex = frameXML.getAttribute(ccs.CONST_A_DISPLAY_INDEX);
+ if( displayIndex != null )
+ frameData.displayIndex = parseFloat(displayIndex);
+ zOrder = frameXML.getAttribute(ccs.CONST_A_Z);
+ if( zOrder != null )
+ frameData.zOrder = parseInt(zOrder);
+ tweenRotate = frameXML.getAttribute(ccs.CONST_A_TWEEN_ROTATE);
+ if( tweenRotate != null )
+ frameData.tweenRotate = parseFloat(tweenRotate);
+
+ blendType = frameXML.getAttribute(ccs.CONST_A_BLEND_TYPE);
+ if ( blendType != null ) {
+ var blendFunc = frameData.blendFunc;
+ switch (blendType) {
+ case ccs.BLEND_TYPE_NORMAL:
+ blendFunc.src = cc.BLEND_SRC;
+ blendFunc.dst = cc.BLEND_DST;
+ break;
+ case ccs.BLEND_TYPE_ADD:
+ blendFunc.src = cc.SRC_ALPHA;
+ blendFunc.dst = cc.ONE;
+ break;
+ case ccs.BLEND_TYPE_MULTIPLY:
+ blendFunc.src = cc.DST_COLOR;
+ blendFunc.dst = cc.ONE_MINUS_SRC_ALPHA;
+ break;
+ case ccs.BLEND_TYPE_SCREEN:
+ blendFunc.src = cc.ONE;
+ blendFunc.dst = cc.ONE_MINUS_DST_COLOR;
+ break;
+ default:
+ frameData.blendFunc.src = cc.BLEND_SRC;
+ frameData.blendFunc.dst = cc.BLEND_DST;
+ break;
+ }
+ }
+
+ var colorTransformXML = frameXML.querySelectorAll(ccs.CONST_FRAME + " > " + ccs.CONST_A_COLOR_TRANSFORM);
+ if (colorTransformXML && colorTransformXML.length > 0) {
+ colorTransformXML = colorTransformXML[0];
+ var alpha, red, green, blue;
+ var alphaOffset, redOffset, greenOffset, blueOffset;
+
+ alpha = parseFloat(colorTransformXML.getAttribute(ccs.CONST_A_ALPHA)) || 0;
+ red = parseFloat(colorTransformXML.getAttribute(ccs.CONST_A_RED)) || 0;
+ green = parseFloat(colorTransformXML.getAttribute(ccs.CONST_A_GREEN)) || 0;
+ blue = parseFloat(colorTransformXML.getAttribute(ccs.CONST_A_BLUE)) || 0;
+
+ alphaOffset = parseFloat(colorTransformXML.getAttribute(ccs.CONST_A_ALPHA_OFFSET)) || 0;
+ redOffset = parseFloat(colorTransformXML.getAttribute(ccs.CONST_A_RED_OFFSET)) || 0;
+ greenOffset = parseFloat(colorTransformXML.getAttribute(ccs.CONST_A_GREEN_OFFSET)) || 0;
+ blueOffset = parseFloat(colorTransformXML.getAttribute(ccs.CONST_A_BLUE_OFFSET)) || 0;
+
+ frameData.a = 2.55 * alphaOffset + alpha;
+ frameData.r = 2.55 * redOffset + red;
+ frameData.g = 2.55 * greenOffset + green;
+ frameData.b = 2.55 * blueOffset + blue;
+
+ frameData.isUseColorInfo = true;
+ }
+
+ var _easing = frameXML.getAttribute(ccs.CONST_A_TWEEN_EASING);
+ if(_easing != null) {
+ if(_easing != ccs.CONST_FL_NAN){
+ tweenEasing = frameXML.getAttribute(ccs.CONST_A_TWEEN_EASING);
+ if( tweenEasing )
+ frameData.tweenEasing = (tweenEasing === 2) ? ccs.TweenType.SINE_EASEINOUT : tweenEasing;
+ } else
+ frameData.tweenEasing = ccs.TweenType.LINEAR;
+ }
+
+ if (parentFrameXml) {
+ //* recalculate frame data from parent frame data, use for translate matrix
+ var helpNode = new ccs.BaseData();
+ if (dataInfo.flashToolVersion >= ccs.CONST_VERSION_2_0) {
+ helpNode.x = parseFloat(parentFrameXml.getAttribute(ccs.CONST_A_COCOS2DX_X));
+ helpNode.y = parseFloat(parentFrameXml.getAttribute(ccs.CONST_A_COCOS2DX_Y));
+ } else {
+ helpNode.x = parseFloat(parentFrameXml.getAttribute(ccs.CONST_A_X));
+ helpNode.y = parseFloat(parentFrameXml.getAttribute(ccs.CONST_A_Y));
+ }
+ helpNode.skewX = parseFloat(parentFrameXml.getAttribute(ccs.CONST_A_SKEW_X));
+ helpNode.skewY = parseFloat(parentFrameXml.getAttribute(ccs.CONST_A_SKEW_Y));
+
+ helpNode.y = -helpNode.y;
+ helpNode.skewX = cc.degreesToRadians(helpNode.skewX);
+ helpNode.skewY = cc.degreesToRadians(-helpNode.skewY);
+ ccs.TransformHelp.transformFromParent(frameData, helpNode);
+ }
+ return frameData;
+ },
+
+ /**
+ * Decodes json data of frame.
+ * @param {Object} json
+ * @param {ccs.DataInfo} dataInfo
+ * @returns {ccs.FrameData}
+ */
+ decodeFrameFromJson: function (json, dataInfo) {
+ var frameData = new ccs.FrameData();
+
+ this.decodeNodeFromJson(frameData, json, dataInfo);
+
+ frameData.tweenEasing = json[ccs.CONST_A_TWEEN_EASING] || ccs.TweenType.LINEAR;
+ frameData.displayIndex = json[ccs.CONST_A_DISPLAY_INDEX];
+ var bd_src = json[ccs.CONST_A_BLEND_SRC] == null ? cc.BLEND_SRC : json[ccs.CONST_A_BLEND_SRC];
+ var bd_dst = json[ccs.CONST_A_BLEND_DST] == null ? cc.BLEND_DST : json[ccs.CONST_A_BLEND_DST];
+ frameData.blendFunc.src = bd_src;
+ frameData.blendFunc.dst = bd_dst;
+ frameData.isTween = json[ccs.CONST_A_TWEEN_FRAME] == null ? true : json[ccs.CONST_A_TWEEN_FRAME];
+
+ var event = json[ccs.CONST_A_EVENT];
+ if(event != null){
+ frameData.strEvent = event;
+ frameData.event = event;
+ }
+
+ if (dataInfo.cocoStudioVersion < ccs.CONST_VERSION_COMBINED)
+ frameData.duration = json[ccs.CONST_A_DURATION] == null ? 1 : json[ccs.CONST_A_DURATION];
+ else
+ frameData.frameID = json[ccs.CONST_A_FRAME_INDEX];
+
+ var twEPs = json[ccs.CONST_A_EASING_PARAM] || [];
+ for (var i = 0; i < twEPs.length; i++) {
+ frameData.easingParams[i] = twEPs[i];
+ }
+
+ return frameData;
+ },
+
+ /**
+ * Decodes xml data of texture
+ * @param {XMLDocument} textureXML
+ * @param {ccs.DataInfo} dataInfo
+ * @returns {ccs.TextureData}
+ */
+ decodeTexture: function (textureXML, dataInfo) {
+ var textureData = new ccs.TextureData();
+ textureData.init();
+
+ if (textureXML.getAttribute(ccs.CONST_A_NAME)) {
+ textureData.name = textureXML.getAttribute(ccs.CONST_A_NAME);
+ }
+
+ var px, py;
+
+ if (dataInfo.flashToolVersion >= ccs.CONST_VERSION_2_0) {
+ px = parseFloat(textureXML.getAttribute(ccs.CONST_A_COCOS2D_PIVOT_X)) || 0;
+ py = parseFloat(textureXML.getAttribute(ccs.CONST_A_COCOS2D_PIVOT_Y)) || 0;
+ } else {
+ px = parseFloat(textureXML.getAttribute(ccs.CONST_A_PIVOT_X)) || 0;
+ py = parseFloat(textureXML.getAttribute(ccs.CONST_A_PIVOT_Y)) || 0;
+ }
+
+ var width = parseFloat(textureXML.getAttribute(ccs.CONST_A_WIDTH)) || 0;
+ var height = parseFloat(textureXML.getAttribute(ccs.CONST_A_HEIGHT)) || 0;
+
+ var anchorPointX = px / width;
+ var anchorPointY = (height - py) / height;
+
+ textureData.pivotX = anchorPointX;
+ textureData.pivotY = anchorPointY;
+
+ var contoursXML = textureXML.querySelectorAll(ccs.CONST_SUB_TEXTURE + " > " + ccs.CONST_CONTOUR);
+ for (var i = 0; i < contoursXML.length; i++) {
+ textureData.addContourData(this.decodeContour(contoursXML[i], dataInfo));
+ }
+ return textureData;
+ },
+
+ /**
+ * Decodes json data of Texture.
+ * @param json
+ * @returns {ccs.TextureData}
+ */
+ decodeTextureFromJson: function (json) {
+ var textureData = new ccs.TextureData();
+ textureData.init();
+
+ var name = json[ccs.CONST_A_NAME];
+ if(name != null)
+ textureData.name = name;
+
+ textureData.width = json[ccs.CONST_A_WIDTH] || 0;
+ textureData.height = json[ccs.CONST_A_HEIGHT] || 0;
+ textureData.pivotX = json[ccs.CONST_A_PIVOT_X] || 0;
+ textureData.pivotY = json[ccs.CONST_A_PIVOT_Y] || 0;
+
+ var contourDataList = json[ccs.CONST_CONTOUR_DATA] || [];
+ for (var i = 0; i < contourDataList.length; i++) {
+ textureData.contourDataList.push(this.decodeContourFromJson(contourDataList[i]));
+ }
+ return textureData;
+ },
+
+ /**
+ * Decodes xml data of contour.
+ * @param {XMLDocument} contourXML
+ * @param {ccs.DataInfo} dataInfo
+ * @returns {ccs.ContourData}
+ */
+ decodeContour: function (contourXML, dataInfo) {
+ var contourData = new ccs.ContourData();
+ contourData.init();
+
+ var vertexDatasXML = contourXML.querySelectorAll(ccs.CONST_CONTOUR + " > " + ccs.CONST_CONTOUR_VERTEX);
+ var vertexDataXML;
+ for (var i = 0; i < vertexDatasXML.length; i++) {
+ vertexDataXML = vertexDatasXML[i];
+ var vertex = cc.p(0, 0);
+ vertex.x = parseFloat(vertexDataXML.getAttribute(ccs.CONST_A_X)) || 0;
+ vertex.y = parseFloat(vertexDataXML.getAttribute(ccs.CONST_A_Y)) || 0;
+
+ vertex.y = - vertex.y;
+ contourData.vertexList.push(vertex);
+ }
+ return contourData;
+ },
+
+ /**
+ * Decodes json data of contour.
+ * @param {Object} json
+ * @returns {ccs.ContourData}
+ */
+ decodeContourFromJson: function (json) {
+ var contourData = new ccs.ContourData();
+ contourData.init();
+
+ var vertexPointList = json[ccs.CONST_VERTEX_POINT] || [];
+ var len = vertexPointList.length;
+ for (var i = 0; i < len; i++) {
+ var dic = vertexPointList[i];
+ var vertex = cc.p(0, 0);
+ vertex.x = dic[ccs.CONST_A_X] || 0;
+ vertex.y = dic[ccs.CONST_A_Y] || 0;
+ contourData.vertexList.push(vertex);
+ }
+ return contourData;
+ },
+
+ /**
+ * Adds json armature data to armature data manager.
+ * @param {Object} dic json armature data
+ * @param {ccs.DataInfo} dataInfo
+ */
+ addDataFromJsonCache: function (dic, dataInfo) {
+ dataInfo.contentScale = dic[ccs.CONST_CONTENT_SCALE] == null ? 1 : dic[ccs.CONST_CONTENT_SCALE];
+
+ // Decode armatures
+ var armatureDataArr = dic[ccs.CONST_ARMATURE_DATA] || [], i;
+ var armatureData;
+ for (i = 0; i < armatureDataArr.length; i++) {
+ armatureData = this.decodeArmatureFromJSON(armatureDataArr[i], dataInfo);
+ ccs.armatureDataManager.addArmatureData(armatureData.name, armatureData, dataInfo.filename);
+ }
+
+ // Decode animations
+ var animationDataArr = dic[ccs.CONST_ANIMATION_DATA] || [];
+ var animationData;
+ for (i = 0; i < animationDataArr.length; i++) {
+ animationData = this.decodeAnimationFromJson(animationDataArr[i], dataInfo);
+ ccs.armatureDataManager.addAnimationData(animationData.name, animationData, dataInfo.filename);
+ }
+
+ // Decode textures
+ var textureDataArr = dic[ccs.CONST_TEXTURE_DATA] || [];
+ var textureData;
+ for (i = 0; i < textureDataArr.length; i++) {
+ textureData = this.decodeTextureFromJson(textureDataArr[i], dataInfo);
+ ccs.armatureDataManager.addTextureData(textureData.name, textureData, dataInfo.filename);
+ }
+
+ // Auto load sprite file
+ var autoLoad = dataInfo.asyncStruct == null ? ccs.armatureDataManager.isAutoLoadSpriteFile() : dataInfo.asyncStruct.autoLoadSpriteFile;
+// if (isLoadSpriteFrame) {
+ if (autoLoad) {
+ var configFiles = dic[ccs.CONST_CONFIG_FILE_PATH] || [];
+ var locFilePath, locPos, locPlistPath, locImagePath;
+ for (i = 0; i < configFiles.length; i++) {
+ locFilePath = configFiles[i];
+ locPos = locFilePath.lastIndexOf(".");
+ locFilePath = locFilePath.substring(0, locPos);
+ locPlistPath = dataInfo.basefilePath + locFilePath + ".plist";
+ locImagePath = dataInfo.basefilePath + locFilePath + ".png";
+ ccs.armatureDataManager.addSpriteFrameFromFile(locPlistPath, locImagePath, dataInfo.filename);
+ }
+ }
+
+ armatureData = null;
+ animationData = null;
+ },
+
+ /**
+ * Decodes json data of node.
+ * @param node
+ * @param json
+ * @param dataInfo
+ */
+ decodeNodeFromJson: function (node, json, dataInfo) {
+ node.x = json[ccs.CONST_A_X] * this._positionReadScale;
+ node.y = json[ccs.CONST_A_Y] * this._positionReadScale;
+
+ node.x *= dataInfo.contentScale;
+ node.y *= dataInfo.contentScale;
+
+ node.zOrder = json[ccs.CONST_A_Z];
+
+ node.skewX = json[ccs.CONST_A_SKEW_X] || 0;
+ node.skewY = json[ccs.CONST_A_SKEW_Y] || 0;
+ node.scaleX = json[ccs.CONST_A_SCALE_X] == null ? 1 : json[ccs.CONST_A_SCALE_X];
+ node.scaleY = json[ccs.CONST_A_SCALE_Y] == null ? 1 : json[ccs.CONST_A_SCALE_Y];
+
+ var colorDic;
+ if (dataInfo.cocoStudioVersion < ccs.VERSION_COLOR_READING) {
+ colorDic = json[0];
+ if (colorDic){
+ node.a = colorDic[ccs.CONST_A_ALPHA] == null ? 255 : colorDic[ccs.CONST_A_ALPHA];
+ node.r = colorDic[ccs.CONST_A_RED] == null ? 255 : colorDic[ccs.CONST_A_RED];
+ node.g = colorDic[ccs.CONST_A_GREEN] == null ? 255 : colorDic[ccs.CONST_A_GREEN];
+ node.b = colorDic[ccs.CONST_A_BLUE] == null ? 255 : colorDic[ccs.CONST_A_BLUE];
+ node.isUseColorInfo = true;
+ }
+ } else {
+ colorDic = json[ccs.CONST_COLOR_INFO] || null;
+ if (colorDic){
+ node.a = colorDic[ccs.CONST_A_ALPHA] == null ? 255 : colorDic[ccs.CONST_A_ALPHA];
+ node.r = colorDic[ccs.CONST_A_RED] == null ? 255 : colorDic[ccs.CONST_A_RED];
+ node.g = colorDic[ccs.CONST_A_GREEN] == null ? 255 : colorDic[ccs.CONST_A_GREEN];
+ node.b = colorDic[ccs.CONST_A_BLUE] == null ? 255 : colorDic[ccs.CONST_A_BLUE];
+ node.isUseColorInfo = true;
+ }
+ }
+ },
+
+ clear: function () {
+ this._configFileList = [];
+ this._asyncRefCount = 0;
+ this._asyncRefTotalCount = 0;
+ },
+
+ _asyncCallBack: function (selector, target, percent) {
+ if(selector && cc.js.isFunction(selector))
+ selector.call(target, percent);
+ if(target && selector && typeof selector === 'string')
+ target[selector](percent);
+ },
+ /**
+ * find the base file path
+ * @param filePath
+ * @returns {String}
+ * @private
+ */
+ _initBaseFilePath: function (filePath) {
+ var path = filePath;
+ var pos = path.lastIndexOf("/");
+ if (pos > -1)
+ path = path.substr(0, pos + 1);
+ else
+ path = "";
+ return path;
+ },
+
+ /**
+ * Adds xml armature data to armature data manager.
+ * @param {XMLDocument} xml
+ * @param {ccs.DataInfo} dataInfo
+ */
+ addDataFromXML: function (xml, dataInfo) {
+ /*
+ * Need to get the full path of the xml file, or the Tiny XML can't find the xml at IOS
+ */
+ var xmlStr = cc.loader.getRes(xml);
+ if (!xmlStr) throw new Error("Please load the resource first : " + xml);
+ var skeletonXML = cc.saxParser.parse(xmlStr);
+ var skeleton = skeletonXML.documentElement;
+ if (skeleton)
+ this.addDataFromCache(skeleton, dataInfo);
+ },
+
+ /**
+ * Adds json armature data to armature data manager.
+ * @param {String} filePath
+ * @param {ccs.DataInfo} dataInfo
+ */
+ addDataFromJson: function (filePath, dataInfo) {
+ var fileContent = cc.loader.getRes(filePath);
+ this.addDataFromJsonCache(fileContent, dataInfo);
+ }
+};
diff --git a/extensions/cocostudio/armature/utils/CCSpriteFrameCacheHelper.js b/extensions/cocostudio/armature/utils/CCSpriteFrameCacheHelper.js
new file mode 100644
index 0000000000..a0496e96a7
--- /dev/null
+++ b/extensions/cocostudio/armature/utils/CCSpriteFrameCacheHelper.js
@@ -0,0 +1,68 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+/**
+ * ccs.spriteFrameCacheHelper is a singleton object, it's a sprite frame cache helper
+ * @class
+ * @name ccs.spriteFrameCacheHelper
+ */
+ccs.spriteFrameCacheHelper = /** @lends ccs.spriteFrameCacheHelper# */ {
+ _textureAtlasDic:{},
+ _imagePaths:[],
+
+ /**
+ * Adds sprite frame from file
+ * @param plistPath
+ * @param imagePath
+ */
+ addSpriteFrameFromFile:function (plistPath, imagePath) {
+ cc.spriteFrameCache.addSpriteFrames(plistPath, imagePath);
+ },
+
+ /**
+ * Returns texture atlas with texture.
+ * @param texture
+ * @returns {*}
+ */
+ getTextureAtlasWithTexture:function (texture) {
+ //todo
+ return null;
+ var textureName = texture.getName();
+ var atlas = this._textureAtlasDic[textureName];
+ if (atlas == null) {
+ atlas = new cc.TextureAtlas(texture, 20);
+ this._textureAtlasDic[textureName] = atlas;
+ }
+ return atlas;
+ },
+
+ /**
+ * Clear the sprite frame cache's data.
+ */
+ clear: function () {
+ this._textureAtlasDic = {};
+ this._imagePaths = [];
+ }
+};
\ No newline at end of file
diff --git a/extensions/cocostudio/armature/utils/CCTransformHelp.js b/extensions/cocostudio/armature/utils/CCTransformHelp.js
new file mode 100644
index 0000000000..0d6228d5cd
--- /dev/null
+++ b/extensions/cocostudio/armature/utils/CCTransformHelp.js
@@ -0,0 +1,183 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+/**
+ * use to calculate the matrix of node from parent node
+ * @class ccs.TransformHelp
+ * @extend ccs.Class
+ */
+ccs.TransformHelp = ccs.TransformHelp || ccs.Class.extend({});
+
+ccs.TransformHelp.helpMatrix1 = cc.affineTransformMake(1, 0, 0, 1, 0, 0);
+ccs.TransformHelp.helpMatrix2 = cc.affineTransformMake(1, 0, 0, 1, 0, 0);
+ccs.TransformHelp.helpPoint1 = cc.p(0, 0);
+ccs.TransformHelp.helpPoint2 = cc.p(0, 0);
+ccs.TransformHelp.helpParentNode = {};
+
+/**
+ * Calculate a BaseData's transform matrix from parent node.
+ * @function
+ * @static
+ * @param {ccs.BaseData} bone
+ * Constructor
+ */
+ccs.TransformHelp.transformFromParent = function (bone, parentNode) {
+ this.nodeToMatrix(bone, this.helpMatrix1);
+ this.nodeToMatrix(parentNode, this.helpMatrix2);
+
+ this.helpMatrix2 = cc.affineTransformInvert(this.helpMatrix2);
+ this.helpMatrix1 = cc.affineTransformConcat(this.helpMatrix1, this.helpMatrix2);
+
+ this.matrixToNode(this.helpMatrix1, bone);
+};
+
+ccs.TransformHelp.transformToParent = function(node, parentNode){
+ this.nodeToMatrix(node, this.helpMatrix1);
+ this.nodeToMatrix(parentNode, this.helpMatrix2);
+
+ this.helpMatrix1 = cc.affineTransformConcat(this.helpMatrix1, this.helpMatrix2);
+
+ this.matrixToNode(this.helpMatrix1, node);
+};
+
+ccs.TransformHelp.transformFromParentWithoutScale = function(node, parentNode){
+// this.helpParentNode.copy(&parentNode);
+
+ for(var p in parentNode){
+ this.helpParentNode[p] = parentNode[p];
+ }
+ this.helpParentNode.scaleX = 1;
+ this.helpParentNode.scaleY = 1;
+
+ this.nodeToMatrix(node, this.helpMatrix1);
+ this.nodeToMatrix(this.helpParentNode, this.helpMatrix2);
+
+ this.helpMatrix2 = cc.affineTransformInvert(this.helpMatrix2);
+ this.helpMatrix1 = cc.affineTransformConcat(this.helpMatrix1, this.helpMatrix2);
+
+ this.matrixToNode(this.helpMatrix1, node);
+};
+
+ccs.TransformHelp.transformToParentWithoutScale = function(node, parentNode){
+ for(var p in parentNode){
+ this.helpParentNode[p] = parentNode[p];
+ }
+ this.helpParentNode.scaleX = 1;
+ this.helpParentNode.scaleY = 1;
+
+ this.nodeToMatrix(node, this.helpMatrix1);
+ this.nodeToMatrix(this.helpParentNode, this.helpMatrix2);
+
+ this.helpMatrix1 = cc.affineTransformConcat(this.helpMatrix1, this.helpMatrix2);
+
+ this.matrixToNode(this.helpMatrix1, node);
+
+};
+
+/**
+ * @function
+ * @static
+ * @param {ccs.BaseData} node
+ * @param {cc.AffineTransform} matrix
+ */
+ccs.TransformHelp.nodeToMatrix = function (node, matrix) {
+ if (node.skewX === -node.skewY) {
+ var sine = Math.sin(node.skewX);
+ var cosine = Math.cos(node.skewX);
+ matrix.a = node.scaleX * cosine;
+ matrix.b = node.scaleX * -sine;
+ matrix.c = node.scaleY * sine;
+ matrix.d = node.scaleY * cosine;
+ } else {
+ matrix.a = node.scaleX * Math.cos(node.skewY);
+ matrix.b = node.scaleX * Math.sin(node.skewY);
+ matrix.c = node.scaleY * Math.sin(node.skewX);
+ matrix.d = node.scaleY * Math.cos(node.skewX);
+ }
+ matrix.tx = node.x;
+ matrix.ty = node.y;
+};
+
+/**
+ * @function
+ * @static
+ * @param {cc.AffineTransform} matrix
+ * @param {ccs.BaseData} node
+ */
+ccs.TransformHelp.matrixToNode = function (matrix, node) {
+ /*
+ * In as3 language, there is a function called "deltaTransformPoint", it calculate a point used give Transform
+ * but not used the tx, ty value. we simulate the function here
+ */
+ this.helpPoint1.x = 0;
+ this.helpPoint1.y = 1;
+ this.helpPoint1 = cc.pointApplyAffineTransform(this.helpPoint1, matrix);
+ this.helpPoint1.x -= matrix.tx;
+ this.helpPoint1.y -= matrix.ty;
+
+ this.helpPoint2.x = 1;
+ this.helpPoint2.y = 0;
+ this.helpPoint2 = cc.pointApplyAffineTransform(this.helpPoint2, matrix);
+ this.helpPoint2.x -= matrix.tx;
+ this.helpPoint2.y -= matrix.ty;
+
+ node.skewX = -(Math.atan2(this.helpPoint1.y, this.helpPoint1.x) - 1.5707964); //todo
+ //node.skewX = -Math.atan2(this.helpPoint2.y, this.helpPoint2.x);
+ node.skewY = Math.atan2(this.helpPoint2.y, this.helpPoint2.x);
+ node.scaleX = Math.sqrt(matrix.a * matrix.a + matrix.b * matrix.b);
+ node.scaleY = Math.sqrt(matrix.c * matrix.c + matrix.d * matrix.d);
+ node.x = matrix.tx;
+ node.y = matrix.ty;
+};
+
+/**
+ * @function
+ * @static
+ * @param {ccs.BaseData} target
+ * @param {ccs.BaseData} source
+ */
+ccs.TransformHelp.nodeConcat = function (target, source) {
+ target.x += source.x;
+ target.y += source.y;
+ target.skewX += source.skewX;
+ target.skewY += source.skewY;
+ target.scaleX += source.scaleX;
+ target.scaleY += source.scaleY;
+};
+
+/**
+ * @function
+ * @static
+ * @param {ccs.BaseData} target
+ * @param {ccs.BaseData} source
+ */
+ccs.TransformHelp.nodeSub = function (target, source) {
+ target.x -= source.x;
+ target.y -= source.y;
+ target.skewX -= source.skewX;
+ target.skewY -= source.skewY;
+ target.scaleX -= source.scaleX;
+ target.scaleY -= source.scaleY;
+};
\ No newline at end of file
diff --git a/extensions/cocostudio/armature/utils/CCTweenFunction.js b/extensions/cocostudio/armature/utils/CCTweenFunction.js
new file mode 100644
index 0000000000..7ced7fad96
--- /dev/null
+++ b/extensions/cocostudio/armature/utils/CCTweenFunction.js
@@ -0,0 +1,501 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+/**
+ * TweenType
+ * @type Object
+ */
+ccs.TweenType = {
+ CUSTOM_EASING: -1,
+ LINEAR: 0,
+
+ SINE_EASEIN: 1,
+ SINE_EASEOUT: 2,
+ SINE_EASEINOUT: 3,
+
+ QUAD_EASEIN: 4,
+ QUAD_EASEOUT: 5,
+ QUAD_EASEINOUT: 6,
+
+ CUBIC_EASEIN: 7,
+ CUBIC_EASEOUT: 8,
+ CUBIC_EASEINOUT: 9,
+
+ QUART_EASEIN: 10,
+ QUART_EASEOUT: 11,
+ QUART_EASEINOUT: 12,
+
+ QUINT_EASEIN: 13,
+ QUINT_EASEOUT: 14,
+ QUINT_EASEINOUT: 15,
+
+ EXPO_EASEIN: 16,
+ EXPO_EASEOUT: 17,
+ EXPO_EASEINOUT: 18,
+
+ CIRC_EASEIN: 19,
+ CIRC_EASEOUT: 20,
+ CIRC_EASEINOUT: 21,
+
+ ELASTIC_EASEIN: 22,
+ ELASTIC_EASEOUT: 23,
+ ELASTIC_EASEINOUT: 24,
+
+ BACK_EASEIN: 25,
+ BACK_EASEOUT: 26,
+ BACK_EASEINOUT: 27,
+
+ BOUNCE_EASEIN: 28,
+ BOUNCE_EASEOUT: 29,
+ BOUNCE_EASEINOUT: 30,
+
+ TWEEN_EASING_MAX: 10000
+};
+
+ccs.TweenFunction = ccs.TweenFunction || ccs.Class.extend({});
+
+ccs.DOUBLE_PI = ccs.M_PI_X_2 = Math.PI * 2;
+ccs.HALF_PI = ccs.M_PI_2 = Math.PI / 2;
+ccs.M_PI = Math.PI;
+
+ccs.TweenFunction.tweenTo = function (time, type, easingParam) {
+ var delta = 0;
+
+ switch (type) {
+ case ccs.TweenType.CUSTOM_EASING:
+ delta = this.customEase(time, easingParam);
+ break;
+ case ccs.TweenType.LINEAR:
+ delta = this.linear(time);
+ break;
+ case ccs.TweenType.SINE_EASEIN:
+ delta = this.sineEaseIn(time);
+ break;
+ case ccs.TweenType.SINE_EASEOUT:
+ delta = this.sineEaseOut(time);
+ break;
+ case ccs.TweenType.SINE_EASEINOUT:
+ delta = this.sineEaseInOut(time);
+ break;
+
+ case ccs.TweenType.QUAD_EASEIN:
+ delta = this.quadEaseIn(time);
+ break;
+ case ccs.TweenType.QUAD_EASEOUT:
+ delta = this.quadEaseOut(time);
+ break;
+ case ccs.TweenType.QUAD_EASEINOUT:
+ delta = this.quadEaseInOut(time);
+ break;
+
+ case ccs.TweenType.CUBIC_EASEIN:
+ delta = this.cubicEaseIn(time);
+ break;
+ case ccs.TweenType.CUBIC_EASEOUT:
+ delta = this.cubicEaseOut(time);
+ break;
+ case ccs.TweenType.CUBIC_EASEINOUT:
+ delta = this.cubicEaseInOut(time);
+ break;
+
+ case ccs.TweenType.QUART_EASEIN:
+ delta = this.quartEaseIn(time);
+ break;
+ case ccs.TweenType.QUART_EASEOUT:
+ delta = this.quartEaseOut(time);
+ break;
+ case ccs.TweenType.QUART_EASEINOUT:
+ delta = this.quartEaseInOut(time);
+ break;
+
+ case ccs.TweenType.QUINT_EASEIN:
+ delta = this.quintEaseIn(time);
+ break;
+ case ccs.TweenType.QUINT_EASEOUT:
+ delta = this.quintEaseOut(time);
+ break;
+ case ccs.TweenType.QUINT_EASEINOUT:
+ delta = this.quintEaseInOut(time);
+ break;
+
+ case ccs.TweenType.EXPO_EASEIN:
+ delta = this.expoEaseIn(time);
+ break;
+ case ccs.TweenType.EXPO_EASEOUT:
+ delta = this.expoEaseOut(time);
+ break;
+ case ccs.TweenType.EXPO_EASEINOUT:
+ delta = this.expoEaseInOut(time);
+ break;
+
+ case ccs.TweenType.CIRC_EASEIN:
+ delta = this.circEaseIn(time);
+ break;
+ case ccs.TweenType.CIRC_EASEOUT:
+ delta = this.circEaseOut(time);
+ break;
+ case ccs.TweenType.CIRC_EASEINOUT:
+ delta = this.circEaseInOut(time);
+ break;
+
+ case ccs.TweenType.ELASTIC_EASEIN:
+ var period = 0.3;
+ if(null != easingParam && easingParam.length > 0){
+ period = easingParam[0];
+ }
+ delta = this.elasticEaseIn(time, period);
+ break;
+ case ccs.TweenType.ELASTIC_EASEOUT:
+ var period = 0.3;
+ if(null != easingParam && easingParam.length > 0){
+ period = easingParam[0];
+ }
+ delta = this.elasticEaseOut(time, period);
+ break;
+ case ccs.TweenType.ELASTIC_EASEINOUT:
+ var period = 0.3;
+ if(null != easingParam && easingParam.length > 0){
+ period = easingParam[0];
+ }
+ delta = this.elasticEaseInOut(time, period);
+ break;
+
+ case ccs.TweenType.BACK_EASEIN:
+ delta = this.backEaseIn(time);
+ break;
+ case ccs.TweenType.BACK_EASEOUT:
+ delta = this.backEaseOut(time);
+ break;
+ case ccs.TweenType.BACK_EASEINOUT:
+ delta = this.backEaseInOut(time);
+ break;
+
+ case ccs.TweenType.BOUNCE_EASEIN:
+ delta = this.bounceEaseIn(time);
+ break;
+ case ccs.TweenType.BOUNCE_EASEOUT:
+ delta = this.bounceEaseOut(time);
+ break;
+ case ccs.TweenType.BOUNCE_EASEINOUT:
+ delta = this.bounceEaseInOut(time);
+ break;
+
+ default:
+ delta = this.sineEaseInOut(time);
+ break;
+ }
+
+ return delta;
+};
+
+
+// Linear
+ccs.TweenFunction.linear = function (time) {
+ return time;
+};
+
+
+// Sine Ease
+ccs.TweenFunction.sineEaseIn = function (time) {
+ return -1 * Math.cos(time * ccs.HALF_PI) + 1;
+};
+ccs.TweenFunction.sineEaseOut = function (time) {
+ return Math.sin(time * ccs.HALF_PI);
+};
+ccs.TweenFunction.sineEaseInOut = function (time) {
+ return -0.5 * (Math.cos(ccs.M_PI * time) - 1);
+};
+
+
+// Quad Ease
+ccs.TweenFunction.quadEaseIn = function (time) {
+ return time * time;
+};
+ccs.TweenFunction.quadEaseOut = function (time) {
+ return -1 * time * (time - 2);
+};
+ccs.TweenFunction.quadEaseInOut = function (time) {
+ time = time * 2;
+ if (time < 1)
+ return 0.5 * time * time;
+ --time;
+ return -0.5 * (time * (time - 2) - 1);
+};
+
+
+// Cubic Ease
+ccs.TweenFunction.cubicEaseIn = function (time) {
+ return time * time * time;
+};
+ccs.TweenFunction.cubicEaseOut = function (time) {
+ time -= 1;
+ return (time * time * time + 1);
+};
+ccs.TweenFunction.cubicEaseInOut = function (time) {
+ time = time * 2;
+ if (time < 1)
+ return 0.5 * time * time * time;
+ time -= 2;
+ return 0.5 * (time * time * time + 2);
+};
+
+
+// Quart Ease
+ccs.TweenFunction.quartEaseIn = function (time) {
+ return time * time * time * time;
+};
+ccs.TweenFunction.quartEaseOut = function (time) {
+ time -= 1;
+ return -(time * time * time * time - 1);
+};
+ccs.TweenFunction.quartEaseInOut = function (time) {
+ time = time * 2;
+ if (time < 1)
+ return 0.5 * time * time * time * time;
+ time -= 2;
+ return -0.5 * (time * time * time * time - 2);
+};
+
+
+// Quint Ease
+ccs.TweenFunction.quintEaseIn = function (time) {
+ return time * time * time * time * time;
+};
+ccs.TweenFunction.quintEaseOut = function (time) {
+ time -= 1;
+ return (time * time * time * time * time + 1);
+};
+ccs.TweenFunction.quintEaseInOut = function (time) {
+ time = time * 2;
+ if (time < 1)
+ return 0.5 * time * time * time * time * time;
+ time -= 2;
+ return 0.5 * (time * time * time * time * time + 2);
+};
+
+
+// Expo Ease
+ccs.TweenFunction.expoEaseIn = function (time) {
+ return time === 0 ? 0 : Math.pow(2, 10 * (time - 1)) - 0.001;
+};
+ccs.TweenFunction.expoEaseOut = function (time) {
+ return time === 1 ? 1 : (-Math.pow(2, -10 * time) + 1);
+};
+ccs.TweenFunction.expoEaseInOut = function (time) {
+ time /= 0.5;
+ if (time < 1) {
+ time = 0.5 * Math.pow(2, 10 * (time - 1));
+ }
+ else {
+ time = 0.5 * (-Math.pow(2, -10 * (time - 1)) + 2);
+ }
+
+ return time;
+};
+
+
+// Circ Ease
+ccs.TweenFunction.circEaseIn = function (time) {
+ return -1 * (Math.sqrt(1 - time * time) - 1);
+};
+ccs.TweenFunction.circEaseOut = function (time) {
+ time = time - 1;
+ return Math.sqrt(1 - time * time);
+};
+ccs.TweenFunction.circEaseInOut = function (time) {
+ time = time * 2;
+ if (time < 1)
+ return -0.5 * (Math.sqrt(1 - time * time) - 1);
+ time -= 2;
+ return 0.5 * (Math.sqrt(1 - time * time) + 1);
+};
+
+
+// Elastic Ease
+ccs.TweenFunction.elasticEaseIn = function (time, easingParam) {
+ var period = 0.3;
+
+ if (easingParam.length > 0) {
+ period = easingParam[0];
+ }
+
+ var newT = 0;
+ if (time === 0 || time === 1) {
+ newT = time;
+ }
+ else {
+ var s = period / 4;
+ time = time - 1;
+ newT = -Math.pow(2, 10 * time) * Math.sin((time - s) * ccs.DOUBLE_PI / period);
+ }
+
+ return newT;
+};
+ccs.TweenFunction.elasticEaseOut = function (time, easingParam) {
+ var period = 0.3;
+
+ if (easingParam.length > 0) {
+ period = easingParam[0];
+ }
+
+ var newT = 0;
+ if (time === 0 || time === 1) {
+ newT = time;
+ }
+ else {
+ var s = period / 4;
+ newT = Math.pow(2, -10 * time) * Math.sin((time - s) * ccs.DOUBLE_PI / period) + 1;
+ }
+
+ return newT;
+};
+ccs.TweenFunction.elasticEaseInOut = function (time, easingParam) {
+ var period = 0.3;
+
+ if (easingParam.length > 0) {
+ period = easingParam[0];
+ }
+
+ var newT = 0;
+ if (time === 0 || time === 1) {
+ newT = time;
+ }
+ else {
+ time = time * 2;
+ if (!period) {
+ period = 0.3 * 1.5;
+ }
+
+ var s = period / 4;
+
+ time = time - 1;
+ if (time < 0) {
+ newT = -0.5 * Math.pow(2, 10 * time) * Math.sin((time - s) * ccs.DOUBLE_PI / period);
+ } else {
+ newT = Math.pow(2, -10 * time) * Math.sin((time - s) * ccs.DOUBLE_PI / period) * 0.5 + 1;
+ }
+ }
+ return newT;
+};
+
+
+// Back Ease
+ccs.TweenFunction.backEaseIn = function (time) {
+ var overshoot = 1.70158;
+ return time * time * ((overshoot + 1) * time - overshoot);
+};
+ccs.TweenFunction.backEaseOut = function (time) {
+ var overshoot = 1.70158;
+
+ time = time - 1;
+ return time * time * ((overshoot + 1) * time + overshoot) + 1;
+};
+ccs.TweenFunction.backEaseInOut = function (time) {
+ var overshoot = 1.70158 * 1.525;
+
+ time = time * 2;
+ if (time < 1) {
+ return (time * time * ((overshoot + 1) * time - overshoot)) / 2;
+ }
+ else {
+ time = time - 2;
+ return (time * time * ((overshoot + 1) * time + overshoot)) / 2 + 1;
+ }
+};
+
+
+// Bounce Ease
+ccs.bounceTime = function (time) {
+ if (time < 1 / 2.75) {
+ return 7.5625 * time * time;
+ } else if (time < 2 / 2.75) {
+ time -= 1.5 / 2.75;
+ return 7.5625 * time * time + 0.75;
+ } else if (time < 2.5 / 2.75) {
+ time -= 2.25 / 2.75;
+ return 7.5625 * time * time + 0.9375;
+ }
+
+ time -= 2.625 / 2.75;
+ return 7.5625 * time * time + 0.984375;
+};
+ccs.TweenFunction.bounceEaseIn = function (time) {
+ return 1 - ccs.bounceTime(1 - time);
+};
+
+ccs.TweenFunction.bounceEaseOut = function (time) {
+ return ccs.bounceTime(time);
+};
+
+ccs.TweenFunction.bounceEaseInOut = function (time) {
+ var newT = 0;
+ if (time < 0.5) {
+ time = time * 2;
+ newT = (1 - ccs.bounceTime(1 - time)) * 0.5;
+ } else {
+ newT = ccs.bounceTime(time * 2 - 1) * 0.5 + 0.5;
+ }
+
+ return newT;
+};
+
+
+// Custom Ease
+ccs.TweenFunction.customEase = function (time, easingParam) {
+ if (easingParam.length > 0) {
+ var tt = 1 - time;
+ return easingParam[1] * tt * tt * tt + 3 * easingParam[3] * time * tt * tt + 3 * easingParam[5] * time * time * tt + easingParam[7] * time * time * time;
+ }
+ return time;
+};
+
+ccs.TweenFunction.easeIn = function(time, rate){
+ return Math.pow(time, rate);
+};
+
+ccs.TweenFunction.easeOut = function(time, rate){
+ return Math.pow(time, 1 / rate);
+};
+
+ccs.TweenFunction.easeInOut = function(time, rate){
+ time *= 2;
+ if(time < 1){
+ return 0.5 * Math.pow(time, rate);
+ }else{
+ return 1 - 0.5 * Math.pow(2 - time, rate);
+ }
+};
+
+ccs.TweenFunction.quadraticIn = function(time){
+ return Math.pow(time, 2);
+};
+
+ccs.TweenFunction.quadraticOut = function(time){
+ return -time * (time - 2);
+};
+
+ccs.TweenFunction.bezieratFunction = 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 );
+};
\ No newline at end of file
diff --git a/extensions/cocostudio/armature/utils/CCUtilMath.js b/extensions/cocostudio/armature/utils/CCUtilMath.js
new file mode 100644
index 0000000000..082ec35b12
--- /dev/null
+++ b/extensions/cocostudio/armature/utils/CCUtilMath.js
@@ -0,0 +1,69 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+var ENABLE_PHYSICS_DETECT = false;
+ccs.fmodf = function (x, y) {
+ while (x > y) {
+ x -= y;
+ }
+ return x;
+};
+var CC_SAFE_RELEASE = function (obj) {
+ if (obj && obj.release) {
+ obj.release();
+ }
+};
+
+ccs.isSpriteContainPoint = function (sprite, point, outPoint) {
+ var p = sprite.convertToNodeSpace(point);
+ if (outPoint) {
+ outPoint.x = p.x;
+ outPoint.y = p.y;
+ }
+ var s = sprite.getContentSize();
+ return cc.rectContainsPoint(cc.rect(0, 0, s.width, s.height), p);
+};
+ccs.SPRITE_CONTAIN_POINT = ccs.isSpriteContainPoint;
+ccs.SPRITE_CONTAIN_POINT_WITH_RETURN = ccs.isSpriteContainPoint;
+
+ccs.extBezierTo = function (t, point1, point2, point3, point4) {
+ var p = cc.p(0, 0);
+ if (point3 && !point4) {
+ p.x = Math.pow((1 - t), 2) * point1.x + 2 * t * (1 - t) * point2.x + Math.pow(t, 2) * point3.x;
+ p.y = Math.pow((1 - t), 2) * point1.y + 2 * t * (1 - t) * point2.y + Math.pow(t, 2) * point3.y;
+ }
+ if (point4) {
+ p.x = point1.x * Math.pow((1 - t), 3) + 3 * t * point2.x * Math.pow((1 - t), 2) + 3 * point3.x * Math.pow(t, 2) * (1 - t) + point4.x * Math.pow(t, 3);
+ p.y = point1.y * Math.pow((1 - t), 3) + 3 * t * point2.y * Math.pow((1 - t), 2) + 3 * point3.y * Math.pow(t, 2) * (1 - t) + point4.y * Math.pow(t, 3);
+ }
+ return p;
+};
+
+ccs.extCircleTo = function (t, center, radius, fromRadian, radianDif) {
+ var p = cc.p(0, 0);
+ p.x = center.x + radius * Math.cos(fromRadian + radianDif * t);
+ p.y = center.y + radius * Math.sin(fromRadian + radianDif * t);
+ return p;
+};
\ No newline at end of file
diff --git a/extensions/cocostudio/components/CCComAttribute.js b/extensions/cocostudio/components/CCComAttribute.js
new file mode 100644
index 0000000000..303cd08ff6
--- /dev/null
+++ b/extensions/cocostudio/components/CCComAttribute.js
@@ -0,0 +1,210 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+/**
+ * The attribute component for Cocostudio.
+ * @class
+ * @extends ccs.Component
+ */
+ccs.ComAttribute = ccs.Component.extend(/** @lends ccs.ComAttribute# */{
+ _jsonDict: null,
+ _filePath: "",
+
+ /**
+ * Construction of ccs.ComAttribute
+ */
+ ctor: function () {
+ cc._Component.prototype.ctor.call(this);
+ this._jsonDict = {};
+ this._filePath = "";
+ this._name = "CCComAttribute";
+ ccs.ComAttribute.prototype.init.call(this);
+ },
+
+ /**
+ * Initializes a ccs.ComAttribute
+ * @returns {boolean}
+ */
+ init: function () {
+ this._jsonDict = {};
+ return true;
+ },
+
+ /**
+ * Sets int attribute
+ * @param {String} key
+ * @param {number} value
+ */
+ setInt: function (key, value) {
+ if (!key) {
+ cc.log("Argument must be non-nil");
+ return;
+ }
+ this._jsonDict[key] = value;
+ },
+
+ /**
+ * Sets double attribute
+ * @param {String} key
+ * @param {number} value
+ */
+ setDouble: function (key, value) {
+ if (!key) {
+ cc.log("Argument must be non-nil");
+ return;
+ }
+ this._jsonDict[key] = value;
+ },
+
+ /**
+ * Sets float attribute
+ * @param {String} key
+ * @param {number} value
+ */
+ setFloat: function (key, value) {
+ if (!key) {
+ cc.log("Argument must be non-nil");
+ return;
+ }
+ this._jsonDict[key] = value;
+ },
+
+ /**
+ * Sets boolean attribute
+ * @param {String} key
+ * @param {Boolean} value
+ */
+ setBool: function (key, value) {
+ if (!key) {
+ cc.log("Argument must be non-nil");
+ return;
+ }
+ this._jsonDict[key] = value;
+ },
+
+ /**
+ * Sets string attribute
+ * @param {String} key
+ * @param {Boolean} value
+ */
+ setString: function (key, value) {
+ if (!key) {
+ cc.log("Argument must be non-nil");
+ return;
+ }
+ this._jsonDict[key] = value;
+ },
+
+ /**
+ * Sets object attribute
+ * @param {String} key
+ * @param {Object} value
+ */
+ setObject: function (key, value) {
+ if (!key) {
+ cc.log("Argument must be non-nil");
+ return;
+ }
+ this._jsonDict[key] = value;
+ },
+
+ /**
+ * Returns int value from attribute
+ * @param {String} key
+ * @returns {Number}
+ */
+ getInt: function (key) {
+ var ret = this._jsonDict[key];
+ return parseInt(ret || 0);
+ },
+
+ /**
+ * Returns double value from attribute
+ * @param {String} key
+ * @returns {Number}
+ */
+ getDouble: function (key) {
+ var ret = this._jsonDict[key];
+ return parseFloat(ret || 0.0);
+ },
+
+ /**
+ * Returns float value from attribute
+ * @param {String} key
+ * @returns {Number}
+ */
+ getFloat: function (key) {
+ var ret = this._jsonDict[key];
+ return parseFloat(ret || 0.0);
+ },
+
+ /**
+ * Returns boolean value from attribute
+ * @param {String} key
+ * @returns {Boolean}
+ */
+ getBool: function (key) {
+ var ret = this._jsonDict[key];
+ return Boolean(ret || false);
+ },
+
+ /**
+ * Returns string value from attribute
+ * @param {String} key
+ * @returns {String}
+ */
+ getString: function (key) {
+ var ret = this._jsonDict[key];
+ return ret || "";
+ },
+
+ /**
+ * Returns object value from attribute
+ * @param {String} key
+ * @returns {Object}
+ */
+ getObject: function (key) {
+ return this._jsonDict[key];
+ },
+
+ /**
+ * Parses json file.
+ * @param filename
+ */
+ parse:function(filename){
+ this._jsonDict = cc.loader.getRes(filename);
+ }
+});
+/**
+ * allocates and initializes a ComAttribute.
+ * @deprecated since v3.0, please use new construction instead.
+ * @return {ccs.ComAttribute}
+ * @example
+ * // example
+ * var com = ccs.ComAttribute.create();
+ */
+ccs.ComAttribute.create = function () {
+ return new ccs.ComAttribute();
+};
\ No newline at end of file
diff --git a/extensions/cocostudio/components/CCComAudio.js b/extensions/cocostudio/components/CCComAudio.js
new file mode 100644
index 0000000000..80bf953c5d
--- /dev/null
+++ b/extensions/cocostudio/components/CCComAudio.js
@@ -0,0 +1,285 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+/**
+ * The audio component for Cocostudio.
+ * @class
+ * @extends ccs.Component
+ */
+ccs.ComAudio = ccs.Component.extend(/** @lends ccs.ComAudio# */{
+ _filePath: "",
+ _loop: false,
+
+ /**
+ * Construction of ccs.ComAudio
+ */
+ ctor: function () {
+ cc._Component.prototype.ctor.call(this);
+ this._name = "Audio";
+ ccs.ComAudio.prototype.init.call(this);
+ },
+
+ /**
+ * Initializes a ccs.ComAudio.
+ * @returns {boolean}
+ */
+ init: function () {
+ return true;
+ },
+
+ /**
+ * The callback calls when a audio component enter stage.
+ * @override
+ */
+ onExit: function () {
+ this.stopBackgroundMusic(true);
+ this.stopAllEffects();
+ },
+
+ /**
+ * Stops all audios.
+ */
+ end: function () {
+ cc.audioEngine.end();
+ },
+
+ /**
+ * Preload background music resource
+ * @param {String} pszFilePath
+ */
+ preloadBackgroundMusic: function (pszFilePath) {
+ cc.loader.load(pszFilePath);
+ },
+
+ /**
+ * Play background music
+ * @param {String} [pszFilePath]
+ * @param {Boolean} [loop]
+ */
+ playBackgroundMusic: function (pszFilePath, loop) {
+ if(pszFilePath){
+ cc.audioEngine.playMusic(pszFilePath, loop);
+ }else{
+ cc.audioEngine.playMusic(this._filePath, this._loop);
+ }
+ },
+
+ /**
+ * Stop background music
+ * @param {String} releaseData
+ */
+ stopBackgroundMusic: function (releaseData) {
+ cc.audioEngine.stopMusic(releaseData);
+ },
+
+ /**
+ * Pause background music
+ */
+ pauseBackgroundMusic: function () {
+ cc.audioEngine.pauseMusic();
+ },
+
+ /**
+ * Resume background music
+ */
+ resumeBackgroundMusic: function () {
+ cc.audioEngine.resumeMusic();
+ },
+
+ /**
+ * Rewind background music
+ */
+ rewindBackgroundMusic: function () {
+ cc.audioEngine.rewindMusic();
+ },
+
+ /**
+ * Indicates whether any background music can be played or not.
+ * @returns {boolean}
+ */
+ willPlayBackgroundMusic: function () {
+ return cc.audioEngine.willPlayMusic();
+ },
+
+ /**
+ * Whether the music is playing.
+ * @returns {Boolean}
+ */
+ isBackgroundMusicPlaying: function () {
+ return cc.audioEngine.isMusicPlaying();
+ },
+
+ /**
+ * The volume of the music max value is 1.0,the min value is 0.0 .
+ * @returns {Number}
+ */
+ getBackgroundMusicVolume: function () {
+ return cc.audioEngine.getMusicVolume();
+ },
+
+ /**
+ * Set the volume of music.
+ * @param {Number} volume must be in 0.0~1.0 .
+ */
+ setBackgroundMusicVolume: function (volume) {
+ cc.audioEngine.setMusicVolume(volume);
+ },
+
+ /**
+ * The volume of the effects max value is 1.0,the min value is 0.0 .
+ * @returns {Number}
+ */
+ getEffectsVolume: function () {
+ return cc.audioEngine.getEffectsVolume();
+ },
+
+ /**
+ * Set the volume of sound effects.
+ * @param {Number} volume
+ */
+ setEffectsVolume: function (volume) {
+ cc.audioEngine.setEffectsVolume(volume);
+ },
+
+ /**
+ * Play sound effect.
+ * @param {String} [pszFilePath]
+ * @param {Boolean} [loop]
+ * @returns {Boolean}
+ */
+ playEffect: function (pszFilePath, loop) {
+ if (pszFilePath)
+ return cc.audioEngine.playEffect(pszFilePath, loop);
+ else
+ return cc.audioEngine.playEffect(this._filePath, this._loop);
+ },
+
+ /**
+ * Pause playing sound effect.
+ * @param {Number} soundId
+ */
+ pauseEffect: function (soundId) {
+ cc.audioEngine.pauseEffect(soundId);
+ },
+
+ /**
+ * Pause all effects
+ */
+ pauseAllEffects: function () {
+ cc.audioEngine.pauseAllEffects();
+ },
+
+ /**
+ * Resume effect
+ * @param {Number} soundId
+ */
+ resumeEffect: function (soundId) {
+ cc.audioEngine.resumeEffect(soundId);
+ },
+
+ /**
+ * Resume all effects
+ */
+ resumeAllEffects: function () {
+ cc.audioEngine.resumeAllEffects();
+ },
+
+ /**
+ * Stop effect
+ * @param {Number} soundId
+ */
+ stopEffect: function (soundId) {
+ cc.audioEngine.stopEffect(soundId);
+ },
+
+ /**
+ * stop all effects
+ */
+ stopAllEffects: function () {
+ cc.audioEngine.stopAllEffects();
+ },
+
+ /**
+ * Preload effect
+ * @param {String} pszFilePath
+ */
+ preloadEffect: function (pszFilePath) {
+ cc.loader.getRes(pszFilePath);
+ this.setFile(pszFilePath);
+ this.setLoop(false);
+ },
+
+ /**
+ * Unload effect
+ * @param {String} pszFilePath
+ */
+ unloadEffect: function (pszFilePath) {
+ cc.audioEngine.unloadEffect(pszFilePath);
+ },
+
+ /**
+ * File path setter
+ * @param {String} pszFilePath
+ */
+ setFile: function (pszFilePath) {
+ this._filePath = pszFilePath;
+ },
+
+ /**
+ * Sets audio component whether plays loop
+ * @param {Boolean} loop
+ */
+ setLoop: function (loop) {
+ this._loop = loop;
+ },
+
+ /**
+ * Returns the file path of audio component.
+ * @returns {string}
+ */
+ getFile: function () {
+ return this._filePath;
+ },
+
+ /**
+ * Returns audio component whether plays loop
+ * @returns {boolean}
+ */
+ isLoop: function () {
+ return this._loop;
+ }
+});
+
+/**
+ * allocates and initializes a ComAudio.
+ * @deprecated since v3.0, please use new construction instead.
+ * @return {ccs.ComAudio}
+ * @example
+ * // example
+ * var com = ccs.ComAudio.create();
+ */
+ccs.ComAudio.create = function () {
+ return new ccs.ComAudio();
+};
\ No newline at end of file
diff --git a/extensions/cocostudio/components/CCComController.js b/extensions/cocostudio/components/CCComController.js
new file mode 100644
index 0000000000..9fa5e82f61
--- /dev/null
+++ b/extensions/cocostudio/components/CCComController.js
@@ -0,0 +1,76 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+/**
+ * The controller component for Cocostudio.
+ * @class
+ * @extends ccs.Component
+ */
+ccs.ComController = ccs.Component.extend(/** @lends ccs.ComController# */{
+ /**
+ * Construction of ccs.ComController.
+ */
+ ctor: function () {
+ cc._Component.prototype.ctor.call(this);
+ this._name = "ComController";
+ ccs.ComController.prototype.init.call(this);
+ },
+
+ /**
+ * The callback calls when controller component enter stage.
+ * @override
+ */
+ onEnter: function () {
+ if (this._owner !== null)
+ this._owner.scheduleUpdate();
+ },
+
+ /**
+ * Returns controller component whether is enabled
+ * @returns {Boolean}
+ */
+ isEnabled: function () {
+ return this._enabled;
+ },
+
+ /**
+ * Sets controller component whether is enabled
+ * @param {Boolean} bool
+ */
+ setEnabled: function (bool) {
+ this._enabled = bool;
+ }
+});
+/**
+ * Allocates and initializes a ComController.
+ * @deprecated since v3.0, please use new construction instead.
+ * @return {ccs.ComController}
+ * @example
+ * // example
+ * var com = ccs.ComController.create();
+ */
+ccs.ComController.create = function () {
+ return new ccs.ComController();
+};
\ No newline at end of file
diff --git a/extensions/cocostudio/components/CCComRender.js b/extensions/cocostudio/components/CCComRender.js
new file mode 100644
index 0000000000..85343a383c
--- /dev/null
+++ b/extensions/cocostudio/components/CCComRender.js
@@ -0,0 +1,91 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+/**
+ * The render component for Cocostudio.
+ * @class
+ * @extends ccs.Component
+ */
+ccs.ComRender = ccs.Component.extend(/** @lends ccs.ComRender# */{
+ _render: null,
+ /**
+ * Construction of ccs.ComRender
+ * @param {cc.Node} node
+ * @param {String} comName
+ */
+ ctor: function (node, comName) {
+ cc._Component.prototype.ctor.call(this);
+ this._render = node;
+ this._name = comName;
+ this.isRenderer = true;
+ ccs.ComRender.prototype.init.call(this);
+ },
+
+ /**
+ * The callback calls when a render component enter stage.
+ */
+ onEnter: function () {
+ if (this._owner)
+ this._owner.addChild(this._render);
+ },
+
+ /**
+ * The callback calls when a render component exit stage.
+ */
+ onExit: function () {
+ if (this._owner) {
+ this._owner.removeChild(this._render, true);
+ this._render = null;
+ }
+ },
+
+ /**
+ * Returns a render node
+ * @returns {cc.Node}
+ */
+ getNode: function () {
+ return this._render;
+ },
+
+ /**
+ * Sets a render node to component.
+ * @param {cc.Node} node
+ */
+ setNode: function (node) {
+ this._render = node;
+ }
+});
+
+/**
+ * allocates and initializes a ComRender.
+ * @deprecated since v3.0, please use new construction instead.
+ * @return {ccs.ComRender}
+ * @example
+ * // example
+ * var com = ccs.ComRender.create();
+ */
+ccs.ComRender.create = function (node, comName) {
+ return new ccs.ComRender(node, comName);
+};
diff --git a/extensions/cocostudio/components/CCComponent.js b/extensions/cocostudio/components/CCComponent.js
new file mode 100644
index 0000000000..4adf508fb5
--- /dev/null
+++ b/extensions/cocostudio/components/CCComponent.js
@@ -0,0 +1,136 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+/**
+ * The base class of component in CocoStudio
+ * @class
+ * @extends cc._Class
+ */
+cc._Component = cc._Class.extend(/** @lends cc._Component# */{
+ _owner: null,
+ _name: "",
+ _enabled: true,
+
+ /**
+ * Construction of cc._Component
+ */
+ ctor:function(){
+ this._owner = null;
+ this._name = "";
+ this._enabled = true;
+ },
+
+ /**
+ * Initializes a cc._Component.
+ * @returns {boolean}
+ */
+ init:function(){
+ return true;
+ },
+
+ /**
+ * The callback when a component enter stage.
+ */
+ onEnter:function(){
+ },
+
+ /**
+ * The callback when a component exit stage.
+ */
+ onExit:function(){
+ },
+
+ /**
+ * The callback per every frame if it schedules update.
+ * @param delta
+ */
+ update:function(delta){
+ },
+
+ /**
+ * Serialize a component object.
+ * @param reader
+ */
+ serialize:function( reader){
+ },
+
+ /**
+ * Returns component whether is enabled.
+ * @returns {boolean}
+ */
+ isEnabled:function(){
+ return this._enabled;
+ },
+
+ /**
+ * Sets component whether is enabled.
+ * @param enable
+ */
+ setEnabled:function(enable){
+ this._enabled = enable;
+ },
+
+ /**
+ * Returns the name of cc._Component.
+ * @returns {string}
+ */
+ getName:function(){
+ return this._name;
+ } ,
+
+ /**
+ * Sets the name to cc._Component.
+ * @param {String} name
+ */
+ setName:function(name){
+ this._name = name;
+ } ,
+
+ /**
+ * Sets the owner to cc._Component.
+ * @param owner
+ */
+ setOwner:function(owner){
+ this._owner = owner;
+ },
+
+ /**
+ * Returns the owner of cc._Component.
+ * @returns {*}
+ */
+ getOwner:function(){
+ return this._owner;
+ }
+});
+
+/**
+ * Allocates and initializes a component.
+ * @deprecated since v3.0, please use new construction instead.
+ * @return {cc._Component}
+ */
+cc._Component.create = function(){
+ return new cc._Component();
+};
+
diff --git a/extensions/cocostudio/components/CCComponentContainer.js b/extensions/cocostudio/components/CCComponentContainer.js
new file mode 100644
index 0000000000..20c8a88288
--- /dev/null
+++ b/extensions/cocostudio/components/CCComponentContainer.js
@@ -0,0 +1,159 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+/**
+ * The component container for Cocostudio, it has some components.
+ * @class
+ * @extends cc._Class
+ */
+cc.ComponentContainer = cc._Class.extend(/** @lends cc.ComponentContainer# */{
+ _components:null,
+ _owner:null,
+
+ /**
+ * Construction of cc.ComponentContainer
+ * @param node
+ */
+ ctor:function(node){
+ this._components = null;
+ this._owner = node;
+ },
+
+ /**
+ * Gets component by name.
+ * @param name
+ * @returns {*}
+ */
+ getComponent:function(name){
+ if(!name)
+ throw new Error("cc.ComponentContainer.getComponent(): name should be non-null");
+ name = name.trim();
+ if(!this._components){
+ this._components = {};
+ }
+ return this._components[name];
+ },
+
+ /**
+ * Adds a component to container
+ * @param {cc._Component} component
+ * @returns {boolean}
+ */
+ add:function(component){
+ if(!component)
+ throw new Error("cc.ComponentContainer.add(): component should be non-null");
+ if(component.getOwner()){
+ cc.log("cc.ComponentContainer.add(): Component already added. It can't be added again");
+ return false;
+ }
+
+ if(this._components == null){
+ this._components = {};
+ this._owner.scheduleUpdate();
+ }
+ var oldComponent = this._components[component.getName()];
+ if(oldComponent){
+ cc.log("cc.ComponentContainer.add(): Component already added. It can't be added again");
+ return false;
+ }
+ component.setOwner(this._owner);
+ this._components[component.getName()] = component;
+ component.onEnter();
+ return true;
+ },
+
+ /**
+ * Removes component from container by name or component object.
+ * @param {String|cc._Component} name component name or component object.
+ * @returns {boolean}
+ */
+ remove:function(name){
+ if(!name)
+ throw new Error("cc.ComponentContainer.remove(): name should be non-null");
+ if(!this._components)
+ return false;
+ if(name instanceof cc._Component)
+ return this._removeByComponent(name);
+ else {
+ name = name.trim();
+ return this._removeByComponent(this._components[name]);
+ }
+ },
+
+ _removeByComponent:function(component){
+ if(!component)
+ return false;
+ component.onExit();
+ component.setOwner(null);
+ delete this._components[component.getName()];
+ return true;
+ },
+
+ /**
+ * Removes all components of container.
+ */
+ removeAll:function(){
+ if(!this._components)
+ return;
+ var locComponents = this._components;
+ for(var selKey in locComponents){
+ var selComponent = locComponents[selKey];
+ selComponent.onExit();
+ selComponent.setOwner(null);
+ delete locComponents[selKey];
+ }
+ this._owner.unscheduleUpdate();
+ this._components = null;
+ },
+
+ _alloc:function(){
+ this._components = {};
+ },
+
+ /**
+ * Visit callback by director. it calls every frame.
+ * @param {Number} delta
+ */
+ visit:function(delta){
+ if(!this._components)
+ return;
+
+ var locComponents = this._components;
+ for(var selKey in locComponents)
+ locComponents[selKey].update(delta);
+ },
+
+ /**
+ * Returns the container whether is empty.
+ * @returns {boolean}
+ */
+ isEmpty: function () {
+ if (!this._components)
+ return true;
+ return this._components.length === 0;
+ }
+});
+
+
diff --git a/extensions/cocostudio/loader/load.js b/extensions/cocostudio/loader/load.js
new file mode 100644
index 0000000000..05e3c0aac1
--- /dev/null
+++ b/extensions/cocostudio/loader/load.js
@@ -0,0 +1,274 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+ccs._load = (function(){
+
+ /**
+ * load file
+ * @param {String} file
+ * @param {String} [type=] - ccui|node|action
+ * @param {String} [path=] - Resource search path
+ * @returns {*}
+ */
+ var load = function(file, type, path){
+
+ var json = cc.loader.getRes(file);
+
+ if(!json)
+ return cc.log("%s does not exist", file);
+ var ext = extname(file).toLocaleLowerCase();
+ if(ext !== "json" && ext !== "exportjson")
+ return cc.log("%s load error, must be json file", file);
+
+ var parse;
+ if(!type){
+ if(json["widgetTree"])
+ parse = parser["ccui"];
+ else if(json["nodeTree"])
+ parse = parser["timeline"];
+ else if(json["Content"] && json["Content"]["Content"])
+ parse = parser["timeline"];
+ else if(json["gameobjects"])
+ parse = parser["scene"];
+ }else{
+ parse = parser[type];
+ }
+
+ if(!parse){
+ cc.log("Can't find the parser : %s", file);
+ return new cc.Node();
+ }
+ var version = json["version"] || json["Version"];
+ if(!version && json["armature_data"]){
+ cc.warn("%s is armature. please use:", file);
+ cc.warn(" ccs.armatureDataManager.addArmatureFileInfoAsync(%s);", file);
+ cc.warn(" var armature = new ccs.Armature('name');");
+ return new cc.Node();
+ }
+ var currentParser = getParser(parse, version);
+ if(!currentParser){
+ cc.log("Can't find the parser : %s", file);
+ return new cc.Node();
+ }
+
+ return currentParser.parse(file, json, path) || null;
+ };
+
+ var parser = {
+ "ccui": {},
+ "timeline": {},
+ "action": {},
+ "scene": {}
+ };
+
+ load.registerParser = function(name, version, target){
+ if(!name || !version || !target)
+ return cc.log("register parser error");
+ if(!parser[name])
+ parser[name] = {};
+ parser[name][version] = target;
+ };
+
+ load.getParser = function(name, version){
+ if(name && version)
+ return parser[name] ? parser[name][version] : undefined;
+ if(name)
+ return parser[name];
+ return parser;
+ };
+
+ //Gets the file extension
+ var extname = function(fileName){
+ var arr = fileName.match(extnameReg);
+ return ( arr && arr[1] ) ? arr[1] : null;
+ };
+ var extnameReg = /\.([^\.]+)$/;
+
+
+ var parserReg = /([^\.](\.\*)?)*$/;
+ var getParser = function(parser, version){
+ if(parser[version])
+ return parser[version];
+ else if(version === "*")
+ return null;
+ else
+ return getParser(parser, version.replace(parserReg, "*"));
+ };
+
+ return load;
+
+})();
+
+ccs._parser = cc._Class.extend({
+
+ ctor: function(){
+ this.parsers = {};
+ },
+
+ _dirnameReg: /\S*\//,
+ _dirname: function(path){
+ var arr = path.match(this._dirnameReg);
+ return (arr && arr[0]) ? arr[0] : "";
+ },
+
+ getClass: function(json){
+ return json["classname"];
+ },
+
+ getNodeJson: function(json){
+ return json["widgetTree"];
+ },
+
+ parse: function(file, json, resourcePath){
+ resourcePath = resourcePath || this._dirname(file);
+ this.pretreatment(json, resourcePath);
+ var node = this.parseNode(this.getNodeJson(json), resourcePath, file);
+ node && this.deferred(json, resourcePath, node, file);
+ return node;
+ },
+
+ pretreatment: function(json, resourcePath, file){},
+
+ deferred: function(json, resourcePath, node, file){},
+
+ parseNode: function(json, resourcePath){
+ var parser = this.parsers[this.getClass(json)];
+ var widget = null;
+ if(parser)
+ widget = parser.call(this, json, resourcePath);
+ else
+ cc.log("Can't find the parser : %s", this.getClass(json));
+
+ return widget;
+ },
+
+ registerParser: function(widget, parse){
+ this.parsers[widget] = parse;
+ }
+});
+
+/**
+ * Analysis of studio JSON file
+ * The incoming file name, parse out the corresponding object
+ * Temporary support file list:
+ * ui 1.*
+ * node 1.* - 2.*
+ * action 1.* - 2.*
+ * scene 0.* - 1.*
+ * @param {String} file
+ * @param {String} [path=] Resource path
+ * @returns {{node: cc.Node, action: cc.Action}}
+ */
+ccs.load = function(file, path){
+ var object = {
+ node: null,
+ action: null
+ };
+
+ object.node = ccs._load(file, null, path);
+ object.action = ccs._load(file, "action", path);
+ if(object.action && object.action.tag === -1 && object.node)
+ object.action.tag = object.node.tag;
+ return object;
+};
+ccs.load.validate = {};
+
+/**
+ * Analysis of studio JSON file and layout ui widgets by visible size.
+ * The incoming file name, parse out the corresponding object
+ * Temporary support file list:
+ * ui 1.*
+ * node 1.* - 2.*
+ * action 1.* - 2.*
+ * scene 0.* - 1.*
+ * @param {String} file
+ * @param {String} [path=] Resource path
+ * @returns {{node: cc.Node, action: cc.Action}}
+ */
+ccs.loadWithVisibleSize = function(file, path){
+ var object = ccs.load(file, path);
+ var size = cc.director.getVisibleSize();
+ if(object.node && size){
+ object.node.setContentSize(size.width, size.height);
+ ccui.helper.doLayout(object.node);
+ }
+ return object;
+};
+
+//Forward compatible interface
+
+ccs.actionTimelineCache = {
+
+
+ //@deprecated This function will be deprecated sooner or later please use ccs.load
+ /**
+ * Create Timeline Action
+ * @param file
+ * @returns {*}
+ */
+ createAction: function(file){
+ return ccs._load(file, "action");
+ }
+};
+
+ccs.csLoader = {
+
+ //@deprecated This function will be deprecated sooner or later please use ccs.load
+ /**
+ * Create Timeline Node
+ * @param file
+ * @returns {*}
+ */
+ createNode: function(file){
+ return ccs._load(file);
+ }
+};
+
+cc.loader.register(["json"], {
+ load : function(realUrl, url, res, cb){
+ cc.loader.loadJson(realUrl, function(error, data){
+ var path = cc.path;
+ if(data && data["Content"] && data["Content"]["Content"]["UsedResources"]){
+ var UsedResources = data["Content"]["Content"]["UsedResources"],
+ dirname = path.dirname(url),
+ list = [],
+ tmpUrl, normalUrl;
+ for(var i=0; i= 1700){
+ cc.warn("Not supported file types, Please try use the ccs.load");
+ return null;
+ }
+ return ccs._load(file, "ccui");
+ },
+
+ //@deprecated This function will be deprecated sooner or later please use parser.registerParser
+ /**
+ * Register a custom Widget reader
+ * @param classType
+ * @param ins
+ * @param object
+ * @param callback
+ * @deprecated This function will be deprecated sooner or later please use parser.registerParser
+ */
+ registerTypeAndCallBack: function(classType, ins, object, callback){
+ var parser = ccs._load.getParser("ccui")["*"];
+ var func = callback.bind(object);
+ parser.registerParser(classType, function(options, resourcePath){
+ var widget = new ins();
+ var uiOptions = options["options"];
+ object.setPropsFromJsonDictionary && object.setPropsFromJsonDictionary(widget, uiOptions);
+ this.generalAttributes(widget, uiOptions);
+ var customProperty = uiOptions["customProperty"];
+ if(customProperty)
+ customProperty = JSON.parse(customProperty);
+ else
+ customProperty = {};
+ func(classType, widget, customProperty);
+ this.colorAttributes(widget, uiOptions);
+ this.anchorPointAttributes(widget, uiOptions);
+ this.parseChild.call(this, widget, options, resourcePath);
+ return widget;
+ });
+ },
+
+ //@deprecated This function will be deprecated sooner or later
+ /**
+ * Gets the version number by version string.
+ * @param {String} version version string.
+ * @returns {Number}
+ */
+ getVersionInteger: function(version){
+ if(!version || typeof version !== "string") return 0;
+ var arr = version.split(".");
+ if (arr.length !== 4)
+ return 0;
+ var num = 0;
+ arr.forEach(function(n, i){
+ num += n * Math.pow(10, 3 - i);
+ });
+ return num;
+ },
+
+ //@deprecated This function will be deprecated sooner or later
+ /**
+ * stores the designSize of UI file.
+ * @param {String} fileName
+ * @param {cc.Size} size
+ */
+ storeFileDesignSize: function (fileName, size) {
+ this._fileDesignSizes[fileName] = size;
+ },
+
+ //@deprecated This function will be deprecated sooner or later
+ /**
+ * Gets the design size by filename.
+ * @param {String} fileName
+ * @returns {cc.Size}
+ */
+ getFileDesignSize: function (fileName) {
+ return this._fileDesignSizes[fileName];
+ },
+
+ //@deprecated This function will be deprecated sooner or later
+ /**
+ * Returns the file path
+ * @returns {string}
+ */
+ getFilePath: function(){
+ return this._filePath;
+ },
+
+ //@deprecated This function will be deprecated sooner or later
+ setFilePath: function(path){
+ this._filePath = path;
+ },
+
+ //@deprecated This function will be deprecated sooner or later
+ /**
+ * Returns the parsed object map. (analytic function)
+ * @returns {Object}
+ */
+ getParseObjectMap: function(){
+ return ccs._load.getParser("ccui")["*"]["parsers"];
+ },
+
+ //@deprecated This function will be deprecated sooner or later
+ /**
+ * Returns the parsed callback map. (analytic function)
+ * @returns {*}
+ */
+ getParseCallBackMap: function(){
+ return ccs._load.getParser("ccui")["*"]["parsers"];
+ },
+
+ //@deprecated This function will be deprecated sooner or later
+ clear: function(){}
+ };
+
+ var parser = ccs._load.getParser("ccui")["*"];
+ ccs.imageViewReader = {setPropsFromJsonDictionary: parser.ImageViewAttributes};
+ ccs.buttonReader = {setPropsFromJsonDictionary: parser.ButtonAttributes};
+ ccs.checkBoxReader = {setPropsFromJsonDictionary: parser.CheckBoxAttributes};
+ ccs.labelAtlasReader = {setPropsFromJsonDictionary: parser.TextAtlasAttributes};
+ ccs.labelBMFontReader= {setPropsFromJsonDictionary: parser.TextBMFontAttributes};
+ ccs.labelReader = {setPropsFromJsonDictionary: parser.TextAttributes};
+ ccs.layoutReader = {setPropsFromJsonDictionary: parser.LayoutAttributes};
+ ccs.listViewReader = {setPropsFromJsonDictionary: parser.ListViewAttributes};
+ ccs.loadingBarReader = {setPropsFromJsonDictionary: parser.LoadingBarAttributes};
+ ccs.pageViewReader = {setPropsFromJsonDictionary: parser.PageViewAttributes};
+ ccs.scrollViewReader = {setPropsFromJsonDictionary: parser.ScrollViewAttributes};
+ ccs.sliderReader = {setPropsFromJsonDictionary: parser.SliderAttributes};
+ ccs.textFieldReader = {setPropsFromJsonDictionary: parser.TextFieldAttributes};
+})();
+
+(function(){
+ ccs.sceneReader = {
+
+ _node: null,
+
+ //@deprecated This function will be deprecated sooner or later please use ccs.load
+ /**
+ * Create Scene Node
+ * @param file
+ * @returns {*}
+ */
+ createNodeWithSceneFile: function(file){
+ var node = ccs._load(file, "scene");
+ this._node = node;
+ return node;
+ },
+
+ /**
+ * Get a node by tag.
+ * @param {Number} tag
+ * @returns {cc.Node|null}
+ */
+ getNodeByTag: function(tag){
+ if (this._node == null)
+ return null;
+ if (this._node.getTag() === tag)
+ return this._node;
+ return this._nodeByTag(this._node, tag);
+ },
+
+ _nodeByTag: function (parent, tag) {
+ if (parent == null)
+ return null;
+ var retNode = null;
+ var children = parent.getChildren();
+ for (var i = 0; i < children.length; i++) {
+ var child = children[i];
+ if (child && child.getTag() === tag) {
+ retNode = child;
+ break;
+ } else {
+ retNode = this._nodeByTag(child, tag);
+ if (retNode)
+ break;
+ }
+ }
+ return retNode;
+ },
+
+ //@deprecated This function will be deprecated sooner or later
+ /**
+ * Returns the version of ccs.SceneReader.
+ * @returns {string}
+ */
+ version: function(){
+ return "*";
+ },
+
+ //@deprecated This function will be deprecated sooner or later
+ /**
+ * Sets the listener to reader.
+ * Cannot use
+ */
+ setTarget: function(){},
+
+ //@deprecated This function will be deprecated sooner or later
+ /**
+ * Clear all triggers and stops all sounds.
+ */
+ clear: function(){
+ ccs.triggerManager.removeAll();
+ cc.audioEngine.end();
+ }
+ };
+})();
\ No newline at end of file
diff --git a/extensions/cocostudio/loader/parsers/scene-1.x.js b/extensions/cocostudio/loader/parsers/scene-1.x.js
new file mode 100644
index 0000000000..57f34c28a3
--- /dev/null
+++ b/extensions/cocostudio/loader/parsers/scene-1.x.js
@@ -0,0 +1,262 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+(function(load, baseParser){
+
+ var Parser = baseParser.extend({
+
+ getNodeJson: function(json){
+ return json;
+ },
+
+ parseNode: function(json, resourcePath){
+ var parser = this.parsers[this.getClass(json)];
+ var node = null;
+ if(parser)
+ node = parser.call(this, json, resourcePath);
+ else
+ cc.log("Can't find the parser : %s", this.getClass(json));
+
+ return node;
+ },
+
+ deferred: function(json, resourcePath, node, file){
+ ccs.triggerManager.parse(json["Triggers"]||[]);
+ if(ccs.sceneReader)
+ ccs.sceneReader._node = node;
+ },
+
+ setPropertyFromJsonDict: function(node, json){
+ var x = (cc.js.isUndefined(json["x"]))?0:json["x"];
+ var y = (cc.js.isUndefined(json["y"]))?0:json["y"];
+ node.setPosition(x, y);
+
+ var bVisible = Boolean((cc.js.isUndefined(json["visible"]))?1:json["visible"]);
+ node.setVisible(bVisible);
+
+ var nTag = (cc.js.isUndefined(json["objecttag"]))?-1:json["objecttag"];
+ node.setTag(nTag);
+
+ var nZorder = (cc.js.isUndefined(json["zorder"]))?0:json["zorder"];
+ node.setLocalZOrder(nZorder);
+
+ var fScaleX = (cc.js.isUndefined(json["scalex"]))?1:json["scalex"];
+ var fScaleY = (cc.js.isUndefined(json["scaley"]))?1:json["scaley"];
+ node.setScaleX(fScaleX);
+ node.setScaleY(fScaleY);
+
+ var fRotationZ = (cc.js.isUndefined(json["rotation"]))?0:json["rotation"];
+ node.setRotation(fRotationZ);
+
+ var sName = json["name"] || "";
+ node.setName(sName);
+ }
+
+ });
+
+ var parser = new Parser();
+
+ parser.parseChild = function(node, objects, resourcePath){
+ for (var i = 0; i < objects.length; i++) {
+ var child,
+ options = objects[i];
+ if(options)
+ child = this.parseNode(options, resourcePath);
+ if(child)
+ node.addChild(child);
+ }
+ };
+
+ var componentsParser = {
+ "CCSprite": function(node, component, resourcePath){
+ var child = new cc.Sprite();
+ loadTexture(component["fileData"], resourcePath, function(path, type){
+ if(type === 0)
+ child.setTexture(path);
+ else if(type === 1){
+ var spriteFrame = cc.spriteFrameCache.getSpriteFrame(path);
+ child.setSpriteFrame(spriteFrame);
+ }
+ });
+ var render = new ccs.ComRender(child, "CCSprite");
+ node.addComponent(render);
+ return render;
+ },
+ "CCTMXTiledMap": function(node, component, resourcePath){
+ var child = null;
+ loadTexture(component["fileData"], resourcePath, function(path, type){
+ if(type === 0)
+ child = new cc.TMXTiledMap(path);
+ });
+ var render = new ccs.ComRender(child, "CCTMXTiledMap");
+ node.addComponent(render);
+ return render;
+ },
+ "CCParticleSystemQuad": function(node, component, resourcePath){
+ var child = null;
+ loadTexture(component["fileData"], resourcePath, function(path, type){
+ if(type === 0)
+ child = new cc.ParticleSystem(path);
+ else
+ cc.log("unknown resourcetype on CCParticleSystemQuad!");
+ child.setPosition(0, 0);
+ });
+ var render = new ccs.ComRender(child, "CCParticleSystemQuad");
+ node.addComponent(render);
+ return render;
+ },
+ "CCArmature": function(node, component, resourcePath){
+ var child = null;
+ loadTexture(component["fileData"], resourcePath, function(path, type){
+ if(type === 0){
+ var jsonDict = cc.loader.getRes(path);
+ if (!jsonDict) cc.log("Please load the resource [%s] first!", path);
+ var armature_data = jsonDict["armature_data"];
+ var subData = armature_data[0];
+ var name = subData["name"];
+ ccs.armatureDataManager.addArmatureFileInfo(path);
+ child = new ccs.Armature(name);
+ }
+ });
+ if(child){
+ var render = new ccs.ComRender(child, "CCArmature");
+ node.addComponent(render);
+ var actionName = component["selectedactionname"];
+ if (actionName && child.getAnimation())
+ child.getAnimation().play(actionName);
+
+ return render;
+ }
+
+ },
+ "CCComAudio": function(node, component, resourcePath){
+ var audio = null;
+ loadTexture(component["fileData"], resourcePath, function(path, type){
+ if(type === 0){
+ audio = new ccs.ComAudio();
+ audio.preloadEffect(path);
+ var name = component["name"];
+ if(name)
+ audio.setName(name);
+ node.addComponent(audio);
+ }
+ });
+ },
+ "CCComAttribute": function(node, component, resourcePath){
+ var attribute = null;
+ loadTexture(component["fileData"], resourcePath, function(path, type){
+ if(type === 0){
+ attribute = new ccs.ComAttribute();
+ if (path !== "")
+ attribute.parse(path);
+ node.addComponent(attribute);
+ }else
+ cc.log("unknown resourcetype on CCComAttribute!");
+ });
+ return attribute;
+ },
+ "CCBackgroundAudio": function(node, component, resourcePath){
+ var audio = null;
+ loadTexture(component["fileData"], resourcePath, function(path, type){
+ if(type === 0){
+ audio = new ccs.ComAudio();
+ audio.preloadBackgroundMusic(path);
+ audio.setFile(path);var bLoop = Boolean(component["loop"] || 0);
+ audio.setLoop(bLoop);
+ var name = component["name"];
+ if(name)
+ audio.setName(name);
+ node.addComponent(audio);
+ audio.playBackgroundMusic(path, bLoop);
+ }
+ });
+ },
+ "GUIComponent": function(node, component, resourcePath){
+ var widget = null;
+ loadTexture(component["fileData"], resourcePath, function(path, type){
+ widget = ccs._load(path, "ccui");
+ });
+ var render = new ccs.ComRender(widget, "GUIComponent");
+ node.addComponent(render);
+ return render;
+ },
+ "CCScene": function(){}
+ };
+ var loadedPlist = {};
+ var loadTexture = function(json, resourcePath, cb){
+ if(json != null){
+ var path = json["path"];
+ var type = json["resourceType"];
+ var plist = json["plist"];
+ if(!path)
+ return;
+ if(plist){
+ if(cc.loader.getRes(resourcePath + plist)){
+ loadedPlist[resourcePath + plist] = true;
+ cc.spriteFrameCache.addSpriteFrames(resourcePath + plist);
+ }else{
+ if(!loadedPlist[resourcePath + plist])
+ cc.log("%s need to be preloaded", resourcePath + plist);
+ }
+ }
+ if(type !== 0)
+ cb(path, type);
+ else
+ cb(resourcePath + path, type);
+ }
+ };
+
+ parser.parseComponents = function(node, json, resourcePath){
+ if(!node || !json)
+ return;
+ json.forEach(function(component){
+ var parser = componentsParser[component["classname"]];
+ var render = null;
+ if(parser)
+ render = parser(node, component, resourcePath);
+ else
+ cc.log("Can't find the component parser : %s", component["classname"]);
+ var name = component["name"];
+ if(render && name){
+ render.setName(name);
+ }
+ });
+ };
+
+ parser.registerParser("CCNode", function(options, resourcePath){
+ var node = new cc.Node();
+ this.setPropertyFromJsonDict(node, options);
+ this.parseChild.call(this, node, options["gameobjects"], resourcePath);
+ this.parseComponents(node, options["components"], resourcePath);
+ var size = options["CanvasSize"];
+ if (size)
+ node.setContentSize(cc.size(size["_width"], size["_height"]));
+
+ return node;
+ });
+
+ load.registerParser("scene", "*", parser);
+
+
+})(ccs._load, ccs._parser);
diff --git a/extensions/cocostudio/loader/parsers/timelineParser-1.x.js b/extensions/cocostudio/loader/parsers/timelineParser-1.x.js
new file mode 100644
index 0000000000..c9c3efbab5
--- /dev/null
+++ b/extensions/cocostudio/loader/parsers/timelineParser-1.x.js
@@ -0,0 +1,292 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+(function(load, baseParser){
+
+ var loadedPlist = {};
+
+ var Parser = baseParser.extend({
+
+ getNodeJson: function(json){
+ return json["nodeTree"];
+ },
+
+ addSpriteFrame: function(plists, pngs, resourcePath){
+ if(!plists || !pngs || plists.length !== pngs.length)
+ return;
+ for (var i = 0; i < plists.length; i++) {
+ var plist = resourcePath + plists[i];
+ if(!cc.loader.getRes(plist) && !loadedPlist[plist])
+ cc.log("%s need to be preloaded", plist);
+ else
+ loadedPlist[plist] = true;
+ cc.spriteFrameCache.addSpriteFrames(
+ plist,
+ resourcePath + pngs[i]
+ );
+ }
+ },
+
+ pretreatment: function(json, resourcePath, file){
+ this.addSpriteFrame(json["textures"], json["texturesPng"], resourcePath);
+ }
+
+ });
+ var parser = new Parser();
+
+ parser.generalAttributes = function(node, options){
+ var width = options["width"] !=null ? options["width"] : 0;
+ var height = options["height"] !=null ? options["height"] : 0;
+ var x = options["x"] !=null ? options["x"] : 0;
+ var y = options["y"] !=null ? options["y"] : 0;
+ var scalex = options["scaleX"] !=null ? options["scaleX"] : 1;
+ var scaley = options["scaleY"] !=null ? options["scaleY"] : 1;
+ var rotation = options["rotation"] !=null ? options["rotation"] : 0;
+ var rotationSkewX = options["rotationSkewX"]!=null ? options["rotationSkewX"] : 0;
+ var rotationSkewY = options["rotationSkewY"]!=null ? options["rotationSkewY"] : 0;
+ var skewx = options["skewX"] !=null ? options["skewX"] : 0;
+ var skewy = options["skewY"] !=null ? options["skewY"] : 0;
+ var anchorx = options["anchorPointX"] !=null ? options["anchorPointX"] : 0.5;
+ var anchory = options["anchorPointY"] !=null ? options["anchorPointY"] : 0.5;
+ var alpha = options["opacity"] !=null ? options["opacity"] : 255;
+ var red = options["colorR"] !=null ? options["colorR"] : 255;
+ var green = options["colorG"] !=null ? options["colorG"] : 255;
+ var blue = options["colorB"] !=null ? options["colorB"] : 255;
+ var zorder = options["colorR"] !=null ? options["colorR"] : 0;
+ var tag = options["tag"] !=null ? options["tag"] : 0;
+ var actionTag = options["actionTag"] !=null ? options["actionTag"] : 0;
+ var visible = options["visible"] !=null ? options["visible"] : true;
+
+ if(x != 0 || y != 0)
+ node.setPosition(cc.p(x, y));
+ if(scalex != 1)
+ node.setScaleX(scalex);
+ if(scaley != 1)
+ node.setScaleY(scaley);
+ if (rotation != 0)
+ node.setRotation(rotation);
+ if(rotationSkewX != 0)
+ node.setRotationX(rotationSkewX);
+ if(rotationSkewY != 0)
+ node.setRotationY(rotationSkewY);
+ if(skewx != 0)
+ node.setSkewX(skewx);
+ if(skewy != 0)
+ node.setSkewY(skewy);
+ if(anchorx != 0.5 || anchory != 0.5)
+ node.setAnchorPoint(cc.p(anchorx, anchory));
+ if(width != 0 || height != 0)
+ node.setContentSize(cc.size(width, height));
+ if(zorder != 0)
+ node.setLocalZOrder(zorder);
+ if(visible != true)
+ node.setVisible(visible);
+
+ if(alpha != 255)
+ {
+ node.setOpacity(alpha);
+ }
+ if(red != 255 || green != 255 || blue != 255)
+ {
+ node.setColor(cc.color(red, green, blue));
+ }
+
+
+ node.setTag(tag);
+ node.setUserObject(new ccs.ActionTimelineData(actionTag));
+ };
+
+ parser.parseComponent = function(node, options){
+ if(!options) return;
+ for (var i = 0; i < options.length; ++i){
+ var dic = options[i];
+ var component = this.loadComponent(dic);
+ if (component){
+ node.addComponent(component);
+ }
+ }
+ };
+
+ parser.parseChild = function(parse, widget, options, resourcePath){
+ var children = options["children"];
+ for (var i = 0; i < children.length; i++) {
+ var child = this.parseNode(children[i], resourcePath);
+ if(child){
+ if(widget instanceof ccui.PageView){
+ if(child instanceof ccui.Layout)
+ widget.addPage(child);
+ } else {
+ if(widget instanceof ccui.ListView){
+ if(child instanceof ccui.Widget)
+ widget.pushBackCustomItem(child);
+ } else {
+ if(!(widget instanceof ccui.Layout) && child instanceof ccui.Widget) {
+ if(child.getPositionType() === ccui.Widget.POSITION_PERCENT) {
+ var position = child.getPositionPercent();
+ var anchor = widget.getAnchorPoint();
+ child.setPositionPercent(cc.p(position.x + anchor.x, position.y + anchor.y));
+ }
+ //To make up for the studio positioning error problem
+ var AnchorPointIn = widget.getAnchorPointInPoints();
+ child.setPosition(cc.p(child.getPositionX() + AnchorPointIn.x, child.getPositionY() + AnchorPointIn.y));
+ }
+ widget.addChild(child);
+ }
+ }
+ }
+ }
+ };
+
+ parser.initNode = function(options){
+ var node = new cc.Node();
+ this.generalAttributes(node, options);
+ return node;
+ };
+ parser.initSubGraph = function(options){
+ var filePath = options["fileName"];
+
+ var node;
+ if (filePath && "" !== filePath){
+ node = this.createNode(filePath);
+ }else{
+ node = new ccs.Node();
+ }
+ this.generalAttributes(node, options);
+ return node;
+ };
+ parser.initSprite = function(options, resourcePath){
+ var path = options["fileName"];
+ var sprite;
+ if(path != null){
+ var spriteFrame = cc.spriteFrameCache.getSpriteFrame(path);
+ if(!spriteFrame){
+ path = resourcePath + path;
+ sprite = new ccs.Sprite(path);
+ }else{
+ sprite = ccs.Sprite.createWithSpriteFrame(spriteFrame);
+ }
+
+ if(!sprite){
+ sprite = new cc.Sprite();
+ cc.log("filePath is empty. Create a sprite with no texture");
+ }
+ }else{
+ sprite = new ccs.Sprite();
+ }
+ this.generalAttributes(sprite, options);
+ var flipX = options["flipX"];
+ var flipY = options["flipY"];
+
+ if(flipX != false)
+ sprite.setFlippedX(flipX);
+ if(flipY != false)
+ sprite.setFlippedY(flipY);
+ return sprite;
+ };
+ parser.initParticle = function(options, resourcePath){
+ var filePath = options["plistFile"];
+ var num = options["tmxFile"];
+ var particle = new cc.ParticleSystemQuad(filePath);
+ particle.setTotalParticles(num);
+ this.generalAttributes(particle, options);
+ return particle;
+ };
+ parser.initTMXTiledMap = function(options, resourcePath){
+ var tmxFile = options["tmxFile"];
+ var tmxString = options["tmxString"];
+ //todo check path and resourcePath
+ var path = options["resourcePath"];
+
+ var tmx = null;
+ if (tmxFile && "" !== tmxFile){
+ tmx = new cc.TMXTiledMap(tmxFile);
+ }else if (tmxString && "" !== tmxString && path && "" !== path){
+ tmx = new cc.TMXTiledMap(tmxString, path);
+ }
+ return tmx;
+ };
+ var uiParser = load.getParser("ccui")["*"];
+ parser.initWidget = function(options, resourcePath){
+ var type = options["classname"];
+
+ var parser = uiParser.parsers[type];
+ if(!parser)
+ return cc.log("%s parser is not found", type);
+
+ var node = parser.call(uiParser, options, resourcePath);
+ if(node){
+ var rotationSkewX = options["rotationSkewX"];
+ var rotationSkewY = options["rotationSkewY"];
+ var skewx = options["skewX"];
+ var skewy = options["skewY"];
+ if(rotationSkewX != 0)
+ node.setRotationX(rotationSkewX);
+ if(rotationSkewY != 0)
+ node.setRotationY(rotationSkewY);
+ if(skewx != 0)
+ node.setSkewX(skewx);
+ if(skewy != 0)
+ node.setSkewY(skewy);
+
+ var actionTag = options["actionTag"];
+ node.setUserObject(new ccs.ActionTimelineData(actionTag));
+ }
+ return node;
+ };
+
+ var register = [
+ {name: "Node", handle: parser.initNode},
+ {name: "SubGraph", handle: parser.initSubGraph},
+ {name: "Sprite", handle: parser.initSprite},
+ {name: "Particle", handle: parser.initParticle},
+ {name: "TMXTiledMap", handle: parser.initTMXTiledMap},
+
+ {name: "Widget", handle: parser.initWidget},
+ {name: "Panel", handle: parser.initWidget},
+ {name: "Button", handle: parser.initWidget},
+ {name: "CheckBox", handle: parser.initWidget},
+ {name: "ImageView", handle: parser.initWidget},
+ {name: "LabelAtlas", handle: parser.initWidget},
+ {name: "LabelBMFont", handle: parser.initWidget},
+ {name: "Label", handle: parser.initWidget},
+ {name: "ListView", handle: parser.initWidget},
+ {name: "LoadingBar", handle: parser.initWidget},
+ {name: "PageView", handle: parser.initWidget},
+ {name: "ScrollView", handle: parser.initWidget},
+ {name: "Slider", handle: parser.initWidget},
+ {name: "TextField", handle: parser.initWidget}
+ ];
+
+ register.forEach(function(item){
+ parser.registerParser(item.name, function(options, parse, resourcePath){
+ var node = item.handle.call(this, options["options"]);
+ this.parseComponent(node, options["components"]);
+ this.parseChild(parse, node, options, resourcePath);
+ return node;
+ });
+ });
+
+ load.registerParser("timeline", "*", parser);
+
+})(ccs._load, ccs._parser);
diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js
new file mode 100644
index 0000000000..2d649372ea
--- /dev/null
+++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js
@@ -0,0 +1,1401 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+(function(load, baseParser){
+
+ var DEBUG = false;
+
+ var Parser = baseParser.extend({
+
+ parse: function(file, json, path){
+ var resourcePath;
+ if(path !== undefined)
+ resourcePath = path;
+ else
+ resourcePath = this._dirname(file);
+ this.pretreatment(json, resourcePath, file);
+ var node = this.parseNode(this.getNodeJson(json), resourcePath);
+ this.deferred(json, resourcePath, node, file);
+ return node;
+ },
+
+ getNodeJson: function(json){
+ var content = json["Content"];
+ if(content["ObjectData"])
+ return content["ObjectData"];
+
+ return content["Content"]["ObjectData"];
+ },
+
+ getClass: function(json){
+ return json["ctype"];
+ }
+
+ });
+ var parser = new Parser();
+
+
+ var getParam = function(value, dValue){
+ if(value === undefined)
+ return dValue;
+ else
+ return value;
+ };
+
+ //////////
+ // NODE //
+ //////////
+
+ parser.generalAttributes = function(node, json){
+ if(json["Name"] != null)
+ node.setName(json["Name"]);
+
+ var position = json["Position"];
+ if(position != null && (position["X"] != null || position["Y"] != null))
+ node.setPosition(cc.p(position["X"]||0, position["Y"]||0));
+
+ var scale = json["Scale"];
+ if(scale != null){
+ if(scale["ScaleX"] != null)
+ node.setScaleX(scale["ScaleX"]);
+ if(scale["ScaleY"] != null)
+ node.setScaleY(scale["ScaleY"]);
+ }
+
+ var rotationSkewX = json["RotationSkewX"];
+ if (rotationSkewX != null)
+ node.setRotationX(rotationSkewX);
+
+ var rotationSkewY = json["RotationSkewY"];
+ if (json["RotationSkewY"] != null)
+ node.setRotationY(rotationSkewY);
+
+
+ var anchor = json["AnchorPoint"];
+ if(anchor != null){
+ if(anchor["ScaleX"] == null)
+ anchor["ScaleX"] = 0;
+ if(anchor["ScaleY"] == null)
+ anchor["ScaleY"] = 0;
+ if(anchor["ScaleX"] != 0.5 || anchor["ScaleY"] != 0.5)
+ node.setAnchorPoint(cc.p(anchor["ScaleX"], anchor["ScaleY"]));
+ }
+
+ if (json["ZOrder"] != null)
+ node.setLocalZOrder(json["ZOrder"]);
+
+ var visible = getParam(json["VisibleForFrame"], true);
+ node.setVisible(visible);
+
+ var size = json["Size"];
+ if(size)
+ setContentSize(node, size);
+
+ if (json["Alpha"] != null)
+ node.setOpacity(json["Alpha"]);
+
+ node.setTag(json["Tag"] || 0);
+
+ var actionTag = json["ActionTag"] || 0;
+ var extensionData = new ccs.ComExtensionData();
+ var customProperty = json["UserData"];
+ if(customProperty !== undefined)
+ extensionData.setCustomProperty(customProperty);
+ extensionData.setActionTag(actionTag);
+ if (node.getComponent("ComExtensionData"))
+ node.removeComponent("ComExtensionData");
+ node.addComponent(extensionData);
+
+ node.setCascadeColorEnabled(true);
+ node.setCascadeOpacityEnabled(true);
+
+ setLayoutComponent(node, json);
+ };
+
+ parser.parseChild = function(node, children, resourcePath){
+ if(!node || !children) return;
+ for (var i = 0; i < children.length; i++) {
+ var child = this.parseNode(children[i], resourcePath);
+ if(child){
+ if(node instanceof ccui.PageView){
+ if(child instanceof ccui.Layout)
+ node.addPage(child);
+ } else {
+ if(node instanceof ccui.ListView){
+ if(child instanceof ccui.Widget)
+ node.pushBackCustomItem(child);
+ } else {
+ if(!(node instanceof ccui.Layout) && child instanceof ccui.Widget) {
+ if(child.getPositionType() === ccui.Widget.POSITION_PERCENT) {
+ var position = child.getPositionPercent();
+ var anchor = node.getAnchorPoint();
+ child.setPositionPercent(cc.p(position.x + anchor.x, position.y + anchor.y));
+ }
+ }
+ node.addChild(child);
+ }
+ }
+ }
+ }
+ };
+
+ /**
+ * SingleNode
+ * @param json
+ * @returns {cc.Node}
+ */
+ parser.initSingleNode = function(json){
+ var node = new cc.Node();
+
+ this.generalAttributes(node, json);
+ var color = json["CColor"];
+ if(color != null)
+ node.setColor(getColor(color));
+
+ return node;
+ };
+
+ /**
+ * Sprite
+ * @param json
+ * @param resourcePath
+ * @returns {cc.Sprite}
+ */
+ parser.initSprite = function(json, resourcePath){
+ var node = new cc.Sprite();
+
+ loadTexture(json["FileData"], resourcePath, function(path, type){
+ if(type === 0)
+ node.setTexture(path);
+ else if(type === 1){
+ var spriteFrame = cc.spriteFrameCache.getSpriteFrame(path);
+ if(spriteFrame)
+ node.setSpriteFrame(spriteFrame);
+ }
+ });
+
+ var blendData = json["BlendFunc"];
+ if(json["BlendFunc"]) {
+ var blendFunc = cc.BlendFunc.ALPHA_PREMULTIPLIED;
+ if (blendData["Src"] !== undefined)
+ blendFunc.src = blendData["Src"];
+ if (blendData["Dst"] !== undefined)
+ blendFunc.dst = blendData["Dst"];
+ node.setBlendFunc(blendFunc);
+ }
+
+ if(json["FlipX"])
+ node.setFlippedX(true);
+ if(json["FlipY"])
+ node.setFlippedY(true);
+
+ this.generalAttributes(node, json);
+ var color = json["CColor"];
+ if(color != null)
+ node.setColor(getColor(color));
+
+ return node;
+ };
+
+ /**
+ * Particle
+ * @param json
+ * @param resourcePath
+ * @returns {*}
+ */
+ parser.initParticle = function(json, resourcePath){
+ var node,
+ self = this;
+ loadTexture(json["FileData"], resourcePath, function(path, type){
+ if(!cc.loader.getRes(path))
+ cc.log("%s need to be preloaded", path);
+ node = new cc.ParticleSystem(path);
+ self.generalAttributes(node, json);
+ node.setPositionType(cc.ParticleSystem.Type.GROUPED);
+ !cc.sys.isNative && node.setDrawMode(cc.ParticleSystem.TEXTURE_MODE);
+
+ var blendData = json["BlendFunc"];
+ if(json["BlendFunc"]){
+ var blendFunc = cc.BlendFunc.ALPHA_PREMULTIPLIED;
+ if(blendData["Src"] !== undefined)
+ blendFunc.src = blendData["Src"];
+ if(blendData["Dst"] !== undefined)
+ blendFunc.dst = blendData["Dst"];
+ node.setBlendFunc(blendFunc);
+ }
+ });
+ return node;
+ };
+
+
+ ////////////
+ // WIDGET //
+ ////////////
+
+ parser.widgetAttributes = function (widget, json, enableContent) {
+ widget.setCascadeColorEnabled(true);
+ widget.setCascadeOpacityEnabled(true);
+
+ widget.setUnifySizeEnabled(false);
+ //widget.setLayoutComponentEnabled(true);
+ widget.ignoreContentAdaptWithSize(false);
+ !enableContent && setContentSize(widget, json["Size"]);
+
+ var name = json["Name"];
+ if (name)
+ widget.setName(name);
+
+ var actionTag = json["ActionTag"] || 0;
+ widget.setActionTag(actionTag);
+ var extensionData = new ccs.ComExtensionData();
+ var customProperty = json["UserData"];
+ if(customProperty !== undefined)
+ extensionData.setCustomProperty(customProperty);
+ extensionData.setActionTag(actionTag);
+ if (widget.getComponent("ComExtensionData"))
+ widget.removeComponent("ComExtensionData");
+ widget.addComponent(extensionData);
+
+ var rotationSkewX = json["RotationSkewX"];
+ if (rotationSkewX)
+ widget.setRotationX(rotationSkewX);
+
+ var rotationSkewY = json["RotationSkewY"];
+ if (rotationSkewY)
+ widget.setRotationY(rotationSkewY);
+
+ //var rotation = json["Rotation"];
+
+ var flipX = json["FlipX"];
+ if (flipX)
+ widget.setFlippedX(true);
+
+ var flipY = json["FlipY"];
+ if (flipY)
+ widget.setFlippedY(true);
+
+ var zOrder = json["zOrder"];
+ if (zOrder != null)
+ widget.setLocalZOrder(zOrder);
+
+ //var visible = json["Visible"];
+
+ var visible = getParam(json["VisibleForFrame"], true);
+ widget.setVisible(visible);
+
+ var alpha = json["Alpha"];
+ if (alpha != null)
+ widget.setOpacity(alpha);
+
+ widget.setTag(json["Tag"] || 0);
+
+ var touchEnabled = json["TouchEnable"] || false;
+ widget.setTouchEnabled(touchEnabled);
+
+ // -- var frameEvent = json["FrameEvent"];
+
+ var callBackType = json["CallBackType"];
+ if (callBackType != null)
+ widget.setCallbackType(callBackType);
+
+ var callBackName = json["CallBackName"];
+ if (callBackName)
+ widget.setCallbackName(callBackName);
+
+ var position = json["Position"];
+ if (position != null)
+ widget.setPosition(position["X"] || 0, position["Y"] || 0);
+
+ var scale = json["Scale"];
+ if (scale != null) {
+ var scaleX = getParam(scale["ScaleX"], 1);
+ var scaleY = getParam(scale["ScaleY"], 1);
+ widget.setScaleX(scaleX);
+ widget.setScaleY(scaleY);
+ }
+
+ var anchorPoint = json["AnchorPoint"];
+ if (anchorPoint != null)
+ widget.setAnchorPoint(anchorPoint["ScaleX"] || 0, anchorPoint["ScaleY"] || 0);
+
+ var color = json["CColor"];
+ if (color != null)
+ widget.setColor(getColor(color));
+
+ setLayoutComponent(widget, json);
+ bindCallback(widget, json);
+ };
+
+ var bindCallback = function(widget, json){
+ var callBackType = json["CallBackType"];
+ var callBackName = json["CallBackName"];
+ var callBack = function(e){
+ if(typeof widget[callBackName] === "function")
+ widget[callBackName](e);
+ };
+ if(callBackType === "Click"){
+ widget.addClickEventListener(callBack);
+ }else if(callBackType === "Touch"){
+ widget.addTouchEventListener(callBack);
+ }else if(callBackType === "Event"){
+ widget.addCCSEventListener(callBack);
+ }
+ };
+
+ var setLayoutComponent = function(widget, json){
+
+ var layoutComponent = ccui.LayoutComponent.bindLayoutComponent(widget);
+ if(!layoutComponent)
+ return;
+
+ var positionXPercentEnabled = json["PositionPercentXEnable"] || json["PositionPercentXEnabled"] || false;
+ var positionYPercentEnabled = json["PositionPercentYEnable"] || json["PositionPercentYEnabled"] || false;
+ var positionXPercent = 0,
+ positionYPercent = 0,
+ PrePosition = json["PrePosition"];
+ if (PrePosition != null) {
+ positionXPercent = PrePosition["X"] || 0;
+ positionYPercent = PrePosition["Y"] || 0;
+ }
+ var sizeXPercentEnable = json["PercentWidthEnable"] || json["PercentWidthEnabled"] || false;
+ var sizeYPercentEnable = json["PercentHeightEnable"]|| json["PercentHeightEnabled"] || false;
+ var sizeXPercent = 0,
+ sizeYPercent = 0,
+ PreSize = json["PreSize"];
+ if (PrePosition != null) {
+ sizeXPercent = PreSize["X"] || 0;
+ sizeYPercent = PreSize["Y"] || 0;
+ }
+ var stretchHorizontalEnabled = json["StretchWidthEnable"] || false;
+ var stretchVerticalEnabled = json["StretchHeightEnable"] || false;
+ var horizontalEdge = json["HorizontalEdge"];// = ccui.LayoutComponent.horizontalEdge.LEFT;
+ var verticalEdge = json["VerticalEdge"]; // = ccui.LayoutComponent.verticalEdge.TOP;
+ var leftMargin = json["LeftMargin"] || 0;
+ var rightMargin = json["RightMargin"] || 0;
+ var topMargin = json["TopMargin"] || 0;
+ var bottomMargin = json["BottomMargin"] || 0;
+
+ layoutComponent.setPositionPercentXEnabled(positionXPercentEnabled);
+ layoutComponent.setPositionPercentYEnabled(positionYPercentEnabled);
+ layoutComponent.setPositionPercentX(positionXPercent);
+ layoutComponent.setPositionPercentY(positionYPercent);
+ layoutComponent.setPercentWidthEnabled(sizeXPercentEnable);
+ layoutComponent.setPercentHeightEnabled(sizeYPercentEnable);
+ layoutComponent.setPercentWidth(sizeXPercent);
+ layoutComponent.setPercentHeight(sizeYPercent);
+ layoutComponent.setPercentWidthEnabled(sizeXPercentEnable || sizeYPercentEnable);
+ layoutComponent.setStretchWidthEnabled(stretchHorizontalEnabled);
+ layoutComponent.setStretchHeightEnabled(stretchVerticalEnabled);
+
+ var horizontalEdgeType = ccui.LayoutComponent.horizontalEdge.NONE;
+ if (horizontalEdge === "LeftEdge") {
+ horizontalEdgeType = ccui.LayoutComponent.horizontalEdge.LEFT;
+ } else if (horizontalEdge === "RightEdge") {
+ horizontalEdgeType = ccui.LayoutComponent.horizontalEdge.RIGHT;
+ } else if (horizontalEdge === "BothEdge") {
+ horizontalEdgeType = ccui.LayoutComponent.horizontalEdge.CENTER;
+ }
+ layoutComponent.setHorizontalEdge(horizontalEdgeType);
+
+ var verticalEdgeType = ccui.LayoutComponent.verticalEdge.NONE;
+ if (verticalEdge === "TopEdge") {
+ verticalEdgeType = ccui.LayoutComponent.verticalEdge.TOP;
+ } else if (verticalEdge === "BottomEdge") {
+ verticalEdgeType = ccui.LayoutComponent.verticalEdge.BOTTOM;
+ } else if (verticalEdge === "BothEdge") {
+ verticalEdgeType = ccui.LayoutComponent.verticalEdge.CENTER;
+ }
+ layoutComponent.setVerticalEdge(verticalEdgeType);
+
+ layoutComponent.setTopMargin(topMargin);
+ layoutComponent.setBottomMargin(bottomMargin);
+ layoutComponent.setLeftMargin(leftMargin);
+ layoutComponent.setRightMargin(rightMargin);
+
+ layoutComponent.setVerticalEdge(verticalEdgeType);
+
+ layoutComponent.setTopMargin(topMargin);
+ layoutComponent.setBottomMargin(bottomMargin);
+ layoutComponent.setLeftMargin(leftMargin);
+ layoutComponent.setRightMargin(rightMargin);
+ };
+
+ var setLayoutBackground = function(layout, single, first, end){
+ if( layout.getBackGroundColorType() === 2 ){
+ first = first || {};
+ end = end || {};
+ layout.setBackGroundColor(getColor(first), getColor(end));
+ }else{
+ single = single || {};
+ layout.setBackGroundColor(getColor(single));
+ }
+ };
+
+ var setLayoutBackgroundVector = function(widget, vector){
+ var x = vector["ScaleX"] || 0;
+ var y = vector["ScaleY"] || 0;
+ widget.setBackGroundColorVector(cc.p(x, y));
+ };
+
+ /**
+ * Layout
+ * @param json
+ * @param resourcePath
+ * @returns {ccui.Layout}
+ */
+ parser.initPanel = function(json, resourcePath){
+ var widget = new ccui.Layout();
+
+ this.widgetAttributes(widget, json);
+
+ var clipEnabled = json["ClipAble"];
+ if(clipEnabled != null)
+ widget.setClippingEnabled(clipEnabled);
+
+ var colorType = getParam(json["ComboBoxIndex"], 0);
+ widget.setBackGroundColorType(colorType);
+
+ var bgColorOpacity = getParam(json["BackColorAlpha"], 255);
+ if(bgColorOpacity != null)
+ widget.setBackGroundColorOpacity(bgColorOpacity);
+
+ var backGroundScale9Enabled = json["Scale9Enable"];
+ if(backGroundScale9Enabled != null)
+ widget.setBackGroundImageScale9Enabled(backGroundScale9Enabled);
+
+ var opacity = getParam(json["Alpha"], 255);
+ widget.setOpacity(opacity);
+
+ loadTexture(json["FileData"], resourcePath, function(path, type){
+ widget.setBackGroundImage(path, type);
+ });
+
+ if(backGroundScale9Enabled){
+ var scale9OriginX = json["Scale9OriginX"] || 0;
+ var scale9OriginY = json["Scale9OriginY"] || 0;
+
+ var scale9Width = json["Scale9Width"] || 0;
+ var scale9Height = json["Scale9Height"] || 0;
+
+ widget.setBackGroundImageCapInsets(cc.rect(
+ scale9OriginX, scale9OriginY, scale9Width, scale9Height
+ ));
+
+ setContentSize(widget, json["Size"]);
+ }else{
+ if (!widget.isIgnoreContentAdaptWithSize()){
+ setContentSize(widget, json["Size"]);
+ }
+
+ }
+
+ setLayoutBackground(widget, json["SingleColor"], json["FirstColor"], json["EndColor"]);
+ setLayoutBackgroundVector(widget, json["ColorVector"]);
+
+ return widget;
+ };
+
+ /**
+ * Text
+ * @param json
+ * @param resourcePath
+ */
+ parser.initText = function(json, resourcePath){
+
+ var widget = new ccui.Text();
+
+ var touchScaleEnabled = json["TouchScaleChangeAble"];
+ if(touchScaleEnabled != null)
+ widget.setTouchScaleChangeEnabled(touchScaleEnabled);
+
+ var text = json["LabelText"];
+ if(text != null)
+ widget.setString(text);
+
+ var fontSize = json["FontSize"];
+ if(fontSize != null)
+ widget.setFontSize(fontSize);
+
+ var fontName = json["FontName"];
+ if(fontName != null)
+ widget.setFontName(fontName);
+
+ var areaWidth = json["AreaWidth"];
+ var areaHeight = json["areaHeight"];
+ if(areaWidth && areaHeight)
+ widget.setTextAreaSize(cc.size(areaWidth, areaHeight));
+
+ var h_alignment = json["HorizontalAlignmentType"] || "HT_Left";
+ switch(h_alignment){
+ case "HT_Right":
+ h_alignment = 2; break;
+ case "HT_Center":
+ h_alignment = 1; break;
+ case "HT_Left":
+ default:
+ h_alignment = 0;
+ }
+ widget.setTextHorizontalAlignment(h_alignment);
+
+ var v_alignment = json["VerticalAlignmentType"] || "VT_Top";
+ switch(v_alignment){
+ case "VT_Bottom":
+ v_alignment = 2; break;
+ case "VT_Center":
+ v_alignment = 1; break;
+ case "VT_Top":
+ default:
+ v_alignment = 0;
+ }
+ widget.setTextVerticalAlignment(v_alignment);
+
+ var fontResource = json["FontResource"];
+ if(fontResource != null){
+ var path = fontResource["Path"];
+ //resoutceType = fontResource["Type"];
+ if(path != null){
+ if (cc.sys.isNative) {
+ fontName = cc.path.join(cc.loader.resPath, resourcePath, path);
+ } else {
+ fontName = path.match(/([^\/]+)\.(\S+)/);
+ fontName = fontName ? fontName[1] : "";
+ }
+ widget.setFontName(fontName);
+ }
+ }
+
+ if(json["OutlineEnabled"] && json["OutlineColor"] && widget.enableOutline)
+ widget.enableOutline(getColor(json["OutlineColor"]), getParam(json["OutlineSize"], 1));
+
+ if(json["ShadowEnabled"] && json["ShadowColor"] && widget.enableShadow)
+ widget.enableShadow(
+ getColor(json["ShadowColor"]),
+ cc.size(getParam(json["ShadowOffsetX"], 2), getParam(json["ShadowOffsetY"], -2)),
+ json["ShadowBlurRadius"] || 0
+ );
+
+ var isCustomSize = json["IsCustomSize"];
+ if(isCustomSize != null)
+ widget.ignoreContentAdaptWithSize(!isCustomSize);
+
+ widget.setUnifySizeEnabled(false);
+
+ var color = json["CColor"];
+ json["CColor"] = null;
+ widget.setTextColor(getColor(color));
+ this.widgetAttributes(widget, json, widget.isIgnoreContentAdaptWithSize());
+ json["CColor"] = color;
+ return widget;
+
+ };
+
+ /**
+ * Button
+ * @param json
+ * @param resourcePath
+ */
+ parser.initButton = function(json, resourcePath){
+
+ var widget = new ccui.Button();
+
+ loadTexture(json["NormalFileData"], resourcePath, function(path, type){
+ widget.loadTextureNormal(path, type);
+ });
+ loadTexture(json["PressedFileData"], resourcePath, function(path, type){
+ widget.loadTexturePressed(path, type);
+ });
+ loadTexture(json["DisabledFileData"], resourcePath, function(path, type){
+ widget.loadTextureDisabled(path, type);
+ });
+
+ var scale9Enabled = getParam(json["Scale9Enable"], false);
+ if(scale9Enabled) {
+ widget.setScale9Enabled(scale9Enabled);
+ }
+
+ var text = json["ButtonText"];
+ if(text != null)
+ widget.setTitleText(text);
+
+ var fontSize = json["FontSize"];
+ if(fontSize != null)
+ widget.setTitleFontSize(fontSize);
+
+ var fontName = json["FontName"];
+ if(fontName != null)
+ widget.setTitleFontName(fontName);
+
+ var textColor = json["TextColor"];
+ if(textColor != null)
+ widget.setTitleColor(getColor(textColor));
+
+ var displaystate = getParam(json["DisplayState"], true);
+ widget.setBright(displaystate);
+ widget.setEnabled(displaystate);
+
+ var fontResource = json["FontResource"];
+ if(fontResource != null){
+ var path = fontResource["Path"];
+ //resoutceType = fontResource["Type"];
+ if(path != null){
+ if (cc.sys.isNative) {
+ fontName = cc.path.join(cc.loader.resPath, resourcePath, path);
+ } else {
+ fontName = path.match(/([^\/]+)\.(\S+)/);
+ fontName = fontName ? fontName[1] : "";
+ }
+ widget.setTitleFontName(fontName);
+ }
+ }
+
+ var label = widget.getTitleRenderer();
+ if(label && json["ShadowEnabled"] && json["ShadowColor"] && label.enableShadow){
+ label.enableShadow(
+ getColor(json["ShadowColor"]),
+ cc.size(getParam(json["ShadowOffsetX"], 2), getParam(json["ShadowOffsetY"], -2)),
+ json["ShadowBlurRadius"] || 0
+ );
+ }
+ if(label && json["OutlineEnabled"] && json["OutlineColor"] && label.enableStroke)
+ label.enableStroke(getColor(json["OutlineColor"]), getParam(json["OutlineSize"], 1));
+
+ this.widgetAttributes(widget, json);
+
+ if(scale9Enabled) {
+ widget.setUnifySizeEnabled(false);
+ widget.ignoreContentAdaptWithSize(false);
+ var capInsets = cc.rect(
+ json["Scale9OriginX"] || 0,
+ json["Scale9OriginY"] || 0,
+ json["Scale9Width"] || 0,
+ json["Scale9Height"] || 0
+ );
+ widget.setCapInsets(capInsets);
+
+ }
+
+ setContentSize(widget, json["Size"]);
+
+ return widget;
+
+ };
+
+ /**
+ * CheckBox
+ * @param json
+ * @param resourcePath
+ */
+ parser.initCheckBox = function(json, resourcePath){
+
+ var widget = new ccui.CheckBox();
+
+ this.widgetAttributes(widget, json);
+
+ var dataList = [
+ {name: "NormalBackFileData", handle: widget.loadTextureBackGround},
+ {name: "PressedBackFileData", handle: widget.loadTextureBackGroundSelected},
+ {name: "NodeNormalFileData", handle: widget.loadTextureFrontCross},
+ {name: "DisableBackFileData", handle: widget.loadTextureBackGroundDisabled},
+ {name: "NodeDisableFileData", handle: widget.loadTextureFrontCrossDisabled}
+ ];
+
+ dataList.forEach(function(item){
+ loadTexture(json[item.name], resourcePath, function(path, type){
+ item.handle.call(widget, path, type);
+ });
+ });
+
+ var selectedState = getParam(json["CheckedState"], false);
+ widget.setSelected(selectedState);
+
+ var displaystate = getParam(json["DisplayState"], true);
+ widget.setBright(displaystate);
+ widget.setEnabled(displaystate);
+
+ return widget;
+ };
+
+ /**
+ * ScrollView
+ * @param json
+ * @param resourcePath
+ */
+ parser.initScrollView = function(json, resourcePath){
+ var widget = new ccui.ScrollView();
+
+ this.widgetAttributes(widget, json);
+
+ loadTexture(json["FileData"], resourcePath, function(path, type){
+ widget.setBackGroundImage(path, type);
+ });
+
+ var clipEnabled = json["ClipAble"];
+ widget.setClippingEnabled(clipEnabled);
+
+ var colorType = getParam(json["ComboBoxIndex"], 0);
+ widget.setBackGroundColorType(colorType);
+
+ var bgColorOpacity = json["BackColorAlpha"];
+ if(bgColorOpacity != null)
+ widget.setBackGroundColorOpacity(bgColorOpacity);
+
+ var backGroundScale9Enabled = json["Scale9Enable"];
+ if(backGroundScale9Enabled){
+ widget.setBackGroundImageScale9Enabled(true);
+
+
+ var scale9OriginX = json["Scale9OriginX"] || 0;
+ var scale9OriginY = json["Scale9OriginY"] || 0;
+ var scale9Width = json["Scale9Width"] || 0;
+ var scale9Height = json["Scale9Height"] || 0;
+ widget.setBackGroundImageCapInsets(cc.rect(
+ scale9OriginX, scale9OriginY, scale9Width, scale9Height
+ ));
+ setContentSize(widget, json["Size"]);
+ }else if(!widget.isIgnoreContentAdaptWithSize()){
+ setContentSize(widget, json["Size"]);
+ }
+
+ setLayoutBackground(widget, json["SingleColor"], json["FirstColor"], json["EndColor"]);
+ setLayoutBackgroundVector(widget, json["ColorVector"]);
+
+ var innerNodeSize = json["InnerNodeSize"];
+ var innerSize = cc.size(
+ innerNodeSize["Width"] || 0,
+ innerNodeSize["Height"] || 0
+ );
+ widget.setInnerContainerSize(innerSize);
+
+ var direction = 0;
+ if(json["ScrollDirectionType"] === "Vertical") direction = 1;
+ if(json["ScrollDirectionType"] === "Horizontal") direction = 2;
+ if(json["ScrollDirectionType"] === "Vertical_Horizontal") direction = 3;
+ widget.setDirection(direction);
+
+ var bounceEnabled = getParam(json["IsBounceEnabled"], false);
+ widget.setBounceEnabled(bounceEnabled);
+
+ return widget;
+ };
+
+ /**
+ * ImageView
+ * @param json
+ * @param resourcePath
+ */
+ parser.initImageView = function(json, resourcePath){
+
+ var widget = new ccui.ImageView();
+
+ loadTexture(json["FileData"], resourcePath, function(path, type){
+ widget.loadTexture(path, type);
+ });
+ loadTexture(json["ImageFileData"], resourcePath, function(path, type){
+ widget.loadTexture(path, type);
+ });
+
+ var scale9Enabled = json["Scale9Enable"];
+ if(scale9Enabled){
+ widget.setScale9Enabled(true);
+ widget.setUnifySizeEnabled(false);
+ widget.ignoreContentAdaptWithSize(false);
+
+ var scale9OriginX = json["Scale9OriginX"] || 0;
+ var scale9OriginY = json["Scale9OriginY"] || 0;
+ var scale9Width = json["Scale9Width"] || 0;
+ var scale9Height = json["Scale9Height"] || 0;
+ widget.setCapInsets(cc.rect(
+ scale9OriginX ,
+ scale9OriginY,
+ scale9Width,
+ scale9Height
+ ));
+ } else
+ setContentSize(widget, json["Size"]);
+
+ this.widgetAttributes(widget, json);
+
+ return widget;
+ };
+
+ /**
+ * LoadingBar
+ * @param json
+ * @param resourcePath
+ * @returns {ccui.LoadingBar}
+ */
+ parser.initLoadingBar = function(json, resourcePath){
+
+ var widget = new ccui.LoadingBar();
+
+ this.widgetAttributes(widget, json);
+
+ loadTexture(json["ImageFileData"], resourcePath, function(path, type){
+ widget.loadTexture(path, type);
+ });
+
+ var direction = json["ProgressType"] === "Right_To_Left" ? 1 : 0;
+ widget.setDirection(direction);
+
+ var percent = getParam(json["ProgressInfo"], 80);
+ if(percent != null)
+ widget.setPercent(percent);
+
+ return widget;
+
+ };
+
+ /**
+ * Slider
+ * @param json
+ * @param resourcePath
+ */
+ parser.initSlider = function(json, resourcePath){
+
+ var widget = new ccui.Slider();
+ var loader = cc.loader;
+
+ this.widgetAttributes(widget, json);
+
+ var textureList = [
+ {name: "BackGroundData", handle: widget.loadBarTexture},
+ {name: "BallNormalData", handle: widget.loadSlidBallTextureNormal},
+ {name: "BallPressedData", handle: widget.loadSlidBallTexturePressed},
+ {name: "BallDisabledData", handle: widget.loadSlidBallTextureDisabled},
+ {name: "ProgressBarData", handle: widget.loadProgressBarTexture}
+ ];
+ textureList.forEach(function(item){
+ loadTexture(json[item.name], resourcePath, function(path, type){
+ if(type === 0 && !loader.getRes(path))
+ cc.log("%s need to be preloaded", path);
+ item.handle.call(widget, path, type);
+ });
+ });
+
+ var percent = json["PercentInfo"] || 0;
+ widget.setPercent(percent);
+
+ var displaystate = getParam(json["DisplayState"], true);
+ widget.setBright(displaystate);
+ widget.setEnabled(displaystate);
+
+ return widget;
+ };
+
+ /**
+ * PageView
+ * @param json
+ * @param resourcePath
+ */
+ parser.initPageView = function(json, resourcePath){
+
+ var widget = new ccui.PageView();
+
+ this.widgetAttributes(widget, json);
+
+ loadTexture(json["FileData"], resourcePath, function(path, type){
+ widget.setBackGroundImage(path, type);
+ });
+
+ var clipEnabled = json["ClipAble"] || false;
+ widget.setClippingEnabled(clipEnabled);
+
+ var backGroundScale9Enabled = json["Scale9Enable"];
+ if(backGroundScale9Enabled){
+ widget.setBackGroundImageScale9Enabled(true);
+
+ var scale9OriginX = json["Scale9OriginX"] || 0;
+ var scale9OriginY = json["Scale9OriginY"] || 0;
+ var scale9Width = json["Scale9Width"] || 0;
+ var scale9Height = json["Scale9Height"] || 0;
+ widget.setBackGroundImageCapInsets(cc.rect(
+ scale9OriginX,
+ scale9OriginY,
+ scale9Width,
+ scale9Height
+ ));
+ }
+
+ var colorType = getParam(json["ComboBoxIndex"], 0);
+ widget.setBackGroundColorType(colorType);
+
+ setLayoutBackground(widget, json["SingleColor"], json["FirstColor"], json["EndColor"]);
+ setLayoutBackgroundVector(widget, json["ColorVector"]);
+
+ var bgColorOpacity = json["BackColorAlpha"];
+ if(bgColorOpacity != null)
+ widget.setBackGroundColorOpacity(bgColorOpacity);
+
+ setContentSize(widget, json["Size"]);
+
+ return widget;
+
+ };
+
+ /**
+ * ListView
+ * @param json
+ * @param resourcePath
+ * @returns {ccui.ListView}
+ */
+ parser.initListView = function(json, resourcePath){
+
+ var widget = new ccui.ListView();
+
+ this.widgetAttributes(widget, json);
+
+ loadTexture(json["FileData"], resourcePath, function(path, type){
+ widget.setBackGroundImage(path, type);
+ });
+
+ var clipEnabled = json["ClipAble"] || false;
+ widget.setClippingEnabled(clipEnabled);
+
+ var colorType = getParam(json["ComboBoxIndex"], 0);
+ widget.setBackGroundColorType(colorType);
+
+ var bgColorOpacity = getParam(json["BackColorAlpha"], 255);
+ var backGroundScale9Enabled = json["Scale9Enable"];
+ if(backGroundScale9Enabled){
+ widget.setBackGroundImageScale9Enabled(true);
+
+ var scale9OriginX = json["Scale9OriginX"] || 0;
+ var scale9OriginY = json["Scale9OriginY"] || 0;
+ var scale9Width = json["Scale9Width"] || 0;
+ var scale9Height = json["Scale9Height"] || 0;
+ widget.setBackGroundImageCapInsets(cc.rect(
+ scale9OriginX,
+ scale9OriginY,
+ scale9Width,
+ scale9Height
+ ));
+ }
+
+ var directionType = getParam(json["DirectionType"], ccui.ListView.DIR_HORIZONTAL);
+ var verticalType = getParam(json["VerticalType"], "Align_Left");
+ var horizontalType = getParam(json["HorizontalType"], "Align_Top");
+ if(!directionType){
+ widget.setDirection(ccui.ScrollView.Dir.HORIZONTAL);
+ if(verticalType === "Align_Bottom")
+ widget.setGravity(ccui.ListView.GRAVITY_BOTTOM);
+ else if(verticalType === "Align_VerticalCenter")
+ widget.setGravity(ccui.ListView.GRAVITY_CENTER_VERTICAL);
+ else
+ widget.setGravity(ccui.ListView.GRAVITY_TOP);
+ }else if(directionType === "Vertical"){
+ widget.setDirection(ccui.ScrollView.Dir.VERTICAL);
+ if (horizontalType === "")
+ widget.setGravity(ccui.ListView.GRAVITY_LEFT);
+ else if (horizontalType === "Align_Right")
+ widget.setGravity(ccui.ListView.GRAVITY_RIGHT);
+ else if (horizontalType === "Align_HorizontalCenter")
+ widget.setGravity(ccui.ListView.GRAVITY_CENTER_HORIZONTAL);
+ }
+
+
+ var bounceEnabled = getParam(json["IsBounceEnabled"], false);
+ widget.setBounceEnabled(bounceEnabled);
+
+ var itemMargin = json["ItemMargin"] || 0;
+ widget.setItemsMargin(itemMargin);
+
+ var innerSize = json["InnerNodeSize"];
+ //Width
+ if(innerSize != null)
+ widget.setInnerContainerSize(cc.size(innerSize["Widget"]||0, innerSize["Height"]||0));
+
+ setLayoutBackground(widget, json["SingleColor"], json["FirstColor"], json["EndColor"]);
+ setLayoutBackgroundVector(widget, json["ColorVector"]);
+
+ if(bgColorOpacity != null)
+ widget.setBackGroundColorOpacity(bgColorOpacity);
+
+ setContentSize(widget, json["Size"]);
+
+ return widget;
+ };
+
+ /**
+ * TextAtlas
+ * @param json
+ * @param resourcePath
+ * @returns {ccui.TextAtlas}
+ */
+ parser.initTextAtlas = function(json, resourcePath){
+
+ var widget = new ccui.TextAtlas();
+
+ var stringValue = json["LabelText"];
+ var itemWidth = json["CharWidth"];
+ var itemHeight = json["CharHeight"];
+
+ var startCharMap = json["StartChar"];
+
+ loadTexture(json["LabelAtlasFileImage_CNB"], resourcePath, function(path, type){
+ if(!cc.loader.getRes(path))
+ cc.log("%s need to be preloaded", path);
+ if(type === 0){
+ widget.setProperty(stringValue, path, itemWidth, itemHeight, startCharMap);
+ }
+ });
+ this.widgetAttributes(widget, json);
+
+ return widget;
+ };
+
+ /**
+ * TextBMFont
+ * @param json
+ * @param resourcePath
+ * @returns {ccui.TextBMFont}
+ */
+ parser.initTextBMFont = function(json, resourcePath){
+
+ var widget = new ccui.TextBMFont();
+ this.widgetAttributes(widget, json);
+
+ var text = json["LabelText"];
+ widget.setString(text);
+
+ loadTexture(json["LabelBMFontFile_CNB"], resourcePath, function(path, type){
+ if(!cc.loader.getRes(path))
+ cc.log("%s need to be pre loaded", path);
+ widget.setFntFile(path);
+ });
+ widget.ignoreContentAdaptWithSize(true);
+ return widget;
+ };
+
+ /**
+ * TextField
+ * @param json
+ * @param resourcePath
+ * @returns {ccui.TextField}
+ */
+ parser.initTextField = function(json, resourcePath){
+ var widget = new ccui.TextField();
+
+ var passwordEnabled = json["PasswordEnable"];
+ if(passwordEnabled){
+ widget.setPasswordEnabled(true);
+ var passwordStyleText = json["PasswordStyleText"] || "*";
+ widget.setPasswordStyleText(passwordStyleText);
+ }
+
+ var placeHolder = json["PlaceHolderText"];
+ if(placeHolder != null)
+ widget.setPlaceHolder(placeHolder);
+
+ var fontSize = json["FontSize"];
+ if(fontSize != null)
+ widget.setFontSize(fontSize);
+
+ var fontName = json["FontName"];
+ if(fontName != null)
+ widget.setFontName(fontName);
+
+ var maxLengthEnabled = json["MaxLengthEnable"];
+ if(maxLengthEnabled){
+ widget.setMaxLengthEnabled(true);
+ var maxLength = json["MaxLengthText"] || 0;
+ widget.setMaxLength(maxLength);
+ }
+
+ //var isCustomSize = json["IsCustomSize"];
+ this.widgetAttributes(widget, json);
+
+ var text = json["LabelText"];
+ if(text != null)
+ widget.setString(text);
+
+ var fontResource = json["FontResource"];
+ if(fontResource != null){
+ var path = fontResource["Path"];
+ //resoutceType = fontResource["Type"];
+ if(path != null){
+ if (cc.sys.isNative) {
+ fontName = cc.path.join(cc.loader.resPath, resourcePath, path);
+ } else {
+ fontName = path.match(/([^\/]+)\.(\S+)/);
+ fontName = fontName ? fontName[1] : "";
+ }
+ widget.setFontName(fontName);
+ }
+ }
+
+ widget.setUnifySizeEnabled(false);
+ widget.ignoreContentAdaptWithSize(false);
+
+ var color = json["CColor"];
+ if(color != null)
+ widget.setTextColor(getColor(color));
+
+ if (!widget.isIgnoreContentAdaptWithSize()){
+ setContentSize(widget, json["Size"]);
+ if (cc.sys.isNative)
+ widget.getVirtualRenderer().setLineBreakWithoutSpace(true);
+ }
+
+
+ return widget;
+
+ };
+
+ /**
+ * SimpleAudio
+ * @param json
+ * @param resourcePath
+ */
+ parser.initSimpleAudio = function(json, resourcePath){
+
+ var node = new ccs.ComAudio();
+ var loop = json["Loop"] || false;
+ //var volume = json["Volume"] || 0;
+ //cc.audioEngine.setMusicVolume(volume);
+ node.setLoop(loop);
+ loadTexture(json["FileData"], resourcePath, function(path, type){
+ node.setFile(path);
+ });
+
+ };
+
+ /**
+ * GameMap
+ * @param json
+ * @param resourcePath
+ * @returns {*}
+ */
+ parser.initGameMap = function(json, resourcePath){
+
+ var node = null;
+
+ loadTexture(json["FileData"], resourcePath, function(path, type){
+ if(type === 0)
+ node = new cc.TMXTiledMap(path);
+
+ parser.generalAttributes(node, json);
+ });
+
+ return node;
+ };
+
+ /**
+ * ProjectNode
+ * @param json
+ * @param resourcePath
+ * @returns {*}
+ */
+ parser.initProjectNode = function(json, resourcePath){
+ var projectFile = json["FileData"];
+ if(projectFile != null && projectFile["Path"]){
+ var file = resourcePath + projectFile["Path"];
+ if(cc.loader.getRes(file)){
+ var obj = ccs.load(file, resourcePath);
+ parser.generalAttributes(obj.node, json);
+ if(obj.action && obj.node){
+ obj.action.tag = obj.node.tag;
+ var InnerActionSpeed = json["InnerActionSpeed"];
+ if(InnerActionSpeed !== undefined)
+ obj.action.setTimeSpeed(InnerActionSpeed);
+ obj.node.runAction(obj.action);
+ obj.action.gotoFrameAndPause(0);
+ }
+ return obj.node;
+ } else
+ cc.log("%s need to be preloaded", file);
+ }
+ };
+
+ var getFileName = function(name){
+ if(!name) return "";
+ var arr = name.match(/([^\/]+)\.[^\/]+$/);
+ if(arr && arr[1])
+ return arr[1];
+ else
+ return "";
+ };
+
+ /**
+ * Armature
+ * @param json
+ * @param resourcePath
+ */
+ parser.initArmature = function(json, resourcePath){
+
+ var node = new ccs.Armature();
+
+ var isLoop = json["IsLoop"];
+
+ var isAutoPlay = json["IsAutoPlay"];
+
+ var currentAnimationName = json["CurrentAnimationName"];
+
+ loadTexture(json["FileData"], resourcePath, function(path, type){
+ var plists, pngs;
+ var armJson = cc.loader.getRes(path);
+ if(!armJson)
+ cc.log("%s need to be preloaded", path);
+ else{
+ plists = armJson["config_file_path"];
+ pngs = armJson["config_png_path"];
+ plists.forEach(function(plist, index){
+ if(pngs[index])
+ cc.spriteFrameCache.addSpriteFrames(plist, pngs[index]);
+ });
+ }
+ ccs.armatureDataManager.addArmatureFileInfo(path);
+ node.init(getFileName(path));
+ if(isAutoPlay)
+ node.getAnimation().play(currentAnimationName, -1, isLoop);
+ else{
+ node.getAnimation().play(currentAnimationName);
+ node.getAnimation().gotoAndPause(0);
+ }
+
+ });
+
+ delete json["AnchorPoint"];
+ delete json["Size"];
+ parser.generalAttributes(node, json);
+
+ node.setColor(getColor(json["CColor"]));
+ return node;
+ };
+
+ parser.initBoneNode = function(json, resourcePath){
+
+ var node = new ccs.BoneNode();
+
+ var length = json["Length"];
+ if(length !== undefined)
+ node.setDebugDrawLength(length);
+
+ var blendFunc = json["BlendFunc"];
+ if(blendFunc && blendFunc["Src"] !== undefined && blendFunc["Dst"] !== undefined)
+ node.setBlendFunc(new cc.BlendFunc(blendFunc["Src"] || 0, blendFunc["Dst"] || 0));
+
+ parser.generalAttributes(node, json);
+ var color = json["CColor"];
+ if(color && (color["R"] !== undefined || color["G"] !== undefined || color["B"] !== undefined))
+ node.setColor(getColor(color));
+ return node;
+ };
+
+ parser.initSkeletonNode = function(json){
+ var node = new ccs.SkeletonNode();
+ parser.generalAttributes(node, json);
+ var color = json["CColor"];
+ if(color && (color["R"] !== undefined || color["G"] !== undefined || color["B"] !== undefined))
+ node.setColor(getColor(color));
+ return node;
+ };
+
+ var loadedPlist = {};
+ var loadTexture = function(json, resourcePath, cb){
+ if(json != null){
+ var path = json["Path"];
+ var type;
+ if(json["Type"] === "Default" || json["Type"] === "Normal")
+ type = 0;
+ else
+ type = 1;
+ var plist = json["Plist"];
+ if(plist){
+ if(cc.loader.getRes(resourcePath + plist)){
+ loadedPlist[resourcePath + plist] = true;
+ cc.spriteFrameCache.addSpriteFrames(resourcePath + plist);
+ }else{
+ if(!loadedPlist[resourcePath + plist] && !cc.spriteFrameCache.getSpriteFrame(path))
+ cc.log("%s need to be preloaded", resourcePath + plist);
+ }
+ }
+ if(type !== 0){
+ if(cc.spriteFrameCache.getSpriteFrame(path))
+ cb(path, type);
+ else
+ cc.log("failed to get spriteFrame: %s", path);
+ }else
+ cb(resourcePath + path, type);
+ }
+ };
+
+ var getColor = function(json){
+ if(!json) return;
+ var r = json["R"] != null ? json["R"] : 255;
+ var g = json["G"] != null ? json["G"] : 255;
+ var b = json["B"] != null ? json["B"] : 255;
+ var a = json["A"] != null ? json["A"] : 255;
+ return cc.color(r, g, b, a);
+ };
+
+ var setContentSize = function(node, size){
+ var x = size["X"] || 0;
+ var y = size["Y"] || 0;
+ if(size)
+ node.setContentSize(cc.size(x, y));
+ };
+
+ var register = [
+ {name: "SingleNodeObjectData", handle: parser.initSingleNode},
+ {name: "NodeObjectData", handle: parser.initSingleNode},
+ {name: "LayerObjectData", handle: parser.initSingleNode},
+ {name: "GameNodeObjectData", handle: parser.initSingleNode},
+ {name: "GameLayerObjectData", handle: parser.initSingleNode},
+ {name: "SpriteObjectData", handle: parser.initSprite},
+ {name: "ParticleObjectData", handle: parser.initParticle},
+ {name: "PanelObjectData", handle: parser.initPanel},
+ {name: "TextObjectData", handle: parser.initText},
+ {name: "ButtonObjectData", handle: parser.initButton},
+ {name: "CheckBoxObjectData", handle: parser.initCheckBox},
+ {name: "ScrollViewObjectData", handle: parser.initScrollView},
+ {name: "ImageViewObjectData", handle: parser.initImageView},
+ {name: "LoadingBarObjectData", handle: parser.initLoadingBar},
+ {name: "SliderObjectData", handle: parser.initSlider},
+ {name: "PageViewObjectData", handle: parser.initPageView},
+ {name: "ListViewObjectData", handle: parser.initListView},
+ {name: "TextAtlasObjectData", handle: parser.initTextAtlas},
+ {name: "TextBMFontObjectData", handle: parser.initTextBMFont},
+ {name: "TextFieldObjectData", handle: parser.initTextField},
+ {name: "SimpleAudioObjectData", handle: parser.initSimpleAudio},
+ {name: "GameMapObjectData", handle: parser.initGameMap},
+ {name: "ProjectNodeObjectData", handle: parser.initProjectNode},
+ {name: "ArmatureNodeObjectData", handle: parser.initArmature},
+ {name: "BoneNodeObjectData", handle: parser.initBoneNode},
+ {name: "SkeletonNodeObjectData", handle: parser.initSkeletonNode}
+ ];
+
+ register.forEach(function(item){
+ parser.registerParser(item.name, function(options, resourcePath){
+ var node = item.handle.call(this, options, resourcePath);
+ this.parseChild(node, options["Children"], resourcePath);
+ DEBUG && node && (node.__parserName = item.name);
+ return node;
+ });
+ });
+
+
+ load.registerParser("timeline", "2.*", parser);
+
+
+})(ccs._load, ccs._parser);
diff --git a/extensions/cocostudio/loader/parsers/uiParser-1.x.js b/extensions/cocostudio/loader/parsers/uiParser-1.x.js
new file mode 100644
index 0000000000..c14763e875
--- /dev/null
+++ b/extensions/cocostudio/loader/parsers/uiParser-1.x.js
@@ -0,0 +1,698 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+(function(load, baseParser){
+
+ var Parser = baseParser.extend({
+
+ addSpriteFrame: function(textures, resourcePath){
+ if(!textures) return;
+ for (var i = 0; i < textures.length; i++) {
+ cc.spriteFrameCache.addSpriteFrames(resourcePath + textures[i]);
+ }
+ },
+
+ pretreatment: function(json, resourcePath){
+ this.addSpriteFrame(json["textures"], resourcePath);
+ },
+
+ deferred: function(json, resourcePath, node, file){
+ if(node){
+ ccs.actionManager.initWithDictionary(file, json["animation"], node);
+ node.setContentSize(cc.size(json["designWidth"], json["designHeight"]));
+ }
+ }
+
+ });
+ var parser = new Parser();
+
+
+ parser.generalAttributes = function(widget, options){
+ var ignoreSizeExsit = options["ignoreSize"];
+ if(ignoreSizeExsit != null)
+ widget.ignoreContentAdaptWithSize(ignoreSizeExsit);
+
+ if (options["sizeType"])
+ {
+ widget.setSizeType(options["sizeType"]);
+ }
+
+ if (options["positionType"])
+ {
+ widget.setPositionType(options["positionType"]);
+ }
+
+ widget.setSizePercent(cc.p(options["sizePercentX"], options["sizePercentY"]));
+ widget.setPositionPercent(cc.p(options["positionPercentX"], options["positionPercentY"]));
+
+ /* adapt screen */
+ var w = 0, h = 0;
+ var adaptScreen = options["adaptScreen"];
+ if (adaptScreen) {
+ var screenSize = cc.director.getWinSize();
+ w = screenSize.width;
+ h = screenSize.height;
+ } else {
+ w = options["width"];
+ h = options["height"];
+ }
+ widget.setContentSize(w, h);
+
+ widget.setTag(options["tag"]);
+ widget.setActionTag(options["actiontag"]);
+ widget.setTouchEnabled(options["touchAble"]);
+ var name = options["name"];
+ var widgetName = name ? name : "default";
+ widget.setName(widgetName);
+
+ var x = options["x"];
+ var y = options["y"];
+ widget.setPosition(x, y);
+
+ var sx = options["scaleX"]!=null ? options["scaleX"] : 1;
+ widget.setScaleX(sx);
+
+ var sy = options["scaleY"]!=null ? options["scaleY"] : 1;
+ widget.setScaleY(sy);
+
+ var rt = options["rotation"] || 0;
+ widget.setRotation(rt);
+
+ var vb = options["visible"] || false;
+ if(vb != null)
+ widget.setVisible(vb);
+ widget.setLocalZOrder(options["ZOrder"]);
+
+ var layout = options["layoutParameter"];
+ if(layout != null){
+ var layoutParameterDic = options["layoutParameter"];
+ var paramType = layoutParameterDic["type"];
+ var parameter = null;
+
+ switch(paramType){
+ case 0:
+ break;
+ case 1:
+ parameter = new ccui.LinearLayoutParameter();
+ var gravity = layoutParameterDic["gravity"];
+ parameter.setGravity(gravity);
+ break;
+ case 2:
+ parameter = new ccui.RelativeLayoutParameter();
+ var rParameter = parameter;
+ var relativeName = layoutParameterDic["relativeName"];
+ rParameter.setRelativeName(relativeName);
+ var relativeToName = layoutParameterDic["relativeToName"];
+ rParameter.setRelativeToWidgetName(relativeToName);
+ var align = layoutParameterDic["align"];
+ rParameter.setAlign(align);
+ break;
+ default:
+ break;
+ }
+ if(parameter != null){
+ var mgl = layoutParameterDic["marginLeft"]||0;
+ var mgt = layoutParameterDic["marginTop"]||0;
+ var mgr = layoutParameterDic["marginRight"]||0;
+ var mgb = layoutParameterDic["marginDown"]||0;
+ parameter.setMargin(mgl, mgt, mgr, mgb);
+ widget.setLayoutParameter(parameter);
+ }
+ }
+ };
+
+ parser.colorAttributes = function(widget, options){
+ var op = options["opacity"];
+ if(op != null)
+ widget.setOpacity(op);
+ var colorR = options["colorR"];
+ var colorG = options["colorG"];
+ var colorB = options["colorB"];
+ widget.setColor(cc.color((colorR == null) ? 255 : colorR, (colorG == null) ? 255 : colorG, (colorB == null) ? 255 : colorB));
+
+ widget.setFlippedX(options["flipX"]);
+ widget.setFlippedY(options["flipY"]);
+ };
+
+ parser.anchorPointAttributes = function(widget, options){
+ var isAnchorPointXExists = options["anchorPointX"];
+ var anchorPointXInFile;
+ if (isAnchorPointXExists != null)
+ anchorPointXInFile = options["anchorPointX"];
+ else
+ anchorPointXInFile = widget.getAnchorPoint().x;
+
+ var isAnchorPointYExists = options["anchorPointY"];
+ var anchorPointYInFile;
+ if (isAnchorPointYExists != null)
+ anchorPointYInFile = options["anchorPointY"];
+ else
+ anchorPointYInFile = widget.getAnchorPoint().y;
+
+ if (isAnchorPointXExists != null || isAnchorPointYExists != null)
+ widget.setAnchorPoint(cc.p(anchorPointXInFile, anchorPointYInFile));
+ };
+
+ parser.parseChild = function(widget, options, resourcePath){
+ var children = options["children"];
+ for (var i = 0; i < children.length; i++) {
+ var child = this.parseNode(children[i], resourcePath);
+ if(child){
+ if(widget instanceof ccui.PageView)
+ widget.addPage(child);
+ else {
+ if(widget instanceof ccui.ListView){
+ widget.pushBackCustomItem(child);
+ } else {
+ if(!(widget instanceof ccui.Layout)) {
+ if(child.getPositionType() === ccui.Widget.POSITION_PERCENT) {
+ var position = child.getPositionPercent();
+ var anchor = widget.getAnchorPoint();
+ child.setPositionPercent(cc.p(position.x + anchor.x, position.y + anchor.y));
+ }
+ var AnchorPointIn = widget.getAnchorPointInPoints();
+ child.setPosition(cc.p(child.getPositionX() + AnchorPointIn.x, child.getPositionY() + AnchorPointIn.y));
+ }
+ widget.addChild(child);
+ }
+ }
+ }
+ }
+ };
+
+ var getPath = function(res, type, path, cb){
+ if(path){
+ if(type === 0)
+ cb(res + path, type);
+ else
+ cb(path, type);
+ }
+ };
+
+ /**
+ * Panel parser (UILayout)
+ */
+ parser.LayoutAttributes = function(widget, options, resourcePath){
+ var w = 0, h = 0;
+ var adaptScreen = options["adaptScreen"];
+ if (adaptScreen){
+ var screenSize = cc.director.getWinSize();
+ w = screenSize.width;
+ h = screenSize.height;
+ }else{
+ w = options["width"];
+ h = options["height"];
+ }
+ widget.setSize(cc.size(w, h));
+
+ widget.setClippingEnabled(options["clipAble"]);
+
+ var backGroundScale9Enable = options["backGroundScale9Enable"];
+ widget.setBackGroundImageScale9Enabled(backGroundScale9Enable);
+ var cr = options["bgColorR"];
+ var cg = options["bgColorG"];
+ var cb = options["bgColorB"];
+
+ var scr = options["bgStartColorR"];
+ var scg = options["bgStartColorG"];
+ var scb = options["bgStartColorB"];
+
+ var ecr = options["bgEndColorR"];
+ var ecg = options["bgEndColorG"];
+ var ecb = options["bgEndColorB"];
+
+ var bgcv1 = options["vectorX"];
+ var bgcv2 = options["vectorY"];
+ widget.setBackGroundColorVector(cc.p(bgcv1, bgcv2));
+
+ var co = options["bgColorOpacity"];
+
+ var colorType = options["colorType"];
+ widget.setBackGroundColorType(colorType/*ui.LayoutBackGroundColorType(colorType)*/);
+ widget.setBackGroundColor(cc.color(scr, scg, scb), cc.color(ecr, ecg, ecb));
+ widget.setBackGroundColor(cc.color(cr, cg, cb));
+ widget.setBackGroundColorOpacity(co);
+
+
+ var imageFileNameDic = options["backGroundImageData"];
+ if(imageFileNameDic){
+ getPath(resourcePath, imageFileNameDic["resourceType"], imageFileNameDic["path"], function(path, type){
+ widget.setBackGroundImage(path, type);
+ });
+ }
+
+ if (backGroundScale9Enable){
+ var cx = options["capInsetsX"];
+ var cy = options["capInsetsY"];
+ var cw = options["capInsetsWidth"];
+ var ch = options["capInsetsHeight"];
+ widget.setBackGroundImageCapInsets(cc.rect(cx, cy, cw, ch));
+ }
+ if (options["layoutType"])
+ {
+ widget.setLayoutType(options["layoutType"]);
+ }
+ };
+ /**
+ * Button parser (UIButton)
+ */
+ parser.ButtonAttributes = function(widget, options, resourcePath){
+ var button = widget;
+ var scale9Enable = options["scale9Enable"];
+ button.setScale9Enabled(scale9Enable);
+
+ var normalDic = options["normalData"];
+ getPath(resourcePath, normalDic["resourceType"], normalDic["path"], function(path, type){
+ button.loadTextureNormal(path, type);
+ });
+ var pressedDic = options["pressedData"];
+ getPath(resourcePath, pressedDic["resourceType"], pressedDic["path"], function(path, type){
+ button.loadTexturePressed(path, type);
+ });
+ var disabledDic = options["disabledData"];
+ getPath(resourcePath, disabledDic["resourceType"], disabledDic["path"], function(path, type){
+ button.loadTextureDisabled(path, type);
+ });
+ if (scale9Enable) {
+ var cx = options["capInsetsX"];
+ var cy = options["capInsetsY"];
+ var cw = options["capInsetsWidth"];
+ var ch = options["capInsetsHeight"];
+
+ button.setCapInsets(cc.rect(cx, cy, cw, ch));
+ var sw = options["scale9Width"];
+ var sh = options["scale9Height"];
+ if (sw != null && sh != null)
+ button.setSize(cc.size(sw, sh));
+ }
+ var text = options["text"];
+ if (text != null)
+ button.setTitleText(text);
+
+ var cr = options["textColorR"];
+ var cg = options["textColorG"];
+ var cb = options["textColorB"];
+ var cri = cr!==null?options["textColorR"]:255;
+ var cgi = cg!==null?options["textColorG"]:255;
+ var cbi = cb!==null?options["textColorB"]:255;
+
+ button.setTitleColor(cc.color(cri,cgi,cbi));
+ var fs = options["fontSize"];
+ if (fs != null)
+ button.setTitleFontSize(options["fontSize"]);
+ var fn = options["fontName"];
+ if (fn)
+ button.setTitleFontName(options["fontName"]);
+ };
+ /**
+ * CheckBox parser (UICheckBox)
+ */
+ parser.CheckBoxAttributes = function(widget, options, resourcePath){
+ //load background image
+ var backGroundDic = options["backGroundBoxData"];
+ getPath(resourcePath, backGroundDic["resourceType"], backGroundDic["path"], function(path, type){
+ widget.loadTextureBackGround(path, type);
+ });
+
+ //load background selected image
+ var backGroundSelectedDic = options["backGroundBoxSelectedData"];
+ getPath(
+ resourcePath,
+ backGroundSelectedDic["resourceType"] || backGroundDic["resourceType"],
+ backGroundSelectedDic["path"] || backGroundDic["path"],
+ function(path, type){
+ widget.loadTextureBackGroundSelected(path, type);
+ });
+
+ //load frontCross image
+ var frontCrossDic = options["frontCrossData"];
+ getPath(resourcePath, frontCrossDic["resourceType"], frontCrossDic["path"], function(path, type){
+ widget.loadTextureFrontCross(path, type);
+ });
+
+ //load backGroundBoxDisabledData
+ var backGroundDisabledDic = options["backGroundBoxDisabledData"];
+ getPath(
+ resourcePath,
+ backGroundDisabledDic["resourceType"] || frontCrossDic["resourceType"],
+ backGroundDisabledDic["path"] || frontCrossDic["path"],
+ function(path, type){
+ widget.loadTextureBackGroundDisabled(path, type);
+ });
+
+ ///load frontCrossDisabledData
+ var frontCrossDisabledDic = options["frontCrossDisabledData"];
+ getPath(resourcePath, frontCrossDisabledDic["resourceType"], frontCrossDisabledDic["path"], function(path, type){
+ widget.loadTextureFrontCrossDisabled(path, type);
+ });
+
+ if (options["selectedState"])
+ widget.setSelected(options["selectedState"]);
+ };
+ /**
+ * ImageView parser (UIImageView)
+ */
+ parser.ImageViewAttributes = function(widget, options, resourcePath){
+ var imageFileNameDic = options["fileNameData"]
+ getPath(resourcePath, imageFileNameDic["resourceType"], imageFileNameDic["path"], function(path, type){
+ widget.loadTexture(path, type);
+ });
+
+ var scale9EnableExist = options["scale9Enable"];
+ var scale9Enable = false;
+ if (scale9EnableExist){
+ scale9Enable = options["scale9Enable"];
+ }
+ widget.setScale9Enabled(scale9Enable);
+
+ if (scale9Enable){
+ var sw = options["scale9Width"];
+ var sh = options["scale9Height"];
+ if (sw && sh)
+ {
+ var swf = options["scale9Width"];
+ var shf = options["scale9Height"];
+ widget.setSize(cc.size(swf, shf));
+ }
+
+ var cx = options["capInsetsX"];
+ var cy = options["capInsetsY"];
+ var cw = options["capInsetsWidth"];
+ var ch = options["capInsetsHeight"];
+
+ widget.setCapInsets(cc.rect(cx, cy, cw, ch));
+
+ }
+ };
+ /**
+ * TextAtlas parser (UITextAtlas)
+ */
+ parser.TextAtlasAttributes = function(widget, options, resourcePath){
+ var sv = options["stringValue"];
+ var cmf = options["charMapFileData"]; // || options["charMapFile"];
+ var iw = options["itemWidth"];
+ var ih = options["itemHeight"];
+ var scm = options["startCharMap"];
+ if (sv != null && cmf && iw != null && ih != null && scm != null){
+ var cmftDic = options["charMapFileData"];
+ var cmfType = cmftDic["resourceType"];
+ switch (cmfType){
+ case 0:
+ var tp_c = resourcePath;
+ var cmfPath = cmftDic["path"];
+ var cmf_tp = tp_c + cmfPath;
+ widget.setProperty(sv, cmf_tp, iw, ih, scm);
+ break;
+ case 1:
+ cc.log("Wrong res type of LabelAtlas!");
+ break;
+ default:
+ break;
+ }
+ }
+ };
+ /**
+ * TextBMFont parser (UITextBMFont)
+ */
+ parser.TextBMFontAttributes = function(widget, options, resourcePath){
+ var cmftDic = options["fileNameData"];
+ var cmfType = cmftDic["resourceType"];
+ switch (cmfType) {
+ case 0:
+ var tp_c = resourcePath;
+ var cmfPath = cmftDic["path"];
+ var cmf_tp = tp_c + cmfPath;
+ widget.setFntFile(cmf_tp);
+ break;
+ case 1:
+ cc.log("Wrong res type of LabelAtlas!");
+ break;
+ default:
+ break;
+ }
+
+ var text = options["text"];
+ widget.setString(text);
+ };
+ /**
+ * Text parser (UIText)
+ */
+ var regTTF = /\.ttf$/;
+ parser.TextAttributes = function(widget, options, resourcePath){
+ var touchScaleChangeAble = options["touchScaleEnable"];
+ widget.setTouchScaleChangeEnabled(touchScaleChangeAble);
+ var text = options["text"];
+ widget.setString(text);
+ var fs = options["fontSize"];
+ if (fs != null){
+ widget.setFontSize(options["fontSize"]);
+ }
+ var fn = options["fontName"];
+ if (fn != null){
+ if(cc.sys.isNative){
+ if(regTTF.test(fn)){
+ widget.setFontName(cc.path.join(cc.loader.resPath, resourcePath, fn));
+ }else{
+ widget.setFontName(fn);
+ }
+ }else{
+ widget.setFontName(fn.replace(regTTF, ''));
+ }
+ }
+ var aw = options["areaWidth"];
+ var ah = options["areaHeight"];
+ if (aw != null && ah != null){
+ var size = cc.size(options["areaWidth"], options["areaHeight"]);
+ widget.setTextAreaSize(size);
+ }
+ var ha = options["hAlignment"];
+ if (ha != null){
+ widget.setTextHorizontalAlignment(options["hAlignment"]);
+ }
+ var va = options["vAlignment"];
+ if (va != null){
+ widget.setTextVerticalAlignment(options["vAlignment"]);
+ }
+ };
+ /**
+ * ListView parser (UIListView)
+ */
+ parser.ListViewAttributes = function(widget, options, resoutcePath){
+ parser.ScrollViewAttributes(widget, options,resoutcePath);
+ var direction = options["direction"];
+ widget.setDirection(direction);
+ var gravity = options["gravity"];
+ widget.setGravity(gravity);
+ var itemMargin = options["itemMargin"];
+ widget.setItemsMargin(itemMargin);
+ };
+ /**
+ * LoadingBar parser (UILoadingBar)
+ */
+ parser.LoadingBarAttributes = function(widget, options, resourcePath){
+ var imageFileNameDic = options["textureData"];
+ getPath(resourcePath, imageFileNameDic["resourceType"], imageFileNameDic["path"], function(path, type){
+ widget.loadTexture(path, type);
+ });
+
+ var scale9Enable = options["scale9Enable"];
+ widget.setScale9Enabled(scale9Enable);
+
+ if (scale9Enable){
+ var cx = options["capInsetsX"];
+ var cy = options["capInsetsY"];
+ var cw = options["capInsetsWidth"];
+ var ch = options["capInsetsHeight"];
+
+ widget.setCapInsets(cc.rect(cx, cy, cw, ch));
+
+ var width = options["width"];
+ var height = options["height"];
+ widget.setSize(cc.size(width, height));
+ }
+
+ widget.setDirection(options["direction"]);
+ widget.setPercent(options["percent"]);
+ };
+ /**
+ * PageView parser (UIPageView)
+ */
+ parser.PageViewAttributes = parser.LayoutAttributes;
+ /**
+ * ScrollView parser (UIScrollView)
+ */
+ parser.ScrollViewAttributes = function(widget, options, resoutcePath){
+ parser.LayoutAttributes(widget, options,resoutcePath);
+ var innerWidth = options["innerWidth"]!=null ? options["innerWidth"] : 200;
+ var innerHeight = options["innerHeight"]!=null ? options["innerHeight"] : 200;
+ widget.setInnerContainerSize(cc.size(innerWidth, innerHeight));
+
+ var direction = options["direction"]!=null ? options["direction"] : 1;
+ widget.setDirection(direction);
+ widget.setBounceEnabled(options["bounceEnable"]);
+ };
+ /**
+ * Slider parser (UISlider)
+ */
+ parser.SliderAttributes = function(widget, options, resourcePath){
+
+ var slider = widget;
+
+ var barTextureScale9Enable = options["scale9Enable"];
+ slider.setScale9Enabled(barTextureScale9Enable);
+ var bt = options["barFileName"];
+ var barLength = options["length"];
+
+ var imageFileNameDic = options["barFileNameData"];
+ var imageFileType = imageFileNameDic["resourceType"];
+ var imageFileName = imageFileNameDic["path"];
+
+ if(bt != null){
+ if(barTextureScale9Enable){
+ getPath(resourcePath, imageFileType, imageFileName, function(path, type){
+ slider.loadBarTexture(path, type);
+ });
+ slider.setSize(cc.size(barLength, slider.getContentSize().height));
+ }
+ }else{
+ getPath(resourcePath, imageFileType, imageFileName, function(path, type){
+ slider.loadBarTexture(path, type);
+ });
+ }
+
+ var normalDic = options["ballNormalData"];
+ getPath(resourcePath, normalDic["resourceType"], normalDic["path"], function(path, type){
+ slider.loadSlidBallTextureNormal(path, type);
+ });
+
+ var pressedDic = options["ballPressedData"];
+ getPath(
+ resourcePath,
+ pressedDic["resourceType"] || normalDic["resourceType"],
+ pressedDic["path"] || normalDic["path"],
+ function(path, type){
+ slider.loadSlidBallTexturePressed(path, type);
+ });
+
+ var disabledDic = options["ballDisabledData"];
+ getPath(resourcePath, disabledDic["resourceType"], disabledDic["path"], function(path, type){
+ slider.loadSlidBallTextureDisabled(path, type);
+ });
+
+ var progressBarDic = options["progressBarData"];
+ getPath(resourcePath, progressBarDic["resourceType"], progressBarDic["path"], function(path, type){
+ slider.loadProgressBarTexture(path, type);
+ });
+ };
+ /**
+ * TextField parser (UITextField)
+ */
+ parser.TextFieldAttributes = function(widget, options, resourcePath){
+ var ph = options["placeHolder"];
+ if(ph)
+ widget.setPlaceHolder(ph);
+ widget.setString(options["text"]||"");
+ var fs = options["fontSize1"];
+ if(fs)
+ widget.setFontSize(fs);
+ var fn = options["fontName"];
+ if (fn != null){
+ if(cc.sys.isNative){
+ if(regTTF.test(fn)){
+ widget.setFontName(cc.path.join(cc.loader.resPath, resourcePath, fn));
+ }else{
+ widget.setFontName(fn);
+ }
+ }else{
+ widget.setFontName(fn.replace(regTTF, ''));
+ }
+ }
+ var tsw = options["touchSizeWidth"];
+ var tsh = options["touchSizeHeight"];
+ if(tsw!=null && tsh!=null)
+ widget.setTouchSize(tsw, tsh);
+
+ var dw = options["width"];
+ var dh = options["height"];
+ if(dw > 0 || dh > 0){
+ //textField.setSize(cc.size(dw, dh));
+ }
+ var maxLengthEnable = options["maxLengthEnable"];
+ widget.setMaxLengthEnabled(maxLengthEnable);
+
+ if(maxLengthEnable){
+ var maxLength = options["maxLength"];
+ widget.setMaxLength(maxLength);
+ }
+ var passwordEnable = options["passwordEnable"];
+ widget.setPasswordEnabled(passwordEnable);
+ if(passwordEnable)
+ widget.setPasswordStyleText(options["passwordStyleText"]);
+
+ var aw = options["areaWidth"];
+ var ah = options["areaHeight"];
+ if(aw && ah){
+ var size = cc.size(aw, ah);
+ widget.setTextAreaSize(size);
+ }
+ var ha = options["hAlignment"];
+ if(ha)
+ widget.setTextHorizontalAlignment(ha);
+ var va = options["vAlignment"];
+ if(va)
+ widget.setTextVerticalAlignment(va);
+ };
+
+ var register = [
+ {name: "Panel", object: ccui.Layout, handle: parser.LayoutAttributes},
+ {name: "Button", object: ccui.Button, handle: parser.ButtonAttributes},
+ {name: "CheckBox", object: ccui.CheckBox, handle: parser.CheckBoxAttributes},
+ {name: "ImageView", object: ccui.ImageView, handle: parser.ImageViewAttributes},
+ {name: "LabelAtlas", object: ccui.TextAtlas, handle: parser.TextAtlasAttributes},
+ {name: "LabelBMFont", object: ccui.TextBMFont, handle: parser.TextBMFontAttributes},
+ {name: "Label", object: ccui.Text, handle: parser.TextAttributes},
+ {name: "ListView", object: ccui.ListView, handle: parser.ListViewAttributes},
+ {name: "LoadingBar", object: ccui.LoadingBar, handle: parser.LoadingBarAttributes},
+ {name: "PageView", object: ccui.PageView, handle: parser.PageViewAttributes},
+ {name: "ScrollView", object: ccui.ScrollView, handle: parser.ScrollViewAttributes},
+ {name: "Slider", object: ccui.Slider, handle: parser.SliderAttributes},
+ {name: "TextField", object: ccui.TextField, handle: parser.TextFieldAttributes}
+ ];
+
+ register.forEach(function(item){
+ parser.registerParser(item.name, function(options, resourcePath){
+ var widget = new item.object;
+ var uiOptions = options["options"];
+ parser.generalAttributes(widget, uiOptions);
+ item.handle(widget, uiOptions, resourcePath);
+ parser.colorAttributes(widget, uiOptions);
+ parser.anchorPointAttributes(widget, uiOptions);
+ parser.parseChild.call(this, widget, options, resourcePath);
+ return widget;
+ });
+ });
+
+ load.registerParser("ccui", "*", parser);
+
+})(ccs._load, ccs._parser);
\ No newline at end of file
diff --git a/extensions/cocostudio/timeline/ActionTimeline.js b/extensions/cocostudio/timeline/ActionTimeline.js
new file mode 100644
index 0000000000..5467f9198b
--- /dev/null
+++ b/extensions/cocostudio/timeline/ActionTimeline.js
@@ -0,0 +1,541 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+
+/**
+ * ActionTimelineData
+ * @name ccs.ActionTimelineData
+ * @extend ccs.Class
+ * @class
+ *
+ */
+ccs.ActionTimelineData = ccs.Class.extend({
+
+ _actionTag: 0,
+
+ ctor: function(actionTag){
+ this._init(actionTag);
+ },
+
+ _init: function(actionTag){
+ this._actionTag = actionTag;
+ return true;
+ },
+
+ /**
+ * Set the action tag.
+ * @param {number} actionTag
+ */
+ setActionTag: function(actionTag){
+ this._actionTag = actionTag;
+ },
+
+ /**
+ * Gets the action tag.
+ */
+ getActionTag: function(){
+ return this._actionTag;
+ }
+
+});
+
+ccs.AnimationInfo = function(name, start, end){
+ this.name = name;
+ this.startIndex = start;
+ this.endIndex = end;
+};
+
+ccs.ComExtensionData = ccs.Component.extend({
+
+ _customProperty: null,
+ _timelineData: null,
+ _name: "ComExtensionData",
+
+ ctor: function(){
+ this._customProperty = "";
+ this._timelineData = new ccs.ActionTimelineData(0);
+ return true;
+ },
+
+ setActionTag: function(actionTag){
+ this._timelineData.setActionTag(actionTag);
+ },
+
+ getActionTag: function(){
+ return this._timelineData.getActionTag();
+ },
+
+ setCustomProperty: function(customProperty){
+ this._customProperty = customProperty;
+ },
+
+ getCustomProperty: function(){
+ return this._customProperty;
+ }
+
+});
+
+ccs.ComExtensionData.create = function(){
+ return new ccs.ComExtensionData();
+};
+
+/**
+ * Create new ActionTimelineData.
+ *
+ * @deprecated v3.0, please use new ccs.ActionTimelineData() instead.
+ *
+ * @name ccs.ActionTimelineData.create
+ * @function
+ * @param actionTag
+ * @returns {ccs.ActionTimelineData}
+ */
+ccs.ActionTimelineData.create = function(actionTag){
+ return new ccs.ActionTimelineData(actionTag);
+};
+
+
+/**
+ * ActionTimeline
+ * @class
+ * @extend cc.Action
+ *
+ * @property gotoFrameAndPlay
+ * @property gotoFrameAndPause
+ */
+ccs.ActionTimeline = cc.Action.extend({
+
+ _timelineMap: null,
+ _timelineList: null,
+ _duration: 0,
+ _time: null,
+ _timeSpeed: 1,
+ _frameInternal: 1/60,
+ _playing: false,
+ _currentFrame: 0,
+ _startFrame: 0,
+ _endFrame: 0,
+ _loop: null,
+ _frameEventListener: null,
+ _animationInfos: null,
+ _lastFrameListener: null,
+
+ ctor: function(){
+ cc.Action.prototype.ctor.call(this);
+ this._timelineMap = {};
+ this._timelineList = [];
+ this._animationInfos = {};
+ this.init();
+ },
+
+ _gotoFrame: function(frameIndex){
+ var size = this._timelineList.length;
+ for(var i = 0; i < size; i++)
+ {
+ this._timelineList[i]._gotoFrame(frameIndex);
+ }
+ },
+
+ _stepToFrame: function(frameIndex){
+ var size = this._timelineList.length;
+ for(var i = 0; i < size; i++){
+ this._timelineList[i]._stepToFrame(frameIndex);
+ }
+ },
+
+ //emit frame event, call it when enter a frame
+ _emitFrameEvent: function(frame){
+ if(this._frameEventListener){
+ this._frameEventListener(frame);
+ }
+ },
+
+ init: function(){
+ return true;
+ },
+
+ /**
+ * Goto the specified frame index, and start playing from this index.
+ * @param startIndex The animation will play from this index.
+ * @param [endIndex=] The animation will end at this index.
+ * @param [currentFrameIndex=] set current frame index.
+ * @param [loop=] Whether or not the animation need loop.
+ */
+ gotoFrameAndPlay: function(startIndex, endIndex, currentFrameIndex, loop){
+ //Consolidation parameters
+ var i = 0,
+ argLen = arguments.length;
+ var num = [],
+ bool;
+ for(i; i= this._startFrame && frameIndex <= this._endFrame){
+ this._currentFrame = frameIndex;
+ this._time = this._currentFrame * this._frameInternal;
+ }else{
+ cc.log("frame index is not between start frame and end frame");
+ }
+
+ },
+
+ /**
+ * Get current frame.
+ * @returns {number}
+ */
+ getCurrentFrame: function(){
+ return this._currentFrame;
+ },
+
+ /**
+ * add Timeline to ActionTimeline
+ * @param {ccs.Timeline} timeline
+ */
+ addTimeline: function(timeline){
+ var tag = timeline.getActionTag();
+ if (!this._timelineMap[tag]) {
+ this._timelineMap[tag] = [];
+ }
+
+ if (this._timelineMap[tag].indexOf(timeline) === -1) {
+ this._timelineList.push(timeline);
+ this._timelineMap[tag].push(timeline);
+ timeline.setActionTimeline(this);
+ }
+
+ },
+
+ /**
+ * remove Timeline to ActionTimeline
+ * @param {ccs.Timeline} timeline
+ */
+ removeTimeline: function(timeline){
+ var tag = timeline.getActionTag();
+ if (this._timelineMap[tag]) {
+ if(this._timelineMap[tag].some(function(item){
+ if(item === timeline)
+ return true;
+ })) {
+ cc.js.array.remove(this._timelineMap[tag], timeline);
+ cc.js.array.remove(this._timelineList, timeline);
+ timeline.setActionTimeline(null);
+ }
+ }
+ },
+
+ /**
+ * Gets the timeline list
+ * @returns {array | null}
+ */
+ getTimelines: function(){
+ return this._timelineList;
+ },
+
+ /**
+ * Set the Frame event
+ * @param {function} listener
+ */
+ setFrameEventCallFunc: function(listener){
+ this._frameEventListener = listener;
+ },
+
+ /**
+ * remove event
+ */
+ clearFrameEventCallFunc: function(){
+ this._frameEventListener = null;
+ },
+
+ /**
+ * Clone this timeline
+ * @returns {ccs.ActionTimeline}
+ */
+ clone: function(){
+ var newAction = new ccs.ActionTimeline();
+ newAction.setDuration(this._duration);
+ newAction.setTimeSpeed(this._timeSpeed);
+
+ for (var a in this._timelineMap){
+ var timelines = this._timelineMap[a];
+ for(var b in timelines)
+ {
+ var timeline = timelines[b];
+ var newTimeline = timeline.clone();
+ newAction.addTimeline(newTimeline);
+ }
+ }
+
+ return newAction;
+
+ },
+
+ /**
+ * Reverse is not defined;
+ * @returns {null}
+ */
+ reverse: function(){
+ return null;
+ },
+
+ /**
+ * Stepping of this time line.
+ * @param {number} delta
+ */
+ step: function(delta){
+ if (!this._playing || this._timelineMap.length === 0 || this._duration === 0)
+ {
+ return;
+ }
+
+ this._time += delta * this._timeSpeed;
+ var endoffset = this._time - this._endFrame * this._frameInternal;
+
+ if(endoffset < this._frameInternal){
+ this._currentFrame = this._time / this._frameInternal;
+ this._stepToFrame(this._currentFrame);
+ if(endoffset >= 0 && this._lastFrameListener)
+ this._lastFrameListener();
+ }else{
+ this._playing = this._loop;
+ if(!this._playing){
+ this._time = this._endFrame * this._frameInternal;
+ if (this._currentFrame != this._endFrame){
+ this._currentFrame = this._endFrame;
+ this._stepToFrame(this._currentFrame);
+ if(this._lastFrameListener)
+ this._lastFrameListener();
+ }
+ }else
+ this.gotoFrameAndPlay(this._startFrame, this._endFrame, this._loop);
+ }
+
+ },
+
+ _foreachNodeDescendant: function(parent, callback){
+ callback(parent);
+
+ var children = parent.getChildren();
+ for (var i=0; i _renderCmd._debug
+ if (this._squareVertices === null)
+ this._squareVertices = [
+ {x: 0, y: 0}, {x: 0, y: 0}, {x: 0, y: 0}, {x: 0, y: 0}
+ ];
+
+ this._rackColor = cc.Color.WHITE;
+ this._blendFunc = BlendFunc.ALPHA_NON_PREMULTIPLIED;
+
+ this._childBones = [];
+ this._boneSkins = [];
+
+ this._rackLength = length === undefined ? 50 : length;
+ this._rackWidth = 20;
+ this._updateVertices();
+ //this._updateColor();
+ },
+
+ addSkin: function (skin, display, hideOthers/*false*/) {
+ // skin, display
+ // skin, display, hideOthers
+ var boneSkins = this._boneSkins;
+ debug.assert(skin != null, "Argument must be non-nil");
+ if (hideOthers) {
+ for (var i = 0; i < boneSkins.length; i++) {
+ boneSkins[i].setVisible(false);
+ }
+ }
+ Node.prototype.addChild.call(this, skin);
+ this._boneSkins.push(skin);
+ skin.setVisible(display);
+ },
+
+ getChildBones: function () {
+ return this._childBones;
+ },
+
+ getSkins: function () {
+ return this._boneSkins;
+ },
+
+ displaySkin: function (skin, hideOthers) {
+ var boneSkins = this._boneSkins;
+ var boneSkin, i;
+ if (typeof skin === "string") {
+ for (i = 0; i < boneSkins.length; i++) {
+ boneSkin = boneSkins[i];
+ if (skin == boneSkin.getName()) {
+ boneSkin.setVisible(true);
+ } else if (hideOthers) {
+ boneSkin.setVisible(false);
+ }
+ }
+ } else {
+ for (i = 0; i < boneSkins.length; i++) {
+ boneSkin = boneSkins[i];
+ if (boneSkin == skin) {
+ boneSkin.setVisible(true);
+ } else if (hideOthers) {
+ boneSkin.setVisible(false);
+ }
+ }
+ }
+ },
+
+ getVisibleSkins: function () {
+ var displayingSkins = [];
+ var boneSkins = this._boneSkins;
+ for (var boneSkin, i = 0; i < boneSkins.length; i++) {
+ boneSkin = boneSkins[i];
+ if (boneSkin.isVisible()) {
+ displayingSkins.push(boneSkin);
+ }
+ }
+ return displayingSkins;
+ },
+
+ getRootSkeletonNode: function () {
+ return this._rootSkeleton;
+ },
+
+ getAllSubBones: function () {
+ var allBones = [];
+ var boneStack = []; // for avoid recursive
+ var childBones = this._childBones;
+ for (var i = 0; i < childBones.length; i++) {
+ boneStack.push(childBones[i]);
+ }
+
+ while (boneStack.length > 0) {
+ var top = boneStack.pop();
+ allBones.push(top);
+ var topChildren = top.getChildBones();
+ for (var j = 0; j < topChildren; j++) {
+ boneStack.push(topChildren[j]);
+ }
+ }
+ return allBones;
+ },
+
+ getAllSubSkins: function () {
+ var allBones = this.getAllSubBones();
+ var allSkins = [];
+ for (var i = 0; i < allBones.length; i++) {
+ var skins = allBones[i].getSkins();
+ for (var j = 0; j < skins.length; j++) {
+ allSkins.push(skins[i]);
+ }
+ }
+ return allSkins;
+ },
+
+ addChild: function (child, localZOrder, tag) {
+ //child, localZOrder, tag
+ //child, localZOrder, name
+ Node.prototype.addChild.call(this, child, localZOrder, tag);
+ this._addToChildrenListHelper(child);
+ },
+
+ removeChild: function (child, cleanup) {
+ if(this._children.indexOf(child) !== -1){
+ Node.prototype.removeChild.call(this, child, cleanup);
+ this._removeFromChildrenListHelper(child);
+ }
+ },
+
+ setBlendFunc: function (blendFunc) {
+ var ob = this._blendFunc;
+ if(blendFunc && ob.src !== blendFunc.src && ob.dst !== blendFunc.dst){
+ this._blendFunc = blendFunc;
+ var boneSkins = this._boneSkins;
+ for (var boneSkin, i = 0; i < boneSkins.length; i++) {
+ boneSkin = boneSkins[i];
+ boneSkin.setBlendFunc(blendFunc);
+ }
+ }
+ },
+
+ getBlendFunc: function () {
+ return this._blendFunc;
+ },
+
+ setDebugDrawLength: function (length) {
+ this._rackLength = length;
+ this._updateVertices();
+ },
+
+ getDebugDrawLength: function () {
+ return this._rackLength;
+ },
+
+ setDebugDrawWidth: function (width) {
+ this._rackWidth = width;
+ this._updateVertices();
+ },
+
+ getDebugDrawWidth: function () {
+ return this._rackWidth;
+ },
+
+ setDebugDrawEnabled: function (isDebugDraw) {
+ var renderCmd = this._renderCmd;
+ if (renderCmd._debug === isDebugDraw)
+ return;
+
+ renderCmd._debug = isDebugDraw;
+ cc.renderer.childrenOrderDirty = true;
+
+ if(this._visible && null != this._rootSkeleton){
+ this._rootSkeleton._subBonesDirty = true;
+ this._rootSkeleton._subBonesOrderDirty = true;
+ }
+ },
+
+ isDebugDrawEnabled: function () {
+ return this._renderCmd._debug;
+ },
+
+ setDebugDrawColor: function (color) {
+ this._rackColor = color;
+ },
+
+ getDebugDrawColor: function () {
+ return this._rackColor;
+ },
+
+ getVisibleSkinsRect: function () {
+ var minx, miny, maxx, maxy = 0;
+ minx = miny = maxx = maxy;
+ var first = true;
+
+ var displayRect = type.rect(0, 0, 0, 0);
+ if (this._renderCmd._debug && this._rootSkeleton != null && this._rootSkeleton._renderCmd._debug) {
+ maxx = this._rackWidth;
+ maxy = this._rackLength;
+ first = false;
+ }
+
+ var boneSkins = this._boneSkins;
+ for (var skin, i = 0; i < boneSkins.length; i++) {
+ skin = boneSkins[i];
+ var r = skin.getBoundingBox();
+ if (!skin.isVisible() || (r.x === 0 && r.y === 0 && r.width === 0 && r.height === 0))
+ continue;
+
+ if (first) {
+ minx = cc.rectGetMinX(r);
+ miny = cc.rectGetMinY(r);
+ maxx = cc.rectGetMaxX(r);
+ maxy = cc.rectGetMaxY(r);
+
+ first = false;
+ } else {
+ minx = Math.min(cc.rectGetMinX(r), minx);
+ miny = Math.min(cc.rectGetMinY(r), miny);
+ maxx = Math.max(cc.rectGetMaxX(r), maxx);
+ maxy = Math.max(cc.rectGetMaxY(r), maxy);
+ }
+ displayRect.setRect(minx, miny, maxx - minx, maxy - miny);
+ }
+ return displayRect;
+ },
+
+ getBoundingBox: function () {
+ var boundingBox = this.getVisibleSkinsRect();
+ return cc.rectApplyAffineTransform(boundingBox, this.getNodeToParentAffineTransform());
+ },
+
+ batchBoneDrawToSkeleton: function (bone) {},
+
+ setLocalZOrder: function (localZOrder) {
+ Node.prototype.setLocalZOrder.call(this, localZOrder);
+ if (this._rootSkeleton != null)
+ this._rootSkeleton._subBonesOrderDirty = true;
+ },
+
+ setName: function (name) {
+ var rootSkeleton = this._rootSkeleton;
+ var oldName = this.getName();
+ Node.prototype.setName.call(this, name);
+ if (rootSkeleton != null) {
+ var oIter = rootSkeleton._subBonesMap[oldName];
+ var nIter = rootSkeleton._subBonesMap[name];
+ if (oIter && !nIter) {
+ delete rootSkeleton._subBonesMap[oIter];
+ rootSkeleton._subBonesMap[name] = oIter;
+ }
+ }
+ },
+
+ setContentSize: function(contentSize){
+ Node.prototype.setContentSize.call(this, contentSize);
+ this._updateVertices();
+ },
+
+ setAnchorPoint: function(anchorPoint){
+ Node.prototype.setAnchorPoint.call(this, anchorPoint);
+ this._updateVertices();
+ },
+
+ setVisible: function (visible) {
+ if (this._visible == visible)
+ return;
+ Node.prototype.setVisible.call(this, visible);
+ if (this._rootSkeleton != null){
+ this._rootSkeleton._subBonesDirty = true;
+ this._rootSkeleton._subBonesOrderDirty = true;
+ }
+ },
+
+ _addToChildrenListHelper: function (child) {
+ if (child instanceof BoneNode) {
+ this._addToBoneList(child);
+ } else {
+ //if (child instanceof SkinNode) {
+ this._addToSkinList(child);
+ //}
+ }
+ },
+
+ _removeFromChildrenListHelper: function (child) {
+ if (child instanceof BoneNode) {
+ this._removeFromBoneList(child);
+ }else{
+ if (child instanceof SkinNode)
+ this._removeFromSkinList(skin);
+ }
+ },
+
+ _removeFromBoneList: function (bone) {
+ if(
+ this._rootSkeleton != null &&
+ bone instanceof ccs.SkeletonNode &&
+ bone._rootSkeleton === this._rootSkeleton
+ ){
+ bone._rootSkeleton = null;
+ var subBones = bone.getAllSubBones();
+ subBones.push(bone);
+ for (var subBone, i = 0; i < subBones.length; i++) {
+ subBone = subBones[i];
+ subBone._rootSkeleton = null;
+ delete this._rootSkeleton._subBonesMap[subBone.getName()];
+ this._rootSkeleton._subBonesDirty = true;
+ this._rootSkeleton._subBonesOrderDirty = true;
+ }
+ }else{
+ this._rootSkeleton._subBonesDirty = true;
+ this._rootSkeleton._subBonesOrderDirty = true;
+ }
+ cc.js.array.remove(this._childBones, bone);
+ },
+
+ _setRootSkeleton: function(rootSkeleton){
+ this._rootSkeleton = rootSkeleton;
+ var subBones = this.getAllSubBones();
+ for (var i = 0; i < subBones.length; i++) {
+ this._addToBoneList(subBones[i]);
+ }
+ },
+
+ _addToBoneList: function (bone) {
+ if(this._childBones.indexOf(bone) === -1)
+ this._childBones.push(bone);
+ if (this._rootSkeleton != null) {
+ var skeletonNode = bone;
+ if (!(skeletonNode instanceof SkinNode) && !bone._rootSkeleton) {// not nest skeleton
+ var subBones = bone.getAllSubBones();
+ subBones.push(bone);
+ for (var subBone, i = 0; i < subBones.length; i++) {
+ subBone = subBones[i];
+ subBone._setRootSkeleton(this._rootSkeleton);
+ var bonename = subBone.getName();
+ if (!this._rootSkeleton._subBonesMap[bonename]){
+ this._rootSkeleton._subBonesMap[subBone.getName()] = subBone;
+ this._rootSkeleton._subBonesDirty = true;
+ this. _rootSkeleton._subBonesOrderDirty = true;
+ }else{
+ cc.log("already has a bone named %s in skeleton %s", bonename, this._rootSkeleton.getName());
+ this._rootSkeleton._subBonesDirty = true;
+ this. _rootSkeleton._subBonesOrderDirty = true;
+ }
+ }
+ }
+ }
+ },
+
+ _visitSkins: function(){
+ var cmd = this._renderCmd;
+ // quick return if not visible
+ if (!this._visible)
+ return;
+
+ var parentCmd = cmd.getParentRenderCmd();
+ if (parentCmd)
+ cmd._curLevel = parentCmd._curLevel + 1;
+
+ //visit for canvas
+ var i, children = this._boneSkins, child;
+ //var i, children = this._children, child;
+ cmd._syncStatus(parentCmd);
+ var len = children.length;
+ if (len > 0) {
+ this.sortAllChildren();
+ // draw children zOrder < 0
+ for (i = 0; i < len; i++) {
+ child = children[i];
+ if (child._localZOrder < 0)
+ child._renderCmd.visit(cmd);
+ else
+ break;
+ }
+ for (; i < len; i++)
+ children[i]._renderCmd.visit(cmd);
+ }
+ cmd._dirtyFlag = 0;
+ },
+
+ _addToSkinList: function (skin) {
+ this._boneSkins.push(skin);
+ if (skin.getBlendFunc){
+ var blendFunc = skin.getBlendFunc();
+ if(this._blendFunc.src !== blendFunc.src && this._blendFunc.dst !== blendFunc.dst)
+ skin.setBlendFunc(this._blendFunc);
+ }
+ },
+
+ _removeFromSkinList: function (skin) {
+ cc.js.array.remove(this._boneSkins, skin);
+ },
+
+ sortAllChildren: function () {
+ this._sortArray(this._childBones);
+ this._sortArray(this._boneSkins);
+ Node.prototype.sortAllChildren.call(this);
+ },
+
+ _sortArray: function (array) {
+ if (!array)
+ return;
+ var len = array.length, i, j, tmp;
+ for (i = 1; i < len; i++) {
+ tmp = array[i];
+ j = i - 1;
+ while (j >= 0) {
+ if (tmp._localZOrder < array[j]._localZOrder) {
+ array[j + 1] = array[j];
+ } else if (tmp._localZOrder === array[j]._localZOrder && tmp.arrivalOrder < array[j].arrivalOrder) {
+ array[j + 1] = array[j];
+ } else {
+ break;
+ }
+ j--;
+ }
+ array[j + 1] = tmp;
+ }
+ },
+
+ _updateVertices: function () {
+ var squareVertices = this._squareVertices,
+ anchorPointInPoints = this._renderCmd._anchorPointInPoints;
+ if (this._rackLength != squareVertices[2].x - anchorPointInPoints.x ||
+ squareVertices[3].y != this._rackWidth / 2 - anchorPointInPoints.y) {
+
+ squareVertices[1].x = squareVertices[1].y = squareVertices[3].y = 0;
+ squareVertices[0].x = squareVertices[2].x = this._rackLength * .1;
+ squareVertices[2].y = this._rackWidth * .5;
+ squareVertices[0].y = -squareVertices[2].y;
+ squareVertices[3].x = this._rackLength;
+
+ for(var i=0; i 0){
+ var top = boneStack.pop();
+ var topCmd = top._renderCmd;
+ topCmd._syncStatus(topCmd.getParentRenderCmd());
+ this._subOrderedAllBones.push(top);
+
+ var topChildren = top.getChildBones();
+
+ for (var childbone, i=0; i= this._frames[0].getFrameIndex())
+ needEnterFrame = true;
+
+ this._fromIndex = 0;
+ this._toIndex = 0;
+
+ from = to = this._frames[0];
+ this._currentKeyFrameIndex = 0;
+ this._betweenDuration = this._frames[0].getFrameIndex();
+ break;
+ }else if(frameIndex >= this._frames[length - 1].getFrameIndex()){
+ this._fromIndex = length - 1;
+ this._toIndex = 0;
+
+ from = to = this._frames[length - 1];
+ this._currentKeyFrameIndex = this._frames[length - 1].getFrameIndex();
+ this._betweenDuration = 0;
+ break;
+ }
+
+ var target = -1;
+ var low = 0,
+ high = length - 1,
+ mid = 0;
+ while(low <= high){
+ mid = Math.ceil(( low + high )/2);
+ if(frameIndex >= this._frames[mid].getFrameIndex() && frameIndex < this._frames[mid + 1].getFrameIndex())
+ {
+ target = mid;
+ break;
+ }
+ if(this._frames[mid].getFrameIndex()>frameIndex)
+ high = mid - 1;
+ else
+ low = mid + 1;
+ }
+
+ this._fromIndex = target;
+
+ if(length > 1)
+ this._toIndex = (target + 1) | 0;
+ else
+ this._toIndex = (target) | 0;
+
+ from = this._frames[this._fromIndex];
+ to = this._frames[this._toIndex];
+
+ from = this._frames[target];
+ to = this._frames[target+1];
+
+ if(target === 0 && this._currentKeyFrameIndex < from.getFrameIndex())
+ needEnterFrame = true;
+
+ this._currentKeyFrameIndex = from.getFrameIndex();
+ this._betweenDuration = to.getFrameIndex() - from.getFrameIndex();
+ } while (0);
+
+ if(needEnterFrame || this._currentKeyFrame != from) {
+ this._currentKeyFrame = from;
+ this._currentKeyFrame.onEnter(to);
+ }
+
+ },
+
+ _updateCurrentKeyFrame: function(frameIndex){
+ if(frameIndex > 60)
+ var a = 0;
+ //! If play to current frame's front or back, then find current frame again
+ if (frameIndex < this._currentKeyFrameIndex || frameIndex >= this._currentKeyFrameIndex + this._betweenDuration)
+ {
+ var from = null;
+ var to = null;
+
+ do
+ {
+ var length = this._frames.length;
+
+ if (frameIndex < this._frames[0].getFrameIndex())
+ {
+ from = to = this._frames[0];
+ this._currentKeyFrameIndex = 0;
+ this._betweenDuration = this._frames[0].getFrameIndex();
+ break;
+ }
+ else if(frameIndex >= this._frames[length - 1].getFrameIndex())
+ {
+ var lastFrameIndex = this._frames[length - 1].getFrameIndex();
+ if(this._currentKeyFrameIndex >= lastFrameIndex)
+ return;
+ frameIndex = lastFrameIndex;
+ }
+
+ do{
+ this._fromIndex = this._toIndex;
+ from = this._frames[this._fromIndex];
+ this._currentKeyFrameIndex = from.getFrameIndex();
+
+ this._toIndex = this._fromIndex + 1;
+ if (this._toIndex >= length)
+ {
+ this._toIndex = 0;
+ }
+
+ to = this._frames[this._toIndex];
+
+ if (frameIndex === from.getFrameIndex())
+ break;
+ if(frameIndex > from.getFrameIndex() && frameIndex < to.getFrameIndex())
+ break;
+ if(from.isEnterWhenPassed())
+ from.onEnter(to);
+ }while (true);
+
+ this._betweenDuration = to.getFrameIndex() - from.getFrameIndex();
+
+ } while (0);
+
+ this._currentKeyFrame = from;
+ this._currentKeyFrame.onEnter(to);
+ }
+ }
+
+});
+
+/**
+ * Create the Timeline
+ *
+ * @deprecated v3.0, please use new ccs.Timeline() instead.
+ * @returns {ccs.Timeline}
+ */
+ccs.Timeline.create = function(){
+ return new ccs.Timeline();
+};
diff --git a/extensions/cocostudio/trigger/ObjectFactory.js b/extensions/cocostudio/trigger/ObjectFactory.js
new file mode 100644
index 0000000000..29c21c8c8d
--- /dev/null
+++ b/extensions/cocostudio/trigger/ObjectFactory.js
@@ -0,0 +1,99 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+/**
+ * The singleton object that creating object factory, it creates object with class name, and manager the type mapping.
+ * @class
+ * @name ccs.objectFactory
+ */
+ccs.objectFactory = /** @lends ccs.objectFactory# */{
+ _typeMap: {},
+
+ /**
+ * Creates object with class name. if the the class name without register in type map, it returns null.
+ * @param {String} className
+ * @returns {*}
+ */
+ createObject: function (className) {
+ var o = null;
+ var t = this._typeMap[className];
+ if (t) {
+ if(cc.js.isFunction(t._fun))
+ o = new t._fun();
+ else
+ o = t._fun;
+ }
+ return o;
+ },
+
+ /**
+ * Registers class type in type map.
+ * @param {ccs.TInfo} t
+ */
+ registerType: function (t) {
+ this._typeMap[t._className] = t;
+ },
+
+ /**
+ * Creates ccui widget object.
+ * @param {String} name widget name
+ * @returns {ccui.Widget|null}
+ */
+ createGUI: function(name){
+ var object = null;
+ if(name === "Panel")
+ name = "Layout";
+ else if(name === "TextArea")
+ name = "Label";
+ else if(name === "TextButton")
+ name = "Button";
+
+ var t = this._typeMap[name];
+ if(t && t._fun)
+ object = t._fun;
+
+ return object;
+ },
+
+ removeAll: function(){
+ this._typeMap = {};
+ }
+};
+
+ccs.TInfo = ccs.Class.extend({
+ _className: "",
+ _fun: null,
+
+ ctor: function (c, f) {
+ if (f) {
+ this._className = c;
+ this._fun = f;
+ } else {
+ this._className = c._className;
+ this._fun = c._fun;
+ }
+ ccs.objectFactory.registerType(this);
+ }
+});
diff --git a/extensions/cocostudio/trigger/TriggerBase.js b/extensions/cocostudio/trigger/TriggerBase.js
new file mode 100644
index 0000000000..4c773e4476
--- /dev/null
+++ b/extensions/cocostudio/trigger/TriggerBase.js
@@ -0,0 +1,49 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+/**
+ * Sends event by trigger manager.
+ * @function
+ * @param {Number} event
+ */
+ccs.sendEvent = function (event) {
+ var triggerObjArr = ccs.triggerManager.get(event);
+ if (triggerObjArr == null)
+ return;
+ for (var i = 0; i < triggerObjArr.length; i++) {
+ var triObj = triggerObjArr[i];
+ if (triObj != null && triObj.detect())
+ triObj.done();
+ }
+};
+
+/**
+ * Registers a trigger class to objectFactory type map.
+ * @param {String} className
+ * @param {function} func
+ */
+ccs.registerTriggerClass = function (className, func) {
+ new ccs.TInfo(className, func);
+};
\ No newline at end of file
diff --git a/extensions/cocostudio/trigger/TriggerMng.js b/extensions/cocostudio/trigger/TriggerMng.js
new file mode 100644
index 0000000000..e0167a1ab6
--- /dev/null
+++ b/extensions/cocostudio/trigger/TriggerMng.js
@@ -0,0 +1,301 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+/**
+ * The trigger manager of Cocostudio
+ * @class
+ * @name ccs.triggerManager
+ */
+ccs.triggerManager = /** @lends ccs.triggerManager# */{
+ _eventTriggers: {},
+ _triggerObjs: {},
+ _movementDispatches: [],
+
+ /**
+ * Parses the triggers.
+ * @param {Array} triggers
+ */
+ parse: function (triggers) {
+ for (var i = 0; i < triggers.length; ++i) {
+ var subDict = triggers[i];
+ var triggerObj = new ccs.TriggerObj();
+ triggerObj.serialize(subDict);
+ var events = triggerObj.getEvents();
+ for (var j = 0; j < events.length; j++) {
+ var event = events[j];
+ this.add(event, triggerObj);
+ }
+ this._triggerObjs[triggerObj.getId()] = triggerObj;
+ }
+ },
+
+ /**
+ * Returns the event triggers by event id.
+ * @param {Number} event
+ * @returns {Array}
+ */
+ get: function (event) {
+ return this._eventTriggers[event];
+ },
+
+ /**
+ * Returns the trigger object by id
+ * @param {Number} id
+ * @returns {ccs.TriggerObj}
+ */
+ getTriggerObj: function (id) {
+ return this._triggerObjs[id];
+ },
+
+ /**
+ * Adds event and trigger object to trigger manager.
+ * @param event
+ * @param triggerObj
+ */
+ add: function (event, triggerObj) {
+ var eventTriggers = this._eventTriggers[event];
+ if (!eventTriggers)
+ eventTriggers = [];
+ if (eventTriggers.indexOf(triggerObj) === -1) {
+ eventTriggers.push(triggerObj);
+ this._eventTriggers[event] = eventTriggers;
+ }
+ },
+
+ /**
+ * Removes all event triggers from manager.
+ */
+ removeAll: function () {
+ for (var key in this._eventTriggers) {
+ var triObjArr = this._eventTriggers[key];
+ for (var j = 0; j < triObjArr.length; j++) {
+ var obj = triObjArr[j];
+ obj.removeAll();
+ }
+ }
+ this._eventTriggers = {};
+ },
+
+ /**
+ * Removes event object from trigger manager.
+ * @param {*} event
+ * @param {*} Obj
+ * @returns {Boolean}
+ */
+ remove: function (event, Obj) {
+ if (Obj)
+ return this._removeObj(event, Obj);
+
+ var bRet = false;
+ do {
+ var triObjects = this._eventTriggers[event];
+ if (!triObjects)
+ break;
+ for (var i = 0; i < triObjects.length; i++) {
+ var triObject = triObjects[i];
+ if (triObject)
+ triObject.removeAll();
+ }
+ delete this._eventTriggers[event];
+ bRet = true;
+ } while (0);
+ return bRet;
+ },
+
+ _removeObj: function (event, Obj) {
+ var bRet = false;
+ do
+ {
+ var triObjects = this._eventTriggers[event];
+ if (!triObjects) break;
+ for (var i = 0; i < triObjects.length; i++) {
+ var triObject = triObjects[i];
+ if (triObject && triObject == Obj) {
+ triObject.removeAll();
+ triObjects.splice(i, 1);
+ break;
+ }
+ }
+ bRet = true;
+ } while (0);
+ return bRet;
+ },
+
+ /**
+ * Removes trigger object from manager
+ * @param {Number} id
+ * @returns {boolean}
+ */
+ removeTriggerObj: function (id) {
+ var obj = this.getTriggerObj(id);
+ if (!obj)
+ return false;
+ var events = obj.getEvents();
+ for (var i = 0; i < events.length; i++) {
+ var event = events[i];
+ this.remove(event, obj);
+ }
+ return true;
+ },
+
+ /**
+ * Returns the event triggers whether is empty.
+ * @returns {boolean}
+ */
+ isEmpty: function () {
+ return !this._eventTriggers || this._eventTriggers.length <= 0;
+ },
+
+ /**
+ * Adds an armature movement callback to manager.
+ * @param {ccs.Armature} armature
+ * @param {function} callFunc
+ * @param {Object} target
+ */
+ addArmatureMovementCallBack: function (armature, callFunc, target) {
+ if (armature == null || target == null || callFunc == null)
+ return;
+ var locAmd, hasADD = false;
+ for (var i = 0; i < this._movementDispatches.length; i++) {
+ locAmd = this._movementDispatches[i];
+ if (locAmd && locAmd[0] === armature) {
+ locAmd.addAnimationEventCallBack(callFunc, target);
+ hasADD = true;
+ }
+ }
+ if (!hasADD) {
+ var newAmd = new ccs.ArmatureMovementDispatcher();
+ armature.getAnimation().setMovementEventCallFunc(newAmd.animationEvent, newAmd);
+ newAmd.addAnimationEventCallBack(callFunc, target);
+ this._movementDispatches.push([armature, newAmd]);
+ }
+ },
+
+ /**
+ * Removes armature movement callback from manager.
+ * @param {ccs.Armature} armature
+ * @param {Object} target
+ * @param {function} callFunc
+ */
+ removeArmatureMovementCallBack: function (armature, target, callFunc) {
+ if (armature == null || target == null || callFunc == null)
+ return;
+ var locAmd;
+ for (var i = 0; i < this._movementDispatches.length; i++) {
+ locAmd = this._movementDispatches[i];
+ if (locAmd && locAmd[0] === armature)
+ locAmd.removeAnimationEventCallBack(callFunc, target);
+ }
+ },
+
+ /**
+ * Removes an armature's all movement callbacks.
+ * @param {ccs.Armature} armature
+ */
+ removeArmatureAllMovementCallBack: function (armature) {
+ if (armature == null)
+ return;
+ var locAmd;
+ for (var i = 0; i < this._movementDispatches.length; i++) {
+ locAmd = this._movementDispatches[i];
+ if (locAmd && locAmd[0] === armature) {
+ this._movementDispatches.splice(i, 1);
+ break;
+ }
+ }
+ },
+
+ /**
+ * Removes all armature movement callbacks from ccs.triggerManager.
+ */
+ removeAllArmatureMovementCallBack: function () {
+ this._movementDispatches.length = 0;
+ },
+
+ /**
+ * Returns the version of ccs.triggerManager
+ * @returns {string}
+ */
+ version: function () {
+ return "1.2.0.0";
+ }
+};
+
+/**
+ * The armature movement dispatcher for trigger manager.
+ * @class
+ * @extends ccs.Class
+ */
+ccs.ArmatureMovementDispatcher = ccs.Class.extend(/** @lends ccs.ArmatureMovementDispatcher# */{
+ _mapEventAnimation: null,
+
+ /**
+ * Constructor of ArmatureMovementDispatcher.
+ */
+ ctor: function () {
+ this._mapEventAnimation = [];
+ },
+
+ /**
+ * Calls armature movement events.
+ * @param {ccs.Armature} armature
+ * @param {Number} movementType
+ * @param {String} movementID
+ */
+ animationEvent: function (armature, movementType, movementID) {
+ var locEventAni, locTarget, locFunc;
+ for (var i = 0; i < this._mapEventAnimation.length; i++) {
+ locEventAni = this._mapEventAnimation[i];
+ locTarget = locEventAni[0];
+ locFunc = locEventAni[1];
+ if (locFunc)
+ locFunc.call(locTarget, armature, movementType, movementID);
+ }
+ },
+
+ /**
+ * Adds animation event callback to event animation list
+ * @param {function} callFunc
+ * @param {Object|null} [target]
+ */
+ addAnimationEventCallBack: function (callFunc, target) {
+ this._mapEventAnimation.push([target, callFunc]);
+ },
+
+ /**
+ * Removes animation event callback from trigger manager.
+ * @param {function} callFunc
+ * @param {Object|null} [target]
+ */
+ removeAnimationEventCallBack: function (callFunc, target) {
+ var locEventAni;
+ for (var i = 0; i < this._mapEventAnimation.length; i++) {
+ locEventAni = this._mapEventAnimation[i];
+ if (locEventAni[0] === target) {
+ this._mapEventAnimation.splice(i, 1);
+ }
+ }
+ }
+});
\ No newline at end of file
diff --git a/extensions/cocostudio/trigger/TriggerObj.js b/extensions/cocostudio/trigger/TriggerObj.js
new file mode 100644
index 0000000000..6a8e3c1226
--- /dev/null
+++ b/extensions/cocostudio/trigger/TriggerObj.js
@@ -0,0 +1,263 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+/**
+ * The base class of trigger condition.
+ * @class
+ * @extends ccs.Class
+ */
+ccs.BaseTriggerCondition = ccs.Class.extend(/** @lends ccs.BaseTriggerCondition# */{
+ /**
+ * Construction of ccs.BaseTriggerCondition
+ */
+ ctor:function(){
+ },
+
+ /**
+ * initializes a BaseTriggerCondition class.
+ * @returns {boolean}
+ */
+ init: function () {
+ return true;
+ },
+
+ /**
+ * Detects trigger condition
+ * @returns {boolean}
+ */
+ detect: function () {
+ return true;
+ },
+
+ /**
+ * Serialize a BaseTriggerCondition object.
+ * @param jsonVal
+ */
+ serialize: function (jsonVal) {
+ },
+
+ /**
+ * Removes all condition
+ */
+ removeAll: function () {
+ }
+});
+
+/**
+ * The base class of trigger action
+ * @class
+ * @extends ccs.Class
+ */
+ccs.BaseTriggerAction = ccs.Class.extend(/** @lends ccs.BaseTriggerAction# */{
+ /**
+ * Construction of ccs.BaseTriggerAction
+ */
+ ctor:function(){
+ },
+
+ /**
+ * Initializes a BaseTriggerAction object.
+ * @returns {boolean}
+ */
+ init: function () {
+ return true;
+ },
+
+ /**
+ * Sets the action to done.
+ */
+ done: function () {
+ },
+
+ /**
+ * Serializes a ccs.BaseTriggerAction object.
+ * @param jsonVal
+ */
+ serialize: function (jsonVal) {
+ },
+
+ /**
+ * Removes all actions.
+ */
+ removeAll: function () {
+ }
+});
+
+/**
+ * The trigger object of Cocostudio.
+ * @class
+ * @extends ccs.Class
+ */
+ccs.TriggerObj = ccs.Class.extend(/** @lends ccs.TriggerObj# */{
+ _cons: null,
+ _acts: null,
+ _id: 0,
+ _enable: true,
+ _vInt: null,
+
+ ctor: function () {
+ this._id = 0;
+ this._enable = true;
+
+ ccs.TriggerObj.prototype.init.call(this);
+ },
+
+ /**
+ * Initializes a ccs.TriggerObj
+ * @returns {boolean}
+ */
+ init: function () {
+ this._cons = [];
+ this._acts = [];
+ this._vInt = [];
+ return true;
+ },
+
+ /**
+ * Detects trigger's conditions.
+ * @returns {boolean}
+ */
+ detect: function () {
+ if (!this._enable || this._cons.length === 0) {
+ return true;
+ }
+ var ret = true;
+ var obj = null;
+ for (var i = 0; i < this._cons.length; i++) {
+ obj = this._cons[i];
+ if (obj && obj.detect)
+ ret = ret && obj.detect();
+ }
+ return ret;
+ },
+
+ /**
+ * Sets trigger's actions to done.
+ */
+ done: function () {
+ if (!this._enable || this._acts.length === 0)
+ return;
+ var obj;
+ for (var i = 0; i < this._acts.length; i++) {
+ obj = this._acts[i];
+ if (obj && obj.done)
+ obj.done();
+ }
+ },
+
+ /**
+ * Removes all condition and actions from ccs.TriggerObj.
+ */
+ removeAll: function () {
+ var obj = null;
+ for (var i = 0; i < this._cons.length; i++) {
+ obj = this._cons[i];
+ if (obj)
+ obj.removeAll();
+ }
+ this._cons = [];
+ for (var i = 0; i < this._acts.length; i++) {
+ obj = this._acts[i];
+ if (obj)
+ obj.removeAll();
+ }
+ this._acts = [];
+ },
+
+ /**
+ * Serializes ccs.TriggerObj
+ * @param jsonVal
+ */
+ serialize: function (jsonVal) {
+ this._id = jsonVal["id"] || 0;
+ var conditions = jsonVal["conditions"] || [];
+ for (var i = 0; i < conditions.length; i++) {
+ var subDict = conditions[i];
+ var classname = subDict["classname"];
+ var con = ccs.objectFactory.createObject(classname);
+ if (!con) {
+ cc.log("class named classname(" + classname + ") can not implement!");
+ continue;
+ }
+
+ con.serialize(subDict);
+ con.init();
+ this._cons.push(con);
+ }
+
+ var actions = jsonVal["actions"] || [];
+ for (var i = 0; i < actions.length; i++) {
+ var subDict = actions[i];
+ var classname = subDict["classname"];
+ var act = ccs.objectFactory.createObject(classname);
+ if (!act) {
+ cc.log("class named classname(" + classname + ") can not implement!");
+ continue;
+ }
+
+ act.serialize(subDict);
+ act.init();
+ this._acts.push(act);
+ }
+
+ var events = jsonVal["events"] || [];
+ for (var i = 0; i < events.length; i++) {
+ var subDict = events[i];
+ var event = subDict["id"];
+ if (event < 0) {
+ continue;
+ }
+ this._vInt.push(event);
+ }
+ },
+
+ /**
+ * Returns the id of ccs.TriggerObj.
+ * @returns {number}
+ */
+ getId: function () {
+ return this._id;
+ },
+
+ /**
+ * Sets enable value.
+ * @param {Boolean} enable
+ */
+ setEnable: function (enable) {
+ this._enable = enable;
+ },
+
+ /**
+ * Returns the events of ccs.TriggerObj.
+ * @returns {null|Array}
+ */
+ getEvents: function () {
+ return this._vInt;
+ }
+});
+
+ccs.TriggerObj.create = function () {
+ return new ccs.TriggerObj();
+};
\ No newline at end of file
diff --git a/extensions/editbox/CCEditBox.js b/extensions/editbox/CCEditBox.js
new file mode 100644
index 0000000000..bc4678ea24
--- /dev/null
+++ b/extensions/editbox/CCEditBox.js
@@ -0,0 +1,688 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2012 James Chen
+
+ 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.
+ ****************************************************************************/
+
+/**
+ * Enum for keyboard return types
+ * @readonly
+ * @enum {number}
+ */
+cc.KeyboardReturnType = cc.Enum({
+ DEFAULT: 0,
+ DONE: 1,
+ SEND: 2,
+ SEARCH: 3,
+ GO: 4
+});
+
+/**
+ * The EditBox's InputMode defines the type of text that the user is allowed to enter
+ * @readonly
+ * @enum {number}
+ * @memberof cc.EditBox
+ */
+var InputMode = cc.Enum({
+
+ ANY: 0,
+
+ /**
+ * The user is allowed to enter an e-mail address.
+ */
+ EMAILADDR: 1,
+
+ /**
+ * The user is allowed to enter an integer value.
+ */
+ NUMERIC: 2,
+
+ /**
+ * The user is allowed to enter a phone number.
+ */
+ PHONENUMBER: 3,
+
+ /**
+ * The user is allowed to enter a URL.
+ */
+ URL: 4,
+
+ /**
+ * The user is allowed to enter a real number value.
+ * This extends kEditBoxInputModeNumeric by allowing a decimal point.
+ */
+ DECIMAL: 5,
+
+ /**
+ * The user is allowed to enter any text, except for line breaks.
+ */
+ SINGLELINE: 6
+});
+
+/**
+ * Enum for the EditBox's input flags
+ * @readonly
+ * @enum {number}
+ * @memberof cc.EditBox
+ */
+var InputFlag = cc.Enum({
+ /**
+ * Indicates that the text entered is confidential data that should be
+ * obscured whenever possible. This implies EDIT_BOX_INPUT_FLAG_SENSITIVE.
+ */
+ PASSWORD: 0,
+
+ /**
+ * Indicates that the text entered is sensitive data that the
+ * implementation must never store into a dictionary or table for use
+ * in predictive, auto-completing, or other accelerated input schemes.
+ * A credit card number is an example of sensitive data.
+ */
+ SENSITIVE: 1,
+
+ /**
+ * This flag is a hint to the implementation that during text editing,
+ * the initial letter of each word should be capitalized.
+ */
+ INITIAL_CAPS_WORD: 2,
+
+ /**
+ * This flag is a hint to the implementation that during text editing,
+ * the initial letter of each sentence should be capitalized.
+ */
+ INITIAL_CAPS_SENTENCE: 3,
+
+ /**
+ * Capitalize all characters automatically.
+ */
+ INITIAL_CAPS_ALL_CHARACTERS: 4
+});
+
+/**
+ * @class
+ * @extends cc._Class
+ */
+cc.EditBoxDelegate = cc._Class.extend({
+ /**
+ * This method is called when an edit box gains focus after keyboard is shown.
+ * @param {cc.EditBox} sender
+ */
+ editBoxEditingDidBegin: function (sender) {
+ },
+
+ /**
+ * This method is called when an edit box loses focus after keyboard is hidden.
+ * @param {cc.EditBox} sender
+ */
+ editBoxEditingDidEnd: function (sender) {
+ },
+
+ /**
+ * This method is called when the edit box text was changed.
+ * @param {cc.EditBox} sender
+ * @param {String} text
+ */
+ editBoxTextChanged: function (sender, text) {
+ },
+
+ /**
+ * This method is called when the return button was pressed.
+ * @param {cc.EditBox} sender
+ */
+ editBoxReturn: function (sender) {
+ }
+});
+
+/**
+ * cc.EditBox is a brief Class for edit box.
+ * You can use this widget to gather small amounts of text from the user.
+ *
+ * @class
+ * @extends cc.ControlButton
+ *
+ * @property {String} string - Content string of edit box
+ * @property {String} maxLength - Max length of the content string
+ * @property {String} font - <@writeonly> Config font of edit box
+ * @property {String} fontName - <@writeonly> Config font name of edit box
+ * @property {Number} fontSize - <@writeonly> Config font size of edit box
+ * @property {cc.Color} fontColor - <@writeonly> Config font color of edit box
+ * @property {String} placeHolder - Place holder of edit box
+ * @property {String} placeHolderFont - <@writeonly> Config font of place holder
+ * @property {String} placeHolderFontName - <@writeonly> Config font name of place holder
+ * @property {Number} placeHolderFontSize - <@writeonly> Config font size of place holder
+ * @property {cc.Color} placeHolderFontColor - <@writeonly> Config font color of place holder
+ * @property {cc.EditBox.InputFlag} inputFlag - <@writeonly> Input flag of edit box, one of the cc.EditBox.InputFlag constants. e.g.cc.EditBox.InputFlag..PASSWORD
+ * @property {Object} delegate - <@writeonly> Delegate of edit box
+ * @property {cc.EditBox.InputMode} inputMode - <@writeonly> Input mode of the edit box. Value should be one of the cc.EditBox.InputMode constants.
+ * @property {Number} returnType - <@writeonly> Return type of edit box, value should be one of the KeyboardReturnType constants.
+ *
+ */
+cc.EditBox = cc.ControlButton.extend({
+ _domInputSprite: null,
+
+ _delegate: null,
+ _editBoxInputMode: InputMode.ANY,
+ _editBoxInputFlag: InputFlag.SENSITIVE,
+ _keyboardReturnType: cc.KeyboardReturnType.DEFAULT,
+
+ _text: "",
+ _placeholderText: "",
+ _textColor: null,
+ _placeholderColor: null,
+ _maxLength: 50,
+ _adjustHeight: 18,
+
+ _edTxt: null,
+ _edFontSize: 14,
+ _edFontName: "Arial",
+
+ _placeholderFontName: "",
+ _placeholderFontSize: 14,
+
+ _tooltip: false,
+ _className: "EditBox",
+
+ /**
+ * constructor of cc.EditBox
+ * @param {cc.Size} size
+ * @param {cc.Scale9Sprite} normal9SpriteBg
+ * @param {cc.Scale9Sprite} press9SpriteBg
+ * @param {cc.Scale9Sprite} disabled9SpriteBg
+ */
+ ctor: function (size, normal9SpriteBg, press9SpriteBg, disabled9SpriteBg) {
+ cc.ControlButton.prototype.ctor.call(this);
+
+ this._textColor = cc.Color.WHITE;
+ this._placeholderColor = cc.Color.GRAY;
+ this.setContentSize(size);
+ var tmpDOMSprite = this._domInputSprite = new cc.Sprite();
+ tmpDOMSprite.draw = function () {}; //redefine draw function
+ this.addChild(tmpDOMSprite);
+ var selfPointer = this;
+ var tmpEdTxt = this._edTxt = document.createElement("input");
+ tmpEdTxt.type = "text";
+ tmpEdTxt.style.fontSize = this._edFontSize + "px";
+ tmpEdTxt.style.color = "#000000";
+ tmpEdTxt.style.border = 0;
+ tmpEdTxt.style.background = "transparent";
+ //tmpEdTxt.style.paddingLeft = "2px";
+ tmpEdTxt.style.width = "100%";
+ tmpEdTxt.style.height = "100%";
+ tmpEdTxt.style.active = 0;
+ tmpEdTxt.style.outline = "medium";
+ tmpEdTxt.style.padding = "0";
+ var onCanvasClick = function() { tmpEdTxt.blur();};
+
+ // TODO the event listener will be remove when EditBox removes from parent.
+ tmpEdTxt.addEventListener("input", function () {
+ if (selfPointer._delegate && selfPointer._delegate.editBoxTextChanged)
+ selfPointer._delegate.editBoxTextChanged(selfPointer, this.value);
+ });
+ tmpEdTxt.addEventListener("keypress", function (e) {
+ if (e.keyCode === cc.KEY.enter) {
+ e.stopPropagation();
+ e.preventDefault();
+ if (selfPointer._delegate && selfPointer._delegate.editBoxReturn)
+ selfPointer._delegate.editBoxReturn(selfPointer);
+ cc._canvas.focus();
+ }
+ });
+ tmpEdTxt.addEventListener("focus", function () {
+ if (this.value === selfPointer._placeholderText) {
+ this.value = "";
+ this.style.fontSize = selfPointer._edFontSize + "px";
+ this.style.color = cc.colorToHex(selfPointer._textColor);
+ if (selfPointer._editBoxInputFlag === InputFlag.PASSWORD)
+ selfPointer._edTxt.type = "password";
+ else
+ selfPointer._edTxt.type = "text";
+ }
+ if (selfPointer._delegate && selfPointer._delegate.editBoxEditingDidBegin)
+ selfPointer._delegate.editBoxEditingDidBegin(selfPointer);
+ cc._canvas.addEventListener("click", onCanvasClick);
+ });
+ tmpEdTxt.addEventListener("blur", function () {
+ if (this.value === "") {
+ this.value = selfPointer._placeholderText;
+ this.style.fontSize = selfPointer._placeholderFontSize + "px";
+ this.style.color = cc.colorToHex(selfPointer._placeholderColor);
+ selfPointer._edTxt.type = "text";
+ }
+ if (selfPointer._delegate && selfPointer._delegate.editBoxEditingDidEnd)
+ selfPointer._delegate.editBoxEditingDidEnd(selfPointer);
+ cc._canvas.removeEventListener('click', onCanvasClick);
+ });
+
+ cc.DOM.convert(tmpDOMSprite);
+ tmpDOMSprite.dom.appendChild(tmpEdTxt);
+ tmpDOMSprite.dom.showTooltipDiv = false;
+ tmpDOMSprite.dom.style.width = (size.width - 6) + "px";
+ tmpDOMSprite.dom.style.height = (size.height - 6) + "px";
+
+ //this._domInputSprite.dom.style.borderWidth = "1px";
+ //this._domInputSprite.dom.style.borderStyle = "solid";
+ //this._domInputSprite.dom.style.borderRadius = "8px";
+ tmpDOMSprite.canvas.remove();
+
+ if (this.initWithSizeAndBackgroundSprite(size, normal9SpriteBg)) {
+ if (press9SpriteBg)
+ this.setBackgroundSpriteForState(press9SpriteBg, cc.CONTROL_STATE_HIGHLIGHTED);
+ if (disabled9SpriteBg)
+ this.setBackgroundSpriteForState(disabled9SpriteBg, cc.CONTROL_STATE_DISABLED);
+ }
+ },
+
+ /**
+ * Set the font.
+ * @param {String} fontName The font name.
+ * @param {Number} fontSize The font size.
+ */
+ setFont: function (fontName, fontSize) {
+ this._edFontSize = fontSize;
+ this._edFontName = fontName;
+ this._setFontToEditBox();
+ },
+
+ _setFont: function (fontStyle) {
+ var res = cc.LabelTTF._fontStyleRE.exec(fontStyle);
+ if (res) {
+ this._edFontSize = parseInt(res[1]);
+ this._edFontName = res[2];
+ this._setFontToEditBox();
+ }
+ },
+
+ /**
+ * set fontName
+ * @param {String} fontName
+ */
+ setFontName: function (fontName) {
+ this._edFontName = fontName;
+ this._setFontToEditBox();
+ },
+
+ /**
+ * set fontSize
+ * @param {Number} fontSize
+ */
+ setFontSize: function (fontSize) {
+ this._edFontSize = fontSize;
+ this._setFontToEditBox();
+ },
+
+ _setFontToEditBox: function () {
+ if (this._edTxt.value !== this._placeholderText) {
+ this._edTxt.style.fontFamily = this._edFontName;
+ this._edTxt.style.fontSize = this._edFontSize + "px";
+ if (this._editBoxInputFlag === InputFlag.PASSWORD)
+ this._edTxt.type = "password";
+ else
+ this._edTxt.type = "text";
+ }
+ },
+
+ /**
+ * Set the text entered in the edit box.
+ * @deprecated
+ * @param {string} text The given text.
+ */
+ setText: function (text) {
+ cc.log("Please use the setString");
+ this.setString(text);
+ },
+
+ /**
+ * Set the text entered in the edit box.
+ * @param {string} text The given text.
+ */
+ setString: function (text) {
+ if (text != null) {
+ if (text === "") {
+ this._edTxt.value = this._placeholderText;
+ this._edTxt.style.color = cc.colorToHex(this._placeholderColor);
+ this._edTxt.type = "text";
+ } else {
+ this._edTxt.value = text;
+ this._edTxt.style.color = cc.colorToHex(this._textColor);
+ if (this._editBoxInputFlag === InputFlag.PASSWORD)
+ this._edTxt.type = "password";
+ else
+ this._edTxt.type = "text";
+ }
+ }
+ },
+
+ /**
+ * Set the font color of the widget's text.
+ * @param {cc.Color} color
+ */
+ setFontColor: function (color) {
+ this._textColor = color;
+ if (this._edTxt.value !== this._placeholderText) {
+ this._edTxt.style.color = cc.colorToHex(color);
+ }
+ },
+
+ /**
+ *
+ * Sets the maximum input length of the edit box.
+ * Setting this value enables multiline input mode by default.
+ *
+ * @param {Number} maxLength The maximum length.
+ */
+ setMaxLength: function (maxLength) {
+ if (!isNaN(maxLength) && maxLength > 0) {
+ this._maxLength = maxLength;
+ this._edTxt.maxLength = maxLength;
+ }
+ },
+
+ /**
+ * Gets the maximum input length of the edit box.
+ * @return {Number} Maximum input length.
+ */
+ getMaxLength: function () {
+ return this._maxLength;
+ },
+
+ /**
+ * Set a text in the edit box that acts as a placeholder when an edit box is empty.
+ * @param {string} text The given text.
+ */
+ setPlaceHolder: function (text) {
+ if (text != null) {
+ var oldPlaceholderText = this._placeholderText;
+ this._placeholderText = text;
+ if (this._edTxt.value === oldPlaceholderText) {
+ this._edTxt.value = text;
+ this._edTxt.style.color = cc.colorToHex(this._placeholderColor);
+ this._setPlaceholderFontToEditText();
+ }
+ }
+ },
+
+ /**
+ * Set the placeholder's font.
+ * @param {String} fontName
+ * @param {Number} fontSize
+ */
+ setPlaceholderFont: function (fontName, fontSize) {
+ this._placeholderFontName = fontName;
+ this._placeholderFontSize = fontSize;
+ this._setPlaceholderFontToEditText();
+ },
+ _setPlaceholderFont: function (fontStyle) {
+ var res = cc.LabelTTF._fontStyleRE.exec(fontStyle);
+ if (res) {
+ this._placeholderFontName = res[2];
+ this._placeholderFontSize = parseInt(res[1]);
+ this._setPlaceholderFontToEditText();
+ }
+ },
+
+ /**
+ * Set the placeholder's fontName.
+ * @param {String} fontName
+ */
+ setPlaceholderFontName: function (fontName) {
+ this._placeholderFontName = fontName;
+ this._setPlaceholderFontToEditText();
+ },
+
+ /**
+ * Set the placeholder's fontSize.
+ * @param {Number} fontSize
+ */
+ setPlaceholderFontSize: function (fontSize) {
+ this._placeholderFontSize = fontSize;
+ this._setPlaceholderFontToEditText();
+ },
+
+ _setPlaceholderFontToEditText: function () {
+ if (this._edTxt.value === this._placeholderText) {
+ this._edTxt.style.fontFamily = this._placeholderFontName;
+ this._edTxt.style.fontSize = this._placeholderFontSize + "px";
+ this._edTxt.type = "text";
+ }
+ },
+
+ /**
+ * Set the font color of the placeholder text when the edit box is empty.
+ * @param {cc.Color} color
+ */
+ setPlaceholderFontColor: function (color) {
+ this._placeholderColor = color;
+ if (this._edTxt.value === this._placeholderText) {
+ this._edTxt.style.color = cc.colorToHex(color);
+ }
+ },
+
+ /**
+ * Set the input flags that are to be applied to the edit box.
+ * @param {cc.EditBox.InputFlag} inputFlag - One of the cc.EditBox.InputFlag constants.
+ * e.g.cc.EditBox.InputFlag..PASSWORD
+ */
+ setInputFlag: function (inputFlag) {
+ this._editBoxInputFlag = inputFlag;
+ if ((this._edTxt.value !== this._placeholderText) && (inputFlag === InputFlag.PASSWORD))
+ this._edTxt.type = "password";
+ else
+ this._edTxt.type = "text";
+ },
+
+ /**
+ * Gets the input string of the edit box.
+ * @deprecated
+ * @return {string}
+ */
+ getText: function () {
+ cc.log("Please use the getString");
+ return this._edTxt.value;
+ },
+
+ /**
+ * Gets the input string of the edit box.
+ * @return {string}
+ */
+ getString: function () {
+ if(this._edTxt.value === this._placeholderText)
+ return "";
+ return this._edTxt.value;
+ },
+
+ /**
+ * Init edit box with specified size.
+ * @param {cc.Size} size
+ * @param {cc.Color | cc.Scale9Sprite} normal9SpriteBg
+ */
+ initWithSizeAndBackgroundSprite: function (size, normal9SpriteBg) {
+ if (this.initWithBackgroundSprite(normal9SpriteBg)) {
+ this._domInputSprite.x = 3;
+ this._domInputSprite.y = 3;
+
+ this.setZoomOnTouchDown(false);
+ this.setPreferredSize(size);
+ this.x = 0;
+ this.y = 0;
+ this._addTargetWithActionForControlEvent(this, this.touchDownAction, cc.CONTROL_EVENT_TOUCH_UP_INSIDE);
+ return true;
+ }
+ return false;
+ },
+
+ /* override functions */
+ /**
+ * Set the delegate for edit box.
+ * @param {cc.EditBoxDelegate} delegate
+ */
+ setDelegate: function (delegate) {
+ this._delegate = delegate;
+ },
+
+ /**
+ * Get a text in the edit box that acts as a placeholder when an
+ * edit box is empty.
+ * @return {String}
+ */
+ getPlaceHolder: function () {
+ return this._placeholderText;
+ },
+
+ /**
+ * Set the input mode of the edit box.
+ * @param {Number} inputMode One of the EditBoxInputMode constants.
+ */
+ setInputMode: function (inputMode) {
+ this._editBoxInputMode = inputMode;
+ },
+
+ /**
+ * Set the return type that are to be applied to the edit box.
+ * @param {Number} returnType One of the CCKeyboardReturnType constants.
+ */
+ setReturnType: function (returnType) {
+ this._keyboardReturnType = returnType;
+ },
+
+ keyboardWillShow: function (info) {
+ var rectTracked = cc.EditBox.getRect(this);
+ // some adjustment for margin between the keyboard and the edit box.
+ rectTracked.y -= 4;
+ // if the keyboard area doesn't intersect with the tracking node area, nothing needs to be done.
+ if (!rectTracked.intersectsRect(info.end)) {
+ cc.log("needn't to adjust view layout.");
+ return;
+ }
+
+ // assume keyboard at the bottom of screen, calculate the vertical adjustment.
+ this._adjustHeight = info.end.getMaxY() - rectTracked.getMinY();
+ // CCLOG("CCEditBox:needAdjustVerticalPosition(%f)", m_fAdjustHeight);
+
+ //callback
+ },
+ keyboardDidShow: function (info) {
+ },
+ keyboardWillHide: function (info) {
+ //if (m_pEditBoxImpl != NULL) {
+ // m_pEditBoxImpl->doAnimationWhenKeyboardMove(info.duration, -m_fAdjustHeight);
+ //}
+ },
+ keyboardDidHide: function (info) {
+ },
+
+ touchDownAction: function (sender, controlEvent) {
+ //this._editBoxImpl.openKeyboard();
+ },
+
+ /**
+ * @warning HTML5 Only
+ * @param {cc.Size} size
+ * @param {cc.color} bgColor
+ */
+ initWithBackgroundColor: function (size, bgColor) {
+ this._edWidth = size.width;
+ this.dom.style.width = this._edWidth.toString() + "px";
+ this._edHeight = size.height;
+ this.dom.style.height = this._edHeight.toString() + "px";
+ this.dom.style.backgroundColor = cc.colorToHex(bgColor);
+ }
+});
+
+var _p = cc.EditBox.prototype;
+
+// Extended properties
+/** @expose */
+_p.font;
+cc.defineGetterSetter(_p, "font", null, _p._setFont);
+/** @expose */
+_p.fontName;
+cc.defineGetterSetter(_p, "fontName", null, _p.setFontName);
+/** @expose */
+_p.fontSize;
+cc.defineGetterSetter(_p, "fontSize", null, _p.setFontSize);
+/** @expose */
+_p.fontColor;
+cc.defineGetterSetter(_p, "fontColor", null, _p.setFontColor);
+/** @expose */
+_p.string;
+cc.defineGetterSetter(_p, "string", _p.getString, _p.setString);
+/** @expose */
+_p.maxLength;
+cc.defineGetterSetter(_p, "maxLength", _p.getMaxLength, _p.setMaxLength);
+/** @expose */
+_p.placeHolder;
+cc.defineGetterSetter(_p, "placeHolder", _p.getPlaceHolder, _p.setPlaceHolder);
+/** @expose */
+_p.placeHolderFont;
+cc.defineGetterSetter(_p, "placeHolderFont", null, _p._setPlaceholderFont);
+/** @expose */
+_p.placeHolderFontName;
+cc.defineGetterSetter(_p, "placeHolderFontName", null, _p.setPlaceholderFontName);
+/** @expose */
+_p.placeHolderFontSize;
+cc.defineGetterSetter(_p, "placeHolderFontSize", null, _p.setPlaceholderFontSize);
+/** @expose */
+_p.placeHolderFontColor;
+cc.defineGetterSetter(_p, "placeHolderFontColor", null, _p.setPlaceholderFontColor);
+/** @expose */
+_p.inputFlag;
+cc.defineGetterSetter(_p, "inputFlag", null, _p.setInputFlag);
+/** @expose */
+_p.delegate;
+cc.defineGetterSetter(_p, "delegate", null, _p.setDelegate);
+/** @expose */
+_p.inputMode;
+cc.defineGetterSetter(_p, "inputMode", null, _p.setInputMode);
+/** @expose */
+_p.returnType;
+cc.defineGetterSetter(_p, "returnType", null, _p.setReturnType);
+
+_p = null;
+
+/**
+ * get the rect of a node in world coordinate frame
+ * @function
+ * @param {cc.Node} node
+ * @return {cc.Rect}
+ */
+cc.EditBox.getRect = function (node) {
+ var contentSize = node.getContentSize();
+ var rect = cc.rect(0, 0, contentSize.width, contentSize.height);
+ return cc.rectApplyAffineTransform(rect, node.getNodeToWorldTransform());
+};
+
+/**
+ * create a edit box with size and background-color or
+ * @deprecated since v3.0, please use new cc.EditBox(size, normal9SpriteBg, press9SpriteBg, disabled9SpriteBg) instead
+ * @param {cc.Size} size
+ * @param {cc.Scale9Sprite } normal9SpriteBg
+ * @param {cc.Scale9Sprite } [press9SpriteBg]
+ * @param {cc.Scale9Sprite } [disabled9SpriteBg]
+ * @return {cc.EditBox}
+ */
+cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9SpriteBg) {
+ return new cc.EditBox(size, normal9SpriteBg, press9SpriteBg, disabled9SpriteBg);
+};
+
+cc.EditBox.InputMode = InputMode;
+cc.EditBox.InputFlag = InputFlag;
diff --git a/extensions/editbox/CCdomNode.js b/extensions/editbox/CCdomNode.js
new file mode 100644
index 0000000000..7bce23c268
--- /dev/null
+++ b/extensions/editbox/CCdomNode.js
@@ -0,0 +1,657 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+/**
+ * the DOM object
+ * @namespace
+ * @name cc.DOM
+ */
+cc.DOM = {};
+
+/**
+ * @function
+ * @private
+ * @param node
+ */
+cc.DOM._addMethods = function (node) {
+ for (var funcs in cc.DOM.methods) {
+ node[funcs] = cc.DOM.methods[funcs];
+ }
+
+ // Redefine getter setter
+ cc.defineGetterSetter(node, "x", node.getPositionX, node.setPositionX);
+ cc.defineGetterSetter(node, "y", node.getPositionY, node.setPositionY);
+ cc.defineGetterSetter(node, "width", node._getWidth, node._setWidth);
+ cc.defineGetterSetter(node, "height", node._getHeight, node._setHeight);
+ cc.defineGetterSetter(node, "anchorX", node._getAnchorX, node._setAnchorX);
+ cc.defineGetterSetter(node, "anchorY", node._getAnchorY, node._setAnchorY);
+ cc.defineGetterSetter(node, "scale", node.getScale, node.setScale);
+ cc.defineGetterSetter(node, "scaleX", node.getScaleX, node.setScaleX);
+ cc.defineGetterSetter(node, "scaleY", node.getScaleY, node.setScaleY);
+ cc.defineGetterSetter(node, "rotation", node.getRotation, node.setRotation);
+ cc.defineGetterSetter(node, "skewX", node.getSkewX, node.setSkewX);
+ cc.defineGetterSetter(node, "skewY", node.getSkewY, node.setSkewY);
+ cc.defineGetterSetter(node, "visible", node.isVisible, node.setVisible);
+ cc.defineGetterSetter(node, "parent", node.getParent, node.setParent);
+ cc.defineGetterSetter(node, "opacity", node.getOpacity, node.setOpacity);
+};
+cc.DOM.methods = /** @lends cc.DOM# */{
+ /**
+ * Replace the set position of ccNode
+ * @param {cc.Vec2|Number} x
+ * @param {Number} y
+ */
+ setPosition:function (x, y) {
+ if (y === undefined) {
+ this._position.x = x.x;
+ this._position.y = x.y;
+ } else {
+ this._position.x = x;
+ this._position.y = y;
+ }
+ this.setNodeDirty();
+ this.dom.translates(this._position.x, -this._position.y);
+ },
+ /**
+ * replace set Position Y of ccNode
+ * @param {Number} y
+ */
+ setPositionY:function (y) {
+ this._position.y = y;
+ this.setNodeDirty();
+ this.dom.translates(this._position.x, -this._position.y);
+ },
+
+ /**
+ * replace set Position X of ccNode
+ * @param {Number} x
+ */
+ setPositionX:function (x) {
+ this._position.x = x;
+ this.setNodeDirty();
+ this.dom.translates(this._position.x, -this._position.y);
+ },
+
+ /**
+ * replace set Scale of ccNode
+ * @param {object|Number} scale
+ * @param {Number} scaleY
+ */
+ setScale:function (scale, scaleY) {
+ //save dirty region when before change
+ //this._addDirtyRegionToDirector(this.getBoundingBoxToWorld());
+
+ this._scaleX = scale;
+ this._scaleY = scaleY || scale;
+
+ //save dirty region when after changed
+ //this._addDirtyRegionToDirector(this.getBoundingBoxToWorld());
+ this.setNodeDirty();
+ this.dom.resize(this._scaleX, this._scaleY);
+ },
+
+ /**
+ * replace set Scale X of ccNode
+ * @param {Number} x
+ */
+ setScaleX:function (x) {
+ this._scaleX = x;
+ this.setNodeDirty();
+ this.dom.resize(this._scaleX, this._scaleY);
+ },
+
+ /**
+ * replace set Scale Y of ccNode
+ * @param {Number} y
+ */
+ setScaleY:function (y) {
+ this._scaleY = y;
+ this.setNodeDirty();
+ this.dom.resize(this._scaleX, this._scaleY);
+ },
+
+ /**
+ * replace set anchorpoint of ccNode
+ * @param {cc.Vec2|Number} point The anchor point of node or The anchor point.x of node.
+ * @param {Number} [y] The anchor point.y of node.
+ */
+ setAnchorPoint:function (point, y) {
+ var cmd = this._renderCmd;
+
+ var locAnchorPoint = this._anchorPoint;
+ if (y === undefined) {
+ locAnchorPoint.x = point.x;
+ locAnchorPoint.y = point.y;
+ } else {
+ locAnchorPoint.x = point;
+ locAnchorPoint.y = y;
+ }
+ var locAPP = cmd._anchorPointInPoints, locSize = this._contentSize;
+ locAPP.x = locSize.width * locAnchorPoint.x;
+ locAPP.y = locSize.height * locAnchorPoint.y;
+
+ this.dom.style[cc.$.pfx + 'TransformOrigin'] = '' + locAPP.x + 'px ' + -locAPP.y + 'px';
+ if (this.ignoreAnchor) {
+ this.dom.style.marginLeft = 0;
+ this.dom.style.marginBottom = 0;
+ } else {
+ this.dom.style.marginLeft = (this.isToggler) ? 0 : -locAPP.x + 'px';
+ this.dom.style.marginBottom = -locAPP.y + 'px';
+ }
+ this.setNodeDirty();
+ },
+
+ /**
+ * replace set anchorpoint x of ccNode
+ * @param {Number} x The anchor x of node.
+ */
+ _setAnchorX:function (x) {
+ var locAnchorPoint = this._anchorPoint;
+ var cmd = this._renderCmd;
+
+ if (x === locAnchorPoint.x)
+ return;
+ locAnchorPoint.x = x;
+
+ var locAPP = cmd._anchorPointInPoints, locSize = this._contentSize;
+ locAPP.x = locSize.width * locAnchorPoint.x;
+
+ this.dom.style[cc.$.pfx + 'TransformOrigin'] = '' + locAPP.x + 'px ' + -locAPP.y + 'px';
+ if (this.ignoreAnchor) {
+ this.dom.style.marginLeft = 0;
+ this.dom.style.marginBottom = 0;
+ } else {
+ this.dom.style.marginLeft = (this.isToggler) ? 0 : -locAPP.x + 'px';
+ }
+ this.setNodeDirty();
+ },
+
+ /**
+ * replace set anchorpoint y of ccNode
+ * @param {Number} y The anchor y of node.
+ */
+ _setAnchorY:function (y) {
+ var locAnchorPoint = this._anchorPoint;
+ var cmd = this._renderCmd;
+
+ if (y === locAnchorPoint.y)
+ return;
+ locAnchorPoint.y = y;
+
+ var locAPP = cmd._anchorPointInPoints, locSize = this._contentSize;
+ locAPP.y = locSize.height * locAnchorPoint.y;
+
+ this.dom.style[cc.$.pfx + 'TransformOrigin'] = '' + locAPP.x + 'px ' + -locAPP.y + 'px';
+ if (this.ignoreAnchor) {
+ this.dom.style.marginLeft = 0;
+ this.dom.style.marginBottom = 0;
+ } else {
+ this.dom.style.marginBottom = -locAPP.y + 'px';
+ }
+ this.setNodeDirty();
+ },
+
+ /**
+ * replace set ContentSize of ccNode
+ * @param {cc.Size|Number} size The untransformed size of the node or The untransformed size's width of the node.
+ * @param {Number} [height] The untransformed size's height of the node.
+ */
+ setContentSize:function (size, height) {
+ var cmd = this._renderCmd;
+
+ var locContentSize = this._contentSize;
+ if (height === undefined) {
+ locContentSize.width = size.width;
+ locContentSize.height = size.height;
+ } else {
+ locContentSize.width = size;
+ locContentSize.height = height;
+ }
+ var locAPP = cmd._anchorPointInPoints, locAnchorPoint = this._anchorPoint;
+ locAPP.x = locContentSize.width * locAnchorPoint.x;
+ locAPP.y = locContentSize.height * locAnchorPoint.y;
+ this.dom.width = locContentSize.width;
+ this.dom.height = locContentSize.height;
+ this.setAnchorPoint(this.getAnchorPoint());
+ if (this.canvas) {
+ this.canvas.width = locContentSize.width;
+ this.canvas.height = locContentSize.height;
+ }
+ this.setNodeDirty();
+ this.redraw();
+ },
+
+ /**
+ * replace set width of ccNode
+ * @param {Number} width The untransformed size's width of the node.
+ */
+ _setWidth:function (width) {
+ var locContentSize = this._contentSize;
+ var cmd = this._renderCmd;
+ if (width === locContentSize.width)
+ return;
+ locContentSize.width = width;
+
+ var locAPP = cmd._anchorPointInPoints, locAnchorPoint = this._anchorPoint;
+ locAPP.x = locContentSize.width * locAnchorPoint.x;
+ this.dom.width = locContentSize.width;
+ this.anchorX = locAnchorPoint.x;
+ if (this.canvas) {
+ this.canvas.width = locContentSize.width;
+ }
+ this.setNodeDirty();
+ this.redraw();
+ },
+
+ /**
+ * replace set height of ccNode
+ * @param {Number} height The untransformed size's height of the node.
+ */
+ _setHeight:function (height) {
+ var locContentSize = this._contentSize;
+ var cmd = this._renderCmd;
+ if (height === locContentSize.height)
+ return;
+ locContentSize.height = height;
+
+ var locAPP = cmd._anchorPointInPoints, locAnchorPoint = this._anchorPoint;
+ locAPP.y = locContentSize.height * locAnchorPoint.y;
+ this.dom.height = locContentSize.height;
+ this.anchorY = locAnchorPoint.y;
+ if (this.canvas) {
+ this.canvas.height = locContentSize.height;
+ }
+ this.setNodeDirty();
+ this.redraw();
+ },
+
+ /**
+ * replace set Rotation of ccNode
+ * @param {Number} newRotation
+ */
+ setRotation:function (newRotation) {
+ if (this._rotation === newRotation)
+ return;
+
+ this._rotationX = this._rotationY = newRotation;
+ this.setNodeDirty();
+ this.dom.rotate(newRotation);
+ },
+
+ /**
+ * replace set SkewX of ccNode
+ * @param {Number} x
+ */
+ setSkewX:function (x) {
+ this._skewX = x;
+ this.setNodeDirty();
+ this.dom.setSkew(this._skewX, this._skewY);
+ },
+
+ /**
+ * replace set SkewY of ccNode
+ * @param {Number} y
+ */
+ setSkewY:function (y) {
+ this._skewY = y;
+ this.setNodeDirty();
+ this.dom.setSkew(this._skewX, this._skewY);
+ },
+
+ /**
+ * replace set Visible of ccNode
+ * @param {Boolean} x
+ */
+ setVisible:function (x) {
+ this._visible = x;
+ this.setNodeDirty();
+ if (this.dom)
+ this.dom.style.display = (x) ? 'block' : 'none';
+ },
+ _setLocalZOrder:function (z) {
+ this._localZOrder = z
+ this.setNodeDirty();
+ if (this.dom)
+ this.dom.zIndex = z;
+ },
+
+ /**
+ * replace set Parent of ccNode
+ * @param {cc.Node} p
+ */
+ setParent:function (p) {
+ this._parent = p;
+
+ if (p !== null) {
+ p.setAnchorPoint(p.getAnchorPoint());
+ this.setNodeDirty();
+ cc.DOM.parentDOM(this);
+ }
+ },
+
+ /**
+ * replace resume Schedule and actions of ccNode
+ */
+ resume:function () {
+ this.getScheduler().resumeTarget(this);
+ this.getActionManager().resumeTarget(this);
+ cc.eventManager.resumeTarget(this);
+ //if dom does not have parent, but node has no parent and its running
+ if (this.dom && !this.dom.parentNode) {
+ if (!this.getParent()) {
+ if(this.dom.id === ""){
+ cc.DOM._createEGLViewDiv(this);
+ }else{
+ this.dom.appendTo(cc.container);
+ }
+ } else {
+ cc.DOM.parentDOM(this);
+ }
+ }
+ if (this.dom)
+ this.dom.style.visibility = "visible";
+ },
+
+ /**
+ * replace pause Schedule and Actions of ccNode
+ */
+ pause:function () {
+ this.getScheduler().pauseTarget(this);
+ this.getActionManager().pauseTarget(this);
+ cc.eventManager.pauseTarget(this);
+ if (this.dom) {
+ this.dom.style.visibility = 'hidden';
+ }
+ },
+
+ /**
+ * replace clean up of ccNode
+ */
+ cleanup:function () {
+ // actions
+ this.stopAllActions();
+ this.unscheduleAllCallbacks();
+
+ // timers
+ this._arrayMakeObjectsPerformSelector(this._children, cc.Node._stateCallbackType.cleanup);
+ if (this.dom) {
+ this.dom.remove();
+ }
+ },
+ /**
+ * replace remove from parent and clean up of ccNode
+ */
+ removeFromParentAndCleanup:function () {
+ this.dom.remove();
+ },
+ setOpacity:function (o) {
+ this._opacity = o;
+ this.dom.style.opacity = o / 255;
+ },
+ /**
+ * refresh/updates the DOM element
+ */
+ redraw:function () {
+ if (this.isSprite) {
+ var tmp = this._children;
+ this._children = [];
+ cc.Sprite.prototype.visit.call(this, this.ctx);
+ this._children = tmp;
+ }
+ else {
+ cc.Sprite.prototype.visit.call(this, this.ctx);
+ }
+ }
+};
+
+cc.DOM._resetEGLViewDiv = function(){
+ var div = cc.$("#EGLViewDiv");
+ if(div){
+ var view = cc.view;
+ var designSize = view.getDesignResolutionSize();
+ var viewPortRect = view.getViewPortRect();
+ var screenSize = view.getFrameSize();
+ var pixelRatio = view.getDevicePixelRatio();
+ var designSizeWidth = designSize.width, designSizeHeight = designSize.height;
+ if((designSize.width === 0) && (designSize.height === 0)){
+ designSizeWidth = screenSize.width;
+ designSizeHeight = screenSize.height;
+ }
+
+ var viewPortWidth = viewPortRect.width/pixelRatio;
+ if((viewPortRect.width === 0) && (viewPortRect.height === 0)){
+ viewPortWidth = screenSize.width;
+ }
+
+ div.style.position = 'absolute';
+ //x.dom.style.display='block';
+ div.style.width = designSizeWidth + "px";
+ div.style.maxHeight = designSizeHeight + "px";
+ div.style.margin = 0;
+
+ div.resize(view.getScaleX()/pixelRatio, view.getScaleY()/pixelRatio);
+ if (view.getResolutionPolicy() === view._rpNoBorder) {
+ div.style.left = (view.getFrameSize().width - designSizeWidth)/2 + "px";
+ div.style.bottom = (view.getFrameSize().height - designSizeHeight*view.getScaleY()/pixelRatio)/2 + "px";
+ }
+ else {
+ div.style.left = (designSizeWidth*view.getScaleX()/pixelRatio - designSizeWidth) / 2 + "px";
+ div.style.bottom = "0px";
+ }
+ }
+};
+
+/**
+ * @function
+ * @private
+ * @param x
+ * @return {Boolean}
+ */
+cc.DOM.parentDOM = function (x) {
+ var p = x.getParent();
+ //if has parent, parent need to have dom too
+ if (!p || !x.dom)
+ return false;
+ if (!p.dom) {
+ cc.DOM.placeHolder(p);
+ p.setParent = cc.DOM.methods.setParent;
+ }
+ //if parent have dom, attach self to parent
+ x.dom.appendTo(p.dom);
+ p.setAnchorPoint(p.getAnchorPoint());
+
+ if (p.getParent()) {
+ cc.DOM.parentDOM(p);
+ } else {
+ //parent has no more parent, if its running, then add it to the container
+ if (p.isRunning()) {
+ //find EGLView div
+ var eglViewDiv = cc.$("#EGLViewDiv");
+ if (eglViewDiv) {
+ p.dom.appendTo(eglViewDiv);
+ } else {
+ cc.DOM._createEGLViewDiv(p);
+ }
+ }
+ }
+ return true;
+};
+
+cc.DOM._createEGLViewDiv = function(p){
+ var div = cc.$("#EGLViewDiv");
+ if(!div){
+ div = cc.$new("div");
+ div.id = "EGLViewDiv";
+ }
+
+ var view = cc.view;
+ var designSize = view.getDesignResolutionSize();
+ var viewPortRect = view.getViewPortRect();
+ var screenSize = view.getFrameSize();
+ var pixelRatio = view.getDevicePixelRatio();
+ var designSizeWidth = designSize.width, designSizeHeight = designSize.height;
+ if ((designSize.width === 0) && (designSize.height === 0)) {
+ designSizeWidth = screenSize.width;
+ designSizeHeight = screenSize.height;
+ }
+
+ var viewPortWidth = viewPortRect.width/pixelRatio;
+ if ((viewPortRect.width === 0) && (viewPortRect.height === 0)) {
+ viewPortWidth = screenSize.width;
+ }
+
+ div.style.position = 'absolute';
+ //x.dom.style.display='block';
+ div.style.width = designSizeWidth + "px";
+ div.style.maxHeight = designSizeHeight + "px";
+ div.style.margin = 0;
+
+ div.resize(view.getScaleX()/pixelRatio, view.getScaleY()/pixelRatio);
+ if (view.getResolutionPolicy() === view._rpNoBorder) {
+ div.style.left = (screenSize.width - designSizeWidth)/2 + "px";
+ div.style.bottom = (screenSize.height - designSizeHeight*view.getScaleY()/pixelRatio)/2 + "px";
+ }
+ else {
+ div.style.left = (designSizeWidth*view.getScaleX()/pixelRatio - designSizeWidth) / 2 + "px";
+ div.style.bottom = "0px";
+ }
+
+ p.dom.appendTo(div);
+ div.appendTo(cc.container);
+};
+
+/**
+ * @function
+ * @private
+ * @param x
+ */
+cc.DOM.setTransform = function (x) {
+ if (x.ctx) {
+ x.ctx.translate(x.getAnchorPointInPoints().x, x.getAnchorPointInPoints().y);
+ if (x.isSprite) {
+ var tmp = x._children;
+ x._children = [];
+ cc.Sprite.prototype.visit.call(x);
+ x._children = tmp;
+ }
+ else {
+ cc.Sprite.prototype.visit.call(x);
+ }
+ }
+ if (x.dom) {
+ x.dom.position.x = x.getPositionX();
+ x.dom.position.y = -x.getPositionY();
+ x.dom.rotation = x.getRotation();
+ x.dom.scale = {x:x.getScaleX(), y:x.getScaleY()};
+ x.dom.skew = {x:x.getSkewX(), y:x.getSkewY()};
+ if (x.setAnchorPoint)
+ x.setAnchorPoint(x.getAnchorPoint());
+ x.dom.transforms();
+ }
+
+};
+
+/**
+ * @function
+ * @private
+ * @param x
+ */
+cc.DOM.forSprite = function (x) {
+ x.dom = cc.$new('div');
+ x.canvas = cc.$new('canvas');
+ var locContentSize = x.getContentSize();
+ x.canvas.width = locContentSize.width;
+ x.canvas.height = locContentSize.height;
+ x.dom.style.position = 'absolute';
+ x.dom.style.bottom = 0;
+ x.ctx = x.canvas.getContext('2d');
+ x.dom.appendChild(x.canvas);
+ if (x.getParent()) {
+ cc.DOM.parentDOM(x);
+ }
+ x.isSprite = true;
+};
+
+/**
+ * This creates divs for parent Nodes that are related to the current node
+ * @function
+ * @private
+ * @param x
+ */
+cc.DOM.placeHolder = function (x) {
+ //creating a placeholder dom to simulate other ccNode in the hierachy
+ x.dom = cc.$new('div');
+ x.placeholder = true;
+ x.dom.style.position = 'absolute';
+ x.dom.style.bottom = 0;
+ //x.dom.style.display='block';
+ x.dom.style.width = (x.getContentSize().width || cc.director.getWinSize().width) + "px";
+ x.dom.style.maxHeight = (x.getContentSize().height || cc.director.getWinSize().height) + "px";
+ x.dom.style.margin = 0;
+ cc.DOM.setTransform(x);
+ x.dom.transforms();
+ cc.DOM._addMethods(x);
+ //x.dom.style.border = 'red 1px dotted';
+};
+
+/**
+ * Converts cc.Sprite or cc.MenuItem to DOM elements
+ * It currently only supports cc.Sprite and cc.MenuItem
+ * @function
+ * @param {cc.Sprite|cc.MenuItem|Array} nodeObject
+ * @example
+ * // example
+ * cc.DOM.convert(Sprite1, Sprite2, Menuitem);
+ *
+ * var myDOMElements = [Sprite1, Sprite2, MenuItem];
+ * cc.DOM.convert(myDOMElements);
+ */
+cc.DOM.convert = function (nodeObject) {
+ //if passing by list, make it an array
+ if (arguments.length > 1) {
+ cc.DOM.convert(arguments);
+ return;
+ } else if (arguments.length === 1 && !arguments[0].length) {
+ cc.DOM.convert([arguments[0]]);
+ return;
+ }
+ var args = arguments[0];
+ for (var i = 0; i < args.length; i++) {
+ //first check if its sprite
+ if (args[i] instanceof cc.Sprite) {
+ // create a canvas
+ if (!args[i].dom)
+ cc.DOM.forSprite(args[i]);
+ } else {
+ cc.log('DOM converter only supports sprite and menuitems yet');
+ }
+ cc.DOM._addMethods(args[i]);
+ args[i].visit = function () {
+ };
+ args[i].transform = function () {
+ };
+ cc.DOM.setTransform(args[i]);
+ args[i].setVisible(args[i].isVisible());
+ }
+};
diff --git a/extensions/gui/control-extension/CCControl.js b/extensions/gui/control-extension/CCControl.js
new file mode 100644
index 0000000000..7ca024d33c
--- /dev/null
+++ b/extensions/gui/control-extension/CCControl.js
@@ -0,0 +1,381 @@
+/**
+ * Copyright (c) 2008-2010 Ricardo Quesada
+ * Copyright (c) 2011-2012 cocos2d-x.org
+ * Copyright (c) 2013-2014 Chukong Technologies Inc.
+ * Copyright 2011 Yannick Loriot.
+ * http://yannickloriot.com
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ */
+
+/** Number of kinds of control event. */
+cc.CONTROL_EVENT_TOTAL_NUMBER = 9;
+
+/** Kinds of possible events for the control objects. */
+cc.CONTROL_EVENT_TOUCH_DOWN = 1 << 0; // A touch-down event in the control.
+cc.CONTROL_EVENT_TOUCH_DRAG_INSIDE = 1 << 1; // An event where a finger is dragged inside the bounds of the control.
+cc.CONTROL_EVENT_TOUCH_DRAG_OUTSIDE = 1 << 2; // An event where a finger is dragged just outside the bounds of the control.
+cc.CONTROL_EVENT_TOUCH_DRAG_ENTER = 1 << 3; // An event where a finger is dragged into the bounds of the control.
+cc.CONTROL_EVENT_TOUCH_DRAG_EXIT = 1 << 4; // An event where a finger is dragged from within a control to outside its bounds.
+cc.CONTROL_EVENT_TOUCH_UP_INSIDE = 1 << 5; // A touch-up event in the control where the finger is inside the bounds of the control.
+cc.CONTROL_EVENT_TOUCH_UP_OUTSIDE = 1 << 6; // A touch-up event in the control where the finger is outside the bounds of the control.
+cc.CONTROL_EVENT_TOUCH_CANCEL = 1 << 7; // A system event canceling the current touches for the control.
+cc.CONTROL_EVENT_VALUECHANGED = 1 << 8; // A touch dragging or otherwise manipulating a control; causing it to emit a series of different values.
+
+/** The possible state for a control. */
+cc.CONTROL_STATE_NORMAL = 1 << 0; // The normal; or default state of a controlæą©hat is; enabled but neither selected nor highlighted.
+cc.CONTROL_STATE_HIGHLIGHTED = 1 << 1; // Highlighted state of a control. A control enters this state when a touch down; drag inside or drag enter is performed. You can retrieve and set this value through the highlighted property.
+cc.CONTROL_STATE_DISABLED = 1 << 2; // Disabled state of a control. This state indicates that the control is currently disabled. You can retrieve and set this value through the enabled property.
+cc.CONTROL_STATE_SELECTED = 1 << 3; // Selected state of a control. This state indicates that the control is currently selected. You can retrieve and set this value through the selected property.
+cc.CONTROL_STATE_INITIAL = 1 << 3;
+
+/**
+ * CCControl is inspired by the UIControl API class from the UIKit library of
+ * CocoaTouch. It provides a base class for control CCSprites such as CCButton
+ * or CCSlider that convey user intent to the application.
+ * The goal of CCControl is to define an interface and base implementation for
+ * preparing action messages and initially dispatching them to their targets when
+ * certain events occur.
+ * To use the CCControl you have to subclass it.
+ * @class
+ * @extends cc.Layer
+ *
+ * @property {Number} state - <@readonly> The current control state: cc.CONTROL_STATE_NORMAL | cc.CONTROL_STATE_HIGHLIGHTED | cc.CONTROL_STATE_DISABLED | cc.CONTROL_STATE_SELECTED | cc.CONTROL_STATE_INITIAL
+ * @property {Boolean} enabled - Indicate whether the control node is enbaled
+ * @property {Boolean} selected - Indicate whether the control node is selected
+ * @property {Boolean} highlighted - Indicate whether the control node is highlighted
+ */
+cc.Control = cc.Layer.extend(/** @lends cc.Control# */{
+ _isOpacityModifyRGB: false,
+ _hasVisibleParents: false,
+ _touchListener: null,
+ _className: "Control",
+
+ isOpacityModifyRGB: function () {
+ return this._isOpacityModifyRGB;
+ },
+ setOpacityModifyRGB: function (opacityModifyRGB) {
+ this._isOpacityModifyRGB = opacityModifyRGB;
+
+ var children = this.getChildren();
+ for (var i = 0, len = children.length; i < len; i++) {
+ var selNode = children[i];
+ if (selNode)
+ selNode.setOpacityModifyRGB(opacityModifyRGB);
+ }
+ },
+
+ /** The current control state constant. */
+ _state: cc.CONTROL_STATE_NORMAL,
+ getState: function () {
+ return this._state;
+ },
+
+ _enabled: false,
+ _selected: false,
+ _highlighted: false,
+
+ _dispatchTable: null,
+
+ /**
+ * Tells whether the control is enabled
+ * @param {Boolean} enabled
+ */
+ setEnabled: function (enabled) {
+ this._enabled = enabled;
+ this._state = enabled ? cc.CONTROL_STATE_NORMAL : cc.CONTROL_STATE_DISABLED;
+
+ this.needsLayout();
+ },
+ isEnabled: function () {
+ return this._enabled;
+ },
+
+ /**
+ * A Boolean value that determines the control selected state.
+ * @param {Boolean} selected
+ */
+ setSelected: function (selected) {
+ this._selected = selected;
+ this.needsLayout();
+ },
+ isSelected: function () {
+ return this._selected;
+ },
+
+ /**
+ * A Boolean value that determines whether the control is highlighted.
+ * @param {Boolean} highlighted
+ */
+ setHighlighted: function (highlighted) {
+ this._highlighted = highlighted;
+ this.needsLayout();
+ },
+ isHighlighted: function () {
+ return this._highlighted;
+ },
+
+ hasVisibleParents: function () {
+ var parent = this.getParent();
+ for (var c = parent; c != null; c = c.getParent()) {
+ if (!c.isVisible())
+ return false;
+ }
+ return true;
+ },
+
+ ctor: function () {
+ cc.Layer.prototype.ctor.call(this);
+ this._dispatchTable = {};
+ this._color = cc.Color.WHITE;
+ },
+
+ init: function () {
+ if (cc.Layer.prototype.init.call(this)) {
+ // Initialise instance variables
+ this._state = cc.CONTROL_STATE_NORMAL;
+ this._enabled = true;
+ this._selected = false;
+ this._highlighted = false;
+
+ var listener = cc.EventListener.create({
+ event: cc.EventListener.TOUCH_ONE_BY_ONE,
+ swallowTouches: true
+ });
+ if (this.onTouchBegan)
+ listener.onTouchBegan = this.onTouchBegan.bind(this);
+ if (this.onTouchMoved)
+ listener.onTouchMoved = this.onTouchMoved.bind(this);
+ if (this.onTouchEnded)
+ listener.onTouchEnded = this.onTouchEnded.bind(this);
+ if (this.onTouchCancelled)
+ listener.onTouchCancelled = this.onTouchCancelled.bind(this);
+ this._touchListener = listener;
+ return true;
+ } else
+ return false;
+ },
+
+ onEnter: function () {
+ var locListener = this._touchListener;
+ if (!locListener._isRegistered())
+ cc.eventManager.addListener(locListener, this);
+ cc.Node.prototype.onEnter.call(this);
+ },
+
+ /**
+ * Sends action messages for the given control events.
+ * which action messages are sent. See "CCControlEvent" for bitmask constants.
+ * @param {Number} controlEvents A bitmask whose set flags specify the control events for
+ */
+ sendActionsForControlEvents: function (controlEvents) {
+ // For each control events
+ for (var i = 0, len = cc.CONTROL_EVENT_TOTAL_NUMBER; i < len; i++) {
+ // If the given controlEvents bitmask contains the curent event
+ if ((controlEvents & (1 << i))) {
+ // Call invocations
+ //
+ var invocationList = this._dispatchListforControlEvent(1 << i);
+ for (var j = 0, inLen = invocationList.length; j < inLen; j++) {
+ invocationList[j].invoke(this);
+ }
+ }
+ }
+ },
+
+ /**
+ *
+ * Adds a target and action for a particular event (or events) to an internal
+ * dispatch table.
+ * The action message may optionally include the sender and the event as
+ * parameters, in that order.
+ * When you call this method, target is not retained.
+ *
+ * @param {Object} target The target object that is, the object to which the action message is sent. It cannot be nil. The target is not retained.
+ * @param {function} action A selector identifying an action message. It cannot be NULL.
+ * @param {Number} controlEvents A bitmask specifying the control events for which the action message is sent. See "CCControlEvent" for bitmask constants.
+ */
+ addTargetWithActionForControlEvents: function (target, action, controlEvents) {
+ // For each control events
+ for (var i = 0, len = cc.CONTROL_EVENT_TOTAL_NUMBER; i < len; i++) {
+ // If the given controlEvents bit mask contains the current event
+ if ((controlEvents & (1 << i)))
+ this._addTargetWithActionForControlEvent(target, action, 1 << i);
+ }
+ },
+
+ /**
+ * Removes a target and action for a particular event (or events) from an internal dispatch table.
+ *
+ * @param {Object} target The target object that is, the object to which the action message is sent. Pass nil to remove all targets paired with action and the specified control events.
+ * @param {function} action A selector identifying an action message. Pass NULL to remove all action messages paired with target.
+ * @param {Number} controlEvents A bitmask specifying the control events associated with target and action. See "CCControlEvent" for bitmask constants.
+ */
+ removeTargetWithActionForControlEvents: function (target, action, controlEvents) {
+ // For each control events
+ for (var i = 0, len = cc.CONTROL_EVENT_TOTAL_NUMBER; i < len; i++) {
+ // If the given controlEvents bitmask contains the current event
+ if ((controlEvents & (1 << i)))
+ this._removeTargetWithActionForControlEvent(target, action, 1 << i);
+ }
+ },
+
+ /**
+ * Returns a point corresponding to the touh location converted into the
+ * control space coordinates.
+ * @param {cc.Touch} touch A CCTouch object that represents a touch.
+ */
+ getTouchLocation: function (touch) {
+ var touchLocation = touch.getLocation(); // Get the touch position
+ return this.convertToNodeSpace(touchLocation); // Convert to the node space of this class
+ },
+
+ /**
+ * Returns a boolean value that indicates whether a touch is inside the bounds of the receiver. The given touch must be relative to the world.
+ *
+ * @param {cc.Touch} touch A cc.Touch object that represents a touch.
+ * @return {Boolean} YES whether a touch is inside the receiver's rect.
+ */
+ isTouchInside: function (touch) {
+ var touchLocation = touch.getLocation(); // Get the touch position
+ touchLocation = this.getParent().convertToNodeSpace(touchLocation);
+ return cc.rectContainsPoint(this.getBoundingBox(), touchLocation);
+ },
+
+ /**
+ *
+ * Returns an cc.Invocation object able to construct messages using a given
+ * target-action pair. (The invocation may optionally include the sender and
+ * the event as parameters, in that order)
+ *
+ * @param {Object} target The target object.
+ * @param {function} action A selector identifying an action message.
+ * @param {Number} controlEvent A control events for which the action message is sent. See "CCControlEvent" for constants.
+ *
+ * @return {cc.Invocation} an CCInvocation object able to construct messages using a given target-action pair.
+ */
+ _invocationWithTargetAndActionForControlEvent: function (target, action, controlEvent) {
+ return null;
+ },
+
+ /**
+ * Returns the cc.Invocation list for the given control event. If the list does not exist, it'll create an empty array before returning it.
+ *
+ * @param {Number} controlEvent A control events for which the action message is sent. See "CCControlEvent" for constants.
+ * @return {cc.Invocation} the cc.Invocation list for the given control event.
+ */
+ _dispatchListforControlEvent: function (controlEvent) {
+ controlEvent = controlEvent.toString();
+ // If the invocation list does not exist for the dispatch table, we create it
+ if (!this._dispatchTable[controlEvent])
+ this._dispatchTable[controlEvent] = [];
+ return this._dispatchTable[controlEvent];
+ },
+
+ /**
+ * Adds a target and action for a particular event to an internal dispatch
+ * table.
+ * The action message may optionally include the sender and the event as
+ * parameters, in that order.
+ * When you call this method, target is not retained.
+ *
+ * @param target The target object that is, the object to which the action
+ * message is sent. It cannot be nil. The target is not retained.
+ * @param action A selector identifying an action message. It cannot be NULL.
+ * @param controlEvent A control event for which the action message is sent.
+ * See "CCControlEvent" for constants.
+ */
+ _addTargetWithActionForControlEvent: function (target, action, controlEvent) {
+ // Create the invocation object
+ var invocation = new cc.Invocation(target, action, controlEvent);
+
+ // Add the invocation into the dispatch list for the given control event
+ var eventInvocationList = this._dispatchListforControlEvent(controlEvent);
+ eventInvocationList.push(invocation);
+ },
+
+ /**
+ * Removes a target and action for a particular event from an internal dispatch table.
+ *
+ * @param {Object} target The target object that is, the object to which the action message is sent. Pass nil to remove all targets paired with action and the specified control events.
+ * @param {function} action A selector identifying an action message. Pass NULL to remove all action messages paired with target.
+ * @param {Number} controlEvent A control event for which the action message is sent. See "CCControlEvent" for constants.
+ */
+ _removeTargetWithActionForControlEvent: function (target, action, controlEvent) {
+ // Retrieve all invocations for the given control event
+ //
+ var eventInvocationList = this._dispatchListforControlEvent(controlEvent);
+
+ //remove all invocations if the target and action are null
+ //TODO: should the invocations be deleted, or just removed from the array? Won't that cause issues if you add a single invocation for multiple events?
+ var bDeleteObjects = true;
+ if (!target && !action) {
+ //remove objects
+ eventInvocationList.length = 0;
+ } else {
+ //normally we would use a predicate, but this won't work here. Have to do it manually
+ for (var i = 0; i < eventInvocationList.length;) {
+ var invocation = eventInvocationList[i];
+ var shouldBeRemoved = true;
+ if (target)
+ shouldBeRemoved = (target === invocation.getTarget());
+ if (action)
+ shouldBeRemoved = (shouldBeRemoved && (action === invocation.getAction()));
+ // Remove the corresponding invocation object
+ if (shouldBeRemoved)
+ cc.js.array.remove(eventInvocationList, invocation);
+ else
+ i++;
+ }
+ }
+ },
+
+ /**
+ * Updates the control layout using its current internal state.
+ */
+ needsLayout: function () {
+ }
+});
+
+var _p = cc.Control.prototype;
+
+// Extended properties
+/** @expose */
+_p.state;
+cc.defineGetterSetter(_p, "state", _p.getState);
+/** @expose */
+_p.enabled;
+cc.defineGetterSetter(_p, "enabled", _p.isEnabled, _p.setEnabled);
+/** @expose */
+_p.selected;
+cc.defineGetterSetter(_p, "selected", _p.isSelected, _p.setSelected);
+/** @expose */
+_p.highlighted;
+cc.defineGetterSetter(_p, "highlighted", _p.isHighlighted, _p.setHighlighted);
+
+_p = null;
+
+cc.Control.create = function () {
+ var retControl = new cc.Control();
+ if (retControl && retControl.init())
+ return retControl;
+ return null;
+};
+
diff --git a/extensions/gui/control-extension/CCControlButton.js b/extensions/gui/control-extension/CCControlButton.js
new file mode 100644
index 0000000000..e571e81f08
--- /dev/null
+++ b/extensions/gui/control-extension/CCControlButton.js
@@ -0,0 +1,688 @@
+/**
+ * CCControlButton.m
+ *
+ * Copyright (c) 2008-2010 Ricardo Quesada
+ * Copyright (c) 2011-2012 cocos2d-x.org
+ * Copyright (c) 2013-2014 Chukong Technologies Inc.
+ * Copyright 2011 Yannick Loriot.
+ * http://yannickloriot.com
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+/**
+ * @ignore
+ */
+cc.CONTROL_ZOOM_ACTION_TAG = 0xCCCB0001;
+
+/**
+ * CCControlButton: Button control for Cocos2D.
+ * @class
+ * @extends cc.Control
+ *
+ * @property {Boolean} adjustBackgroundImage - Indicate whether the background image will be adjusted
+ * @property {Boolean} zoomOnTouchDown - Indicate whether the button will be zoomed while touch down
+ * @property {cc.Size} preferredSize - The preferred size of the control button
+ * @property {Boolean} labelAnchor - The anchor point for the label of the control button
+ */
+cc.ControlButton = cc.Control.extend(/** @lends cc.ControlButton# */{
+ _doesAdjustBackgroundImage: false,
+ zoomOnTouchDown: false,
+ _preferredSize: null,
+ _labelAnchorPoint: null,
+ _currentTitle: null,
+ _currentTitleColor: null,
+ _titleLabel: null,
+ _backgroundSprite: null,
+ _opacity: 0,
+ _isPushed: false,
+ _titleDispatchTable: null,
+ _titleColorDispatchTable: null,
+ _titleLabelDispatchTable: null,
+ _backgroundSpriteDispatchTable: null,
+ _parentInited: false,
+
+ _marginV: 0,
+ _marginH: 0,
+ _className: "ControlButton",
+
+ ctor: function (label, backgroundSprite, fontSize) {
+ cc.Control.prototype.ctor.call(this);
+ this._preferredSize = cc.size(0, 0);
+ this._labelAnchorPoint = cc.p(0, 0);
+ this._currentTitle = "";
+ this._currentTitleColor = cc.Color.WHITE;
+ this._titleDispatchTable = {};
+ this._titleColorDispatchTable = {};
+ this._titleLabelDispatchTable = {};
+ this._backgroundSpriteDispatchTable = {};
+
+ if(fontSize != undefined)
+ this.initWithTitleAndFontNameAndFontSize(label, backgroundSprite, fontSize);
+ else if(backgroundSprite != undefined)
+ this.initWithLabelAndBackgroundSprite(label, backgroundSprite);
+ else if(label != undefined)
+ this.initWithBackgroundSprite(label);
+ else
+ this.init();
+ },
+
+ init: function () {
+ return this.initWithLabelAndBackgroundSprite(new cc.LabelTTF("", "Arial", 12), new cc.Scale9Sprite());
+ },
+
+ needsLayout: function () {
+ if (!this._parentInited) {
+ return;
+ }
+ // Hide the background and the label
+ if (this._titleLabel)
+ this._titleLabel.setVisible(false);
+ if (this._backgroundSprite)
+ this._backgroundSprite.setVisible(false);
+
+ // Update anchor of all labels
+ this.setLabelAnchorPoint(this._labelAnchorPoint);
+
+ // Update the label to match with the current state
+ //CC_SAFE_RELEASE(this._currentTitle)
+ var locState = this._state;
+
+ this._currentTitle = this.getTitleForState(locState);
+ this._currentTitleColor = this.getTitleColorForState(locState);
+ this._titleLabel = this.getTitleLabelForState(locState);
+
+ var label = this._titleLabel;
+ if (label && label.setString)
+ label.setString(this._currentTitle);
+ if (label)
+ label.setColor(this._currentTitleColor);
+
+ var locContentSize = this.getContentSize();
+ if (label)
+ label.setPosition(locContentSize.width / 2, locContentSize.height / 2);
+
+ // Update the background sprite
+ this._backgroundSprite = this.getBackgroundSpriteForState(locState);
+ var locBackgroundSprite = this._backgroundSprite;
+ if (locBackgroundSprite)
+ locBackgroundSprite.setPosition(locContentSize.width / 2, locContentSize.height / 2);
+
+ // Get the title label size
+ var titleLabelSize = cc.size(0, 0);
+ if (label) {
+ var boundingBox = label.getBoundingBox();
+ titleLabelSize.width = boundingBox.width;
+ titleLabelSize.height = boundingBox.height;
+ }
+ // Adjust the background image if necessary
+ if (this._doesAdjustBackgroundImage) {
+ // Add the margins
+ if (locBackgroundSprite)
+ locBackgroundSprite.setContentSize(titleLabelSize.width + this._marginH * 2, titleLabelSize.height + this._marginV * 2);
+ } else {
+ //TODO: should this also have margins if one of the preferred sizes is relaxed?
+ if (locBackgroundSprite) {
+ var preferredSize = locBackgroundSprite.getPreferredSize();
+ preferredSize = cc.size(preferredSize.width, preferredSize.height);
+ if (preferredSize.width <= 0)
+ preferredSize.width = titleLabelSize.width;
+ if (preferredSize.height <= 0)
+ preferredSize.height = titleLabelSize.height;
+
+ locBackgroundSprite.setContentSize(preferredSize);
+ }
+ }
+
+ // Set the content size
+ var rectTitle = label ? label.getBoundingBox() : cc.rect(0, 0, 0, 0);
+ var rectBackground = locBackgroundSprite ? locBackgroundSprite.getBoundingBox() : cc.rect(0, 0, 0, 0);
+ var maxRect = cc.rectUnion(rectTitle, rectBackground);
+ this.setContentSize(maxRect.width, maxRect.height);
+ locContentSize = this.getContentSize();
+ if (label) {
+ label.setPosition(locContentSize.width / 2, locContentSize.height / 2);
+ label.setVisible(true);
+ }
+ if (locBackgroundSprite) {
+ locBackgroundSprite.setPosition(locContentSize.width / 2, locContentSize.height / 2);
+ locBackgroundSprite.setVisible(true);
+ }
+ },
+
+ initWithLabelAndBackgroundSprite: function (label, backgroundSprite) {
+ if (!label)
+ throw new Error("cc.ControlButton.initWithLabelAndBackgroundSprite(): label should be non-null");
+ if (!backgroundSprite)
+ throw new Error("cc.ControlButton.initWithLabelAndBackgroundSprite(): backgroundSprite should be non-null");
+ if (cc.Control.prototype.init.call(this, true)) {
+ this._parentInited = true;
+
+ // Initialize the button state tables
+ this._titleDispatchTable = {};
+ this._titleColorDispatchTable = {};
+ this._titleLabelDispatchTable = {};
+ this._backgroundSpriteDispatchTable = {};
+
+ this._isPushed = false;
+ this.zoomOnTouchDown = true;
+
+ this._currentTitle = null;
+
+ // Adjust the background image by default
+ this.setAdjustBackgroundImage(true);
+ this.setPreferredSize(cc.size(0, 0));
+
+ // Zooming button by default
+ this.zoomOnTouchDown = true;
+
+ // Set the default anchor point
+ this.ignoreAnchorPointForPosition(false);
+ this.setAnchorPoint(0.5, 0.5);
+
+ // Set the nodes
+ this._titleLabel = label;
+ this._backgroundSprite = backgroundSprite;
+
+ // Set the default color and opacity
+ this.setOpacity(255);
+ this.setOpacityModifyRGB(true);
+
+ // Initialize the dispatch table
+ var tempString = label.getString();
+ //tempString.autorelease();
+ this.setTitleForState(tempString, cc.CONTROL_STATE_NORMAL);
+ this.setTitleColorForState(label.getColor(), cc.CONTROL_STATE_NORMAL);
+ this.setTitleLabelForState(label, cc.CONTROL_STATE_NORMAL);
+ this.setBackgroundSpriteForState(backgroundSprite, cc.CONTROL_STATE_NORMAL);
+
+ this._state = cc.CONTROL_STATE_NORMAL;
+
+ //default margins
+ this._marginH = 24;
+ this._marginV = 12;
+
+ this._labelAnchorPoint = cc.p(0.5, 0.5);
+
+ this.setPreferredSize(cc.size(0, 0));
+
+ // Layout update
+ this.needsLayout();
+ return true;
+ }//couldn't init the CCControl
+ else
+ return false;
+ },
+
+ initWithTitleAndFontNameAndFontSize: function (title, fontName, fontSize) {
+ var label = new cc.LabelTTF(title, fontName, fontSize);
+ return this.initWithLabelAndBackgroundSprite(label, new cc.Scale9Sprite());
+ },
+
+ initWithBackgroundSprite: function (sprite) {
+ var label = new cc.LabelTTF("", "Arial", 30);//
+ return this.initWithLabelAndBackgroundSprite(label, sprite);
+ },
+
+ /**
+ * Adjust the background image. YES by default. If the property is set to NO, the background will use the prefered size of the background image.
+ * @return {Boolean}
+ */
+ doesAdjustBackgroundImage: function () {
+ return this._doesAdjustBackgroundImage;
+ },
+
+ setAdjustBackgroundImage: function (adjustBackgroundImage) {
+ this._doesAdjustBackgroundImage = adjustBackgroundImage;
+ this.needsLayout();
+ },
+
+ /** Adjust the button zooming on touchdown. Default value is YES. */
+ getZoomOnTouchDown: function () {
+ return this.zoomOnTouchDown;
+ },
+
+ setZoomOnTouchDown: function (zoomOnTouchDown) {
+ return this.zoomOnTouchDown = zoomOnTouchDown;
+ },
+
+ /** The prefered size of the button, if label is larger it will be expanded. */
+ getPreferredSize: function () {
+ return this._preferredSize;
+ },
+
+ setPreferredSize: function (size) {
+ if (size.width === 0 && size.height === 0) {
+ this._doesAdjustBackgroundImage = true;
+ } else {
+ this._doesAdjustBackgroundImage = false;
+ var locTable = this._backgroundSpriteDispatchTable;
+ for (var itemKey in locTable)
+ locTable[itemKey].setPreferredSize(size);
+ }
+ this._preferredSize = size;
+ this.needsLayout();
+ },
+
+ getLabelAnchorPoint: function () {
+ return this._labelAnchorPoint;
+ },
+ setLabelAnchorPoint: function (labelAnchorPoint) {
+ this._labelAnchorPoint = labelAnchorPoint;
+ if (this._titleLabel)
+ this._titleLabel.setAnchorPoint(labelAnchorPoint);
+ },
+
+ /**
+ * The current title that is displayed on the button.
+ * @return {string}
+ */
+ _getCurrentTitle: function () {
+ return this._currentTitle;
+ },
+
+ /** The current color used to display the title. */
+ _getCurrentTitleColor: function () {
+ return this._currentTitleColor;
+ },
+
+ /* Override setter to affect a background sprite too */
+ getOpacity: function () {
+ return this._opacity;
+ },
+
+ setOpacity: function (opacity) {
+ // XXX fixed me if not correct
+ cc.Control.prototype.setOpacity.call(this, opacity);
+ /*this._opacity = opacity;
+ var controlChildren = this.getChildren();
+ for (var i = 0; i < controlChildren.length; i++) {
+ var selChild = controlChildren[i];
+ if (selChild)
+ selChild.setOpacity(opacity);
+ }*/
+ var locTable = this._backgroundSpriteDispatchTable;
+ for (var itemKey in locTable)
+ locTable[itemKey].setOpacity(opacity);
+ },
+
+ setColor: function (color) {
+ cc.Control.prototype.setColor.call(this, color);
+ var locTable = this._backgroundSpriteDispatchTable;
+ for (var key in locTable)
+ locTable[key].setColor(color);
+ },
+
+ getColor: function () {
+ var locRealColor = this._realColor;
+ return cc.color(locRealColor.r, locRealColor.g, locRealColor.b, locRealColor.a);
+ },
+
+
+ /** Flag to know if the button is currently pushed. */
+ isPushed: function () {
+ return this._isPushed;
+ },
+
+ /* Define the button margin for Top/Bottom edge */
+ _getVerticalMargin: function () {
+ return this._marginV;
+ },
+ /* Define the button margin for Left/Right edge */
+ _getHorizontalOrigin: function () {
+ return this._marginH;
+ },
+
+ /**
+ * set the margins at once (so we only have to do one call of needsLayout)
+ * @param {Number} marginH
+ * @param {Number} marginV
+ */
+ setMargins: function (marginH, marginV) {
+ this._marginV = marginV;
+ this._marginH = marginH;
+ this.needsLayout();
+ },
+
+ setEnabled: function (enabled) {
+ cc.Control.prototype.setEnabled.call(this, enabled);
+ this.needsLayout();
+ },
+ setSelected: function (enabled) {
+ cc.Control.prototype.setSelected.call(this, enabled);
+ this.needsLayout();
+ },
+
+ setHighlighted: function (enabled) {
+ this._state = enabled ? cc.CONTROL_STATE_HIGHLIGHTED : cc.CONTROL_STATE_NORMAL;
+
+ cc.Control.prototype.setHighlighted.call(this, enabled);
+ var action = this.getActionByTag(cc.CONTROL_ZOOM_ACTION_TAG);
+ if (action)
+ this.stopAction(action);
+
+ //this.needsLayout();// needn't
+ if (this.zoomOnTouchDown) {
+ var scaleValue = (this.isHighlighted() && this.isEnabled() && !this.isSelected()) ? 1.1 : 1.0;
+ var zoomAction = cc.scaleTo(0.05, scaleValue);
+ zoomAction.setTag(cc.CONTROL_ZOOM_ACTION_TAG);
+ this.runAction(zoomAction);
+ }
+ },
+
+ onTouchBegan: function (touch, event) {
+ if (!this.isTouchInside(touch) || !this.isEnabled() || !this.isVisible() || !this.hasVisibleParents())
+ return false;
+
+ this._isPushed = true;
+ this.setHighlighted(true);
+ this.sendActionsForControlEvents(cc.CONTROL_EVENT_TOUCH_DOWN);
+ return true;
+ },
+
+ onTouchMoved: function (touch, event) {
+ if (!this._enabled || !this._isPushed || this._selected) {
+ if (this._highlighted)
+ this.setHighlighted(false);
+ return;
+ }
+
+ var isTouchMoveInside = this.isTouchInside(touch);
+ if (isTouchMoveInside && !this._highlighted) {
+ this.setHighlighted(true);
+ this.sendActionsForControlEvents(cc.CONTROL_EVENT_TOUCH_DRAG_ENTER);
+ } else if (isTouchMoveInside && this._highlighted) {
+ this.sendActionsForControlEvents(cc.CONTROL_EVENT_TOUCH_DRAG_INSIDE);
+ } else if (!isTouchMoveInside && this._highlighted) {
+ this.setHighlighted(false);
+ this.sendActionsForControlEvents(cc.CONTROL_EVENT_TOUCH_DRAG_EXIT);
+ } else if (!isTouchMoveInside && !this._highlighted) {
+ this.sendActionsForControlEvents(cc.CONTROL_EVENT_TOUCH_DRAG_OUTSIDE);
+ }
+ },
+ onTouchEnded: function (touch, event) {
+ this._isPushed = false;
+ this.setHighlighted(false);
+
+ if (this.isTouchInside(touch)) {
+ this.sendActionsForControlEvents(cc.CONTROL_EVENT_TOUCH_UP_INSIDE);
+ } else {
+ this.sendActionsForControlEvents(cc.CONTROL_EVENT_TOUCH_UP_OUTSIDE);
+ }
+ },
+
+ onTouchCancelled: function (touch, event) {
+ this._isPushed = false;
+ this.setHighlighted(false);
+ this.sendActionsForControlEvents(cc.CONTROL_EVENT_TOUCH_CANCEL);
+ },
+
+ /**
+ * Returns the title used for a state.
+ *
+ * @param {Number} state The state that uses the title. Possible values are described in "CCControlState".
+ * @return {string} The title for the specified state.
+ */
+ getTitleForState: function (state) {
+ var locTable = this._titleDispatchTable;
+ if (locTable) {
+ if (locTable[state])
+ return locTable[state];
+ return locTable[cc.CONTROL_STATE_NORMAL];
+ }
+ return "";
+ },
+
+ /**
+ *
+ * Sets the title string to use for the specified state.
+ * If a property is not specified for a state, the default is to use the CCButtonStateNormal value.
+ *
+ * @param {string} title The title string to use for the specified state.
+ * @param {Number} state The state that uses the specified title. The values are described in "CCControlState".
+ */
+ setTitleForState: function (title, state) {
+ this._titleDispatchTable[state] = title || "";
+
+ // If the current state if equal to the given state we update the layout
+ if (this.getState() === state)
+ this.needsLayout();
+ },
+
+ /**
+ * Returns the title color used for a state.
+ *
+ * @param {Number} state The state that uses the specified color. The values are described in "CCControlState".
+ * @return {cc.Color} The color of the title for the specified state.
+ */
+ getTitleColorForState: function (state) {
+ var colorObject = this._titleColorDispatchTable[state];
+ if (colorObject)
+ return colorObject;
+ colorObject = this._titleColorDispatchTable[cc.CONTROL_STATE_NORMAL];
+ if (colorObject)
+ return colorObject;
+ return cc.Color.WHITE;
+ },
+
+ /**
+ * Sets the color of the title to use for the specified state.
+ *
+ * @param {cc.Color} color The color of the title to use for the specified state.
+ * @param {Number} state The state that uses the specified color. The values are described in "CCControlState".
+ */
+ setTitleColorForState: function (color, state) {
+ //ccColor3B* colorValue=&color;
+ this._titleColorDispatchTable[state] = color;
+
+ // If the current state if equal to the given state we update the layout
+ if (this.getState() === state)
+ this.needsLayout();
+ },
+
+ /**
+ * Returns the title label used for a state.
+ *
+ * @param state The state that uses the title label. Possible values are described in "CCControlState".
+ * @return {cc.Node} the title label used for a state.
+ */
+ getTitleLabelForState: function (state) {
+ var locTable = this._titleLabelDispatchTable;
+ if (locTable[state])
+ return locTable[state];
+
+ return locTable[cc.CONTROL_STATE_NORMAL];
+ },
+
+ /**
+ * Sets the title label to use for the specified state.
+ * If a property is not specified for a state, the default is to use the CCButtonStateNormal value.
+ *
+ * @param {cc.Node} titleLabel The title label to use for the specified state.
+ * @param {Number} state The state that uses the specified title. The values are described in "CCControlState".
+ */
+ setTitleLabelForState: function (titleLabel, state) {
+ var locTable = this._titleLabelDispatchTable;
+ if (locTable[state]) {
+ var previousLabel = locTable[state];
+ if (previousLabel)
+ this.removeChild(previousLabel, true);
+ }
+
+ locTable[state] = titleLabel;
+ titleLabel.setVisible(false);
+ titleLabel.setAnchorPoint(0.5, 0.5);
+ this.addChild(titleLabel, 1);
+
+ // If the current state if equal to the given state we update the layout
+ if (this.getState() === state)
+ this.needsLayout();
+ },
+
+ /**
+ * Sets the title TTF filename to use for the specified state.
+ * @param {string} fntFile
+ * @param {Number} state
+ */
+ setTitleTTFForState: function (fntFile, state) {
+ var title = this.getTitleForState(state);
+ if (!title)
+ title = "";
+ this.setTitleLabelForState(new cc.LabelTTF(title, fntFile, 12), state);
+ },
+
+ /**
+ * return the title TTF filename to use for the specified state.
+ * @param {Number} state
+ * @returns {string}
+ */
+ getTitleTTFForState: function (state) {
+ var labelTTF = this.getTitleLabelForState(state);
+ if ((labelTTF != null) && (labelTTF instanceof cc.LabelTTF)) {
+ return labelTTF.getFontName();
+ } else {
+ return "";
+ }
+ },
+
+ /**
+ * @param {Number} size
+ * @param {Number} state
+ */
+ setTitleTTFSizeForState: function (size, state) {
+ var labelTTF = this.getTitleLabelForState(state);
+ if ((labelTTF != null) && (labelTTF instanceof cc.LabelTTF)) {
+ labelTTF.setFontSize(size);
+ }
+ },
+
+ /**
+ * return the font size of LabelTTF to use for the specified state
+ * @param {Number} state
+ * @returns {Number}
+ */
+ getTitleTTFSizeForState: function (state) {
+ var labelTTF = this.getTitleLabelForState(state);
+ if ((labelTTF != null) && (labelTTF instanceof cc.LabelTTF)) {
+ return labelTTF.getFontSize();
+ }
+ return 0;
+ },
+
+ /**
+ * Sets the font of the label, changes the label to a CCLabelBMFont if necessary.
+ * @param {string} fntFile The name of the font to change to
+ * @param {Number} state The state that uses the specified fntFile. The values are described in "CCControlState".
+ */
+ setTitleBMFontForState: function (fntFile, state) {
+ var title = this.getTitleForState(state);
+ if (!title)
+ title = "";
+ this.setTitleLabelForState(new cc.LabelBMFont(title, fntFile), state);
+ },
+
+ getTitleBMFontForState: function (state) {
+ var labelBMFont = this.getTitleLabelForState(state);
+ if ((labelBMFont != null) && (labelBMFont instanceof cc.LabelBMFont)) {
+ return labelBMFont.getFntFile();
+ }
+ return "";
+ },
+
+ /**
+ * Returns the background sprite used for a state.
+ *
+ * @param {Number} state The state that uses the background sprite. Possible values are described in "CCControlState".
+ */
+ getBackgroundSpriteForState: function (state) {
+ var locTable = this._backgroundSpriteDispatchTable;
+ if (locTable[state]) {
+ return locTable[state];
+ }
+ return locTable[cc.CONTROL_STATE_NORMAL];
+ },
+
+ /**
+ * Sets the background sprite to use for the specified button state.
+ *
+ * @param {Scale9Sprite} sprite The background sprite to use for the specified state.
+ * @param {Number} state The state that uses the specified image. The values are described in "CCControlState".
+ */
+ setBackgroundSpriteForState: function (sprite, state) {
+ var locTable = this._backgroundSpriteDispatchTable;
+ if (locTable[state]) {
+ var previousSprite = locTable[state];
+ if (previousSprite)
+ this.removeChild(previousSprite, true);
+ }
+
+ locTable[state] = sprite;
+ sprite.setVisible(false);
+ sprite.setAnchorPoint(0.5, 0.5);
+ this.addChild(sprite);
+
+ var locPreferredSize = this._preferredSize;
+ if (locPreferredSize.width !== 0 || locPreferredSize.height !== 0) {
+ sprite.setPreferredSize(locPreferredSize);
+ }
+
+ // If the current state if equal to the given state we update the layout
+ if (this._state === state)
+ this.needsLayout();
+ },
+
+ /**
+ * Sets the background spriteFrame to use for the specified button state.
+ *
+ * @param {SpriteFrame} spriteFrame The background spriteFrame to use for the specified state.
+ * @param {Number} state The state that uses the specified image. The values are described in "CCControlState".
+ */
+ setBackgroundSpriteFrameForState: function (spriteFrame, state) {
+ var sprite = cc.Scale9Sprite.createWithSpriteFrame(spriteFrame);
+ this.setBackgroundSpriteForState(sprite, state);
+ }
+});
+
+var _p = cc.ControlButton.prototype;
+
+// Extended properties
+/** @expose */
+_p.adjustBackground;
+cc.defineGetterSetter(_p, "adjustBackground", _p.getAdjustBackgroundImage, _p.setAdjustBackgroundImage);
+/** @expose */
+_p.preferredSize;
+cc.defineGetterSetter(_p, "preferredSize", _p.getPreferredSize, _p.setPreferredSize);
+/** @expose */
+_p.labelAnchor;
+cc.defineGetterSetter(_p, "labelAnchor", _p.getLabelAnchorPoint, _p.setLabelAnchorPoint);
+
+_p = null;
+
+/**
+ * @deprecated
+ * @param label
+ * @param backgroundSprite
+ * @param fontSize
+ * @returns {ControlButton}
+ */
+cc.ControlButton.create = function (label, backgroundSprite, fontSize) {
+ return new cc.ControlButton(label, backgroundSprite, fontSize);
+};
+
+
diff --git a/extensions/gui/control-extension/CCControlColourPicker.js b/extensions/gui/control-extension/CCControlColourPicker.js
new file mode 100644
index 0000000000..6cdfd6bcc8
--- /dev/null
+++ b/extensions/gui/control-extension/CCControlColourPicker.js
@@ -0,0 +1,187 @@
+/**
+ *
+ * Copyright (c) 2008-2010 Ricardo Quesada
+ * Copyright (c) 2011-2012 cocos2d-x.org
+ * Copyright (c) 2013-2014 Chukong Technologies Inc.
+ *
+ * Copyright 2012 Stewart Hamilton-Arrandale.
+ * http://creativewax.co.uk
+ *
+ * Modified by Yannick Loriot.
+ * http://yannickloriot.com
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE. *
+ *
+ */
+
+/**
+ * ControlColourPicker: color picker ui component.
+ * @class
+ * @extends cc.Control
+ *
+ * @property {cc.Sprite} background - <@readonly> The background sprite
+ */
+cc.ControlColourPicker = cc.Control.extend(/** @lends cc.ControlColourPicker# */{
+ _hsv:null,
+ _colourPicker:null,
+ _huePicker:null,
+
+ _background:null,
+ _className:"ControlColourPicker",
+ ctor:function () {
+ cc.Control.prototype.ctor.call(this);
+ this.init();
+ },
+ hueSliderValueChanged:function (sender, controlEvent) {
+ this._hsv.h = sender.getHue();
+
+ // Update the value
+ var rgb = cc.ControlUtils.RGBfromHSV(this._hsv);
+ cc.Control.prototype.setColor.call(this,cc.color(0 | (rgb.r * 255), 0 | (rgb.g * 255), 0 | (rgb.b * 255)));
+
+ // Send CCControl callback
+ this.sendActionsForControlEvents(cc.CONTROL_EVENT_VALUECHANGED);
+ this._updateControlPicker();
+ },
+
+ colourSliderValueChanged:function (sender, controlEvent) {
+ this._hsv.s = sender.getSaturation();
+ this._hsv.v = sender.getBrightness();
+
+
+ // Update the value
+ var rgb = cc.ControlUtils.RGBfromHSV(this._hsv);
+ cc.Control.prototype.setColor.call(this,cc.color(0 | (rgb.r * 255), 0 | (rgb.g * 255), 0 | (rgb.b * 255)));
+
+ // Send CCControl callback
+ this.sendActionsForControlEvents(cc.CONTROL_EVENT_VALUECHANGED);
+ },
+
+ setColor:function (color) {
+ cc.Control.prototype.setColor.call(this,color);
+ //this._colorValue = color;
+ var rgba = new cc.RGBA();
+ rgba.r = color.r / 255.0;
+ rgba.g = color.g / 255.0;
+ rgba.b = color.b / 255.0;
+ rgba.a = 1.0;
+
+ this._hsv = cc.ControlUtils.HSVfromRGB(rgba);
+ this._updateHueAndControlPicker();
+ },
+
+ getBackground:function () {
+ return this._background;
+ },
+
+ init:function () {
+ if (cc.Control.prototype.init.call(this)) {
+ // Cache the sprites
+ cc.spriteFrameCache.addSpriteFrames(res.CCControlColourPickerSpriteSheet_plist);
+
+ // Create the sprite batch node
+ var spriteSheet = new cc.SpriteBatchNode(res.CCControlColourPickerSpriteSheet_png);
+ this.addChild(spriteSheet);
+
+ /*// MIPMAP
+ //TODO WebGL code
+ var params = [gl.LINEAR_MIPMAP_NEAREST, gl.LINEAR, gl.REPEAT, gl.CLAMP_TO_EDGE];
+ spriteSheet.getTexture().setAliasTexParameters();
+ spriteSheet.getTexture().setTexParameters(params);
+ spriteSheet.getTexture().generateMipmap();*/
+
+ // Init default color
+ this._hsv = new cc.HSV(0, 0, 0);
+
+ // Add image
+ this._background = cc.ControlUtils.addSpriteToTargetWithPosAndAnchor("menuColourPanelBackground.png", spriteSheet, cc.p(0,0), cc.p(0.5, 0.5));
+
+ var backgroundPointZero = cc.pSub(this._background.getPosition(),
+ cc.p(this._background.getContentSize().width / 2, this._background.getContentSize().height / 2));
+
+ // Setup panels . currently hard-coded...
+ var hueShift = 8;
+ var colourShift = 28;
+
+ this._huePicker = new cc.ControlHuePicker(spriteSheet, cc.p(backgroundPointZero.x + hueShift, backgroundPointZero.y + hueShift));
+ this._colourPicker = new cc.ControlSaturationBrightnessPicker(spriteSheet, cc.p(backgroundPointZero.x + colourShift, backgroundPointZero.y + colourShift));
+
+ // Setup events
+ this._huePicker.addTargetWithActionForControlEvents(this, this.hueSliderValueChanged, cc.CONTROL_EVENT_VALUECHANGED);
+ this._colourPicker.addTargetWithActionForControlEvents(this, this.colourSliderValueChanged, cc.CONTROL_EVENT_VALUECHANGED);
+
+ // Set defaults
+ this._updateHueAndControlPicker();
+ this.addChild(this._huePicker);
+ this.addChild(this._colourPicker);
+
+ // Set content size
+ this.setContentSize(this._background.getContentSize());
+ return true;
+ }
+ else
+ return false;
+ },
+
+ _updateControlPicker:function () {
+ this._huePicker.setHue(this._hsv.h);
+ this._colourPicker.updateWithHSV(this._hsv);
+ },
+
+ _updateHueAndControlPicker:function () {
+ this._huePicker.setHue(this._hsv.h);
+ this._colourPicker.updateWithHSV(this._hsv);
+ this._colourPicker.updateDraggerWithHSV(this._hsv);
+ },
+ setEnabled:function (enabled) {
+ cc.Control.prototype.setEnabled.call(this, enabled);
+ if (this._huePicker !== null) {
+ this._huePicker.setEnabled(enabled);
+ }
+ if (this._colourPicker) {
+ this._colourPicker.setEnabled(enabled);
+ }
+ },
+ onTouchBegan:function () {
+ //ignore all touches, handled by children
+ return false;
+ }
+});
+
+var _p = cc.ControlColourPicker.prototype;
+
+// Extended properties
+/** @expose */
+_p.background;
+cc.defineGetterSetter(_p, "background", _p.getBackground);
+
+_p = null;
+
+/**
+ * @deprecated
+ * @returns {ControlColourPicker}
+ */
+cc.ControlColourPicker.create = function () {
+ return new cc.ControlColourPicker();
+};
+
+// compatible with NPM
+var res = res || {};
+res.CCControlColourPickerSpriteSheet_plist = res.CCControlColourPickerSpriteSheet_plist || "res/extensions/CCControlColourPickerSpriteSheet.plist";
+res.CCControlColourPickerSpriteSheet_png = res.CCControlColourPickerSpriteSheet_png || "res/extensions/CCControlColourPickerSpriteSheet.png";
\ No newline at end of file
diff --git a/extensions/gui/control-extension/CCControlHuePicker.js b/extensions/gui/control-extension/CCControlHuePicker.js
new file mode 100644
index 0000000000..58db95f4ac
--- /dev/null
+++ b/extensions/gui/control-extension/CCControlHuePicker.js
@@ -0,0 +1,218 @@
+/**
+ *
+ * Copyright (c) 2008-2010 Ricardo Quesada
+ * Copyright (c) 2011-2012 cocos2d-x.org
+ * Copyright (c) 2013-2014 Chukong Technologies Inc.
+ *
+ * Copyright 2012 Stewart Hamilton-Arrandale.
+ * http://creativewax.co.uk
+ *
+ * Modified by Yannick Loriot.
+ * http://yannickloriot.com
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ *
+ * converted to Javascript / cocos2d-x by Angus C
+ */
+
+/**
+ * ControlHuePicker: HUE picker ui component.
+ * @class
+ * @extends cc.Control
+ *
+ * @property {Number} hue - The hue value
+ * @property {Number} huePercent - The hue value in percentage
+ * @property {cc.Sprite} background - <@readonly> The background sprite
+ * @property {cc.Sprite} slider - <@readonly> The slider sprite
+ * @property {cc.Vec2} startPos - <@readonly> The start position of the picker
+ */
+cc.ControlHuePicker = cc.Control.extend(/** @lends cc.ControlHuePicker# */{
+ _hue:0,
+ _huePercentage:0,
+ _background:null,
+ _slider:null,
+ _startPos:null,
+ _className:"ControlHuePicker",
+
+ /**
+ * The constructor of cc.ControlHuePicker
+ * @param {cc.Node} target
+ * @param {cc.Vec2} pos position
+ */
+ ctor:function(target, pos) {
+ cc.Control.prototype.ctor.call(this);
+ pos && this.initWithTargetAndPos(target, pos);
+ },
+
+ //maunally put in the setters
+ getHue:function () {
+ return this._hue;
+ },
+ setHue:function (hueValue) {
+ this._hue = hueValue;
+ this.setHuePercentage(this._hue / 360.0);
+ },
+
+ getHuePercentage:function () {
+ return this._huePercentage;
+ },
+ setHuePercentage:function (hueValueInPercent) {
+ this._huePercentage = hueValueInPercent;
+ this._hue = this._huePercentage * 360.0;
+
+ // Clamp the position of the icon within the circle
+ var backgroundBox = this._background.getBoundingBox();
+
+ // Get the center point of the background image
+ var centerX = this._startPos.x + backgroundBox.width * 0.5;
+ var centerY = this._startPos.y + backgroundBox.height * 0.5;
+
+ // Work out the limit to the distance of the picker when moving around the hue bar
+ var limit = backgroundBox.width * 0.5 - 15.0;
+
+ // Update angle
+ var angleDeg = this._huePercentage * 360.0 - 180.0;
+ var angle = cc.degreesToRadians(angleDeg);
+
+ // Set new position of the slider
+ var x = centerX + limit * Math.cos(angle);
+ var y = centerY + limit * Math.sin(angle);
+ this._slider.setPosition(x, y);
+ },
+
+ setEnabled:function (enabled) {
+ cc.Control.prototype.setEnabled.call(this, enabled);
+ if (this._slider) {
+ this._slider.setOpacity(enabled ? 255 : 128);
+ }
+ },
+
+ getBackground:function () {
+ return this._background;
+ },
+ getSlider:function () {
+ return this._slider;
+ },
+ getStartPos:function () {
+ return this._startPos;
+ },
+
+ initWithTargetAndPos:function (target, pos) {
+ if (cc.Control.prototype.init.call(this)) {
+ // Add background and slider sprites
+ this._background = cc.ControlUtils.addSpriteToTargetWithPosAndAnchor("huePickerBackground.png", target, pos, cc.p(0.0, 0.0));
+ this._slider = cc.ControlUtils.addSpriteToTargetWithPosAndAnchor("colourPicker.png", target, pos, cc.p(0.5, 0.5));
+
+ this._slider.setPosition(pos.x, pos.y + this._background.getBoundingBox().height * 0.5);
+ this._startPos = pos;
+
+ // Sets the default value
+ this._hue = 0.0;
+ this._huePercentage = 0.0;
+ return true;
+ } else
+ return false;
+ },
+
+ _updateSliderPosition:function (location) {
+ // Clamp the position of the icon within the circle
+ var backgroundBox = this._background.getBoundingBox();
+
+ // Get the center point of the background image
+ var centerX = this._startPos.x + backgroundBox.width * 0.5;
+ var centerY = this._startPos.y + backgroundBox.height * 0.5;
+
+ // Work out the distance difference between the location and center
+ var dx = location.x - centerX;
+ var dy = location.y - centerY;
+
+ // Update angle by using the direction of the location
+ var angle = Math.atan2(dy, dx);
+ var angleDeg = cc.radiansToDegrees(angle) + 180.0;
+
+ // use the position / slider width to determin the percentage the dragger is at
+ this.setHue(angleDeg);
+
+ // send CCControl callback
+ this.sendActionsForControlEvents(cc.CONTROL_EVENT_VALUECHANGED);
+ },
+ _checkSliderPosition:function (location) {
+ // compute the distance between the current location and the center
+ var distance = Math.sqrt(Math.pow(location.x + 10, 2) + Math.pow(location.y, 2));
+
+ // check that the touch location is within the circle
+ if (80 > distance && distance > 59) {
+ this._updateSliderPosition(location);
+ return true;
+ }
+ return false;
+ },
+
+ onTouchBegan:function (touch, event) {
+ if (!this.isEnabled() || !this.isVisible()) {
+ return false;
+ }
+ var touchLocation = this.getTouchLocation(touch);
+
+ // Check the touch position on the slider
+ return this._checkSliderPosition(touchLocation);
+ },
+ onTouchMoved:function (touch, event) {
+ // Get the touch location
+ var touchLocation = this.getTouchLocation(touch);
+
+ //small modification: this allows changing of the colour, even if the touch leaves the bounding area
+ //this._updateSliderPosition(touchLocation);
+ //this.sendActionsForControlEvents(cc.CONTROL_EVENT_VALUECHANGED);
+ // Check the touch position on the slider
+ this._checkSliderPosition(touchLocation);
+ }
+});
+
+var _p = cc.ControlHuePicker.prototype;
+
+// Extended properties
+/** @expose */
+_p.hue;
+cc.defineGetterSetter(_p, "hue", _p.getHue, _p.setHue);
+/** @expose */
+_p.huePercent;
+cc.defineGetterSetter(_p, "huePercent", _p.getHuePercentage, _p.setHuePercentage);
+/** @expose */
+_p.background;
+cc.defineGetterSetter(_p, "background", _p.getBackground);
+/** @expose */
+_p.slider;
+cc.defineGetterSetter(_p, "slider", _p.getSlider);
+/** @expose */
+_p.startPos;
+cc.defineGetterSetter(_p, "startPos", _p.getStartPos);
+
+_p = null;
+
+/**
+ * @deprecated
+ * @param target
+ * @param pos
+ * @returns {ControlHuePicker}
+ */
+cc.ControlHuePicker.create = function (target, pos) {
+ return new cc.ControlHuePicker(target, pos);
+};
\ No newline at end of file
diff --git a/extensions/gui/control-extension/CCControlPotentiometer.js b/extensions/gui/control-extension/CCControlPotentiometer.js
new file mode 100644
index 0000000000..298c7074ab
--- /dev/null
+++ b/extensions/gui/control-extension/CCControlPotentiometer.js
@@ -0,0 +1,300 @@
+/**
+ * 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
+ *
+ * Copyright 2012 Yannick Loriot. All rights reserved.
+ * http://yannickloriot.com
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ */
+
+/**
+ * CCControlPotentiometer: Potentiometer control for Cocos2D.
+ * @class
+ * @extends cc.Control
+ *
+ * @property {Number} value - The current value of the potentionmeter
+ * @property {Number} minValue - The minimum value of the potentionmeter
+ * @property {Number} maxValue - The maximum value of the potentionmeter
+ * @property {cc.ProgressTimer} progressTimer - The progress timer of the potentionmeter
+ * @property {cc.Sprite} thumbSprite - The thumb sprite of the potentionmeter
+ * @property {cc.Vec2} prevLocation - The previous location of the potentionmeter
+ */
+cc.ControlPotentiometer = cc.Control.extend(/** @lends cc.ControlPotentiometer# */{
+ _thumbSprite:null,
+ _progressTimer:null,
+ _previousLocation:null,
+ /** Contains the receiverâs current value. */
+ _value:0,
+ /** Contains the minimum value of the receiver.
+ * The default value of this property is 0.0. */
+ _minimumValue:0,
+ /** Contains the maximum value of the receiver.
+ * The default value of this property is 1.0. */
+ _maximumValue:1,
+ _className:"ControlPotentiometer",
+
+ ctor:function (backgroundFile, progressFile, thumbFile) {
+ cc.Control.prototype.ctor.call(this);
+ if (thumbFile != undefined) {
+ // Prepare track for potentiometer
+ var backgroundSprite = new cc.Sprite(backgroundFile);
+
+ // Prepare thumb for potentiometer
+ var thumbSprite = new cc.Sprite(thumbFile);
+
+ // Prepare progress for potentiometer
+ var progressTimer = new cc.ProgressTimer(new cc.Sprite(progressFile));
+ this.initWithTrackSprite_ProgressTimer_ThumbSprite(backgroundSprite, progressTimer, thumbSprite);
+ }
+ },
+
+ /**
+ *
+ * @param {cc.Sprite} trackSprite
+ * @param {cc.ProgressTimer} progressTimer
+ * @param {cc.Sprite} thumbSprite
+ * @return {Boolean}
+ */
+ initWithTrackSprite_ProgressTimer_ThumbSprite:function (trackSprite, progressTimer, thumbSprite) {
+ if (this.init()) {
+ this.setProgressTimer(progressTimer);
+ this.setThumbSprite(thumbSprite);
+ this._thumbSprite.setPosition(progressTimer.getPosition());
+
+ this.addChild(thumbSprite, 2);
+ this.addChild(progressTimer, 1);
+ this.addChild(trackSprite);
+
+ this.setContentSize(trackSprite.getContentSize());
+
+ // Init default values
+ this._minimumValue = 0.0;
+ this._maximumValue = 1.0;
+ this.setValue(this._minimumValue);
+ return true;
+ }
+ return false;
+ },
+
+ setEnabled:function (enabled) {
+ this.setEnabled(enabled);
+ if (this._thumbSprite !== null) {
+ this._thumbSprite.setOpacity((enabled) ? 255 : 128);
+ }
+ },
+
+ setValue:function (value) {
+ // set new value with sentinel
+ if (value < this._minimumValue) {
+ value = this._minimumValue;
+ }
+
+ if (value > this._maximumValue) {
+ value = this._maximumValue;
+ }
+
+ this._value = value;
+
+ // Update thumb and progress position for new value
+ var percent = (value - this._minimumValue) / (this._maximumValue - this._minimumValue);
+ this._progressTimer.setPercentage(percent * 100.0);
+ this._thumbSprite.setRotation(percent * 360.0);
+
+ this.sendActionsForControlEvents(cc.CONTROL_EVENT_VALUECHANGED);
+ },
+
+ getValue:function () {
+ return this._value;
+ },
+
+ setMinimumValue:function (minimumValue) {
+ this._minimumValue = minimumValue;
+
+ if (this._minimumValue >= this._maximumValue) {
+ this._maximumValue = this._minimumValue + 1.0;
+ }
+
+ this.setValue(this._maximumValue);
+ },
+
+ getMinimumValue:function () {
+ return this._minimumValue;
+ },
+
+ setMaximumValue:function (maximumValue) {
+ this._maximumValue = maximumValue;
+
+ if (this._maximumValue <= this._minimumValue) {
+ this._minimumValue = this._maximumValue - 1.0;
+ }
+
+ this.setValue(this._minimumValue);
+ },
+
+ getMaximumValue:function () {
+ return this._maximumValue;
+ },
+
+ isTouchInside:function (touch) {
+ var touchLocation = this.getTouchLocation(touch);
+
+ var distance = this.distanceBetweenPointAndPoint(this._progressTimer.getPosition(), touchLocation);
+
+ return distance < Math.min(this.getContentSize().width / 2, this.getContentSize().height / 2);
+ },
+
+ onTouchBegan:function (touch, event) {
+ if (!this.isTouchInside(touch) || !this.isEnabled() || !this.isVisible()) {
+ return false;
+ }
+
+ this._previousLocation = this.getTouchLocation(touch);
+
+ this.potentiometerBegan(this._previousLocation);
+
+ return true;
+ },
+
+ onTouchMoved:function (touch, event) {
+ var location = this.getTouchLocation(touch);
+
+ this.potentiometerMoved(location);
+ },
+
+ onTouchEnded:function (touch, event) {
+ this.potentiometerEnded(cc.p(0, 0));
+ },
+
+ /**
+ * the distance between the point1 and point2
+ * @param {cc.Vec2} point1
+ * @param {cc.Vec2} point2
+ * @return {Number}
+ */
+ distanceBetweenPointAndPoint:function (point1, point2) {
+ var dx = point1.x - point2.x;
+ var dy = point1.y - point2.y;
+ return Math.sqrt(dx * dx + dy * dy);
+ },
+
+ /**
+ * the angle in degree between line1 and line2.
+ * @param {cc.Vec2} beginLineA
+ * @param {cc.Vec2} endLineA
+ * @param {cc.Vec2} beginLineB
+ * @param {cc.Vec2} endLineB
+ * @return {Number}
+ */
+ angleInDegreesBetweenLineFromPoint_toPoint_toLineFromPoint_toPoint:function (beginLineA, endLineA, beginLineB, endLineB) {
+ var a = endLineA.x - beginLineA.x;
+ var b = endLineA.y - beginLineA.y;
+ var c = endLineB.x - beginLineB.x;
+ var d = endLineB.y - beginLineB.y;
+
+ var atanA = Math.atan2(a, b);
+ var atanB = Math.atan2(c, d);
+
+ // convert radiants to degrees
+ return (atanA - atanB) * 180 / Math.PI;
+ },
+
+ potentiometerBegan:function (location) {
+ this.setSelected(true);
+ this.getThumbSprite().setColor(cc.Color.GRAY);
+ },
+
+ potentiometerMoved:function (location) {
+ var angle = this.angleInDegreesBetweenLineFromPoint_toPoint_toLineFromPoint_toPoint(this._progressTimer.getPosition(), location, this._progressTimer.getPosition(), this._previousLocation);
+
+ // fix value, if the 12 o'clock position is between location and previousLocation
+ if (angle > 180) {
+ angle -= 360;
+ }
+ else if (angle < -180) {
+ angle += 360;
+ }
+
+ this.setValue(this._value + angle / 360.0 * (this._maximumValue - this._minimumValue));
+
+ this._previousLocation = location;
+ },
+
+ potentiometerEnded:function (location) {
+ this.getThumbSprite().setColor(cc.Color.WHITE);
+ this.setSelected(false);
+ },
+ setThumbSprite:function (sprite) {
+ this._thumbSprite = sprite;
+ },
+ getThumbSprite:function () {
+ return this._thumbSprite;
+ },
+ setProgressTimer:function (sprite) {
+ this._progressTimer = sprite;
+ },
+ getProgressTimer:function () {
+ return this._progressTimer;
+ },
+ setPreviousLocation:function (point) {
+ this._previousLocation = point;
+ },
+ getPreviousLocation:function () {
+ return this._previousLocation;
+ }
+});
+
+var _p = cc.ControlPotentiometer.prototype;
+
+// Extended properties
+/** @expose */
+_p.value;
+cc.defineGetterSetter(_p, "value", _p.getValue, _p.setValue);
+/** @expose */
+_p.minValue;
+cc.defineGetterSetter(_p, "minValue", _p.getMinimumValue, _p.setMinimumValue);
+/** @expose */
+_p.maxValue;
+cc.defineGetterSetter(_p, "maxValue", _p.getMaximumValue, _p.setMaximumValue);
+/** @expose */
+_p.progressTimer;
+cc.defineGetterSetter(_p, "progressTimer", _p.getProgressTimer, _p.setProgressTimer);
+/** @expose */
+_p.thumbSprite;
+cc.defineGetterSetter(_p, "thumbSprite", _p.getThumbSprite, _p.setThumbSprite);
+/** @expose */
+_p.prevLocation;
+cc.defineGetterSetter(_p, "prevLocation", _p.getPreviousLocation, _p.setPreviousLocation);
+
+_p = null;
+
+/**
+ * @deprecated
+ * @param backgroundFile
+ * @param progressFile
+ * @param thumbFile
+ * @returns {ControlPotentiometer}
+ */
+cc.ControlPotentiometer.create = function (backgroundFile, progressFile, thumbFile) {
+ return new cc.ControlPotentiometer(backgroundFile, progressFile, thumbFile);
+};
\ No newline at end of file
diff --git a/extensions/gui/control-extension/CCControlSaturationBrightnessPicker.js b/extensions/gui/control-extension/CCControlSaturationBrightnessPicker.js
new file mode 100644
index 0000000000..bd635c342e
--- /dev/null
+++ b/extensions/gui/control-extension/CCControlSaturationBrightnessPicker.js
@@ -0,0 +1,257 @@
+/**
+ *
+ * Copyright (c) 2008-2010 Ricardo Quesada
+ * Copyright (c) 2011-2012 cocos2d-x.org
+ * Copyright (c) 2013-2014 Chukong Technologies Inc.
+ *
+ * Copyright 2012 Stewart Hamilton-Arrandale.
+ * http://creativewax.co.uk
+ *
+ * Modified by Yannick Loriot.
+ * http://yannickloriot.com
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ *
+ * converted to Javascript / cocos2d-x by Angus C
+ */
+
+/**
+ * ControlSaturationBrightnessPicker: Saturation brightness picker ui component.
+ * @class
+ * @extends cc.Control
+ *
+ * @property {Number} saturation - <@readonly> Saturation value of the picker
+ * @property {Number} brightness - <@readonly> Brightness value of the picker
+ * @property {cc.Sprite} background - <@readonly> The background sprite
+ * @property {cc.Sprite} overlay - <@readonly> The overlay sprite
+ * @property {cc.Sprite} shadow - <@readonly> The shadow sprite
+ * @property {cc.Sprite} slider - <@readonly> The slider sprite
+ * @property {cc.Vec2} startPos - <@readonly> The start position of the picker
+ */
+cc.ControlSaturationBrightnessPicker = cc.Control.extend(/** @lends cc.ControlSaturationBrightnessPicker# */{
+ _saturation:0,
+ _brightness:0,
+
+ _background:null,
+ _overlay:null,
+ _shadow:null,
+ _slider:null,
+ _startPos:null,
+
+ _boxPos:0,
+ _boxSize:0,
+ _className:"ControlSaturationBrightnessPicker",
+
+ /**
+ * The constructor of cc.ControlSaturationBrightnessPicker
+ * @param {cc.Node} target
+ * @param {cc.Vec2} pos position
+ */
+ ctor:function (target, pos) {
+ cc.Control.prototype.ctor.call(this);
+ pos && this.initWithTargetAndPos(target, pos);
+ },
+ getSaturation:function () {
+ return this._saturation;
+ },
+ getBrightness:function () {
+ return this._brightness;
+ },
+
+ //not sure if these need to be there actually. I suppose someone might want to access the sprite?
+ getBackground:function () {
+ return this._background;
+ },
+ getOverlay:function () {
+ return this._brightness;
+ },
+ getShadow:function () {
+ return this._shadow;
+ },
+ getSlider:function () {
+ return this._slider;
+ },
+ getStartPos:function () {
+ return this._startPos;
+ },
+
+ initWithTargetAndPos:function (target, pos) {
+ if (cc.Control.prototype.init.call(this)) {
+ // Add background and slider sprites
+ this._background = cc.ControlUtils.addSpriteToTargetWithPosAndAnchor("colourPickerBackground.png", target, pos, cc.p(0.0, 0.0));
+ this._overlay = cc.ControlUtils.addSpriteToTargetWithPosAndAnchor("colourPickerOverlay.png", target, pos, cc.p(0.0, 0.0));
+ this._shadow = cc.ControlUtils.addSpriteToTargetWithPosAndAnchor("colourPickerShadow.png", target, pos, cc.p(0.0, 0.0));
+ this._slider = cc.ControlUtils.addSpriteToTargetWithPosAndAnchor("colourPicker.png", target, pos, cc.p(0.5, 0.5));
+
+ this._startPos = pos; // starting position of the colour picker
+ this._boxPos = 35; // starting position of the virtual box area for picking a colour
+ this._boxSize = this._background.getContentSize().width / 2; // the size (width and height) of the virtual box for picking a colour from
+ return true;
+ } else
+ return false;
+ },
+
+ setEnabled:function (enabled) {
+ cc.Control.prototype.setEnabled.call(this, enabled);
+ if (this._slider) {
+ this._slider.setOpacity(enabled ? 255 : 128);
+ }
+ },
+
+ updateWithHSV:function (hsv) {
+ var hsvTemp = new cc.HSV();
+ hsvTemp.s = 1;
+ hsvTemp.h = hsv.h;
+ hsvTemp.v = 1;
+
+ var rgb = cc.ControlUtils.RGBfromHSV(hsvTemp);
+ this._background.setColor(cc.color(0 | (rgb.r * 255), 0 | (rgb.g * 255), 0 | (rgb.b * 255)));
+ },
+ updateDraggerWithHSV:function (hsv) {
+ // Set the position of the slider to the correct saturation and brightness
+ var pos = cc.p(this._startPos.x + this._boxPos + (this._boxSize * (1 - hsv.s)),
+ this._startPos.y + this._boxPos + (this._boxSize * hsv.v));
+
+ // update
+ this._updateSliderPosition(pos);
+ },
+
+ _updateSliderPosition:function (sliderPosition) {
+ // Clamp the position of the icon within the circle
+
+ // Get the center point of the bkgd image
+ var centerX = this._startPos.x + this._background.getBoundingBox().width * 0.5;
+ var centerY = this._startPos.y + this._background.getBoundingBox().height * 0.5;
+
+ // Work out the distance difference between the location and center
+ var dx = sliderPosition.x - centerX;
+ var dy = sliderPosition.y - centerY;
+ var dist = Math.sqrt(dx * dx + dy * dy);
+
+ // Update angle by using the direction of the location
+ var angle = Math.atan2(dy, dx);
+
+ // Set the limit to the slider movement within the colour picker
+ var limit = this._background.getBoundingBox().width * 0.5;
+
+ // Check distance doesn't exceed the bounds of the circle
+ if (dist > limit) {
+ sliderPosition.x = centerX + limit * Math.cos(angle);
+ sliderPosition.y = centerY + limit * Math.sin(angle);
+ }
+
+ // Set the position of the dragger
+ this._slider.setPosition(sliderPosition);
+
+
+ // Clamp the position within the virtual box for colour selection
+ if (sliderPosition.x < this._startPos.x + this._boxPos)
+ sliderPosition.x = this._startPos.x + this._boxPos;
+ else if (sliderPosition.x > this._startPos.x + this._boxPos + this._boxSize - 1)
+ sliderPosition.x = this._startPos.x + this._boxPos + this._boxSize - 1;
+ if (sliderPosition.y < this._startPos.y + this._boxPos)
+ sliderPosition.y = this._startPos.y + this._boxPos;
+ else if (sliderPosition.y > this._startPos.y + this._boxPos + this._boxSize)
+ sliderPosition.y = this._startPos.y + this._boxPos + this._boxSize;
+
+ // Use the position / slider width to determin the percentage the dragger is at
+ this._saturation = 1.0 - Math.abs((this._startPos.x + this._boxPos - sliderPosition.x) / this._boxSize);
+ this._brightness = Math.abs((this._startPos.y + this._boxPos - sliderPosition.y) / this._boxSize);
+ },
+
+ _checkSliderPosition:function (location) {
+ // Clamp the position of the icon within the circle
+ // get the center point of the bkgd image
+ var centerX = this._startPos.x + this._background.getBoundingBox().width * 0.5;
+ var centerY = this._startPos.y + this._background.getBoundingBox().height * 0.5;
+
+ // work out the distance difference between the location and center
+ var dx = location.x - centerX;
+ var dy = location.y - centerY;
+ var dist = Math.sqrt(dx * dx + dy * dy);
+
+ // check that the touch location is within the bounding rectangle before sending updates
+ if (dist <= this._background.getBoundingBox().width * 0.5) {
+ this._updateSliderPosition(location);
+ this.sendActionsForControlEvents(cc.CONTROL_EVENT_VALUECHANGED);
+ return true;
+ }
+ return false;
+ },
+
+ onTouchBegan:function (touch, event) {
+ if (!this.isEnabled() || !this.isVisible()) {
+ return false;
+ }
+ // Get the touch location
+ var touchLocation = this.getTouchLocation(touch);
+
+ // Check the touch position on the slider
+ return this._checkSliderPosition(touchLocation);
+ },
+
+ onTouchMoved:function (touch, event) {
+ // Get the touch location
+ var touchLocation = this.getTouchLocation(touch);
+
+ //small modification: this allows changing of the colour, even if the touch leaves the bounding area
+ //this._updateSliderPosition(touchLocation);
+ //this.sendActionsForControlEvents(cc.CONTROL_EVENT_VALUECHANGED);
+ // Check the touch position on the slider
+ this._checkSliderPosition(touchLocation);
+ }
+});
+
+var _p = cc.ControlSaturationBrightnessPicker.prototype;
+
+// Extended properties
+/** @expose */
+_p.saturation;
+cc.defineGetterSetter(_p, "saturation", _p.getSaturation);
+/** @expose */
+_p.brightness;
+cc.defineGetterSetter(_p, "brightness", _p.getBrightness);
+/** @expose */
+_p.background;
+cc.defineGetterSetter(_p, "background", _p.getBackground);
+/** @expose */
+_p.overlay;
+cc.defineGetterSetter(_p, "overlay", _p.getOverlay);
+/** @expose */
+_p.shadow;
+cc.defineGetterSetter(_p, "shadow", _p.getShadow);
+/** @expose */
+_p.slider;
+cc.defineGetterSetter(_p, "slider", _p.getSlider);
+/** @expose */
+_p.startPos;
+cc.defineGetterSetter(_p, "startPos", _p.getStartPos);
+
+_p = null;
+
+/**
+ * Creates a cc.ControlSaturationBrightnessPicker
+ * @param {cc.Node} target
+ * @param {cc.Vec2} pos position
+ * @returns {ControlSaturationBrightnessPicker}
+ */
+cc.ControlSaturationBrightnessPicker.create = function (target, pos) {
+ return new cc.ControlSaturationBrightnessPicker(target, pos);
+};
\ No newline at end of file
diff --git a/extensions/gui/control-extension/CCControlSlider.js b/extensions/gui/control-extension/CCControlSlider.js
new file mode 100644
index 0000000000..c9947394a4
--- /dev/null
+++ b/extensions/gui/control-extension/CCControlSlider.js
@@ -0,0 +1,308 @@
+/**
+ *
+ * Copyright (c) 2008-2010 Ricardo Quesada
+ * Copyright (c) 2011-2012 cocos2d-x.org
+ * Copyright (c) 2013-2014 Chukong Technologies Inc.
+ *
+ * Copyright 2011 Yannick Loriot. All rights reserved.
+ * http://yannickloriot.com
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ *
+ * converted to Javascript / cocos2d-x by Angus C
+ */
+
+/**
+ * @ignore
+ */
+cc.SLIDER_MARGIN_H = 24;
+cc.SLIDER_MARGIN_V = 8;
+
+/**
+ * ControlSlider: Slider ui component.
+ * @class
+ * @extends cc.Control
+ *
+ * @property {Number} value - The value of the slider
+ * @property {Number} minValue - The minimum value of the slider
+ * @property {Number} maxValue - The maximum value of the slider
+ * @property {Number} minAllowedValue - The minimum allowed value of the slider
+ * @property {Number} maxAllowedValue - The maximum allowed value of the slider
+ * @property {Number} thumbSprite - <@readonly> Brightness value of the picker
+ * @property {cc.Sprite} progressSprite - <@readonly> The background sprite
+ * @property {cc.Sprite} backgroundSprite - <@readonly> The overlay sprite
+ */
+cc.ControlSlider = cc.Control.extend(/** @lends cc.ControlSlider# */{
+ _value:0,
+ _minimumValue:0,
+ _maximumValue:0,
+ _minimumAllowedValue:0,
+ _maximumAllowedValue:0,
+
+ _thumbSprite:null,
+ _progressSprite:null,
+ _backgroundSprite:null,
+ _className:"ControlSlider",
+
+ ctor:function (bgFile, progressFile, thumbFile) {
+ cc.Control.prototype.ctor.call(this);
+ if (thumbFile != undefined) {
+ // Prepare background for slider
+ var bgSprite = new cc.Sprite(bgFile);
+
+ // Prepare progress for slider
+ var progressSprite = new cc.Sprite(progressFile);
+
+ // Prepare thumb (menuItem) for slider
+ var thumbSprite = new cc.Sprite(thumbFile);
+
+ this.initWithSprites(bgSprite, progressSprite, thumbSprite);
+ }
+ },
+
+ getValue:function () {
+ return this._value;
+ },
+ setValue:function (value) {
+ //clamp between the two bounds
+ value = Math.max(value, this._minimumValue);
+ value = Math.min(value, this._maximumValue);
+ this._value = value;
+ this.needsLayout();
+ this.sendActionsForControlEvents(cc.CONTROL_EVENT_VALUECHANGED);
+ },
+
+ getMinimumValue:function () {
+ return this._minimumValue;
+ },
+ setMinimumValue:function (minimumValue) {
+ this._minimumValue = minimumValue;
+ this._minimumAllowedValue = minimumValue;
+ if (this._minimumValue >= this._maximumValue)
+ this._maximumValue = this._minimumValue + 1.0;
+ this.setValue(this._value);
+ },
+
+ getMaximumValue:function () {
+ return this._maximumValue;
+ },
+ setMaximumValue:function (maximumValue) {
+ this._maximumValue = maximumValue;
+ this._maximumAllowedValue = maximumValue;
+ if (this._maximumValue <= this._minimumValue)
+ this._minimumValue = this._maximumValue - 1.0;
+ this.setValue(this._value);
+ },
+ isTouchInside:function (touch) {
+ var touchLocation = touch.getLocation();
+ touchLocation = this.getParent().convertToNodeSpace(touchLocation);
+
+ var rect = this.getBoundingBox();
+ rect.width += this._thumbSprite.getContentSize().width;
+ rect.x -= this._thumbSprite.getContentSize().width / 2;
+
+ return cc.rectContainsPoint(rect, touchLocation);
+ },
+ locationFromTouch:function (touch) {
+ var touchLocation = touch.getLocation(); // Get the touch position
+ touchLocation = this.convertToNodeSpace(touchLocation); // Convert to the node space of this class
+
+ if (touchLocation.x < 0) {
+ touchLocation.x = 0;
+ } else if (touchLocation.x > this._backgroundSprite.getContentSize().width) {
+ touchLocation.x = this._backgroundSprite.getContentSize().width;
+ }
+
+ return touchLocation;
+ },
+ getMinimumAllowedValue:function () {
+ return this._minimumAllowedValue;
+ },
+ setMinimumAllowedValue:function (val) {
+ this._minimumAllowedValue = val;
+ },
+
+ getMaximumAllowedValue:function () {
+ return this._maximumAllowedValue;
+ },
+
+ setMaximumAllowedValue:function (val) {
+ this._maximumAllowedValue = val;
+ },
+
+ getThumbSprite:function () {
+ return this._thumbSprite;
+ },
+ getProgressSprite:function () {
+ return this._progressSprite;
+ },
+ getBackgroundSprite:function () {
+ return this._backgroundSprite;
+ },
+
+ /**
+ * Initializes a slider with a background sprite, a progress bar and a thumb
+ * item.
+ *
+ * @param {cc.Sprite} backgroundSprite CCSprite, that is used as a background.
+ * @param {cc.Sprite} progressSprite CCSprite, that is used as a progress bar.
+ * @param {cc.Sprite} thumbSprite CCMenuItem, that is used as a thumb.
+ */
+ initWithSprites:function (backgroundSprite, progressSprite, thumbSprite) {
+ if (cc.Control.prototype.init.call(this)) {
+ this.ignoreAnchorPointForPosition(false);
+
+ this._backgroundSprite = backgroundSprite;
+ this._progressSprite = progressSprite;
+ this._thumbSprite = thumbSprite;
+
+ // Defines the content size
+ var maxRect = cc.ControlUtils.CCRectUnion(backgroundSprite.getBoundingBox(), thumbSprite.getBoundingBox());
+ this.setContentSize(maxRect.width, maxRect.height);
+
+ // Add the slider background
+ this._backgroundSprite.setAnchorPoint(0.5, 0.5);
+ this._backgroundSprite.setPosition(maxRect.width / 2, maxRect.height / 2);
+ this.addChild(this._backgroundSprite);
+
+ // Add the progress bar
+ this._progressSprite.setAnchorPoint(0.0, 0.5);
+ this._progressSprite.setPosition(0, maxRect.height / 2);
+ this.addChild(this._progressSprite);
+
+ // Add the slider thumb
+ this._thumbSprite.setPosition(0, maxRect.height / 2);
+ this.addChild(this._thumbSprite);
+
+ // Init default values
+ this._minimumValue = 0.0;
+ this._maximumValue = 1.0;
+ this.setValue(this._minimumValue);
+ return true;
+ } else
+ return false;
+ },
+
+ setEnabled:function (enabled) {
+ cc.Control.prototype.setEnabled.call(this, enabled);
+ if (this._thumbSprite) {
+ this._thumbSprite.setOpacity(enabled ? 255 : 128);
+ }
+ },
+
+ sliderBegan:function (location) {
+ this.setSelected(true);
+ this._thumbSprite.setColor(cc.Color.GRAY);
+ this.setValue(this.valueForLocation(location));
+ },
+ sliderMoved:function (location) {
+ this.setValue(this.valueForLocation(location));
+ },
+ sliderEnded:function (location) {
+ if (this.isSelected()) {
+ this.setValue(this.valueForLocation(this._thumbSprite.getPosition()));
+ }
+ this._thumbSprite.setColor(cc.Color.WHITE);
+ this.setSelected(false);
+ },
+
+ getTouchLocationInControl:function (touch) {
+ var touchLocation = touch.getLocation(); // Get the touch position
+ touchLocation = this.convertToNodeSpace(touchLocation); // Convert to the node space of this class
+
+ if (touchLocation.x < 0) {
+ touchLocation.x = 0;
+ } else if (touchLocation.x > this._backgroundSprite.getContentSize().width + cc.SLIDER_MARGIN_H) {
+ touchLocation.x = this._backgroundSprite.getContentSize().width + cc.SLIDER_MARGIN_H;
+ }
+ return touchLocation;
+ },
+
+ onTouchBegan:function (touch, event) {
+ if (!this.isTouchInside(touch)|| !this.isEnabled() || !this.isVisible())
+ return false;
+
+ var location = this.locationFromTouch(touch);
+ this.sliderBegan(location);
+ return true;
+ },
+ onTouchMoved:function (touch, event) {
+ var location = this.locationFromTouch(touch);
+ this.sliderMoved(location);
+ },
+ onTouchEnded:function (touch, event) {
+ this.sliderEnded(cc.p(0,0));
+ },
+ needsLayout:function(){
+ var percent = (this._value - this._minimumValue) / (this._maximumValue - this._minimumValue);
+ this._thumbSprite.setPositionX(percent * this._backgroundSprite.getContentSize().width);
+
+ // Stretches content proportional to newLevel
+ var textureRect = this._progressSprite.getTextureRect();
+ textureRect = cc.rect(textureRect.x, textureRect.y, this._thumbSprite.getPositionX(), textureRect.height);
+ this._progressSprite.setTextureRect(textureRect, this._progressSprite.isTextureRectRotated());
+ this._thumbSprite._renderCmd.transform(this._renderCmd);
+ },
+ /** Returns the value for the given location. */
+ valueForLocation:function (location) {
+ var percent = location.x / this._backgroundSprite.getContentSize().width;
+ return Math.max(Math.min(this._minimumValue + percent * (this._maximumValue - this._minimumValue), this._maximumAllowedValue), this._minimumAllowedValue);
+ }
+});
+
+var _p = cc.ControlSlider.prototype;
+
+// Extended properties
+/** @expose */
+_p.value;
+cc.defineGetterSetter(_p, "value", _p.getValue, _p.setValue);
+/** @expose */
+_p.minValue;
+cc.defineGetterSetter(_p, "minValue", _p.getMinimumValue, _p.setMinimumValue);
+/** @expose */
+_p.maxValue;
+cc.defineGetterSetter(_p, "maxValue", _p.getMaximumValue, _p.setMaximumValue);
+/** @expose */
+_p.minAllowedValue;
+cc.defineGetterSetter(_p, "minAllowedValue", _p.getMinimumAllowedValue, _p.setMinimumAllowedValue);
+/** @expose */
+_p.maxAllowedValue;
+cc.defineGetterSetter(_p, "maxAllowedValue", _p.getMaximumAllowedValue, _p.setMaximumAllowedValue);
+/** @expose */
+_p.thumbSprite;
+cc.defineGetterSetter(_p, "thumbSprite", _p.getThumbSprite);
+/** @expose */
+_p.progressSprite;
+cc.defineGetterSetter(_p, "progressSprite", _p.getProgressSprite);
+/** @expose */
+_p.backgroundSprite;
+cc.defineGetterSetter(_p, "backgroundSprite", _p.getBackgroundSprite);
+
+_p = null;
+
+/**
+ * Creates a slider with a given background sprite and a progress bar and a
+ * thumb item.
+ * @deprecated
+ * @see cc.ControlSlider
+ */
+cc.ControlSlider.create = function (bgFile, progressFile, thumbFile) {
+ return new cc.ControlSlider(bgFile, progressFile, thumbFile);
+};
\ No newline at end of file
diff --git a/extensions/gui/control-extension/CCControlStepper.js b/extensions/gui/control-extension/CCControlStepper.js
new file mode 100644
index 0000000000..9ddec8e12b
--- /dev/null
+++ b/extensions/gui/control-extension/CCControlStepper.js
@@ -0,0 +1,390 @@
+/**
+ * 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
+ *
+ * Copyright 2012 Yannick Loriot. All rights reserved.
+ * http://yannickloriot.com
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ */
+
+/**
+ * @ignore
+ */
+cc.CONTROL_STEPPER_PARTMINUS = 0;
+cc.CONTROL_STEPPER_PARTPLUS = 1;
+cc.CONTROL_STEPPER_PARTNONE = 2;
+cc.CONTROL_STEPPER_LABELCOLOR_ENABLED = cc.color(55, 55, 55);
+cc.CONTROL_STEPPER_LABELCOLOR_DISABLED = cc.color(147, 147, 147);
+cc.CONTROL_STEPPER_LABELFONT = "CourierNewPSMT";
+cc.AUTOREPEAT_DELTATIME = 0.15;
+cc.AUTOREPEAT_INCREASETIME_INCREMENT = 12;
+
+/**
+ * ControlStepper: Stepper ui component.
+ * @class
+ * @extends cc.Control
+ *
+ * @property {Boolean} wraps - Indicate whether the stepper wraps
+ * @property {Number} value - The value of the stepper control
+ * @property {Number} minValue - The minimum value of the stepper control
+ * @property {Number} maxValue - The maximum value of the stepper control
+ * @property {Number} stepValue - The interval value for each step of the stepper control
+ * @property {Boolean} continuous - <@readonly> Indicate whether the stepper value is continuous
+ * @property {cc.Sprite} minusSprite - The sprite for minus button of the stepper control
+ * @property {cc.Sprite} plusSprite - The sprite for plus button of the stepper control
+ * @property {cc.LabelTTF} minusLabel - The label for minus button of the stepper control
+ * @property {cc.LabelTTF} plusSLabel - The label for plus button of the stepper control
+ */
+cc.ControlStepper = cc.Control.extend(/** @lends cc.ControlStepper# */{
+ _minusSprite:null,
+ _plusSprite:null,
+ _minusLabel:null,
+ _plusLabel:null,
+ _value:0,
+ _continuous:false,
+ _autorepeat:false,
+ _wraps:false,
+ _minimumValue:0,
+ _maximumValue:0,
+ _stepValue:0,
+ _touchInsideFlag:false,
+ _touchedPart:cc.CONTROL_STEPPER_PARTNONE,
+ _autorepeatCount:0,
+ _className:"ControlStepper",
+ ctor:function (minusSprite, plusSprite) {
+ cc.Control.prototype.ctor.call(this);
+ this._minusSprite = null;
+ this._plusSprite = null;
+ this._minusLabel = null;
+ this._plusLabel = null;
+ this._value = 0;
+ this._continuous = false;
+ this._autorepeat = false;
+ this._wraps = false;
+ this._minimumValue = 0;
+ this._maximumValue = 0;
+ this._stepValue = 0;
+ this._touchInsideFlag = false;
+ this._touchedPart = cc.CONTROL_STEPPER_PARTNONE;
+ this._autorepeatCount = 0;
+
+ plusSprite && this.initWithMinusSpriteAndPlusSprite(minusSprite, plusSprite);
+
+ },
+
+ initWithMinusSpriteAndPlusSprite:function (minusSprite, plusSprite) {
+ if(!minusSprite)
+ throw new Error("cc.ControlStepper.initWithMinusSpriteAndPlusSprite(): Minus sprite should be non-null.");
+ if(!plusSprite)
+ throw new Error("cc.ControlStepper.initWithMinusSpriteAndPlusSprite(): Plus sprite should be non-null.");
+
+ if (this.init()) {
+ // Set the default values
+ this._autorepeat = true;
+ this._continuous = true;
+ this._minimumValue = 0;
+ this._maximumValue = 100;
+ this._value = 0;
+ this._stepValue = 1;
+ this._wraps = false;
+ this.ignoreAnchorPointForPosition(false);
+
+ // Add the minus components
+ this.setMinusSprite(minusSprite);
+ this._minusSprite.setPosition(minusSprite.getContentSize().width / 2, minusSprite.getContentSize().height / 2);
+ this.addChild(this._minusSprite);
+
+ this.setMinusLabel(new cc.LabelTTF("-", cc.CONTROL_STEPPER_LABELFONT, 40, cc.size(40, 40), cc.TextAlignment.CENTER, cc.VerticalTextAlignment.CENTER));
+ this._minusLabel.setColor(cc.CONTROL_STEPPER_LABELCOLOR_DISABLED);
+ this._minusLabel.setPosition(this._minusSprite.getContentSize().width / 2, this._minusSprite.getContentSize().height / 2);
+ this._minusSprite.addChild(this._minusLabel);
+
+ // Add the plus components
+ this.setPlusSprite(plusSprite);
+ this._plusSprite.setPosition(minusSprite.getContentSize().width + plusSprite.getContentSize().width / 2,
+ minusSprite.getContentSize().height / 2);
+ this.addChild(this._plusSprite);
+
+ this.setPlusLabel(new cc.LabelTTF("+", cc.CONTROL_STEPPER_LABELFONT, 40, cc.size(40, 40), cc.TextAlignment.CENTER, cc.VerticalTextAlignment.CENTER));
+ this._plusLabel.setColor(cc.CONTROL_STEPPER_LABELCOLOR_ENABLED);
+ this._plusLabel.setPosition(this._plusSprite.getContentSize().width / 2, this._plusSprite.getContentSize().height / 2);
+ this._plusSprite.addChild(this._plusLabel);
+
+ // Defines the content size
+ var maxRect = cc.ControlUtils.CCRectUnion(this._minusSprite.getBoundingBox(), this._plusSprite.getBoundingBox());
+ this.setContentSize(this._minusSprite.getContentSize().width + this._plusSprite.getContentSize().height, maxRect.height);
+ return true;
+ }
+ return false;
+ },
+
+//#pragma mark Properties
+
+ setWraps: function (wraps) {
+ this._wraps = wraps;
+
+ if (this._wraps) {
+ this._minusLabel.setColor(cc.CONTROL_STEPPER_LABELCOLOR_ENABLED);
+ this._plusLabel.setColor(cc.CONTROL_STEPPER_LABELCOLOR_ENABLED);
+ }
+
+ this.setValue(this._value);
+ },
+
+ getWraps: function () {
+ return this._wraps;
+ },
+
+ setMinimumValue:function (minimumValue) {
+ if (minimumValue >= this._maximumValue)
+ throw new Error("cc.ControlStepper.setMinimumValue(): minimumValue should be numerically less than maximumValue.");
+
+ this._minimumValue = minimumValue;
+ this.setValue(this._value);
+ },
+ getMinimumValue: function () {
+ return this._minimumValue;
+ },
+
+ setMaximumValue:function (maximumValue) {
+ if (maximumValue <= this._minimumValue)
+ throw new Error("cc.ControlStepper.setMaximumValue(): maximumValue should be numerically less than maximumValue.");
+
+ this._maximumValue = maximumValue;
+ this.setValue(this._value);
+ },
+ getMaximumValue: function () {
+ return this._maximumValue;
+ },
+
+ setValue:function (value) {
+ this.setValueWithSendingEvent(value, true);
+ },
+
+ getValue:function () {
+ return this._value;
+ },
+
+ setStepValue:function (stepValue) {
+ if (stepValue <= 0)
+ throw new Error("cc.ControlStepper.setMaximumValue(): stepValue should be numerically greater than 0.");
+ this._stepValue = stepValue;
+ },
+
+ getStepValue:function () {
+ return this._stepValue;
+ },
+
+ isContinuous:function () {
+ return this._continuous;
+ },
+
+ setValueWithSendingEvent:function (value, send) {
+ if (value < this._minimumValue) {
+ value = this._wraps ? this._maximumValue : this._minimumValue;
+ } else if (value > this._maximumValue) {
+ value = this._wraps ? this._minimumValue : this._maximumValue;
+ }
+
+ this._value = value;
+
+ if (!this._wraps) {
+ this._minusLabel.setColor((value === this._minimumValue) ? cc.CONTROL_STEPPER_LABELCOLOR_DISABLED : cc.CONTROL_STEPPER_LABELCOLOR_ENABLED);
+ this._plusLabel.setColor((value === this._maximumValue) ? cc.CONTROL_STEPPER_LABELCOLOR_DISABLED : cc.CONTROL_STEPPER_LABELCOLOR_ENABLED);
+ }
+
+ if (send) {
+ this.sendActionsForControlEvents(cc.CONTROL_EVENT_VALUECHANGED);
+ }
+ },
+
+ startAutorepeat:function () {
+ this._autorepeatCount = -1;
+ this.schedule(this.update, cc.AUTOREPEAT_DELTATIME, cc.REPEAT_FOREVER, cc.AUTOREPEAT_DELTATIME * 3);
+ },
+
+ /** Stop the autorepeat. */
+ stopAutorepeat:function () {
+ this.unschedule(this.update);
+ },
+
+ update:function (dt) {
+ this._autorepeatCount++;
+
+ if ((this._autorepeatCount < cc.AUTOREPEAT_INCREASETIME_INCREMENT) && (this._autorepeatCount % 3) !== 0)
+ return;
+
+ if (this._touchedPart === cc.CONTROL_STEPPER_PARTMINUS) {
+ this.setValueWithSendingEvent(this._value - this._stepValue, this._continuous);
+ } else if (this._touchedPart === cc.CONTROL_STEPPER_PARTPLUS) {
+ this.setValueWithSendingEvent(this._value + this._stepValue, this._continuous);
+ }
+ },
+
+//#pragma mark CCControlStepper Private Methods
+
+ updateLayoutUsingTouchLocation:function (location) {
+ if (location.x < this._minusSprite.getContentSize().width
+ && this._value > this._minimumValue) {
+ this._touchedPart = cc.CONTROL_STEPPER_PARTMINUS;
+ this._minusSprite.setColor(cc.Color.GRAY);
+ this._plusSprite.setColor(cc.Color.WHITE);
+
+ } else if (location.x >= this._minusSprite.getContentSize().width
+ && this._value < this._maximumValue) {
+ this._touchedPart = cc.CONTROL_STEPPER_PARTPLUS;
+ this._minusSprite.setColor(cc.Color.WHITE);
+ this._plusSprite.setColor(cc.Color.GRAY);
+
+ } else {
+ this._touchedPart = cc.CONTROL_STEPPER_PARTNONE;
+ this._minusSprite.setColor(cc.Color.WHITE);
+ this._plusSprite.setColor(cc.Color.WHITE);
+ }
+ },
+
+
+ onTouchBegan:function (touch, event) {
+ if (!this.isTouchInside(touch) || !this.isEnabled() || !this.isVisible()) {
+ return false;
+ }
+
+ var location = this.getTouchLocation(touch);
+ this.updateLayoutUsingTouchLocation(location);
+ this._touchInsideFlag = true;
+
+ if (this._autorepeat) {
+ this.startAutorepeat();
+ }
+
+ return true;
+ },
+
+ onTouchMoved:function (touch, event) {
+ if (this.isTouchInside(touch)) {
+ var location = this.getTouchLocation(touch);
+ this.updateLayoutUsingTouchLocation(location);
+
+ if (!this._touchInsideFlag) {
+ this._touchInsideFlag = true;
+
+ if (this._autorepeat) {
+ this.startAutorepeat();
+ }
+ }
+ } else {
+ this._touchInsideFlag = false;
+ this._touchedPart = cc.CONTROL_STEPPER_PARTNONE;
+ this._minusSprite.setColor(cc.Color.WHITE);
+ this._plusSprite.setColor(cc.Color.WHITE);
+ if (this._autorepeat) {
+ this.stopAutorepeat();
+ }
+ }
+ },
+
+ onTouchEnded:function (touch, event) {
+ this._minusSprite.setColor(cc.Color.WHITE);
+ this._plusSprite.setColor(cc.Color.WHITE);
+
+ if (this._autorepeat) {
+ this.stopAutorepeat();
+ }
+
+ if (this.isTouchInside(touch)) {
+ var location = this.getTouchLocation(touch);
+ this.setValue(this._value + ((location.x < this._minusSprite.getContentSize().width) ? (0.0 - this._stepValue) : this._stepValue));
+ }
+ },
+ setMinusSprite:function (sprite) {
+ this._minusSprite = sprite;
+ },
+ getMinusSprite:function () {
+ return this._minusSprite;
+ },
+ setPlusSprite:function (sprite) {
+ this._plusSprite = sprite;
+ },
+ getPlusSprite:function () {
+ return this._plusSprite;
+ },
+ setMinusLabel:function (sprite) {
+ this._minusLabel = sprite;
+ },
+ getMinusLabel:function () {
+ return this._minusLabel;
+ },
+ setPlusLabel:function (sprite) {
+ this._plusLabel = sprite;
+ },
+ getPlusLabel:function () {
+ return this._plusLabel;
+ }
+});
+
+var _p = cc.ControlStepper.prototype;
+
+// Extedned properties
+/** @expose */
+_p.wraps;
+cc.defineGetterSetter(_p, "wraps", _p.getWraps, _p.setWraps);
+/** @expose */
+_p.value;
+cc.defineGetterSetter(_p, "value", _p.getValue, _p.setValue);
+/** @expose */
+_p.minValue;
+cc.defineGetterSetter(_p, "minValue", _p.getMinimumValue, _p.setMinimumValue);
+/** @expose */
+_p.maxValue;
+cc.defineGetterSetter(_p, "maxValue", _p.getMaximumValue, _p.setMaximumValue);
+/** @expose */
+_p.stepValue;
+cc.defineGetterSetter(_p, "stepValue", _p.getStepValue, _p.setStepValue);
+/** @expose */
+_p.continuous;
+cc.defineGetterSetter(_p, "continuous", _p.isContinuous);
+/** @expose */
+_p.minusSprite;
+cc.defineGetterSetter(_p, "minusSprite", _p.getMinusSprite, _p.setMinusSprite);
+/** @expose */
+_p.plusSprite;
+cc.defineGetterSetter(_p, "plusSprite", _p.getPlusSprite, _p.setPlusSprite);
+/** @expose */
+_p.minusLabel;
+cc.defineGetterSetter(_p, "minusLabel", _p.getMinusLabel, _p.setMinusLabel);
+/** @expose */
+_p.plusLabel;
+cc.defineGetterSetter(_p, "plusLabel", _p.getPlusLabel, _p.setPlusLabel);
+
+_p = null;
+
+/**
+ * Creates a cc.ControlStepper
+ * @param {cc.Sprite} minusSprite
+ * @param {cc.Sprite} plusSprite
+ * @returns {ControlStepper}
+ */
+cc.ControlStepper.create = function (minusSprite, plusSprite) {
+ return new cc.ControlStepper(minusSprite, plusSprite);
+};
\ No newline at end of file
diff --git a/extensions/gui/control-extension/CCControlSwitch.js b/extensions/gui/control-extension/CCControlSwitch.js
new file mode 100644
index 0000000000..2bf1f5d296
--- /dev/null
+++ b/extensions/gui/control-extension/CCControlSwitch.js
@@ -0,0 +1,425 @@
+/**
+ *
+ * Copyright (c) 2008-2010 Ricardo Quesada
+ * Copyright (c) 2011-2012 cocos2d-x.org
+ * Copyright (c) 2013-2014 Chukong Technologies Inc.
+ *
+ * Copyright 2011 Yannick Loriot. All rights reserved.
+ * http://yannickloriot.com
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+/**
+ * CCControlSwitch: Switch control ui component
+ * @class
+ * @extends cc.Control
+ */
+cc.ControlSwitch = cc.Control.extend(/** @lends cc.ControlSwitch# */{
+ /** Sprite which represents the view. */
+ _switchSprite:null,
+ _initialTouchXPosition:0,
+
+ _moved:false,
+ /** A Boolean value that determines the off/on state of the switch. */
+ _on:false,
+ _className:"ControlSwitch",
+ ctor:function (maskSprite, onSprite, offSprite, thumbSprite, onLabel, offLabel) {
+ cc.Control.prototype.ctor.call(this);
+
+ offLabel && this.initWithMaskSprite(maskSprite, onSprite, offSprite, thumbSprite, onLabel, offLabel);
+ },
+
+ /** Creates a switch with a mask sprite, on/off sprites for on/off states, a thumb sprite and an on/off labels. */
+ initWithMaskSprite:function (maskSprite, onSprite, offSprite, thumbSprite, onLabel, offLabel) {
+ if(!maskSprite)
+ throw new Error("cc.ControlSwitch.initWithMaskSprite(): maskSprite should be non-null.");
+ if(!onSprite)
+ throw new Error("cc.ControlSwitch.initWithMaskSprite(): onSprite should be non-null.");
+ if(!offSprite)
+ throw new Error("cc.ControlSwitch.initWithMaskSprite(): offSprite should be non-null.");
+ if(!thumbSprite)
+ throw new Error("cc.ControlSwitch.initWithMaskSprite(): thumbSprite should be non-null.");
+ if (this.init()) {
+ this._on = true;
+
+ this._switchSprite = new cc.ControlSwitchSprite();
+ this._switchSprite.initWithMaskSprite(maskSprite, onSprite, offSprite, thumbSprite, onLabel, offLabel);
+ this._switchSprite.setPosition(this._switchSprite.getContentSize().width / 2, this._switchSprite.getContentSize().height / 2);
+ this.addChild(this._switchSprite);
+
+ this.ignoreAnchorPointForPosition(false);
+ this.setAnchorPoint(0.5, 0.5);
+ this.setContentSize(this._switchSprite.getContentSize());
+ return true;
+ }
+ return false;
+ },
+
+ setOn:function (isOn, animated) {
+ animated = animated || false;
+ this._on = isOn;
+ var xPosition = (this._on) ? this._switchSprite.getOnPosition() : this._switchSprite.getOffPosition();
+ if(animated){
+ this._switchSprite.runAction(new cc.ActionTween(0.2, "sliderXPosition", this._switchSprite.getSliderXPosition(),xPosition));
+ }else{
+ this._switchSprite.setSliderXPosition(xPosition);
+ }
+ this.sendActionsForControlEvents(cc.CONTROL_EVENT_VALUECHANGED);
+ },
+
+ isOn:function () {
+ return this._on;
+ },
+
+ hasMoved:function () {
+ return this._moved;
+ },
+
+ setEnabled:function (enabled) {
+ this._enabled = enabled;
+
+ this._switchSprite.setOpacity((enabled) ? 255 : 128);
+ },
+
+ locationFromTouch:function (touch) {
+ var touchLocation = touch.getLocation(); // Get the touch position
+ touchLocation = this.convertToNodeSpace(touchLocation); // Convert to the node space of this class
+
+ return touchLocation;
+ },
+
+ onTouchBegan:function (touch, event) {
+ if (!this.isTouchInside(touch) || !this.isEnabled()|| !this.isVisible()) {
+ return false;
+ }
+
+ this._moved = false;
+
+ var location = this.locationFromTouch(touch);
+
+ this._initialTouchXPosition = location.x - this._switchSprite.getSliderXPosition();
+
+ this._switchSprite.getThumbSprite().setColor(cc.Color.GRAY);
+ this._switchSprite.needsLayout();
+
+ return true;
+ },
+
+ onTouchMoved:function (touch, event) {
+ var location = this.locationFromTouch(touch);
+ location = cc.p(location.x - this._initialTouchXPosition, 0);
+
+ this._moved = true;
+
+ this._switchSprite.setSliderXPosition(location.x);
+ },
+
+ onTouchEnded:function (touch, event) {
+ var location = this.locationFromTouch(touch);
+
+ this._switchSprite.getThumbSprite().setColor(cc.Color.WHITE);
+
+ if (this.hasMoved()) {
+ this.setOn(!(location.x < this._switchSprite.getContentSize().width / 2), true);
+ } else {
+ this.setOn(!this._on, true);
+ }
+ },
+
+ onTouchCancelled:function (touch, event) {
+ var location = this.locationFromTouch(touch);
+
+ this._switchSprite.getThumbSprite().setColor(cc.Color.WHITE);
+
+ if (this.hasMoved()) {
+ this.setOn(!(location.x < this._switchSprite.getContentSize().width / 2), true);
+ } else {
+ this.setOn(!this._on, true);
+ }
+ }
+});
+
+/** Creates a switch with a mask sprite, on/off sprites for on/off states and a thumb sprite.
+ * @deprecated
+ */
+cc.ControlSwitch.create = function (maskSprite, onSprite, offSprite, thumbSprite, onLabel, offLabel) {
+ return new cc.ControlSwitch(maskSprite, onSprite, offSprite, thumbSprite, onLabel, offLabel);
+};
+
+/**
+ * ControlSwitchSprite: Sprite switch control ui component
+ * @class
+ * @extends cc.Sprite
+ *
+ * @property {Number} sliderX - Slider's x position
+ * @property {cc.Vec2} onPos - The position of slider when switch is on
+ * @property {cc.Vec2} offPos - The position of slider when switch is off
+ * @property {cc.Texture2D} maskTexture - The texture of the mask
+ * @property {cc.Vec2} texturePos - The position of the texture
+ * @property {cc.Vec2} maskPos - The position of the mask
+ * @property {cc.Sprite} onSprite - The sprite of switch on
+ * @property {cc.Sprite} offSprite - The sprite of switch off
+ * @property {cc.Sprite} thumbSprite - The thumb sprite of the switch control
+ * @property {cc.LabelTTF} onLabel - The sprite of switch on
+ * @property {cc.LabelTTF} offLabel - The sprite of switch off
+ * @property {Number} onSideWidth - <@readonly> The width of the on side of the switch control
+ * @property {Number} offSideWidth - <@readonly> The width of the off side of the switch control
+ */
+cc.ControlSwitchSprite = cc.Sprite.extend({
+ _sliderXPosition:0,
+ _onPosition:0,
+ _offPosition:0,
+
+ _textureLocation:0,
+ _maskLocation:0,
+ _maskSize:null,
+
+ _onSprite:null,
+ _offSprite:null,
+ _thumbSprite:null,
+ _onLabel:null,
+ _offLabel:null,
+ _clipper:null,
+ _stencil:null,
+ _backRT:null,
+
+ ctor:function () {
+ cc.Sprite.prototype.ctor.call(this);
+ this._sliderXPosition = 0;
+ this._onPosition = 0;
+ this._offPosition = 0;
+ this._maskLocation = 0;
+ this._maskSize = cc.size(0, 0);
+ this._onSprite = null;
+ this._offSprite = null;
+ this._thumbSprite = null;
+ this._onLabel = null;
+ this._offLabel = null;
+ },
+
+ initWithMaskSprite:function (maskSprite, onSprite, offSprite, thumbSprite, onLabel, offLabel) {
+ if (cc.Sprite.prototype.init.call(this)) {
+ this.setSpriteFrame(maskSprite.displayFrame());
+ // Sets the default values
+ this._onPosition = 0;
+ this._offPosition = -onSprite.getContentSize().width + thumbSprite.getContentSize().width / 2;
+ this._sliderXPosition = this._onPosition;
+
+ this.setOnSprite(onSprite);
+ this.setOffSprite(offSprite);
+ this.setThumbSprite(thumbSprite);
+ this.setOnLabel(onLabel);
+ this.setOffLabel(offLabel);
+
+ // Set up the mask with the Mask shader
+ this._stencil = maskSprite;
+ var maskSize = this._maskSize = this._stencil.getContentSize();
+ this._stencil.setPosition(0, 0);
+
+ // Init clipper for mask
+ this._clipper = new cc.ClippingNode();
+ this._clipper.setAnchorPoint(0.5, 0.5);
+ this._clipper.setPosition(maskSize.width / 2, maskSize.height / 2);
+ this._clipper.setStencil(this._stencil);
+ this.addChild(this._clipper);
+
+ this._clipper.addChild(onSprite);
+ this._clipper.addChild(offSprite);
+ this._clipper.addChild(onLabel);
+ this._clipper.addChild(offLabel);
+
+ this.addChild(this._thumbSprite);
+
+ this.needsLayout();
+ return true;
+ }
+ return false;
+ },
+
+ needsLayout:function () {
+ var maskSize = this._maskSize;
+ this._onSprite.setPosition(
+ this._onSprite.getContentSize().width / 2 + this._sliderXPosition - maskSize.width / 2,
+ this._onSprite.getContentSize().height / 2 - maskSize.height / 2
+ );
+ this._offSprite.setPosition(
+ this._onSprite.getContentSize().width + this._offSprite.getContentSize().width / 2 + this._sliderXPosition - maskSize.width / 2,
+ this._offSprite.getContentSize().height / 2 - maskSize.height / 2
+ );
+
+ if (this._onLabel) {
+ this._onLabel.setPosition(
+ this._onSprite.getPositionX() - this._thumbSprite.getContentSize().width / 6,
+ this._onSprite.getContentSize().height / 2 - maskSize.height / 2
+ );
+ }
+ if (this._offLabel) {
+ this._offLabel.setPosition(
+ this._offSprite.getPositionX() + this._thumbSprite.getContentSize().width / 6,
+ this._offSprite.getContentSize().height / 2 - maskSize.height / 2
+ );
+ }
+ this._thumbSprite.setPosition(
+ this._onSprite.getContentSize().width + this._sliderXPosition,
+ this._maskSize.height / 2
+ );
+ },
+
+ setSliderXPosition:function (sliderXPosition) {
+ if (sliderXPosition <= this._offPosition) {
+ // Off
+ sliderXPosition = this._offPosition;
+ } else if (sliderXPosition >= this._onPosition) {
+ // On
+ sliderXPosition = this._onPosition;
+ }
+
+ this._sliderXPosition = sliderXPosition;
+
+ this.needsLayout();
+ },
+ getSliderXPosition:function () {
+ return this._sliderXPosition;
+ },
+
+ _getOnSideWidth:function () {
+ return this._onSprite.getContentSize().width;
+ },
+
+ _getOffSideWidth:function () {
+ return this._offSprite.getContentSize().height;
+ },
+
+ updateTweenAction:function (value, key) {
+ if (key === "sliderXPosition")
+ this.setSliderXPosition(value);
+ },
+
+ setOnPosition:function (onPosition) {
+ this._onPosition = onPosition;
+ },
+ getOnPosition:function () {
+ return this._onPosition;
+ },
+
+ setOffPosition:function (offPosition) {
+ this._offPosition = offPosition;
+ },
+ getOffPosition:function () {
+ return this._offPosition;
+ },
+
+ setMaskTexture:function (maskTexture) {
+ this._stencil.setTexture(maskTexture);
+ },
+ getMaskTexture:function () {
+ return this._stencil.getTexture();
+ },
+
+ setTextureLocation:function (textureLocation) {
+ this._textureLocation = textureLocation;
+ },
+ getTextureLocation:function () {
+ return this._textureLocation;
+ },
+
+ setMaskLocation:function (maskLocation) {
+ this._maskLocation = maskLocation;
+ },
+ getMaskLocation:function () {
+ return this._maskLocation;
+ },
+
+ setOnSprite:function (onSprite) {
+ this._onSprite = onSprite;
+ },
+ getOnSprite:function () {
+ return this._onSprite;
+ },
+
+ setOffSprite:function (offSprite) {
+ this._offSprite = offSprite;
+ },
+ getOffSprite:function () {
+ return this._offSprite;
+ },
+
+ setThumbSprite:function (thumbSprite) {
+ this._thumbSprite = thumbSprite;
+ },
+ getThumbSprite:function () {
+ return this._thumbSprite;
+ },
+
+ setOnLabel:function (onLabel) {
+ this._onLabel = onLabel;
+ },
+ getOnLabel:function () {
+ return this._onLabel;
+ },
+
+ setOffLabel:function (offLabel) {
+ this._offLabel = offLabel;
+ },
+ getOffLabel:function () {
+ return this._offLabel;
+ }
+});
+
+var _p = cc.ControlSwitchSprite.prototype;
+
+/** @expose */
+_p.sliderX;
+cc.defineGetterSetter(_p, "sliderX", _p.getSliderXPosition, _p.setSliderXPosition);
+/** @expose */
+_p.onPos;
+cc.defineGetterSetter(_p, "onPos", _p.getOnPosition, _p.setOnPosition);
+/** @expose */
+_p.offPos;
+cc.defineGetterSetter(_p, "offPos", _p.getOffPosition, _p.setOffPosition);
+/** @expose */
+_p.maskTexture;
+cc.defineGetterSetter(_p, "maskTexture", _p.getMaskTexture, _p.setMaskTexture);
+/** @expose */
+_p.maskPos;
+cc.defineGetterSetter(_p, "maskPos", _p.getMaskLocation, _p.setMaskLocation);
+/** @expose */
+_p.onSprite;
+cc.defineGetterSetter(_p, "onSprite", _p.getOnSprite, _p.setOnSprite);
+/** @expose */
+_p.offSprite;
+cc.defineGetterSetter(_p, "offSprite", _p.getOffSprite, _p.setOffSprite);
+/** @expose */
+_p.thumbSprite;
+cc.defineGetterSetter(_p, "thumbSprite", _p.getThumbSprite, _p.setThumbSprite);
+/** @expose */
+_p.onLabel;
+cc.defineGetterSetter(_p, "onLabel", _p.getOnLabel, _p.setOnLabel);
+/** @expose */
+_p.offLabel;
+cc.defineGetterSetter(_p, "offLabel", _p.getOffLabel, _p.setOffLabel);
+/** @expose */
+_p.onSideWidth;
+cc.defineGetterSetter(_p, "onSideWidth", _p._getOnSideWidth);
+/** @expose */
+_p.offSideWidth;
+cc.defineGetterSetter(_p, "offSideWidth", _p._getOffSideWidth);
+
+_p = null;
diff --git a/extensions/gui/control-extension/CCControlUtils.js b/extensions/gui/control-extension/CCControlUtils.js
new file mode 100644
index 0000000000..5e803bd56a
--- /dev/null
+++ b/extensions/gui/control-extension/CCControlUtils.js
@@ -0,0 +1,177 @@
+/****************************************************************************
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ Copyright 2012 Stewart Hamilton-Arrandale.
+ http://creativewax.co.uk
+
+ Modified by Yannick Loriot.
+ http://yannickloriot.com
+
+ 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.
+ ****************************************************************************/
+
+/**
+ * An RGBA color class, its value present as percent
+ * @param {Number} r
+ * @param {Number} g
+ * @param {Number} b
+ * @param {Number} a
+ * @constructor
+ */
+cc.RGBA = function(r,g,b,a){
+ this.r = r ; // percent
+ this.g = g ; // percent
+ this.b = b ; // percent
+ this.a = a ; // percent
+};
+
+cc.HSV = function(h,s,v){
+ this.h = h ; // angle in degrees
+ this.s = s ; // percent
+ this.v = v ; // percent
+};
+
+cc.ControlUtils = {};
+
+cc.ControlUtils.addSpriteToTargetWithPosAndAnchor = function(spriteName,target,pos,anchor){
+ var sprite = new cc.Sprite("#" + spriteName);
+
+ if (!sprite)
+ return null;
+
+ sprite.setPosition(pos);
+ sprite.setAnchorPoint(anchor);
+ target.addChild(sprite);
+ return sprite;
+};
+
+cc.ControlUtils.HSVfromRGB = function(rgbaValue){
+ var out = new cc.HSV();
+ var min, max, delta;
+
+ min = rgbaValue.r < rgbaValue.g ? rgbaValue.r : rgbaValue.g;
+ min = min < rgbaValue.b ? min : rgbaValue.b;
+
+ max = rgbaValue.r > rgbaValue.g ? rgbaValue.r : rgbaValue.g;
+ max = max > rgbaValue.b ? max : rgbaValue.b;
+
+ out.v = max; // v
+ delta = max - min;
+ if( max > 0.0 ){
+ out.s = (delta / max); // s
+ } else {
+ // r = g = b = 0 // s = 0, v is undefined
+ out.s = 0.0;
+ out.h = -1; // its now undefined (don't know if setting to NAN is a good idea)
+ return out;
+ }
+
+ if( rgbaValue.r >= max ){ // > is bogus, just keeps compilor happy
+ out.h = ( rgbaValue.g - rgbaValue.b ) / delta; // between yellow & magenta
+ } else {
+ if( rgbaValue.g >= max )
+ out.h = 2.0 + ( rgbaValue.b - rgbaValue.r ) / delta; // between cyan & yellow
+ else
+ out.h = 4.0 + ( rgbaValue.r - rgbaValue.g ) / delta; // between magenta & cyan
+ }
+
+ out.h *= 60.0; // degrees
+
+ if( out.h < 0.0 )
+ out.h += 360.0;
+
+ return out;
+};
+
+cc.ControlUtils.RGBfromHSV = function(hsvValue){
+ var hh, p, q, t, ff;
+ var i;
+ var out = new cc.RGBA();
+ out.a = 1;
+
+ if (hsvValue.s <= 0.0){ // < is bogus, just shuts up warnings
+
+ if (!hsvValue.h){ // value.h == NAN
+ out.r = hsvValue.v;
+ out.g = hsvValue.v;
+ out.b = hsvValue.v;
+ return out;
+ }
+
+ // error - should never happen
+ out.r = 0.0;
+ out.g = 0.0;
+ out.b = 0.0;
+ return out;
+ }
+
+ hh = hsvValue.h;
+ if(hh >= 360.0)
+ hh = 0.0;
+ hh /= 60.0;
+
+ i = 0 | hh;
+ ff = hh - i;
+ p = hsvValue.v * (1.0 - hsvValue.s);
+ q = hsvValue.v * (1.0 - (hsvValue.s * ff));
+ t = hsvValue.v * (1.0 - (hsvValue.s * (1.0 - ff)));
+
+ switch(i) {
+ case 0:
+ out.r = hsvValue.v;
+ out.g = t;
+ out.b = p;
+ break;
+ case 1:
+ out.r = q;
+ out.g = hsvValue.v;
+ out.b = p;
+ break;
+ case 2:
+ out.r = p;
+ out.g = hsvValue.v;
+ out.b = t;
+ break;
+
+ case 3:
+ out.r = p;
+ out.g = q;
+ out.b = hsvValue.v;
+ break;
+ case 4:
+ out.r = t;
+ out.g = p;
+ out.b = hsvValue.v;
+ break;
+ default:
+ out.r = hsvValue.v;
+ out.g = p;
+ out.b = q;
+ break;
+ }
+ return out;
+};
+
+cc.ControlUtils.CCRectUnion = function(rect1, rect2){
+ return cc.rectUnion(rect1,rect2);
+};
\ No newline at end of file
diff --git a/extensions/gui/control-extension/CCInvocation.js b/extensions/gui/control-extension/CCInvocation.js
new file mode 100644
index 0000000000..2a5d477b87
--- /dev/null
+++ b/extensions/gui/control-extension/CCInvocation.js
@@ -0,0 +1,65 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+/**
+ * An Invocation class
+ * @class
+ * @extends cc._Class
+ */
+cc.Invocation = cc._Class.extend(/** @lends cc.Invocation# */{
+ _action:null,
+ _target:null,
+ _controlEvent:null,
+
+ ctor:function(target,action,controlEvent){
+ this._target=target;
+ this._action=action;
+ this._controlEvent=controlEvent;
+ },
+
+ getAction:function(){
+ return this._action;
+ },
+
+ getTarget:function(){
+ return this._target ;
+ },
+
+ getControlEvent:function(){
+ return this._controlEvent;
+ },
+
+ invoke:function(sender){
+ if (this._target && this._action) {
+ if (cc.js.isString(this._action)) {
+ this._target[this._action](sender, this._controlEvent);
+ } else{
+ this._action.call(this._target, sender, this._controlEvent);
+ }
+ }
+ }
+});
+
diff --git a/extensions/gui/control-extension/CCMenuPassive.js b/extensions/gui/control-extension/CCMenuPassive.js
new file mode 100644
index 0000000000..82a3fd32fe
--- /dev/null
+++ b/extensions/gui/control-extension/CCMenuPassive.js
@@ -0,0 +1,415 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+/**
+ * The Spacer class
+ * @class
+ * @extends cc.Layer
+ */
+cc.Spacer = cc.Layer.extend(/** @lends cc.Spacer */{});
+
+cc.Spacer.verticalSpacer = function (space) {
+ var pRet = new cc.Spacer();
+ pRet.init();
+ pRet.setContentSize(0, space);
+ return pRet;
+};
+
+cc.Spacer.horizontalSpacer = function (space) {
+ var pRet = new cc.Spacer();
+ pRet.init();
+ pRet.setContentSize(space, 0);
+ return pRet;
+};
+
+/**
+ * MenuPassive: The menu passive ui component
+ * @class
+ * @extends cc.Layer
+ */
+cc.MenuPassive = cc.Layer.extend(/** @lends cc.MenuPassive# */{
+
+ _color:null,
+ _opacity:0,
+ _className:"MenuPassive",
+
+ ctor:function () {
+ },
+
+ /** Color: conforms with CCRGBAProtocol protocol */
+ getColor:function () {
+ var locColor = this._color;
+ return cc.color(locColor.r, locColor.g, locColor.b, locColor.a);
+ },
+ setColor:function (color) {
+ var locColor = this._color;
+ locColor.r = color.r;
+ locColor.g = color.g;
+ locColor.b = color.b;
+
+ if (this._children && this._children.length > 0) {
+ for (var i = 0; i < this._children.length; i++) {
+ if (this._children[i]) {
+ this._children[i].setColor(color);
+ }
+ }
+ }
+ if (color.a !== undefined && !color.a_undefined) {
+ this.setOpacity(color.a);
+ }
+ },
+
+ /** Opacity: conforms with CCRGBAProtocol protocol */
+ getOpacity:function () {
+ return this._opacity;
+ },
+
+ setOpacity:function (opacity) {
+ this._opacity = opacity;
+
+ if (this._children && this._children.length > 0) {
+ for (var i = 0; i < this._children.length; i++) {
+ if (this._children[i]) {
+ this._children[i].setOpacity(opacity);
+ }
+ }
+ }
+
+ this._color.a = opacity;
+ },
+
+ /** initializes a CCMenu with it's items */
+ initWithItems:function (item, args) {
+ if (this.init()) {
+ //this.m_bIsTouchEnabled = false;
+
+ // menu in the center of the screen
+ var winSize = cc.director.getWinSize();
+
+ // Set the default anchor point
+ this.ignoreAnchorPointForPosition(true);
+ this.setAnchorPoint(0.5, 0.5);
+ this.setContentSize(winSize);
+
+ this.setPosition(winSize.width / 2, winSize.height / 2);
+ var z = 0;
+
+ if (item) {
+ this.addChild(item, z);
+ for (var i = 0; i < args.length; i++) {
+ if (args[i]) {
+ z++;
+ this.addChild(args[i], z);
+ }
+ }
+ }
+ return true;
+ }
+ return false;
+ },
+
+ /** align items vertically */
+ alignItemsVertically:function () {
+ this.alignItemsVerticallyWithPadding(cc.DEFAULT_PADDING);
+ },
+
+ /** align items vertically with padding
+ @since v0.7.2
+ */
+ alignItemsVerticallyWithPadding:function (padding) {
+ var height = -padding;
+
+ var i;
+ if (this._children && this._children.length > 0) {
+ for (i = 0; i < this._children.length; i++) {
+ if (this._children[i]) {
+ height += this._children[i].getContentSize().height * this._children[i].getScaleY() + padding;
+ }
+ }
+ }
+
+ var width = 0;
+ var y = height / 2.0;
+ if (this._children && this._children.length > 0) {
+ for (i = 0; i < this._children.length; i++) {
+ if (this._children[i]) {
+ width = Math.max(width, this._children[i].getContentSize().width);
+ this._children[i].setPosition(0, y - this._children[i].getContentSize().height * this._children[i].getScaleY() / 2.0);
+ y -= this._children[i].getContentSize().height * this._children[i].getScaleY() + padding;
+ }
+ }
+ }
+ this.setContentSize(width, height);
+ },
+
+ /** align items horizontally */
+ alignItemsHorizontally:function () {
+ this.alignItemsHorizontallyWithPadding(cc.DEFAULT_PADDING);
+ },
+
+ /** align items horizontally with padding
+ @since v0.7.2
+ */
+ alignItemsHorizontallyWithPadding:function (padding) {
+ var width = -padding;
+ var i;
+ if (this._children && this._children.length > 0) {
+ for (i = 0; i < this._children.length; i++) {
+ if (this._children[i]) {
+ width += this._children[i].getContentSize().width * this._children[i].getScaleX() + padding;
+ }
+ }
+ }
+
+ var height = 0;
+ var x = -width / 2.0;
+ if (this._children && this._children.length > 0) {
+ for (i = 0; i < this._children.length; i++) {
+ if (this._children[i]) {
+ height = Math.max(height, this._children[i].getContentSize().height);
+ this._children[i].setPosition(x + this._children[i].getContentSize().width * this._children[i].getScaleX() / 2.0, 0);
+ x += this._children[i].getContentSize().width * this._children[i].getScaleX() + padding;
+ }
+ }
+ }
+ this.setContentSize(width, height);
+ },
+
+ /** align items in rows of columns */
+ alignItemsInColumns:function (columns) {
+ var rows = [];
+ var i;
+ for (i = 1; i < arguments.length; i++) {
+ rows.push(arguments[i]);
+ }
+
+ var height = -5;
+ var row = 0;
+ var rowHeight = 0;
+ var columnsOccupied = 0;
+ var rowColumns;
+
+ var tmp;
+ if (this._children && this._children.length > 0) {
+ for (i = 0; i < this._children.length; i++) {
+ if (this._children[i]) {
+ if(row >= rows.length){
+ cc.log("cc.MenuPassive.alignItemsInColumns(): invalid row index");
+ continue;
+ }
+
+ rowColumns = rows[row];
+ // can not have zero columns on a row
+ if(!rowColumns) {
+ cc.log("cc.MenuPassive.alignItemsInColumns(): can not have zero columns on a row");
+ continue;
+ }
+
+ tmp = this._children[i].getContentSize().height;
+ rowHeight = 0 | ((rowHeight >= tmp || (tmp == null)) ? rowHeight : tmp);
+
+ ++columnsOccupied;
+ if (columnsOccupied >= rowColumns) {
+ height += rowHeight + 5;
+
+ columnsOccupied = 0;
+ rowHeight = 0;
+ ++row;
+ }
+ }
+ }
+ }
+
+ // check if too many rows/columns for available menu items
+ //cc.assert(!columnsOccupied, ""); //?
+
+ var winSize = cc.director.getWinSize();
+
+ row = 0;
+ rowHeight = 0;
+ rowColumns = 0;
+ var w = 0.0;
+ var x = 0.0;
+ var y = (height / 2);
+ if (this._children && this._children.length > 0) {
+ for (i = 0; i < this._children.length; i++) {
+ if (this._children[i]) {
+ if (rowColumns === 0) {
+ rowColumns = rows[row];
+ w = winSize.width / (1 + rowColumns);
+ x = w;
+ }
+
+ tmp = this._children[i].getContentSize().height;
+ rowHeight = 0 | ((rowHeight >= tmp || (tmp == null)) ? rowHeight : tmp);
+
+ this._children[i].setPosition(x - winSize.width / 2,
+ y - this._children[i].getContentSize().height / 2);
+
+ x += w;
+ ++columnsOccupied;
+
+ if (columnsOccupied >= rowColumns) {
+ y -= rowHeight + 5;
+
+ columnsOccupied = 0;
+ rowColumns = 0;
+ rowHeight = 0;
+ ++row;
+ }
+ }
+ }
+ }
+ },
+
+ /** align items in columns of rows */
+ alignItemsInRows:function (rows) {
+ var columns = [];
+ var i;
+ for (i = 1; i < arguments.length; i++) {
+ columns.push(arguments[i]);
+ }
+
+ var columnWidths = [];
+ var columnHeights = [];
+
+ var width = -10;
+ var columnHeight = -5;
+ var column = 0;
+ var columnWidth = 0;
+ var rowsOccupied = 0;
+ var columnRows;
+
+ var tmp;
+ if (this._children && this._children.length > 0) {
+ for (i = 0; i < this._children.length; i++) {
+ if (this._children[i]) {
+ // check if too many menu items for the amount of rows/columns
+ if(column >= columns.length){
+ cc.log("cc.MenuPassive.alignItemsInRows(): invalid row index");
+ continue;
+ }
+
+ columnRows = columns[column];
+ // can't have zero rows on a column
+ if(!columnRows) {
+ cc.log("cc.MenuPassive.alignItemsInColumns(): can't have zero rows on a column");
+ continue;
+ }
+
+ // columnWidth = fmaxf(columnWidth, [item contentSize].width);
+ tmp = this._children[i].getContentSize().width;
+ columnWidth = 0 | ((columnWidth >= tmp || (tmp == null)) ? columnWidth : tmp);
+
+ columnHeight += 0 | (this._children[i].getContentSize().height + 5);
+ ++rowsOccupied;
+
+ if (rowsOccupied >= columnRows) {
+ columnWidths.push(columnWidth);
+ columnHeights.push(columnHeight);
+ width += columnWidth + 10;
+
+ rowsOccupied = 0;
+ columnWidth = 0;
+ columnHeight = -5;
+ ++column;
+ }
+ }
+ }
+ }
+
+ // check if too many rows/columns for available menu items.
+ //cc.assert(!rowsOccupied, ""); //?
+
+ var winSize = cc.director.getWinSize();
+
+ column = 0;
+ columnWidth = 0;
+ columnRows = null;
+ var x = (-width / 2);
+ var y = 0.0;
+ if (this._children && this._children.length > 0) {
+ for (i = 0; i < this._children.length; i++) {
+ if (this._children[i]) {
+ if (columnRows == null) {
+ columnRows = columns[column];
+ y = columnHeights[column];
+ }
+
+ // columnWidth = fmaxf(columnWidth, [item contentSize].width);
+ tmp = this._children[i].getContentSize().width;
+ columnWidth = 0 | ((columnWidth >= tmp || (tmp == null)) ? columnWidth : tmp);
+
+ this._children[i].setPosition(x + columnWidths[column] / 2, y - winSize.height / 2);
+
+ y -= this._children[i].getContentSize().height + 10;
+ ++rowsOccupied;
+
+ if (rowsOccupied >= columnRows) {
+ x += columnWidth + 5;
+ rowsOccupied = 0;
+ columnRows = 0;
+ columnWidth = 0;
+ ++column;
+ }
+ }
+ }
+ }
+ },
+
+ //RGBA protocol
+ setOpacityModifyRGB:function (bValue) {
+ },
+ isOpacityModifyRGB:function () {
+ return false;
+ }
+});
+
+/** creates an empty CCMenu */
+cc.MenuPassive.create = function (item) {
+ if (!item) {
+ item = null;
+ }
+
+ var argArr = [];
+ for (var i = 1; i < arguments.length; i++) {
+ argArr.push(arguments[i]);
+ }
+
+ var pRet = new cc.MenuPassive();
+ if (pRet && pRet.initWithItems(item, argArr)) {
+ return pRet;
+ }
+ return null;
+};
+
+/** creates a CCMenu with it's item, then use addChild() to add
+ * other items. It is used for script, it can't init with undetermined
+ * number of variables.
+ */
+cc.MenuPassive.createWithItem = function (item) {
+ return cc.MenuPassive.create(item, null);
+};
\ No newline at end of file
diff --git a/extensions/gui/scrollview/CCScrollView.js b/extensions/gui/scrollview/CCScrollView.js
new file mode 100644
index 0000000000..9326a43643
--- /dev/null
+++ b/extensions/gui/scrollview/CCScrollView.js
@@ -0,0 +1,826 @@
+/****************************************************************************
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2010 Sangwoo Im
+
+ 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.
+ ****************************************************************************/
+
+/**
+ * @ignore
+ */
+cc.SCROLLVIEW_DIRECTION_NONE = -1;
+
+cc.SCROLLVIEW_DIRECTION_HORIZONTAL = 0;
+
+cc.SCROLLVIEW_DIRECTION_VERTICAL = 1;
+
+cc.SCROLLVIEW_DIRECTION_BOTH = 2;
+
+var SCROLL_DEACCEL_RATE = 0.95;
+var SCROLL_DEACCEL_DIST = 1.0;
+var BOUNCE_DURATION = 0.15;
+var INSET_RATIO = 0.2;
+var MOVE_INCH = 7.0/160.0;
+var BOUNCE_BACK_FACTOR = 0.35;
+
+cc.convertDistanceFromPointToInch = function(pointDis){
+ var eglViewer = cc.view;
+ var factor = (eglViewer.getScaleX() + eglViewer.getScaleY())/2;
+ return (pointDis * factor) / 160; // CCDevice::getDPI() default value
+};
+
+cc.ScrollViewDelegate = cc._Class.extend({
+ scrollViewDidScroll:function (view) {
+ },
+ scrollViewDidZoom:function (view) {
+ }
+});
+
+/**
+ * ScrollView support for cocos2d -x.
+ * It provides scroll view functionalities to cocos2d projects natively.
+ * @class
+ * @extends cc.Layer
+ *
+ * @property {cc.Vec2} minOffset - <@readonly> The current container's minimum offset
+ * @property {cc.Vec2} maxOffset - <@readonly> The current container's maximum offset
+ * @property {Boolean} bounceable - Indicate whether the scroll view is bounceable
+ * @property {cc.Size} viewSize - The size of the scroll view
+ * @property {cc.Layer} container - The inside container of the scroll view
+ * @property {Number} direction - The direction allowed to scroll: cc.SCROLLVIEW_DIRECTION_BOTH by default, or cc.SCROLLVIEW_DIRECTION_NONE | cc.SCROLLVIEW_DIRECTION_HORIZONTAL | cc.SCROLLVIEW_DIRECTION_VERTICAL
+ * @property {cc.ScrollViewDelegate} delegate - The inside container of the scroll view
+ * @property {Boolean} clippingToBounds - Indicate whether the scroll view clips its children
+ */
+cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
+ _zoomScale:0,
+ _minZoomScale:0,
+ _maxZoomScale:0,
+ _delegate:null,
+ _direction:cc.SCROLLVIEW_DIRECTION_BOTH,
+ _dragging:false,
+ _contentOffset:null,
+ _container:null,
+ _touchMoved:false,
+ _maxInset:null,
+ _minInset:null,
+ _bounceable:false,
+ _clippingToBounds:false,
+ _scrollDistance:null,
+ _touchPoint:null,
+ _touchLength:0,
+ _touches:null,
+ _viewSize:null,
+ _minScale:0,
+ _maxScale:0,
+
+ //scissor rect for parent, just for restoring GL_SCISSOR_BOX
+ _parentScissorRect:null,
+ _scissorRestored:false,
+
+ // cache object
+ _tmpViewRect:null,
+ _touchListener: null,
+ _className:"ScrollView",
+
+ /**
+ * @contructor
+ * @param size
+ * @param container
+ * @returns {ScrollView}
+ */
+ ctor:function (size, container) {
+ cc.Layer.prototype.ctor.call(this);
+ this._contentOffset = cc.p(0,0);
+ this._maxInset = cc.p(0, 0);
+ this._minInset = cc.p(0, 0);
+ this._scrollDistance = cc.p(0, 0);
+ this._touchPoint = cc.p(0, 0);
+ this._touches = [];
+ this._viewSize = cc.size(0, 0);
+ this._parentScissorRect = new cc.Rect(0,0,0,0);
+ this._tmpViewRect = new cc.Rect(0,0,0,0);
+
+ if(container != undefined)
+ this.initWithViewSize(size, container);
+ else
+ this.initWithViewSize(cc.size(200, 200), null);
+
+ },
+
+ init:function () {
+ return this.initWithViewSize(cc.size(200, 200), null);
+ },
+
+ /**
+ * initialized whether success or fail
+ * @param {cc.Size} size
+ * @param {cc.Node} container
+ * @return {Boolean}
+ */
+ initWithViewSize:function (size, container) {
+ var pZero = cc.p(0,0);
+ if (cc.Layer.prototype.init.call(this)) {
+ if (!container && !this._container) {
+ container = new cc.Layer();
+ }
+ if (container) {
+ this.setContainer(container);
+ }
+ this.setViewSize(size);
+
+ this.setTouchEnabled(true);
+ this._touches.length = 0;
+ this._delegate = null;
+ this._bounceable = true;
+ this._clippingToBounds = true;
+
+ //this._container.setContentSize(CCSizeZero);
+ this._direction = cc.SCROLLVIEW_DIRECTION_BOTH;
+ this._container.setPosition(pZero);
+ this._touchLength = 0.0;
+
+ this._minScale = this._maxScale = 1.0;
+ return true;
+ }
+ return false;
+ },
+
+ /**
+ * Sets a new content offset. It ignores max/min offset. It just sets what's given. (just like UIKit's UIScrollView)
+ *
+ * @param {cc.Vec2} offset new offset
+ * @param {Number} [animated=] If true, the view will scroll to the new offset
+ */
+ setContentOffset: function (offset, animated) {
+ if (animated) { //animate scrolling
+ this.setContentOffsetInDuration(offset, BOUNCE_DURATION);
+ return;
+ }
+ if (!this._bounceable) {
+ var minOffset = this.minContainerOffset();
+ var maxOffset = this.maxContainerOffset();
+
+ offset.x = Math.max(minOffset.x, Math.min(maxOffset.x, offset.x));
+ offset.y = Math.max(minOffset.y, Math.min(maxOffset.y, offset.y));
+ }
+
+ this._container.setPosition(offset);
+ var locDelegate = this._delegate;
+ if (locDelegate != null && locDelegate.scrollViewDidScroll) {
+ locDelegate.scrollViewDidScroll(this);
+ }
+
+ },
+
+ getContentOffset:function () {
+ var locPos = this._container.getPosition();
+ return cc.p(locPos.x, locPos.y);
+ },
+
+ /**
+ * Sets a new content offset. It ignores max/min offset. It just sets what's given. (just like UIKit's UIScrollView)
+ * You can override the animation duration with this method.
+ *
+ * @param {cc.Vec2} offset new offset
+ * @param {Number} dt animation duration
+ */
+ setContentOffsetInDuration:function (offset, dt) {
+ var scroll = cc.moveTo(dt, offset);
+ var expire = cc.callFunc(this._stoppedAnimatedScroll, this);
+ this._container.runAction(cc.sequence(scroll, expire));
+ this.schedule(this._performedAnimatedScroll);
+ },
+
+ /**
+ * Sets a new scale and does that for a predefined duration.
+ *
+ * @param {Number} scale a new scale vale
+ * @param {Boolean} [animated=null] if YES, scaling is animated
+ */
+ setZoomScale: function (scale, animated) {
+ if (animated) {
+ this.setZoomScaleInDuration(scale, BOUNCE_DURATION);
+ return;
+ }
+
+ var locContainer = this._container;
+ if (locContainer.getScale() !== scale) {
+ var oldCenter, newCenter;
+ var center;
+
+ if (this._touchLength === 0.0) {
+ var locViewSize = this._viewSize;
+ center = cc.p(locViewSize.width * 0.5, locViewSize.height * 0.5);
+ center = this.convertToWorldSpace(center);
+ } else
+ center = this._touchPoint;
+
+ oldCenter = locContainer.convertToNodeSpace(center);
+ locContainer.setScale(Math.max(this._minScale, Math.min(this._maxScale, scale)));
+ newCenter = locContainer.convertToWorldSpace(oldCenter);
+
+ var offset = cc.pSub(center, newCenter);
+ if (this._delegate && this._delegate.scrollViewDidZoom)
+ this._delegate.scrollViewDidZoom(this);
+ this.setContentOffset(cc.pAdd(locContainer.getPosition(), offset));
+ }
+ },
+
+ getZoomScale:function () {
+ return this._container.getScale();
+ },
+
+ /**
+ * Sets a new scale for container in a given duration.
+ *
+ * @param {Number} s a new scale value
+ * @param {Number} dt animation duration
+ */
+ setZoomScaleInDuration:function (s, dt) {
+ if (dt > 0) {
+ var locScale = this._container.getScale();
+ if (locScale !== s) {
+ var scaleAction = cc.actionTween(dt, "zoomScale", locScale, s);
+ this.runAction(scaleAction);
+ }
+ } else {
+ this.setZoomScale(s);
+ }
+ },
+
+ /**
+ * Returns the current container's minimum offset. You may want this while you animate scrolling by yourself
+ * @return {cc.Vec2} Returns the current container's minimum offset.
+ */
+ minContainerOffset:function () {
+ var locContainer = this._container;
+ var locContentSize = locContainer.getContentSize(), locViewSize = this._viewSize;
+ return cc.p(locViewSize.width - locContentSize.width * locContainer.getScaleX(),
+ locViewSize.height - locContentSize.height * locContainer.getScaleY());
+ },
+
+ /**
+ * Returns the current container's maximum offset. You may want this while you animate scrolling by yourself
+ * @return {cc.Vec2} Returns the current container's maximum offset.
+ */
+ maxContainerOffset:function () {
+ return cc.p(0.0, 0.0);
+ },
+
+ /**
+ * Determines if a given node's bounding box is in visible bounds
+ * @param {cc.Node} node
+ * @return {Boolean} YES if it is in visible bounds
+ */
+ isNodeVisible:function (node) {
+ var offset = this.getContentOffset();
+ var size = this.getViewSize();
+ var scale = this.getZoomScale();
+
+ var viewRect = cc.rect(-offset.x / scale, -offset.y / scale, size.width / scale, size.height / scale);
+
+ return cc.rectIntersectsRect(viewRect, node.getBoundingBox());
+ },
+
+ /**
+ * Provided to make scroll view compatible with SWLayer's pause method
+ */
+ pause:function (sender) {
+ this._container.pause();
+ var selChildren = this._container.getChildren();
+ for (var i = 0; i < selChildren.length; i++) {
+ selChildren[i].pause();
+ }
+ this._super();
+ },
+
+ /**
+ * Provided to make scroll view compatible with SWLayer's resume method
+ */
+ resume:function (sender) {
+ var selChildren = this._container.getChildren();
+ for (var i = 0, len = selChildren.length; i < len; i++) {
+ selChildren[i].resume();
+ }
+ this._container.resume();
+ this._super();
+ },
+
+ isDragging:function () {
+ return this._dragging;
+ },
+ isTouchMoved:function () {
+ return this._touchMoved;
+ },
+ isBounceable:function () {
+ return this._bounceable;
+ },
+ setBounceable:function (bounceable) {
+ this._bounceable = bounceable;
+ },
+
+ /**
+ *
+ * size to clip. CCNode boundingBox uses contentSize directly.
+ * It's semantically different what it actually means to common scroll views.
+ * Hence, this scroll view will use a separate size property.
+ *
+ */
+ getViewSize:function () {
+ return this._viewSize;
+ },
+
+ setViewSize:function (size) {
+ this._viewSize = size;
+ cc.Node.prototype.setContentSize.call(this,size);
+ },
+
+ getContainer:function () {
+ return this._container;
+ },
+
+ setContainer:function (container) {
+ // Make sure that 'm_pContainer' has a non-NULL value since there are
+ // lots of logic that use 'm_pContainer'.
+ if (!container)
+ return;
+
+ this.removeAllChildren(true);
+
+ this._container = container;
+ container.ignoreAnchorPointForPosition(false);
+ container.setAnchorPoint(0, 0);
+
+ this.addChild(container);
+ this.setViewSize(this._viewSize);
+ },
+
+ /**
+ * direction allowed to scroll. CCScrollViewDirectionBoth by default.
+ */
+ getDirection:function () {
+ return this._direction;
+ },
+ setDirection:function (direction) {
+ this._direction = direction;
+ },
+
+ getDelegate:function () {
+ return this._delegate;
+ },
+ setDelegate:function (delegate) {
+ this._delegate = delegate;
+ },
+
+ /** override functions */
+ // optional
+ onTouchBegan:function (touch, event) {
+ for (var c = this; c != null; c = c.parent) {
+ if (!c.isVisible())
+ return false;
+ }
+ //var frameOriginal = this.getParent().convertToWorldSpace(this.getPosition());
+ //var frame = cc.rect(frameOriginal.x, frameOriginal.y, this._viewSize.width, this._viewSize.height);
+ var frame = this._getViewRect();
+
+ //dispatcher does not know about clipping. reject touches outside visible bounds.
+ var locContainer = this._container;
+ var locPoint = locContainer.convertToWorldSpace(locContainer.convertTouchToNodeSpace(touch));
+ var locTouches = this._touches;
+ if (locTouches.length > 2 || this._touchMoved || !cc.rectContainsPoint(frame, locPoint))
+ return false;
+
+ locTouches.push(touch);
+ //}
+
+ if (locTouches.length === 1) { // scrolling
+ this._touchPoint = this.convertTouchToNodeSpace(touch);
+ this._touchMoved = false;
+ this._dragging = true; //dragging started
+ this._scrollDistance.x = 0;
+ this._scrollDistance.y = 0;
+ this._touchLength = 0.0;
+ } else if (locTouches.length === 2) {
+ this._touchPoint = cc.pMidpoint(this.convertTouchToNodeSpace(locTouches[0]),
+ this.convertTouchToNodeSpace(locTouches[1]));
+ this._touchLength = cc.pDistance(locContainer.convertTouchToNodeSpace(locTouches[0]),
+ locContainer.convertTouchToNodeSpace(locTouches[1]));
+ this._dragging = false;
+ }
+ return true;
+ },
+
+ onTouchMoved:function (touch, event) {
+ if (!this.isVisible())
+ return;
+
+ this.setNodeDirty();
+
+ if (this._touches.length === 1 && this._dragging) { // scrolling
+ this._touchMoved = true;
+ //var frameOriginal = this.getParent().convertToWorldSpace(this.getPosition());
+ //var frame = cc.rect(frameOriginal.x, frameOriginal.y, this._viewSize.width, this._viewSize.height);
+ var frame = this._getViewRect();
+
+ //var newPoint = this.convertTouchToNodeSpace(this._touches[0]);
+ var newPoint = this.convertTouchToNodeSpace(touch);
+ var moveDistance = cc.pSub(newPoint, this._touchPoint);
+
+ var dis = 0.0, locDirection = this._direction, pos;
+ if (locDirection === cc.SCROLLVIEW_DIRECTION_VERTICAL){
+ dis = moveDistance.y;
+ pos = this._container.getPositionY();
+ if (!(this.minContainerOffset().y <= pos && pos <= this.maxContainerOffset().y))
+ moveDistance.y *= BOUNCE_BACK_FACTOR;
+ } else if (locDirection === cc.SCROLLVIEW_DIRECTION_HORIZONTAL){
+ dis = moveDistance.x;
+ pos = this._container.getPositionX();
+ if (!(this.minContainerOffset().x <= pos && pos <= this.maxContainerOffset().x))
+ moveDistance.x *= BOUNCE_BACK_FACTOR;
+ }else {
+ dis = Math.sqrt(moveDistance.x * moveDistance.x + moveDistance.y * moveDistance.y);
+
+ pos = this._container.getPositionY();
+ var _minOffset = this.minContainerOffset(), _maxOffset = this.maxContainerOffset();
+ if (!(_minOffset.y <= pos && pos <= _maxOffset.y))
+ moveDistance.y *= BOUNCE_BACK_FACTOR;
+
+ pos = this._container.getPositionX();
+ if (!(_minOffset.x <= pos && pos <= _maxOffset.x))
+ moveDistance.x *= BOUNCE_BACK_FACTOR;
+ }
+
+ if (!this._touchMoved && Math.abs(cc.convertDistanceFromPointToInch(dis)) < MOVE_INCH ){
+ //CCLOG("Invalid movement, distance = [%f, %f], disInch = %f", moveDistance.x, moveDistance.y);
+ return;
+ }
+
+ if (!this._touchMoved){
+ moveDistance.x = 0;
+ moveDistance.y = 0;
+ }
+
+ this._touchPoint = newPoint;
+ this._touchMoved = true;
+
+ if (this._dragging) {
+ switch (locDirection) {
+ case cc.SCROLLVIEW_DIRECTION_VERTICAL:
+ moveDistance.x = 0.0;
+ break;
+ case cc.SCROLLVIEW_DIRECTION_HORIZONTAL:
+ moveDistance.y = 0.0;
+ break;
+ default:
+ break;
+ }
+
+ var locPosition = this._container.getPosition();
+ var newX = locPosition.x + moveDistance.x;
+ var newY = locPosition.y + moveDistance.y;
+
+ this._scrollDistance = moveDistance;
+ this.setContentOffset(cc.p(newX, newY));
+ }
+ } else if (this._touches.length === 2 && !this._dragging) {
+ var len = cc.pDistance(this._container.convertTouchToNodeSpace(this._touches[0]),
+ this._container.convertTouchToNodeSpace(this._touches[1]));
+ this.setZoomScale(this.getZoomScale() * len / this._touchLength);
+ }
+ },
+
+ onTouchEnded:function (touch, event) {
+ if (!this.isVisible())
+ return;
+
+ if (this._touches.length === 1 && this._touchMoved)
+ this.schedule(this._deaccelerateScrolling);
+
+ this._touches.length = 0;
+ this._dragging = false;
+ this._touchMoved = false;
+ },
+
+ onTouchCancelled:function (touch, event) {
+ if (!this.isVisible())
+ return;
+
+ this._touches.length = 0;
+ this._dragging = false;
+ this._touchMoved = false;
+ },
+
+ setContentSize: function (size, height) {
+ if (this.getContainer() !== null) {
+ if(height === undefined)
+ this.getContainer().setContentSize(size);
+ else
+ this.getContainer().setContentSize(size, height);
+ this.updateInset();
+ }
+ },
+ _setWidth: function (value) {
+ var container = this.getContainer();
+ if (container !== null) {
+ container._setWidth(value);
+ this.updateInset();
+ }
+ },
+ _setHeight: function (value) {
+ var container = this.getContainer();
+ if (container !== null) {
+ container._setHeight(value);
+ this.updateInset();
+ }
+ },
+
+ getContentSize:function () {
+ return this._container.getContentSize();
+ },
+
+ updateInset:function () {
+ if (this.getContainer() !== null) {
+ var locViewSize = this._viewSize;
+ var tempOffset = this.maxContainerOffset();
+ this._maxInset.x = tempOffset.x + locViewSize.width * INSET_RATIO;
+ this._maxInset.y = tempOffset.y + locViewSize.height * INSET_RATIO;
+ tempOffset = this.minContainerOffset();
+ this._minInset.x = tempOffset.x - locViewSize.width * INSET_RATIO;
+ this._minInset.y = tempOffset.y - locViewSize.height * INSET_RATIO;
+ }
+ },
+
+ /**
+ * Determines whether it clips its children or not.
+ */
+ isClippingToBounds:function () {
+ return this._clippingToBounds;
+ },
+
+ setClippingToBounds:function (clippingToBounds) {
+ this._clippingToBounds = clippingToBounds;
+ },
+
+ visit:function (parentCmd) {
+ // quick return if not visible
+ if (!this.isVisible())
+ return;
+
+ this._renderCmd.visit(parentCmd);
+ },
+
+ addChild:function (child, zOrder, tag) {
+ if (!child)
+ throw new Error("child must not nil!");
+
+ zOrder = zOrder || child.getLocalZOrder();
+ tag = tag || child.getTag();
+
+ //child.ignoreAnchorPointForPosition(false);
+ //child.setAnchorPoint(0, 0);
+ if (this._container !== child) {
+ this._container.addChild(child, zOrder, tag);
+ } else {
+ cc.Layer.prototype.addChild.call(this, child, zOrder, tag);
+ }
+ },
+
+ isTouchEnabled: function(){
+ return this._touchListener !== null;
+ },
+
+ setTouchEnabled:function (e) {
+ if(this._touchListener)
+ cc.eventManager.removeListener(this._touchListener);
+ this._touchListener = null;
+ if (!e) {
+ this._dragging = false;
+ this._touchMoved = false;
+ this._touches.length = 0;
+ } else {
+ var listener = cc.EventListener.create({
+ event: cc.EventListener.TOUCH_ONE_BY_ONE
+ });
+ if(this.onTouchBegan)
+ listener.onTouchBegan = this.onTouchBegan.bind(this);
+ if(this.onTouchMoved)
+ listener.onTouchMoved = this.onTouchMoved.bind(this);
+ if(this.onTouchEnded)
+ listener.onTouchEnded = this.onTouchEnded.bind(this);
+ if(this.onTouchCancelled)
+ listener.onTouchCancelled = this.onTouchCancelled.bind(this);
+ this._touchListener = listener;
+ cc.eventManager.addListener(listener, this);
+ }
+ },
+
+ /**
+ * Init this object with a given size to clip its content.
+ *
+ * @param size view size
+ * @return initialized scroll view object
+ */
+ _initWithViewSize:function (size) {
+ return null;
+ },
+
+ /**
+ * Relocates the container at the proper offset, in bounds of max/min offsets.
+ *
+ * @param animated If YES, relocation is animated
+ */
+ _relocateContainer:function (animated) {
+ var min = this.minContainerOffset();
+ var max = this.maxContainerOffset();
+ var locDirection = this._direction;
+
+ var oldPoint = this._container.getPosition();
+ var newX = oldPoint.x;
+ var newY = oldPoint.y;
+ if (locDirection === cc.SCROLLVIEW_DIRECTION_BOTH || locDirection === cc.SCROLLVIEW_DIRECTION_HORIZONTAL) {
+ newX = Math.max(newX, min.x);
+ newX = Math.min(newX, max.x);
+ }
+
+ if (locDirection === cc.SCROLLVIEW_DIRECTION_BOTH || locDirection === cc.SCROLLVIEW_DIRECTION_VERTICAL) {
+ newY = Math.min(newY, max.y);
+ newY = Math.max(newY, min.y);
+ }
+
+ if (newY !== oldPoint.y || newX !== oldPoint.x) {
+ this.setContentOffset(cc.p(newX, newY), animated);
+ }
+ },
+ /**
+ * implements auto-scrolling behavior. change SCROLL_DEACCEL_RATE as needed to choose
+ * deacceleration speed. it must be less than 1.0.
+ *
+ * @param {Number} dt delta
+ */
+ _deaccelerateScrolling:function (dt) {
+ if (this._dragging) {
+ this.unschedule(this._deaccelerateScrolling);
+ return;
+ }
+
+ var maxInset, minInset;
+ var oldPosition = this._container.getPosition();
+ var locScrollDistance = this._scrollDistance;
+ this._container.setPosition(oldPosition.x + locScrollDistance.x , oldPosition.y + locScrollDistance.y);
+ if (this._bounceable) {
+ maxInset = this._maxInset;
+ minInset = this._minInset;
+ } else {
+ maxInset = this.maxContainerOffset();
+ minInset = this.minContainerOffset();
+ }
+
+ //check to see if offset lies within the inset bounds
+ var newX = this._container.getPositionX();
+ var newY = this._container.getPositionY();
+
+ locScrollDistance.x = locScrollDistance.x * SCROLL_DEACCEL_RATE;
+ locScrollDistance.y = locScrollDistance.y * SCROLL_DEACCEL_RATE;
+
+ this.setContentOffset(cc.p(newX, newY));
+
+ if ((Math.abs(locScrollDistance.x) <= SCROLL_DEACCEL_DIST &&
+ Math.abs(locScrollDistance.y) <= SCROLL_DEACCEL_DIST) ||
+ newY > maxInset.y || newY < minInset.y ||
+ newX > maxInset.x || newX < minInset.x ||
+ newX === maxInset.x || newX === minInset.x ||
+ newY === maxInset.y || newY === minInset.y) {
+ this.unschedule(this._deaccelerateScrolling);
+ this._relocateContainer(true);
+ }
+ },
+ /**
+ * This method makes sure auto scrolling causes delegate to invoke its method
+ */
+ _performedAnimatedScroll:function (dt) {
+ if (this._dragging) {
+ this.unschedule(this._performedAnimatedScroll);
+ return;
+ }
+
+ if (this._delegate && this._delegate.scrollViewDidScroll)
+ this._delegate.scrollViewDidScroll(this);
+ },
+ /**
+ * Expire animated scroll delegate calls
+ */
+ _stoppedAnimatedScroll:function (node) {
+ this.unschedule(this._performedAnimatedScroll);
+ // After the animation stopped, "scrollViewDidScroll" should be invoked, this could fix the bug of lack of tableview cells.
+ if (this._delegate && this._delegate.scrollViewDidScroll) {
+ this._delegate.scrollViewDidScroll(this);
+ }
+ },
+
+ /**
+ * Zoom handling
+ */
+ _handleZoom:function () {
+ },
+
+ _getViewRect:function(){
+ var screenPos = this.convertToWorldSpace(cc.p(0,0));
+ var locViewSize = this._viewSize;
+
+ var scaleX = this.getScaleX();
+ var scaleY = this.getScaleY();
+
+ for (var p = this._parent; p != null; p = p.getParent()) {
+ scaleX *= p.getScaleX();
+ scaleY *= p.getScaleY();
+ }
+
+ // Support negative scaling. Not doing so causes intersectsRect calls
+ // (eg: to check if the touch was within the bounds) to return false.
+ // Note, CCNode::getScale will assert if X and Y scales are different.
+ if (scaleX < 0) {
+ screenPos.x += locViewSize.width * scaleX;
+ scaleX = -scaleX;
+ }
+ if (scaleY < 0) {
+ screenPos.y += locViewSize.height * scaleY;
+ scaleY = -scaleY;
+ }
+
+ var locViewRect = this._tmpViewRect;
+ locViewRect.x = screenPos.x;
+ locViewRect.y = screenPos.y;
+ locViewRect.width = locViewSize.width * scaleX;
+ locViewRect.height = locViewSize.height * scaleY;
+ return locViewRect;
+ },
+
+ _createRenderCmd: function(){
+ if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
+ return new cc.ScrollView.CanvasRenderCmd(this);
+ } else {
+ return new cc.ScrollView.WebGLRenderCmd(this);
+ }
+ }
+});
+
+var _p = cc.ScrollView.prototype;
+
+// Extended properties
+/** @expose */
+_p.minOffset;
+cc.defineGetterSetter(_p, "minOffset", _p.minContainerOffset);
+/** @expose */
+_p.maxOffset;
+cc.defineGetterSetter(_p, "maxOffset", _p.maxContainerOffset);
+/** @expose */
+_p.bounceable;
+cc.defineGetterSetter(_p, "bounceable", _p.isBounceable, _p.setBounceable);
+/** @expose */
+_p.viewSize;
+cc.defineGetterSetter(_p, "viewSize", _p.getViewSize, _p.setViewSize);
+/** @expose */
+_p.container;
+cc.defineGetterSetter(_p, "container", _p.getContainer, _p.setContainer);
+/** @expose */
+_p.direction;
+cc.defineGetterSetter(_p, "direction", _p.getDirection, _p.setDirection);
+/** @expose */
+_p.delegate;
+cc.defineGetterSetter(_p, "delegate", _p.getDelegate, _p.setDelegate);
+/** @expose */
+_p.clippingToBounds;
+cc.defineGetterSetter(_p, "clippingToBounds", _p.isClippingToBounds, _p.setClippingToBounds);
+
+_p = null;
+
+/**
+ * Returns an autoreleased scroll view object.
+ * @deprecated
+ * @param {cc.Size} size view size
+ * @param {cc.Node} container parent object
+ * @return {cc.ScrollView} scroll view object
+ */
+cc.ScrollView.create = function (size, container) {
+ return new cc.ScrollView(size, container);
+};
\ No newline at end of file
diff --git a/extensions/gui/scrollview/CCScrollViewCanvasRenderCmd.js b/extensions/gui/scrollview/CCScrollViewCanvasRenderCmd.js
new file mode 100644
index 0000000000..3fdc92851f
--- /dev/null
+++ b/extensions/gui/scrollview/CCScrollViewCanvasRenderCmd.js
@@ -0,0 +1,81 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+(function() {
+ cc.ScrollView.CanvasRenderCmd = function(renderable){
+ cc.Layer.CanvasRenderCmd.call(this, renderable);
+ this._needDraw = false;
+
+ this.startCmd = new cc.CustomRenderCmd(this, this._startCmd);
+ this.endCmd = new cc.CustomRenderCmd(this, this._endCmd);
+ };
+
+ var proto = cc.ScrollView.CanvasRenderCmd.prototype = Object.create(cc.Layer.CanvasRenderCmd.prototype);
+ proto.constructor = cc.ScrollView.CanvasRenderCmd;
+
+ proto._startCmd = function(ctx, scaleX, scaleY){
+ var node = this._node;
+ var wrapper = ctx || cc._renderContext, context = wrapper.getContext();
+ wrapper.save();
+
+ if (node._clippingToBounds) {
+ this._scissorRestored = false;
+ wrapper.setTransform(this._worldTransform, scaleX, scaleY);
+
+ var locScaleX = node.getScaleX(), locScaleY = node.getScaleY();
+
+ var getWidth = (node._viewSize.width * locScaleX) * scaleX;
+ var getHeight = (node._viewSize.height * locScaleY) * scaleY;
+
+ context.beginPath();
+ context.rect(0, 0, getWidth, -getHeight);
+ context.closePath();
+ context.clip();
+ }
+ };
+
+ proto._endCmd = function(wrapper){
+ wrapper = wrapper || cc._renderContext;
+ wrapper.restore();
+ };
+
+ proto.visit = function(parentCmd){
+ var node = this._node;
+ if (!node._visible) return;
+
+ var i, locChildren = node._children, childrenLen;
+
+ this.transform(parentCmd);
+ cc.renderer.pushRenderCommand(this.startCmd);
+
+ if (locChildren && locChildren.length > 0) {
+ childrenLen = locChildren.length;
+ node.sortAllChildren();
+ for (i = 0; i < childrenLen; i++) {
+ locChildren[i]._renderCmd.visit(this);
+ }
+ }
+ cc.renderer.pushRenderCommand(this.endCmd);
+ };
+})();
diff --git a/extensions/gui/scrollview/CCScrollViewWebGLRenderCmd.js b/extensions/gui/scrollview/CCScrollViewWebGLRenderCmd.js
new file mode 100644
index 0000000000..7098f1a825
--- /dev/null
+++ b/extensions/gui/scrollview/CCScrollViewWebGLRenderCmd.js
@@ -0,0 +1,109 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+(function() {
+ cc.ScrollView.WebGLRenderCmd = function(renderable){
+ cc.Layer.WebGLRenderCmd.call(this, renderable);
+ this._needDraw = false;
+
+ this.startCmd = new cc.CustomRenderCmd(this, this._startCmd);
+ this.endCmd = new cc.CustomRenderCmd(this, this._endCmd);
+ };
+
+ var proto = cc.ScrollView.WebGLRenderCmd.prototype = Object.create(cc.Layer.WebGLRenderCmd.prototype);
+ proto.constructor = cc.ScrollView.WebGLRenderCmd;
+
+ proto._startCmd = function(){
+ var node = this._node;
+ var EGLViewer = cc.view;
+ var frame = node._getViewRect();
+ if(EGLViewer.isScissorEnabled()){
+ node._scissorRestored = true;
+ node._parentScissorRect = EGLViewer.getScissorRect();
+ //set the intersection of m_tParentScissorRect and frame as the new scissor rect
+ if (cc.rectIntersection(frame, node._parentScissorRect)) {
+ var locPSRect = node._parentScissorRect;
+ var x = Math.max(frame.x, locPSRect.x);
+ var y = Math.max(frame.y, locPSRect.y);
+ var xx = Math.min(frame.x + frame.width, locPSRect.x + locPSRect.width);
+ var yy = Math.min(frame.y + frame.height, locPSRect.y + locPSRect.height);
+ EGLViewer.setScissorInPoints(x, y, xx - x, yy - y);
+ }
+ }else{
+ var ctx = cc._renderContext;
+ ctx.enable(ctx.SCISSOR_TEST);
+ //clip
+ EGLViewer.setScissorInPoints(frame.x, frame.y, frame.width, frame.height);
+ }
+ };
+
+ proto._endCmd = function(){
+ var node = this._node;
+ if (node._scissorRestored) { //restore the parent's scissor rect
+ var rect = node._parentScissorRect;
+ cc.view.setScissorInPoints(rect.x, rect.y, rect.width, rect.height)
+ }else{
+ var ctx = cc._renderContext;
+ ctx.disable(ctx.SCISSOR_TEST);
+ }
+ };
+
+ proto.visit = function(parendCmd){
+ var node = this._node;
+ if (!node._visible) return;
+
+ var i, locChildren = node._children, selChild, childrenLen;
+
+ cc.kmGLPushMatrix();
+
+ this.transform(parendCmd);
+
+ if (node._clippingToBounds) {
+ cc.renderer.pushRenderCommand(this.startCmd);
+ }
+
+ if (locChildren && locChildren.length > 0) {
+ childrenLen = locChildren.length;
+ // draw children zOrder < 0
+ for (i = 0; i < childrenLen; i++) {
+ selChild = locChildren[i];
+ if (selChild && selChild._localZOrder < 0)
+ selChild._renderCmd.visit();
+ else
+ break;
+ }
+
+ // draw children zOrder >= 0
+ for (; i < childrenLen; i++)
+ locChildren[i]._renderCmd.visit();
+ }
+
+ if (node._clippingToBounds) {
+ cc.renderer.pushRenderCommand(this.endCmd);
+ }
+
+ this._dirtyFlag = 0;
+ cc.kmGLPopMatrix();
+ };
+})();
\ No newline at end of file
diff --git a/extensions/gui/scrollview/CCSorting.js b/extensions/gui/scrollview/CCSorting.js
new file mode 100644
index 0000000000..7902018171
--- /dev/null
+++ b/extensions/gui/scrollview/CCSorting.js
@@ -0,0 +1,239 @@
+/****************************************************************************
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2010 Sangwoo Im
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+/**
+ * The sortable object interface
+ * @class
+ * @extends cc._Class
+ */
+cc.SortableObject = cc._Class.extend(/** @lends cc.SortableObject */{
+ setObjectID:function (objectId) {
+ },
+ getObjectID:function () {
+ return 0;
+ }
+});
+
+/**
+ * The SortedObject class
+ * @class
+ * @extends cc.SortableObject
+ */
+cc.SortedObject = cc.SortableObject.extend(/** @lends cc.SortedObject */{
+ _objectID:0,
+
+ ctor:function () {
+ this._objectID = 0;
+ },
+
+ setObjectID:function (objectID) {
+ this._objectID = objectID;
+ },
+
+ getObjectID:function () {
+ return this._objectID;
+ }
+});
+
+var _compareObject = function (val1, val2) {
+ return (val1.getObjectID() - val2.getObjectID());
+};
+
+/**
+ * Array for object sorting utils
+ * @class
+ * @extend cc._Class
+ */
+cc.ArrayForObjectSorting = cc._Class.extend(/** @lends cc.ArrayForObjectSorting# */{
+ _saveObjectArr:null,
+
+ ctor:function () {
+ this._saveObjectArr = [];
+ },
+ /**
+ * Inserts a given object into array.
+ *
+ * Inserts a given object into array with key and value that are used in
+ * sorting. "value" must respond to message, compare:, which returns
+ * (NSComparisonResult). If it does not respond to the message, it is appended.
+ * If the compare message does not result NSComparisonResult, sorting behavior
+ * is not defined. It ignores duplicate entries and inserts next to it.
+ *
+ * @function
+ * @param {Object} addObject Object to insert
+ */
+ insertSortedObject:function (addObject) {
+ if(!addObject)
+ throw new Error("cc.ArrayForObjectSorting.insertSortedObject(): addObject should be non-null.");
+ var idx = this.indexOfSortedObject(addObject);
+ this.insertObject(addObject, idx);
+ },
+
+ /*!
+ * Removes an object in array.
+ *
+ * Removes an object with given key and value. If no object is found in array
+ * with the key and value, no action is taken.
+ *
+ * @function
+ * @param {Object} delObject Object to remove
+ */
+ removeSortedObject:function (delObject) {
+ if (this.count() === 0) {
+ return;
+ }
+
+ var idx = this.indexOfSortedObject(delObject);
+ if (idx < this.count() && idx !== cc.INVALID_INDEX) {
+ var foundObj = this.objectAtIndex(idx);
+ if (foundObj.getObjectID() === delObject.getObjectID()) {
+ this.removeObjectAtIndex(idx);
+ }
+ }
+ },
+
+ /*!
+ * Sets a new value of the key for the given object.
+ *
+ * In case where sorting value must be changed, this message must be sent to
+ * keep consistency of being sorted. If it is changed externally, it must be
+ * sorted completely again.
+ *
+ * @function
+ * @param {Number} tag Tag to set
+ * @param {Object} setObject The object which would be set
+ */
+ setObjectID_ofSortedObject:function (tag, setObject) {
+ var idx = this.indexOfSortedObject(setObject);
+ if (idx < this.count() && idx !== cc.INVALID_INDEX) {
+ var foundObj = this.objectAtIndex(idx);
+ if (foundObj.getObjectID() === setObject.getObjectID()) {
+ this.removeObjectAtIndex(idx);
+ foundObj.setObjectID(tag);
+ this.insertSortedObject(foundObj);
+ }
+ }
+ },
+
+ objectWithObjectID:function (tag) {
+ if (this.count() === 0) {
+ return null;
+ }
+ var foundObj = new cc.SortedObject();
+ foundObj.setObjectID(tag);
+
+ var idx = this.indexOfSortedObject(foundObj);
+ if (idx < this.count() && idx !== cc.INVALID_INDEX) {
+ foundObj = this.objectAtIndex(idx);
+ if (foundObj.getObjectID() !== tag)
+ foundObj = null;
+ }
+ return foundObj;
+ },
+
+ /*!
+ * Returns an object with given key and value.
+ *
+ * Returns an object with given key and value. If no object is found,
+ * it returns nil.
+ *
+ * @function
+ * @param {Number} tag Tag to locate object
+ * @return {Object|null}
+ */
+ getObjectWithObjectID:function (tag) {
+ return null;
+ },
+
+ /*!
+ * Returns an index of the object with given key and value.
+ *
+ * Returns the index of an object with given key and value.
+ * If no object is found, it returns an index at which the given object value
+ * would have been located. If object must be located at the end of array,
+ * it returns the length of the array, which is out of bound.
+ *
+ * @function
+ * @param {Number} idxObj Id to locate object
+ * @return {Number} index of an object found
+ */
+ indexOfSortedObject:function (idxObj) {
+ var idx = 0;
+ if (idxObj) {
+ // CCObject* pObj = (CCObject*)bsearch((CCObject*)&object, data.arr, data.num, sizeof(CCObject*), _compareObject);
+ // FIXME: need to use binary search to improve performance
+ var uPrevObjectID = 0;
+ var uOfSortObjectID = idxObj.getObjectID();
+
+ var locObjectArr = this._saveObjectArr;
+ for (var i = 0; i < locObjectArr.length; i++) {
+ var pSortableObj = locObjectArr[i];
+ var curObjectID = pSortableObj.getObjectID();
+ if ((uOfSortObjectID === curObjectID) ||
+ (uOfSortObjectID >= uPrevObjectID && uOfSortObjectID < curObjectID)) {
+ break;
+ }
+ uPrevObjectID = curObjectID;
+ idx++;
+ }
+ } else {
+ idx = cc.INVALID_INDEX;
+ }
+ return idx;
+ },
+
+ //implement array method
+ count:function () {
+ return this._saveObjectArr.length;
+ },
+
+ lastObject:function () {
+ var locObjectArr = this._saveObjectArr;
+ if (locObjectArr.length === 0)
+ return null;
+ return locObjectArr[locObjectArr.length - 1];
+ },
+
+ objectAtIndex:function (idx) {
+ return this._saveObjectArr[idx];
+ },
+
+ addObject:function (addObj) {
+ this._saveObjectArr.push(addObj);
+ this._saveObjectArr.sort(_compareObject);
+ },
+
+ removeObjectAtIndex:function (idx) {
+ this._saveObjectArr.splice(idx, 1);
+ this._saveObjectArr.sort(_compareObject);
+ },
+
+ insertObject:function (addObj, idx) {
+ this._saveObjectArr.splice(idx, 0, addObj);
+ this._saveObjectArr.sort(_compareObject);
+ }
+});
diff --git a/extensions/gui/scrollview/CCTableView.js b/extensions/gui/scrollview/CCTableView.js
new file mode 100644
index 0000000000..7b7f2c2846
--- /dev/null
+++ b/extensions/gui/scrollview/CCTableView.js
@@ -0,0 +1,720 @@
+/****************************************************************************
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2010 Sangwoo Im
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+/**
+ * The constant value of the fill style from top to bottom for cc.TableView
+ * @constant
+ * @type {number}
+ */
+cc.TABLEVIEW_FILL_TOPDOWN = 0;
+
+/**
+ * The constant value of the fill style from bottom to top for cc.TableView
+ * @constant
+ * @type {number}
+ */
+cc.TABLEVIEW_FILL_BOTTOMUP = 1;
+
+/**
+ * Abstract class for SWTableView cell node
+ * @class
+ * @abstract
+ * @extends cc.Node
+ *
+ * @property {Number} objectId - The index used internally by SWTableView and its subclasses
+ */
+cc.TableViewCell = cc.Node.extend(/** @lends cc.TableViewCell# */{
+ _idx:0,
+ _className:"TableViewCell",
+
+ /**
+ * The index used internally by SWTableView and its subclasses
+ */
+ getIdx:function () {
+ return this._idx;
+ },
+ setIdx:function (idx) {
+ this._idx = idx;
+ },
+
+ /**
+ * Cleans up any resources linked to this cell and resets idx property.
+ */
+ reset:function () {
+ this._idx = cc.INVALID_INDEX;
+ },
+
+ setObjectID:function (idx) {
+ this._idx = idx;
+ },
+ getObjectID:function () {
+ return this._idx;
+ }
+});
+
+var _p = cc.TableViewCell.prototype;
+
+/** @expose */
+_p.objectId;
+cc.defineGetterSetter(_p, "objectId", _p.getObjectID, _p.setObjectID);
+
+_p = null;
+
+/**
+ * Sole purpose of this delegate is to single touch event in this version.
+ */
+cc.TableViewDelegate = cc.ScrollViewDelegate.extend(/** @lends cc.TableViewDelegate# */{
+ /**
+ * Delegate to respond touch event
+ *
+ * @param {cc.TableView} table table contains the given cell
+ * @param {cc.TableViewCell} cell cell that is touched
+ */
+ tableCellTouched:function (table, cell) {
+ },
+
+ /**
+ * Delegate to respond a table cell press event.
+ *
+ * @param {cc.TableView} table table contains the given cell
+ * @param {cc.TableViewCell} cell cell that is pressed
+ */
+ tableCellHighlight:function(table, cell){
+ },
+
+ /**
+ * Delegate to respond a table cell release event
+ *
+ * @param {cc.TableView} table table contains the given cell
+ * @param {cc.TableViewCell} cell cell that is pressed
+ */
+ tableCellUnhighlight:function(table, cell){
+
+ },
+
+ /**
+ *
+ * Delegate called when the cell is about to be recycled. Immediately
+ * after this call the cell will be removed from the scene graph and
+ * recycled.
+ *
+ * @param table table contains the given cell
+ * @param cell cell that is pressed
+ */
+ tableCellWillRecycle:function(table, cell){
+
+ }
+});
+
+/**
+ * Data source that governs table backend data.
+ */
+cc.TableViewDataSource = cc._Class.extend(/** @lends cc.TableViewDataSource# */{
+ /**
+ * cell size for a given index
+ * @param {cc.TableView} table table to hold the instances of Class
+ * @param {Number} idx the index of a cell to get a size
+ * @return {cc.Size} size of a cell at given index
+ */
+ tableCellSizeForIndex:function(table, idx){
+ return this.cellSizeForTable(table);
+ },
+ /**
+ * cell height for a given table.
+ *
+ * @param {cc.TableView} table table to hold the instances of Class
+ * @return {cc.Size} cell size
+ */
+ cellSizeForTable:function (table) {
+ return cc.size(0,0);
+ },
+
+ /**
+ * a cell instance at a given index
+ * @param {cc.TableView} table table to hold the instances of Class
+ * @param idx index to search for a cell
+ * @return {cc.TableView} cell found at idx
+ */
+ tableCellAtIndex:function (table, idx) {
+ return null;
+ },
+
+ /**
+ * Returns number of cells in a given table view.
+ * @param {cc.TableView} table table to hold the instances of Class
+ * @return {Number} number of cells
+ */
+ numberOfCellsInTableView:function (table) {
+ return 0;
+ }
+});
+
+/**
+ * UITableView counterpart for cocos2d for iphone.
+ * this is a very basic, minimal implementation to bring UITableView-like component into cocos2d world.
+ *
+ * @class
+ * @extends cc.ScrollView
+ *
+ * @property {cc.TableViewDataSource} dataSource - The data source of the table view
+ * @property {cc.TableViewDelegate} delegate - The event delegate of the table view
+ * @property {Number} verticalFillOrder - The index to determine how cell is ordered and filled in the view
+ *
+ */
+cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
+ _vOrdering:null,
+ _indices:null,
+ _cellsFreed:null,
+ _dataSource:null,
+ _tableViewDelegate:null,
+ _oldDirection:null,
+ _cellsPositions:null, //vector with all cell positions
+ _touchedCell:null,
+
+ /**
+ * The
+ * @param dataSource
+ * @param size
+ * @param container
+ */
+ ctor:function (dataSource, size, container) {
+ cc.ScrollView.prototype.ctor.call(this);
+ this._oldDirection = cc.SCROLLVIEW_DIRECTION_NONE;
+ this._cellsPositions = [];
+
+ this.initWithViewSize(size, container);
+ this.setDataSource(dataSource);
+ this._updateCellPositions();
+ this._updateContentSize();
+ },
+
+ __indexFromOffset:function (offset) {
+ var low = 0;
+ var high = this._dataSource.numberOfCellsInTableView(this) - 1;
+ var search;
+ switch (this.getDirection()) {
+ case cc.SCROLLVIEW_DIRECTION_HORIZONTAL:
+ search = offset.x;
+ break;
+ default:
+ search = offset.y;
+ break;
+ }
+
+ var locCellsPositions = this._cellsPositions;
+ while (high >= low){
+ var index = 0|(low + (high - low) / 2);
+ var cellStart = locCellsPositions[index];
+ var cellEnd = locCellsPositions[index + 1];
+
+ if (search >= cellStart && search <= cellEnd){
+ return index;
+ } else if (search < cellStart){
+ high = index - 1;
+ }else {
+ low = index + 1;
+ }
+ }
+
+ if (low <= 0)
+ return 0;
+ return -1;
+ },
+
+ _indexFromOffset:function (offset) {
+ var locOffset = {x: offset.x, y: offset.y};
+ var locDataSource = this._dataSource;
+ var maxIdx = locDataSource.numberOfCellsInTableView(this) - 1;
+
+ if (this._vOrdering === cc.TABLEVIEW_FILL_TOPDOWN)
+ locOffset.y = this.getContainer().getContentSize().height - locOffset.y;
+
+ var index = this.__indexFromOffset(locOffset);
+ if (index !== -1) {
+ index = Math.max(0, index);
+ if (index > maxIdx)
+ index = cc.INVALID_INDEX;
+ }
+ return index;
+ },
+
+ __offsetFromIndex:function (index) {
+ var offset;
+ switch (this.getDirection()) {
+ case cc.SCROLLVIEW_DIRECTION_HORIZONTAL:
+ offset = cc.p(this._cellsPositions[index], 0);
+ break;
+ default:
+ offset = cc.p(0, this._cellsPositions[index]);
+ break;
+ }
+
+ return offset;
+ },
+
+ _offsetFromIndex:function (index) {
+ var offset = this.__offsetFromIndex(index);
+
+ var cellSize = this._dataSource.tableCellSizeForIndex(this, index);
+ if (this._vOrdering === cc.TABLEVIEW_FILL_TOPDOWN)
+ offset.y = this.getContainer().getContentSize().height - offset.y - cellSize.height;
+
+ return offset;
+ },
+
+ _updateCellPositions:function(){
+ var cellsCount = this._dataSource.numberOfCellsInTableView(this);
+ var locCellsPositions = this._cellsPositions;
+
+ if (cellsCount > 0){
+ var currentPos = 0;
+ var cellSize, locDataSource = this._dataSource;
+ for (var i=0; i < cellsCount; i++) {
+ locCellsPositions[i] = currentPos;
+ cellSize = locDataSource.tableCellSizeForIndex(this, i);
+ switch (this.getDirection()) {
+ case cc.SCROLLVIEW_DIRECTION_HORIZONTAL:
+ currentPos += cellSize.width;
+ break;
+ default:
+ currentPos += cellSize.height;
+ break;
+ }
+ }
+ this._cellsPositions[cellsCount] = currentPos;//1 extra value allows us to get right/bottom of the last cell
+ }
+ },
+
+ _updateContentSize:function () {
+ var size = cc.size(0, 0);
+
+ var cellsCount = this._dataSource.numberOfCellsInTableView(this);
+
+ if(cellsCount > 0){
+ var maxPosition = this._cellsPositions[cellsCount];
+ switch (this.getDirection()) {
+ case cc.SCROLLVIEW_DIRECTION_HORIZONTAL:
+ size = cc.size(maxPosition, this._viewSize.height);
+ break;
+ default:
+ size = cc.size(this._viewSize.width, maxPosition);
+ break;
+ }
+ }
+
+ this.setContentSize(size);
+
+ if (this._oldDirection !== this._direction) {
+ if (this._direction === cc.SCROLLVIEW_DIRECTION_HORIZONTAL) {
+ this.setContentOffset(cc.p(0, 0));
+ } else {
+ this.setContentOffset(cc.p(0, this.minContainerOffset().y));
+ }
+ this._oldDirection = this._direction;
+ }
+ },
+
+ _moveCellOutOfSight:function (cell) {
+ if(this._tableViewDelegate && this._tableViewDelegate.tableCellWillRecycle)
+ this._tableViewDelegate.tableCellWillRecycle(this, cell);
+
+ this._cellsFreed.addObject(cell);
+ this._cellsUsed.removeSortedObject(cell);
+ cc.js.array.remove(this._indices, cell.getIdx());
+
+ cell.reset();
+ if (cell.getParent() === this.getContainer()) {
+ this.getContainer().removeChild(cell, true);
+ }
+ },
+
+ _setIndexForCell:function (index, cell) {
+ cell.setAnchorPoint(0, 0);
+ cell.setPosition(this._offsetFromIndex(index));
+ cell.setIdx(index);
+ },
+
+ _addCellIfNecessary:function (cell) {
+ if (cell.getParent() !== this.getContainer()) {
+ this.getContainer().addChild(cell);
+ }
+ this._cellsUsed.insertSortedObject(cell);
+ var locIndices = this._indices, addIdx = cell.getIdx();
+ if(locIndices.indexOf(addIdx) === -1){
+ locIndices.push(addIdx);
+ //sort
+ locIndices.sort(function(a,b){return a-b;});
+ }
+ },
+
+ /**
+ * data source
+ */
+ getDataSource:function () {
+ return this._dataSource;
+ },
+ setDataSource:function (source) {
+ this._dataSource = source;
+ },
+
+ /**
+ * delegate
+ */
+ getDelegate:function () {
+ return this._tableViewDelegate;
+ },
+
+ setDelegate:function (delegate) {
+ this._tableViewDelegate = delegate;
+ },
+
+ /**
+ * determines how cell is ordered and filled in the view.
+ */
+ setVerticalFillOrder:function (fillOrder) {
+ if (this._vOrdering !== fillOrder) {
+ this._vOrdering = fillOrder;
+ if (this._cellsUsed.count() > 0) {
+ this.reloadData();
+ }
+ }
+ },
+ getVerticalFillOrder:function () {
+ return this._vOrdering;
+ },
+
+ initWithViewSize:function (size, container) {
+ if (cc.ScrollView.prototype.initWithViewSize.call(this, size, container)) {
+ this._cellsUsed = new cc.ArrayForObjectSorting();
+ this._cellsFreed = new cc.ArrayForObjectSorting();
+ this._indices = [];
+ this._tableViewDelegate = null;
+ this._vOrdering = cc.TABLEVIEW_FILL_BOTTOMUP;
+ this.setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL);
+
+ cc.ScrollView.prototype.setDelegate.call(this, this);
+ return true;
+ }
+ return false;
+ },
+
+ /**
+ * Updates the content of the cell at a given index.
+ *
+ * @param idx index to find a cell
+ */
+ updateCellAtIndex:function (idx) {
+ if (idx === cc.INVALID_INDEX || idx > this._dataSource.numberOfCellsInTableView(this) - 1)
+ return;
+
+ var cell = this.cellAtIndex(idx);
+ if (cell)
+ this._moveCellOutOfSight(cell);
+
+ cell = this._dataSource.tableCellAtIndex(this, idx);
+ this._setIndexForCell(idx, cell);
+ this._addCellIfNecessary(cell);
+ },
+
+ /**
+ * Inserts a new cell at a given index
+ *
+ * @param idx location to insert
+ */
+ insertCellAtIndex:function (idx) {
+ if (idx === cc.INVALID_INDEX || idx > this._dataSource.numberOfCellsInTableView(this) - 1)
+ return;
+
+ var newIdx, locCellsUsed = this._cellsUsed;
+ var cell = locCellsUsed.objectWithObjectID(idx);
+ if (cell) {
+ newIdx = locCellsUsed.indexOfSortedObject(cell);
+ for (var i = newIdx; i < locCellsUsed.count(); i++) {
+ cell = locCellsUsed.objectAtIndex(i);
+ this._setIndexForCell(cell.getIdx() + 1, cell);
+ }
+ }
+
+ //insert a new cell
+ cell = this._dataSource.tableCellAtIndex(this, idx);
+ this._setIndexForCell(idx, cell);
+ this._addCellIfNecessary(cell);
+
+ this._updateCellPositions();
+ this._updateContentSize();
+ },
+
+ /**
+ * Removes a cell at a given index
+ *
+ * @param idx index to find a cell
+ */
+ removeCellAtIndex:function (idx) {
+ if (idx === cc.INVALID_INDEX || idx > this._dataSource.numberOfCellsInTableView(this) - 1)
+ return;
+
+ var cell = this.cellAtIndex(idx);
+ if (!cell)
+ return;
+
+ var locCellsUsed = this._cellsUsed;
+ var newIdx = locCellsUsed.indexOfSortedObject(cell);
+
+ //remove first
+ this._moveCellOutOfSight(cell);
+ cc.js.array.remove(this._indices, idx);
+ this._updateCellPositions();
+
+ for (var i = locCellsUsed.count() - 1; i > newIdx; i--) {
+ cell = locCellsUsed.objectAtIndex(i);
+ this._setIndexForCell(cell.getIdx() - 1, cell);
+ }
+ },
+
+ /**
+ * reloads data from data source. the view will be refreshed.
+ */
+ reloadData:function () {
+ this._oldDirection = cc.SCROLLVIEW_DIRECTION_NONE;
+ var locCellsUsed = this._cellsUsed, locCellsFreed = this._cellsFreed, locContainer = this.getContainer();
+ for (var i = 0, len = locCellsUsed.count(); i < len; i++) {
+ var cell = locCellsUsed.objectAtIndex(i);
+
+ if(this._tableViewDelegate && this._tableViewDelegate.tableCellWillRecycle)
+ this._tableViewDelegate.tableCellWillRecycle(this, cell);
+
+ locCellsFreed.addObject(cell);
+ cell.reset();
+ if (cell.getParent() === locContainer)
+ locContainer.removeChild(cell, true);
+ }
+
+ this._indices = [];
+ this._cellsUsed = new cc.ArrayForObjectSorting();
+
+ this._updateCellPositions();
+ this._updateContentSize();
+ if (this._dataSource.numberOfCellsInTableView(this) > 0)
+ this.scrollViewDidScroll(this);
+ },
+
+ /**
+ * Dequeues a free cell if available. nil if not.
+ *
+ * @return {TableViewCell} free cell
+ */
+ dequeueCell:function () {
+ if (this._cellsFreed.count() === 0) {
+ return null;
+ } else {
+ var cell = this._cellsFreed.objectAtIndex(0);
+ this._cellsFreed.removeObjectAtIndex(0);
+ return cell;
+ }
+ },
+
+ /**
+ * Returns an existing cell at a given index. Returns nil if a cell is nonexistent at the moment of query.
+ *
+ * @param idx index
+ * @return {cc.TableViewCell} a cell at a given index
+ */
+ cellAtIndex:function (idx) {
+ var i = this._indices.indexOf(idx);
+ if (i === -1)
+ return null;
+ return this._cellsUsed.objectWithObjectID(idx);
+ },
+
+ scrollViewDidScroll:function (view) {
+ var locDataSource = this._dataSource;
+ var countOfItems = locDataSource.numberOfCellsInTableView(this);
+ if (0 === countOfItems)
+ return;
+
+ if (this._tableViewDelegate !== null && this._tableViewDelegate.scrollViewDidScroll)
+ this._tableViewDelegate.scrollViewDidScroll(this);
+
+ var idx = 0, locViewSize = this._viewSize, locContainer = this.getContainer();
+ var offset = this.getContentOffset();
+ offset.x *= -1;
+ offset.y *= -1;
+
+ var maxIdx = Math.max(countOfItems-1, 0);
+
+ if (this._vOrdering === cc.TABLEVIEW_FILL_TOPDOWN)
+ offset.y = offset.y + locViewSize.height/locContainer.getScaleY();
+ var startIdx = this._indexFromOffset(offset);
+ if (startIdx === cc.INVALID_INDEX)
+ startIdx = countOfItems - 1;
+
+ if (this._vOrdering === cc.TABLEVIEW_FILL_TOPDOWN)
+ offset.y -= locViewSize.height/locContainer.getScaleY();
+ else
+ offset.y += locViewSize.height/locContainer.getScaleY();
+ offset.x += locViewSize.width/locContainer.getScaleX();
+
+ var endIdx = this._indexFromOffset(offset);
+ if (endIdx === cc.INVALID_INDEX)
+ endIdx = countOfItems - 1;
+
+ var cell, locCellsUsed = this._cellsUsed;
+ if (locCellsUsed.count() > 0) {
+ cell = locCellsUsed.objectAtIndex(0);
+ idx = cell.getIdx();
+ while (idx < startIdx) {
+ this._moveCellOutOfSight(cell);
+ if (locCellsUsed.count() > 0) {
+ cell = locCellsUsed.objectAtIndex(0);
+ idx = cell.getIdx();
+ } else
+ break;
+ }
+ }
+
+ if (locCellsUsed.count() > 0) {
+ cell = locCellsUsed.lastObject();
+ idx = cell.getIdx();
+ while (idx <= maxIdx && idx > endIdx) {
+ this._moveCellOutOfSight(cell);
+ if (locCellsUsed.count() > 0) {
+ cell = locCellsUsed.lastObject();
+ idx = cell.getIdx();
+ } else
+ break;
+ }
+ }
+
+ var locIndices = this._indices;
+ for (var i = startIdx; i <= endIdx; i++) {
+ if (locIndices.indexOf(i) !== -1)
+ continue;
+ this.updateCellAtIndex(i);
+ }
+ },
+
+ scrollViewDidZoom:function (view) {
+ },
+
+ onTouchEnded:function (touch, event) {
+ if (!this.isVisible())
+ return;
+
+ if (this._touchedCell){
+ var bb = this.getBoundingBox();
+ var tmpOrigin = cc.p(bb.x, bb.y);
+ tmpOrigin = this._parent.convertToWorldSpace(tmpOrigin);
+ bb.x = tmpOrigin.x;
+ bb.y = tmpOrigin.y;
+ var locTableViewDelegate = this._tableViewDelegate;
+ if (cc.rectContainsPoint(bb, touch.getLocation()) && locTableViewDelegate !== null){
+ if(locTableViewDelegate.tableCellUnhighlight)
+ locTableViewDelegate.tableCellUnhighlight(this, this._touchedCell);
+ if(locTableViewDelegate.tableCellTouched)
+ locTableViewDelegate.tableCellTouched(this, this._touchedCell);
+ }
+ this._touchedCell = null;
+ }
+ cc.ScrollView.prototype.onTouchEnded.call(this, touch, event);
+ },
+
+ onTouchBegan:function(touch, event){
+ for (var c = this; c != null; c = c.parent) {
+ if (!c.isVisible())
+ return false;
+ }
+
+ var touchResult = cc.ScrollView.prototype.onTouchBegan.call(this, touch, event);
+
+ if(this._touches.length === 1) {
+ var index, point;
+
+ point = this.getContainer().convertTouchToNodeSpace(touch);
+
+ index = this._indexFromOffset(point);
+ if (index === cc.INVALID_INDEX)
+ this._touchedCell = null;
+ else
+ this._touchedCell = this.cellAtIndex(index);
+
+ if (this._touchedCell && this._tableViewDelegate !== null && this._tableViewDelegate.tableCellHighlight)
+ this._tableViewDelegate.tableCellHighlight(this, this._touchedCell);
+ } else if(this._touchedCell) {
+ if(this._tableViewDelegate !== null && this._tableViewDelegate.tableCellUnhighlight)
+ this._tableViewDelegate.tableCellUnhighlight(this, this._touchedCell);
+ this._touchedCell = null;
+ }
+
+ return touchResult;
+ },
+
+ onTouchMoved: function(touch, event){
+ cc.ScrollView.prototype.onTouchMoved.call(this, touch, event);
+
+ if (this._touchedCell && this.isTouchMoved()) {
+ if(this._tableViewDelegate !== null && this._tableViewDelegate.tableCellUnhighlight)
+ this._tableViewDelegate.tableCellUnhighlight(this, this._touchedCell);
+ this._touchedCell = null;
+ }
+ },
+
+ onTouchCancelled: function(touch, event){
+ cc.ScrollView.prototype.onTouchCancelled.call(this, touch, event);
+
+ if (this._touchedCell) {
+ if(this._tableViewDelegate !== null && this._tableViewDelegate.tableCellUnhighlight)
+ this._tableViewDelegate.tableCellUnhighlight(this, this._touchedCell);
+ this._touchedCell = null;
+ }
+ }
+});
+
+var _p = cc.TableView.prototype;
+
+/** @expose */
+_p.dataSource;
+cc.defineGetterSetter(_p, "dataSource", _p.getDataSource, _p.setDataSource);
+/** @expose */
+_p.delegate;
+cc.defineGetterSetter(_p, "delegate", _p.getDelegate, _p.setDelegate);
+/** @expose */
+_p.verticalFillOrder;
+cc.defineGetterSetter(_p, "verticalFillOrder", _p.getVerticalFillOrder, _p.setVerticalFillOrder);
+
+_p = null;
+
+/**
+ * An initialized table view object
+ * @deprecated
+ * @param {cc.TableViewDataSource} dataSource data source;
+ * @param {cc.Size} size view size
+ * @param {cc.Node} [container] parent object for cells
+ * @return {cc.TableView} table view
+ */
+cc.TableView.create = function (dataSource, size, container) {
+ return new cc.TableView(dataSource, size, container);
+};
diff --git a/extensions/runtime/CCLoaderLayer.js b/extensions/runtime/CCLoaderLayer.js
new file mode 100644
index 0000000000..bfbe12ea3c
--- /dev/null
+++ b/extensions/runtime/CCLoaderLayer.js
@@ -0,0 +1,974 @@
+/****************************************************************************
+ Copyright (c) 2014-2015 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.
+ ****************************************************************************/
+(function () {
+
+var INT_MAX = Number.MAX_VALUE;
+var GROUP_JSON_PATH = "group.json";
+
+cc.LoaderLayer = cc.Layer.extend({
+ _backgroundSprite: null,
+ _progressBackgroundSprite: null,
+ _progressBarSprite: null,
+ _logoSprite: null,
+ _titleSprite: null,
+ _groupname: null,
+ _callback: null,
+ _selector: null,
+ _preloadCount: 0,
+ _isPreloadFromFailed: false,
+ _progressOriginalWidth: 0,
+ _isLandScape: false,
+ _scaleFactor: null,
+
+ ctor: function (config) {
+ this._super();
+ if (config) {
+ cc.LoaderLayer.setConfig(config);
+ }
+ },
+ onEnter: function () {
+ this._super();
+ this.initView();
+ var config = cc.LoaderLayer._finalConfig;
+ if (config.onEnter) {
+ config.onEnter(this);
+ }
+ },
+ onExit: function () {
+ this._super();
+ var config = cc.LoaderLayer._finalConfig;
+ if (config.logo.action) {
+ config.logo.action.release();
+ }
+ if(config.title.action){
+ config.title.action.release();
+ }
+ if (config.onExit) {
+ config.onExit(this);
+ }
+ },
+ initView: function () {
+ var config = cc.LoaderLayer._finalConfig;
+ this._contentLayer = new cc.Layer();
+ this._isLandScape = cc.winSize.width > cc.winSize.height;
+ this._scaleFactor = !cc.LoaderLayer._useDefaultSource ? 1 : cc.winSize.width > cc.winSize.height ? cc.winSize.width / 720 : cc.winSize.width / 480;
+
+ //background
+ this.backgroundSprite = new cc.Sprite(config.background.res);
+ this.addChild(this.backgroundSprite);
+ this.backgroundSprite.x = 0, this.backgroundSprite.y = 0, this.backgroundSprite.anchorX = 0, this.backgroundSprite.anchorY = 0;
+ if (cc.LoaderLayer._useDefaultSource) {
+ this.backgroundSprite.scaleX = cc.winSize.width / this.backgroundSprite.width;
+ this.backgroundSprite.scaleY = cc.winSize.height / this.backgroundSprite.height;
+ }
+
+ //title
+ if (config.title.show) {
+ this.titleSprite = new cc.Sprite(config.title.res);
+ var defaultTitlePosition = cc.pAdd(cc.visibleRect.center, cc.p(0, this._scaleFactor < 1 ? 0 : this._isLandScape ? -80 : 30));
+ this.titleSprite.setPosition(config.title.position ? config.title.position : defaultTitlePosition);
+ this._contentLayer.addChild(this.titleSprite);
+ if (config.title.action) {
+ this.titleSprite.runAction(config.title.action);
+ }
+ }
+
+ //logo
+ if (config.logo.show) {
+ this.logoSprite = new cc.Sprite(config.logo.res);
+ var defaultLogoPosition = cc.pAdd(cc.visibleRect.top, cc.p(0, this._scaleFactor < 1 ? 0 : -this.logoSprite.height / 2 - (this._isLandScape ? 56 : 76)));
+ this.logoSprite.setPosition(config.logo.position ? config.logo.position : defaultLogoPosition);
+ this._contentLayer.addChild(this.logoSprite);
+ if (config.logo.action) {
+ this.logoSprite.runAction(config.logo.action);
+ }
+ }
+
+ //progressbar
+ if (config.progressBar.show) {
+ this.progressBarSprite = new cc.Sprite(config.progressBar.res);
+ this._progressOriginalWidth = this.progressBarSprite.width;
+ this.progressBackgroundSprite = new cc.Sprite(config.progressBar.barBackgroundRes);
+ this.progressBarSprite.anchorX = 0;
+ this.progressBarSprite.anchorY = 0;
+ if (cc.LoaderLayer._isDefaultProgress) {
+ this._barPoint = new cc.Sprite(config.progressBar.barPoint);
+ this.progressBarSprite.addChild(this._barPoint);
+ }
+ if (config.progressBar.barBackgroundRes == null) {
+ this.progressBackgroundSprite.setTextureRect(cc.rect(0, 0, this.progressBarSprite.width, this.progressBarSprite.height));
+ }
+ if (config.progressBar.offset == null) {
+ var deltaProgressWithX = (this.progressBackgroundSprite.width - this.progressBarSprite.width) / 2;
+ var deltaProgressWithY = (this.progressBackgroundSprite.height - this.progressBarSprite.height) / 2;
+ config.progressBar.offset = cc.p(deltaProgressWithX, deltaProgressWithY);
+ }
+ this.progressBarSprite.setPosition(config.progressBar.offset);
+ this.progressBackgroundSprite.addChild(this.progressBarSprite);
+ var defaultProgressPosition = cc.pAdd(cc.visibleRect.bottom, cc.p(0, this.progressBarSprite.height / 2 + this._isLandScape ? 60 : 80));
+ this.progressBackgroundSprite.setPosition(config.progressBar.position ? config.progressBar.position : defaultProgressPosition);
+ this._contentLayer.addChild(this.progressBackgroundSprite);
+ this._setProgress(0);
+ }
+
+ //tips
+ if (config.tips.show) {
+ this.tipsLabel = new cc.LabelTTF("100%", "Arial", config.tips.fontSize);
+ this.tipsLabel.setColor(config.tips.color);
+ this.tipsLabel.setPosition(config.tips.position ? config.tips.position : this.progressBackgroundSprite ? cc.p(this.progressBackgroundSprite.x, this.progressBackgroundSprite.y + this.progressBackgroundSprite.height / 2 + 20) : cc.pAdd(cc.visibleRect.bottom, cc.p(0, 100)));
+ this._contentLayer.addChild(this.tipsLabel);
+ }
+ this.addChild(this._contentLayer);
+ if (this._scaleFactor < 1) {
+ this._contentLayer.setScale(this._scaleFactor);
+ this._contentLayer.setPosition(cc.pAdd(this._contentLayer.getPosition(), cc.p(0, -50)));
+ }
+
+ },
+ _setProgress: function (percent) {
+ if (this.progressBarSprite) {
+ percent < 1 ? percent : 1;
+ var width = percent * this._progressOriginalWidth;
+ this.progressBarSprite.setTextureRect(cc.rect(0, 0, width, this.progressBarSprite.height));
+ if (cc.LoaderLayer._isDefaultProgress) {
+ this._barPoint.setPosition(cc.p(this.progressBarSprite.width, this.progressBarSprite.height / 2));
+ }
+ }
+ },
+ setTipsString: function (str) {
+ if (this.tipsLabel != null) {
+ this.tipsLabel.setString(str);
+ }
+ },
+ getProgressBar: function () {
+ return this.progressBarSprite;
+ },
+ getTipsLabel: function () {
+ return this.tipsLabel;
+ },
+ getLogoSprite: function () {
+ return this.logoSprite;
+ },
+ getTitleSprite: function () {
+ return this.titleSprite;
+ },
+ updateGroup: function (groupname, callback, target) {
+ this._groupname = groupname;
+ this._callback = callback;
+ this._selector = target;
+ },
+ _resetLoadingLabel: function () {
+ this.setTipsString("");
+ this._setProgress(0);
+ },
+ _preloadSource: function () {
+ cc.log("cc.LoaderLayer is preloading resource group: " + this._groupname);
+ this._resetLoadingLabel();
+ if (cc.sys.isNative) {
+ cc.Loader.preload(this._groupname, this._preload_native, this);
+ } else {
+ this._preload_html5();
+ }
+ },
+ _preload_html5: function () {
+ var res = "";
+ var groupIndex = [];
+ var config = cc.LoaderLayer._finalConfig;
+ var groups = cc.LoaderLayer.groups;
+ if (cc.isString(this._groupname)) {
+ if (this._groupname.indexOf(".") != -1) {
+ res = [this._groupname];
+ } else {
+ res = groups[this._groupname];
+ }
+ } else if (cc.isArray(this._groupname)) {
+ res = [];
+ for (var i = 0; i < this._groupname.length; i++) {
+ var group = groups[this._groupname[i]];
+ var files = group && group.files;
+ var preCount = i > 0 ? groupIndex[i - 1] : 0;
+ groupIndex.push(preCount + files ? files.length : 0);
+ res = res.concat(files);
+ }
+ }
+ var self = this;
+ //var progressFunction = self.config.progressCallback ? self.config.progressCallback : null;
+ cc.loader.load(res, function (result, count, loadedCount) {
+ var checkGroupName = function (loadedCount) {
+ for (var i = 0; i < groupIndex.length; i++) {
+ if (groupIndex[i] >= loadedCount) {
+ return self._groupname[i];
+ }
+ }
+ };
+ var groupName = checkGroupName(loadedCount);
+ var status = {
+ groupName: groupName,
+ isCompleted: false,
+ percent: (loadedCount / count * 100) | 0,//(float),
+ stage: 1, //(1 downloadïŒ2 unzip)
+ isFailed: false
+ }
+ if (status.percent != 0) {
+ self._setProgress(status.percent / 100);
+ }
+ config.tips.tipsProgress(status, self);
+ }, function () {
+ self.removeFromParent();
+ self._preloadCount--;
+ if (self._callback) {
+ if (self._selector) {
+ self._callback(self._selector, true);
+ } else {
+ self._callback(true);
+ }
+ }
+ self._callback.call(this._target, !status.isFailed);
+ });
+ },
+ _preload_native: function (status) {
+ cc.log(JSON.stringify(status));
+ var config = cc.LoaderLayer._finalConfig;
+ if (status.percent) {
+ this._setProgress(status.percent / 100);
+ }
+ if (config.tips.tipsProgress) {
+ config.tips.tipsProgress(status, this);
+ }
+ if (status.isCompleted || status.isFailed) {
+ this._preloadCount--;
+
+ if (status.isCompleted) {
+ cc.log("preload finish!");
+ this._isPreloadFromFailed = false;
+ }
+ if (status.isFailed) {
+ cc.log("preload failed!");
+ this._isPreloadFromFailed = true;
+ }
+
+ // Remove loading layer from scene after loading was done.
+ if (this._preloadCount == 0 && !this._isPreloadFromFailed) {
+ this.removeFromParent();
+ if (cc.LoaderLayer._useDefaultSource) {
+ var _config = cc.runtime.config.design_resolution || {width: 480, height: 720, policy: "SHOW_ALL"};
+ cc.view.setDesignResolutionSize(_config.width, _config.height, cc.ResolutionPolicy[_config.policy]);
+ }
+ }
+
+ // Callback must be invoked after removeFromParent.
+ this._callback.call(this._target, status);
+ }
+ },
+ _addToScene: function () {
+ if (this._preloadCount == 0 && !this._isPreloadFromFailed) {
+ if (cc.sys.isNative && cc.LoaderLayer._useDefaultSource) {
+ var config = cc.runtime.config.design_resolution;
+ var isLandscape = false;
+ var isLargeThanResource = false;
+ if (config) {
+ var orientation = cc.runtime.config.orientation;
+ cc.log("_addToScene orientation is " + orientation);
+ if (orientation == "landscape") {
+ isLandscape = true;
+ isLargeThanResource = config.width > 720 || config.height > 480;
+ } else {
+ isLargeThanResource = config.width > 480 || config.height > 720;
+ }
+ }
+ cc.log("isLargeThanResource is " + isLargeThanResource);
+ cc.view.setDesignResolutionSize(isLargeThanResource ? config.width : isLandscape ? 720 : 480, isLargeThanResource ? config.height : isLandscape ? 480 : 720, cc.ResolutionPolicy["FIXED_HEIGHT"]);
+ }
+ cc.director.getRunningScene().addChild(this, INT_MAX - 1);
+ }
+ this._preloadCount++;
+ }
+});
+cc.LoaderLayer._config = {//default setting for loaderlayer
+ background: {
+ res: "res_engine/preload_bg.jpg"
+ },
+ title: {
+ show: true,
+ res: "res_engine/preload_title.png",
+ position: null,
+ action: null
+ },
+ logo: {
+ res: "res_engine/preload_logo.png",
+ show: true,
+ position: null
+ },
+ progressBar: {
+ show: true,
+ res: "res_engine/progress_bar.png",
+ offset: null,
+ position: null,
+ barBackgroundRes: "res_engine/progress_bg.png",
+ barPoint: "res_engine/progress_light.png",
+ barShadow: "res_engine/shadow.png"
+ },
+ tips: {
+ show: true,
+ fontSize: 22,
+ position: null,
+ color: null,
+ tipsProgress: function (status, loaderlayer) {
+ if(loaderlayer.getTipsLabel()){
+ var statusStr = "æŁćš";
+ if (status.stage == cc.network.preloadstatus.DOWNLOAD) {
+ statusStr += "äžèœœ";
+ } else if (status.stage == cc.network.preloadstatus.UNZIP) {
+ statusStr += "è§Łć";
+ }
+ if (status.groupName) {
+ statusStr += status.groupName;
+ }
+ statusStr += "èżćșŠ:" + status.percent.toFixed(2) + "%";
+ loaderlayer.getTipsLabel().setString(statusStr);
+ }
+ }
+ },
+ progressCallback: function (progress) {
+
+ },
+ onEnter: function (layer) {
+ cc.log("LoaderLayer onEnter");
+ },
+ onExit: function (layer) {
+ cc.log("LoaderLayer onExit");
+ }
+}
+
+var res_engine_loaded = false;
+
+cc.LoaderLayer.preload = function (groupname, callback, target) {
+ var loaderLayer = new cc.LoaderLayer();
+ var preloadCb = function (status) {
+ if (status.isFailed) {
+ var tips, conirmfunc, cancelfunc;
+ switch (status.errorCode) {
+ case "err_no_space":
+ {
+ tips = "ç©șéŽäžè¶łïŒèŻ·æž
ççŁçç©șéŽ";
+ conirmfunc = function () {
+ callPreload();
+ };
+ cancelfunc = function () {
+ cc.director.end();
+ };
+ break;
+ }
+ case "err_verify":
+ {
+ tips = "æ ĄéȘć€±èŽ„ïŒæŻćŠéæ°äžèœœïŒ";
+ conirmfunc = function () {
+ callPreload();
+ }
+ cancelfunc = function () {
+ cc.director.end();
+ }
+ break;
+ }
+ case "err_network":
+ {
+ tips = "çœç»ćŒćžžæŻćŠéæ°äžèœœ";
+ conirmfunc = function () {
+ callPreload();
+ }
+ cancelfunc = function () {
+ cc.director.end();
+ }
+ break;
+ }
+ default :
+ {
+ conirmfunc = cancelfunc = function () {
+
+ }
+ }
+ }
+ cc._NetworkErrorDialog._show(status.errorCode, tips, conirmfunc, cancelfunc);
+ } else {
+ if (callback) {
+ if (target) {
+ callback.call(target, !status.isFailed);
+ } else {
+ callback(!status.isFailed)
+ }
+ }
+ }
+ }
+ var callPreload = function () {
+ if (cc.director.getRunningScene()) {
+ loaderLayer.updateGroup(groupname, preloadCb, target);
+ loaderLayer._addToScene();
+ loaderLayer._preloadSource();
+ } else {
+ cc.log("Current scene is null we can't start preload");
+ }
+ };
+
+ if (res_engine_loaded) {
+ callPreload();
+ return;
+ }
+
+ // Res engine not loaded, load them
+ cc.loader.load([
+ GROUP_JSON_PATH,
+ cc.LoaderLayer._finalConfig.background.res,
+ cc.LoaderLayer._finalConfig.title.res,
+ cc.LoaderLayer._finalConfig.logo.res,
+ cc.LoaderLayer._finalConfig.progressBar.res,
+ cc.LoaderLayer._finalConfig.progressBar.barBackgroundRes,
+ cc.LoaderLayer._finalConfig.progressBar.barPoint,
+ cc.LoaderLayer._finalConfig.progressBar.barShadow,
+ cc.Dialog._finalConfig.background.res,
+ cc.Dialog._finalConfig.confirmBtn.normalRes,
+ cc.Dialog._finalConfig.confirmBtn.pressRes,
+ cc.Dialog._finalConfig.cancelBtn.normalRes,
+ cc.Dialog._finalConfig.cancelBtn.pressRes
+ ],
+ function (result, count, loadedCount) {
+ var percent = (loadedCount / count * 100) | 0;
+ percent = Math.min(percent, 100);
+ cc.log("Preloading engine resources... " + percent + "%");
+ }, function () {
+ var groups = cc.loader.getRes(GROUP_JSON_PATH);
+ if (groups) {
+ cc.LoaderLayer.groups = groups;
+ }
+ else {
+ cc.warn("Group versions haven't been loaded, you can also set group data with 'cc.LoaderLayer.groups'");
+ }
+ res_engine_loaded = true;
+ callPreload();
+ });
+};
+
+cc.LoaderLayer._useDefaultSource = true;
+cc.LoaderLayer._isDefaultProgress = true;
+cc.LoaderLayer._finalConfig = cc.LoaderLayer._confg;
+cc.LoaderLayer.groups = {};
+cc.LoaderLayer.setUseDefaultSource = function (status) {
+ cc.LoaderLayer._useDefaultSource = status;
+};
+cc.LoaderLayer.setConfig = function (config) {
+ if(config.title && config.title.action){
+ config.title.action.retain();
+ }
+ if(config.logo && config.logo.action){
+ config.logo.action.retain();
+ }
+ this._initData(config);
+};
+cc.LoaderLayer._initData = function (uConfig) {
+ this._finalConfig = cc.clone(this._config);
+ var config = this._finalConfig;
+ if (uConfig != null) {
+ if (uConfig.background && uConfig.background.res) {
+ config.background.res = uConfig.background.res;
+ }
+ if (uConfig.title) {
+ var uTitle = uConfig.title;
+ var title = config.title;
+ title.show = typeof uTitle.show != "undefined" ? uTitle.show : title.show;
+ title.res = uTitle.res ? uTitle.res : title.res;
+ title.position = uTitle.position ? uTitle.position : title.position;
+ title.action = uTitle.action ? uTitle.action : title.action;
+ if (title.action) {
+ title.action = uTitle.action;
+ title.action.retain();
+ }
+ }
+ if (uConfig.logo) {
+ var uLogo = uConfig.logo;
+ var logo = config.logo;
+ logo.show = typeof uLogo.show != "undefined" ? uLogo.show : logo.show;
+ logo.res = uLogo.res ? uLogo.res : logo.res;
+ logo.position = uLogo.position ? uLogo.position : logo.position;
+ if (typeof uLogo.action != "undefined") {
+ logo.action = uLogo.action;
+ if (logo.action) {
+ logo.action.retain();
+ }
+ }
+ }
+ if (uConfig.progressBar) {
+ var uProgress = uConfig.progressBar;
+ var progress = config.progressBar;
+ progress.show = typeof uProgress.show != "undefined" ? uProgress.show : progress.show;
+ if (uProgress.res) {
+ progress.res = uProgress.res;
+ this._isDefaultProgress = false;
+ }
+ progress.offset = uProgress.offset ? uProgress.offset : progress.offset;
+ progress.position = uProgress.position ? uProgress.position : progress.position;
+ progress.barBackgroundRes = uProgress.barBackgroundRes ? uProgress.barBackgroundRes : progress.barBackgroundRes;
+ }
+ if (uConfig.tips) {
+ var uTips = uConfig.tips;
+ var tips = config.tips;
+ tips.show = typeof uTips.show != "undefined" ? uTips.show : tips.show;
+ tips.res = uTips.res ? uTips.res : tips.res;
+ tips.offset = uTips.offset ? uTips.offset : tips.offset;
+ tips.fontSize = uTips.fontSize ? uTips.fontSize : tips.fontSize;
+ tips.position = uTips.position ? uTips.position : tips.position;
+ tips.color = uTips.color ? uTips.color : tips.color;
+ if (uConfig.tips.tipsProgress && typeof uConfig.tips.tipsProgress == "function") {
+ tips.tipsProgress = uConfig.tips.tipsProgress;
+ }
+ }
+ if (typeof uConfig.onEnter == "function") {
+ config.onEnter = uConfig.onEnter;
+ }
+ if (typeof uConfig.onExit == "function") {
+ config.onExit = uConfig.onExit;
+ }
+ }
+
+ if (typeof config.logo.action == "undefined" && this._useDefaultSource) {
+ config.logo.action = cc.sequence(
+ cc.spawn(cc.moveBy(0.4, cc.p(0, 40)).easing(cc.easeIn(0.5)), cc.scaleTo(0.4, 0.95, 1.05).easing(cc.easeIn(0.5))),
+ cc.delayTime(0.08),
+ cc.spawn(cc.moveBy(0.4, cc.p(0, -40)).easing(cc.easeOut(0.5)), cc.scaleTo(0.4, 1.05, 0.95).easing(cc.easeOut(0.5)))
+ ).repeatForever();
+ config.logo.action.retain();
+ }
+ if (!config.tips.color) {
+ config.tips.color = cc.color(255, 255, 255);
+ }
+};
+
+cc.Dialog = cc.Layer.extend({
+ _defaultConfig: null,
+ backgroundSprite: null,
+ _menuItemConfirm: null,
+ _menuItemCancel: null,
+ _messageLabel: null,
+ _eventListener: null,
+ _scaleFactor: null,
+
+ ctor: function (config) {
+ this._super();
+ this.setConfig(config);
+ },
+ setConfig: function (config) {
+ this.removeAllChildren();
+ if (config) {
+ cc.Dialog.setConfig(config);
+ }
+ },
+ initView: function () {
+ var useDefaultSource = cc.Dialog._useDefaultSource;
+ var winSize = cc.director.getWinSize();
+ this._scaleFactor = !useDefaultSource ? 1 : winSize.width > winSize.height ? winSize.width / 720 : winSize.width / 480;
+ var config = cc.Dialog._finalConfig;
+
+ //bg
+ this.backgroundSprite = new cc.Scale9Sprite(config.background.res);
+ this._setScale(this.backgroundSprite);
+ if (this._scaleFactor < 1) {
+ this.backgroundSprite.setScale(this._scaleFactor);
+ }
+ this.backgroundSprite.setPosition(config.position ? config.position : cc.p(winSize.width / 2, winSize.height / 2));
+
+ //menu
+ this.menuItemConfirm = this._createMenuItemSprite(config.confirmBtn, this._confirmCallback);
+ this.menuItemCancel = this._createMenuItemSprite(config.cancelBtn, this._cancelCallback);
+ this.menuItemCancel.setPosition(config.cancelBtn.position ? config.cancelBtn.position : cc.p(this.backgroundSprite.width / 2 - this.menuItemCancel.width / 2 - 20, this.menuItemCancel.height + 20));
+ this.menuItemConfirm.setPosition(config.confirmBtn.position ? config.confirmBtn.position : cc.p(this.backgroundSprite.width / 2 + this.menuItemConfirm.width / 2 + 20, this.menuItemConfirm.height + 20));
+ var menu = new cc.Menu(this.menuItemConfirm, this.menuItemCancel);
+ menu.setPosition(cc.p(0, 0));
+ this.backgroundSprite.addChild(menu);
+
+ //message
+ var fontSize = config.messageLabel.fontSize ? config.messageLabel.fontSize : this._scaleFactor > 1 ? 16 * this._scaleFactor : 16;
+ this.messageLabel = new cc.LabelTTF(config.messageLabel.text, "Arial", fontSize);
+ this.messageLabel.setDimensions(config.messageLabel.dimensions ? config.messageLabel.dimensions : cc.size(this.backgroundSprite.width - 30, this.backgroundSprite.height - this.menuItemConfirm.y - 10));
+ this.messageLabel.setColor(config.messageLabel.color ? config.messageLabel.color : cc.color(255, 255, 255));
+ this.messageLabel.setPosition(config.messageLabel.position ? config.messageLabel.position : cc.p(this.backgroundSprite.width / 2, this.backgroundSprite.height - this.messageLabel.height / 2 - 20));
+ this.backgroundSprite.addChild(this.messageLabel);
+ if (!config.action) {
+ var action = cc.sequence(cc.EaseIn.create(cc.scaleTo(0.1, this.backgroundSprite.scale + 0.02), 0.4), cc.EaseOut.create(cc.scaleTo(0.1, this.backgroundSprite.scale), 0.3));
+ this.backgroundSprite.runAction(action);
+ } else {
+ this.backgroundSprite.runAction(config.action);
+ }
+ this.addChild(this.backgroundSprite);
+
+ },
+ _createMenuItemSprite: function (res, callback) {
+ var spriteNormal = new cc.Scale9Sprite(res.normalRes);
+ var spritePress = new cc.Scale9Sprite(res.pressRes);
+ this._setScale(spriteNormal);
+ this._setScale(spritePress);
+ var fontSize = res.fontSize ? res.fontSize : this._scaleFactor > 1 ? 16 * this._scaleFactor : 16;
+ var menuLabel = new cc.LabelTTF(res.text, "Arial", fontSize);
+ menuLabel.setColor(res.textColor);
+ var menuItem = new cc.MenuItemSprite(spriteNormal, spritePress, callback, this);
+ menuLabel.setPosition(cc.p(menuItem.width / 2, menuItem.height / 2));
+ menuItem.addChild(menuLabel);
+ return menuItem;
+ },
+ _setScale: function (s9Sprite) {
+ if (this._scaleFactor > 1) {
+ s9Sprite.setContentSize(cc.size(this._scaleFactor * s9Sprite.width, this._scaleFactor * s9Sprite.height));
+ }
+ },
+ _confirmCallback: function () {
+ var config = cc.Dialog._finalConfig;
+ if (config.confirmBtn.callback) {
+ if (config.target) {
+ config.confirmBtn.callback.call(config.target, this);
+ } else {
+ config.confirmBtn.callback(this);
+ }
+ }
+ this.removeFromParent();
+ },
+ _cancelCallback: function () {
+ var config = cc.Dialog._finalConfig;
+ if (config.cancelBtn.callback) {
+ if (config.target) {
+ config.cancelBtn.callback.call(config.target, this);
+ } else {
+ config.cancelBtn.callback(this);
+ }
+ }
+ this.removeFromParent();
+ },
+ onEnter: function () {
+ this._super();
+ var config = cc.Dialog._finalConfig;
+ this.initView();
+ config.onEnter(this);
+ var self = this;
+ self._eventListener = cc.EventListener.create({
+ event: cc.EventListener.TOUCH_ONE_BY_ONE,
+ swallowTouches: true,
+ onTouchBegan: function (touch, event) {
+ return true;
+ }
+ });
+ cc.eventManager.addListener(self._eventListener, self);
+ },
+ onExit: function () {
+ this._super();
+ var config = cc.Dialog._finalConfig;
+ config.onExit(this);
+ this.removeAllChildren();
+ cc.Dialog._dialog = null;
+ cc.eventManager.removeListener(this._eventListener);
+ }
+});
+
+cc.Dialog._dialog = null;
+cc.Dialog._clearDialog = function () {
+ if (cc.Dialog._dialog != null) {
+ cc.Dialog._dialog.removeFromParent();
+ cc.Dialog._dialog = null;
+ }
+}
+
+cc.Dialog.show = function (tips, confirmCb, cancelCb) {
+ if (cc.Dialog._dialog != null) {
+ cc.log("other dialog is on the screen,this dialog can't show now");
+ return;
+ }
+
+ var conf;
+ if (typeof tips == "string") {
+ conf = {
+ messageLabel: {
+ text: tips
+ },
+ confirmBtn: {
+ callback: confirmCb
+ },
+ cancelBtn: {
+ callback: cancelCb
+ }
+ }
+ } else if (typeof tips == "object") {
+ conf = tips;
+ } else {
+ cc.log("tips is invalid");
+ return;
+ }
+
+ cc.Dialog._dialog = new cc.Dialog(conf);
+ if (cc.director.getRunningScene()) {
+ cc.director.getRunningScene().addChild(cc.Dialog._dialog, INT_MAX);
+ } else {
+ cc.log("Current scene is null we can't show dialog");
+ }
+};
+cc.Dialog._useDefaultSource = true;
+cc.Dialog.setUseDefaultSource = function (status) {
+ cc.Dialog._useDefaultSource = status;
+}
+cc.Dialog._defaultConfig = {
+ position: null,
+ target: null,
+ action: null,
+ background: {
+ res: "res_engine/dialog_bg.png"
+ },
+ confirmBtn: {
+ normalRes: "res_engine/dialog_confirm_normal.png",
+ pressRes: "res_engine/dialog_confirm_press.png",
+ text: "祟ćź",
+ textColor: null,
+ fontSize: null,
+ position: null,
+ callback: function () {
+ cc.log("this is confirm callback");
+ }
+ },
+ cancelBtn: {
+ normalRes: "res_engine/dialog_cancel_normal.png",
+ pressRes: "res_engine/dialog_cancel_press.png",
+ text: "ćæ¶",
+ textColor: null,
+ position: null,
+ fontSize: null,
+ callback: function () {
+ cc.log("this is cancel callback");
+ }
+ },
+ messageLabel: {
+ text: "",
+ color: null,
+ dimensions: null,
+ fontSize: null,
+ position: null
+ },
+ onEnter: function (dialog) {
+ cc.log("dialog call onEnter");
+ },
+ onExit: function (dialog) {
+ cc.log("dialog call onExit");
+ }
+};
+cc.Dialog._finalConfig = cc.Dialog._defaultConfig;
+cc.Dialog.setConfig = function (config) {
+ this._initData(config);
+};
+cc.Dialog._initData = function (uConfig) {
+ this._finalConfig = cc.clone(this._defaultConfig);
+ var config = this._finalConfig;
+ if (uConfig != null) {
+ if (uConfig.position) {
+ config.position = uConfig.position;
+ }
+ if (uConfig.action) {
+ config.action = uConfig.action;
+ }
+ if (uConfig.background && uConfig.background.res) {
+ config.background = uConfig.background;
+ }
+ if (uConfig.confirmBtn) {
+ var uConfirmBtn = uConfig.confirmBtn;
+ var confirmBtn = config.confirmBtn;
+ confirmBtn.normalRes = uConfirmBtn.normalRes ? uConfirmBtn.normalRes : confirmBtn.normalRes;
+ confirmBtn.pressRes = uConfirmBtn.pressRes ? uConfirmBtn.pressRes : confirmBtn.pressRes;
+ confirmBtn.text = typeof uConfirmBtn.text != "undefined" ? uConfirmBtn.text : confirmBtn.text;
+ confirmBtn.textColor = uConfirmBtn.textColor ? uConfirmBtn.textColor : confirmBtn.textColor;
+ confirmBtn.fontSize = uConfirmBtn.fontSize ? uConfirmBtn.fontSize : confirmBtn.fontSize;
+ confirmBtn.position = uConfirmBtn.position ? uConfirmBtn.position : confirmBtn.position;
+ confirmBtn.callback = uConfirmBtn.callback ? uConfirmBtn.callback : confirmBtn.callback;
+ }
+ if (uConfig.cancelBtn) {
+ var uCancelBtn = uConfig.cancelBtn;
+ var cancelBtn = config.cancelBtn;
+ cancelBtn.normalRes = uCancelBtn.normalRes ? uCancelBtn.normalRes : cancelBtn.normalRes;
+ cancelBtn.pressRes = uCancelBtn.pressRes ? uCancelBtn.pressRes : cancelBtn.pressRes;
+ cancelBtn.text = typeof uCancelBtn.text != "undefined" ? uCancelBtn.text : cancelBtn.text;
+ cancelBtn.textColor = uCancelBtn.textColor ? uCancelBtn.textColor : cancelBtn.textColor;
+ cancelBtn.fontSize = uCancelBtn.fontSize ? uCancelBtn.fontSize : cancelBtn.fontSize;
+ cancelBtn.position = uCancelBtn.position ? uCancelBtn.position : cancelBtn.position;
+ cancelBtn.callback = uCancelBtn.callback ? uCancelBtn.callback : cancelBtn.callback;
+ }
+ if (uConfig.messageLabel) {
+ var uMessageLabel = uConfig.messageLabel;
+ var messageLabel = config.messageLabel;
+ messageLabel.text = typeof uMessageLabel.text != "undefined" ? uMessageLabel.text : messageLabel.text;
+ messageLabel.color = uMessageLabel.color ? uMessageLabel.color : messageLabel.color;
+ messageLabel.fontSize = uMessageLabel.fontSize ? uMessageLabel.fontSize : messageLabel.fontSize;
+ messageLabel.position = uMessageLabel.position ? uMessageLabel.position : messageLabel.position;
+ messageLabel.dimensions = uMessageLabel.dimensions ? uMessageLabel.dimensions : messageLabel.dimensions;
+ }
+ if (uConfig.target) {
+ config.target = uConfig.target;
+ }
+ if (typeof uConfig.onEnter == "function") {
+ config.onEnter = uConfig.onEnter;
+ }
+ if (typeof uConfig.onExit == "function") {
+ config.onExit = uConfig.onExit;
+ }
+ }
+
+ if (!config.cancelBtn.textColor) {
+ config.cancelBtn.textColor = cc.color(255, 255, 255);
+ }
+ if (!config.confirmBtn.textColor) {
+ config.confirmBtn.textColor = cc.color(255, 255, 255);
+ }
+};
+
+cc._NetworkErrorDialog = function () {
+ cc.Dialog._clearDialog();
+ cc.Dialog._dialog = new cc.Dialog(cc._NetworkErrorDialog._config);
+ return cc.Dialog._dialog;
+}
+cc._NetworkErrorDialog._config = {
+ networkError: {},
+ spaceError: {},
+ verifyError: {}
+};
+cc._NetworkErrorDialog._show = function (type, tips, confirmCb, cancelCb) {
+ var networkDialog = cc._NetworkErrorDialog();
+ var config;
+ switch (type) {
+ case "err_network":
+ {
+ config = cc._NetworkErrorDialog._config.networkError;
+ break;
+ }
+ case "err_no_space":
+ {
+ config = cc._NetworkErrorDialog._config.spaceError;
+ break;
+ }
+ case "err_verify":
+ {
+ config = cc._NetworkErrorDialog._config.verifyError;
+ break;
+ }
+ default:
+ {
+ cc.log("type is not found");
+ return;
+ }
+ }
+ if (!networkDialog.getParent()) {
+
+ config.confirmBtn = config.confirmBtn || {};
+ config.confirmBtn.callback = function () {
+ if (confirmCb)
+ confirmCb();
+ }
+
+ config.cancelBtn = config.cancelBtn || {};
+ config.cancelBtn.callback = function () {
+ if (cancelCb)
+ cancelCb();
+ }
+
+ config.messageLabel = config.messageLabel || {};
+ if (typeof config.messageLabel.text == "undefined") {
+ config.messageLabel.text = tips;
+ }
+
+ networkDialog.setConfig(config);
+ if (cc.director.getRunningScene()) {
+ cc.director.getRunningScene().addChild(networkDialog, INT_MAX);
+ } else {
+ cc.log("Current scene is null we can't show dialog");
+ }
+ }
+}
+
+cc._NetworkErrorDialog._setConfig = function (key, config) {
+ if (key && config) {
+ switch (key) {
+ case "err_network":
+ {
+ cc._NetworkErrorDialog._config.networkError = config;
+ break;
+ }
+ case "err_no_space":
+ {
+ cc._NetworkErrorDialog._config.spaceError = config;
+ break;
+ }
+ case "err_verify":
+ {
+ cc._NetworkErrorDialog._config.verifyError = config;
+ break;
+ }
+ }
+ }
+}
+
+cc.runtime = cc.runtime || {};
+
+cc.runtime.setOption = function (promptype, config) {
+ if (config) {
+ switch (promptype) {
+ case "network_error_dialog":
+ {
+ cc._NetworkErrorDialog._setConfig("err_network", config);
+ break;
+ }
+ case "no_space_error_dialog":
+ {
+ cc._NetworkErrorDialog._setConfig("err_no_space", config);
+ break;
+ }
+ case "verify_error_dialog":
+ {
+ cc._NetworkErrorDialog._setConfig("err_verify", config);
+ break;
+ }
+ default :
+ {
+ cc.log("promptype not found please check your promptype");
+ }
+ }
+ } else {
+ cc.log("config is null please check your config");
+ }
+}
+
+/**
+ * only use in JSB get network type
+ * @type {{}|*|cc.network}
+ */
+cc.network = cc.network || {};
+cc.network.type = {
+ NO_NETWORK: -1,
+ MOBILE: 0,
+ WIFI: 1
+}
+cc.network.preloadstatus = {
+ DOWNLOAD: 1,
+ UNZIP: 2
+}
+cc.runtime.network = cc.network;
+
+})();
diff --git a/extensions/spine/CCSkeleton.js b/extensions/spine/CCSkeleton.js
new file mode 100644
index 0000000000..9555725a9d
--- /dev/null
+++ b/extensions/spine/CCSkeleton.js
@@ -0,0 +1,407 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2014 Shengxiang Chen (Nero Chan)
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+/**
+ * The main namespace of Spine, all classes, functions, properties and constants of Spine are defined in this namespace
+ * @namespace
+ * @name sp
+ */
+var sp = sp || {};
+
+/**
+ * The vertex index of spine.
+ * @constant
+ * @type {{X1: number, Y1: number, X2: number, Y2: number, X3: number, Y3: number, X4: number, Y4: number}}
+ */
+sp.VERTEX_INDEX = {
+ X1: 0,
+ Y1: 1,
+ X2: 2,
+ Y2: 3,
+ X3: 4,
+ Y3: 5,
+ X4: 6,
+ Y4: 7
+};
+
+/**
+ * The attachment type of spine. It contains three type: REGION(0), BOUNDING_BOX(1), MESH(2) and SKINNED_MESH.
+ * @constant
+ * @type {{REGION: number, BOUNDING_BOX: number, REGION_SEQUENCE: number, MESH: number}}
+ */
+sp.ATTACHMENT_TYPE = {
+ REGION: 0,
+ BOUNDING_BOX: 1,
+ MESH: 2,
+ SKINNED_MESH:3
+};
+
+/**
+ *
+ * The skeleton of Spine.
+ * Skeleton has a reference to a SkeletonData and stores the state for skeleton instance,
+ * which consists of the current pose's bone SRT, slot colors, and which slot attachments are visible.
+ * Multiple skeletons can use the same SkeletonData (which includes all animations, skins, and attachments).
+ *
+ * @class
+ * @extends cc.Node
+ */
+sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{
+ _skeleton: null,
+ _rootBone: null,
+ _timeScale: 1,
+ _debugSlots: false,
+ _debugBones: false,
+ _premultipliedAlpha: false,
+ _ownsSkeletonData: null,
+ _atlas: null,
+ _blendFunc: null,
+
+ /**
+ * The constructor of sp.Skeleton. override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
+ */
+ ctor:function(skeletonDataFile, atlasFile, scale){
+ cc.Node.prototype.ctor.call(this);
+ this._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST};
+
+ if(arguments.length === 0)
+ this.init();
+ else
+ this.initWithArgs(skeletonDataFile, atlasFile, scale);
+ },
+
+ _createRenderCmd:function () {
+ if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ return new sp.Skeleton.CanvasRenderCmd(this);
+ else
+ return new sp.Skeleton.WebGLRenderCmd(this);
+ },
+
+ /**
+ * Initializes a sp.Skeleton. please do not call this function by yourself, you should pass the parameters to constructor to initialize it.
+ */
+ init: function () {
+ cc.Node.prototype.init.call(this);
+ //this.setOpacityModifyRGB(true);
+ this._blendFunc.src = cc.ONE;
+ this._blendFunc.dst = cc.ONE_MINUS_SRC_ALPHA;
+ this.scheduleUpdate();
+ },
+
+ /**
+ * Sets whether open debug slots.
+ * @param {boolean} enable true to open, false to close.
+ */
+ setDebugSolots:function(enable){
+ this._debugSlots = enable;
+ },
+
+ /**
+ * Sets whether open debug bones.
+ * @param {boolean} enable
+ */
+ setDebugBones:function(enable){
+ this._debugBones = enable;
+ },
+
+ /**
+ * Sets whether open debug slots.
+ * @param {boolean} enabled true to open, false to close.
+ */
+ setDebugSlotsEnabled: function(enabled) {
+ this._debugSlots = enabled;
+ },
+
+ /**
+ * Gets whether open debug slots.
+ * @returns {boolean} true to open, false to close.
+ */
+ getDebugSlotsEnabled: function() {
+ return this._debugSlots;
+ },
+
+ /**
+ * Sets whether open debug bones.
+ * @param {boolean} enabled
+ */
+ setDebugBonesEnabled: function(enabled) {
+ this._debugBones = enabled;
+ },
+
+ /**
+ * Gets whether open debug bones.
+ * @returns {boolean} true to open, false to close.
+ */
+ getDebugBonesEnabled: function() {
+ return this._debugBones;
+ },
+
+ /**
+ * Sets the time scale of sp.Skeleton.
+ * @param {Number} scale
+ */
+ setTimeScale:function(scale){
+ this._timeScale = scale;
+ },
+
+ getTimeScale: function(){
+ return this._timeScale;
+ },
+
+ /**
+ * Initializes sp.Skeleton with Data.
+ * @param {spine.SkeletonData|String} skeletonDataFile
+ * @param {String|spine.Atlas|spine.SkeletonData} atlasFile atlas filename or atlas data or owns SkeletonData
+ * @param {Number} [scale] scale can be specified on the JSON or binary loader which will scale the bone positions, image sizes, and animation translations.
+ */
+ initWithArgs: function (skeletonDataFile, atlasFile, scale) {
+ var argSkeletonFile = skeletonDataFile, argAtlasFile = atlasFile,
+ skeletonData, atlas, ownsSkeletonData;
+
+ if (cc.js.isString(argSkeletonFile)) {
+ if (cc.js.isString(argAtlasFile)) {
+ var data = cc.loader.getRes(argAtlasFile);
+ sp._atlasLoader.setAtlasFile(argAtlasFile);
+ atlas = new spine.Atlas(data, sp._atlasLoader);
+ } else {
+ atlas = atlasFile;
+ }
+ scale = scale || 1 / cc.director.getContentScaleFactor();
+
+ var attachmentLoader = new spine.AtlasAttachmentLoader(atlas);
+ var skeletonJsonReader = new spine.SkeletonJson(attachmentLoader);
+ skeletonJsonReader.scale = scale;
+
+ var skeletonJson = cc.loader.getRes(argSkeletonFile);
+ skeletonData = skeletonJsonReader.readSkeletonData(skeletonJson);
+ atlas.dispose(skeletonJsonReader);
+ ownsSkeletonData = true;
+ } else {
+ skeletonData = skeletonDataFile;
+ ownsSkeletonData = atlasFile;
+ }
+ this.setSkeletonData(skeletonData, ownsSkeletonData);
+ this.init();
+ },
+
+ /**
+ * Returns the bounding box of sp.Skeleton.
+ * @returns {cc.Rect}
+ */
+ getBoundingBox: function () {
+ var minX = cc.FLT_MAX, minY = cc.FLT_MAX, maxX = cc.FLT_MIN, maxY = cc.FLT_MIN;
+ var scaleX = this.getScaleX(), scaleY = this.getScaleY(), vertices = [],
+ slots = this._skeleton.slots, VERTEX = sp.VERTEX_INDEX;
+
+ for (var i = 0, slotCount = slots.length; i < slotCount; ++i) {
+ var slot = slots[i];
+ if (!slot.attachment || slot.attachment.type != sp.ATTACHMENT_TYPE.REGION)
+ continue;
+ var attachment = slot.attachment;
+ this._computeRegionAttachmentWorldVertices(attachment, slot.bone.skeleton.x, slot.bone.skeleton.y, slot.bone, vertices);
+ minX = Math.min(minX, vertices[VERTEX.X1] * scaleX, vertices[VERTEX.X4] * scaleX, vertices[VERTEX.X2] * scaleX, vertices[VERTEX.X3] * scaleX);
+ minY = Math.min(minY, vertices[VERTEX.Y1] * scaleY, vertices[VERTEX.Y4] * scaleY, vertices[VERTEX.Y2] * scaleY, vertices[VERTEX.Y3] * scaleY);
+ maxX = Math.max(maxX, vertices[VERTEX.X1] * scaleX, vertices[VERTEX.X4] * scaleX, vertices[VERTEX.X2] * scaleX, vertices[VERTEX.X3] * scaleX);
+ maxY = Math.max(maxY, vertices[VERTEX.Y1] * scaleY, vertices[VERTEX.Y4] * scaleY, vertices[VERTEX.Y2] * scaleY, vertices[VERTEX.Y3] * scaleY);
+ }
+ var position = this.getPosition();
+ return cc.rect(position.x + minX, position.y + minY, maxX - minX, maxY - minY);
+ },
+
+ _computeRegionAttachmentWorldVertices : function(self, x, y, bone, vertices){
+ var offset = self.offset, vertexIndex = sp.VERTEX_INDEX;
+ x += bone.worldX;
+ y += bone.worldY;
+ vertices[vertexIndex.X1] = offset[vertexIndex.X1] * bone.m00 + offset[vertexIndex.Y1] * bone.m01 + x;
+ vertices[vertexIndex.Y1] = offset[vertexIndex.X1] * bone.m10 + offset[vertexIndex.Y1] * bone.m11 + y;
+ vertices[vertexIndex.X2] = offset[vertexIndex.X2] * bone.m00 + offset[vertexIndex.Y2] * bone.m01 + x;
+ vertices[vertexIndex.Y2] = offset[vertexIndex.X2] * bone.m10 + offset[vertexIndex.Y2] * bone.m11 + y;
+ vertices[vertexIndex.X3] = offset[vertexIndex.X3] * bone.m00 + offset[vertexIndex.Y3] * bone.m01 + x;
+ vertices[vertexIndex.Y3] = offset[vertexIndex.X3] * bone.m10 + offset[vertexIndex.Y3] * bone.m11 + y;
+ vertices[vertexIndex.X4] = offset[vertexIndex.X4] * bone.m00 + offset[vertexIndex.Y4] * bone.m01 + x;
+ vertices[vertexIndex.Y4] = offset[vertexIndex.X4] * bone.m10 + offset[vertexIndex.Y4] * bone.m11 + y;
+ },
+
+ /**
+ * Computes the world SRT from the local SRT for each bone.
+ */
+ updateWorldTransform: function () {
+ this._skeleton.updateWorldTransform();
+ },
+
+ /**
+ * Sets the bones and slots to the setup pose.
+ */
+ setToSetupPose: function () {
+ this._skeleton.setToSetupPose();
+ },
+
+ /**
+ * Sets the bones to the setup pose, using the values from the `BoneData` list in the `SkeletonData`.
+ */
+ setBonesToSetupPose: function () {
+ this._skeleton.setBonesToSetupPose();
+ },
+
+ /**
+ * Sets the slots to the setup pose, using the values from the `SlotData` list in the `SkeletonData`.
+ */
+ setSlotsToSetupPose: function () {
+ this._skeleton.setSlotsToSetupPose();
+ },
+
+ /**
+ * Finds a bone by name. This does a string comparison for every bone.
+ * @param {String} boneName
+ * @returns {spine.Bone}
+ */
+ findBone: function (boneName) {
+ return this._skeleton.findBone(boneName);
+ },
+
+ /**
+ * Finds a slot by name. This does a string comparison for every slot.
+ * @param {String} slotName
+ * @returns {spine.Slot}
+ */
+ findSlot: function (slotName) {
+ return this._skeleton.findSlot(slotName);
+ },
+
+ /**
+ * Finds a skin by name and makes it the active skin. This does a string comparison for every skin. Note that setting the skin does not change which attachments are visible.
+ * @param {string} skinName
+ * @returns {spine.Skin}
+ */
+ setSkin: function (skinName) {
+ return this._skeleton.setSkinByName(skinName);
+ },
+
+ /**
+ * Returns the attachment for the slot and attachment name. The skeleton looks first in its skin, then in the skeleton dataâs default skin.
+ * @param {String} slotName
+ * @param {String} attachmentName
+ * @returns {spine.RegionAttachment|spine.BoundingBoxAttachment}
+ */
+ getAttachment: function (slotName, attachmentName) {
+ return this._skeleton.getAttachmentBySlotName(slotName, attachmentName);
+ },
+
+ /**
+ * Sets the attachment for the slot and attachment name. The skeleton looks first in its skin, then in the skeleton dataâs default skin.
+ * @param {String} slotName
+ * @param {String} attachmentName
+ */
+ setAttachment: function (slotName, attachmentName) {
+ this._skeleton.setAttachment(slotName, attachmentName);
+ },
+
+ /**
+ * Sets the premultiplied alpha value to sp.Skeleton.
+ * @param {Number} alpha
+ */
+ setOpacityModifyRGB: function (alpha) {
+ this._premultipliedAlpha = alpha;
+ },
+
+ /**
+ * Returns whether to enable premultiplied alpha.
+ * @returns {boolean}
+ */
+ isOpacityModifyRGB: function () {
+ return this._premultipliedAlpha;
+ },
+
+ /**
+ * Sets skeleton data to sp.Skeleton.
+ * @param {spine.SkeletonData} skeletonData
+ * @param {spine.SkeletonData} ownsSkeletonData
+ */
+ setSkeletonData: function (skeletonData, ownsSkeletonData) {
+ if(skeletonData.width != null && skeletonData.height != null)
+ this.setContentSize(skeletonData.width / cc.director.getContentScaleFactor(), skeletonData.height / cc.director.getContentScaleFactor());
+
+ this._skeleton = new spine.Skeleton(skeletonData);
+ this._skeleton.updateWorldTransform();
+ this._rootBone = this._skeleton.getRootBone();
+ this._ownsSkeletonData = ownsSkeletonData;
+
+ this._renderCmd._createChildFormSkeletonData();
+ },
+
+ /**
+ * Return the renderer of attachment.
+ * @param {spine.RegionAttachment|spine.BoundingBoxAttachment} regionAttachment
+ * @returns {cc.Node}
+ */
+ getTextureAtlas: function (regionAttachment) {
+ return regionAttachment.rendererObject.page.rendererObject;
+ },
+
+ /**
+ * Returns the blendFunc of sp.Skeleton.
+ * @returns {cc.BlendFunc}
+ */
+ getBlendFunc: function () {
+ return this._blendFunc;
+ },
+
+ /**
+ * Sets the blendFunc of sp.Skeleton.
+ * @param {cc.BlendFunc|Number} src
+ * @param {Number} [dst]
+ */
+ setBlendFunc: function (src, dst) {
+ var locBlendFunc = this._blendFunc;
+ if (dst === undefined) {
+ locBlendFunc.src = src.src;
+ locBlendFunc.dst = src.dst;
+ } else {
+ locBlendFunc.src = src;
+ locBlendFunc.dst = dst;
+ }
+ },
+
+ /**
+ * Update will be called automatically every frame if "scheduleUpdate" is called when the node is "live".
+ * @param {Number} dt Delta time since last update
+ */
+ update: function (dt) {
+ this._skeleton.update(dt);
+ }
+});
+
+/**
+ * Creates a skeleton object.
+ * @deprecated since v3.0, please use new sp.Skeleton(skeletonDataFile, atlasFile, scale) instead.
+ * @param {spine.SkeletonData|String} skeletonDataFile
+ * @param {String|spine.Atlas|spine.SkeletonData} atlasFile atlas filename or atlas data or owns SkeletonData
+ * @param {Number} [scale] scale can be specified on the JSON or binary loader which will scale the bone positions, image sizes, and animation translations.
+ * @returns {sp.Skeleton}
+ */
+sp.Skeleton.create = function (skeletonDataFile, atlasFile/* or atlas*/, scale) {
+ return new sp.Skeleton(skeletonDataFile, atlasFile, scale);
+};
\ No newline at end of file
diff --git a/extensions/spine/CCSkeletonAnimation.js b/extensions/spine/CCSkeletonAnimation.js
new file mode 100644
index 0000000000..54b0c17d4d
--- /dev/null
+++ b/extensions/spine/CCSkeletonAnimation.js
@@ -0,0 +1,348 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2014 Shengxiang Chen (Nero Chan)
+
+ 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.
+ ****************************************************************************/
+
+/**
+ * @ignore
+ */
+sp._atlasPage_createTexture_webGL = function (self, path) {
+ var texture = cc.textureCache.addImage(path);
+ self.rendererObject = new cc.TextureAtlas(texture, 128);
+ self.width = texture.getPixelWidth();
+ self.height = texture.getPixelHeight();
+};
+
+sp._atlasPage_createTexture_canvas = function(self, path) {
+ self._texture = cc.textureCache.addImage(path);
+};
+
+sp._atlasPage_disposeTexture = function (self) {
+ self.rendererObject.release();
+};
+
+sp._atlasLoader = {
+ spAtlasFile:null,
+ setAtlasFile:function(spAtlasFile){
+ this.spAtlasFile = spAtlasFile;
+ },
+ load:function(page, line, spAtlas){
+ var texturePath = cc.path.join(cc.path.dirname(this.spAtlasFile), line);
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ sp._atlasPage_createTexture_webGL(page,texturePath);
+ else
+ sp._atlasPage_createTexture_canvas(page,texturePath);
+ },
+ unload:function(obj){
+ }
+};
+
+/**
+ * The event type of spine skeleton animation. It contains event types: START(0), END(1), COMPLETE(2), EVENT(3).
+ * @constant
+ * @type {{START: number, END: number, COMPLETE: number, EVENT: number}}
+ */
+sp.ANIMATION_EVENT_TYPE = {
+ START: 0,
+ END: 1,
+ COMPLETE: 2,
+ EVENT: 3
+};
+
+sp.TrackEntryListeners = function(startListener, endListener, completeListener, eventListener){
+ this.startListener = startListener || null;
+ this.endListener = endListener || null;
+ this.completeListener = completeListener || null;
+ this.eventListener = eventListener || null;
+};
+
+sp.TrackEntryListeners.getListeners = function(entry){
+ if(!entry.rendererObject){
+ entry.rendererObject = new sp.TrackEntryListeners();
+ entry.listener = sp.trackEntryCallback;
+ }
+ return entry.rendererObject;
+};
+
+sp.trackEntryCallback = function(state, trackIndex, type, event, loopCount) {
+ state.rendererObject.onTrackEntryEvent(trackIndex, type, event, loopCount);
+};
+
+/**
+ * The skeleton animation of spine. It updates animation's state and skeleton's world transform.
+ * @class
+ * @extends sp.Skeleton
+ * @example
+ * var spineBoy = new sp.SkeletonAnimation('res/skeletons/spineboy.json', 'res/skeletons/spineboy.atlas');
+ * this.addChild(spineBoy, 4);
+ */
+sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{
+ _state: null,
+ _target: null,
+ _callback: null,
+
+ _ownsAnimationStateData: false,
+ _startListener: null,
+ _endListener: null,
+ _completeListener: null,
+ _eventListener: null,
+
+ /**
+ * Initializes a sp.SkeletonAnimation. please do not call this function by yourself, you should pass the parameters to constructor to initialize it.
+ * @override
+ */
+ init: function () {
+ sp.Skeleton.prototype.init.call(this);
+ this._ownsAnimationStateData = true;
+ this.setAnimationStateData(new spine.AnimationStateData(this._skeleton.data));
+ },
+
+ /**
+ * Sets animation state data to sp.SkeletonAnimation.
+ * @param {spine.AnimationStateData} stateData
+ */
+ setAnimationStateData: function (stateData) {
+ var state = new spine.AnimationState(stateData);
+ state.rendererObject = this;
+ state.onStart = this._onAnimationStateStart.bind(this);
+ state.onComplete = this._onAnimationStateComplete.bind(this);
+ state.onEnd = this._onAnimationStateEnd.bind(this);
+ state.onEvent = this._onAnimationStateEvent.bind(this);
+ this._state = state;
+ },
+
+ /**
+ * Mix applies all keyframe values, interpolated for the specified time and mixed with the current values.
+ * @param {String} fromAnimation
+ * @param {String} toAnimation
+ * @param {Number} duration
+ */
+ setMix: function (fromAnimation, toAnimation, duration) {
+ this._state.data.setMixByName(fromAnimation, toAnimation, duration);
+ },
+
+ /**
+ * Sets event listener of sp.SkeletonAnimation.
+ * @param {Object} target
+ * @param {Function} callback
+ */
+ setAnimationListener: function (target, callback) {
+ this._target = target;
+ this._callback = callback;
+ },
+
+ /**
+ * Set the current animation. Any queued animations are cleared.
+ * @param {Number} trackIndex
+ * @param {String} name
+ * @param {Boolean} loop
+ * @returns {spine.TrackEntry|null}
+ */
+ setAnimation: function (trackIndex, name, loop) {
+ var animation = this._skeleton.data.findAnimation(name);
+ if (!animation) {
+ cc.log("Spine: Animation not found: " + name);
+ return null;
+ }
+ return this._state.setAnimation(trackIndex, animation, loop);
+ },
+
+ /**
+ * Adds an animation to be played delay seconds after the current or last queued animation.
+ * @param {Number} trackIndex
+ * @param {String} name
+ * @param {Boolean} loop
+ * @param {Number} [delay=0]
+ * @returns {spine.TrackEntry|null}
+ */
+ addAnimation: function (trackIndex, name, loop, delay) {
+ delay = delay == null ? 0 : delay;
+ var animation = this._skeleton.data.findAnimation(name);
+ if (!animation) {
+ cc.log("Spine: Animation not found:" + name);
+ return null;
+ }
+ return this._state.addAnimation(trackIndex, animation, loop, delay);
+ },
+
+ /**
+ * Returns track entry by trackIndex.
+ * @param trackIndex
+ * @returns {spine.TrackEntry|null}
+ */
+ getCurrent: function (trackIndex) {
+ return this._state.getCurrent(trackIndex);
+ },
+
+ /**
+ * Clears all tracks of animation state.
+ */
+ clearTracks: function () {
+ this._state.clearTracks();
+ },
+
+ /**
+ * Clears track of animation state by trackIndex.
+ * @param {Number} trackIndex
+ */
+ clearTrack: function (trackIndex) {
+ this._state.clearTrack(trackIndex);
+ },
+
+ /**
+ * Update will be called automatically every frame if "scheduleUpdate" is called when the node is "live".
+ * It updates animation's state and skeleton's world transform.
+ * @param {Number} dt Delta time since last update
+ * @override
+ */
+ update: function (dt) {
+ this._super(dt);
+ dt *= this._timeScale;
+ this._state.update(dt);
+ this._state.apply(this._skeleton);
+ this._skeleton.updateWorldTransform();
+ this._renderCmd._updateChild();
+ },
+
+ /**
+ * Set the start event listener.
+ * @param {function} listener
+ */
+ setStartListener: function(listener){
+ this._startListener = listener;
+ },
+
+ /**
+ * Set the end event listener.
+ * @param {function} listener
+ */
+ setEndListener: function(listener) {
+ this._endListener = listener;
+ },
+
+ setCompleteListener: function(listener) {
+ this._completeListener = listener;
+ },
+
+ setEventListener: function(listener){
+ this._eventListener = listener;
+ },
+
+ setTrackStartListener: function(entry, listener){
+ sp.TrackEntryListeners.getListeners(entry).startListener = listener;
+ },
+
+ setTrackEndListener: function(entry, listener){
+ sp.TrackEntryListeners.getListeners(entry).endListener = listener;
+ },
+
+ setTrackCompleteListener: function(entry, listener){
+ sp.TrackEntryListeners.getListeners(entry).completeListener = listener;
+ },
+
+ setTrackEventListener: function(entry, listener){
+ sp.TrackEntryListeners.getListeners(entry).eventListener = listener;
+ },
+
+ onTrackEntryEvent: function(traceIndex, type, event, loopCount){
+ var entry = this._state.getCurrent(traceIndex);
+ if(!entry.rendererObject)
+ return;
+ var listeners = entry.rendererObject;
+ switch (type){
+ case sp.ANIMATION_EVENT_TYPE.START:
+ if(listeners.startListener)
+ listeners.startListener(traceIndex);
+ break;
+ case sp.ANIMATION_EVENT_TYPE.END:
+ if(listeners.endListener)
+ listeners.endListener(traceIndex);
+ break;
+ case sp.ANIMATION_EVENT_TYPE.COMPLETE:
+ if(listeners.completeListener)
+ listeners.completeListener(traceIndex, loopCount);
+ break;
+ case sp.ANIMATION_EVENT_TYPE.EVENT:
+ if(listeners.eventListener)
+ listeners.eventListener(traceIndex, event);
+ break;
+ }
+ },
+
+ onAnimationStateEvent: function(trackIndex, type, event, loopCount) {
+ switch(type){
+ case sp.ANIMATION_EVENT_TYPE.START:
+ if(this._startListener)
+ this._startListener(trackIndex);
+ break;
+ case sp.ANIMATION_EVENT_TYPE.END:
+ if(this._endListener)
+ this._endListener(trackIndex);
+ break;
+ case sp.ANIMATION_EVENT_TYPE.COMPLETE:
+ if(this._completeListener)
+ this._completeListener(trackIndex, loopCount);
+ break;
+ case sp.ANIMATION_EVENT_TYPE.EVENT:
+ if(this._eventListener)
+ this._eventListener(trackIndex, event);
+ break;
+ }
+ },
+
+ getState: function(){
+ return this._state;
+ },
+
+ _onAnimationStateStart: function (trackIndex) {
+ this._animationStateCallback(trackIndex, sp.ANIMATION_EVENT_TYPE.START, null, 0);
+ },
+ _onAnimationStateEnd: function (trackIndex) {
+ this._animationStateCallback(trackIndex, sp.ANIMATION_EVENT_TYPE.END, null, 0);
+ },
+ _onAnimationStateComplete: function (trackIndex, count) {
+ this._animationStateCallback(trackIndex, sp.ANIMATION_EVENT_TYPE.COMPLETE, null, count);
+ },
+ _onAnimationStateEvent: function (trackIndex, event) {
+ this._animationStateCallback(trackIndex, sp.ANIMATION_EVENT_TYPE.EVENT, event, 0);
+ },
+ _animationStateCallback: function (trackIndex, type, event, loopCount) {
+ this.onAnimationStateEvent(trackIndex, type, event, loopCount);
+ if (this._target && this._callback) {
+ this._callback.call(this._target, this, trackIndex, type, event, loopCount)
+ }
+ }
+});
+
+/**
+ * Creates a skeleton animation object.
+ * @deprecated since v3.0, please use new sp.SkeletonAnimation(skeletonDataFile, atlasFile, scale) instead.
+ * @param {spine.SkeletonData|String} skeletonDataFile
+ * @param {String|spine.Atlas|spine.SkeletonData} atlasFile atlas filename or atlas data or owns SkeletonData
+ * @param {Number} [scale] scale can be specified on the JSON or binary loader which will scale the bone positions, image sizes, and animation translations.
+ * @returns {sp.Skeleton}
+ */
+sp.SkeletonAnimation.create = function (skeletonDataFile, atlasFile/* or atlas*/, scale) {
+ return new sp.SkeletonAnimation(skeletonDataFile, atlasFile, scale);
+};
\ No newline at end of file
diff --git a/extensions/spine/CCSkeletonCanvasRenderCmd.js b/extensions/spine/CCSkeletonCanvasRenderCmd.js
new file mode 100644
index 0000000000..1b4f873cd1
--- /dev/null
+++ b/extensions/spine/CCSkeletonCanvasRenderCmd.js
@@ -0,0 +1,213 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+(function(){
+ sp.Skeleton.CanvasRenderCmd = function(renderableObject){
+ cc.Node.CanvasRenderCmd.call(this, renderableObject);
+ this._needDraw = true;
+ };
+
+ var proto = sp.Skeleton.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
+ proto.constructor = sp.Skeleton.CanvasRenderCmd;
+
+ proto.rendering = function (wrapper, scaleX, scaleY) {
+ var node = this._node, i, n, slot, slotNode;
+ wrapper = wrapper || cc._renderContext;
+
+ var locSkeleton = node._skeleton, drawOrder = locSkeleton.drawOrder;
+ for(i = 0, n = drawOrder.length; i < n; i++){
+ slot = drawOrder[i];
+ slotNode = slot._slotNode;
+ if(slotNode._visible && slotNode._renderCmd && slot.currentSprite){
+ slotNode._renderCmd.transform(this, true);
+ slot.currentSprite._renderCmd.rendering(wrapper, scaleX, scaleY);
+ slotNode._renderCmd._dirtyFlag = slot.currentSprite._renderCmd._dirtyFlag = 0;
+ }
+ }
+
+ if (!node._debugSlots && !node._debugBones)
+ return;
+
+ wrapper.setTransform(this._worldTransform, scaleX, scaleY);
+ wrapper.setGlobalAlpha(1);
+ var attachment, drawingUtil = cc._drawingUtil;
+ if (node._debugSlots) {
+ // Slots.
+ drawingUtil.setDrawColor(0, 0, 255, 255);
+ drawingUtil.setLineWidth(1);
+
+ var points = [];
+ for (i = 0, n = locSkeleton.slots.length; i < n; i++) {
+ slot = locSkeleton.drawOrder[i];
+ if (!slot.attachment || slot.attachment.type != sp.ATTACHMENT_TYPE.REGION)
+ continue;
+ attachment = slot.attachment;
+ this._updateRegionAttachmentSlot(attachment, slot, points);
+ drawingUtil.drawPoly(points, 4, true);
+ }
+ }
+
+ if (node._debugBones) {
+ // Bone lengths.
+ var bone;
+ drawingUtil.setLineWidth(2);
+ drawingUtil.setDrawColor(255, 0, 0, 255);
+
+ for (i = 0, n = locSkeleton.bones.length; i < n; i++) {
+ bone = locSkeleton.bones[i];
+ var x = bone.data.length * bone.m00 + bone.worldX;
+ var y = bone.data.length * bone.m10 + bone.worldY;
+ drawingUtil.drawLine(
+ {x: bone.worldX, y: bone.worldY},
+ {x: x, y: y});
+ }
+
+ // Bone origins.
+ drawingUtil.setPointSize(4);
+ drawingUtil.setDrawColor(0, 0, 255, 255); // Root bone is blue.
+
+ for (i = 0, n = locSkeleton.bones.length; i < n; i++) {
+ bone = locSkeleton.bones[i];
+ drawingUtil.drawPoint({x: bone.worldX, y: bone.worldY});
+ if (i === 0)
+ drawingUtil.setDrawColor(0, 255, 0, 255);
+ }
+ }
+ };
+
+ proto._updateRegionAttachmentSlot = function(attachment, slot, points) {
+ if(!points)
+ return;
+
+ var vertices = {}, VERTEX = sp.VERTEX_INDEX, bone = slot.bone;
+ attachment.computeVertices(bone.skeleton.x, bone.skeleton.y, bone, vertices);
+ points.length = 0;
+ points.push(cc.p(vertices[VERTEX.X1], vertices[VERTEX.Y1]));
+ points.push(cc.p(vertices[VERTEX.X4], vertices[VERTEX.Y4]));
+ points.push(cc.p(vertices[VERTEX.X3], vertices[VERTEX.Y3]));
+ points.push(cc.p(vertices[VERTEX.X2], vertices[VERTEX.Y2]));
+ };
+
+ proto._createChildFormSkeletonData = function(){
+ var node = this._node;
+ var locSkeleton = node._skeleton, spriteName, sprite;
+ for (var i = 0, n = locSkeleton.slots.length; i < n; i++) {
+ var slot = locSkeleton.slots[i], attachment = slot.attachment;
+ var slotNode = new cc.Node();
+ slot._slotNode = slotNode;
+
+ if(attachment instanceof spine.RegionAttachment){
+ spriteName = attachment.rendererObject.name;
+ sprite = this._createSprite(slot, attachment);
+ slot.currentSprite = sprite;
+ slot.currentSpriteName = spriteName;
+ slotNode.addChild(sprite);
+ } else if(attachment instanceof spine.MeshAttachment){
+ //todo for mesh
+ }
+ }
+ };
+
+ proto._createSprite = function(slot, attachment){
+ var rendererObject = attachment.rendererObject;
+ var texture = rendererObject.page._texture;
+ var rect = new cc.Rect(rendererObject.x, rendererObject.y, rendererObject.width, rendererObject.height);
+ var sprite = new cc.Sprite();
+ sprite.initWithTexture(rendererObject.page._texture, rect, rendererObject.rotate, false);
+ sprite._rect.width = attachment.width;
+ sprite._rect.height = attachment.height;
+ sprite.setContentSize(attachment.width, attachment.height);
+ sprite.setRotation(-attachment.rotation);
+ sprite.setScale(rendererObject.width / rendererObject.originalWidth * attachment.scaleX,
+ rendererObject.height / rendererObject.originalHeight * attachment.scaleY);
+
+ slot.sprites = slot.sprites || {};
+ slot.sprites[rendererObject.name] = sprite;
+
+ return sprite;
+ };
+
+ proto._updateChild = function(){
+ var locSkeleton = this._node._skeleton, slots = locSkeleton.slots;
+ var i, n, selSprite;
+
+ var slot, attachment, slotNode;
+ for(i = 0, n = slots.length; i < n; i++){
+ slot = slots[i];
+ attachment = slot.attachment;
+ slotNode = slot._slotNode;
+ if(!attachment){
+ slotNode.setVisible(false);
+ continue;
+ }
+ var type = attachment.type;
+ if (type === spine.AttachmentType.region){
+ if(attachment.rendererObject){
+ if(!slot.currentSpriteName || slot.currentSpriteName !== attachment.name){
+ var spriteName = attachment.rendererObject.name;
+ if(slot.currentSprite !== undefined)
+ slot.currentSprite.setVisible(false);
+ slot.sprites = slot.sprites ||{};
+ if(slot.sprites[spriteName] !== undefined)
+ slot.sprites[spriteName].setVisible(true);
+ else{
+ var sprite = this._createSprite(slot, attachment);
+ slotNode.addChild(sprite);
+ }
+ slot.currentSprite = slot.sprites[spriteName];
+ slot.currentSpriteName = spriteName;
+ }
+ }
+ var bone = slot.bone;
+ slotNode.setPosition(bone.worldX + attachment.x * bone.m00 + attachment.y * bone.m01,
+ bone.worldY + attachment.x * bone.m10 + attachment.y * bone.m11);
+ slotNode.setScale(bone.worldScaleX, bone.worldScaleY);
+
+ //set the color and opacity
+ selSprite = slot.currentSprite;
+ selSprite._flippedX = bone.worldFlipX;
+ selSprite._flippedY = bone.worldFlipY;
+ if(selSprite._flippedY || selSprite._flippedX){
+ slotNode.setRotation(bone.worldRotation);
+ selSprite.setRotation(attachment.rotation);
+ }else{
+ slotNode.setRotation(-bone.worldRotation);
+ selSprite.setRotation(-attachment.rotation);
+ }
+
+ //hack for sprite
+ selSprite._renderCmd._displayedOpacity = 0 | (locSkeleton.a * slot.a * 255);
+ var r = 0 | (locSkeleton.r * slot.r * 255), g = 0 | (locSkeleton.g * slot.g * 255), b = 0 | (locSkeleton.b * slot.b * 255);
+ selSprite.setColor(cc.color(r,g,b));
+ selSprite._renderCmd._updateColor();
+ } else if (type === spine.AttachmentType.skinnedmesh) {
+ //todo for mesh
+ } else {
+ slotNode.setVisible(false);
+ continue;
+ }
+ slotNode.setVisible(true);
+ }
+ };
+})();
\ No newline at end of file
diff --git a/extensions/spine/CCSkeletonWebGLRenderCmd.js b/extensions/spine/CCSkeletonWebGLRenderCmd.js
new file mode 100644
index 0000000000..b00b3c44c5
--- /dev/null
+++ b/extensions/spine/CCSkeletonWebGLRenderCmd.js
@@ -0,0 +1,260 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+(function(){
+ sp.Skeleton.WebGLRenderCmd = function (renderableObject) {
+ cc.Node.WebGLRenderCmd.call(this, renderableObject);
+ this._needDraw = true;
+ this.setShaderProgram(cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURECOLOR));
+ this._tmpQuad = new cc.V3F_C4B_T2F_Quad();
+ };
+
+ var proto = sp.Skeleton.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
+ proto.constructor = sp.Skeleton.WebGLRenderCmd;
+
+ proto.rendering = function (ctx) {
+ var node = this._node, tmpQuad = this._tmpQuad;
+ var color = node.getColor(), locSkeleton = node._skeleton;
+
+ var blendMode, textureAtlas, attachment, slot, i, n;
+ var locBlendFunc = node._blendFunc;
+ var premultiAlpha = node._premultipliedAlpha;
+
+ this._shaderProgram.use();
+ this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix);
+// cc.glBlendFunc(this._blendFunc.src, this._blendFunc.dst);
+ locSkeleton.r = color.r / 255;
+ locSkeleton.g = color.g / 255;
+ locSkeleton.b = color.b / 255;
+ locSkeleton.a = node.getOpacity() / 255;
+ if (premultiAlpha) {
+ locSkeleton.r *= locSkeleton.a;
+ locSkeleton.g *= locSkeleton.a;
+ locSkeleton.b *= locSkeleton.a;
+ }
+
+ //for (i = 0, n = locSkeleton.slots.length; i < n; i++) {
+ for (i = 0, n = locSkeleton.drawOrder.length; i < n; i++) {
+ slot = locSkeleton.drawOrder[i];
+ if (!slot.attachment)
+ continue;
+ attachment = slot.attachment;
+
+ switch(slot.attachment.type) {
+ case sp.ATTACHMENT_TYPE.REGION:
+ this._updateRegionAttachmentQuad(attachment, slot, tmpQuad, premultiAlpha);
+ break;
+ case sp.ATTACHMENT_TYPE.MESH:
+ this._updateMeshAttachmentQuad(attachment, slot, tmpQuad, premultiAlpha);
+ break;
+ case sp.ATTACHMENT_TYPE.SKINNED_MESH:
+ break;
+ default:
+ continue;
+ }
+
+ var regionTextureAtlas = node.getTextureAtlas(attachment);
+
+ if (slot.data.blendMode != blendMode) {
+ if (textureAtlas) {
+ textureAtlas.drawQuads();
+ textureAtlas.removeAllQuads();
+ }
+ blendMode = slot.data.blendMode;
+ switch (blendMode) {
+ case spine.BlendMode.additive:
+ cc.glBlendFunc(premultiAlpha ? cc.ONE : cc.SRC_ALPHA, cc.ONE);
+ break;
+ case spine.BlendMode.multiply:
+ cc.glBlendFunc(cc.DST_COLOR, cc.ONE_MINUS_SRC_ALPHA);
+ break;
+ case spine.BlendMode.screen:
+ cc.glBlendFunc(cc.ONE, cc.ONE_MINUS_SRC_COLOR);
+ break;
+ default:
+ cc.glBlendFunc(locBlendFunc.src, locBlendFunc.dst);
+ }
+ } else if (regionTextureAtlas != textureAtlas && textureAtlas) {
+ textureAtlas.drawQuads();
+ textureAtlas.removeAllQuads();
+ }
+ textureAtlas = regionTextureAtlas;
+
+ var quadCount = textureAtlas.getTotalQuads();
+ if (textureAtlas.getCapacity() == quadCount) {
+ textureAtlas.drawQuads();
+ textureAtlas.removeAllQuads();
+ if (!textureAtlas.resizeCapacity(textureAtlas.getCapacity() * 2))
+ return;
+ }
+
+ textureAtlas.updateQuad(tmpQuad, quadCount);
+ }
+
+ if (textureAtlas) {
+ textureAtlas.drawQuads();
+ textureAtlas.removeAllQuads();
+ }
+
+ if (node._debugBones || node._debugSlots) {
+ cc.kmGLMatrixMode(cc.KM_GL_MODELVIEW);
+ //cc.kmGLPushMatrixWitMat4(this._stackMatrix);
+ cc.current_stack.stack.push(cc.current_stack.top);
+ cc.current_stack.top = this._stackMatrix;
+ var drawingUtil = cc._drawingUtil;
+
+ if (node._debugSlots) {
+ // Slots.
+ drawingUtil.setDrawColor(0, 0, 255, 255);
+ drawingUtil.setLineWidth(1);
+
+ for (i = 0, n = locSkeleton.slots.length; i < n; i++) {
+ slot = locSkeleton.drawOrder[i];
+ if (!slot.attachment || slot.attachment.type != sp.ATTACHMENT_TYPE.REGION)
+ continue;
+ attachment = slot.attachment;
+ this._updateRegionAttachmentQuad(attachment, slot, tmpQuad);
+
+ var points = [];
+ points.push(cc.p(tmpQuad.bl.vertices.x, tmpQuad.bl.vertices.y));
+ points.push(cc.p(tmpQuad.br.vertices.x, tmpQuad.br.vertices.y));
+ points.push(cc.p(tmpQuad.tr.vertices.x, tmpQuad.tr.vertices.y));
+ points.push(cc.p(tmpQuad.tl.vertices.x, tmpQuad.tl.vertices.y));
+
+ drawingUtil.drawPoly(points, 4, true);
+ }
+ }
+
+ if (node._debugBones) {
+ // Bone lengths.
+ var bone;
+ drawingUtil.setLineWidth(2);
+ drawingUtil.setDrawColor(255, 0, 0, 255);
+
+ for (i = 0, n = locSkeleton.bones.length; i < n; i++) {
+ bone = locSkeleton.bones[i];
+ var x = bone.data.length * bone.m00 + bone.worldX;
+ var y = bone.data.length * bone.m10 + bone.worldY;
+ drawingUtil.drawLine(cc.p(bone.worldX, bone.worldY), cc.p(x, y));
+ }
+
+ // Bone origins.
+ drawingUtil.setPointSize(4);
+ drawingUtil.setDrawColor(0, 0, 255, 255); // Root bone is blue.
+
+ for (i = 0, n = locSkeleton.bones.length; i < n; i++) {
+ bone = locSkeleton.bones[i];
+ drawingUtil.drawPoint(cc.p(bone.worldX, bone.worldY));
+ if (i == 0) {
+ drawingUtil.setDrawColor(0, 255, 0, 255);
+ }
+ }
+ }
+ cc.kmGLPopMatrix();
+ }
+ };
+
+ proto._createChildFormSkeletonData = function(){};
+
+ proto._updateChild = function(){};
+
+ proto._updateRegionAttachmentQuad = function(self, slot, quad, premultipliedAlpha) {
+ var vertices = {};
+ self.computeVertices(slot.bone.skeleton.x, slot.bone.skeleton.y, slot.bone, vertices);
+ var r = slot.bone.skeleton.r * slot.r * 255;
+ var g = slot.bone.skeleton.g * slot.g * 255;
+ var b = slot.bone.skeleton.b * slot.b * 255;
+ var normalizedAlpha = slot.bone.skeleton.a * slot.a;
+
+ if (premultipliedAlpha) {
+ r *= normalizedAlpha;
+ g *= normalizedAlpha;
+ b *= normalizedAlpha;
+ }
+ var a = normalizedAlpha * 255;
+
+ quad.bl.colors.r = quad.tl.colors.r = quad.tr.colors.r = quad.br.colors.r = r;
+ quad.bl.colors.g = quad.tl.colors.g = quad.tr.colors.g = quad.br.colors.g = g;
+ quad.bl.colors.b = quad.tl.colors.b = quad.tr.colors.b = quad.br.colors.b = b;
+ quad.bl.colors.a = quad.tl.colors.a = quad.tr.colors.a = quad.br.colors.a = a;
+
+ var VERTEX = sp.VERTEX_INDEX;
+ quad.bl.vertices.x = vertices[VERTEX.X1];
+ quad.bl.vertices.y = vertices[VERTEX.Y1];
+ quad.tl.vertices.x = vertices[VERTEX.X2];
+ quad.tl.vertices.y = vertices[VERTEX.Y2];
+ quad.tr.vertices.x = vertices[VERTEX.X3];
+ quad.tr.vertices.y = vertices[VERTEX.Y3];
+ quad.br.vertices.x = vertices[VERTEX.X4];
+ quad.br.vertices.y = vertices[VERTEX.Y4];
+
+ quad.bl.texCoords.u = self.uvs[VERTEX.X1];
+ quad.bl.texCoords.v = self.uvs[VERTEX.Y1];
+ quad.tl.texCoords.u = self.uvs[VERTEX.X2];
+ quad.tl.texCoords.v = self.uvs[VERTEX.Y2];
+ quad.tr.texCoords.u = self.uvs[VERTEX.X3];
+ quad.tr.texCoords.v = self.uvs[VERTEX.Y3];
+ quad.br.texCoords.u = self.uvs[VERTEX.X4];
+ quad.br.texCoords.v = self.uvs[VERTEX.Y4];
+ };
+
+ proto._updateMeshAttachmentQuad = function(self, slot, quad, premultipliedAlpha) {
+ var vertices = {};
+ self.computeWorldVertices(slot.bone.x, slot.bone.y, slot, vertices);
+ var r = slot.bone.skeleton.r * slot.r * 255;
+ var g = slot.bone.skeleton.g * slot.g * 255;
+ var b = slot.bone.skeleton.b * slot.b * 255;
+ var normalizedAlpha = slot.bone.skeleton.a * slot.a;
+ if (premultipliedAlpha) {
+ r *= normalizedAlpha;
+ g *= normalizedAlpha;
+ b *= normalizedAlpha;
+ }
+ var a = normalizedAlpha * 255;
+
+ quad.bl.colors.r = quad.tl.colors.r = quad.tr.colors.r = quad.br.colors.r = r;
+ quad.bl.colors.g = quad.tl.colors.g = quad.tr.colors.g = quad.br.colors.g = g;
+ quad.bl.colors.b = quad.tl.colors.b = quad.tr.colors.b = quad.br.colors.b = b;
+ quad.bl.colors.a = quad.tl.colors.a = quad.tr.colors.a = quad.br.colors.a = a;
+
+ var VERTEX = sp.VERTEX_INDEX;
+ quad.bl.vertices.x = vertices[VERTEX.X1];
+ quad.bl.vertices.y = vertices[VERTEX.Y1];
+ quad.tl.vertices.x = vertices[VERTEX.X2];
+ quad.tl.vertices.y = vertices[VERTEX.Y2];
+ quad.tr.vertices.x = vertices[VERTEX.X3];
+ quad.tr.vertices.y = vertices[VERTEX.Y3];
+ quad.br.vertices.x = vertices[VERTEX.X4];
+ quad.br.vertices.y = vertices[VERTEX.Y4];
+
+ quad.bl.texCoords.u = self.uvs[VERTEX.X1];
+ quad.bl.texCoords.v = self.uvs[VERTEX.Y1];
+ quad.tl.texCoords.u = self.uvs[VERTEX.X2];
+ quad.tl.texCoords.v = self.uvs[VERTEX.Y2];
+ quad.tr.texCoords.u = self.uvs[VERTEX.X3];
+ quad.tr.texCoords.v = self.uvs[VERTEX.Y3];
+ quad.br.texCoords.u = self.uvs[VERTEX.X4];
+ quad.br.texCoords.v = self.uvs[VERTEX.Y4];
+ };
+})();
\ No newline at end of file
diff --git a/extensions/spine/Spine.js b/extensions/spine/Spine.js
new file mode 100644
index 0000000000..32af69d94e
--- /dev/null
+++ b/extensions/spine/Spine.js
@@ -0,0 +1,2636 @@
+/******************************************************************************
+ * Spine Runtimes Software License
+ * Version 2.3
+ *
+ * Copyright (c) 2013-2015, Esoteric Software
+ * All rights reserved.
+ *
+ * You are granted a perpetual, non-exclusive, non-sublicensable and
+ * non-transferable license to use, install, execute and perform the Spine
+ * Runtimes Software (the "Software") and derivative works solely for personal
+ * or internal use. Without the written permission of Esoteric Software (see
+ * Section 2 of the Spine Software License Agreement), you may not (a) modify,
+ * translate, adapt or otherwise create derivative works, improvements of the
+ * Software or develop new applications using the Software or (b) remove,
+ * delete, alter or obscure any trademarks or any copyright, trademark, patent
+ * or other intellectual property or proprietary rights notices on or in the
+ * Software, including any copy thereof. Redistributions in binary or source
+ * form must include this license and terms.
+ *
+ * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+ * EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *****************************************************************************/
+
+var spine = {
+ radDeg: 180 / Math.PI,
+ degRad: Math.PI / 180,
+ temp: [],
+ Float32Array: (typeof(Float32Array) === 'undefined') ? Array : Float32Array,
+ Uint16Array: (typeof(Uint16Array) === 'undefined') ? Array : Uint16Array
+};
+
+spine.BoneData = function (name, parent) {
+ this.name = name;
+ this.parent = parent;
+};
+spine.BoneData.prototype = {
+ length: 0,
+ x: 0, y: 0,
+ rotation: 0,
+ scaleX: 1, scaleY: 1,
+ inheritScale: true,
+ inheritRotation: true,
+ flipX: false, flipY: false
+};
+
+spine.BlendMode = {
+ normal: 0,
+ additive: 1,
+ multiply: 2,
+ screen: 3
+};
+
+spine.SlotData = function (name, boneData) {
+ this.name = name;
+ this.boneData = boneData;
+};
+spine.SlotData.prototype = {
+ r: 1, g: 1, b: 1, a: 1,
+ attachmentName: null,
+ blendMode: spine.BlendMode.normal
+};
+
+spine.IkConstraintData = function (name) {
+ this.name = name;
+ this.bones = [];
+};
+spine.IkConstraintData.prototype = {
+ target: null,
+ bendDirection: 1,
+ mix: 1
+};
+
+spine.Bone = function (boneData, skeleton, parent) {
+ this.data = boneData;
+ this.skeleton = skeleton;
+ this.parent = parent;
+ this.setToSetupPose();
+};
+spine.Bone.yDown = false;
+spine.Bone.prototype = {
+ x: 0, y: 0,
+ rotation: 0, rotationIK: 0,
+ scaleX: 1, scaleY: 1,
+ flipX: false, flipY: false,
+ m00: 0, m01: 0, worldX: 0, // a b x
+ m10: 0, m11: 0, worldY: 0, // c d y
+ worldRotation: 0,
+ worldScaleX: 1, worldScaleY: 1,
+ worldFlipX: false, worldFlipY: false,
+ updateWorldTransform: function () {
+ var parent = this.parent;
+ if (parent) {
+ this.worldX = this.x * parent.m00 + this.y * parent.m01 + parent.worldX;
+ this.worldY = this.x * parent.m10 + this.y * parent.m11 + parent.worldY;
+ if (this.data.inheritScale) {
+ this.worldScaleX = parent.worldScaleX * this.scaleX;
+ this.worldScaleY = parent.worldScaleY * this.scaleY;
+ } else {
+ this.worldScaleX = this.scaleX;
+ this.worldScaleY = this.scaleY;
+ }
+ this.worldRotation = this.data.inheritRotation ? (parent.worldRotation + this.rotationIK) : this.rotationIK;
+ this.worldFlipX = parent.worldFlipX != this.flipX;
+ this.worldFlipY = parent.worldFlipY != this.flipY;
+ } else {
+ var skeletonFlipX = this.skeleton.flipX, skeletonFlipY = this.skeleton.flipY;
+ this.worldX = skeletonFlipX ? -this.x : this.x;
+ this.worldY = (skeletonFlipY != spine.Bone.yDown) ? -this.y : this.y;
+ this.worldScaleX = this.scaleX;
+ this.worldScaleY = this.scaleY;
+ this.worldRotation = this.rotationIK;
+ this.worldFlipX = skeletonFlipX != this.flipX;
+ this.worldFlipY = skeletonFlipY != this.flipY;
+ }
+ var radians = this.worldRotation * spine.degRad;
+ var cos = Math.cos(radians);
+ var sin = Math.sin(radians);
+ if (this.worldFlipX) {
+ this.m00 = -cos * this.worldScaleX;
+ this.m01 = sin * this.worldScaleY;
+ } else {
+ this.m00 = cos * this.worldScaleX;
+ this.m01 = -sin * this.worldScaleY;
+ }
+ if (this.worldFlipY != spine.Bone.yDown) {
+ this.m10 = -sin * this.worldScaleX;
+ this.m11 = -cos * this.worldScaleY;
+ } else {
+ this.m10 = sin * this.worldScaleX;
+ this.m11 = cos * this.worldScaleY;
+ }
+ },
+ setToSetupPose: function () {
+ var data = this.data;
+ this.x = data.x;
+ this.y = data.y;
+ this.rotation = data.rotation;
+ this.rotationIK = this.rotation;
+ this.scaleX = data.scaleX;
+ this.scaleY = data.scaleY;
+ this.flipX = data.flipX;
+ this.flipY = data.flipY;
+ },
+ worldToLocal: function (world) {
+ var dx = world[0] - this.worldX, dy = world[1] - this.worldY;
+ var m00 = this.m00, m10 = this.m10, m01 = this.m01, m11 = this.m11;
+ if (this.worldFlipX != (this.worldFlipY != spine.Bone.yDown)) {
+ m00 = -m00;
+ m11 = -m11;
+ }
+ var invDet = 1 / (m00 * m11 - m01 * m10);
+ world[0] = dx * m00 * invDet - dy * m01 * invDet;
+ world[1] = dy * m11 * invDet - dx * m10 * invDet;
+ },
+ localToWorld: function (local) {
+ var localX = local[0], localY = local[1];
+ local[0] = localX * this.m00 + localY * this.m01 + this.worldX;
+ local[1] = localX * this.m10 + localY * this.m11 + this.worldY;
+ }
+};
+
+spine.Slot = function (slotData, bone) {
+ this.data = slotData;
+ this.bone = bone;
+ this.setToSetupPose();
+};
+spine.Slot.prototype = {
+ r: 1, g: 1, b: 1, a: 1,
+ _attachmentTime: 0,
+ attachment: null,
+ attachmentVertices: [],
+ setAttachment: function (attachment) {
+ this.attachment = attachment;
+ this._attachmentTime = this.bone.skeleton.time;
+ this.attachmentVertices.length = 0;
+ },
+ setAttachmentTime: function (time) {
+ this._attachmentTime = this.bone.skeleton.time - time;
+ },
+ getAttachmentTime: function () {
+ return this.bone.skeleton.time - this._attachmentTime;
+ },
+ setToSetupPose: function () {
+ var data = this.data;
+ this.r = data.r;
+ this.g = data.g;
+ this.b = data.b;
+ this.a = data.a;
+
+ var slotDatas = this.bone.skeleton.data.slots;
+ for (var i = 0, n = slotDatas.length; i < n; i++) {
+ if (slotDatas[i] == data) {
+ this.setAttachment(!data.attachmentName ? null : this.bone.skeleton.getAttachmentBySlotIndex(i, data.attachmentName));
+ break;
+ }
+ }
+ }
+};
+
+spine.IkConstraint = function (data, skeleton) {
+ this.data = data;
+ this.mix = data.mix;
+ this.bendDirection = data.bendDirection;
+
+ this.bones = [];
+ for (var i = 0, n = data.bones.length; i < n; i++)
+ this.bones.push(skeleton.findBone(data.bones[i].name));
+ this.target = skeleton.findBone(data.target.name);
+};
+spine.IkConstraint.prototype = {
+ apply: function () {
+ var target = this.target;
+ var bones = this.bones;
+ switch (bones.length) {
+ case 1:
+ spine.IkConstraint.apply1(bones[0], target.worldX, target.worldY, this.mix);
+ break;
+ case 2:
+ spine.IkConstraint.apply2(bones[0], bones[1], target.worldX, target.worldY, this.bendDirection, this.mix);
+ break;
+ }
+ }
+};
+/** Adjusts the bone rotation so the tip is as close to the target position as possible. The target is specified in the world
+ * coordinate system. */
+spine.IkConstraint.apply1 = function (bone, targetX, targetY, alpha) {
+ var parentRotation = (!bone.data.inheritRotation || !bone.parent) ? 0 : bone.parent.worldRotation;
+ var rotation = bone.rotation;
+ var rotationIK = Math.atan2(targetY - bone.worldY, targetX - bone.worldX) * spine.radDeg;
+ if (bone.worldFlipX != (bone.worldFlipY != spine.Bone.yDown)) rotationIK = -rotationIK;
+ rotationIK -= parentRotation;
+ bone.rotationIK = rotation + (rotationIK - rotation) * alpha;
+};
+/** Adjusts the parent and child bone rotations so the tip of the child is as close to the target position as possible. The
+ * target is specified in the world coordinate system.
+ * @param child Any descendant bone of the parent. */
+spine.IkConstraint.apply2 = function (parent, child, targetX, targetY, bendDirection, alpha) {
+ var childRotation = child.rotation, parentRotation = parent.rotation;
+ if (!alpha) {
+ child.rotationIK = childRotation;
+ parent.rotationIK = parentRotation;
+ return;
+ }
+ var positionX, positionY, tempPosition = spine.temp;
+ var parentParent = parent.parent;
+ if (parentParent) {
+ tempPosition[0] = targetX;
+ tempPosition[1] = targetY;
+ parentParent.worldToLocal(tempPosition);
+ targetX = (tempPosition[0] - parent.x) * parentParent.worldScaleX;
+ targetY = (tempPosition[1] - parent.y) * parentParent.worldScaleY;
+ } else {
+ targetX -= parent.x;
+ targetY -= parent.y;
+ }
+ if (child.parent == parent) {
+ positionX = child.x;
+ positionY = child.y;
+ } else {
+ tempPosition[0] = child.x;
+ tempPosition[1] = child.y;
+ child.parent.localToWorld(tempPosition);
+ parent.worldToLocal(tempPosition);
+ positionX = tempPosition[0];
+ positionY = tempPosition[1];
+ }
+ var childX = positionX * parent.worldScaleX, childY = positionY * parent.worldScaleY;
+ var offset = Math.atan2(childY, childX);
+ var len1 = Math.sqrt(childX * childX + childY * childY), len2 = child.data.length * child.worldScaleX;
+ // Based on code by Ryan Juckett with permission: Copyright (c) 2008-2009 Ryan Juckett, http://www.ryanjuckett.com/
+ var cosDenom = 2 * len1 * len2;
+ if (cosDenom < 0.0001) {
+ child.rotationIK = childRotation + (Math.atan2(targetY, targetX) * spine.radDeg - parentRotation - childRotation) * alpha;
+ return;
+ }
+ var cos = (targetX * targetX + targetY * targetY - len1 * len1 - len2 * len2) / cosDenom;
+ if (cos < -1)
+ cos = -1;
+ else if (cos > 1)
+ cos = 1;
+ var childAngle = Math.acos(cos) * bendDirection;
+ var adjacent = len1 + len2 * cos, opposite = len2 * Math.sin(childAngle);
+ var parentAngle = Math.atan2(targetY * adjacent - targetX * opposite, targetX * adjacent + targetY * opposite);
+ var rotation = (parentAngle - offset) * spine.radDeg - parentRotation;
+ if (rotation > 180)
+ rotation -= 360;
+ else if (rotation < -180) //
+ rotation += 360;
+ parent.rotationIK = parentRotation + rotation * alpha;
+ rotation = (childAngle + offset) * spine.radDeg - childRotation;
+ if (rotation > 180)
+ rotation -= 360;
+ else if (rotation < -180) //
+ rotation += 360;
+ child.rotationIK = childRotation + (rotation + parent.worldRotation - child.parent.worldRotation) * alpha;
+};
+
+spine.Skin = function (name) {
+ this.name = name;
+ this.attachments = {};
+};
+spine.Skin.prototype = {
+ addAttachment: function (slotIndex, name, attachment) {
+ this.attachments[slotIndex + ":" + name] = attachment;
+ },
+ getAttachment: function (slotIndex, name) {
+ return this.attachments[slotIndex + ":" + name];
+ },
+ _attachAll: function (skeleton, oldSkin) {
+ for (var key in oldSkin.attachments) {
+ var colon = key.indexOf(":");
+ var slotIndex = parseInt(key.substring(0, colon));
+ var name = key.substring(colon + 1);
+ var slot = skeleton.slots[slotIndex];
+ if (slot.attachment && slot.attachment.name == name) {
+ var attachment = this.getAttachment(slotIndex, name);
+ if (attachment) slot.setAttachment(attachment);
+ }
+ }
+ }
+};
+
+spine.Animation = function (name, timelines, duration) {
+ this.name = name;
+ this.timelines = timelines;
+ this.duration = duration;
+};
+spine.Animation.prototype = {
+ apply: function (skeleton, lastTime, time, loop, events) {
+ if (loop && this.duration != 0) {
+ time %= this.duration;
+ lastTime %= this.duration;
+ }
+ var timelines = this.timelines;
+ for (var i = 0, n = timelines.length; i < n; i++)
+ timelines[i].apply(skeleton, lastTime, time, events, 1);
+ },
+ mix: function (skeleton, lastTime, time, loop, events, alpha) {
+ if (loop && this.duration != 0) {
+ time %= this.duration;
+ lastTime %= this.duration;
+ }
+ var timelines = this.timelines;
+ for (var i = 0, n = timelines.length; i < n; i++)
+ timelines[i].apply(skeleton, lastTime, time, events, alpha);
+ }
+};
+spine.Animation.binarySearch = function (values, target, step) {
+ var low = 0;
+ var high = Math.floor(values.length / step) - 2;
+ if (!high) return step;
+ var current = high >>> 1;
+ while (true) {
+ if (values[(current + 1) * step] <= target)
+ low = current + 1;
+ else
+ high = current;
+ if (low == high) return (low + 1) * step;
+ current = (low + high) >>> 1;
+ }
+};
+spine.Animation.binarySearch1 = function (values, target) {
+ var low = 0;
+ var high = values.length - 2;
+ if (!high) return 1;
+ var current = high >>> 1;
+ while (true) {
+ if (values[current + 1] <= target)
+ low = current + 1;
+ else
+ high = current;
+ if (low == high) return low + 1;
+ current = (low + high) >>> 1;
+ }
+};
+spine.Animation.linearSearch = function (values, target, step) {
+ for (var i = 0, last = values.length - step; i <= last; i += step)
+ if (values[i] > target) return i;
+ return -1;
+};
+
+spine.Curves = function (frameCount) {
+ this.curves = []; // type, x, y, ...
+ //this.curves.length = (frameCount - 1) * 19/*BEZIER_SIZE*/;
+};
+spine.Curves.prototype = {
+ setLinear: function (frameIndex) {
+ this.curves[frameIndex * 19/*BEZIER_SIZE*/] = 0/*LINEAR*/;
+ },
+ setStepped: function (frameIndex) {
+ this.curves[frameIndex * 19/*BEZIER_SIZE*/] = 1/*STEPPED*/;
+ },
+ /** Sets the control handle positions for an interpolation bezier curve used to transition from this keyframe to the next.
+ * cx1 and cx2 are from 0 to 1, representing the percent of time between the two keyframes. cy1 and cy2 are the percent of
+ * the difference between the keyframe's values. */
+ setCurve: function (frameIndex, cx1, cy1, cx2, cy2) {
+ var subdiv1 = 1 / 10/*BEZIER_SEGMENTS*/, subdiv2 = subdiv1 * subdiv1, subdiv3 = subdiv2 * subdiv1;
+ var pre1 = 3 * subdiv1, pre2 = 3 * subdiv2, pre4 = 6 * subdiv2, pre5 = 6 * subdiv3;
+ var tmp1x = -cx1 * 2 + cx2, tmp1y = -cy1 * 2 + cy2, tmp2x = (cx1 - cx2) * 3 + 1, tmp2y = (cy1 - cy2) * 3 + 1;
+ var dfx = cx1 * pre1 + tmp1x * pre2 + tmp2x * subdiv3, dfy = cy1 * pre1 + tmp1y * pre2 + tmp2y * subdiv3;
+ var ddfx = tmp1x * pre4 + tmp2x * pre5, ddfy = tmp1y * pre4 + tmp2y * pre5;
+ var dddfx = tmp2x * pre5, dddfy = tmp2y * pre5;
+
+ var i = frameIndex * 19/*BEZIER_SIZE*/;
+ var curves = this.curves;
+ curves[i++] = 2/*BEZIER*/;
+
+ var x = dfx, y = dfy;
+ for (var n = i + 19/*BEZIER_SIZE*/ - 1; i < n; i += 2) {
+ curves[i] = x;
+ curves[i + 1] = y;
+ dfx += ddfx;
+ dfy += ddfy;
+ ddfx += dddfx;
+ ddfy += dddfy;
+ x += dfx;
+ y += dfy;
+ }
+ },
+ getCurvePercent: function (frameIndex, percent) {
+ percent = percent < 0 ? 0 : (percent > 1 ? 1 : percent);
+ var curves = this.curves;
+ var i = frameIndex * 19/*BEZIER_SIZE*/;
+ var type = curves[i];
+ if (type === 0/*LINEAR*/) return percent;
+ if (type == 1/*STEPPED*/) return 0;
+ i++;
+ var x = 0;
+ for (var start = i, n = i + 19/*BEZIER_SIZE*/ - 1; i < n; i += 2) {
+ x = curves[i];
+ if (x >= percent) {
+ var prevX, prevY;
+ if (i == start) {
+ prevX = 0;
+ prevY = 0;
+ } else {
+ prevX = curves[i - 2];
+ prevY = curves[i - 1];
+ }
+ return prevY + (curves[i + 1] - prevY) * (percent - prevX) / (x - prevX);
+ }
+ }
+ var y = curves[i - 1];
+ return y + (1 - y) * (percent - x) / (1 - x); // Last point is 1,1.
+ }
+};
+
+spine.RotateTimeline = function (frameCount) {
+ this.curves = new spine.Curves(frameCount);
+ this.frames = []; // time, angle, ...
+ this.frames.length = frameCount * 2;
+};
+spine.RotateTimeline.prototype = {
+ boneIndex: 0,
+ getFrameCount: function () {
+ return this.frames.length / 2;
+ },
+ setFrame: function (frameIndex, time, angle) {
+ frameIndex *= 2;
+ this.frames[frameIndex] = time;
+ this.frames[frameIndex + 1] = angle;
+ },
+ apply: function (skeleton, lastTime, time, firedEvents, alpha) {
+ var frames = this.frames;
+ if (time < frames[0]) return; // Time is before first frame.
+
+ var bone = skeleton.bones[this.boneIndex];
+
+ if (time >= frames[frames.length - 2]) { // Time is after last frame.
+ var amount = bone.data.rotation + frames[frames.length - 1] - bone.rotation;
+ while (amount > 180)
+ amount -= 360;
+ while (amount < -180)
+ amount += 360;
+ bone.rotation += amount * alpha;
+ return;
+ }
+
+ // Interpolate between the previous frame and the current frame.
+ var frameIndex = spine.Animation.binarySearch(frames, time, 2);
+ var prevFrameValue = frames[frameIndex - 1];
+ var frameTime = frames[frameIndex];
+ var percent = 1 - (time - frameTime) / (frames[frameIndex - 2/*PREV_FRAME_TIME*/] - frameTime);
+ percent = this.curves.getCurvePercent(frameIndex / 2 - 1, percent);
+
+ var amount = frames[frameIndex + 1/*FRAME_VALUE*/] - prevFrameValue;
+ while (amount > 180)
+ amount -= 360;
+ while (amount < -180)
+ amount += 360;
+ amount = bone.data.rotation + (prevFrameValue + amount * percent) - bone.rotation;
+ while (amount > 180)
+ amount -= 360;
+ while (amount < -180)
+ amount += 360;
+ bone.rotation += amount * alpha;
+ }
+};
+
+spine.TranslateTimeline = function (frameCount) {
+ this.curves = new spine.Curves(frameCount);
+ this.frames = []; // time, x, y, ...
+ this.frames.length = frameCount * 3;
+};
+spine.TranslateTimeline.prototype = {
+ boneIndex: 0,
+ getFrameCount: function () {
+ return this.frames.length / 3;
+ },
+ setFrame: function (frameIndex, time, x, y) {
+ frameIndex *= 3;
+ this.frames[frameIndex] = time;
+ this.frames[frameIndex + 1] = x;
+ this.frames[frameIndex + 2] = y;
+ },
+ apply: function (skeleton, lastTime, time, firedEvents, alpha) {
+ var frames = this.frames;
+ if (time < frames[0]) return; // Time is before first frame.
+
+ var bone = skeleton.bones[this.boneIndex];
+
+ if (time >= frames[frames.length - 3]) { // Time is after last frame.
+ bone.x += (bone.data.x + frames[frames.length - 2] - bone.x) * alpha;
+ bone.y += (bone.data.y + frames[frames.length - 1] - bone.y) * alpha;
+ return;
+ }
+
+ // Interpolate between the previous frame and the current frame.
+ var frameIndex = spine.Animation.binarySearch(frames, time, 3);
+ var prevFrameX = frames[frameIndex - 2];
+ var prevFrameY = frames[frameIndex - 1];
+ var frameTime = frames[frameIndex];
+ var percent = 1 - (time - frameTime) / (frames[frameIndex + -3/*PREV_FRAME_TIME*/] - frameTime);
+ percent = this.curves.getCurvePercent(frameIndex / 3 - 1, percent);
+
+ bone.x += (bone.data.x + prevFrameX + (frames[frameIndex + 1/*FRAME_X*/] - prevFrameX) * percent - bone.x) * alpha;
+ bone.y += (bone.data.y + prevFrameY + (frames[frameIndex + 2/*FRAME_Y*/] - prevFrameY) * percent - bone.y) * alpha;
+ }
+};
+
+spine.ScaleTimeline = function (frameCount) {
+ this.curves = new spine.Curves(frameCount);
+ this.frames = []; // time, x, y, ...
+ this.frames.length = frameCount * 3;
+};
+spine.ScaleTimeline.prototype = {
+ boneIndex: 0,
+ getFrameCount: function () {
+ return this.frames.length / 3;
+ },
+ setFrame: function (frameIndex, time, x, y) {
+ frameIndex *= 3;
+ this.frames[frameIndex] = time;
+ this.frames[frameIndex + 1] = x;
+ this.frames[frameIndex + 2] = y;
+ },
+ apply: function (skeleton, lastTime, time, firedEvents, alpha) {
+ var frames = this.frames;
+ if (time < frames[0]) return; // Time is before first frame.
+
+ var bone = skeleton.bones[this.boneIndex];
+
+ if (time >= frames[frames.length - 3]) { // Time is after last frame.
+ bone.scaleX += (bone.data.scaleX * frames[frames.length - 2] - bone.scaleX) * alpha;
+ bone.scaleY += (bone.data.scaleY * frames[frames.length - 1] - bone.scaleY) * alpha;
+ return;
+ }
+
+ // Interpolate between the previous frame and the current frame.
+ var frameIndex = spine.Animation.binarySearch(frames, time, 3);
+ var prevFrameX = frames[frameIndex - 2];
+ var prevFrameY = frames[frameIndex - 1];
+ var frameTime = frames[frameIndex];
+ var percent = 1 - (time - frameTime) / (frames[frameIndex + -3/*PREV_FRAME_TIME*/] - frameTime);
+ percent = this.curves.getCurvePercent(frameIndex / 3 - 1, percent);
+
+ bone.scaleX += (bone.data.scaleX * (prevFrameX + (frames[frameIndex + 1/*FRAME_X*/] - prevFrameX) * percent) - bone.scaleX) * alpha;
+ bone.scaleY += (bone.data.scaleY * (prevFrameY + (frames[frameIndex + 2/*FRAME_Y*/] - prevFrameY) * percent) - bone.scaleY) * alpha;
+ }
+};
+
+spine.ColorTimeline = function (frameCount) {
+ this.curves = new spine.Curves(frameCount);
+ this.frames = []; // time, r, g, b, a, ...
+ this.frames.length = frameCount * 5;
+};
+spine.ColorTimeline.prototype = {
+ slotIndex: 0,
+ getFrameCount: function () {
+ return this.frames.length / 5;
+ },
+ setFrame: function (frameIndex, time, r, g, b, a) {
+ frameIndex *= 5;
+ this.frames[frameIndex] = time;
+ this.frames[frameIndex + 1] = r;
+ this.frames[frameIndex + 2] = g;
+ this.frames[frameIndex + 3] = b;
+ this.frames[frameIndex + 4] = a;
+ },
+ apply: function (skeleton, lastTime, time, firedEvents, alpha) {
+ var frames = this.frames;
+ if (time < frames[0]) return; // Time is before first frame.
+
+ var r, g, b, a;
+ if (time >= frames[frames.length - 5]) {
+ // Time is after last frame.
+ var i = frames.length - 1;
+ r = frames[i - 3];
+ g = frames[i - 2];
+ b = frames[i - 1];
+ a = frames[i];
+ } else {
+ // Interpolate between the previous frame and the current frame.
+ var frameIndex = spine.Animation.binarySearch(frames, time, 5);
+ var prevFrameR = frames[frameIndex - 4];
+ var prevFrameG = frames[frameIndex - 3];
+ var prevFrameB = frames[frameIndex - 2];
+ var prevFrameA = frames[frameIndex - 1];
+ var frameTime = frames[frameIndex];
+ var percent = 1 - (time - frameTime) / (frames[frameIndex - 5/*PREV_FRAME_TIME*/] - frameTime);
+ percent = this.curves.getCurvePercent(frameIndex / 5 - 1, percent);
+
+ r = prevFrameR + (frames[frameIndex + 1/*FRAME_R*/] - prevFrameR) * percent;
+ g = prevFrameG + (frames[frameIndex + 2/*FRAME_G*/] - prevFrameG) * percent;
+ b = prevFrameB + (frames[frameIndex + 3/*FRAME_B*/] - prevFrameB) * percent;
+ a = prevFrameA + (frames[frameIndex + 4/*FRAME_A*/] - prevFrameA) * percent;
+ }
+ var slot = skeleton.slots[this.slotIndex];
+ if (alpha < 1) {
+ slot.r += (r - slot.r) * alpha;
+ slot.g += (g - slot.g) * alpha;
+ slot.b += (b - slot.b) * alpha;
+ slot.a += (a - slot.a) * alpha;
+ } else {
+ slot.r = r;
+ slot.g = g;
+ slot.b = b;
+ slot.a = a;
+ }
+ }
+};
+
+spine.AttachmentTimeline = function (frameCount) {
+ this.curves = new spine.Curves(frameCount);
+ this.frames = []; // time, ...
+ this.frames.length = frameCount;
+ this.attachmentNames = [];
+ this.attachmentNames.length = frameCount;
+};
+spine.AttachmentTimeline.prototype = {
+ slotIndex: 0,
+ getFrameCount: function () {
+ return this.frames.length;
+ },
+ setFrame: function (frameIndex, time, attachmentName) {
+ this.frames[frameIndex] = time;
+ this.attachmentNames[frameIndex] = attachmentName;
+ },
+ apply: function (skeleton, lastTime, time, firedEvents, alpha) {
+ var frames = this.frames;
+ if (time < frames[0]) {
+ if (lastTime > time) this.apply(skeleton, lastTime, Number.MAX_VALUE, null, 0);
+ return;
+ } else if (lastTime > time) //
+ lastTime = -1;
+
+ var frameIndex = time >= frames[frames.length - 1] ? frames.length - 1 : spine.Animation.binarySearch1(frames, time) - 1;
+ if (frames[frameIndex] < lastTime) return;
+
+ var attachmentName = this.attachmentNames[frameIndex];
+ skeleton.slots[this.slotIndex].setAttachment(
+ !attachmentName ? null : skeleton.getAttachmentBySlotIndex(this.slotIndex, attachmentName));
+ }
+};
+
+spine.EventTimeline = function (frameCount) {
+ this.frames = []; // time, ...
+ this.frames.length = frameCount;
+ this.events = [];
+ this.events.length = frameCount;
+};
+spine.EventTimeline.prototype = {
+ getFrameCount: function () {
+ return this.frames.length;
+ },
+ setFrame: function (frameIndex, time, event) {
+ this.frames[frameIndex] = time;
+ this.events[frameIndex] = event;
+ },
+ /** Fires events for frames > lastTime and <= time. */
+ apply: function (skeleton, lastTime, time, firedEvents, alpha) {
+ if (!firedEvents) return;
+
+ var frames = this.frames;
+ var frameCount = frames.length;
+
+ if (lastTime > time) { // Fire events after last time for looped animations.
+ this.apply(skeleton, lastTime, Number.MAX_VALUE, firedEvents, alpha);
+ lastTime = -1;
+ } else if (lastTime >= frames[frameCount - 1]) // Last time is after last frame.
+ return;
+ if (time < frames[0]) return; // Time is before first frame.
+
+ var frameIndex;
+ if (lastTime < frames[0])
+ frameIndex = 0;
+ else {
+ frameIndex = spine.Animation.binarySearch1(frames, lastTime);
+ var frame = frames[frameIndex];
+ while (frameIndex > 0) { // Fire multiple events with the same frame.
+ if (frames[frameIndex - 1] != frame) break;
+ frameIndex--;
+ }
+ }
+ var events = this.events;
+ for (; frameIndex < frameCount && time >= frames[frameIndex]; frameIndex++)
+ firedEvents.push(events[frameIndex]);
+ }
+};
+
+spine.DrawOrderTimeline = function (frameCount) {
+ this.frames = []; // time, ...
+ this.frames.length = frameCount;
+ this.drawOrders = [];
+ this.drawOrders.length = frameCount;
+};
+spine.DrawOrderTimeline.prototype = {
+ getFrameCount: function () {
+ return this.frames.length;
+ },
+ setFrame: function (frameIndex, time, drawOrder) {
+ this.frames[frameIndex] = time;
+ this.drawOrders[frameIndex] = drawOrder;
+ },
+ apply: function (skeleton, lastTime, time, firedEvents, alpha) {
+ var frames = this.frames;
+ if (time < frames[0]) return; // Time is before first frame.
+
+ var frameIndex;
+ if (time >= frames[frames.length - 1]) // Time is after last frame.
+ frameIndex = frames.length - 1;
+ else
+ frameIndex = spine.Animation.binarySearch1(frames, time) - 1;
+
+ var drawOrder = skeleton.drawOrder;
+ var slots = skeleton.slots;
+ var drawOrderToSetupIndex = this.drawOrders[frameIndex];
+ if (!drawOrderToSetupIndex) {
+ for (var i = 0, n = slots.length; i < n; i++)
+ drawOrder[i] = slots[i];
+ } else {
+ for (var i = 0, n = drawOrderToSetupIndex.length; i < n; i++)
+ drawOrder[i] = skeleton.slots[drawOrderToSetupIndex[i]];
+ }
+
+ }
+};
+
+spine.FfdTimeline = function (frameCount) {
+ this.curves = new spine.Curves(frameCount);
+ this.frames = [];
+ this.frames.length = frameCount;
+ this.frameVertices = [];
+ this.frameVertices.length = frameCount;
+};
+spine.FfdTimeline.prototype = {
+ slotIndex: 0,
+ attachment: 0,
+ getFrameCount: function () {
+ return this.frames.length;
+ },
+ setFrame: function (frameIndex, time, vertices) {
+ this.frames[frameIndex] = time;
+ this.frameVertices[frameIndex] = vertices;
+ },
+ apply: function (skeleton, lastTime, time, firedEvents, alpha) {
+ var slot = skeleton.slots[this.slotIndex];
+ if (slot.attachment != this.attachment) return;
+
+ var frames = this.frames;
+ if (time < frames[0]) return; // Time is before first frame.
+
+ var frameVertices = this.frameVertices;
+ var vertexCount = frameVertices[0].length;
+
+ var vertices = slot.attachmentVertices;
+ if (vertices.length != vertexCount) alpha = 1;
+ vertices.length = vertexCount;
+
+ if (time >= frames[frames.length - 1]) { // Time is after last frame.
+ var lastVertices = frameVertices[frames.length - 1];
+ if (alpha < 1) {
+ for (var i = 0; i < vertexCount; i++)
+ vertices[i] += (lastVertices[i] - vertices[i]) * alpha;
+ } else {
+ for (var i = 0; i < vertexCount; i++)
+ vertices[i] = lastVertices[i];
+ }
+ return;
+ }
+
+ // Interpolate between the previous frame and the current frame.
+ var frameIndex = spine.Animation.binarySearch1(frames, time);
+ var frameTime = frames[frameIndex];
+ var percent = 1 - (time - frameTime) / (frames[frameIndex - 1] - frameTime);
+ percent = this.curves.getCurvePercent(frameIndex - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent));
+
+ var prevVertices = frameVertices[frameIndex - 1];
+ var nextVertices = frameVertices[frameIndex];
+
+ if (alpha < 1) {
+ for (var i = 0; i < vertexCount; i++) {
+ var prev = prevVertices[i];
+ vertices[i] += (prev + (nextVertices[i] - prev) * percent - vertices[i]) * alpha;
+ }
+ } else {
+ for (var i = 0; i < vertexCount; i++) {
+ var prev = prevVertices[i];
+ vertices[i] = prev + (nextVertices[i] - prev) * percent;
+ }
+ }
+ }
+};
+
+spine.IkConstraintTimeline = function (frameCount) {
+ this.curves = new spine.Curves(frameCount);
+ this.frames = []; // time, mix, bendDirection, ...
+ this.frames.length = frameCount * 3;
+};
+spine.IkConstraintTimeline.prototype = {
+ ikConstraintIndex: 0,
+ getFrameCount: function () {
+ return this.frames.length / 3;
+ },
+ setFrame: function (frameIndex, time, mix, bendDirection) {
+ frameIndex *= 3;
+ this.frames[frameIndex] = time;
+ this.frames[frameIndex + 1] = mix;
+ this.frames[frameIndex + 2] = bendDirection;
+ },
+ apply: function (skeleton, lastTime, time, firedEvents, alpha) {
+ var frames = this.frames;
+ if (time < frames[0]) return; // Time is before first frame.
+
+ var ikConstraint = skeleton.ikConstraints[this.ikConstraintIndex];
+
+ if (time >= frames[frames.length - 3]) { // Time is after last frame.
+ ikConstraint.mix += (frames[frames.length - 2] - ikConstraint.mix) * alpha;
+ ikConstraint.bendDirection = frames[frames.length - 1];
+ return;
+ }
+
+ // Interpolate between the previous frame and the current frame.
+ var frameIndex = spine.Animation.binarySearch(frames, time, 3);
+ var prevFrameMix = frames[frameIndex + -2/*PREV_FRAME_MIX*/];
+ var frameTime = frames[frameIndex];
+ var percent = 1 - (time - frameTime) / (frames[frameIndex + -3/*PREV_FRAME_TIME*/] - frameTime);
+ percent = this.curves.getCurvePercent(frameIndex / 3 - 1, percent);
+
+ var mix = prevFrameMix + (frames[frameIndex + 1/*FRAME_MIX*/] - prevFrameMix) * percent;
+ ikConstraint.mix += (mix - ikConstraint.mix) * alpha;
+ ikConstraint.bendDirection = frames[frameIndex + -1/*PREV_FRAME_BEND_DIRECTION*/];
+ }
+};
+
+spine.FlipXTimeline = function (frameCount) {
+ this.curves = new spine.Curves(frameCount);
+ this.frames = []; // time, flip, ...
+ this.frames.length = frameCount * 2;
+};
+spine.FlipXTimeline.prototype = {
+ boneIndex: 0,
+ getFrameCount: function () {
+ return this.frames.length / 2;
+ },
+ setFrame: function (frameIndex, time, flip) {
+ frameIndex *= 2;
+ this.frames[frameIndex] = time;
+ this.frames[frameIndex + 1] = flip ? 1 : 0;
+ },
+ apply: function (skeleton, lastTime, time, firedEvents, alpha) {
+ var frames = this.frames;
+ if (time < frames[0]) {
+ if (lastTime > time) this.apply(skeleton, lastTime, Number.MAX_VALUE, null, 0);
+ return;
+ } else if (lastTime > time) //
+ lastTime = -1;
+ var frameIndex = (time >= frames[frames.length - 2] ? frames.length : spine.Animation.binarySearch(frames, time, 2)) - 2;
+ if (frames[frameIndex] < lastTime) return;
+ skeleton.bones[this.boneIndex].flipX = frames[frameIndex + 1] != 0;
+ }
+};
+
+spine.FlipYTimeline = function (frameCount) {
+ this.curves = new spine.Curves(frameCount);
+ this.frames = []; // time, flip, ...
+ this.frames.length = frameCount * 2;
+};
+spine.FlipYTimeline.prototype = {
+ boneIndex: 0,
+ getFrameCount: function () {
+ return this.frames.length / 2;
+ },
+ setFrame: function (frameIndex, time, flip) {
+ frameIndex *= 2;
+ this.frames[frameIndex] = time;
+ this.frames[frameIndex + 1] = flip ? 1 : 0;
+ },
+ apply: function (skeleton, lastTime, time, firedEvents, alpha) {
+ var frames = this.frames;
+ if (time < frames[0]) {
+ if (lastTime > time) this.apply(skeleton, lastTime, Number.MAX_VALUE, null, 0);
+ return;
+ } else if (lastTime > time) //
+ lastTime = -1;
+ var frameIndex = (time >= frames[frames.length - 2] ? frames.length : spine.Animation.binarySearch(frames, time, 2)) - 2;
+ if (frames[frameIndex] < lastTime) return;
+ skeleton.bones[this.boneIndex].flipY = frames[frameIndex + 1] != 0;
+ }
+};
+
+spine.SkeletonData = function () {
+ this.bones = [];
+ this.slots = [];
+ this.skins = [];
+ this.events = [];
+ this.animations = [];
+ this.ikConstraints = [];
+};
+spine.SkeletonData.prototype = {
+ name: null,
+ defaultSkin: null,
+ width: 0, height: 0,
+ version: null, hash: null,
+ /** @return May be null. */
+ findBone: function (boneName) {
+ var bones = this.bones;
+ for (var i = 0, n = bones.length; i < n; i++)
+ if (bones[i].name == boneName) return bones[i];
+ return null;
+ },
+ /** @return -1 if the bone was not found. */
+ findBoneIndex: function (boneName) {
+ var bones = this.bones;
+ for (var i = 0, n = bones.length; i < n; i++)
+ if (bones[i].name == boneName) return i;
+ return -1;
+ },
+ /** @return May be null. */
+ findSlot: function (slotName) {
+ var slots = this.slots;
+ for (var i = 0, n = slots.length; i < n; i++) {
+ if (slots[i].name == slotName) return slot[i];
+ }
+ return null;
+ },
+ /** @return -1 if the bone was not found. */
+ findSlotIndex: function (slotName) {
+ var slots = this.slots;
+ for (var i = 0, n = slots.length; i < n; i++)
+ if (slots[i].name == slotName) return i;
+ return -1;
+ },
+ /** @return May be null. */
+ findSkin: function (skinName) {
+ var skins = this.skins;
+ for (var i = 0, n = skins.length; i < n; i++)
+ if (skins[i].name == skinName) return skins[i];
+ return null;
+ },
+ /** @return May be null. */
+ findEvent: function (eventName) {
+ var events = this.events;
+ for (var i = 0, n = events.length; i < n; i++)
+ if (events[i].name == eventName) return events[i];
+ return null;
+ },
+ /** @return May be null. */
+ findAnimation: function (animationName) {
+ var animations = this.animations;
+ for (var i = 0, n = animations.length; i < n; i++)
+ if (animations[i].name == animationName) return animations[i];
+ return null;
+ },
+ /** @return May be null. */
+ findIkConstraint: function (ikConstraintName) {
+ var ikConstraints = this.ikConstraints;
+ for (var i = 0, n = ikConstraints.length; i < n; i++)
+ if (ikConstraints[i].name == ikConstraintName) return ikConstraints[i];
+ return null;
+ }
+};
+
+spine.Skeleton = function (skeletonData) {
+ this.data = skeletonData;
+
+ this.bones = [];
+ for (var i = 0, n = skeletonData.bones.length; i < n; i++) {
+ var boneData = skeletonData.bones[i];
+ var parent = !boneData.parent ? null : this.bones[skeletonData.bones.indexOf(boneData.parent)];
+ this.bones.push(new spine.Bone(boneData, this, parent));
+ }
+
+ this.slots = [];
+ this.drawOrder = [];
+ for (var i = 0, n = skeletonData.slots.length; i < n; i++) {
+ var slotData = skeletonData.slots[i];
+ var bone = this.bones[skeletonData.bones.indexOf(slotData.boneData)];
+ var slot = new spine.Slot(slotData, bone);
+ this.slots.push(slot);
+ this.drawOrder.push(slot);
+ }
+
+ this.ikConstraints = [];
+ for (var i = 0, n = skeletonData.ikConstraints.length; i < n; i++)
+ this.ikConstraints.push(new spine.IkConstraint(skeletonData.ikConstraints[i], this));
+
+ this.boneCache = [];
+ this.updateCache();
+};
+spine.Skeleton.prototype = {
+ x: 0, y: 0,
+ skin: null,
+ r: 1, g: 1, b: 1, a: 1,
+ time: 0,
+ flipX: false, flipY: false,
+ /** Caches information about bones and IK constraints. Must be called if bones or IK constraints are added or removed. */
+ updateCache: function () {
+ var ikConstraints = this.ikConstraints;
+ var ikConstraintsCount = ikConstraints.length;
+
+ var arrayCount = ikConstraintsCount + 1;
+ var boneCache = this.boneCache;
+ if (boneCache.length > arrayCount) boneCache.length = arrayCount;
+ for (var i = 0, n = boneCache.length; i < n; i++)
+ boneCache[i].length = 0;
+ while (boneCache.length < arrayCount)
+ boneCache[boneCache.length] = [];
+
+ var nonIkBones = boneCache[0];
+ var bones = this.bones;
+
+ outer:
+ for (var i = 0, n = bones.length; i < n; i++) {
+ var bone = bones[i];
+ var current = bone;
+ do {
+ for (var ii = 0; ii < ikConstraintsCount; ii++) {
+ var ikConstraint = ikConstraints[ii];
+ var parent = ikConstraint.bones[0];
+ var child= ikConstraint.bones[ikConstraint.bones.length - 1];
+ while (true) {
+ if (current == child) {
+ boneCache[ii].push(bone);
+ boneCache[ii + 1].push(bone);
+ continue outer;
+ }
+ if (child == parent) break;
+ child = child.parent;
+ }
+ }
+ current = current.parent;
+ } while (current);
+ nonIkBones[nonIkBones.length] = bone;
+ }
+ },
+ /** Updates the world transform for each bone. */
+ updateWorldTransform: function () {
+ var bones = this.bones;
+ for (var i = 0, n = bones.length; i < n; i++) {
+ var bone = bones[i];
+ bone.rotationIK = bone.rotation;
+ }
+ var i = 0, last = this.boneCache.length - 1;
+ while (true) {
+ var cacheBones = this.boneCache[i];
+ for (var ii = 0, nn = cacheBones.length; ii < nn; ii++)
+ cacheBones[ii].updateWorldTransform();
+ if (i == last) break;
+ this.ikConstraints[i].apply();
+ i++;
+ }
+ },
+ /** Sets the bones and slots to their setup pose values. */
+ setToSetupPose: function () {
+ this.setBonesToSetupPose();
+ this.setSlotsToSetupPose();
+ },
+ setBonesToSetupPose: function () {
+ var bones = this.bones;
+ for (var i = 0, n = bones.length; i < n; i++)
+ bones[i].setToSetupPose();
+
+ var ikConstraints = this.ikConstraints;
+ for (var i = 0, n = ikConstraints.length; i < n; i++) {
+ var ikConstraint = ikConstraints[i];
+ ikConstraint.bendDirection = ikConstraint.data.bendDirection;
+ ikConstraint.mix = ikConstraint.data.mix;
+ }
+ },
+ setSlotsToSetupPose: function () {
+ var slots = this.slots;
+ var drawOrder = this.drawOrder;
+ for (var i = 0, n = slots.length; i < n; i++) {
+ drawOrder[i] = slots[i];
+ slots[i].setToSetupPose(i);
+ }
+ },
+ /** @return May return null. */
+ getRootBone: function () {
+ return this.bones.length ? this.bones[0] : null;
+ },
+ /** @return May be null. */
+ findBone: function (boneName) {
+ var bones = this.bones;
+ for (var i = 0, n = bones.length; i < n; i++)
+ if (bones[i].data.name == boneName) return bones[i];
+ return null;
+ },
+ /** @return -1 if the bone was not found. */
+ findBoneIndex: function (boneName) {
+ var bones = this.bones;
+ for (var i = 0, n = bones.length; i < n; i++)
+ if (bones[i].data.name == boneName) return i;
+ return -1;
+ },
+ /** @return May be null. */
+ findSlot: function (slotName) {
+ var slots = this.slots;
+ for (var i = 0, n = slots.length; i < n; i++)
+ if (slots[i].data.name == slotName) return slots[i];
+ return null;
+ },
+ /** @return -1 if the bone was not found. */
+ findSlotIndex: function (slotName) {
+ var slots = this.slots;
+ for (var i = 0, n = slots.length; i < n; i++)
+ if (slots[i].data.name == slotName) return i;
+ return -1;
+ },
+ setSkinByName: function (skinName) {
+ var skin = this.data.findSkin(skinName);
+ if (!skin) throw new Error("Skin not found: " + skinName);
+ this.setSkin(skin);
+ },
+ /** Sets the skin used to look up attachments before looking in the {@link SkeletonData#getDefaultSkin() default skin}.
+ * Attachments from the new skin are attached if the corresponding attachment from the old skin was attached. If there was
+ * no old skin, each slot's setup mode attachment is attached from the new skin.
+ * @param newSkin May be null. */
+ setSkin: function (newSkin) {
+ if (newSkin) {
+ if (this.skin)
+ newSkin._attachAll(this, this.skin);
+ else {
+ var slots = this.slots;
+ for (var i = 0, n = slots.length; i < n; i++) {
+ var slot = slots[i];
+ var name = slot.data.attachmentName;
+ if (name) {
+ var attachment = newSkin.getAttachment(i, name);
+ if (attachment) slot.setAttachment(attachment);
+ }
+ }
+ }
+ }
+ this.skin = newSkin;
+ },
+ /** @return May be null. */
+ getAttachmentBySlotName: function (slotName, attachmentName) {
+ return this.getAttachmentBySlotIndex(this.data.findSlotIndex(slotName), attachmentName);
+ },
+ /** @return May be null. */
+ getAttachmentBySlotIndex: function (slotIndex, attachmentName) {
+ if (this.skin) {
+ var attachment = this.skin.getAttachment(slotIndex, attachmentName);
+ if (attachment) return attachment;
+ }
+ if (this.data.defaultSkin) return this.data.defaultSkin.getAttachment(slotIndex, attachmentName);
+ return null;
+ },
+ /** @param attachmentName May be null. */
+ setAttachment: function (slotName, attachmentName) {
+ var slots = this.slots;
+ for (var i = 0, n = slots.length; i < n; i++) {
+ var slot = slots[i];
+ if (slot.data.name == slotName) {
+ var attachment = null;
+ if (attachmentName) {
+ attachment = this.getAttachmentBySlotIndex(i, attachmentName);
+ if (!attachment) throw new Error("Attachment not found: " + attachmentName + ", for slot: " + slotName);
+ }
+ slot.setAttachment(attachment);
+ return;
+ }
+ }
+ throw new Error("Slot not found: " + slotName);
+ },
+ /** @return May be null. */
+ findIkConstraint: function (ikConstraintName) {
+ var ikConstraints = this.ikConstraints;
+ for (var i = 0, n = ikConstraints.length; i < n; i++)
+ if (ikConstraints[i].data.name == ikConstraintName) return ikConstraints[i];
+ return null;
+ },
+ update: function (delta) {
+ this.time += delta;
+ }
+};
+
+spine.EventData = function (name) {
+ this.name = name;
+};
+spine.EventData.prototype = {
+ intValue: 0,
+ floatValue: 0,
+ stringValue: null
+};
+
+spine.Event = function (data) {
+ this.data = data;
+};
+spine.Event.prototype = {
+ intValue: 0,
+ floatValue: 0,
+ stringValue: null
+};
+
+spine.AttachmentType = {
+ region: 0,
+ boundingbox: 1,
+ mesh: 2,
+ skinnedmesh: 3
+};
+
+spine.RegionAttachment = function (name) {
+ this.name = name;
+ this.offset = [];
+ this.offset.length = 8;
+ this.uvs = [];
+ this.uvs.length = 8;
+};
+spine.RegionAttachment.prototype = {
+ type: spine.AttachmentType.region,
+ x: 0, y: 0,
+ rotation: 0,
+ scaleX: 1, scaleY: 1,
+ width: 0, height: 0,
+ r: 1, g: 1, b: 1, a: 1,
+ path: null,
+ rendererObject: null,
+ regionOffsetX: 0, regionOffsetY: 0,
+ regionWidth: 0, regionHeight: 0,
+ regionOriginalWidth: 0, regionOriginalHeight: 0,
+ setUVs: function (u, v, u2, v2, rotate) {
+ var uvs = this.uvs;
+ if (rotate) {
+ uvs[2/*X2*/] = u;
+ uvs[3/*Y2*/] = v2;
+ uvs[4/*X3*/] = u;
+ uvs[5/*Y3*/] = v;
+ uvs[6/*X4*/] = u2;
+ uvs[7/*Y4*/] = v;
+ uvs[0/*X1*/] = u2;
+ uvs[1/*Y1*/] = v2;
+ } else {
+ uvs[0/*X1*/] = u;
+ uvs[1/*Y1*/] = v2;
+ uvs[2/*X2*/] = u;
+ uvs[3/*Y2*/] = v;
+ uvs[4/*X3*/] = u2;
+ uvs[5/*Y3*/] = v;
+ uvs[6/*X4*/] = u2;
+ uvs[7/*Y4*/] = v2;
+ }
+ },
+ updateOffset: function () {
+ var regionScaleX = this.width / this.regionOriginalWidth * this.scaleX;
+ var regionScaleY = this.height / this.regionOriginalHeight * this.scaleY;
+ var localX = -this.width / 2 * this.scaleX + this.regionOffsetX * regionScaleX;
+ var localY = -this.height / 2 * this.scaleY + this.regionOffsetY * regionScaleY;
+ var localX2 = localX + this.regionWidth * regionScaleX;
+ var localY2 = localY + this.regionHeight * regionScaleY;
+ var radians = this.rotation * spine.degRad;
+ var cos = Math.cos(radians);
+ var sin = Math.sin(radians);
+ var localXCos = localX * cos + this.x;
+ var localXSin = localX * sin;
+ var localYCos = localY * cos + this.y;
+ var localYSin = localY * sin;
+ var localX2Cos = localX2 * cos + this.x;
+ var localX2Sin = localX2 * sin;
+ var localY2Cos = localY2 * cos + this.y;
+ var localY2Sin = localY2 * sin;
+ var offset = this.offset;
+ offset[0/*X1*/] = localXCos - localYSin;
+ offset[1/*Y1*/] = localYCos + localXSin;
+ offset[2/*X2*/] = localXCos - localY2Sin;
+ offset[3/*Y2*/] = localY2Cos + localXSin;
+ offset[4/*X3*/] = localX2Cos - localY2Sin;
+ offset[5/*Y3*/] = localY2Cos + localX2Sin;
+ offset[6/*X4*/] = localX2Cos - localYSin;
+ offset[7/*Y4*/] = localYCos + localX2Sin;
+ },
+ computeVertices: function (x, y, bone, vertices) {
+ x += bone.worldX;
+ y += bone.worldY;
+ var m00 = bone.m00, m01 = bone.m01, m10 = bone.m10, m11 = bone.m11;
+ var offset = this.offset;
+ vertices[0/*X1*/] = offset[0/*X1*/] * m00 + offset[1/*Y1*/] * m01 + x;
+ vertices[1/*Y1*/] = offset[0/*X1*/] * m10 + offset[1/*Y1*/] * m11 + y;
+ vertices[2/*X2*/] = offset[2/*X2*/] * m00 + offset[3/*Y2*/] * m01 + x;
+ vertices[3/*Y2*/] = offset[2/*X2*/] * m10 + offset[3/*Y2*/] * m11 + y;
+ vertices[4/*X3*/] = offset[4/*X3*/] * m00 + offset[5/*X3*/] * m01 + x;
+ vertices[5/*X3*/] = offset[4/*X3*/] * m10 + offset[5/*X3*/] * m11 + y;
+ vertices[6/*X4*/] = offset[6/*X4*/] * m00 + offset[7/*Y4*/] * m01 + x;
+ vertices[7/*Y4*/] = offset[6/*X4*/] * m10 + offset[7/*Y4*/] * m11 + y;
+ }
+};
+
+spine.MeshAttachment = function (name) {
+ this.name = name;
+};
+spine.MeshAttachment.prototype = {
+ type: spine.AttachmentType.mesh,
+ vertices: null,
+ uvs: null,
+ regionUVs: null,
+ triangles: null,
+ hullLength: 0,
+ r: 1, g: 1, b: 1, a: 1,
+ path: null,
+ rendererObject: null,
+ regionU: 0, regionV: 0, regionU2: 0, regionV2: 0, regionRotate: false,
+ regionOffsetX: 0, regionOffsetY: 0,
+ regionWidth: 0, regionHeight: 0,
+ regionOriginalWidth: 0, regionOriginalHeight: 0,
+ edges: null,
+ width: 0, height: 0,
+ updateUVs: function () {
+ var width = this.regionU2 - this.regionU, height = this.regionV2 - this.regionV;
+ var n = this.regionUVs.length;
+ if (!this.uvs || this.uvs.length != n) {
+ this.uvs = new spine.Float32Array(n);
+ }
+ if (this.regionRotate) {
+ for (var i = 0; i < n; i += 2) {
+ this.uvs[i] = this.regionU + this.regionUVs[i + 1] * width;
+ this.uvs[i + 1] = this.regionV + height - this.regionUVs[i] * height;
+ }
+ } else {
+ for (var i = 0; i < n; i += 2) {
+ this.uvs[i] = this.regionU + this.regionUVs[i] * width;
+ this.uvs[i + 1] = this.regionV + this.regionUVs[i + 1] * height;
+ }
+ }
+ },
+ computeWorldVertices: function (x, y, slot, worldVertices) {
+ var bone = slot.bone;
+ x += bone.worldX;
+ y += bone.worldY;
+ var m00 = bone.m00, m01 = bone.m01, m10 = bone.m10, m11 = bone.m11;
+ var vertices = this.vertices;
+ var verticesCount = vertices.length;
+ if (slot.attachmentVertices.length == verticesCount) vertices = slot.attachmentVertices;
+ for (var i = 0; i < verticesCount; i += 2) {
+ var vx = vertices[i];
+ var vy = vertices[i + 1];
+ worldVertices[i] = vx * m00 + vy * m01 + x;
+ worldVertices[i + 1] = vx * m10 + vy * m11 + y;
+ }
+ }
+};
+
+spine.SkinnedMeshAttachment = function (name) {
+ this.name = name;
+};
+spine.SkinnedMeshAttachment.prototype = {
+ type: spine.AttachmentType.skinnedmesh,
+ bones: null,
+ weights: null,
+ uvs: null,
+ regionUVs: null,
+ triangles: null,
+ hullLength: 0,
+ r: 1, g: 1, b: 1, a: 1,
+ path: null,
+ rendererObject: null,
+ regionU: 0, regionV: 0, regionU2: 0, regionV2: 0, regionRotate: false,
+ regionOffsetX: 0, regionOffsetY: 0,
+ regionWidth: 0, regionHeight: 0,
+ regionOriginalWidth: 0, regionOriginalHeight: 0,
+ edges: null,
+ width: 0, height: 0,
+ updateUVs: function (u, v, u2, v2, rotate) {
+ var width = this.regionU2 - this.regionU, height = this.regionV2 - this.regionV;
+ var n = this.regionUVs.length;
+ if (!this.uvs || this.uvs.length != n) {
+ this.uvs = new spine.Float32Array(n);
+ }
+ if (this.regionRotate) {
+ for (var i = 0; i < n; i += 2) {
+ this.uvs[i] = this.regionU + this.regionUVs[i + 1] * width;
+ this.uvs[i + 1] = this.regionV + height - this.regionUVs[i] * height;
+ }
+ } else {
+ for (var i = 0; i < n; i += 2) {
+ this.uvs[i] = this.regionU + this.regionUVs[i] * width;
+ this.uvs[i + 1] = this.regionV + this.regionUVs[i + 1] * height;
+ }
+ }
+ },
+ computeWorldVertices: function (x, y, slot, worldVertices) {
+ var skeletonBones = slot.bone.skeleton.bones;
+ var weights = this.weights;
+ var bones = this.bones;
+
+ var w = 0, v = 0, b = 0, f = 0, n = bones.length, nn;
+ var wx, wy, bone, vx, vy, weight;
+ if (!slot.attachmentVertices.length) {
+ for (; v < n; w += 2) {
+ wx = 0;
+ wy = 0;
+ nn = bones[v++] + v;
+ for (; v < nn; v++, b += 3) {
+ bone = skeletonBones[bones[v]];
+ vx = weights[b];
+ vy = weights[b + 1];
+ weight = weights[b + 2];
+ wx += (vx * bone.m00 + vy * bone.m01 + bone.worldX) * weight;
+ wy += (vx * bone.m10 + vy * bone.m11 + bone.worldY) * weight;
+ }
+ worldVertices[w] = wx + x;
+ worldVertices[w + 1] = wy + y;
+ }
+ } else {
+ var ffd = slot.attachmentVertices;
+ for (; v < n; w += 2) {
+ wx = 0;
+ wy = 0;
+ nn = bones[v++] + v;
+ for (; v < nn; v++, b += 3, f += 2) {
+ bone = skeletonBones[bones[v]];
+ vx = weights[b] + ffd[f];
+ vy = weights[b + 1] + ffd[f + 1];
+ weight = weights[b + 2];
+ wx += (vx * bone.m00 + vy * bone.m01 + bone.worldX) * weight;
+ wy += (vx * bone.m10 + vy * bone.m11 + bone.worldY) * weight;
+ }
+ worldVertices[w] = wx + x;
+ worldVertices[w + 1] = wy + y;
+ }
+ }
+ }
+};
+
+spine.BoundingBoxAttachment = function (name) {
+ this.name = name;
+ this.vertices = [];
+};
+spine.BoundingBoxAttachment.prototype = {
+ type: spine.AttachmentType.boundingbox,
+ computeWorldVertices: function (x, y, bone, worldVertices) {
+ x += bone.worldX;
+ y += bone.worldY;
+ var m00 = bone.m00, m01 = bone.m01, m10 = bone.m10, m11 = bone.m11;
+ var vertices = this.vertices;
+ for (var i = 0, n = vertices.length; i < n; i += 2) {
+ var px = vertices[i];
+ var py = vertices[i + 1];
+ worldVertices[i] = px * m00 + py * m01 + x;
+ worldVertices[i + 1] = px * m10 + py * m11 + y;
+ }
+ }
+};
+
+spine.AnimationStateData = function (skeletonData) {
+ this.skeletonData = skeletonData;
+ this.animationToMixTime = {};
+};
+spine.AnimationStateData.prototype = {
+ defaultMix: 0,
+ setMixByName: function (fromName, toName, duration) {
+ var from = this.skeletonData.findAnimation(fromName);
+ if (!from) throw new Error("Animation not found: " + fromName);
+ var to = this.skeletonData.findAnimation(toName);
+ if (!to) throw new Error("Animation not found: " + toName);
+ this.setMix(from, to, duration);
+ },
+ setMix: function (from, to, duration) {
+ this.animationToMixTime[from.name + ":" + to.name] = duration;
+ },
+ getMix: function (from, to) {
+ var key = from.name + ":" + to.name;
+ return this.animationToMixTime.hasOwnProperty(key) ? this.animationToMixTime[key] : this.defaultMix;
+ }
+};
+
+spine.TrackEntry = function () {};
+spine.TrackEntry.prototype = {
+ next: null, previous: null,
+ animation: null,
+ loop: false,
+ delay: 0, time: 0, lastTime: -1, endTime: 0,
+ timeScale: 1,
+ mixTime: 0, mixDuration: 0, mix: 1,
+ onStart: null, onEnd: null, onComplete: null, onEvent: null
+};
+
+spine.AnimationState = function (stateData) {
+ this.data = stateData;
+ this.tracks = [];
+ this.events = [];
+};
+spine.AnimationState.prototype = {
+ onStart: null,
+ onEnd: null,
+ onComplete: null,
+ onEvent: null,
+ timeScale: 1,
+ update: function (delta) {
+ delta *= this.timeScale;
+ for (var i = 0; i < this.tracks.length; i++) {
+ var current = this.tracks[i];
+ if (!current) continue;
+
+ current.time += delta * current.timeScale;
+ if (current.previous) {
+ var previousDelta = delta * current.previous.timeScale;
+ current.previous.time += previousDelta;
+ current.mixTime += previousDelta;
+ }
+
+ var next = current.next;
+ if (next) {
+ next.time = current.lastTime - next.delay;
+ if (next.time >= 0) this.setCurrent(i, next);
+ } else {
+ // End non-looping animation when it reaches its end time and there is no next entry.
+ if (!current.loop && current.lastTime >= current.endTime) this.clearTrack(i);
+ }
+ }
+ },
+ apply: function (skeleton) {
+ for (var i = 0; i < this.tracks.length; i++) {
+ var current = this.tracks[i];
+ if (!current) continue;
+
+ this.events.length = 0;
+
+ var time = current.time;
+ var lastTime = current.lastTime;
+ var endTime = current.endTime;
+ var loop = current.loop;
+ if (!loop && time > endTime) time = endTime;
+
+ var previous = current.previous;
+ if (!previous) {
+ if (current.mix == 1)
+ current.animation.apply(skeleton, current.lastTime, time, loop, this.events);
+ else
+ current.animation.mix(skeleton, current.lastTime, time, loop, this.events, current.mix);
+ } else {
+ var previousTime = previous.time;
+ if (!previous.loop && previousTime > previous.endTime) previousTime = previous.endTime;
+ previous.animation.apply(skeleton, previousTime, previousTime, previous.loop, null);
+
+ var alpha = current.mixTime / current.mixDuration * current.mix;
+ if (alpha >= 1) {
+ alpha = 1;
+ current.previous = null;
+ }
+ current.animation.mix(skeleton, current.lastTime, time, loop, this.events, alpha);
+ }
+
+ for (var ii = 0, nn = this.events.length; ii < nn; ii++) {
+ var event = this.events[ii];
+ if (current.onEvent) current.onEvent(i, event);
+ if (this.onEvent) this.onEvent(i, event);
+ }
+
+ // Check if completed the animation or a loop iteration.
+ if (loop ? (lastTime % endTime > time % endTime) : (lastTime < endTime && time >= endTime)) {
+ var count = Math.floor(time / endTime);
+ if (current.onComplete) current.onComplete(i, count);
+ if (this.onComplete) this.onComplete(i, count);
+ }
+
+ current.lastTime = current.time;
+ }
+ },
+ clearTracks: function () {
+ for (var i = 0, n = this.tracks.length; i < n; i++)
+ this.clearTrack(i);
+ this.tracks.length = 0;
+ },
+ clearTrack: function (trackIndex) {
+ if (trackIndex >= this.tracks.length) return;
+ var current = this.tracks[trackIndex];
+ if (!current) return;
+
+ if (current.onEnd) current.onEnd(trackIndex);
+ if (this.onEnd) this.onEnd(trackIndex);
+
+ this.tracks[trackIndex] = null;
+ },
+ _expandToIndex: function (index) {
+ if (index < this.tracks.length) return this.tracks[index];
+ while (index >= this.tracks.length)
+ this.tracks.push(null);
+ return null;
+ },
+ setCurrent: function (index, entry) {
+ var current = this._expandToIndex(index);
+ if (current) {
+ var previous = current.previous;
+ current.previous = null;
+
+ if (current.onEnd) current.onEnd(index);
+ if (this.onEnd) this.onEnd(index);
+
+ entry.mixDuration = this.data.getMix(current.animation, entry.animation);
+ if (entry.mixDuration > 0) {
+ entry.mixTime = 0;
+ // If a mix is in progress, mix from the closest animation.
+ if (previous && current.mixTime / current.mixDuration < 0.5)
+ entry.previous = previous;
+ else
+ entry.previous = current;
+ }
+ }
+
+ this.tracks[index] = entry;
+
+ if (entry.onStart) entry.onStart(index);
+ if (this.onStart) this.onStart(index);
+ },
+ setAnimationByName: function (trackIndex, animationName, loop) {
+ var animation = this.data.skeletonData.findAnimation(animationName);
+ if (!animation) throw new Error("Animation not found: " + animationName);
+ return this.setAnimation(trackIndex, animation, loop);
+ },
+ /** Set the current animation. Any queued animations are cleared. */
+ setAnimation: function (trackIndex, animation, loop) {
+ var entry = new spine.TrackEntry();
+ entry.animation = animation;
+ entry.loop = loop;
+ entry.endTime = animation.duration;
+ this.setCurrent(trackIndex, entry);
+ return entry;
+ },
+ addAnimationByName: function (trackIndex, animationName, loop, delay) {
+ var animation = this.data.skeletonData.findAnimation(animationName);
+ if (!animation) throw new Error("Animation not found: " + animationName);
+ return this.addAnimation(trackIndex, animation, loop, delay);
+ },
+ /** Adds an animation to be played delay seconds after the current or last queued animation.
+ * @param delay May be <= 0 to use duration of previous animation minus any mix duration plus the negative delay. */
+ addAnimation: function (trackIndex, animation, loop, delay) {
+ var entry = new spine.TrackEntry();
+ entry.animation = animation;
+ entry.loop = loop;
+ entry.endTime = animation.duration;
+
+ var last = this._expandToIndex(trackIndex);
+ if (last) {
+ while (last.next)
+ last = last.next;
+ last.next = entry;
+ } else
+ this.tracks[trackIndex] = entry;
+
+ if (delay <= 0) {
+ if (last)
+ delay += last.endTime - this.data.getMix(last.animation, animation);
+ else
+ delay = 0;
+ }
+ entry.delay = delay;
+
+ return entry;
+ },
+ /** May be null. */
+ getCurrent: function (trackIndex) {
+ if (trackIndex >= this.tracks.length) return null;
+ return this.tracks[trackIndex];
+ }
+};
+
+spine.SkeletonJson = function (attachmentLoader) {
+ this.attachmentLoader = attachmentLoader;
+};
+spine.SkeletonJson.prototype = {
+ scale: 1,
+ readSkeletonData: function (root, name) {
+ var skeletonData = new spine.SkeletonData();
+ skeletonData.name = name;
+
+ // Skeleton.
+ var skeletonMap = root["skeleton"];
+ if (skeletonMap) {
+ skeletonData.hash = skeletonMap["hash"];
+ skeletonData.version = skeletonMap["spine"];
+ skeletonData.width = skeletonMap["width"] || 0;
+ skeletonData.height = skeletonMap["height"] || 0;
+ }
+
+ // Bones.
+ var bones = root["bones"];
+ for (var i = 0, n = bones.length; i < n; i++) {
+ var boneMap = bones[i];
+ var parent = null;
+ if (boneMap["parent"]) {
+ parent = skeletonData.findBone(boneMap["parent"]);
+ if (!parent) throw new Error("Parent bone not found: " + boneMap["parent"]);
+ }
+ var boneData = new spine.BoneData(boneMap["name"], parent);
+ boneData.length = (boneMap["length"] || 0) * this.scale;
+ boneData.x = (boneMap["x"] || 0) * this.scale;
+ boneData.y = (boneMap["y"] || 0) * this.scale;
+ boneData.rotation = (boneMap["rotation"] || 0);
+ boneData.scaleX = boneMap.hasOwnProperty("scaleX") ? boneMap["scaleX"] : 1;
+ boneData.scaleY = boneMap.hasOwnProperty("scaleY") ? boneMap["scaleY"] : 1;
+ boneData.inheritScale = boneMap.hasOwnProperty("inheritScale") ? boneMap["inheritScale"] : true;
+ boneData.inheritRotation = boneMap.hasOwnProperty("inheritRotation") ? boneMap["inheritRotation"] : true;
+ skeletonData.bones.push(boneData);
+ }
+
+ // IK constraints.
+ var ik = root["ik"];
+ if (ik) {
+ for (var i = 0, n = ik.length; i < n; i++) {
+ var ikMap = ik[i];
+ var ikConstraintData = new spine.IkConstraintData(ikMap["name"]);
+
+ var bones = ikMap["bones"];
+ for (var ii = 0, nn = bones.length; ii < nn; ii++) {
+ var bone = skeletonData.findBone(bones[ii]);
+ if (!bone) throw new Error("IK bone not found: " + bones[ii]);
+ ikConstraintData.bones.push(bone);
+ }
+
+ ikConstraintData.target = skeletonData.findBone(ikMap["target"]);
+ if (!ikConstraintData.target) throw new Error("Target bone not found: " + ikMap["target"]);
+
+ ikConstraintData.bendDirection = (!ikMap.hasOwnProperty("bendPositive") || ikMap["bendPositive"]) ? 1 : -1;
+ ikConstraintData.mix = ikMap.hasOwnProperty("mix") ? ikMap["mix"] : 1;
+
+ skeletonData.ikConstraints.push(ikConstraintData);
+ }
+ }
+
+ // Slots.
+ var slots = root["slots"];
+ for (var i = 0, n = slots.length; i < n; i++) {
+ var slotMap = slots[i];
+ var boneData = skeletonData.findBone(slotMap["bone"]);
+ if (!boneData) throw new Error("Slot bone not found: " + slotMap["bone"]);
+ var slotData = new spine.SlotData(slotMap["name"], boneData);
+
+ var color = slotMap["color"];
+ if (color) {
+ slotData.r = this.toColor(color, 0);
+ slotData.g = this.toColor(color, 1);
+ slotData.b = this.toColor(color, 2);
+ slotData.a = this.toColor(color, 3);
+ }
+
+ slotData.attachmentName = slotMap["attachment"];
+ slotData.blendMode = spine.AttachmentType[slotMap["blend"] || "normal"];
+
+ skeletonData.slots.push(slotData);
+ }
+
+ // Skins.
+ var skins = root["skins"];
+ for (var skinName in skins) {
+ if (!skins.hasOwnProperty(skinName)) continue;
+ var skinMap = skins[skinName];
+ var skin = new spine.Skin(skinName);
+ for (var slotName in skinMap) {
+ if (!skinMap.hasOwnProperty(slotName)) continue;
+ var slotIndex = skeletonData.findSlotIndex(slotName);
+ var slotEntry = skinMap[slotName];
+ for (var attachmentName in slotEntry) {
+ if (!slotEntry.hasOwnProperty(attachmentName)) continue;
+ var attachment = this.readAttachment(skin, attachmentName, slotEntry[attachmentName]);
+ if (attachment) skin.addAttachment(slotIndex, attachmentName, attachment);
+ }
+ }
+ skeletonData.skins.push(skin);
+ if (skin.name == "default") skeletonData.defaultSkin = skin;
+ }
+
+ // Events.
+ var events = root["events"];
+ for (var eventName in events) {
+ if (!events.hasOwnProperty(eventName)) continue;
+ var eventMap = events[eventName];
+ var eventData = new spine.EventData(eventName);
+ eventData.intValue = eventMap["int"] || 0;
+ eventData.floatValue = eventMap["float"] || 0;
+ eventData.stringValue = eventMap["string"] || null;
+ skeletonData.events.push(eventData);
+ }
+
+ // Animations.
+ var animations = root["animations"];
+ for (var animationName in animations) {
+ if (!animations.hasOwnProperty(animationName)) continue;
+ this.readAnimation(animationName, animations[animationName], skeletonData);
+ }
+
+ return skeletonData;
+ },
+ readAttachment: function (skin, name, map) {
+ name = map["name"] || name;
+
+ var type = spine.AttachmentType[map["type"] || "region"];
+ var path = map["path"] || name;
+
+ var scale = this.scale;
+ if (type == spine.AttachmentType.region) {
+ var region = this.attachmentLoader.newRegionAttachment(skin, name, path);
+ if (!region) return null;
+ region.path = path;
+ region.x = (map["x"] || 0) * scale;
+ region.y = (map["y"] || 0) * scale;
+ region.scaleX = map.hasOwnProperty("scaleX") ? map["scaleX"] : 1;
+ region.scaleY = map.hasOwnProperty("scaleY") ? map["scaleY"] : 1;
+ region.rotation = map["rotation"] || 0;
+ region.width = (map["width"] || 0) * scale;
+ region.height = (map["height"] || 0) * scale;
+
+ var color = map["color"];
+ if (color) {
+ region.r = this.toColor(color, 0);
+ region.g = this.toColor(color, 1);
+ region.b = this.toColor(color, 2);
+ region.a = this.toColor(color, 3);
+ }
+
+ region.updateOffset();
+ return region;
+ } else if (type == spine.AttachmentType.mesh) {
+ var mesh = this.attachmentLoader.newMeshAttachment(skin, name, path);
+ if (!mesh) return null;
+ mesh.path = path;
+ mesh.vertices = this.getFloatArray(map, "vertices", scale);
+ mesh.triangles = this.getIntArray(map, "triangles");
+ mesh.regionUVs = this.getFloatArray(map, "uvs", 1);
+ mesh.updateUVs();
+
+ color = map["color"];
+ if (color) {
+ mesh.r = this.toColor(color, 0);
+ mesh.g = this.toColor(color, 1);
+ mesh.b = this.toColor(color, 2);
+ mesh.a = this.toColor(color, 3);
+ }
+
+ mesh.hullLength = (map["hull"] || 0) * 2;
+ if (map["edges"]) mesh.edges = this.getIntArray(map, "edges");
+ mesh.width = (map["width"] || 0) * scale;
+ mesh.height = (map["height"] || 0) * scale;
+ return mesh;
+ } else if (type == spine.AttachmentType.skinnedmesh) {
+ var mesh = this.attachmentLoader.newSkinnedMeshAttachment(skin, name, path);
+ if (!mesh) return null;
+ mesh.path = path;
+
+ var uvs = this.getFloatArray(map, "uvs", 1);
+ var vertices = this.getFloatArray(map, "vertices", 1);
+ var weights = [];
+ var bones = [];
+ for (var i = 0, n = vertices.length; i < n; ) {
+ var boneCount = vertices[i++] | 0;
+ bones[bones.length] = boneCount;
+ for (var nn = i + boneCount * 4; i < nn; ) {
+ bones[bones.length] = vertices[i];
+ weights[weights.length] = vertices[i + 1] * scale;
+ weights[weights.length] = vertices[i + 2] * scale;
+ weights[weights.length] = vertices[i + 3];
+ i += 4;
+ }
+ }
+ mesh.bones = bones;
+ mesh.weights = weights;
+ mesh.triangles = this.getIntArray(map, "triangles");
+ mesh.regionUVs = uvs;
+ mesh.updateUVs();
+
+ color = map["color"];
+ if (color) {
+ mesh.r = this.toColor(color, 0);
+ mesh.g = this.toColor(color, 1);
+ mesh.b = this.toColor(color, 2);
+ mesh.a = this.toColor(color, 3);
+ }
+
+ mesh.hullLength = (map["hull"] || 0) * 2;
+ if (map["edges"]) mesh.edges = this.getIntArray(map, "edges");
+ mesh.width = (map["width"] || 0) * scale;
+ mesh.height = (map["height"] || 0) * scale;
+ return mesh;
+ } else if (type == spine.AttachmentType.boundingbox) {
+ var attachment = this.attachmentLoader.newBoundingBoxAttachment(skin, name);
+ var vertices = map["vertices"];
+ for (var i = 0, n = vertices.length; i < n; i++)
+ attachment.vertices.push(vertices[i] * scale);
+ return attachment;
+ }
+ throw new Error("Unknown attachment type: " + type);
+ },
+ readAnimation: function (name, map, skeletonData) {
+ var timelines = [];
+ var duration = 0;
+
+ var slots = map["slots"];
+ for (var slotName in slots) {
+ if (!slots.hasOwnProperty(slotName)) continue;
+ var slotMap = slots[slotName];
+ var slotIndex = skeletonData.findSlotIndex(slotName);
+
+ for (var timelineName in slotMap) {
+ if (!slotMap.hasOwnProperty(timelineName)) continue;
+ var values = slotMap[timelineName];
+ if (timelineName == "color") {
+ var timeline = new spine.ColorTimeline(values.length);
+ timeline.slotIndex = slotIndex;
+
+ var frameIndex = 0;
+ for (var i = 0, n = values.length; i < n; i++) {
+ var valueMap = values[i];
+ var color = valueMap["color"];
+ var r = this.toColor(color, 0);
+ var g = this.toColor(color, 1);
+ var b = this.toColor(color, 2);
+ var a = this.toColor(color, 3);
+ timeline.setFrame(frameIndex, valueMap["time"], r, g, b, a);
+ this.readCurve(timeline, frameIndex, valueMap);
+ frameIndex++;
+ }
+ timelines.push(timeline);
+ duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 5 - 5]);
+
+ } else if (timelineName == "attachment") {
+ var timeline = new spine.AttachmentTimeline(values.length);
+ timeline.slotIndex = slotIndex;
+
+ var frameIndex = 0;
+ for (var i = 0, n = values.length; i < n; i++) {
+ var valueMap = values[i];
+ timeline.setFrame(frameIndex++, valueMap["time"], valueMap["name"]);
+ }
+ timelines.push(timeline);
+ duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]);
+
+ } else
+ throw new Error("Invalid timeline type for a slot: " + timelineName + " (" + slotName + ")");
+ }
+ }
+
+ var bones = map["bones"];
+ for (var boneName in bones) {
+ if (!bones.hasOwnProperty(boneName)) continue;
+ var boneIndex = skeletonData.findBoneIndex(boneName);
+ if (boneIndex == -1) throw new Error("Bone not found: " + boneName);
+ var boneMap = bones[boneName];
+
+ for (var timelineName in boneMap) {
+ if (!boneMap.hasOwnProperty(timelineName)) continue;
+ var values = boneMap[timelineName];
+ if (timelineName == "rotate") {
+ var timeline = new spine.RotateTimeline(values.length);
+ timeline.boneIndex = boneIndex;
+
+ var frameIndex = 0;
+ for (var i = 0, n = values.length; i < n; i++) {
+ var valueMap = values[i];
+ timeline.setFrame(frameIndex, valueMap["time"], valueMap["angle"]);
+ this.readCurve(timeline, frameIndex, valueMap);
+ frameIndex++;
+ }
+ timelines.push(timeline);
+ duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 2 - 2]);
+
+ } else if (timelineName == "translate" || timelineName == "scale") {
+ var timeline;
+ var timelineScale = 1;
+ if (timelineName == "scale")
+ timeline = new spine.ScaleTimeline(values.length);
+ else {
+ timeline = new spine.TranslateTimeline(values.length);
+ timelineScale = this.scale;
+ }
+ timeline.boneIndex = boneIndex;
+
+ var frameIndex = 0;
+ for (var i = 0, n = values.length; i < n; i++) {
+ var valueMap = values[i];
+ var x = (valueMap["x"] || 0) * timelineScale;
+ var y = (valueMap["y"] || 0) * timelineScale;
+ timeline.setFrame(frameIndex, valueMap["time"], x, y);
+ this.readCurve(timeline, frameIndex, valueMap);
+ frameIndex++;
+ }
+ timelines.push(timeline);
+ duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 3 - 3]);
+
+ } else if (timelineName == "flipX" || timelineName == "flipY") {
+ var x = timelineName == "flipX";
+ var timeline = x ? new spine.FlipXTimeline(values.length) : new spine.FlipYTimeline(values.length);
+ timeline.boneIndex = boneIndex;
+
+ var field = x ? "x" : "y";
+ var frameIndex = 0;
+ for (var i = 0, n = values.length; i < n; i++) {
+ var valueMap = values[i];
+ timeline.setFrame(frameIndex, valueMap["time"], valueMap[field] || false);
+ frameIndex++;
+ }
+ timelines.push(timeline);
+ duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 2 - 2]);
+ } else
+ throw new Error("Invalid timeline type for a bone: " + timelineName + " (" + boneName + ")");
+ }
+ }
+
+ var ikMap = map["ik"];
+ for (var ikConstraintName in ikMap) {
+ if (!ikMap.hasOwnProperty(ikConstraintName)) continue;
+ var ikConstraint = skeletonData.findIkConstraint(ikConstraintName);
+ var values = ikMap[ikConstraintName];
+ var timeline = new spine.IkConstraintTimeline(values.length);
+ timeline.ikConstraintIndex = skeletonData.ikConstraints.indexOf(ikConstraint);
+ var frameIndex = 0;
+ for (var i = 0, n = values.length; i < n; i++) {
+ var valueMap = values[i];
+ var mix = valueMap.hasOwnProperty("mix") ? valueMap["mix"] : 1;
+ var bendDirection = (!valueMap.hasOwnProperty("bendPositive") || valueMap["bendPositive"]) ? 1 : -1;
+ timeline.setFrame(frameIndex, valueMap["time"], mix, bendDirection);
+ this.readCurve(timeline, frameIndex, valueMap);
+ frameIndex++;
+ }
+ timelines.push(timeline);
+ duration = Math.max(duration, timeline.frames[timeline.frameCount * 3 - 3]);
+ }
+
+ var ffd = map["ffd"];
+ for (var skinName in ffd) {
+ var skin = skeletonData.findSkin(skinName);
+ var slotMap = ffd[skinName];
+ for (slotName in slotMap) {
+ var slotIndex = skeletonData.findSlotIndex(slotName);
+ var meshMap = slotMap[slotName];
+ for (var meshName in meshMap) {
+ var values = meshMap[meshName];
+ var timeline = new spine.FfdTimeline(values.length);
+ var attachment = skin.getAttachment(slotIndex, meshName);
+ if (!attachment) throw new Error("FFD attachment not found: " + meshName);
+ timeline.slotIndex = slotIndex;
+ timeline.attachment = attachment;
+
+ var isMesh = attachment.type == spine.AttachmentType.mesh;
+ var vertexCount;
+ if (isMesh)
+ vertexCount = attachment.vertices.length;
+ else
+ vertexCount = attachment.weights.length / 3 * 2;
+
+ var frameIndex = 0;
+ for (var i = 0, n = values.length; i < n; i++) {
+ var valueMap = values[i];
+ var vertices;
+ if (!valueMap["vertices"]) {
+ if (isMesh)
+ vertices = attachment.vertices;
+ else {
+ vertices = [];
+ vertices.length = vertexCount;
+ }
+ } else {
+ var verticesValue = valueMap["vertices"];
+ var vertices = [];
+ vertices.length = vertexCount;
+ var start = valueMap["offset"] || 0;
+ var nn = verticesValue.length;
+ if (this.scale == 1) {
+ for (var ii = 0; ii < nn; ii++)
+ vertices[ii + start] = verticesValue[ii];
+ } else {
+ for (var ii = 0; ii < nn; ii++)
+ vertices[ii + start] = verticesValue[ii] * this.scale;
+ }
+ if (isMesh) {
+ var meshVertices = attachment.vertices;
+ for (var ii = 0, nn = vertices.length; ii < nn; ii++)
+ vertices[ii] += meshVertices[ii];
+ }
+ }
+
+ timeline.setFrame(frameIndex, valueMap["time"], vertices);
+ this.readCurve(timeline, frameIndex, valueMap);
+ frameIndex++;
+ }
+ timelines[timelines.length] = timeline;
+ duration = Math.max(duration, timeline.frames[timeline.frameCount - 1]);
+ }
+ }
+ }
+
+ var drawOrderValues = map["drawOrder"];
+ if (!drawOrderValues) drawOrderValues = map["draworder"];
+ if (drawOrderValues) {
+ var timeline = new spine.DrawOrderTimeline(drawOrderValues.length);
+ var slotCount = skeletonData.slots.length;
+ var frameIndex = 0;
+ for (var i = 0, n = drawOrderValues.length; i < n; i++) {
+ var drawOrderMap = drawOrderValues[i];
+ var drawOrder = null;
+ if (drawOrderMap["offsets"]) {
+ drawOrder = [];
+ drawOrder.length = slotCount;
+ for (var ii = slotCount - 1; ii >= 0; ii--)
+ drawOrder[ii] = -1;
+ var offsets = drawOrderMap["offsets"];
+ var unchanged = [];
+ unchanged.length = slotCount - offsets.length;
+ var originalIndex = 0, unchangedIndex = 0;
+ for (var ii = 0, nn = offsets.length; ii < nn; ii++) {
+ var offsetMap = offsets[ii];
+ var slotIndex = skeletonData.findSlotIndex(offsetMap["slot"]);
+ if (slotIndex == -1) throw new Error("Slot not found: " + offsetMap["slot"]);
+ // Collect unchanged items.
+ while (originalIndex != slotIndex)
+ unchanged[unchangedIndex++] = originalIndex++;
+ // Set changed items.
+ drawOrder[originalIndex + offsetMap["offset"]] = originalIndex++;
+ }
+ // Collect remaining unchanged items.
+ while (originalIndex < slotCount)
+ unchanged[unchangedIndex++] = originalIndex++;
+ // Fill in unchanged items.
+ for (var ii = slotCount - 1; ii >= 0; ii--)
+ if (drawOrder[ii] == -1) drawOrder[ii] = unchanged[--unchangedIndex];
+ }
+ timeline.setFrame(frameIndex++, drawOrderMap["time"], drawOrder);
+ }
+ timelines.push(timeline);
+ duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]);
+ }
+
+ var events = map["events"];
+ if (events) {
+ var timeline = new spine.EventTimeline(events.length);
+ var frameIndex = 0;
+ for (var i = 0, n = events.length; i < n; i++) {
+ var eventMap = events[i];
+ var eventData = skeletonData.findEvent(eventMap["name"]);
+ if (!eventData) throw new Error("Event not found: " + eventMap["name"]);
+ var event = new spine.Event(eventData);
+ event.intValue = eventMap.hasOwnProperty("int") ? eventMap["int"] : eventData.intValue;
+ event.floatValue = eventMap.hasOwnProperty("float") ? eventMap["float"] : eventData.floatValue;
+ event.stringValue = eventMap.hasOwnProperty("string") ? eventMap["string"] : eventData.stringValue;
+ timeline.setFrame(frameIndex++, eventMap["time"], event);
+ }
+ timelines.push(timeline);
+ duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]);
+ }
+
+ skeletonData.animations.push(new spine.Animation(name, timelines, duration));
+ },
+ readCurve: function (timeline, frameIndex, valueMap) {
+ var curve = valueMap["curve"];
+ if (!curve)
+ timeline.curves.setLinear(frameIndex);
+ else if (curve == "stepped")
+ timeline.curves.setStepped(frameIndex);
+ else if (curve instanceof Array)
+ timeline.curves.setCurve(frameIndex, curve[0], curve[1], curve[2], curve[3]);
+ },
+ toColor: function (hexString, colorIndex) {
+ if (hexString.length != 8) throw new Error("Color hexidecimal length must be 8, recieved: " + hexString);
+ return parseInt(hexString.substring(colorIndex * 2, (colorIndex * 2) + 2), 16) / 255;
+ },
+ getFloatArray: function (map, name, scale) {
+ var list = map[name];
+ var values = new spine.Float32Array(list.length);
+ var i = 0, n = list.length;
+ if (scale == 1) {
+ for (; i < n; i++)
+ values[i] = list[i];
+ } else {
+ for (; i < n; i++)
+ values[i] = list[i] * scale;
+ }
+ return values;
+ },
+ getIntArray: function (map, name) {
+ var list = map[name];
+ var values = new spine.Uint16Array(list.length);
+ for (var i = 0, n = list.length; i < n; i++)
+ values[i] = list[i] | 0;
+ return values;
+ }
+};
+
+spine.Atlas = function (atlasText, textureLoader) {
+ this.textureLoader = textureLoader;
+ this.pages = [];
+ this.regions = [];
+
+ var reader = new spine.AtlasReader(atlasText);
+ var tuple = [];
+ tuple.length = 4;
+ var page = null;
+ while (true) {
+ var line = reader.readLine();
+ if (line === null) break;
+ line = reader.trim(line);
+ if (!line.length)
+ page = null;
+ else if (!page) {
+ page = new spine.AtlasPage();
+ page.name = line;
+
+ if (reader.readTuple(tuple) == 2) { // size is only optional for an atlas packed with an old TexturePacker.
+ page.width = parseInt(tuple[0]);
+ page.height = parseInt(tuple[1]);
+ reader.readTuple(tuple);
+ }
+ page.format = spine.Atlas.Format[tuple[0]];
+
+ reader.readTuple(tuple);
+ page.minFilter = spine.Atlas.TextureFilter[tuple[0]];
+ page.magFilter = spine.Atlas.TextureFilter[tuple[1]];
+
+ var direction = reader.readValue();
+ page.uWrap = spine.Atlas.TextureWrap.clampToEdge;
+ page.vWrap = spine.Atlas.TextureWrap.clampToEdge;
+ if (direction == "x")
+ page.uWrap = spine.Atlas.TextureWrap.repeat;
+ else if (direction == "y")
+ page.vWrap = spine.Atlas.TextureWrap.repeat;
+ else if (direction == "xy")
+ page.uWrap = page.vWrap = spine.Atlas.TextureWrap.repeat;
+
+ textureLoader.load(page, line, this);
+
+ this.pages.push(page);
+
+ } else {
+ var region = new spine.AtlasRegion();
+ region.name = line;
+ region.page = page;
+
+ region.rotate = reader.readValue() == "true";
+
+ reader.readTuple(tuple);
+ var x = parseInt(tuple[0]);
+ var y = parseInt(tuple[1]);
+
+ reader.readTuple(tuple);
+ var width = parseInt(tuple[0]);
+ var height = parseInt(tuple[1]);
+
+ region.u = x / page.width;
+ region.v = y / page.height;
+ if (region.rotate) {
+ region.u2 = (x + height) / page.width;
+ region.v2 = (y + width) / page.height;
+ } else {
+ region.u2 = (x + width) / page.width;
+ region.v2 = (y + height) / page.height;
+ }
+ region.x = x;
+ region.y = y;
+ region.width = Math.abs(width);
+ region.height = Math.abs(height);
+
+ if (reader.readTuple(tuple) == 4) { // split is optional
+ region.splits = [parseInt(tuple[0]), parseInt(tuple[1]), parseInt(tuple[2]), parseInt(tuple[3])];
+
+ if (reader.readTuple(tuple) == 4) { // pad is optional, but only present with splits
+ region.pads = [parseInt(tuple[0]), parseInt(tuple[1]), parseInt(tuple[2]), parseInt(tuple[3])];
+
+ reader.readTuple(tuple);
+ }
+ }
+
+ region.originalWidth = parseInt(tuple[0]);
+ region.originalHeight = parseInt(tuple[1]);
+
+ reader.readTuple(tuple);
+ region.offsetX = parseInt(tuple[0]);
+ region.offsetY = parseInt(tuple[1]);
+
+ region.index = parseInt(reader.readValue());
+
+ this.regions.push(region);
+ }
+ }
+};
+spine.Atlas.prototype = {
+ findRegion: function (name) {
+ var regions = this.regions;
+ for (var i = 0, n = regions.length; i < n; i++)
+ if (regions[i].name == name) return regions[i];
+ return null;
+ },
+ dispose: function () {
+ var pages = this.pages;
+ for (var i = 0, n = pages.length; i < n; i++)
+ this.textureLoader.unload(pages[i].rendererObject);
+ },
+ updateUVs: function (page) {
+ var regions = this.regions;
+ for (var i = 0, n = regions.length; i < n; i++) {
+ var region = regions[i];
+ if (region.page != page) continue;
+ region.u = region.x / page.width;
+ region.v = region.y / page.height;
+ if (region.rotate) {
+ region.u2 = (region.x + region.height) / page.width;
+ region.v2 = (region.y + region.width) / page.height;
+ } else {
+ region.u2 = (region.x + region.width) / page.width;
+ region.v2 = (region.y + region.height) / page.height;
+ }
+ }
+ }
+};
+
+spine.Atlas.Format = {
+ alpha: 0,
+ intensity: 1,
+ luminanceAlpha: 2,
+ rgb565: 3,
+ rgba4444: 4,
+ rgb888: 5,
+ rgba8888: 6
+};
+
+spine.Atlas.TextureFilter = {
+ nearest: 0,
+ linear: 1,
+ mipMap: 2,
+ mipMapNearestNearest: 3,
+ mipMapLinearNearest: 4,
+ mipMapNearestLinear: 5,
+ mipMapLinearLinear: 6
+};
+
+spine.Atlas.TextureWrap = {
+ mirroredRepeat: 0,
+ clampToEdge: 1,
+ repeat: 2
+};
+
+spine.AtlasPage = function () {};
+spine.AtlasPage.prototype = {
+ name: null,
+ format: null,
+ minFilter: null,
+ magFilter: null,
+ uWrap: null,
+ vWrap: null,
+ rendererObject: null,
+ width: 0,
+ height: 0
+};
+
+spine.AtlasRegion = function () {};
+spine.AtlasRegion.prototype = {
+ page: null,
+ name: null,
+ x: 0, y: 0,
+ width: 0, height: 0,
+ u: 0, v: 0, u2: 0, v2: 0,
+ offsetX: 0, offsetY: 0,
+ originalWidth: 0, originalHeight: 0,
+ index: 0,
+ rotate: false,
+ splits: null,
+ pads: null
+};
+
+spine.AtlasReader = function (text) {
+ this.lines = text.split(/\r\n|\r|\n/);
+};
+spine.AtlasReader.prototype = {
+ index: 0,
+ trim: function (value) {
+ return value.replace(/^\s+|\s+$/g, "");
+ },
+ readLine: function () {
+ if (this.index >= this.lines.length) return null;
+ return this.lines[this.index++];
+ },
+ readValue: function () {
+ var line = this.readLine();
+ var colon = line.indexOf(":");
+ if (colon == -1) throw new Error("Invalid line: " + line);
+ return this.trim(line.substring(colon + 1));
+ },
+ /** Returns the number of tuple values read (1, 2 or 4). */
+ readTuple: function (tuple) {
+ var line = this.readLine();
+ var colon = line.indexOf(":");
+ if (colon == -1) throw new Error("Invalid line: " + line);
+ var i = 0, lastMatch = colon + 1;
+ for (; i < 3; i++) {
+ var comma = line.indexOf(",", lastMatch);
+ if (comma == -1) break;
+ tuple[i] = this.trim(line.substr(lastMatch, comma - lastMatch));
+ lastMatch = comma + 1;
+ }
+ tuple[i] = this.trim(line.substring(lastMatch));
+ return i + 1;
+ }
+};
+
+spine.AtlasAttachmentLoader = function (atlas) {
+ this.atlas = atlas;
+};
+spine.AtlasAttachmentLoader.prototype = {
+ newRegionAttachment: function (skin, name, path) {
+ var region = this.atlas.findRegion(path);
+ if (!region) throw new Error("Region not found in atlas: " + path + " (region attachment: " + name + ")");
+ var attachment = new spine.RegionAttachment(name);
+ attachment.rendererObject = region;
+ attachment.setUVs(region.u, region.v, region.u2, region.v2, region.rotate);
+ attachment.regionOffsetX = region.offsetX;
+ attachment.regionOffsetY = region.offsetY;
+ attachment.regionWidth = region.width;
+ attachment.regionHeight = region.height;
+ attachment.regionOriginalWidth = region.originalWidth;
+ attachment.regionOriginalHeight = region.originalHeight;
+ return attachment;
+ },
+ newMeshAttachment: function (skin, name, path) {
+ var region = this.atlas.findRegion(path);
+ if (!region) throw new Error("Region not found in atlas: " + path + " (mesh attachment: " + name + ")");
+ var attachment = new spine.MeshAttachment(name);
+ attachment.rendererObject = region;
+ attachment.regionU = region.u;
+ attachment.regionV = region.v;
+ attachment.regionU2 = region.u2;
+ attachment.regionV2 = region.v2;
+ attachment.regionRotate = region.rotate;
+ attachment.regionOffsetX = region.offsetX;
+ attachment.regionOffsetY = region.offsetY;
+ attachment.regionWidth = region.width;
+ attachment.regionHeight = region.height;
+ attachment.regionOriginalWidth = region.originalWidth;
+ attachment.regionOriginalHeight = region.originalHeight;
+ return attachment;
+ },
+ newSkinnedMeshAttachment: function (skin, name, path) {
+ var region = this.atlas.findRegion(path);
+ if (!region) throw new Error("Region not found in atlas: " + path + " (skinned mesh attachment: " + name + ")");
+ var attachment = new spine.SkinnedMeshAttachment(name);
+ attachment.rendererObject = region;
+ attachment.regionU = region.u;
+ attachment.regionV = region.v;
+ attachment.regionU2 = region.u2;
+ attachment.regionV2 = region.v2;
+ attachment.regionRotate = region.rotate;
+ attachment.regionOffsetX = region.offsetX;
+ attachment.regionOffsetY = region.offsetY;
+ attachment.regionWidth = region.width;
+ attachment.regionHeight = region.height;
+ attachment.regionOriginalWidth = region.originalWidth;
+ attachment.regionOriginalHeight = region.originalHeight;
+ return attachment;
+ },
+ newBoundingBoxAttachment: function (skin, name) {
+ return new spine.BoundingBoxAttachment(name);
+ }
+};
+
+spine.SkeletonBounds = function () {
+ this.polygonPool = [];
+ this.polygons = [];
+ this.boundingBoxes = [];
+};
+spine.SkeletonBounds.prototype = {
+ minX: 0, minY: 0, maxX: 0, maxY: 0,
+ update: function (skeleton, updateAabb) {
+ var slots = skeleton.slots;
+ var slotCount = slots.length;
+ var x = skeleton.x, y = skeleton.y;
+ var boundingBoxes = this.boundingBoxes;
+ var polygonPool = this.polygonPool;
+ var polygons = this.polygons;
+
+ boundingBoxes.length = 0;
+ for (var i = 0, n = polygons.length; i < n; i++)
+ polygonPool.push(polygons[i]);
+ polygons.length = 0;
+
+ for (var i = 0; i < slotCount; i++) {
+ var slot = slots[i];
+ var boundingBox = slot.attachment;
+ if (boundingBox.type != spine.AttachmentType.boundingbox) continue;
+ boundingBoxes.push(boundingBox);
+
+ var poolCount = polygonPool.length, polygon;
+ if (poolCount > 0) {
+ polygon = polygonPool[poolCount - 1];
+ polygonPool.splice(poolCount - 1, 1);
+ } else
+ polygon = [];
+ polygons.push(polygon);
+
+ polygon.length = boundingBox.vertices.length;
+ boundingBox.computeWorldVertices(x, y, slot.bone, polygon);
+ }
+
+ if (updateAabb) this.aabbCompute();
+ },
+ aabbCompute: function () {
+ var polygons = this.polygons;
+ var minX = Number.MAX_VALUE, minY = Number.MAX_VALUE, maxX = Number.MIN_VALUE, maxY = Number.MIN_VALUE;
+ for (var i = 0, n = polygons.length; i < n; i++) {
+ var vertices = polygons[i];
+ for (var ii = 0, nn = vertices.length; ii < nn; ii += 2) {
+ var x = vertices[ii];
+ var y = vertices[ii + 1];
+ minX = Math.min(minX, x);
+ minY = Math.min(minY, y);
+ maxX = Math.max(maxX, x);
+ maxY = Math.max(maxY, y);
+ }
+ }
+ this.minX = minX;
+ this.minY = minY;
+ this.maxX = maxX;
+ this.maxY = maxY;
+ },
+ /** Returns true if the axis aligned bounding box contains the point. */
+ aabbContainsPoint: function (x, y) {
+ return x >= this.minX && x <= this.maxX && y >= this.minY && y <= this.maxY;
+ },
+ /** Returns true if the axis aligned bounding box intersects the line segment. */
+ aabbIntersectsSegment: function (x1, y1, x2, y2) {
+ var minX = this.minX, minY = this.minY, maxX = this.maxX, maxY = this.maxY;
+ if ((x1 <= minX && x2 <= minX) || (y1 <= minY && y2 <= minY) || (x1 >= maxX && x2 >= maxX) || (y1 >= maxY && y2 >= maxY))
+ return false;
+ var m = (y2 - y1) / (x2 - x1);
+ var y = m * (minX - x1) + y1;
+ if (y > minY && y < maxY) return true;
+ y = m * (maxX - x1) + y1;
+ if (y > minY && y < maxY) return true;
+ var x = (minY - y1) / m + x1;
+ if (x > minX && x < maxX) return true;
+ x = (maxY - y1) / m + x1;
+ if (x > minX && x < maxX) return true;
+ return false;
+ },
+ /** Returns true if the axis aligned bounding box intersects the axis aligned bounding box of the specified bounds. */
+ aabbIntersectsSkeleton: function (bounds) {
+ return this.minX < bounds.maxX && this.maxX > bounds.minX && this.minY < bounds.maxY && this.maxY > bounds.minY;
+ },
+ /** Returns the first bounding box attachment that contains the point, or null. When doing many checks, it is usually more
+ * efficient to only call this method if {@link #aabbContainsPoint(float, float)} returns true. */
+ containsPoint: function (x, y) {
+ var polygons = this.polygons;
+ for (var i = 0, n = polygons.length; i < n; i++)
+ if (this.polygonContainsPoint(polygons[i], x, y)) return this.boundingBoxes[i];
+ return null;
+ },
+ /** Returns the first bounding box attachment that contains the line segment, or null. When doing many checks, it is usually
+ * more efficient to only call this method if {@link #aabbIntersectsSegment(float, float, float, float)} returns true. */
+ intersectsSegment: function (x1, y1, x2, y2) {
+ var polygons = this.polygons;
+ for (var i = 0, n = polygons.length; i < n; i++)
+ if (polygons[i].intersectsSegment(x1, y1, x2, y2)) return this.boundingBoxes[i];
+ return null;
+ },
+ /** Returns true if the polygon contains the point. */
+ polygonContainsPoint: function (polygon, x, y) {
+ var nn = polygon.length;
+ var prevIndex = nn - 2;
+ var inside = false;
+ for (var ii = 0; ii < nn; ii += 2) {
+ var vertexY = polygon[ii + 1];
+ var prevY = polygon[prevIndex + 1];
+ if ((vertexY < y && prevY >= y) || (prevY < y && vertexY >= y)) {
+ var vertexX = polygon[ii];
+ if (vertexX + (y - vertexY) / (prevY - vertexY) * (polygon[prevIndex] - vertexX) < x) inside = !inside;
+ }
+ prevIndex = ii;
+ }
+ return inside;
+ },
+ /** Returns true if the polygon contains the line segment. */
+ polygonIntersectsSegment: function (polygon, x1, y1, x2, y2) {
+ var nn = polygon.length;
+ var width12 = x1 - x2, height12 = y1 - y2;
+ var det1 = x1 * y2 - y1 * x2;
+ var x3 = polygon[nn - 2], y3 = polygon[nn - 1];
+ for (var ii = 0; ii < nn; ii += 2) {
+ var x4 = polygon[ii], y4 = polygon[ii + 1];
+ var det2 = x3 * y4 - y3 * x4;
+ var width34 = x3 - x4, height34 = y3 - y4;
+ var det3 = width12 * height34 - height12 * width34;
+ var x = (det1 * width34 - width12 * det2) / det3;
+ if (((x >= x3 && x <= x4) || (x >= x4 && x <= x3)) && ((x >= x1 && x <= x2) || (x >= x2 && x <= x1))) {
+ var y = (det1 * height34 - height12 * det2) / det3;
+ if (((y >= y3 && y <= y4) || (y >= y4 && y <= y3)) && ((y >= y1 && y <= y2) || (y >= y2 && y <= y1))) return true;
+ }
+ x3 = x4;
+ y3 = y4;
+ }
+ return false;
+ },
+ getPolygon: function (attachment) {
+ var index = this.boundingBoxes.indexOf(attachment);
+ return index == -1 ? null : this.polygons[index];
+ },
+ getWidth: function () {
+ return this.maxX - this.minX;
+ },
+ getHeight: function () {
+ return this.maxY - this.minY;
+ }
+};
diff --git a/external/box2d/box2d.js b/external/box2d/box2d.js
new file mode 100644
index 0000000000..55fc3b047e
--- /dev/null
+++ b/external/box2d/box2d.js
@@ -0,0 +1,10882 @@
+/*
+ * Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
+ *
+ * This software is provided 'as-is', without any express or implied
+ * warranty. In no event will the authors be held liable for any damages
+ * arising from the use of this software.
+ * Permission is granted to anyone to use this software for any purpose,
+ * including commercial applications, and to alter it and redistribute it
+ * freely, subject to the following restrictions:
+ * 1. The origin of this software must not be misrepresented; you must not
+ * claim that you wrote the original software. If you use this software
+ * in a product, an acknowledgment in the product documentation would be
+ * appreciated but is not required.
+ * 2. Altered source versions must be plainly marked as such, and must not be
+ * misrepresented as being the original software.
+ * 3. This notice may not be removed or altered from any source distribution.
+ *
+ *
+ * Sean Lin 2012-5-8,
+ *
+ * The library is box2dweb, http://code.google.com/p/box2dweb/
+ *
+ * It is a port of Box2DFlash 2.1a to JavaScript.
+ * You can read the documentation for Box2dFlash, since nearly everything is
+ * organized the same way. http://www.box2dflash.org/docs/2.1a/reference/
+ *
+ */
+
+var Box2D = {};
+
+(function (a2j, undefined) {
+
+ if(!(Object.defineProperty instanceof Function)
+ && Object.prototype.__defineGetter__ instanceof Function
+ && Object.prototype.__defineSetter__ instanceof Function)
+ {
+ Object.defineProperty = function(obj, p, cfg) {
+ if(cfg.get instanceof Function)
+ obj.__defineGetter__(p, cfg.get);
+ if(cfg.set instanceof Function)
+ obj.__defineSetter__(p, cfg.set);
+ }
+ }
+
+ function emptyFn() {};
+ a2j.inherit = function(cls, base) {
+ var tmpCtr = cls;
+ emptyFn.prototype = base.prototype;
+ cls.prototype = new emptyFn;
+ cls.prototype.constructor = tmpCtr;
+ };
+
+ a2j.generateCallback = function generateCallback(context, cb) {
+ return function () {
+ cb.apply(context, arguments);
+ };
+ };
+
+ a2j.NVector = function NVector(length) {
+ if (length === undefined) length = 0;
+ var tmp = new Array(length || 0);
+ for (var i = 0; i < length; ++i)
+ tmp[i] = 0;
+ return tmp;
+ };
+
+ a2j.is = function is(o1, o2) {
+ if (o1 === null) return false;
+ if ((o2 instanceof Function) && (o1 instanceof o2)) return true;
+ if ((o1.constructor.__implements != undefined) && (o1.constructor.__implements[o2])) return true;
+ return false;
+ };
+
+ a2j.parseUInt = function(v) {
+ return Math.abs(parseInt(v));
+ }
+
+})(Box2D);
+
+//#TODO remove assignments from global namespace
+var Vector = Array;
+var Vector_a2j_Number = Box2D.NVector;
+//package structure
+if (typeof(Box2D) === "undefined") Box2D = {};
+if (typeof(Box2D.Collision) === "undefined") Box2D.Collision = {};
+if (typeof(Box2D.Collision.Shapes) === "undefined") Box2D.Collision.Shapes = {};
+if (typeof(Box2D.Common) === "undefined") Box2D.Common = {};
+if (typeof(Box2D.Common.Math) === "undefined") Box2D.Common.Math = {};
+if (typeof(Box2D.Dynamics) === "undefined") Box2D.Dynamics = {};
+if (typeof(Box2D.Dynamics.Contacts) === "undefined") Box2D.Dynamics.Contacts = {};
+if (typeof(Box2D.Dynamics.Controllers) === "undefined") Box2D.Dynamics.Controllers = {};
+if (typeof(Box2D.Dynamics.Joints) === "undefined") Box2D.Dynamics.Joints = {};
+//pre-definitions
+(function () {
+ Box2D.Collision.IBroadPhase = 'Box2D.Collision.IBroadPhase';
+
+ function b2AABB() {
+ b2AABB.b2AABB.apply(this, arguments);
+ };
+ Box2D.Collision.b2AABB = b2AABB;
+
+ function b2Bound() {
+ b2Bound.b2Bound.apply(this, arguments);
+ };
+ Box2D.Collision.b2Bound = b2Bound;
+
+ function b2BoundValues() {
+ b2BoundValues.b2BoundValues.apply(this, arguments);
+ if (this.constructor === b2BoundValues) this.b2BoundValues.apply(this, arguments);
+ };
+ Box2D.Collision.b2BoundValues = b2BoundValues;
+
+ function b2Collision() {
+ b2Collision.b2Collision.apply(this, arguments);
+ };
+ Box2D.Collision.b2Collision = b2Collision;
+
+ function b2ContactID() {
+ b2ContactID.b2ContactID.apply(this, arguments);
+ if (this.constructor === b2ContactID) this.b2ContactID.apply(this, arguments);
+ };
+ Box2D.Collision.b2ContactID = b2ContactID;
+
+ function b2ContactPoint() {
+ b2ContactPoint.b2ContactPoint.apply(this, arguments);
+ };
+ Box2D.Collision.b2ContactPoint = b2ContactPoint;
+
+ function b2Distance() {
+ b2Distance.b2Distance.apply(this, arguments);
+ };
+ Box2D.Collision.b2Distance = b2Distance;
+
+ function b2DistanceInput() {
+ b2DistanceInput.b2DistanceInput.apply(this, arguments);
+ };
+ Box2D.Collision.b2DistanceInput = b2DistanceInput;
+
+ function b2DistanceOutput() {
+ b2DistanceOutput.b2DistanceOutput.apply(this, arguments);
+ };
+ Box2D.Collision.b2DistanceOutput = b2DistanceOutput;
+
+ function b2DistanceProxy() {
+ b2DistanceProxy.b2DistanceProxy.apply(this, arguments);
+ };
+ Box2D.Collision.b2DistanceProxy = b2DistanceProxy;
+
+ function b2DynamicTree() {
+ b2DynamicTree.b2DynamicTree.apply(this, arguments);
+ if (this.constructor === b2DynamicTree) this.b2DynamicTree.apply(this, arguments);
+ };
+ Box2D.Collision.b2DynamicTree = b2DynamicTree;
+
+ function b2DynamicTreeBroadPhase() {
+ b2DynamicTreeBroadPhase.b2DynamicTreeBroadPhase.apply(this, arguments);
+ };
+ Box2D.Collision.b2DynamicTreeBroadPhase = b2DynamicTreeBroadPhase;
+
+ function b2DynamicTreeNode() {
+ b2DynamicTreeNode.b2DynamicTreeNode.apply(this, arguments);
+ };
+ Box2D.Collision.b2DynamicTreeNode = b2DynamicTreeNode;
+
+ function b2DynamicTreePair() {
+ b2DynamicTreePair.b2DynamicTreePair.apply(this, arguments);
+ };
+ Box2D.Collision.b2DynamicTreePair = b2DynamicTreePair;
+
+ function b2Manifold() {
+ b2Manifold.b2Manifold.apply(this, arguments);
+ if (this.constructor === b2Manifold) this.b2Manifold.apply(this, arguments);
+ };
+ Box2D.Collision.b2Manifold = b2Manifold;
+
+ function b2ManifoldPoint() {
+ b2ManifoldPoint.b2ManifoldPoint.apply(this, arguments);
+ if (this.constructor === b2ManifoldPoint) this.b2ManifoldPoint.apply(this, arguments);
+ };
+ Box2D.Collision.b2ManifoldPoint = b2ManifoldPoint;
+
+ function b2Point() {
+ b2Point.b2Point.apply(this, arguments);
+ };
+ Box2D.Collision.b2Point = b2Point;
+
+ function b2RayCastInput() {
+ b2RayCastInput.b2RayCastInput.apply(this, arguments);
+ if (this.constructor === b2RayCastInput) this.b2RayCastInput.apply(this, arguments);
+ };
+ Box2D.Collision.b2RayCastInput = b2RayCastInput;
+
+ function b2RayCastOutput() {
+ b2RayCastOutput.b2RayCastOutput.apply(this, arguments);
+ };
+ Box2D.Collision.b2RayCastOutput = b2RayCastOutput;
+
+ function b2Segment() {
+ b2Segment.b2Segment.apply(this, arguments);
+ };
+ Box2D.Collision.b2Segment = b2Segment;
+
+ function b2SeparationFunction() {
+ b2SeparationFunction.b2SeparationFunction.apply(this, arguments);
+ };
+ Box2D.Collision.b2SeparationFunction = b2SeparationFunction;
+
+ function b2Simplex() {
+ b2Simplex.b2Simplex.apply(this, arguments);
+ if (this.constructor === b2Simplex) this.b2Simplex.apply(this, arguments);
+ };
+ Box2D.Collision.b2Simplex = b2Simplex;
+
+ function b2SimplexCache() {
+ b2SimplexCache.b2SimplexCache.apply(this, arguments);
+ };
+ Box2D.Collision.b2SimplexCache = b2SimplexCache;
+
+ function b2SimplexVertex() {
+ b2SimplexVertex.b2SimplexVertex.apply(this, arguments);
+ };
+ Box2D.Collision.b2SimplexVertex = b2SimplexVertex;
+
+ function b2TimeOfImpact() {
+ b2TimeOfImpact.b2TimeOfImpact.apply(this, arguments);
+ };
+ Box2D.Collision.b2TimeOfImpact = b2TimeOfImpact;
+
+ function b2TOIInput() {
+ b2TOIInput.b2TOIInput.apply(this, arguments);
+ };
+ Box2D.Collision.b2TOIInput = b2TOIInput;
+
+ function b2WorldManifold() {
+ b2WorldManifold.b2WorldManifold.apply(this, arguments);
+ if (this.constructor === b2WorldManifold) this.b2WorldManifold.apply(this, arguments);
+ };
+ Box2D.Collision.b2WorldManifold = b2WorldManifold;
+
+ function ClipVertex() {
+ ClipVertex.ClipVertex.apply(this, arguments);
+ };
+ Box2D.Collision.ClipVertex = ClipVertex;
+
+ function Features() {
+ Features.Features.apply(this, arguments);
+ };
+ Box2D.Collision.Features = Features;
+
+ function b2CircleShape() {
+ b2CircleShape.b2CircleShape.apply(this, arguments);
+ if (this.constructor === b2CircleShape) this.b2CircleShape.apply(this, arguments);
+ };
+ Box2D.Collision.Shapes.b2CircleShape = b2CircleShape;
+
+ function b2EdgeChainDef() {
+ b2EdgeChainDef.b2EdgeChainDef.apply(this, arguments);
+ if (this.constructor === b2EdgeChainDef) this.b2EdgeChainDef.apply(this, arguments);
+ };
+ Box2D.Collision.Shapes.b2EdgeChainDef = b2EdgeChainDef;
+
+ function b2EdgeShape() {
+ b2EdgeShape.b2EdgeShape.apply(this, arguments);
+ if (this.constructor === b2EdgeShape) this.b2EdgeShape.apply(this, arguments);
+ };
+ Box2D.Collision.Shapes.b2EdgeShape = b2EdgeShape;
+
+ function b2MassData() {
+ b2MassData.b2MassData.apply(this, arguments);
+ };
+ Box2D.Collision.Shapes.b2MassData = b2MassData;
+
+ function b2PolygonShape() {
+ b2PolygonShape.b2PolygonShape.apply(this, arguments);
+ if (this.constructor === b2PolygonShape) this.b2PolygonShape.apply(this, arguments);
+ };
+ Box2D.Collision.Shapes.b2PolygonShape = b2PolygonShape;
+
+ function b2Shape() {
+ b2Shape.b2Shape.apply(this, arguments);
+ if (this.constructor === b2Shape) this.b2Shape.apply(this, arguments);
+ };
+ Box2D.Collision.Shapes.b2Shape = b2Shape;
+ Box2D.Common.b2internal = 'Box2D.Common.b2internal';
+
+ function b2Color() {
+ b2Color.b2Color.apply(this, arguments);
+ if (this.constructor === b2Color) this.b2Color.apply(this, arguments);
+ };
+ Box2D.Common.b2Color = b2Color;
+
+ function b2Settings() {
+ b2Settings.b2Settings.apply(this, arguments);
+ };
+ Box2D.Common.b2Settings = b2Settings;
+
+ function b2Mat22() {
+ b2Mat22.b2Mat22.apply(this, arguments);
+ if (this.constructor === b2Mat22) this.b2Mat22.apply(this, arguments);
+ };
+ Box2D.Common.Math.b2Mat22 = b2Mat22;
+
+ function b2Mat33() {
+ b2Mat33.b2Mat33.apply(this, arguments);
+ if (this.constructor === b2Mat33) this.b2Mat33.apply(this, arguments);
+ };
+ Box2D.Common.Math.b2Mat33 = b2Mat33;
+
+ function b2Math() {
+ b2Math.b2Math.apply(this, arguments);
+ };
+ Box2D.Common.Math.b2Math = b2Math;
+
+ function b2Sweep() {
+ b2Sweep.b2Sweep.apply(this, arguments);
+ };
+ Box2D.Common.Math.b2Sweep = b2Sweep;
+
+ function b2Transform() {
+ b2Transform.b2Transform.apply(this, arguments);
+ if (this.constructor === b2Transform) this.b2Transform.apply(this, arguments);
+ };
+ Box2D.Common.Math.b2Transform = b2Transform;
+
+ function b2Vec2() {
+ b2Vec2.b2Vec2.apply(this, arguments);
+ if (this.constructor === b2Vec2) this.b2Vec2.apply(this, arguments);
+ };
+ Box2D.Common.Math.b2Vec2 = b2Vec2;
+
+ function b2Vec3() {
+ b2Vec3.b2Vec3.apply(this, arguments);
+ if (this.constructor === b2Vec3) this.b2Vec3.apply(this, arguments);
+ };
+ Box2D.Common.Math.b2Vec3 = b2Vec3;
+
+ function b2Body() {
+ b2Body.b2Body.apply(this, arguments);
+ if (this.constructor === b2Body) this.b2Body.apply(this, arguments);
+ };
+ Box2D.Dynamics.b2Body = b2Body;
+
+ function b2BodyDef() {
+ b2BodyDef.b2BodyDef.apply(this, arguments);
+ if (this.constructor === b2BodyDef) this.b2BodyDef.apply(this, arguments);
+ };
+ Box2D.Dynamics.b2BodyDef = b2BodyDef;
+
+ function b2ContactFilter() {
+ b2ContactFilter.b2ContactFilter.apply(this, arguments);
+ };
+ Box2D.Dynamics.b2ContactFilter = b2ContactFilter;
+
+ function b2ContactImpulse() {
+ b2ContactImpulse.b2ContactImpulse.apply(this, arguments);
+ };
+ Box2D.Dynamics.b2ContactImpulse = b2ContactImpulse;
+
+ function b2ContactListener() {
+ b2ContactListener.b2ContactListener.apply(this, arguments);
+ };
+ Box2D.Dynamics.b2ContactListener = b2ContactListener;
+
+ function b2ContactManager() {
+ b2ContactManager.b2ContactManager.apply(this, arguments);
+ if (this.constructor === b2ContactManager) this.b2ContactManager.apply(this, arguments);
+ };
+ Box2D.Dynamics.b2ContactManager = b2ContactManager;
+
+ function b2DebugDraw() {
+ b2DebugDraw.b2DebugDraw.apply(this, arguments);
+ if (this.constructor === b2DebugDraw) this.b2DebugDraw.apply(this, arguments);
+ };
+ Box2D.Dynamics.b2DebugDraw = b2DebugDraw;
+
+ function b2DestructionListener() {
+ b2DestructionListener.b2DestructionListener.apply(this, arguments);
+ };
+ Box2D.Dynamics.b2DestructionListener = b2DestructionListener;
+
+ function b2FilterData() {
+ b2FilterData.b2FilterData.apply(this, arguments);
+ };
+ Box2D.Dynamics.b2FilterData = b2FilterData;
+
+ function b2Fixture() {
+ b2Fixture.b2Fixture.apply(this, arguments);
+ if (this.constructor === b2Fixture) this.b2Fixture.apply(this, arguments);
+ };
+ Box2D.Dynamics.b2Fixture = b2Fixture;
+
+ function b2FixtureDef() {
+ b2FixtureDef.b2FixtureDef.apply(this, arguments);
+ if (this.constructor === b2FixtureDef) this.b2FixtureDef.apply(this, arguments);
+ };
+ Box2D.Dynamics.b2FixtureDef = b2FixtureDef;
+
+ function b2Island() {
+ b2Island.b2Island.apply(this, arguments);
+ if (this.constructor === b2Island) this.b2Island.apply(this, arguments);
+ };
+ Box2D.Dynamics.b2Island = b2Island;
+
+ function b2TimeStep() {
+ b2TimeStep.b2TimeStep.apply(this, arguments);
+ };
+ Box2D.Dynamics.b2TimeStep = b2TimeStep;
+
+ function b2World() {
+ b2World.b2World.apply(this, arguments);
+ if (this.constructor === b2World) this.b2World.apply(this, arguments);
+ };
+ Box2D.Dynamics.b2World = b2World;
+
+ function b2CircleContact() {
+ b2CircleContact.b2CircleContact.apply(this, arguments);
+ };
+ Box2D.Dynamics.Contacts.b2CircleContact = b2CircleContact;
+
+ function b2Contact() {
+ b2Contact.b2Contact.apply(this, arguments);
+ if (this.constructor === b2Contact) this.b2Contact.apply(this, arguments);
+ };
+ Box2D.Dynamics.Contacts.b2Contact = b2Contact;
+
+ function b2ContactConstraint() {
+ b2ContactConstraint.b2ContactConstraint.apply(this, arguments);
+ if (this.constructor === b2ContactConstraint) this.b2ContactConstraint.apply(this, arguments);
+ };
+ Box2D.Dynamics.Contacts.b2ContactConstraint = b2ContactConstraint;
+
+ function b2ContactConstraintPoint() {
+ b2ContactConstraintPoint.b2ContactConstraintPoint.apply(this, arguments);
+ };
+ Box2D.Dynamics.Contacts.b2ContactConstraintPoint = b2ContactConstraintPoint;
+
+ function b2ContactEdge() {
+ b2ContactEdge.b2ContactEdge.apply(this, arguments);
+ };
+ Box2D.Dynamics.Contacts.b2ContactEdge = b2ContactEdge;
+
+ function b2ContactFactory() {
+ b2ContactFactory.b2ContactFactory.apply(this, arguments);
+ if (this.constructor === b2ContactFactory) this.b2ContactFactory.apply(this, arguments);
+ };
+ Box2D.Dynamics.Contacts.b2ContactFactory = b2ContactFactory;
+
+ function b2ContactRegister() {
+ b2ContactRegister.b2ContactRegister.apply(this, arguments);
+ };
+ Box2D.Dynamics.Contacts.b2ContactRegister = b2ContactRegister;
+
+ function b2ContactResult() {
+ b2ContactResult.b2ContactResult.apply(this, arguments);
+ };
+ Box2D.Dynamics.Contacts.b2ContactResult = b2ContactResult;
+
+ function b2ContactSolver() {
+ b2ContactSolver.b2ContactSolver.apply(this, arguments);
+ if (this.constructor === b2ContactSolver) this.b2ContactSolver.apply(this, arguments);
+ };
+ Box2D.Dynamics.Contacts.b2ContactSolver = b2ContactSolver;
+
+ function b2EdgeAndCircleContact() {
+ b2EdgeAndCircleContact.b2EdgeAndCircleContact.apply(this, arguments);
+ };
+ Box2D.Dynamics.Contacts.b2EdgeAndCircleContact = b2EdgeAndCircleContact;
+
+ function b2NullContact() {
+ b2NullContact.b2NullContact.apply(this, arguments);
+ if (this.constructor === b2NullContact) this.b2NullContact.apply(this, arguments);
+ };
+ Box2D.Dynamics.Contacts.b2NullContact = b2NullContact;
+
+ function b2PolyAndCircleContact() {
+ b2PolyAndCircleContact.b2PolyAndCircleContact.apply(this, arguments);
+ };
+ Box2D.Dynamics.Contacts.b2PolyAndCircleContact = b2PolyAndCircleContact;
+
+ function b2PolyAndEdgeContact() {
+ b2PolyAndEdgeContact.b2PolyAndEdgeContact.apply(this, arguments);
+ };
+ Box2D.Dynamics.Contacts.b2PolyAndEdgeContact = b2PolyAndEdgeContact;
+
+ function b2PolygonContact() {
+ b2PolygonContact.b2PolygonContact.apply(this, arguments);
+ };
+ Box2D.Dynamics.Contacts.b2PolygonContact = b2PolygonContact;
+
+ function b2PositionSolverManifold() {
+ b2PositionSolverManifold.b2PositionSolverManifold.apply(this, arguments);
+ if (this.constructor === b2PositionSolverManifold) this.b2PositionSolverManifold.apply(this, arguments);
+ };
+ Box2D.Dynamics.Contacts.b2PositionSolverManifold = b2PositionSolverManifold;
+
+ function b2BuoyancyController() {
+ b2BuoyancyController.b2BuoyancyController.apply(this, arguments);
+ };
+ Box2D.Dynamics.Controllers.b2BuoyancyController = b2BuoyancyController;
+
+ function b2ConstantAccelController() {
+ b2ConstantAccelController.b2ConstantAccelController.apply(this, arguments);
+ };
+ Box2D.Dynamics.Controllers.b2ConstantAccelController = b2ConstantAccelController;
+
+ function b2ConstantForceController() {
+ b2ConstantForceController.b2ConstantForceController.apply(this, arguments);
+ };
+ Box2D.Dynamics.Controllers.b2ConstantForceController = b2ConstantForceController;
+
+ function b2Controller() {
+ b2Controller.b2Controller.apply(this, arguments);
+ };
+ Box2D.Dynamics.Controllers.b2Controller = b2Controller;
+
+ function b2ControllerEdge() {
+ b2ControllerEdge.b2ControllerEdge.apply(this, arguments);
+ };
+ Box2D.Dynamics.Controllers.b2ControllerEdge = b2ControllerEdge;
+
+ function b2GravityController() {
+ b2GravityController.b2GravityController.apply(this, arguments);
+ };
+ Box2D.Dynamics.Controllers.b2GravityController = b2GravityController;
+
+ function b2TensorDampingController() {
+ b2TensorDampingController.b2TensorDampingController.apply(this, arguments);
+ };
+ Box2D.Dynamics.Controllers.b2TensorDampingController = b2TensorDampingController;
+
+ function b2DistanceJoint() {
+ b2DistanceJoint.b2DistanceJoint.apply(this, arguments);
+ if (this.constructor === b2DistanceJoint) this.b2DistanceJoint.apply(this, arguments);
+ };
+ Box2D.Dynamics.Joints.b2DistanceJoint = b2DistanceJoint;
+
+ function b2DistanceJointDef() {
+ b2DistanceJointDef.b2DistanceJointDef.apply(this, arguments);
+ if (this.constructor === b2DistanceJointDef) this.b2DistanceJointDef.apply(this, arguments);
+ };
+ Box2D.Dynamics.Joints.b2DistanceJointDef = b2DistanceJointDef;
+
+ function b2FrictionJoint() {
+ b2FrictionJoint.b2FrictionJoint.apply(this, arguments);
+ if (this.constructor === b2FrictionJoint) this.b2FrictionJoint.apply(this, arguments);
+ };
+ Box2D.Dynamics.Joints.b2FrictionJoint = b2FrictionJoint;
+
+ function b2FrictionJointDef() {
+ b2FrictionJointDef.b2FrictionJointDef.apply(this, arguments);
+ if (this.constructor === b2FrictionJointDef) this.b2FrictionJointDef.apply(this, arguments);
+ };
+ Box2D.Dynamics.Joints.b2FrictionJointDef = b2FrictionJointDef;
+
+ function b2GearJoint() {
+ b2GearJoint.b2GearJoint.apply(this, arguments);
+ if (this.constructor === b2GearJoint) this.b2GearJoint.apply(this, arguments);
+ };
+ Box2D.Dynamics.Joints.b2GearJoint = b2GearJoint;
+
+ function b2GearJointDef() {
+ b2GearJointDef.b2GearJointDef.apply(this, arguments);
+ if (this.constructor === b2GearJointDef) this.b2GearJointDef.apply(this, arguments);
+ };
+ Box2D.Dynamics.Joints.b2GearJointDef = b2GearJointDef;
+
+ function b2Jacobian() {
+ b2Jacobian.b2Jacobian.apply(this, arguments);
+ };
+ Box2D.Dynamics.Joints.b2Jacobian = b2Jacobian;
+
+ function b2Joint() {
+ b2Joint.b2Joint.apply(this, arguments);
+ if (this.constructor === b2Joint) this.b2Joint.apply(this, arguments);
+ };
+ Box2D.Dynamics.Joints.b2Joint = b2Joint;
+
+ function b2JointDef() {
+ b2JointDef.b2JointDef.apply(this, arguments);
+ if (this.constructor === b2JointDef) this.b2JointDef.apply(this, arguments);
+ };
+ Box2D.Dynamics.Joints.b2JointDef = b2JointDef;
+
+ function b2JointEdge() {
+ b2JointEdge.b2JointEdge.apply(this, arguments);
+ };
+ Box2D.Dynamics.Joints.b2JointEdge = b2JointEdge;
+
+ function b2LineJoint() {
+ b2LineJoint.b2LineJoint.apply(this, arguments);
+ if (this.constructor === b2LineJoint) this.b2LineJoint.apply(this, arguments);
+ };
+ Box2D.Dynamics.Joints.b2LineJoint = b2LineJoint;
+
+ function b2LineJointDef() {
+ b2LineJointDef.b2LineJointDef.apply(this, arguments);
+ if (this.constructor === b2LineJointDef) this.b2LineJointDef.apply(this, arguments);
+ };
+ Box2D.Dynamics.Joints.b2LineJointDef = b2LineJointDef;
+
+ function b2MouseJoint() {
+ b2MouseJoint.b2MouseJoint.apply(this, arguments);
+ if (this.constructor === b2MouseJoint) this.b2MouseJoint.apply(this, arguments);
+ };
+ Box2D.Dynamics.Joints.b2MouseJoint = b2MouseJoint;
+
+ function b2MouseJointDef() {
+ b2MouseJointDef.b2MouseJointDef.apply(this, arguments);
+ if (this.constructor === b2MouseJointDef) this.b2MouseJointDef.apply(this, arguments);
+ };
+ Box2D.Dynamics.Joints.b2MouseJointDef = b2MouseJointDef;
+
+ function b2PrismaticJoint() {
+ b2PrismaticJoint.b2PrismaticJoint.apply(this, arguments);
+ if (this.constructor === b2PrismaticJoint) this.b2PrismaticJoint.apply(this, arguments);
+ };
+ Box2D.Dynamics.Joints.b2PrismaticJoint = b2PrismaticJoint;
+
+ function b2PrismaticJointDef() {
+ b2PrismaticJointDef.b2PrismaticJointDef.apply(this, arguments);
+ if (this.constructor === b2PrismaticJointDef) this.b2PrismaticJointDef.apply(this, arguments);
+ };
+ Box2D.Dynamics.Joints.b2PrismaticJointDef = b2PrismaticJointDef;
+
+ function b2PulleyJoint() {
+ b2PulleyJoint.b2PulleyJoint.apply(this, arguments);
+ if (this.constructor === b2PulleyJoint) this.b2PulleyJoint.apply(this, arguments);
+ };
+ Box2D.Dynamics.Joints.b2PulleyJoint = b2PulleyJoint;
+
+ function b2PulleyJointDef() {
+ b2PulleyJointDef.b2PulleyJointDef.apply(this, arguments);
+ if (this.constructor === b2PulleyJointDef) this.b2PulleyJointDef.apply(this, arguments);
+ };
+ Box2D.Dynamics.Joints.b2PulleyJointDef = b2PulleyJointDef;
+
+ function b2RevoluteJoint() {
+ b2RevoluteJoint.b2RevoluteJoint.apply(this, arguments);
+ if (this.constructor === b2RevoluteJoint) this.b2RevoluteJoint.apply(this, arguments);
+ };
+ Box2D.Dynamics.Joints.b2RevoluteJoint = b2RevoluteJoint;
+
+ function b2RevoluteJointDef() {
+ b2RevoluteJointDef.b2RevoluteJointDef.apply(this, arguments);
+ if (this.constructor === b2RevoluteJointDef) this.b2RevoluteJointDef.apply(this, arguments);
+ };
+ Box2D.Dynamics.Joints.b2RevoluteJointDef = b2RevoluteJointDef;
+
+ function b2WeldJoint() {
+ b2WeldJoint.b2WeldJoint.apply(this, arguments);
+ if (this.constructor === b2WeldJoint) this.b2WeldJoint.apply(this, arguments);
+ };
+ Box2D.Dynamics.Joints.b2WeldJoint = b2WeldJoint;
+
+ function b2WeldJointDef() {
+ b2WeldJointDef.b2WeldJointDef.apply(this, arguments);
+ if (this.constructor === b2WeldJointDef) this.b2WeldJointDef.apply(this, arguments);
+ };
+ Box2D.Dynamics.Joints.b2WeldJointDef = b2WeldJointDef;
+})(); //definitions
+Box2D.postDefs = [];
+(function () {
+ var b2CircleShape = Box2D.Collision.Shapes.b2CircleShape,
+ b2EdgeChainDef = Box2D.Collision.Shapes.b2EdgeChainDef,
+ b2EdgeShape = Box2D.Collision.Shapes.b2EdgeShape,
+ b2MassData = Box2D.Collision.Shapes.b2MassData,
+ b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape,
+ b2Shape = Box2D.Collision.Shapes.b2Shape,
+ b2Color = Box2D.Common.b2Color,
+ b2internal = Box2D.Common.b2internal,
+ b2Settings = Box2D.Common.b2Settings,
+ b2Mat22 = Box2D.Common.Math.b2Mat22,
+ b2Mat33 = Box2D.Common.Math.b2Mat33,
+ b2Math = Box2D.Common.Math.b2Math,
+ b2Sweep = Box2D.Common.Math.b2Sweep,
+ b2Transform = Box2D.Common.Math.b2Transform,
+ b2Vec2 = Box2D.Common.Math.b2Vec2,
+ b2Vec3 = Box2D.Common.Math.b2Vec3,
+ b2AABB = Box2D.Collision.b2AABB,
+ b2Bound = Box2D.Collision.b2Bound,
+ b2BoundValues = Box2D.Collision.b2BoundValues,
+ b2Collision = Box2D.Collision.b2Collision,
+ b2ContactID = Box2D.Collision.b2ContactID,
+ b2ContactPoint = Box2D.Collision.b2ContactPoint,
+ b2Distance = Box2D.Collision.b2Distance,
+ b2DistanceInput = Box2D.Collision.b2DistanceInput,
+ b2DistanceOutput = Box2D.Collision.b2DistanceOutput,
+ b2DistanceProxy = Box2D.Collision.b2DistanceProxy,
+ b2DynamicTree = Box2D.Collision.b2DynamicTree,
+ b2DynamicTreeBroadPhase = Box2D.Collision.b2DynamicTreeBroadPhase,
+ b2DynamicTreeNode = Box2D.Collision.b2DynamicTreeNode,
+ b2DynamicTreePair = Box2D.Collision.b2DynamicTreePair,
+ b2Manifold = Box2D.Collision.b2Manifold,
+ b2ManifoldPoint = Box2D.Collision.b2ManifoldPoint,
+ b2Point = Box2D.Collision.b2Point,
+ b2RayCastInput = Box2D.Collision.b2RayCastInput,
+ b2RayCastOutput = Box2D.Collision.b2RayCastOutput,
+ b2Segment = Box2D.Collision.b2Segment,
+ b2SeparationFunction = Box2D.Collision.b2SeparationFunction,
+ b2Simplex = Box2D.Collision.b2Simplex,
+ b2SimplexCache = Box2D.Collision.b2SimplexCache,
+ b2SimplexVertex = Box2D.Collision.b2SimplexVertex,
+ b2TimeOfImpact = Box2D.Collision.b2TimeOfImpact,
+ b2TOIInput = Box2D.Collision.b2TOIInput,
+ b2WorldManifold = Box2D.Collision.b2WorldManifold,
+ ClipVertex = Box2D.Collision.ClipVertex,
+ Features = Box2D.Collision.Features,
+ IBroadPhase = Box2D.Collision.IBroadPhase;
+
+ b2AABB.b2AABB = function () {
+ this.lowerBound = new b2Vec2();
+ this.upperBound = new b2Vec2();
+ };
+ b2AABB.prototype.IsValid = function () {
+ var dX = this.upperBound.x - this.lowerBound.x;
+ var dY = this.upperBound.y - this.lowerBound.y;
+ var valid = dX >= 0.0 && dY >= 0.0;
+ valid = valid && this.lowerBound.IsValid() && this.upperBound.IsValid();
+ return valid;
+ }
+ b2AABB.prototype.GetCenter = function () {
+ return new b2Vec2((this.lowerBound.x + this.upperBound.x) / 2, (this.lowerBound.y + this.upperBound.y) / 2);
+ }
+ b2AABB.prototype.GetExtents = function () {
+ return new b2Vec2((this.upperBound.x - this.lowerBound.x) / 2, (this.upperBound.y - this.lowerBound.y) / 2);
+ }
+ b2AABB.prototype.Contains = function (aabb) {
+ var result = true;
+ result = result && this.lowerBound.x <= aabb.lowerBound.x;
+ result = result && this.lowerBound.y <= aabb.lowerBound.y;
+ result = result && aabb.upperBound.x <= this.upperBound.x;
+ result = result && aabb.upperBound.y <= this.upperBound.y;
+ return result;
+ }
+ b2AABB.prototype.RayCast = function (output, input) {
+ var tmin = (-Number.MAX_VALUE);
+ var tmax = Number.MAX_VALUE;
+ var pX = input.p1.x;
+ var pY = input.p1.y;
+ var dX = input.p2.x - input.p1.x;
+ var dY = input.p2.y - input.p1.y;
+ var absDX = Math.abs(dX);
+ var absDY = Math.abs(dY);
+ var normal = output.normal;
+ var inv_d = 0;
+ var t1 = 0;
+ var t2 = 0;
+ var t3 = 0;
+ var s = 0; {
+ if (absDX < Number.MIN_VALUE) {
+ if (pX < this.lowerBound.x || this.upperBound.x < pX) return false;
+ }
+ else {
+ inv_d = 1.0 / dX;
+ t1 = (this.lowerBound.x - pX) * inv_d;
+ t2 = (this.upperBound.x - pX) * inv_d;
+ s = (-1.0);
+ if (t1 > t2) {
+ t3 = t1;
+ t1 = t2;
+ t2 = t3;
+ s = 1.0;
+ }
+ if (t1 > tmin) {
+ normal.x = s;
+ normal.y = 0;
+ tmin = t1;
+ }
+ tmax = Math.min(tmax, t2);
+ if (tmin > tmax) return false;
+ }
+ } {
+ if (absDY < Number.MIN_VALUE) {
+ if (pY < this.lowerBound.y || this.upperBound.y < pY) return false;
+ }
+ else {
+ inv_d = 1.0 / dY;
+ t1 = (this.lowerBound.y - pY) * inv_d;
+ t2 = (this.upperBound.y - pY) * inv_d;
+ s = (-1.0);
+ if (t1 > t2) {
+ t3 = t1;
+ t1 = t2;
+ t2 = t3;
+ s = 1.0;
+ }
+ if (t1 > tmin) {
+ normal.y = s;
+ normal.x = 0;
+ tmin = t1;
+ }
+ tmax = Math.min(tmax, t2);
+ if (tmin > tmax) return false;
+ }
+ }
+ output.fraction = tmin;
+ return true;
+ }
+ b2AABB.prototype.TestOverlap = function (other) {
+ var d1X = other.lowerBound.x - this.upperBound.x;
+ var d1Y = other.lowerBound.y - this.upperBound.y;
+ var d2X = this.lowerBound.x - other.upperBound.x;
+ var d2Y = this.lowerBound.y - other.upperBound.y;
+ if (d1X > 0.0 || d1Y > 0.0) return false;
+ if (d2X > 0.0 || d2Y > 0.0) return false;
+ return true;
+ }
+ b2AABB.Combine = function (aabb1, aabb2) {
+ var aabb = new b2AABB();
+ aabb.Combine(aabb1, aabb2);
+ return aabb;
+ }
+ b2AABB.prototype.Combine = function (aabb1, aabb2) {
+ this.lowerBound.x = Math.min(aabb1.lowerBound.x, aabb2.lowerBound.x);
+ this.lowerBound.y = Math.min(aabb1.lowerBound.y, aabb2.lowerBound.y);
+ this.upperBound.x = Math.max(aabb1.upperBound.x, aabb2.upperBound.x);
+ this.upperBound.y = Math.max(aabb1.upperBound.y, aabb2.upperBound.y);
+ }
+ b2Bound.b2Bound = function () {};
+ b2Bound.prototype.IsLower = function () {
+ return (this.value & 1) == 0;
+ }
+ b2Bound.prototype.IsUpper = function () {
+ return (this.value & 1) == 1;
+ }
+ b2Bound.prototype.Swap = function (b) {
+ var tempValue = this.value;
+ var tempProxy = this.proxy;
+ var tempStabbingCount = this.stabbingCount;
+ this.value = b.value;
+ this.proxy = b.proxy;
+ this.stabbingCount = b.stabbingCount;
+ b.value = tempValue;
+ b.proxy = tempProxy;
+ b.stabbingCount = tempStabbingCount;
+ }
+ b2BoundValues.b2BoundValues = function () {};
+ b2BoundValues.prototype.b2BoundValues = function () {
+ this.lowerValues = new Vector_a2j_Number();
+ this.lowerValues[0] = 0.0;
+ this.lowerValues[1] = 0.0;
+ this.upperValues = new Vector_a2j_Number();
+ this.upperValues[0] = 0.0;
+ this.upperValues[1] = 0.0;
+ }
+ b2Collision.b2Collision = function () {};
+ b2Collision.ClipSegmentToLine = function (vOut, vIn, normal, offset) {
+ if (offset === undefined) offset = 0;
+ var cv;
+ var numOut = 0;
+ cv = vIn[0];
+ var vIn0 = cv.v;
+ cv = vIn[1];
+ var vIn1 = cv.v;
+ var distance0 = normal.x * vIn0.x + normal.y * vIn0.y - offset;
+ var distance1 = normal.x * vIn1.x + normal.y * vIn1.y - offset;
+ if (distance0 <= 0.0) vOut[numOut++].Set(vIn[0]);
+ if (distance1 <= 0.0) vOut[numOut++].Set(vIn[1]);
+ if (distance0 * distance1 < 0.0) {
+ var interp = distance0 / (distance0 - distance1);
+ cv = vOut[numOut];
+ var tVec = cv.v;
+ tVec.x = vIn0.x + interp * (vIn1.x - vIn0.x);
+ tVec.y = vIn0.y + interp * (vIn1.y - vIn0.y);
+ cv = vOut[numOut];
+ var cv2;
+ if (distance0 > 0.0) {
+ cv2 = vIn[0];
+ cv.id = cv2.id;
+ }
+ else {
+ cv2 = vIn[1];
+ cv.id = cv2.id;
+ }++numOut;
+ }
+ return numOut;
+ }
+ b2Collision.EdgeSeparation = function (poly1, xf1, edge1, poly2, xf2) {
+ if (edge1 === undefined) edge1 = 0;
+ var count1 = parseInt(poly1.m_vertexCount);
+ var vertices1 = poly1.m_vertices;
+ var normals1 = poly1.m_normals;
+ var count2 = parseInt(poly2.m_vertexCount);
+ var vertices2 = poly2.m_vertices;
+ var tMat;
+ var tVec;
+ tMat = xf1.R;
+ tVec = normals1[edge1];
+ var normal1WorldX = (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ var normal1WorldY = (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ tMat = xf2.R;
+ var normal1X = (tMat.col1.x * normal1WorldX + tMat.col1.y * normal1WorldY);
+ var normal1Y = (tMat.col2.x * normal1WorldX + tMat.col2.y * normal1WorldY);
+ var index = 0;
+ var minDot = Number.MAX_VALUE;
+ for (var i = 0; i < count2; ++i) {
+ tVec = vertices2[i];
+ var dot = tVec.x * normal1X + tVec.y * normal1Y;
+ if (dot < minDot) {
+ minDot = dot;
+ index = i;
+ }
+ }
+ tVec = vertices1[edge1];
+ tMat = xf1.R;
+ var v1X = xf1.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ var v1Y = xf1.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ tVec = vertices2[index];
+ tMat = xf2.R;
+ var v2X = xf2.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ var v2Y = xf2.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ v2X -= v1X;
+ v2Y -= v1Y;
+ var separation = v2X * normal1WorldX + v2Y * normal1WorldY;
+ return separation;
+ }
+ b2Collision.FindMaxSeparation = function (edgeIndex, poly1, xf1, poly2, xf2) {
+ var count1 = parseInt(poly1.m_vertexCount);
+ var normals1 = poly1.m_normals;
+ var tVec;
+ var tMat;
+ tMat = xf2.R;
+ tVec = poly2.m_centroid;
+ var dX = xf2.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ var dY = xf2.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ tMat = xf1.R;
+ tVec = poly1.m_centroid;
+ dX -= xf1.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ dY -= xf1.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ var dLocal1X = (dX * xf1.R.col1.x + dY * xf1.R.col1.y);
+ var dLocal1Y = (dX * xf1.R.col2.x + dY * xf1.R.col2.y);
+ var edge = 0;
+ var maxDot = (-Number.MAX_VALUE);
+ for (var i = 0; i < count1; ++i) {
+ tVec = normals1[i];
+ var dot = (tVec.x * dLocal1X + tVec.y * dLocal1Y);
+ if (dot > maxDot) {
+ maxDot = dot;
+ edge = i;
+ }
+ }
+ var s = b2Collision.EdgeSeparation(poly1, xf1, edge, poly2, xf2);
+ var prevEdge = parseInt(edge - 1 >= 0 ? edge - 1 : count1 - 1);
+ var sPrev = b2Collision.EdgeSeparation(poly1, xf1, prevEdge, poly2, xf2);
+ var nextEdge = parseInt(edge + 1 < count1 ? edge + 1 : 0);
+ var sNext = b2Collision.EdgeSeparation(poly1, xf1, nextEdge, poly2, xf2);
+ var bestEdge = 0;
+ var bestSeparation = 0;
+ var increment = 0;
+ if (sPrev > s && sPrev > sNext) {
+ increment = (-1);
+ bestEdge = prevEdge;
+ bestSeparation = sPrev;
+ }
+ else if (sNext > s) {
+ increment = 1;
+ bestEdge = nextEdge;
+ bestSeparation = sNext;
+ }
+ else {
+ edgeIndex[0] = edge;
+ return s;
+ }
+ while (true) {
+ if (increment == (-1)) edge = bestEdge - 1 >= 0 ? bestEdge - 1 : count1 - 1;
+ else edge = bestEdge + 1 < count1 ? bestEdge + 1 : 0;s = b2Collision.EdgeSeparation(poly1, xf1, edge, poly2, xf2);
+ if (s > bestSeparation) {
+ bestEdge = edge;
+ bestSeparation = s;
+ }
+ else {
+ break;
+ }
+ }
+ edgeIndex[0] = bestEdge;
+ return bestSeparation;
+ }
+ b2Collision.FindIncidentEdge = function (c, poly1, xf1, edge1, poly2, xf2) {
+ if (edge1 === undefined) edge1 = 0;
+ var count1 = parseInt(poly1.m_vertexCount);
+ var normals1 = poly1.m_normals;
+ var count2 = parseInt(poly2.m_vertexCount);
+ var vertices2 = poly2.m_vertices;
+ var normals2 = poly2.m_normals;
+ var tMat;
+ var tVec;
+ tMat = xf1.R;
+ tVec = normals1[edge1];
+ var normal1X = (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ var normal1Y = (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ tMat = xf2.R;
+ var tX = (tMat.col1.x * normal1X + tMat.col1.y * normal1Y);
+ normal1Y = (tMat.col2.x * normal1X + tMat.col2.y * normal1Y);
+ normal1X = tX;
+ var index = 0;
+ var minDot = Number.MAX_VALUE;
+ for (var i = 0; i < count2; ++i) {
+ tVec = normals2[i];
+ var dot = (normal1X * tVec.x + normal1Y * tVec.y);
+ if (dot < minDot) {
+ minDot = dot;
+ index = i;
+ }
+ }
+ var tClip;
+ var i1 = parseInt(index);
+ var i2 = parseInt(i1 + 1 < count2 ? i1 + 1 : 0);
+ tClip = c[0];
+ tVec = vertices2[i1];
+ tMat = xf2.R;
+ tClip.v.x = xf2.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ tClip.v.y = xf2.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ tClip.id.features.referenceEdge = edge1;
+ tClip.id.features.incidentEdge = i1;
+ tClip.id.features.incidentVertex = 0;
+ tClip = c[1];
+ tVec = vertices2[i2];
+ tMat = xf2.R;
+ tClip.v.x = xf2.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ tClip.v.y = xf2.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ tClip.id.features.referenceEdge = edge1;
+ tClip.id.features.incidentEdge = i2;
+ tClip.id.features.incidentVertex = 1;
+ }
+ b2Collision.MakeClipPointVector = function () {
+ var r = new Vector(2);
+ r[0] = new ClipVertex();
+ r[1] = new ClipVertex();
+ return r;
+ }
+ b2Collision.CollidePolygons = function (manifold, polyA, xfA, polyB, xfB) {
+ var cv;
+ manifold.m_pointCount = 0;
+ var totalRadius = polyA.m_radius + polyB.m_radius;
+ var edgeA = 0;
+ b2Collision.s_edgeAO[0] = edgeA;
+ var separationA = b2Collision.FindMaxSeparation(b2Collision.s_edgeAO, polyA, xfA, polyB, xfB);
+ edgeA = b2Collision.s_edgeAO[0];
+ if (separationA > totalRadius) return;
+ var edgeB = 0;
+ b2Collision.s_edgeBO[0] = edgeB;
+ var separationB = b2Collision.FindMaxSeparation(b2Collision.s_edgeBO, polyB, xfB, polyA, xfA);
+ edgeB = b2Collision.s_edgeBO[0];
+ if (separationB > totalRadius) return;
+ var poly1;
+ var poly2;
+ var xf1;
+ var xf2;
+ var edge1 = 0;
+ var flip = 0;
+ var k_relativeTol = 0.98;
+ var k_absoluteTol = 0.001;
+ var tMat;
+ if (separationB > k_relativeTol * separationA + k_absoluteTol) {
+ poly1 = polyB;
+ poly2 = polyA;
+ xf1 = xfB;
+ xf2 = xfA;
+ edge1 = edgeB;
+ manifold.m_type = b2Manifold.e_faceB;
+ flip = 1;
+ }
+ else {
+ poly1 = polyA;
+ poly2 = polyB;
+ xf1 = xfA;
+ xf2 = xfB;
+ edge1 = edgeA;
+ manifold.m_type = b2Manifold.e_faceA;
+ flip = 0;
+ }
+ var incidentEdge = b2Collision.s_incidentEdge;
+ b2Collision.FindIncidentEdge(incidentEdge, poly1, xf1, edge1, poly2, xf2);
+ var count1 = parseInt(poly1.m_vertexCount);
+ var vertices1 = poly1.m_vertices;
+ var local_v11 = vertices1[edge1];
+ var local_v12;
+ if (edge1 + 1 < count1) {
+ local_v12 = vertices1[parseInt(edge1 + 1)];
+ }
+ else {
+ local_v12 = vertices1[0];
+ }
+ var localTangent = b2Collision.s_localTangent;
+ localTangent.Set(local_v12.x - local_v11.x, local_v12.y - local_v11.y);
+ localTangent.Normalize();
+ var localNormal = b2Collision.s_localNormal;
+ localNormal.x = localTangent.y;
+ localNormal.y = (-localTangent.x);
+ var planePoint = b2Collision.s_planePoint;
+ planePoint.Set(0.5 * (local_v11.x + local_v12.x), 0.5 * (local_v11.y + local_v12.y));
+ var tangent = b2Collision.s_tangent;
+ tMat = xf1.R;
+ tangent.x = (tMat.col1.x * localTangent.x + tMat.col2.x * localTangent.y);
+ tangent.y = (tMat.col1.y * localTangent.x + tMat.col2.y * localTangent.y);
+ var tangent2 = b2Collision.s_tangent2;
+ tangent2.x = (-tangent.x);
+ tangent2.y = (-tangent.y);
+ var normal = b2Collision.s_normal;
+ normal.x = tangent.y;
+ normal.y = (-tangent.x);
+ var v11 = b2Collision.s_v11;
+ var v12 = b2Collision.s_v12;
+ v11.x = xf1.position.x + (tMat.col1.x * local_v11.x + tMat.col2.x * local_v11.y);
+ v11.y = xf1.position.y + (tMat.col1.y * local_v11.x + tMat.col2.y * local_v11.y);
+ v12.x = xf1.position.x + (tMat.col1.x * local_v12.x + tMat.col2.x * local_v12.y);
+ v12.y = xf1.position.y + (tMat.col1.y * local_v12.x + tMat.col2.y * local_v12.y);
+ var frontOffset = normal.x * v11.x + normal.y * v11.y;
+ var sideOffset1 = (-tangent.x * v11.x) - tangent.y * v11.y + totalRadius;
+ var sideOffset2 = tangent.x * v12.x + tangent.y * v12.y + totalRadius;
+ var clipPoints1 = b2Collision.s_clipPoints1;
+ var clipPoints2 = b2Collision.s_clipPoints2;
+ var np = 0;
+ np = b2Collision.ClipSegmentToLine(clipPoints1, incidentEdge, tangent2, sideOffset1);
+ if (np < 2) return;
+ np = b2Collision.ClipSegmentToLine(clipPoints2, clipPoints1, tangent, sideOffset2);
+ if (np < 2) return;
+ manifold.m_localPlaneNormal.SetV(localNormal);
+ manifold.m_localPoint.SetV(planePoint);
+ var pointCount = 0;
+ for (var i = 0; i < b2Settings.b2_maxManifoldPoints; ++i) {
+ cv = clipPoints2[i];
+ var separation = normal.x * cv.v.x + normal.y * cv.v.y - frontOffset;
+ if (separation <= totalRadius) {
+ var cp = manifold.m_points[pointCount];
+ tMat = xf2.R;
+ var tX = cv.v.x - xf2.position.x;
+ var tY = cv.v.y - xf2.position.y;
+ cp.m_localPoint.x = (tX * tMat.col1.x + tY * tMat.col1.y);
+ cp.m_localPoint.y = (tX * tMat.col2.x + tY * tMat.col2.y);
+ cp.m_id.Set(cv.id);
+ cp.m_id.features.flip = flip;
+ ++pointCount;
+ }
+ }
+ manifold.m_pointCount = pointCount;
+ }
+ b2Collision.CollideCircles = function (manifold, circle1, xf1, circle2, xf2) {
+ manifold.m_pointCount = 0;
+ var tMat;
+ var tVec;
+ tMat = xf1.R;
+ tVec = circle1.m_p;
+ var p1X = xf1.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ var p1Y = xf1.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ tMat = xf2.R;
+ tVec = circle2.m_p;
+ var p2X = xf2.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ var p2Y = xf2.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ var dX = p2X - p1X;
+ var dY = p2Y - p1Y;
+ var distSqr = dX * dX + dY * dY;
+ var radius = circle1.m_radius + circle2.m_radius;
+ if (distSqr > radius * radius) {
+ return;
+ }
+ manifold.m_type = b2Manifold.e_circles;
+ manifold.m_localPoint.SetV(circle1.m_p);
+ manifold.m_localPlaneNormal.SetZero();
+ manifold.m_pointCount = 1;
+ manifold.m_points[0].m_localPoint.SetV(circle2.m_p);
+ manifold.m_points[0].m_id.key = 0;
+ }
+ b2Collision.CollidePolygonAndCircle = function (manifold, polygon, xf1, circle, xf2) {
+ manifold.m_pointCount = 0;
+ var tPoint;
+ var dX = 0;
+ var dY = 0;
+ var positionX = 0;
+ var positionY = 0;
+ var tVec;
+ var tMat;
+ tMat = xf2.R;
+ tVec = circle.m_p;
+ var cX = xf2.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ var cY = xf2.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ dX = cX - xf1.position.x;
+ dY = cY - xf1.position.y;
+ tMat = xf1.R;
+ var cLocalX = (dX * tMat.col1.x + dY * tMat.col1.y);
+ var cLocalY = (dX * tMat.col2.x + dY * tMat.col2.y);
+ var dist = 0;
+ var normalIndex = 0;
+ var separation = (-Number.MAX_VALUE);
+ var radius = polygon.m_radius + circle.m_radius;
+ var vertexCount = parseInt(polygon.m_vertexCount);
+ var vertices = polygon.m_vertices;
+ var normals = polygon.m_normals;
+ for (var i = 0; i < vertexCount; ++i) {
+ tVec = vertices[i];
+ dX = cLocalX - tVec.x;
+ dY = cLocalY - tVec.y;
+ tVec = normals[i];
+ var s = tVec.x * dX + tVec.y * dY;
+ if (s > radius) {
+ return;
+ }
+ if (s > separation) {
+ separation = s;
+ normalIndex = i;
+ }
+ }
+ var vertIndex1 = parseInt(normalIndex);
+ var vertIndex2 = parseInt(vertIndex1 + 1 < vertexCount ? vertIndex1 + 1 : 0);
+ var v1 = vertices[vertIndex1];
+ var v2 = vertices[vertIndex2];
+ if (separation < Number.MIN_VALUE) {
+ manifold.m_pointCount = 1;
+ manifold.m_type = b2Manifold.e_faceA;
+ manifold.m_localPlaneNormal.SetV(normals[normalIndex]);
+ manifold.m_localPoint.x = 0.5 * (v1.x + v2.x);
+ manifold.m_localPoint.y = 0.5 * (v1.y + v2.y);
+ manifold.m_points[0].m_localPoint.SetV(circle.m_p);
+ manifold.m_points[0].m_id.key = 0;
+ return;
+ }
+ var u1 = (cLocalX - v1.x) * (v2.x - v1.x) + (cLocalY - v1.y) * (v2.y - v1.y);
+ var u2 = (cLocalX - v2.x) * (v1.x - v2.x) + (cLocalY - v2.y) * (v1.y - v2.y);
+ if (u1 <= 0.0) {
+ if ((cLocalX - v1.x) * (cLocalX - v1.x) + (cLocalY - v1.y) * (cLocalY - v1.y) > radius * radius) return;
+ manifold.m_pointCount = 1;
+ manifold.m_type = b2Manifold.e_faceA;
+ manifold.m_localPlaneNormal.x = cLocalX - v1.x;
+ manifold.m_localPlaneNormal.y = cLocalY - v1.y;
+ manifold.m_localPlaneNormal.Normalize();
+ manifold.m_localPoint.SetV(v1);
+ manifold.m_points[0].m_localPoint.SetV(circle.m_p);
+ manifold.m_points[0].m_id.key = 0;
+ }
+ else if (u2 <= 0) {
+ if ((cLocalX - v2.x) * (cLocalX - v2.x) + (cLocalY - v2.y) * (cLocalY - v2.y) > radius * radius) return;
+ manifold.m_pointCount = 1;
+ manifold.m_type = b2Manifold.e_faceA;
+ manifold.m_localPlaneNormal.x = cLocalX - v2.x;
+ manifold.m_localPlaneNormal.y = cLocalY - v2.y;
+ manifold.m_localPlaneNormal.Normalize();
+ manifold.m_localPoint.SetV(v2);
+ manifold.m_points[0].m_localPoint.SetV(circle.m_p);
+ manifold.m_points[0].m_id.key = 0;
+ }
+ else {
+ var faceCenterX = 0.5 * (v1.x + v2.x);
+ var faceCenterY = 0.5 * (v1.y + v2.y);
+ separation = (cLocalX - faceCenterX) * normals[vertIndex1].x + (cLocalY - faceCenterY) * normals[vertIndex1].y;
+ if (separation > radius) return;
+ manifold.m_pointCount = 1;
+ manifold.m_type = b2Manifold.e_faceA;
+ manifold.m_localPlaneNormal.x = normals[vertIndex1].x;
+ manifold.m_localPlaneNormal.y = normals[vertIndex1].y;
+ manifold.m_localPlaneNormal.Normalize();
+ manifold.m_localPoint.Set(faceCenterX, faceCenterY);
+ manifold.m_points[0].m_localPoint.SetV(circle.m_p);
+ manifold.m_points[0].m_id.key = 0;
+ }
+ }
+ b2Collision.TestOverlap = function (a, b) {
+ var t1 = b.lowerBound;
+ var t2 = a.upperBound;
+ var d1X = t1.x - t2.x;
+ var d1Y = t1.y - t2.y;
+ t1 = a.lowerBound;
+ t2 = b.upperBound;
+ var d2X = t1.x - t2.x;
+ var d2Y = t1.y - t2.y;
+ if (d1X > 0.0 || d1Y > 0.0) return false;
+ if (d2X > 0.0 || d2Y > 0.0) return false;
+ return true;
+ }
+ Box2D.postDefs.push(function () {
+ Box2D.Collision.b2Collision.s_incidentEdge = b2Collision.MakeClipPointVector();
+ Box2D.Collision.b2Collision.s_clipPoints1 = b2Collision.MakeClipPointVector();
+ Box2D.Collision.b2Collision.s_clipPoints2 = b2Collision.MakeClipPointVector();
+ Box2D.Collision.b2Collision.s_edgeAO = new Vector_a2j_Number(1);
+ Box2D.Collision.b2Collision.s_edgeBO = new Vector_a2j_Number(1);
+ Box2D.Collision.b2Collision.s_localTangent = new b2Vec2();
+ Box2D.Collision.b2Collision.s_localNormal = new b2Vec2();
+ Box2D.Collision.b2Collision.s_planePoint = new b2Vec2();
+ Box2D.Collision.b2Collision.s_normal = new b2Vec2();
+ Box2D.Collision.b2Collision.s_tangent = new b2Vec2();
+ Box2D.Collision.b2Collision.s_tangent2 = new b2Vec2();
+ Box2D.Collision.b2Collision.s_v11 = new b2Vec2();
+ Box2D.Collision.b2Collision.s_v12 = new b2Vec2();
+ Box2D.Collision.b2Collision.b2CollidePolyTempVec = new b2Vec2();
+ Box2D.Collision.b2Collision.b2_nullFeature = 0x000000ff;
+ });
+ b2ContactID.b2ContactID = function () {
+ this.features = new Features();
+ };
+ b2ContactID.prototype.b2ContactID = function () {
+ this.features._m_id = this;
+ }
+ b2ContactID.prototype.Set = function (id) {
+ this.key = id._key;
+ }
+ b2ContactID.prototype.Copy = function () {
+ var id = new b2ContactID();
+ id.key = this.key;
+ return id;
+ }
+ Object.defineProperty(b2ContactID.prototype, 'key', {
+ enumerable: false,
+ configurable: true,
+ get: function () {
+ return this._key;
+ }
+ });
+ Object.defineProperty(b2ContactID.prototype, 'key', {
+ enumerable: false,
+ configurable: true,
+ set: function (value) {
+ if (value === undefined) value = 0;
+ this._key = value;
+ this.features._referenceEdge = this._key & 0x000000ff;
+ this.features._incidentEdge = ((this._key & 0x0000ff00) >> 8) & 0x000000ff;
+ this.features._incidentVertex = ((this._key & 0x00ff0000) >> 16) & 0x000000ff;
+ this.features._flip = ((this._key & 0xff000000) >> 24) & 0x000000ff;
+ }
+ });
+ b2ContactPoint.b2ContactPoint = function () {
+ this.position = new b2Vec2();
+ this.velocity = new b2Vec2();
+ this.normal = new b2Vec2();
+ this.id = new b2ContactID();
+ };
+ b2Distance.b2Distance = function () {};
+ b2Distance.Distance = function (output, cache, input) {
+ ++b2Distance.b2_gjkCalls;
+ var proxyA = input.proxyA;
+ var proxyB = input.proxyB;
+ var transformA = input.transformA;
+ var transformB = input.transformB;
+ var simplex = b2Distance.s_simplex;
+ simplex.ReadCache(cache, proxyA, transformA, proxyB, transformB);
+ var vertices = simplex.m_vertices;
+ var k_maxIters = 20;
+ var saveA = b2Distance.s_saveA;
+ var saveB = b2Distance.s_saveB;
+ var saveCount = 0;
+ var closestPoint = simplex.GetClosestPoint();
+ var distanceSqr1 = closestPoint.LengthSquared();
+ var distanceSqr2 = distanceSqr1;
+ var i = 0;
+ var p;
+ var iter = 0;
+ while (iter < k_maxIters) {
+ saveCount = simplex.m_count;
+ for (i = 0;
+ i < saveCount; i++) {
+ saveA[i] = vertices[i].indexA;
+ saveB[i] = vertices[i].indexB;
+ }
+ switch (simplex.m_count) {
+ case 1:
+ break;
+ case 2:
+ simplex.Solve2();
+ break;
+ case 3:
+ simplex.Solve3();
+ break;
+ default:
+ b2Settings.b2Assert(false);
+ }
+ if (simplex.m_count == 3) {
+ break;
+ }
+ p = simplex.GetClosestPoint();
+ distanceSqr2 = p.LengthSquared();
+ if (distanceSqr2 > distanceSqr1) {}
+ distanceSqr1 = distanceSqr2;
+ var d = simplex.GetSearchDirection();
+ if (d.LengthSquared() < Number.MIN_VALUE * Number.MIN_VALUE) {
+ break;
+ }
+ var vertex = vertices[simplex.m_count];
+ vertex.indexA = proxyA.GetSupport(b2Math.MulTMV(transformA.R, d.GetNegative()));
+ vertex.wA = b2Math.MulX(transformA, proxyA.GetVertex(vertex.indexA));
+ vertex.indexB = proxyB.GetSupport(b2Math.MulTMV(transformB.R, d));
+ vertex.wB = b2Math.MulX(transformB, proxyB.GetVertex(vertex.indexB));
+ vertex.w = b2Math.SubtractVV(vertex.wB, vertex.wA);
+ ++iter;
+ ++b2Distance.b2_gjkIters;
+ var duplicate = false;
+ for (i = 0;
+ i < saveCount; i++) {
+ if (vertex.indexA == saveA[i] && vertex.indexB == saveB[i]) {
+ duplicate = true;
+ break;
+ }
+ }
+ if (duplicate) {
+ break;
+ }++simplex.m_count;
+ }
+ b2Distance.b2_gjkMaxIters = b2Math.Max(b2Distance.b2_gjkMaxIters, iter);
+ simplex.GetWitnessPoints(output.pointA, output.pointB);
+ output.distance = b2Math.SubtractVV(output.pointA, output.pointB).Length();
+ output.iterations = iter;
+ simplex.WriteCache(cache);
+ if (input.useRadii) {
+ var rA = proxyA.m_radius;
+ var rB = proxyB.m_radius;
+ if (output.distance > rA + rB && output.distance > Number.MIN_VALUE) {
+ output.distance -= rA + rB;
+ var normal = b2Math.SubtractVV(output.pointB, output.pointA);
+ normal.Normalize();
+ output.pointA.x += rA * normal.x;
+ output.pointA.y += rA * normal.y;
+ output.pointB.x -= rB * normal.x;
+ output.pointB.y -= rB * normal.y;
+ }
+ else {
+ p = new b2Vec2();
+ p.x = .5 * (output.pointA.x + output.pointB.x);
+ p.y = .5 * (output.pointA.y + output.pointB.y);
+ output.pointA.x = output.pointB.x = p.x;
+ output.pointA.y = output.pointB.y = p.y;
+ output.distance = 0.0;
+ }
+ }
+ }
+ Box2D.postDefs.push(function () {
+ Box2D.Collision.b2Distance.s_simplex = new b2Simplex();
+ Box2D.Collision.b2Distance.s_saveA = new Vector_a2j_Number(3);
+ Box2D.Collision.b2Distance.s_saveB = new Vector_a2j_Number(3);
+ });
+ b2DistanceInput.b2DistanceInput = function () {};
+ b2DistanceOutput.b2DistanceOutput = function () {
+ this.pointA = new b2Vec2();
+ this.pointB = new b2Vec2();
+ };
+ b2DistanceProxy.b2DistanceProxy = function () {};
+ b2DistanceProxy.prototype.Set = function (shape) {
+ switch (shape.GetType()) {
+ case b2Shape.e_circleShape:
+ {
+ var circle = (shape instanceof b2CircleShape ? shape : null);
+ this.m_vertices = new Vector(1, true);
+ this.m_vertices[0] = circle.m_p;
+ this.m_count = 1;
+ this.m_radius = circle.m_radius;
+ }
+ break;
+ case b2Shape.e_polygonShape:
+ {
+ var polygon = (shape instanceof b2PolygonShape ? shape : null);
+ this.m_vertices = polygon.m_vertices;
+ this.m_count = polygon.m_vertexCount;
+ this.m_radius = polygon.m_radius;
+ }
+ break;
+ default:
+ b2Settings.b2Assert(false);
+ }
+ }
+ b2DistanceProxy.prototype.GetSupport = function (d) {
+ var bestIndex = 0;
+ var bestValue = this.m_vertices[0].x * d.x + this.m_vertices[0].y * d.y;
+ for (var i = 1; i < this.m_count; ++i) {
+ var value = this.m_vertices[i].x * d.x + this.m_vertices[i].y * d.y;
+ if (value > bestValue) {
+ bestIndex = i;
+ bestValue = value;
+ }
+ }
+ return bestIndex;
+ }
+ b2DistanceProxy.prototype.GetSupportVertex = function (d) {
+ var bestIndex = 0;
+ var bestValue = this.m_vertices[0].x * d.x + this.m_vertices[0].y * d.y;
+ for (var i = 1; i < this.m_count; ++i) {
+ var value = this.m_vertices[i].x * d.x + this.m_vertices[i].y * d.y;
+ if (value > bestValue) {
+ bestIndex = i;
+ bestValue = value;
+ }
+ }
+ return this.m_vertices[bestIndex];
+ }
+ b2DistanceProxy.prototype.GetVertexCount = function () {
+ return this.m_count;
+ }
+ b2DistanceProxy.prototype.GetVertex = function (index) {
+ if (index === undefined) index = 0;
+ b2Settings.b2Assert(0 <= index && index < this.m_count);
+ return this.m_vertices[index];
+ }
+ b2DynamicTree.b2DynamicTree = function () {};
+ b2DynamicTree.prototype.b2DynamicTree = function () {
+ this.m_root = null;
+ this.m_freeList = null;
+ this.m_path = 0;
+ this.m_insertionCount = 0;
+ }
+ b2DynamicTree.prototype.CreateProxy = function (aabb, userData) {
+ var node = this.AllocateNode();
+ var extendX = b2Settings.b2_aabbExtension;
+ var extendY = b2Settings.b2_aabbExtension;
+ node.aabb.lowerBound.x = aabb.lowerBound.x - extendX;
+ node.aabb.lowerBound.y = aabb.lowerBound.y - extendY;
+ node.aabb.upperBound.x = aabb.upperBound.x + extendX;
+ node.aabb.upperBound.y = aabb.upperBound.y + extendY;
+ node.userData = userData;
+ this.InsertLeaf(node);
+ return node;
+ }
+ b2DynamicTree.prototype.DestroyProxy = function (proxy) {
+ this.RemoveLeaf(proxy);
+ this.FreeNode(proxy);
+ }
+ b2DynamicTree.prototype.MoveProxy = function (proxy, aabb, displacement) {
+ b2Settings.b2Assert(proxy.IsLeaf());
+ if (proxy.aabb.Contains(aabb)) {
+ return false;
+ }
+ this.RemoveLeaf(proxy);
+ var extendX = b2Settings.b2_aabbExtension + b2Settings.b2_aabbMultiplier * (displacement.x > 0 ? displacement.x : (-displacement.x));
+ var extendY = b2Settings.b2_aabbExtension + b2Settings.b2_aabbMultiplier * (displacement.y > 0 ? displacement.y : (-displacement.y));
+ proxy.aabb.lowerBound.x = aabb.lowerBound.x - extendX;
+ proxy.aabb.lowerBound.y = aabb.lowerBound.y - extendY;
+ proxy.aabb.upperBound.x = aabb.upperBound.x + extendX;
+ proxy.aabb.upperBound.y = aabb.upperBound.y + extendY;
+ this.InsertLeaf(proxy);
+ return true;
+ }
+ b2DynamicTree.prototype.Rebalance = function (iterations) {
+ if (iterations === undefined) iterations = 0;
+ if (this.m_root == null) return;
+ for (var i = 0; i < iterations; i++) {
+ var node = this.m_root;
+ var bit = 0;
+ while (node.IsLeaf() == false) {
+ node = (this.m_path >> bit) & 1 ? node.child2 : node.child1;
+ bit = (bit + 1) & 31;
+ }++this.m_path;
+ this.RemoveLeaf(node);
+ this.InsertLeaf(node);
+ }
+ }
+ b2DynamicTree.prototype.GetFatAABB = function (proxy) {
+ return proxy.aabb;
+ }
+ b2DynamicTree.prototype.GetUserData = function (proxy) {
+ return proxy.userData;
+ }
+ b2DynamicTree.prototype.Query = function (callback, aabb) {
+ if (this.m_root == null) return;
+ var stack = new Vector();
+ var count = 0;
+ stack[count++] = this.m_root;
+ while (count > 0) {
+ var node = stack[--count];
+ if (node.aabb.TestOverlap(aabb)) {
+ if (node.IsLeaf()) {
+ var proceed = callback(node);
+ if (!proceed) return;
+ }
+ else {
+ stack[count++] = node.child1;
+ stack[count++] = node.child2;
+ }
+ }
+ }
+ }
+ b2DynamicTree.prototype.RayCast = function (callback, input) {
+ if (this.m_root == null) return;
+ var p1 = input.p1;
+ var p2 = input.p2;
+ var r = b2Math.SubtractVV(p1, p2);
+ r.Normalize();
+ var v = b2Math.CrossFV(1.0, r);
+ var abs_v = b2Math.AbsV(v);
+ var maxFraction = input.maxFraction;
+ var segmentAABB = new b2AABB();
+ var tX = 0;
+ var tY = 0; {
+ tX = p1.x + maxFraction * (p2.x - p1.x);
+ tY = p1.y + maxFraction * (p2.y - p1.y);
+ segmentAABB.lowerBound.x = Math.min(p1.x, tX);
+ segmentAABB.lowerBound.y = Math.min(p1.y, tY);
+ segmentAABB.upperBound.x = Math.max(p1.x, tX);
+ segmentAABB.upperBound.y = Math.max(p1.y, tY);
+ }
+ var stack = new Vector();
+ var count = 0;
+ stack[count++] = this.m_root;
+ while (count > 0) {
+ var node = stack[--count];
+ if (node.aabb.TestOverlap(segmentAABB) == false) {
+ continue;
+ }
+ var c = node.aabb.GetCenter();
+ var h = node.aabb.GetExtents();
+ var separation = Math.abs(v.x * (p1.x - c.x) + v.y * (p1.y - c.y)) - abs_v.x * h.x - abs_v.y * h.y;
+ if (separation > 0.0) continue;
+ if (node.IsLeaf()) {
+ var subInput = new b2RayCastInput();
+ subInput.p1 = input.p1;
+ subInput.p2 = input.p2;
+ subInput.maxFraction = input.maxFraction;
+ maxFraction = callback(subInput, node);
+ if (maxFraction == 0.0) return;
+ if (maxFraction > 0.0) {
+ tX = p1.x + maxFraction * (p2.x - p1.x);
+ tY = p1.y + maxFraction * (p2.y - p1.y);
+ segmentAABB.lowerBound.x = Math.min(p1.x, tX);
+ segmentAABB.lowerBound.y = Math.min(p1.y, tY);
+ segmentAABB.upperBound.x = Math.max(p1.x, tX);
+ segmentAABB.upperBound.y = Math.max(p1.y, tY);
+ }
+ }
+ else {
+ stack[count++] = node.child1;
+ stack[count++] = node.child2;
+ }
+ }
+ }
+ b2DynamicTree.prototype.AllocateNode = function () {
+ if (this.m_freeList) {
+ var node = this.m_freeList;
+ this.m_freeList = node.parent;
+ node.parent = null;
+ node.child1 = null;
+ node.child2 = null;
+ return node;
+ }
+ return new b2DynamicTreeNode();
+ }
+ b2DynamicTree.prototype.FreeNode = function (node) {
+ node.parent = this.m_freeList;
+ this.m_freeList = node;
+ }
+ b2DynamicTree.prototype.InsertLeaf = function (leaf) {
+ ++this.m_insertionCount;
+ if (this.m_root == null) {
+ this.m_root = leaf;
+ this.m_root.parent = null;
+ return;
+ }
+ var center = leaf.aabb.GetCenter();
+ var sibling = this.m_root;
+ if (sibling.IsLeaf() == false) {
+ do {
+ var child1 = sibling.child1;
+ var child2 = sibling.child2;
+ var norm1 = Math.abs((child1.aabb.lowerBound.x + child1.aabb.upperBound.x) / 2 - center.x) + Math.abs((child1.aabb.lowerBound.y + child1.aabb.upperBound.y) / 2 - center.y);
+ var norm2 = Math.abs((child2.aabb.lowerBound.x + child2.aabb.upperBound.x) / 2 - center.x) + Math.abs((child2.aabb.lowerBound.y + child2.aabb.upperBound.y) / 2 - center.y);
+ if (norm1 < norm2) {
+ sibling = child1;
+ }
+ else {
+ sibling = child2;
+ }
+ }
+ while (sibling.IsLeaf() == false)
+ }
+ var node1 = sibling.parent;
+ var node2 = this.AllocateNode();
+ node2.parent = node1;
+ node2.userData = null;
+ node2.aabb.Combine(leaf.aabb, sibling.aabb);
+ if (node1) {
+ if (sibling.parent.child1 == sibling) {
+ node1.child1 = node2;
+ }
+ else {
+ node1.child2 = node2;
+ }
+ node2.child1 = sibling;
+ node2.child2 = leaf;
+ sibling.parent = node2;
+ leaf.parent = node2;
+ do {
+ if (node1.aabb.Contains(node2.aabb)) break;
+ node1.aabb.Combine(node1.child1.aabb, node1.child2.aabb);
+ node2 = node1;
+ node1 = node1.parent;
+ }
+ while (node1)
+ }
+ else {
+ node2.child1 = sibling;
+ node2.child2 = leaf;
+ sibling.parent = node2;
+ leaf.parent = node2;
+ this.m_root = node2;
+ }
+ }
+ b2DynamicTree.prototype.RemoveLeaf = function (leaf) {
+ if (leaf == this.m_root) {
+ this.m_root = null;
+ return;
+ }
+ var node2 = leaf.parent;
+ var node1 = node2.parent;
+ var sibling;
+ if (node2.child1 == leaf) {
+ sibling = node2.child2;
+ }
+ else {
+ sibling = node2.child1;
+ }
+ if (node1) {
+ if (node1.child1 == node2) {
+ node1.child1 = sibling;
+ }
+ else {
+ node1.child2 = sibling;
+ }
+ sibling.parent = node1;
+ this.FreeNode(node2);
+ while (node1) {
+ var oldAABB = node1.aabb;
+ node1.aabb = b2AABB.Combine(node1.child1.aabb, node1.child2.aabb);
+ if (oldAABB.Contains(node1.aabb)) break;
+ node1 = node1.parent;
+ }
+ }
+ else {
+ this.m_root = sibling;
+ sibling.parent = null;
+ this.FreeNode(node2);
+ }
+ }
+ b2DynamicTreeBroadPhase.b2DynamicTreeBroadPhase = function () {
+ this.m_tree = new b2DynamicTree();
+ this.m_moveBuffer = new Vector();
+ this.m_pairBuffer = new Vector();
+ this.m_pairCount = 0;
+ };
+ b2DynamicTreeBroadPhase.prototype.CreateProxy = function (aabb, userData) {
+ var proxy = this.m_tree.CreateProxy(aabb, userData);
+ ++this.m_proxyCount;
+ this.BufferMove(proxy);
+ return proxy;
+ }
+ b2DynamicTreeBroadPhase.prototype.DestroyProxy = function (proxy) {
+ this.UnBufferMove(proxy);
+ --this.m_proxyCount;
+ this.m_tree.DestroyProxy(proxy);
+ }
+ b2DynamicTreeBroadPhase.prototype.MoveProxy = function (proxy, aabb, displacement) {
+ var buffer = this.m_tree.MoveProxy(proxy, aabb, displacement);
+ if (buffer) {
+ this.BufferMove(proxy);
+ }
+ }
+ b2DynamicTreeBroadPhase.prototype.TestOverlap = function (proxyA, proxyB) {
+ var aabbA = this.m_tree.GetFatAABB(proxyA);
+ var aabbB = this.m_tree.GetFatAABB(proxyB);
+ return aabbA.TestOverlap(aabbB);
+ }
+ b2DynamicTreeBroadPhase.prototype.GetUserData = function (proxy) {
+ return this.m_tree.GetUserData(proxy);
+ }
+ b2DynamicTreeBroadPhase.prototype.GetFatAABB = function (proxy) {
+ return this.m_tree.GetFatAABB(proxy);
+ }
+ b2DynamicTreeBroadPhase.prototype.GetProxyCount = function () {
+ return this.m_proxyCount;
+ }
+ b2DynamicTreeBroadPhase.prototype.UpdatePairs = function (callback) {
+ var __this = this;
+ __this.m_pairCount = 0;
+ var i = 0,
+ queryProxy;
+ for (i = 0;
+ i < __this.m_moveBuffer.length; ++i) {
+ queryProxy = __this.m_moveBuffer[i];
+
+ function QueryCallback(proxy) {
+ if (proxy == queryProxy) return true;
+ if (__this.m_pairCount == __this.m_pairBuffer.length) {
+ __this.m_pairBuffer[__this.m_pairCount] = new b2DynamicTreePair();
+ }
+ var pair = __this.m_pairBuffer[__this.m_pairCount];
+ pair.proxyA = proxy < queryProxy ? proxy : queryProxy;
+ pair.proxyB = proxy >= queryProxy ? proxy : queryProxy;++__this.m_pairCount;
+ return true;
+ };
+ var fatAABB = __this.m_tree.GetFatAABB(queryProxy);
+ __this.m_tree.Query(QueryCallback, fatAABB);
+ }
+ __this.m_moveBuffer.length = 0;
+ for (var i = 0; i < __this.m_pairCount;) {
+ var primaryPair = __this.m_pairBuffer[i];
+ var userDataA = __this.m_tree.GetUserData(primaryPair.proxyA);
+ var userDataB = __this.m_tree.GetUserData(primaryPair.proxyB);
+ callback(userDataA, userDataB);
+ ++i;
+ while (i < __this.m_pairCount) {
+ var pair = __this.m_pairBuffer[i];
+ if (pair.proxyA != primaryPair.proxyA || pair.proxyB != primaryPair.proxyB) {
+ break;
+ }++i;
+ }
+ }
+ }
+ b2DynamicTreeBroadPhase.prototype.Query = function (callback, aabb) {
+ this.m_tree.Query(callback, aabb);
+ }
+ b2DynamicTreeBroadPhase.prototype.RayCast = function (callback, input) {
+ this.m_tree.RayCast(callback, input);
+ }
+ b2DynamicTreeBroadPhase.prototype.Validate = function () {}
+ b2DynamicTreeBroadPhase.prototype.Rebalance = function (iterations) {
+ if (iterations === undefined) iterations = 0;
+ this.m_tree.Rebalance(iterations);
+ }
+ b2DynamicTreeBroadPhase.prototype.BufferMove = function (proxy) {
+ this.m_moveBuffer[this.m_moveBuffer.length] = proxy;
+ }
+ b2DynamicTreeBroadPhase.prototype.UnBufferMove = function (proxy) {
+ var i = parseInt(this.m_moveBuffer.indexOf(proxy));
+ this.m_moveBuffer.splice(i, 1);
+ }
+ b2DynamicTreeBroadPhase.prototype.ComparePairs = function (pair1, pair2) {
+ return 0;
+ }
+ b2DynamicTreeBroadPhase.__implements = {};
+ b2DynamicTreeBroadPhase.__implements[IBroadPhase] = true;
+ b2DynamicTreeNode.b2DynamicTreeNode = function () {
+ this.aabb = new b2AABB();
+ };
+ b2DynamicTreeNode.prototype.IsLeaf = function () {
+ return this.child1 == null;
+ }
+ b2DynamicTreePair.b2DynamicTreePair = function () {};
+ b2Manifold.b2Manifold = function () {
+ this.m_pointCount = 0;
+ };
+ b2Manifold.prototype.b2Manifold = function () {
+ this.m_points = new Vector(b2Settings.b2_maxManifoldPoints);
+ for (var i = 0; i < b2Settings.b2_maxManifoldPoints; i++) {
+ this.m_points[i] = new b2ManifoldPoint();
+ }
+ this.m_localPlaneNormal = new b2Vec2();
+ this.m_localPoint = new b2Vec2();
+ }
+ b2Manifold.prototype.Reset = function () {
+ for (var i = 0; i < b2Settings.b2_maxManifoldPoints; i++) {
+ ((this.m_points[i] instanceof b2ManifoldPoint ? this.m_points[i] : null)).Reset();
+ }
+ this.m_localPlaneNormal.SetZero();
+ this.m_localPoint.SetZero();
+ this.m_type = 0;
+ this.m_pointCount = 0;
+ }
+ b2Manifold.prototype.Set = function (m) {
+ this.m_pointCount = m.m_pointCount;
+ for (var i = 0; i < b2Settings.b2_maxManifoldPoints; i++) {
+ ((this.m_points[i] instanceof b2ManifoldPoint ? this.m_points[i] : null)).Set(m.m_points[i]);
+ }
+ this.m_localPlaneNormal.SetV(m.m_localPlaneNormal);
+ this.m_localPoint.SetV(m.m_localPoint);
+ this.m_type = m.m_type;
+ }
+ b2Manifold.prototype.Copy = function () {
+ var copy = new b2Manifold();
+ copy.Set(this);
+ return copy;
+ }
+ Box2D.postDefs.push(function () {
+ Box2D.Collision.b2Manifold.e_circles = 0x0001;
+ Box2D.Collision.b2Manifold.e_faceA = 0x0002;
+ Box2D.Collision.b2Manifold.e_faceB = 0x0004;
+ });
+ b2ManifoldPoint.b2ManifoldPoint = function () {
+ this.m_localPoint = new b2Vec2();
+ this.m_id = new b2ContactID();
+ };
+ b2ManifoldPoint.prototype.b2ManifoldPoint = function () {
+ this.Reset();
+ }
+ b2ManifoldPoint.prototype.Reset = function () {
+ this.m_localPoint.SetZero();
+ this.m_normalImpulse = 0.0;
+ this.m_tangentImpulse = 0.0;
+ this.m_id.key = 0;
+ }
+ b2ManifoldPoint.prototype.Set = function (m) {
+ this.m_localPoint.SetV(m.m_localPoint);
+ this.m_normalImpulse = m.m_normalImpulse;
+ this.m_tangentImpulse = m.m_tangentImpulse;
+ this.m_id.Set(m.m_id);
+ }
+ b2Point.b2Point = function () {
+ this.p = new b2Vec2();
+ };
+ b2Point.prototype.Support = function (xf, vX, vY) {
+ if (vX === undefined) vX = 0;
+ if (vY === undefined) vY = 0;
+ return this.p;
+ }
+ b2Point.prototype.GetFirstVertex = function (xf) {
+ return this.p;
+ }
+ b2RayCastInput.b2RayCastInput = function () {
+ this.p1 = new b2Vec2();
+ this.p2 = new b2Vec2();
+ };
+ b2RayCastInput.prototype.b2RayCastInput = function (p1, p2, maxFraction) {
+ if (p1 === undefined) p1 = null;
+ if (p2 === undefined) p2 = null;
+ if (maxFraction === undefined) maxFraction = 1;
+ if (p1) this.p1.SetV(p1);
+ if (p2) this.p2.SetV(p2);
+ this.maxFraction = maxFraction;
+ }
+ b2RayCastOutput.b2RayCastOutput = function () {
+ this.normal = new b2Vec2();
+ };
+ b2Segment.b2Segment = function () {
+ this.p1 = new b2Vec2();
+ this.p2 = new b2Vec2();
+ };
+ b2Segment.prototype.TestSegment = function (lambda, normal, segment, maxLambda) {
+ if (maxLambda === undefined) maxLambda = 0;
+ var s = segment.p1;
+ var rX = segment.p2.x - s.x;
+ var rY = segment.p2.y - s.y;
+ var dX = this.p2.x - this.p1.x;
+ var dY = this.p2.y - this.p1.y;
+ var nX = dY;
+ var nY = (-dX);
+ var k_slop = 100.0 * Number.MIN_VALUE;
+ var denom = (-(rX * nX + rY * nY));
+ if (denom > k_slop) {
+ var bX = s.x - this.p1.x;
+ var bY = s.y - this.p1.y;
+ var a = (bX * nX + bY * nY);
+ if (0.0 <= a && a <= maxLambda * denom) {
+ var mu2 = (-rX * bY) + rY * bX;
+ if ((-k_slop * denom) <= mu2 && mu2 <= denom * (1.0 + k_slop)) {
+ a /= denom;
+ var nLen = Math.sqrt(nX * nX + nY * nY);
+ nX /= nLen;
+ nY /= nLen;
+ lambda[0] = a;
+ normal.Set(nX, nY);
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+ b2Segment.prototype.Extend = function (aabb) {
+ this.ExtendForward(aabb);
+ this.ExtendBackward(aabb);
+ }
+ b2Segment.prototype.ExtendForward = function (aabb) {
+ var dX = this.p2.x - this.p1.x;
+ var dY = this.p2.y - this.p1.y;
+ var lambda = Math.min(dX > 0 ? (aabb.upperBound.x - this.p1.x) / dX : dX < 0 ? (aabb.lowerBound.x - this.p1.x) / dX : Number.POSITIVE_INFINITY,
+ dY > 0 ? (aabb.upperBound.y - this.p1.y) / dY : dY < 0 ? (aabb.lowerBound.y - this.p1.y) / dY : Number.POSITIVE_INFINITY);
+ this.p2.x = this.p1.x + dX * lambda;
+ this.p2.y = this.p1.y + dY * lambda;
+ }
+ b2Segment.prototype.ExtendBackward = function (aabb) {
+ var dX = (-this.p2.x) + this.p1.x;
+ var dY = (-this.p2.y) + this.p1.y;
+ var lambda = Math.min(dX > 0 ? (aabb.upperBound.x - this.p2.x) / dX : dX < 0 ? (aabb.lowerBound.x - this.p2.x) / dX : Number.POSITIVE_INFINITY,
+ dY > 0 ? (aabb.upperBound.y - this.p2.y) / dY : dY < 0 ? (aabb.lowerBound.y - this.p2.y) / dY : Number.POSITIVE_INFINITY);
+ this.p1.x = this.p2.x + dX * lambda;
+ this.p1.y = this.p2.y + dY * lambda;
+ }
+ b2SeparationFunction.b2SeparationFunction = function () {
+ this.m_localPoint = new b2Vec2();
+ this.m_axis = new b2Vec2();
+ };
+ b2SeparationFunction.prototype.Initialize = function (cache, proxyA, transformA, proxyB, transformB) {
+ this.m_proxyA = proxyA;
+ this.m_proxyB = proxyB;
+ var count = parseInt(cache.count);
+ b2Settings.b2Assert(0 < count && count < 3);
+ var localPointA;
+ var localPointA1;
+ var localPointA2;
+ var localPointB;
+ var localPointB1;
+ var localPointB2;
+ var pointAX = 0;
+ var pointAY = 0;
+ var pointBX = 0;
+ var pointBY = 0;
+ var normalX = 0;
+ var normalY = 0;
+ var tMat;
+ var tVec;
+ var s = 0;
+ var sgn = 0;
+ if (count == 1) {
+ this.m_type = b2SeparationFunction.e_points;
+ localPointA = this.m_proxyA.GetVertex(cache.indexA[0]);
+ localPointB = this.m_proxyB.GetVertex(cache.indexB[0]);
+ tVec = localPointA;
+ tMat = transformA.R;
+ pointAX = transformA.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ pointAY = transformA.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ tVec = localPointB;
+ tMat = transformB.R;
+ pointBX = transformB.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ pointBY = transformB.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ this.m_axis.x = pointBX - pointAX;
+ this.m_axis.y = pointBY - pointAY;
+ this.m_axis.Normalize();
+ }
+ else if (cache.indexB[0] == cache.indexB[1]) {
+ this.m_type = b2SeparationFunction.e_faceA;
+ localPointA1 = this.m_proxyA.GetVertex(cache.indexA[0]);
+ localPointA2 = this.m_proxyA.GetVertex(cache.indexA[1]);
+ localPointB = this.m_proxyB.GetVertex(cache.indexB[0]);
+ this.m_localPoint.x = 0.5 * (localPointA1.x + localPointA2.x);
+ this.m_localPoint.y = 0.5 * (localPointA1.y + localPointA2.y);
+ this.m_axis = b2Math.CrossVF(b2Math.SubtractVV(localPointA2, localPointA1), 1.0);
+ this.m_axis.Normalize();
+ tVec = this.m_axis;
+ tMat = transformA.R;
+ normalX = tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
+ normalY = tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
+ tVec = this.m_localPoint;
+ tMat = transformA.R;
+ pointAX = transformA.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ pointAY = transformA.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ tVec = localPointB;
+ tMat = transformB.R;
+ pointBX = transformB.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ pointBY = transformB.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ s = (pointBX - pointAX) * normalX + (pointBY - pointAY) * normalY;
+ if (s < 0.0) {
+ this.m_axis.NegativeSelf();
+ }
+ }
+ else if (cache.indexA[0] == cache.indexA[0]) {
+ this.m_type = b2SeparationFunction.e_faceB;
+ localPointB1 = this.m_proxyB.GetVertex(cache.indexB[0]);
+ localPointB2 = this.m_proxyB.GetVertex(cache.indexB[1]);
+ localPointA = this.m_proxyA.GetVertex(cache.indexA[0]);
+ this.m_localPoint.x = 0.5 * (localPointB1.x + localPointB2.x);
+ this.m_localPoint.y = 0.5 * (localPointB1.y + localPointB2.y);
+ this.m_axis = b2Math.CrossVF(b2Math.SubtractVV(localPointB2, localPointB1), 1.0);
+ this.m_axis.Normalize();
+ tVec = this.m_axis;
+ tMat = transformB.R;
+ normalX = tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
+ normalY = tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
+ tVec = this.m_localPoint;
+ tMat = transformB.R;
+ pointBX = transformB.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ pointBY = transformB.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ tVec = localPointA;
+ tMat = transformA.R;
+ pointAX = transformA.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ pointAY = transformA.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ s = (pointAX - pointBX) * normalX + (pointAY - pointBY) * normalY;
+ if (s < 0.0) {
+ this.m_axis.NegativeSelf();
+ }
+ }
+ else {
+ localPointA1 = this.m_proxyA.GetVertex(cache.indexA[0]);
+ localPointA2 = this.m_proxyA.GetVertex(cache.indexA[1]);
+ localPointB1 = this.m_proxyB.GetVertex(cache.indexB[0]);
+ localPointB2 = this.m_proxyB.GetVertex(cache.indexB[1]);
+ var pA = b2Math.MulX(transformA, localPointA);
+ var dA = b2Math.MulMV(transformA.R, b2Math.SubtractVV(localPointA2, localPointA1));
+ var pB = b2Math.MulX(transformB, localPointB);
+ var dB = b2Math.MulMV(transformB.R, b2Math.SubtractVV(localPointB2, localPointB1));
+ var a = dA.x * dA.x + dA.y * dA.y;
+ var e = dB.x * dB.x + dB.y * dB.y;
+ var r = b2Math.SubtractVV(dB, dA);
+ var c = dA.x * r.x + dA.y * r.y;
+ var f = dB.x * r.x + dB.y * r.y;
+ var b = dA.x * dB.x + dA.y * dB.y;
+ var denom = a * e - b * b;
+ s = 0.0;
+ if (denom != 0.0) {
+ s = b2Math.Clamp((b * f - c * e) / denom, 0.0, 1.0);
+ }
+ var t = (b * s + f) / e;
+ if (t < 0.0) {
+ t = 0.0;
+ s = b2Math.Clamp((b - c) / a, 0.0, 1.0);
+ }
+ localPointA = new b2Vec2();
+ localPointA.x = localPointA1.x + s * (localPointA2.x - localPointA1.x);
+ localPointA.y = localPointA1.y + s * (localPointA2.y - localPointA1.y);
+ localPointB = new b2Vec2();
+ localPointB.x = localPointB1.x + s * (localPointB2.x - localPointB1.x);
+ localPointB.y = localPointB1.y + s * (localPointB2.y - localPointB1.y);
+ if (s == 0.0 || s == 1.0) {
+ this.m_type = b2SeparationFunction.e_faceB;
+ this.m_axis = b2Math.CrossVF(b2Math.SubtractVV(localPointB2, localPointB1), 1.0);
+ this.m_axis.Normalize();
+ this.m_localPoint = localPointB;
+ tVec = this.m_axis;
+ tMat = transformB.R;
+ normalX = tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
+ normalY = tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
+ tVec = this.m_localPoint;
+ tMat = transformB.R;
+ pointBX = transformB.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ pointBY = transformB.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ tVec = localPointA;
+ tMat = transformA.R;
+ pointAX = transformA.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ pointAY = transformA.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ sgn = (pointAX - pointBX) * normalX + (pointAY - pointBY) * normalY;
+ if (s < 0.0) {
+ this.m_axis.NegativeSelf();
+ }
+ }
+ else {
+ this.m_type = b2SeparationFunction.e_faceA;
+ this.m_axis = b2Math.CrossVF(b2Math.SubtractVV(localPointA2, localPointA1), 1.0);
+ this.m_localPoint = localPointA;
+ tVec = this.m_axis;
+ tMat = transformA.R;
+ normalX = tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
+ normalY = tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
+ tVec = this.m_localPoint;
+ tMat = transformA.R;
+ pointAX = transformA.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ pointAY = transformA.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ tVec = localPointB;
+ tMat = transformB.R;
+ pointBX = transformB.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ pointBY = transformB.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ sgn = (pointBX - pointAX) * normalX + (pointBY - pointAY) * normalY;
+ if (s < 0.0) {
+ this.m_axis.NegativeSelf();
+ }
+ }
+ }
+ }
+ b2SeparationFunction.prototype.Evaluate = function (transformA, transformB) {
+ var axisA;
+ var axisB;
+ var localPointA;
+ var localPointB;
+ var pointA;
+ var pointB;
+ var seperation = 0;
+ var normal;
+ switch (this.m_type) {
+ case b2SeparationFunction.e_points:
+ {
+ axisA = b2Math.MulTMV(transformA.R, this.m_axis);
+ axisB = b2Math.MulTMV(transformB.R, this.m_axis.GetNegative());
+ localPointA = this.m_proxyA.GetSupportVertex(axisA);
+ localPointB = this.m_proxyB.GetSupportVertex(axisB);
+ pointA = b2Math.MulX(transformA, localPointA);
+ pointB = b2Math.MulX(transformB, localPointB);
+ seperation = (pointB.x - pointA.x) * this.m_axis.x + (pointB.y - pointA.y) * this.m_axis.y;
+ return seperation;
+ }
+ case b2SeparationFunction.e_faceA:
+ {
+ normal = b2Math.MulMV(transformA.R, this.m_axis);
+ pointA = b2Math.MulX(transformA, this.m_localPoint);
+ axisB = b2Math.MulTMV(transformB.R, normal.GetNegative());
+ localPointB = this.m_proxyB.GetSupportVertex(axisB);
+ pointB = b2Math.MulX(transformB, localPointB);
+ seperation = (pointB.x - pointA.x) * normal.x + (pointB.y - pointA.y) * normal.y;
+ return seperation;
+ }
+ case b2SeparationFunction.e_faceB:
+ {
+ normal = b2Math.MulMV(transformB.R, this.m_axis);
+ pointB = b2Math.MulX(transformB, this.m_localPoint);
+ axisA = b2Math.MulTMV(transformA.R, normal.GetNegative());
+ localPointA = this.m_proxyA.GetSupportVertex(axisA);
+ pointA = b2Math.MulX(transformA, localPointA);
+ seperation = (pointA.x - pointB.x) * normal.x + (pointA.y - pointB.y) * normal.y;
+ return seperation;
+ }
+ default:
+ b2Settings.b2Assert(false);
+ return 0.0;
+ }
+ }
+ Box2D.postDefs.push(function () {
+ Box2D.Collision.b2SeparationFunction.e_points = 0x01;
+ Box2D.Collision.b2SeparationFunction.e_faceA = 0x02;
+ Box2D.Collision.b2SeparationFunction.e_faceB = 0x04;
+ });
+ b2Simplex.b2Simplex = function () {
+ this.m_v1 = new b2SimplexVertex();
+ this.m_v2 = new b2SimplexVertex();
+ this.m_v3 = new b2SimplexVertex();
+ this.m_vertices = new Vector(3);
+ };
+ b2Simplex.prototype.b2Simplex = function () {
+ this.m_vertices[0] = this.m_v1;
+ this.m_vertices[1] = this.m_v2;
+ this.m_vertices[2] = this.m_v3;
+ }
+ b2Simplex.prototype.ReadCache = function (cache, proxyA, transformA, proxyB, transformB) {
+ b2Settings.b2Assert(0 <= cache.count && cache.count <= 3);
+ var wALocal;
+ var wBLocal;
+ this.m_count = cache.count;
+ var vertices = this.m_vertices;
+ for (var i = 0; i < this.m_count; i++) {
+ var v = vertices[i];
+ v.indexA = cache.indexA[i];
+ v.indexB = cache.indexB[i];
+ wALocal = proxyA.GetVertex(v.indexA);
+ wBLocal = proxyB.GetVertex(v.indexB);
+ v.wA = b2Math.MulX(transformA, wALocal);
+ v.wB = b2Math.MulX(transformB, wBLocal);
+ v.w = b2Math.SubtractVV(v.wB, v.wA);
+ v.a = 0;
+ }
+ if (this.m_count > 1) {
+ var metric1 = cache.metric;
+ var metric2 = this.GetMetric();
+ if (metric2 < .5 * metric1 || 2.0 * metric1 < metric2 || metric2 < Number.MIN_VALUE) {
+ this.m_count = 0;
+ }
+ }
+ if (this.m_count == 0) {
+ v = vertices[0];
+ v.indexA = 0;
+ v.indexB = 0;
+ wALocal = proxyA.GetVertex(0);
+ wBLocal = proxyB.GetVertex(0);
+ v.wA = b2Math.MulX(transformA, wALocal);
+ v.wB = b2Math.MulX(transformB, wBLocal);
+ v.w = b2Math.SubtractVV(v.wB, v.wA);
+ this.m_count = 1;
+ }
+ }
+ b2Simplex.prototype.WriteCache = function (cache) {
+ cache.metric = this.GetMetric();
+ cache.count = Box2D.parseUInt(this.m_count);
+ var vertices = this.m_vertices;
+ for (var i = 0; i < this.m_count; i++) {
+ cache.indexA[i] = Box2D.parseUInt(vertices[i].indexA);
+ cache.indexB[i] = Box2D.parseUInt(vertices[i].indexB);
+ }
+ }
+ b2Simplex.prototype.GetSearchDirection = function () {
+ switch (this.m_count) {
+ case 1:
+ return this.m_v1.w.GetNegative();
+ case 2:
+ {
+ var e12 = b2Math.SubtractVV(this.m_v2.w, this.m_v1.w);
+ var sgn = b2Math.CrossVV(e12, this.m_v1.w.GetNegative());
+ if (sgn > 0.0) {
+ return b2Math.CrossFV(1.0, e12);
+ }
+ else {
+ return b2Math.CrossVF(e12, 1.0);
+ }
+ }
+ default:
+ b2Settings.b2Assert(false);
+ return new b2Vec2();
+ }
+ }
+ b2Simplex.prototype.GetClosestPoint = function () {
+ switch (this.m_count) {
+ case 0:
+ b2Settings.b2Assert(false);
+ return new b2Vec2();
+ case 1:
+ return this.m_v1.w;
+ case 2:
+ return new b2Vec2(this.m_v1.a * this.m_v1.w.x + this.m_v2.a * this.m_v2.w.x, this.m_v1.a * this.m_v1.w.y + this.m_v2.a * this.m_v2.w.y);
+ default:
+ b2Settings.b2Assert(false);
+ return new b2Vec2();
+ }
+ }
+ b2Simplex.prototype.GetWitnessPoints = function (pA, pB) {
+ switch (this.m_count) {
+ case 0:
+ b2Settings.b2Assert(false);
+ break;
+ case 1:
+ pA.SetV(this.m_v1.wA);
+ pB.SetV(this.m_v1.wB);
+ break;
+ case 2:
+ pA.x = this.m_v1.a * this.m_v1.wA.x + this.m_v2.a * this.m_v2.wA.x;
+ pA.y = this.m_v1.a * this.m_v1.wA.y + this.m_v2.a * this.m_v2.wA.y;
+ pB.x = this.m_v1.a * this.m_v1.wB.x + this.m_v2.a * this.m_v2.wB.x;
+ pB.y = this.m_v1.a * this.m_v1.wB.y + this.m_v2.a * this.m_v2.wB.y;
+ break;
+ case 3:
+ pB.x = pA.x = this.m_v1.a * this.m_v1.wA.x + this.m_v2.a * this.m_v2.wA.x + this.m_v3.a * this.m_v3.wA.x;
+ pB.y = pA.y = this.m_v1.a * this.m_v1.wA.y + this.m_v2.a * this.m_v2.wA.y + this.m_v3.a * this.m_v3.wA.y;
+ break;
+ default:
+ b2Settings.b2Assert(false);
+ break;
+ }
+ }
+ b2Simplex.prototype.GetMetric = function () {
+ switch (this.m_count) {
+ case 0:
+ b2Settings.b2Assert(false);
+ return 0.0;
+ case 1:
+ return 0.0;
+ case 2:
+ return b2Math.SubtractVV(this.m_v1.w, this.m_v2.w).Length();
+ case 3:
+ return b2Math.CrossVV(b2Math.SubtractVV(this.m_v2.w, this.m_v1.w), b2Math.SubtractVV(this.m_v3.w, this.m_v1.w));
+ default:
+ b2Settings.b2Assert(false);
+ return 0.0;
+ }
+ }
+ b2Simplex.prototype.Solve2 = function () {
+ var w1 = this.m_v1.w;
+ var w2 = this.m_v2.w;
+ var e12 = b2Math.SubtractVV(w2, w1);
+ var d12_2 = (-(w1.x * e12.x + w1.y * e12.y));
+ if (d12_2 <= 0.0) {
+ this.m_v1.a = 1.0;
+ this.m_count = 1;
+ return;
+ }
+ var d12_1 = (w2.x * e12.x + w2.y * e12.y);
+ if (d12_1 <= 0.0) {
+ this.m_v2.a = 1.0;
+ this.m_count = 1;
+ this.m_v1.Set(this.m_v2);
+ return;
+ }
+ var inv_d12 = 1.0 / (d12_1 + d12_2);
+ this.m_v1.a = d12_1 * inv_d12;
+ this.m_v2.a = d12_2 * inv_d12;
+ this.m_count = 2;
+ }
+ b2Simplex.prototype.Solve3 = function () {
+ var w1 = this.m_v1.w;
+ var w2 = this.m_v2.w;
+ var w3 = this.m_v3.w;
+ var e12 = b2Math.SubtractVV(w2, w1);
+ var w1e12 = b2Math.Dot(w1, e12);
+ var w2e12 = b2Math.Dot(w2, e12);
+ var d12_1 = w2e12;
+ var d12_2 = (-w1e12);
+ var e13 = b2Math.SubtractVV(w3, w1);
+ var w1e13 = b2Math.Dot(w1, e13);
+ var w3e13 = b2Math.Dot(w3, e13);
+ var d13_1 = w3e13;
+ var d13_2 = (-w1e13);
+ var e23 = b2Math.SubtractVV(w3, w2);
+ var w2e23 = b2Math.Dot(w2, e23);
+ var w3e23 = b2Math.Dot(w3, e23);
+ var d23_1 = w3e23;
+ var d23_2 = (-w2e23);
+ var n123 = b2Math.CrossVV(e12, e13);
+ var d123_1 = n123 * b2Math.CrossVV(w2, w3);
+ var d123_2 = n123 * b2Math.CrossVV(w3, w1);
+ var d123_3 = n123 * b2Math.CrossVV(w1, w2);
+ if (d12_2 <= 0.0 && d13_2 <= 0.0) {
+ this.m_v1.a = 1.0;
+ this.m_count = 1;
+ return;
+ }
+ if (d12_1 > 0.0 && d12_2 > 0.0 && d123_3 <= 0.0) {
+ var inv_d12 = 1.0 / (d12_1 + d12_2);
+ this.m_v1.a = d12_1 * inv_d12;
+ this.m_v2.a = d12_2 * inv_d12;
+ this.m_count = 2;
+ return;
+ }
+ if (d13_1 > 0.0 && d13_2 > 0.0 && d123_2 <= 0.0) {
+ var inv_d13 = 1.0 / (d13_1 + d13_2);
+ this.m_v1.a = d13_1 * inv_d13;
+ this.m_v3.a = d13_2 * inv_d13;
+ this.m_count = 2;
+ this.m_v2.Set(this.m_v3);
+ return;
+ }
+ if (d12_1 <= 0.0 && d23_2 <= 0.0) {
+ this.m_v2.a = 1.0;
+ this.m_count = 1;
+ this.m_v1.Set(this.m_v2);
+ return;
+ }
+ if (d13_1 <= 0.0 && d23_1 <= 0.0) {
+ this.m_v3.a = 1.0;
+ this.m_count = 1;
+ this.m_v1.Set(this.m_v3);
+ return;
+ }
+ if (d23_1 > 0.0 && d23_2 > 0.0 && d123_1 <= 0.0) {
+ var inv_d23 = 1.0 / (d23_1 + d23_2);
+ this.m_v2.a = d23_1 * inv_d23;
+ this.m_v3.a = d23_2 * inv_d23;
+ this.m_count = 2;
+ this.m_v1.Set(this.m_v3);
+ return;
+ }
+ var inv_d123 = 1.0 / (d123_1 + d123_2 + d123_3);
+ this.m_v1.a = d123_1 * inv_d123;
+ this.m_v2.a = d123_2 * inv_d123;
+ this.m_v3.a = d123_3 * inv_d123;
+ this.m_count = 3;
+ }
+ b2SimplexCache.b2SimplexCache = function () {
+ this.indexA = new Vector_a2j_Number(3);
+ this.indexB = new Vector_a2j_Number(3);
+ };
+ b2SimplexVertex.b2SimplexVertex = function () {};
+ b2SimplexVertex.prototype.Set = function (other) {
+ this.wA.SetV(other.wA);
+ this.wB.SetV(other.wB);
+ this.w.SetV(other.w);
+ this.a = other.a;
+ this.indexA = other.indexA;
+ this.indexB = other.indexB;
+ }
+ b2TimeOfImpact.b2TimeOfImpact = function () {};
+ b2TimeOfImpact.TimeOfImpact = function (input) {
+ ++b2TimeOfImpact.b2_toiCalls;
+ var proxyA = input.proxyA;
+ var proxyB = input.proxyB;
+ var sweepA = input.sweepA;
+ var sweepB = input.sweepB;
+ b2Settings.b2Assert(sweepA.t0 == sweepB.t0);
+ b2Settings.b2Assert(1.0 - sweepA.t0 > Number.MIN_VALUE);
+ var radius = proxyA.m_radius + proxyB.m_radius;
+ var tolerance = input.tolerance;
+ var alpha = 0.0;
+ var k_maxIterations = 1000;
+ var iter = 0;
+ var target = 0.0;
+ b2TimeOfImpact.s_cache.count = 0;
+ b2TimeOfImpact.s_distanceInput.useRadii = false;
+ for (;;) {
+ sweepA.GetTransform(b2TimeOfImpact.s_xfA, alpha);
+ sweepB.GetTransform(b2TimeOfImpact.s_xfB, alpha);
+ b2TimeOfImpact.s_distanceInput.proxyA = proxyA;
+ b2TimeOfImpact.s_distanceInput.proxyB = proxyB;
+ b2TimeOfImpact.s_distanceInput.transformA = b2TimeOfImpact.s_xfA;
+ b2TimeOfImpact.s_distanceInput.transformB = b2TimeOfImpact.s_xfB;
+ b2Distance.Distance(b2TimeOfImpact.s_distanceOutput, b2TimeOfImpact.s_cache, b2TimeOfImpact.s_distanceInput);
+ if (b2TimeOfImpact.s_distanceOutput.distance <= 0.0) {
+ alpha = 1.0;
+ break;
+ }
+ b2TimeOfImpact.s_fcn.Initialize(b2TimeOfImpact.s_cache, proxyA, b2TimeOfImpact.s_xfA, proxyB, b2TimeOfImpact.s_xfB);
+ var separation = b2TimeOfImpact.s_fcn.Evaluate(b2TimeOfImpact.s_xfA, b2TimeOfImpact.s_xfB);
+ if (separation <= 0.0) {
+ alpha = 1.0;
+ break;
+ }
+ if (iter == 0) {
+ if (separation > radius) {
+ target = b2Math.Max(radius - tolerance, 0.75 * radius);
+ }
+ else {
+ target = b2Math.Max(separation - tolerance, 0.02 * radius);
+ }
+ }
+ if (separation - target < 0.5 * tolerance) {
+ if (iter == 0) {
+ alpha = 1.0;
+ break;
+ }
+ break;
+ }
+ var newAlpha = alpha; {
+ var x1 = alpha;
+ var x2 = 1.0;
+ var f1 = separation;
+ sweepA.GetTransform(b2TimeOfImpact.s_xfA, x2);
+ sweepB.GetTransform(b2TimeOfImpact.s_xfB, x2);
+ var f2 = b2TimeOfImpact.s_fcn.Evaluate(b2TimeOfImpact.s_xfA, b2TimeOfImpact.s_xfB);
+ if (f2 >= target) {
+ alpha = 1.0;
+ break;
+ }
+ var rootIterCount = 0;
+ for (;;) {
+ var x = 0;
+ if (rootIterCount & 1) {
+ x = x1 + (target - f1) * (x2 - x1) / (f2 - f1);
+ }
+ else {
+ x = 0.5 * (x1 + x2);
+ }
+ sweepA.GetTransform(b2TimeOfImpact.s_xfA, x);
+ sweepB.GetTransform(b2TimeOfImpact.s_xfB, x);
+ var f = b2TimeOfImpact.s_fcn.Evaluate(b2TimeOfImpact.s_xfA, b2TimeOfImpact.s_xfB);
+ if (b2Math.Abs(f - target) < 0.025 * tolerance) {
+ newAlpha = x;
+ break;
+ }
+ if (f > target) {
+ x1 = x;
+ f1 = f;
+ }
+ else {
+ x2 = x;
+ f2 = f;
+ }++rootIterCount;
+ ++b2TimeOfImpact.b2_toiRootIters;
+ if (rootIterCount == 50) {
+ break;
+ }
+ }
+ b2TimeOfImpact.b2_toiMaxRootIters = b2Math.Max(b2TimeOfImpact.b2_toiMaxRootIters, rootIterCount);
+ }
+ if (newAlpha < (1.0 + 100.0 * Number.MIN_VALUE) * alpha) {
+ break;
+ }
+ alpha = newAlpha;
+ iter++;
+ ++b2TimeOfImpact.b2_toiIters;
+ if (iter == k_maxIterations) {
+ break;
+ }
+ }
+ b2TimeOfImpact.b2_toiMaxIters = b2Math.Max(b2TimeOfImpact.b2_toiMaxIters, iter);
+ return alpha;
+ }
+ Box2D.postDefs.push(function () {
+ Box2D.Collision.b2TimeOfImpact.b2_toiCalls = 0;
+ Box2D.Collision.b2TimeOfImpact.b2_toiIters = 0;
+ Box2D.Collision.b2TimeOfImpact.b2_toiMaxIters = 0;
+ Box2D.Collision.b2TimeOfImpact.b2_toiRootIters = 0;
+ Box2D.Collision.b2TimeOfImpact.b2_toiMaxRootIters = 0;
+ Box2D.Collision.b2TimeOfImpact.s_cache = new b2SimplexCache();
+ Box2D.Collision.b2TimeOfImpact.s_distanceInput = new b2DistanceInput();
+ Box2D.Collision.b2TimeOfImpact.s_xfA = new b2Transform();
+ Box2D.Collision.b2TimeOfImpact.s_xfB = new b2Transform();
+ Box2D.Collision.b2TimeOfImpact.s_fcn = new b2SeparationFunction();
+ Box2D.Collision.b2TimeOfImpact.s_distanceOutput = new b2DistanceOutput();
+ });
+ b2TOIInput.b2TOIInput = function () {
+ this.proxyA = new b2DistanceProxy();
+ this.proxyB = new b2DistanceProxy();
+ this.sweepA = new b2Sweep();
+ this.sweepB = new b2Sweep();
+ };
+ b2WorldManifold.b2WorldManifold = function () {
+ this.m_normal = new b2Vec2();
+ };
+ b2WorldManifold.prototype.b2WorldManifold = function () {
+ this.m_points = new Vector(b2Settings.b2_maxManifoldPoints);
+ for (var i = 0; i < b2Settings.b2_maxManifoldPoints; i++) {
+ this.m_points[i] = new b2Vec2();
+ }
+ }
+ b2WorldManifold.prototype.Initialize = function (manifold, xfA, radiusA, xfB, radiusB) {
+ if (radiusA === undefined) radiusA = 0;
+ if (radiusB === undefined) radiusB = 0;
+ if (manifold.m_pointCount == 0) {
+ return;
+ }
+ var i = 0;
+ var tVec;
+ var tMat;
+ var normalX = 0;
+ var normalY = 0;
+ var planePointX = 0;
+ var planePointY = 0;
+ var clipPointX = 0;
+ var clipPointY = 0;
+ switch (manifold.m_type) {
+ case b2Manifold.e_circles:
+ {
+ tMat = xfA.R;
+ tVec = manifold.m_localPoint;
+ var pointAX = xfA.position.x + tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
+ var pointAY = xfA.position.y + tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
+ tMat = xfB.R;
+ tVec = manifold.m_points[0].m_localPoint;
+ var pointBX = xfB.position.x + tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
+ var pointBY = xfB.position.y + tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
+ var dX = pointBX - pointAX;
+ var dY = pointBY - pointAY;
+ var d2 = dX * dX + dY * dY;
+ if (d2 > Number.MIN_VALUE * Number.MIN_VALUE) {
+ var d = Math.sqrt(d2);
+ this.m_normal.x = dX / d;
+ this.m_normal.y = dY / d;
+ }
+ else {
+ this.m_normal.x = 1;
+ this.m_normal.y = 0;
+ }
+ var cAX = pointAX + radiusA * this.m_normal.x;
+ var cAY = pointAY + radiusA * this.m_normal.y;
+ var cBX = pointBX - radiusB * this.m_normal.x;
+ var cBY = pointBY - radiusB * this.m_normal.y;
+ this.m_points[0].x = 0.5 * (cAX + cBX);
+ this.m_points[0].y = 0.5 * (cAY + cBY);
+ }
+ break;
+ case b2Manifold.e_faceA:
+ {
+ tMat = xfA.R;
+ tVec = manifold.m_localPlaneNormal;
+ normalX = tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
+ normalY = tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
+ tMat = xfA.R;
+ tVec = manifold.m_localPoint;
+ planePointX = xfA.position.x + tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
+ planePointY = xfA.position.y + tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
+ this.m_normal.x = normalX;
+ this.m_normal.y = normalY;
+ for (i = 0;
+ i < manifold.m_pointCount; i++) {
+ tMat = xfB.R;
+ tVec = manifold.m_points[i].m_localPoint;
+ clipPointX = xfB.position.x + tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
+ clipPointY = xfB.position.y + tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
+ this.m_points[i].x = clipPointX + 0.5 * (radiusA - (clipPointX - planePointX) * normalX - (clipPointY - planePointY) * normalY - radiusB) * normalX;
+ this.m_points[i].y = clipPointY + 0.5 * (radiusA - (clipPointX - planePointX) * normalX - (clipPointY - planePointY) * normalY - radiusB) * normalY;
+ }
+ }
+ break;
+ case b2Manifold.e_faceB:
+ {
+ tMat = xfB.R;
+ tVec = manifold.m_localPlaneNormal;
+ normalX = tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
+ normalY = tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
+ tMat = xfB.R;
+ tVec = manifold.m_localPoint;
+ planePointX = xfB.position.x + tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
+ planePointY = xfB.position.y + tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
+ this.m_normal.x = (-normalX);
+ this.m_normal.y = (-normalY);
+ for (i = 0;
+ i < manifold.m_pointCount; i++) {
+ tMat = xfA.R;
+ tVec = manifold.m_points[i].m_localPoint;
+ clipPointX = xfA.position.x + tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
+ clipPointY = xfA.position.y + tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
+ this.m_points[i].x = clipPointX + 0.5 * (radiusB - (clipPointX - planePointX) * normalX - (clipPointY - planePointY) * normalY - radiusA) * normalX;
+ this.m_points[i].y = clipPointY + 0.5 * (radiusB - (clipPointX - planePointX) * normalX - (clipPointY - planePointY) * normalY - radiusA) * normalY;
+ }
+ }
+ break;
+ }
+ }
+ ClipVertex.ClipVertex = function () {
+ this.v = new b2Vec2();
+ this.id = new b2ContactID();
+ };
+ ClipVertex.prototype.Set = function (other) {
+ this.v.SetV(other.v);
+ this.id.Set(other.id);
+ }
+ Features.Features = function () {};
+ Object.defineProperty(Features.prototype, 'referenceEdge', {
+ enumerable: false,
+ configurable: true,
+ get: function () {
+ return this._referenceEdge;
+ }
+ });
+ Object.defineProperty(Features.prototype, 'referenceEdge', {
+ enumerable: false,
+ configurable: true,
+ set: function (value) {
+ if (value === undefined) value = 0;
+ this._referenceEdge = value;
+ this._m_id._key = (this._m_id._key & 0xffffff00) | (this._referenceEdge & 0x000000ff);
+ }
+ });
+ Object.defineProperty(Features.prototype, 'incidentEdge', {
+ enumerable: false,
+ configurable: true,
+ get: function () {
+ return this._incidentEdge;
+ }
+ });
+ Object.defineProperty(Features.prototype, 'incidentEdge', {
+ enumerable: false,
+ configurable: true,
+ set: function (value) {
+ if (value === undefined) value = 0;
+ this._incidentEdge = value;
+ this._m_id._key = (this._m_id._key & 0xffff00ff) | ((this._incidentEdge << 8) & 0x0000ff00);
+ }
+ });
+ Object.defineProperty(Features.prototype, 'incidentVertex', {
+ enumerable: false,
+ configurable: true,
+ get: function () {
+ return this._incidentVertex;
+ }
+ });
+ Object.defineProperty(Features.prototype, 'incidentVertex', {
+ enumerable: false,
+ configurable: true,
+ set: function (value) {
+ if (value === undefined) value = 0;
+ this._incidentVertex = value;
+ this._m_id._key = (this._m_id._key & 0xff00ffff) | ((this._incidentVertex << 16) & 0x00ff0000);
+ }
+ });
+ Object.defineProperty(Features.prototype, 'flip', {
+ enumerable: false,
+ configurable: true,
+ get: function () {
+ return this._flip;
+ }
+ });
+ Object.defineProperty(Features.prototype, 'flip', {
+ enumerable: false,
+ configurable: true,
+ set: function (value) {
+ if (value === undefined) value = 0;
+ this._flip = value;
+ this._m_id._key = (this._m_id._key & 0x00ffffff) | ((this._flip << 24) & 0xff000000);
+ }
+ });
+})();
+(function () {
+ var b2Color = Box2D.Common.b2Color,
+ b2internal = Box2D.Common.b2internal,
+ b2Settings = Box2D.Common.b2Settings,
+ b2CircleShape = Box2D.Collision.Shapes.b2CircleShape,
+ b2EdgeChainDef = Box2D.Collision.Shapes.b2EdgeChainDef,
+ b2EdgeShape = Box2D.Collision.Shapes.b2EdgeShape,
+ b2MassData = Box2D.Collision.Shapes.b2MassData,
+ b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape,
+ b2Shape = Box2D.Collision.Shapes.b2Shape,
+ b2Mat22 = Box2D.Common.Math.b2Mat22,
+ b2Mat33 = Box2D.Common.Math.b2Mat33,
+ b2Math = Box2D.Common.Math.b2Math,
+ b2Sweep = Box2D.Common.Math.b2Sweep,
+ b2Transform = Box2D.Common.Math.b2Transform,
+ b2Vec2 = Box2D.Common.Math.b2Vec2,
+ b2Vec3 = Box2D.Common.Math.b2Vec3,
+ b2Body = Box2D.Dynamics.b2Body,
+ b2BodyDef = Box2D.Dynamics.b2BodyDef,
+ b2ContactFilter = Box2D.Dynamics.b2ContactFilter,
+ b2ContactImpulse = Box2D.Dynamics.b2ContactImpulse,
+ b2ContactListener = Box2D.Dynamics.b2ContactListener,
+ b2ContactManager = Box2D.Dynamics.b2ContactManager,
+ b2DebugDraw = Box2D.Dynamics.b2DebugDraw,
+ b2DestructionListener = Box2D.Dynamics.b2DestructionListener,
+ b2FilterData = Box2D.Dynamics.b2FilterData,
+ b2Fixture = Box2D.Dynamics.b2Fixture,
+ b2FixtureDef = Box2D.Dynamics.b2FixtureDef,
+ b2Island = Box2D.Dynamics.b2Island,
+ b2TimeStep = Box2D.Dynamics.b2TimeStep,
+ b2World = Box2D.Dynamics.b2World,
+ b2AABB = Box2D.Collision.b2AABB,
+ b2Bound = Box2D.Collision.b2Bound,
+ b2BoundValues = Box2D.Collision.b2BoundValues,
+ b2Collision = Box2D.Collision.b2Collision,
+ b2ContactID = Box2D.Collision.b2ContactID,
+ b2ContactPoint = Box2D.Collision.b2ContactPoint,
+ b2Distance = Box2D.Collision.b2Distance,
+ b2DistanceInput = Box2D.Collision.b2DistanceInput,
+ b2DistanceOutput = Box2D.Collision.b2DistanceOutput,
+ b2DistanceProxy = Box2D.Collision.b2DistanceProxy,
+ b2DynamicTree = Box2D.Collision.b2DynamicTree,
+ b2DynamicTreeBroadPhase = Box2D.Collision.b2DynamicTreeBroadPhase,
+ b2DynamicTreeNode = Box2D.Collision.b2DynamicTreeNode,
+ b2DynamicTreePair = Box2D.Collision.b2DynamicTreePair,
+ b2Manifold = Box2D.Collision.b2Manifold,
+ b2ManifoldPoint = Box2D.Collision.b2ManifoldPoint,
+ b2Point = Box2D.Collision.b2Point,
+ b2RayCastInput = Box2D.Collision.b2RayCastInput,
+ b2RayCastOutput = Box2D.Collision.b2RayCastOutput,
+ b2Segment = Box2D.Collision.b2Segment,
+ b2SeparationFunction = Box2D.Collision.b2SeparationFunction,
+ b2Simplex = Box2D.Collision.b2Simplex,
+ b2SimplexCache = Box2D.Collision.b2SimplexCache,
+ b2SimplexVertex = Box2D.Collision.b2SimplexVertex,
+ b2TimeOfImpact = Box2D.Collision.b2TimeOfImpact,
+ b2TOIInput = Box2D.Collision.b2TOIInput,
+ b2WorldManifold = Box2D.Collision.b2WorldManifold,
+ ClipVertex = Box2D.Collision.ClipVertex,
+ Features = Box2D.Collision.Features,
+ IBroadPhase = Box2D.Collision.IBroadPhase;
+
+ Box2D.inherit(b2CircleShape, Box2D.Collision.Shapes.b2Shape);
+ b2CircleShape.prototype.__super = Box2D.Collision.Shapes.b2Shape.prototype;
+ b2CircleShape.b2CircleShape = function () {
+ Box2D.Collision.Shapes.b2Shape.b2Shape.apply(this, arguments);
+ this.m_p = new b2Vec2();
+ };
+ b2CircleShape.prototype.Copy = function () {
+ var s = new b2CircleShape();
+ s.Set(this);
+ return s;
+ }
+ b2CircleShape.prototype.Set = function (other) {
+ this.__super.Set.call(this, other);
+ if (Box2D.is(other, b2CircleShape)) {
+ var other2 = (other instanceof b2CircleShape ? other : null);
+ this.m_p.SetV(other2.m_p);
+ }
+ }
+ b2CircleShape.prototype.TestPoint = function (transform, p) {
+ var tMat = transform.R;
+ var dX = transform.position.x + (tMat.col1.x * this.m_p.x + tMat.col2.x * this.m_p.y);
+ var dY = transform.position.y + (tMat.col1.y * this.m_p.x + tMat.col2.y * this.m_p.y);
+ dX = p.x - dX;
+ dY = p.y - dY;
+ return (dX * dX + dY * dY) <= this.m_radius * this.m_radius;
+ }
+ b2CircleShape.prototype.RayCast = function (output, input, transform) {
+ var tMat = transform.R;
+ var positionX = transform.position.x + (tMat.col1.x * this.m_p.x + tMat.col2.x * this.m_p.y);
+ var positionY = transform.position.y + (tMat.col1.y * this.m_p.x + tMat.col2.y * this.m_p.y);
+ var sX = input.p1.x - positionX;
+ var sY = input.p1.y - positionY;
+ var b = (sX * sX + sY * sY) - this.m_radius * this.m_radius;
+ var rX = input.p2.x - input.p1.x;
+ var rY = input.p2.y - input.p1.y;
+ var c = (sX * rX + sY * rY);
+ var rr = (rX * rX + rY * rY);
+ var sigma = c * c - rr * b;
+ if (sigma < 0.0 || rr < Number.MIN_VALUE) {
+ return false;
+ }
+ var a = (-(c + Math.sqrt(sigma)));
+ if (0.0 <= a && a <= input.maxFraction * rr) {
+ a /= rr;
+ output.fraction = a;
+ output.normal.x = sX + a * rX;
+ output.normal.y = sY + a * rY;
+ output.normal.Normalize();
+ return true;
+ }
+ return false;
+ }
+ b2CircleShape.prototype.ComputeAABB = function (aabb, transform) {
+ var tMat = transform.R;
+ var pX = transform.position.x + (tMat.col1.x * this.m_p.x + tMat.col2.x * this.m_p.y);
+ var pY = transform.position.y + (tMat.col1.y * this.m_p.x + tMat.col2.y * this.m_p.y);
+ aabb.lowerBound.Set(pX - this.m_radius, pY - this.m_radius);
+ aabb.upperBound.Set(pX + this.m_radius, pY + this.m_radius);
+ }
+ b2CircleShape.prototype.ComputeMass = function (massData, density) {
+ if (density === undefined) density = 0;
+ massData.mass = density * b2Settings.b2_pi * this.m_radius * this.m_radius;
+ massData.center.SetV(this.m_p);
+ massData.I = massData.mass * (0.5 * this.m_radius * this.m_radius + (this.m_p.x * this.m_p.x + this.m_p.y * this.m_p.y));
+ }
+ b2CircleShape.prototype.ComputeSubmergedArea = function (normal, offset, xf, c) {
+ if (offset === undefined) offset = 0;
+ var p = b2Math.MulX(xf, this.m_p);
+ var l = (-(b2Math.Dot(normal, p) - offset));
+ if (l < (-this.m_radius) + Number.MIN_VALUE) {
+ return 0;
+ }
+ if (l > this.m_radius) {
+ c.SetV(p);
+ return Math.PI * this.m_radius * this.m_radius;
+ }
+ var r2 = this.m_radius * this.m_radius;
+ var l2 = l * l;
+ var area = r2 * (Math.asin(l / this.m_radius) + Math.PI / 2) + l * Math.sqrt(r2 - l2);
+ var com = (-2 / 3 * Math.pow(r2 - l2, 1.5) / area);
+ c.x = p.x + normal.x * com;
+ c.y = p.y + normal.y * com;
+ return area;
+ }
+ b2CircleShape.prototype.GetLocalPosition = function () {
+ return this.m_p;
+ }
+ b2CircleShape.prototype.SetLocalPosition = function (position) {
+ this.m_p.SetV(position);
+ }
+ b2CircleShape.prototype.GetRadius = function () {
+ return this.m_radius;
+ }
+ b2CircleShape.prototype.SetRadius = function (radius) {
+ if (radius === undefined) radius = 0;
+ this.m_radius = radius;
+ }
+ b2CircleShape.prototype.b2CircleShape = function (radius) {
+ if (radius === undefined) radius = 0;
+ this.__super.b2Shape.call(this);
+ this.m_type = b2Shape.e_circleShape;
+ this.m_radius = radius;
+ }
+ b2EdgeChainDef.b2EdgeChainDef = function () {};
+ b2EdgeChainDef.prototype.b2EdgeChainDef = function () {
+ this.vertexCount = 0;
+ this.isALoop = true;
+ this.vertices = [];
+ }
+ Box2D.inherit(b2EdgeShape, Box2D.Collision.Shapes.b2Shape);
+ b2EdgeShape.prototype.__super = Box2D.Collision.Shapes.b2Shape.prototype;
+ b2EdgeShape.b2EdgeShape = function () {
+ Box2D.Collision.Shapes.b2Shape.b2Shape.apply(this, arguments);
+ this.s_supportVec = new b2Vec2();
+ this.m_v1 = new b2Vec2();
+ this.m_v2 = new b2Vec2();
+ this.m_coreV1 = new b2Vec2();
+ this.m_coreV2 = new b2Vec2();
+ this.m_normal = new b2Vec2();
+ this.m_direction = new b2Vec2();
+ this.m_cornerDir1 = new b2Vec2();
+ this.m_cornerDir2 = new b2Vec2();
+ };
+ b2EdgeShape.prototype.TestPoint = function (transform, p) {
+ return false;
+ }
+ b2EdgeShape.prototype.RayCast = function (output, input, transform) {
+ var tMat;
+ var rX = input.p2.x - input.p1.x;
+ var rY = input.p2.y - input.p1.y;
+ tMat = transform.R;
+ var v1X = transform.position.x + (tMat.col1.x * this.m_v1.x + tMat.col2.x * this.m_v1.y);
+ var v1Y = transform.position.y + (tMat.col1.y * this.m_v1.x + tMat.col2.y * this.m_v1.y);
+ var nX = transform.position.y + (tMat.col1.y * this.m_v2.x + tMat.col2.y * this.m_v2.y) - v1Y;
+ var nY = (-(transform.position.x + (tMat.col1.x * this.m_v2.x + tMat.col2.x * this.m_v2.y) - v1X));
+ var k_slop = 100.0 * Number.MIN_VALUE;
+ var denom = (-(rX * nX + rY * nY));
+ if (denom > k_slop) {
+ var bX = input.p1.x - v1X;
+ var bY = input.p1.y - v1Y;
+ var a = (bX * nX + bY * nY);
+ if (0.0 <= a && a <= input.maxFraction * denom) {
+ var mu2 = (-rX * bY) + rY * bX;
+ if ((-k_slop * denom) <= mu2 && mu2 <= denom * (1.0 + k_slop)) {
+ a /= denom;
+ output.fraction = a;
+ var nLen = Math.sqrt(nX * nX + nY * nY);
+ output.normal.x = nX / nLen;
+ output.normal.y = nY / nLen;
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+ b2EdgeShape.prototype.ComputeAABB = function (aabb, transform) {
+ var tMat = transform.R;
+ var v1X = transform.position.x + (tMat.col1.x * this.m_v1.x + tMat.col2.x * this.m_v1.y);
+ var v1Y = transform.position.y + (tMat.col1.y * this.m_v1.x + tMat.col2.y * this.m_v1.y);
+ var v2X = transform.position.x + (tMat.col1.x * this.m_v2.x + tMat.col2.x * this.m_v2.y);
+ var v2Y = transform.position.y + (tMat.col1.y * this.m_v2.x + tMat.col2.y * this.m_v2.y);
+ if (v1X < v2X) {
+ aabb.lowerBound.x = v1X;
+ aabb.upperBound.x = v2X;
+ }
+ else {
+ aabb.lowerBound.x = v2X;
+ aabb.upperBound.x = v1X;
+ }
+ if (v1Y < v2Y) {
+ aabb.lowerBound.y = v1Y;
+ aabb.upperBound.y = v2Y;
+ }
+ else {
+ aabb.lowerBound.y = v2Y;
+ aabb.upperBound.y = v1Y;
+ }
+ }
+ b2EdgeShape.prototype.ComputeMass = function (massData, density) {
+ if (density === undefined) density = 0;
+ massData.mass = 0;
+ massData.center.SetV(this.m_v1);
+ massData.I = 0;
+ }
+ b2EdgeShape.prototype.ComputeSubmergedArea = function (normal, offset, xf, c) {
+ if (offset === undefined) offset = 0;
+ var v0 = new b2Vec2(normal.x * offset, normal.y * offset);
+ var v1 = b2Math.MulX(xf, this.m_v1);
+ var v2 = b2Math.MulX(xf, this.m_v2);
+ var d1 = b2Math.Dot(normal, v1) - offset;
+ var d2 = b2Math.Dot(normal, v2) - offset;
+ if (d1 > 0) {
+ if (d2 > 0) {
+ return 0;
+ }
+ else {
+ v1.x = (-d2 / (d1 - d2) * v1.x) + d1 / (d1 - d2) * v2.x;
+ v1.y = (-d2 / (d1 - d2) * v1.y) + d1 / (d1 - d2) * v2.y;
+ }
+ }
+ else {
+ if (d2 > 0) {
+ v2.x = (-d2 / (d1 - d2) * v1.x) + d1 / (d1 - d2) * v2.x;
+ v2.y = (-d2 / (d1 - d2) * v1.y) + d1 / (d1 - d2) * v2.y;
+ }
+ else {}
+ }
+ c.x = (v0.x + v1.x + v2.x) / 3;
+ c.y = (v0.y + v1.y + v2.y) / 3;
+ return 0.5 * ((v1.x - v0.x) * (v2.y - v0.y) - (v1.y - v0.y) * (v2.x - v0.x));
+ }
+ b2EdgeShape.prototype.GetLength = function () {
+ return this.m_length;
+ }
+ b2EdgeShape.prototype.GetVertex1 = function () {
+ return this.m_v1;
+ }
+ b2EdgeShape.prototype.GetVertex2 = function () {
+ return this.m_v2;
+ }
+ b2EdgeShape.prototype.GetCoreVertex1 = function () {
+ return this.m_coreV1;
+ }
+ b2EdgeShape.prototype.GetCoreVertex2 = function () {
+ return this.m_coreV2;
+ }
+ b2EdgeShape.prototype.GetNormalVector = function () {
+ return this.m_normal;
+ }
+ b2EdgeShape.prototype.GetDirectionVector = function () {
+ return this.m_direction;
+ }
+ b2EdgeShape.prototype.GetCorner1Vector = function () {
+ return this.m_cornerDir1;
+ }
+ b2EdgeShape.prototype.GetCorner2Vector = function () {
+ return this.m_cornerDir2;
+ }
+ b2EdgeShape.prototype.Corner1IsConvex = function () {
+ return this.m_cornerConvex1;
+ }
+ b2EdgeShape.prototype.Corner2IsConvex = function () {
+ return this.m_cornerConvex2;
+ }
+ b2EdgeShape.prototype.GetFirstVertex = function (xf) {
+ var tMat = xf.R;
+ return new b2Vec2(xf.position.x + (tMat.col1.x * this.m_coreV1.x + tMat.col2.x * this.m_coreV1.y), xf.position.y + (tMat.col1.y * this.m_coreV1.x + tMat.col2.y * this.m_coreV1.y));
+ }
+ b2EdgeShape.prototype.GetNextEdge = function () {
+ return this.m_nextEdge;
+ }
+ b2EdgeShape.prototype.GetPrevEdge = function () {
+ return this.m_prevEdge;
+ }
+ b2EdgeShape.prototype.Support = function (xf, dX, dY) {
+ if (dX === undefined) dX = 0;
+ if (dY === undefined) dY = 0;
+ var tMat = xf.R;
+ var v1X = xf.position.x + (tMat.col1.x * this.m_coreV1.x + tMat.col2.x * this.m_coreV1.y);
+ var v1Y = xf.position.y + (tMat.col1.y * this.m_coreV1.x + tMat.col2.y * this.m_coreV1.y);
+ var v2X = xf.position.x + (tMat.col1.x * this.m_coreV2.x + tMat.col2.x * this.m_coreV2.y);
+ var v2Y = xf.position.y + (tMat.col1.y * this.m_coreV2.x + tMat.col2.y * this.m_coreV2.y);
+ if ((v1X * dX + v1Y * dY) > (v2X * dX + v2Y * dY)) {
+ this.s_supportVec.x = v1X;
+ this.s_supportVec.y = v1Y;
+ }
+ else {
+ this.s_supportVec.x = v2X;
+ this.s_supportVec.y = v2Y;
+ }
+ return this.s_supportVec;
+ }
+ b2EdgeShape.prototype.b2EdgeShape = function (v1, v2) {
+ this.__super.b2Shape.call(this);
+ this.m_type = b2Shape.e_edgeShape;
+ this.m_prevEdge = null;
+ this.m_nextEdge = null;
+ this.m_v1 = v1;
+ this.m_v2 = v2;
+ this.m_direction.Set(this.m_v2.x - this.m_v1.x, this.m_v2.y - this.m_v1.y);
+ this.m_length = this.m_direction.Normalize();
+ this.m_normal.Set(this.m_direction.y, (-this.m_direction.x));
+ this.m_coreV1.Set((-b2Settings.b2_toiSlop * (this.m_normal.x - this.m_direction.x)) + this.m_v1.x, (-b2Settings.b2_toiSlop * (this.m_normal.y - this.m_direction.y)) + this.m_v1.y);
+ this.m_coreV2.Set((-b2Settings.b2_toiSlop * (this.m_normal.x + this.m_direction.x)) + this.m_v2.x, (-b2Settings.b2_toiSlop * (this.m_normal.y + this.m_direction.y)) + this.m_v2.y);
+ this.m_cornerDir1 = this.m_normal;
+ this.m_cornerDir2.Set((-this.m_normal.x), (-this.m_normal.y));
+ }
+ b2EdgeShape.prototype.SetPrevEdge = function (edge, core, cornerDir, convex) {
+ this.m_prevEdge = edge;
+ this.m_coreV1 = core;
+ this.m_cornerDir1 = cornerDir;
+ this.m_cornerConvex1 = convex;
+ }
+ b2EdgeShape.prototype.SetNextEdge = function (edge, core, cornerDir, convex) {
+ this.m_nextEdge = edge;
+ this.m_coreV2 = core;
+ this.m_cornerDir2 = cornerDir;
+ this.m_cornerConvex2 = convex;
+ }
+ b2MassData.b2MassData = function () {
+ this.mass = 0.0;
+ this.center = new b2Vec2(0, 0);
+ this.I = 0.0;
+ };
+ Box2D.inherit(b2PolygonShape, Box2D.Collision.Shapes.b2Shape);
+ b2PolygonShape.prototype.__super = Box2D.Collision.Shapes.b2Shape.prototype;
+ b2PolygonShape.b2PolygonShape = function () {
+ Box2D.Collision.Shapes.b2Shape.b2Shape.apply(this, arguments);
+ };
+ b2PolygonShape.prototype.Copy = function () {
+ var s = new b2PolygonShape();
+ s.Set(this);
+ return s;
+ }
+ b2PolygonShape.prototype.Set = function (other) {
+ this.__super.Set.call(this, other);
+ if (Box2D.is(other, b2PolygonShape)) {
+ var other2 = (other instanceof b2PolygonShape ? other : null);
+ this.m_centroid.SetV(other2.m_centroid);
+ this.m_vertexCount = other2.m_vertexCount;
+ this.Reserve(this.m_vertexCount);
+ for (var i = 0; i < this.m_vertexCount; i++) {
+ this.m_vertices[i].SetV(other2.m_vertices[i]);
+ this.m_normals[i].SetV(other2.m_normals[i]);
+ }
+ }
+ }
+ b2PolygonShape.prototype.SetAsArray = function (vertices, vertexCount) {
+ if (vertexCount === undefined) vertexCount = 0;
+ var v = new Vector();
+ var i = 0,
+ tVec;
+ for (i = 0;
+ i < vertices.length; ++i) {
+ tVec = vertices[i];
+ v.push(tVec);
+ }
+ this.SetAsVector(v, vertexCount);
+ }
+ b2PolygonShape.AsArray = function (vertices, vertexCount) {
+ if (vertexCount === undefined) vertexCount = 0;
+ var polygonShape = new b2PolygonShape();
+ polygonShape.SetAsArray(vertices, vertexCount);
+ return polygonShape;
+ }
+ b2PolygonShape.prototype.SetAsVector = function (vertices, vertexCount) {
+ if (vertexCount === undefined) vertexCount = 0;
+ if (vertexCount == 0) vertexCount = vertices.length;
+ b2Settings.b2Assert(2 <= vertexCount);
+ this.m_vertexCount = vertexCount;
+ this.Reserve(vertexCount);
+ var i = 0;
+ for (i = 0;
+ i < this.m_vertexCount; i++) {
+ this.m_vertices[i].SetV(vertices[i]);
+ }
+ for (i = 0;
+ i < this.m_vertexCount; ++i) {
+ var i1 = parseInt(i);
+ var i2 = parseInt(i + 1 < this.m_vertexCount ? i + 1 : 0);
+ var edge = b2Math.SubtractVV(this.m_vertices[i2], this.m_vertices[i1]);
+ b2Settings.b2Assert(edge.LengthSquared() > Number.MIN_VALUE);
+ this.m_normals[i].SetV(b2Math.CrossVF(edge, 1.0));
+ this.m_normals[i].Normalize();
+ }
+ this.m_centroid = b2PolygonShape.ComputeCentroid(this.m_vertices, this.m_vertexCount);
+ }
+ b2PolygonShape.AsVector = function (vertices, vertexCount) {
+ if (vertexCount === undefined) vertexCount = 0;
+ var polygonShape = new b2PolygonShape();
+ polygonShape.SetAsVector(vertices, vertexCount);
+ return polygonShape;
+ }
+ b2PolygonShape.prototype.SetAsBox = function (hx, hy) {
+ if (hx === undefined) hx = 0;
+ if (hy === undefined) hy = 0;
+ this.m_vertexCount = 4;
+ this.Reserve(4);
+ this.m_vertices[0].Set((-hx), (-hy));
+ this.m_vertices[1].Set(hx, (-hy));
+ this.m_vertices[2].Set(hx, hy);
+ this.m_vertices[3].Set((-hx), hy);
+ this.m_normals[0].Set(0.0, (-1.0));
+ this.m_normals[1].Set(1.0, 0.0);
+ this.m_normals[2].Set(0.0, 1.0);
+ this.m_normals[3].Set((-1.0), 0.0);
+ this.m_centroid.SetZero();
+ }
+ b2PolygonShape.AsBox = function (hx, hy) {
+ if (hx === undefined) hx = 0;
+ if (hy === undefined) hy = 0;
+ var polygonShape = new b2PolygonShape();
+ polygonShape.SetAsBox(hx, hy);
+ return polygonShape;
+ }
+ b2PolygonShape.prototype.SetAsOrientedBox = function (hx, hy, center, angle) {
+ if (hx === undefined) hx = 0;
+ if (hy === undefined) hy = 0;
+ if (center === undefined) center = null;
+ if (angle === undefined) angle = 0.0;
+ this.m_vertexCount = 4;
+ this.Reserve(4);
+ this.m_vertices[0].Set((-hx), (-hy));
+ this.m_vertices[1].Set(hx, (-hy));
+ this.m_vertices[2].Set(hx, hy);
+ this.m_vertices[3].Set((-hx), hy);
+ this.m_normals[0].Set(0.0, (-1.0));
+ this.m_normals[1].Set(1.0, 0.0);
+ this.m_normals[2].Set(0.0, 1.0);
+ this.m_normals[3].Set((-1.0), 0.0);
+ this.m_centroid = center;
+ var xf = new b2Transform();
+ xf.position = center;
+ xf.R.Set(angle);
+ for (var i = 0; i < this.m_vertexCount; ++i) {
+ this.m_vertices[i] = b2Math.MulX(xf, this.m_vertices[i]);
+ this.m_normals[i] = b2Math.MulMV(xf.R, this.m_normals[i]);
+ }
+ }
+ b2PolygonShape.AsOrientedBox = function (hx, hy, center, angle) {
+ if (hx === undefined) hx = 0;
+ if (hy === undefined) hy = 0;
+ if (center === undefined) center = null;
+ if (angle === undefined) angle = 0.0;
+ var polygonShape = new b2PolygonShape();
+ polygonShape.SetAsOrientedBox(hx, hy, center, angle);
+ return polygonShape;
+ }
+ b2PolygonShape.prototype.SetAsEdge = function (v1, v2) {
+ this.m_vertexCount = 2;
+ this.Reserve(2);
+ this.m_vertices[0].SetV(v1);
+ this.m_vertices[1].SetV(v2);
+ this.m_centroid.x = 0.5 * (v1.x + v2.x);
+ this.m_centroid.y = 0.5 * (v1.y + v2.y);
+ this.m_normals[0] = b2Math.CrossVF(b2Math.SubtractVV(v2, v1), 1.0);
+ this.m_normals[0].Normalize();
+ this.m_normals[1].x = (-this.m_normals[0].x);
+ this.m_normals[1].y = (-this.m_normals[0].y);
+ }
+ b2PolygonShape.AsEdge = function (v1, v2) {
+ var polygonShape = new b2PolygonShape();
+ polygonShape.SetAsEdge(v1, v2);
+ return polygonShape;
+ }
+ b2PolygonShape.prototype.TestPoint = function (xf, p) {
+ var tVec;
+ var tMat = xf.R;
+ var tX = p.x - xf.position.x;
+ var tY = p.y - xf.position.y;
+ var pLocalX = (tX * tMat.col1.x + tY * tMat.col1.y);
+ var pLocalY = (tX * tMat.col2.x + tY * tMat.col2.y);
+ for (var i = 0; i < this.m_vertexCount; ++i) {
+ tVec = this.m_vertices[i];
+ tX = pLocalX - tVec.x;
+ tY = pLocalY - tVec.y;
+ tVec = this.m_normals[i];
+ var dot = (tVec.x * tX + tVec.y * tY);
+ if (dot > 0.0) {
+ return false;
+ }
+ }
+ return true;
+ }
+ b2PolygonShape.prototype.RayCast = function (output, input, transform) {
+ var lower = 0.0;
+ var upper = input.maxFraction;
+ var tX = 0;
+ var tY = 0;
+ var tMat;
+ var tVec;
+ tX = input.p1.x - transform.position.x;
+ tY = input.p1.y - transform.position.y;
+ tMat = transform.R;
+ var p1X = (tX * tMat.col1.x + tY * tMat.col1.y);
+ var p1Y = (tX * tMat.col2.x + tY * tMat.col2.y);
+ tX = input.p2.x - transform.position.x;
+ tY = input.p2.y - transform.position.y;
+ tMat = transform.R;
+ var p2X = (tX * tMat.col1.x + tY * tMat.col1.y);
+ var p2Y = (tX * tMat.col2.x + tY * tMat.col2.y);
+ var dX = p2X - p1X;
+ var dY = p2Y - p1Y;
+ var index = parseInt((-1));
+ for (var i = 0; i < this.m_vertexCount; ++i) {
+ tVec = this.m_vertices[i];
+ tX = tVec.x - p1X;
+ tY = tVec.y - p1Y;
+ tVec = this.m_normals[i];
+ var numerator = (tVec.x * tX + tVec.y * tY);
+ var denominator = (tVec.x * dX + tVec.y * dY);
+ if (denominator == 0.0) {
+ if (numerator < 0.0) {
+ return false;
+ }
+ }
+ else {
+ if (denominator < 0.0 && numerator < lower * denominator) {
+ lower = numerator / denominator;
+ index = i;
+ }
+ else if (denominator > 0.0 && numerator < upper * denominator) {
+ upper = numerator / denominator;
+ }
+ }
+ if (upper < lower - Number.MIN_VALUE) {
+ return false;
+ }
+ }
+ if (index >= 0) {
+ output.fraction = lower;
+ tMat = transform.R;
+ tVec = this.m_normals[index];
+ output.normal.x = (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ output.normal.y = (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ return true;
+ }
+ return false;
+ }
+ b2PolygonShape.prototype.ComputeAABB = function (aabb, xf) {
+ var tMat = xf.R;
+ var tVec = this.m_vertices[0];
+ var lowerX = xf.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ var lowerY = xf.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ var upperX = lowerX;
+ var upperY = lowerY;
+ for (var i = 1; i < this.m_vertexCount; ++i) {
+ tVec = this.m_vertices[i];
+ var vX = xf.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ var vY = xf.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ lowerX = lowerX < vX ? lowerX : vX;
+ lowerY = lowerY < vY ? lowerY : vY;
+ upperX = upperX > vX ? upperX : vX;
+ upperY = upperY > vY ? upperY : vY;
+ }
+ aabb.lowerBound.x = lowerX - this.m_radius;
+ aabb.lowerBound.y = lowerY - this.m_radius;
+ aabb.upperBound.x = upperX + this.m_radius;
+ aabb.upperBound.y = upperY + this.m_radius;
+ }
+ b2PolygonShape.prototype.ComputeMass = function (massData, density) {
+ if (density === undefined) density = 0;
+ if (this.m_vertexCount == 2) {
+ massData.center.x = 0.5 * (this.m_vertices[0].x + this.m_vertices[1].x);
+ massData.center.y = 0.5 * (this.m_vertices[0].y + this.m_vertices[1].y);
+ massData.mass = 0.0;
+ massData.I = 0.0;
+ return;
+ }
+ var centerX = 0.0;
+ var centerY = 0.0;
+ var area = 0.0;
+ var I = 0.0;
+ var p1X = 0.0;
+ var p1Y = 0.0;
+ var k_inv3 = 1.0 / 3.0;
+ for (var i = 0; i < this.m_vertexCount; ++i) {
+ var p2 = this.m_vertices[i];
+ var p3 = i + 1 < this.m_vertexCount ? this.m_vertices[parseInt(i + 1)] : this.m_vertices[0];
+ var e1X = p2.x - p1X;
+ var e1Y = p2.y - p1Y;
+ var e2X = p3.x - p1X;
+ var e2Y = p3.y - p1Y;
+ var D = e1X * e2Y - e1Y * e2X;
+ var triangleArea = 0.5 * D;area += triangleArea;
+ centerX += triangleArea * k_inv3 * (p1X + p2.x + p3.x);
+ centerY += triangleArea * k_inv3 * (p1Y + p2.y + p3.y);
+ var px = p1X;
+ var py = p1Y;
+ var ex1 = e1X;
+ var ey1 = e1Y;
+ var ex2 = e2X;
+ var ey2 = e2Y;
+ var intx2 = k_inv3 * (0.25 * (ex1 * ex1 + ex2 * ex1 + ex2 * ex2) + (px * ex1 + px * ex2)) + 0.5 * px * px;
+ var inty2 = k_inv3 * (0.25 * (ey1 * ey1 + ey2 * ey1 + ey2 * ey2) + (py * ey1 + py * ey2)) + 0.5 * py * py;I += D * (intx2 + inty2);
+ }
+ massData.mass = density * area;
+ centerX *= 1.0 / area;
+ centerY *= 1.0 / area;
+ massData.center.Set(centerX, centerY);
+ massData.I = density * I;
+ }
+ b2PolygonShape.prototype.ComputeSubmergedArea = function (normal, offset, xf, c) {
+ if (offset === undefined) offset = 0;
+ var normalL = b2Math.MulTMV(xf.R, normal);
+ var offsetL = offset - b2Math.Dot(normal, xf.position);
+ var depths = new Vector_a2j_Number();
+ var diveCount = 0;
+ var intoIndex = parseInt((-1));
+ var outoIndex = parseInt((-1));
+ var lastSubmerged = false;
+ var i = 0;
+ for (i = 0;
+ i < this.m_vertexCount; ++i) {
+ depths[i] = b2Math.Dot(normalL, this.m_vertices[i]) - offsetL;
+ var isSubmerged = depths[i] < (-Number.MIN_VALUE);
+ if (i > 0) {
+ if (isSubmerged) {
+ if (!lastSubmerged) {
+ intoIndex = i - 1;
+ diveCount++;
+ }
+ }
+ else {
+ if (lastSubmerged) {
+ outoIndex = i - 1;
+ diveCount++;
+ }
+ }
+ }
+ lastSubmerged = isSubmerged;
+ }
+ switch (diveCount) {
+ case 0:
+ if (lastSubmerged) {
+ var md = new b2MassData();
+ this.ComputeMass(md, 1);
+ c.SetV(b2Math.MulX(xf, md.center));
+ return md.mass;
+ }
+ else {
+ return 0;
+ }
+ break;
+ case 1:
+ if (intoIndex == (-1)) {
+ intoIndex = this.m_vertexCount - 1;
+ }
+ else {
+ outoIndex = this.m_vertexCount - 1;
+ }
+ break;
+ }
+ var intoIndex2 = parseInt((intoIndex + 1) % this.m_vertexCount);
+ var outoIndex2 = parseInt((outoIndex + 1) % this.m_vertexCount);
+ var intoLamdda = (0 - depths[intoIndex]) / (depths[intoIndex2] - depths[intoIndex]);
+ var outoLamdda = (0 - depths[outoIndex]) / (depths[outoIndex2] - depths[outoIndex]);
+ var intoVec = new b2Vec2(this.m_vertices[intoIndex].x * (1 - intoLamdda) + this.m_vertices[intoIndex2].x * intoLamdda, this.m_vertices[intoIndex].y * (1 - intoLamdda) + this.m_vertices[intoIndex2].y * intoLamdda);
+ var outoVec = new b2Vec2(this.m_vertices[outoIndex].x * (1 - outoLamdda) + this.m_vertices[outoIndex2].x * outoLamdda, this.m_vertices[outoIndex].y * (1 - outoLamdda) + this.m_vertices[outoIndex2].y * outoLamdda);
+ var area = 0;
+ var center = new b2Vec2();
+ var p2 = this.m_vertices[intoIndex2];
+ var p3;
+ i = intoIndex2;
+ while (i != outoIndex2) {
+ i = (i + 1) % this.m_vertexCount;
+ if (i == outoIndex2) p3 = outoVec;
+ else p3 = this.m_vertices[i];
+ var triangleArea = 0.5 * ((p2.x - intoVec.x) * (p3.y - intoVec.y) - (p2.y - intoVec.y) * (p3.x - intoVec.x));
+ area += triangleArea;
+ center.x += triangleArea * (intoVec.x + p2.x + p3.x) / 3;
+ center.y += triangleArea * (intoVec.y + p2.y + p3.y) / 3;
+ p2 = p3;
+ }
+ center.Multiply(1 / area);
+ c.SetV(b2Math.MulX(xf, center));
+ return area;
+ }
+ b2PolygonShape.prototype.GetVertexCount = function () {
+ return this.m_vertexCount;
+ }
+ b2PolygonShape.prototype.GetVertices = function () {
+ return this.m_vertices;
+ }
+ b2PolygonShape.prototype.GetNormals = function () {
+ return this.m_normals;
+ }
+ b2PolygonShape.prototype.GetSupport = function (d) {
+ var bestIndex = 0;
+ var bestValue = this.m_vertices[0].x * d.x + this.m_vertices[0].y * d.y;
+ for (var i = 1; i < this.m_vertexCount; ++i) {
+ var value = this.m_vertices[i].x * d.x + this.m_vertices[i].y * d.y;
+ if (value > bestValue) {
+ bestIndex = i;
+ bestValue = value;
+ }
+ }
+ return bestIndex;
+ }
+ b2PolygonShape.prototype.GetSupportVertex = function (d) {
+ var bestIndex = 0;
+ var bestValue = this.m_vertices[0].x * d.x + this.m_vertices[0].y * d.y;
+ for (var i = 1; i < this.m_vertexCount; ++i) {
+ var value = this.m_vertices[i].x * d.x + this.m_vertices[i].y * d.y;
+ if (value > bestValue) {
+ bestIndex = i;
+ bestValue = value;
+ }
+ }
+ return this.m_vertices[bestIndex];
+ }
+ b2PolygonShape.prototype.Validate = function () {
+ return false;
+ }
+ b2PolygonShape.prototype.b2PolygonShape = function () {
+ this.__super.b2Shape.call(this);
+ this.m_type = b2Shape.e_polygonShape;
+ this.m_centroid = new b2Vec2();
+ this.m_vertices = new Vector();
+ this.m_normals = new Vector();
+ }
+ b2PolygonShape.prototype.Reserve = function (count) {
+ if (count === undefined) count = 0;
+ for (var i = parseInt(this.m_vertices.length); i < count; i++) {
+ this.m_vertices[i] = new b2Vec2();
+ this.m_normals[i] = new b2Vec2();
+ }
+ }
+ b2PolygonShape.ComputeCentroid = function (vs, count) {
+ if (count === undefined) count = 0;
+ var c = new b2Vec2();
+ var area = 0.0;
+ var p1X = 0.0;
+ var p1Y = 0.0;
+ var inv3 = 1.0 / 3.0;
+ for (var i = 0; i < count; ++i) {
+ var p2 = vs[i];
+ var p3 = i + 1 < count ? vs[parseInt(i + 1)] : vs[0];
+ var e1X = p2.x - p1X;
+ var e1Y = p2.y - p1Y;
+ var e2X = p3.x - p1X;
+ var e2Y = p3.y - p1Y;
+ var D = (e1X * e2Y - e1Y * e2X);
+ var triangleArea = 0.5 * D;area += triangleArea;
+ c.x += triangleArea * inv3 * (p1X + p2.x + p3.x);
+ c.y += triangleArea * inv3 * (p1Y + p2.y + p3.y);
+ }
+ c.x *= 1.0 / area;
+ c.y *= 1.0 / area;
+ return c;
+ }
+ b2PolygonShape.ComputeOBB = function (obb, vs, count) {
+ if (count === undefined) count = 0;
+ var i = 0;
+ var p = new Vector(count + 1);
+ for (i = 0;
+ i < count; ++i) {
+ p[i] = vs[i];
+ }
+ p[count] = p[0];
+ var minArea = Number.MAX_VALUE;
+ for (i = 1;
+ i <= count; ++i) {
+ var root = p[parseInt(i - 1)];
+ var uxX = p[i].x - root.x;
+ var uxY = p[i].y - root.y;
+ var length = Math.sqrt(uxX * uxX + uxY * uxY);
+ uxX /= length;
+ uxY /= length;
+ var uyX = (-uxY);
+ var uyY = uxX;
+ var lowerX = Number.MAX_VALUE;
+ var lowerY = Number.MAX_VALUE;
+ var upperX = (-Number.MAX_VALUE);
+ var upperY = (-Number.MAX_VALUE);
+ for (var j = 0; j < count; ++j) {
+ var dX = p[j].x - root.x;
+ var dY = p[j].y - root.y;
+ var rX = (uxX * dX + uxY * dY);
+ var rY = (uyX * dX + uyY * dY);
+ if (rX < lowerX) lowerX = rX;
+ if (rY < lowerY) lowerY = rY;
+ if (rX > upperX) upperX = rX;
+ if (rY > upperY) upperY = rY;
+ }
+ var area = (upperX - lowerX) * (upperY - lowerY);
+ if (area < 0.95 * minArea) {
+ minArea = area;
+ obb.R.col1.x = uxX;
+ obb.R.col1.y = uxY;
+ obb.R.col2.x = uyX;
+ obb.R.col2.y = uyY;
+ var centerX = 0.5 * (lowerX + upperX);
+ var centerY = 0.5 * (lowerY + upperY);
+ var tMat = obb.R;
+ obb.center.x = root.x + (tMat.col1.x * centerX + tMat.col2.x * centerY);
+ obb.center.y = root.y + (tMat.col1.y * centerX + tMat.col2.y * centerY);
+ obb.extents.x = 0.5 * (upperX - lowerX);
+ obb.extents.y = 0.5 * (upperY - lowerY);
+ }
+ }
+ }
+ Box2D.postDefs.push(function () {
+ Box2D.Collision.Shapes.b2PolygonShape.s_mat = new b2Mat22();
+ });
+ b2Shape.b2Shape = function () {};
+ b2Shape.prototype.Copy = function () {
+ return null;
+ }
+ b2Shape.prototype.Set = function (other) {
+ this.m_radius = other.m_radius;
+ }
+ b2Shape.prototype.GetType = function () {
+ return this.m_type;
+ }
+ b2Shape.prototype.TestPoint = function (xf, p) {
+ return false;
+ }
+ b2Shape.prototype.RayCast = function (output, input, transform) {
+ return false;
+ }
+ b2Shape.prototype.ComputeAABB = function (aabb, xf) {}
+ b2Shape.prototype.ComputeMass = function (massData, density) {
+ if (density === undefined) density = 0;
+ }
+ b2Shape.prototype.ComputeSubmergedArea = function (normal, offset, xf, c) {
+ if (offset === undefined) offset = 0;
+ return 0;
+ }
+ b2Shape.TestOverlap = function (shape1, transform1, shape2, transform2) {
+ var input = new b2DistanceInput();
+ input.proxyA = new b2DistanceProxy();
+ input.proxyA.Set(shape1);
+ input.proxyB = new b2DistanceProxy();
+ input.proxyB.Set(shape2);
+ input.transformA = transform1;
+ input.transformB = transform2;
+ input.useRadii = true;
+ var simplexCache = new b2SimplexCache();
+ simplexCache.count = 0;
+ var output = new b2DistanceOutput();
+ b2Distance.Distance(output, simplexCache, input);
+ return output.distance < 10.0 * Number.MIN_VALUE;
+ }
+ b2Shape.prototype.b2Shape = function () {
+ this.m_type = b2Shape.e_unknownShape;
+ this.m_radius = b2Settings.b2_linearSlop;
+ }
+ Box2D.postDefs.push(function () {
+ Box2D.Collision.Shapes.b2Shape.e_unknownShape = parseInt((-1));
+ Box2D.Collision.Shapes.b2Shape.e_circleShape = 0;
+ Box2D.Collision.Shapes.b2Shape.e_polygonShape = 1;
+ Box2D.Collision.Shapes.b2Shape.e_edgeShape = 2;
+ Box2D.Collision.Shapes.b2Shape.e_shapeTypeCount = 3;
+ Box2D.Collision.Shapes.b2Shape.e_hitCollide = 1;
+ Box2D.Collision.Shapes.b2Shape.e_missCollide = 0;
+ Box2D.Collision.Shapes.b2Shape.e_startsInsideCollide = parseInt((-1));
+ });
+})();
+(function () {
+ var b2Color = Box2D.Common.b2Color,
+ b2internal = Box2D.Common.b2internal,
+ b2Settings = Box2D.Common.b2Settings,
+ b2Mat22 = Box2D.Common.Math.b2Mat22,
+ b2Mat33 = Box2D.Common.Math.b2Mat33,
+ b2Math = Box2D.Common.Math.b2Math,
+ b2Sweep = Box2D.Common.Math.b2Sweep,
+ b2Transform = Box2D.Common.Math.b2Transform,
+ b2Vec2 = Box2D.Common.Math.b2Vec2,
+ b2Vec3 = Box2D.Common.Math.b2Vec3;
+
+ b2Color.b2Color = function () {
+ this._r = 0;
+ this._g = 0;
+ this._b = 0;
+ };
+ b2Color.prototype.b2Color = function (rr, gg, bb) {
+ if (rr === undefined) rr = 0;
+ if (gg === undefined) gg = 0;
+ if (bb === undefined) bb = 0;
+ this._r = Box2D.parseUInt(255 * b2Math.Clamp(rr, 0.0, 1.0));
+ this._g = Box2D.parseUInt(255 * b2Math.Clamp(gg, 0.0, 1.0));
+ this._b = Box2D.parseUInt(255 * b2Math.Clamp(bb, 0.0, 1.0));
+ }
+ b2Color.prototype.Set = function (rr, gg, bb) {
+ if (rr === undefined) rr = 0;
+ if (gg === undefined) gg = 0;
+ if (bb === undefined) bb = 0;
+ this._r = Box2D.parseUInt(255 * b2Math.Clamp(rr, 0.0, 1.0));
+ this._g = Box2D.parseUInt(255 * b2Math.Clamp(gg, 0.0, 1.0));
+ this._b = Box2D.parseUInt(255 * b2Math.Clamp(bb, 0.0, 1.0));
+ }
+ Object.defineProperty(b2Color.prototype, 'r', {
+ enumerable: false,
+ configurable: true,
+ set: function (rr) {
+ if (rr === undefined) rr = 0;
+ this._r = Box2D.parseUInt(255 * b2Math.Clamp(rr, 0.0, 1.0));
+ }
+ });
+ Object.defineProperty(b2Color.prototype, 'g', {
+ enumerable: false,
+ configurable: true,
+ set: function (gg) {
+ if (gg === undefined) gg = 0;
+ this._g = Box2D.parseUInt(255 * b2Math.Clamp(gg, 0.0, 1.0));
+ }
+ });
+ Object.defineProperty(b2Color.prototype, 'b', {
+ enumerable: false,
+ configurable: true,
+ set: function (bb) {
+ if (bb === undefined) bb = 0;
+ this._b = Box2D.parseUInt(255 * b2Math.Clamp(bb, 0.0, 1.0));
+ }
+ });
+ Object.defineProperty(b2Color.prototype, 'color', {
+ enumerable: false,
+ configurable: true,
+ get: function () {
+ return (this._r << 16) | (this._g << 8) | (this._b);
+ }
+ });
+ b2Settings.b2Settings = function () {};
+ b2Settings.b2MixFriction = function (friction1, friction2) {
+ if (friction1 === undefined) friction1 = 0;
+ if (friction2 === undefined) friction2 = 0;
+ return Math.sqrt(friction1 * friction2);
+ }
+ b2Settings.b2MixRestitution = function (restitution1, restitution2) {
+ if (restitution1 === undefined) restitution1 = 0;
+ if (restitution2 === undefined) restitution2 = 0;
+ return restitution1 > restitution2 ? restitution1 : restitution2;
+ }
+ b2Settings.b2Assert = function (a) {
+ if (!a) {
+ throw "Assertion Failed";
+ }
+ }
+ Box2D.postDefs.push(function () {
+ Box2D.Common.b2Settings.VERSION = "2.1alpha";
+ Box2D.Common.b2Settings.USHRT_MAX = 0x0000ffff;
+ Box2D.Common.b2Settings.b2_pi = Math.PI;
+ Box2D.Common.b2Settings.b2_maxManifoldPoints = 2;
+ Box2D.Common.b2Settings.b2_aabbExtension = 0.1;
+ Box2D.Common.b2Settings.b2_aabbMultiplier = 2.0;
+ Box2D.Common.b2Settings.b2_polygonRadius = 2.0 * b2Settings.b2_linearSlop;
+ Box2D.Common.b2Settings.b2_linearSlop = 0.005;
+ Box2D.Common.b2Settings.b2_angularSlop = 2.0 / 180.0 * b2Settings.b2_pi;
+ Box2D.Common.b2Settings.b2_toiSlop = 8.0 * b2Settings.b2_linearSlop;
+ Box2D.Common.b2Settings.b2_maxTOIContactsPerIsland = 32;
+ Box2D.Common.b2Settings.b2_maxTOIJointsPerIsland = 32;
+ Box2D.Common.b2Settings.b2_velocityThreshold = 1.0;
+ Box2D.Common.b2Settings.b2_maxLinearCorrection = 0.2;
+ Box2D.Common.b2Settings.b2_maxAngularCorrection = 8.0 / 180.0 * b2Settings.b2_pi;
+ Box2D.Common.b2Settings.b2_maxTranslation = 2.0;
+ Box2D.Common.b2Settings.b2_maxTranslationSquared = b2Settings.b2_maxTranslation * b2Settings.b2_maxTranslation;
+ Box2D.Common.b2Settings.b2_maxRotation = 0.5 * b2Settings.b2_pi;
+ Box2D.Common.b2Settings.b2_maxRotationSquared = b2Settings.b2_maxRotation * b2Settings.b2_maxRotation;
+ Box2D.Common.b2Settings.b2_contactBaumgarte = 0.2;
+ Box2D.Common.b2Settings.b2_timeToSleep = 0.5;
+ Box2D.Common.b2Settings.b2_linearSleepTolerance = 0.01;
+ Box2D.Common.b2Settings.b2_angularSleepTolerance = 2.0 / 180.0 * b2Settings.b2_pi;
+ });
+})();
+(function () {
+ var b2AABB = Box2D.Collision.b2AABB,
+ b2Color = Box2D.Common.b2Color,
+ b2internal = Box2D.Common.b2internal,
+ b2Settings = Box2D.Common.b2Settings,
+ b2Mat22 = Box2D.Common.Math.b2Mat22,
+ b2Mat33 = Box2D.Common.Math.b2Mat33,
+ b2Math = Box2D.Common.Math.b2Math,
+ b2Sweep = Box2D.Common.Math.b2Sweep,
+ b2Transform = Box2D.Common.Math.b2Transform,
+ b2Vec2 = Box2D.Common.Math.b2Vec2,
+ b2Vec3 = Box2D.Common.Math.b2Vec3;
+
+ b2Mat22.b2Mat22 = function () {
+ this.col1 = new b2Vec2();
+ this.col2 = new b2Vec2();
+ };
+ b2Mat22.prototype.b2Mat22 = function () {
+ this.SetIdentity();
+ }
+ b2Mat22.FromAngle = function (angle) {
+ if (angle === undefined) angle = 0;
+ var mat = new b2Mat22();
+ mat.Set(angle);
+ return mat;
+ }
+ b2Mat22.FromVV = function (c1, c2) {
+ var mat = new b2Mat22();
+ mat.SetVV(c1, c2);
+ return mat;
+ }
+ b2Mat22.prototype.Set = function (angle) {
+ if (angle === undefined) angle = 0;
+ var c = Math.cos(angle);
+ var s = Math.sin(angle);
+ this.col1.x = c;
+ this.col2.x = (-s);
+ this.col1.y = s;
+ this.col2.y = c;
+ }
+ b2Mat22.prototype.SetVV = function (c1, c2) {
+ this.col1.SetV(c1);
+ this.col2.SetV(c2);
+ }
+ b2Mat22.prototype.Copy = function () {
+ var mat = new b2Mat22();
+ mat.SetM(this);
+ return mat;
+ }
+ b2Mat22.prototype.SetM = function (m) {
+ this.col1.SetV(m.col1);
+ this.col2.SetV(m.col2);
+ }
+ b2Mat22.prototype.AddM = function (m) {
+ this.col1.x += m.col1.x;
+ this.col1.y += m.col1.y;
+ this.col2.x += m.col2.x;
+ this.col2.y += m.col2.y;
+ }
+ b2Mat22.prototype.SetIdentity = function () {
+ this.col1.x = 1.0;
+ this.col2.x = 0.0;
+ this.col1.y = 0.0;
+ this.col2.y = 1.0;
+ }
+ b2Mat22.prototype.SetZero = function () {
+ this.col1.x = 0.0;
+ this.col2.x = 0.0;
+ this.col1.y = 0.0;
+ this.col2.y = 0.0;
+ }
+ b2Mat22.prototype.GetAngle = function () {
+ return Math.atan2(this.col1.y, this.col1.x);
+ }
+ b2Mat22.prototype.GetInverse = function (out) {
+ var a = this.col1.x;
+ var b = this.col2.x;
+ var c = this.col1.y;
+ var d = this.col2.y;
+ var det = a * d - b * c;
+ if (det != 0.0) {
+ det = 1.0 / det;
+ }
+ out.col1.x = det * d;
+ out.col2.x = (-det * b);
+ out.col1.y = (-det * c);
+ out.col2.y = det * a;
+ return out;
+ }
+ b2Mat22.prototype.Solve = function (out, bX, bY) {
+ if (bX === undefined) bX = 0;
+ if (bY === undefined) bY = 0;
+ var a11 = this.col1.x;
+ var a12 = this.col2.x;
+ var a21 = this.col1.y;
+ var a22 = this.col2.y;
+ var det = a11 * a22 - a12 * a21;
+ if (det != 0.0) {
+ det = 1.0 / det;
+ }
+ out.x = det * (a22 * bX - a12 * bY);
+ out.y = det * (a11 * bY - a21 * bX);
+ return out;
+ }
+ b2Mat22.prototype.Abs = function () {
+ this.col1.Abs();
+ this.col2.Abs();
+ }
+ b2Mat33.b2Mat33 = function () {
+ this.col1 = new b2Vec3();
+ this.col2 = new b2Vec3();
+ this.col3 = new b2Vec3();
+ };
+ b2Mat33.prototype.b2Mat33 = function (c1, c2, c3) {
+ if (c1 === undefined) c1 = null;
+ if (c2 === undefined) c2 = null;
+ if (c3 === undefined) c3 = null;
+ if (!c1 && !c2 && !c3) {
+ this.col1.SetZero();
+ this.col2.SetZero();
+ this.col3.SetZero();
+ }
+ else {
+ this.col1.SetV(c1);
+ this.col2.SetV(c2);
+ this.col3.SetV(c3);
+ }
+ }
+ b2Mat33.prototype.SetVVV = function (c1, c2, c3) {
+ this.col1.SetV(c1);
+ this.col2.SetV(c2);
+ this.col3.SetV(c3);
+ }
+ b2Mat33.prototype.Copy = function () {
+ return new b2Mat33(this.col1, this.col2, this.col3);
+ }
+ b2Mat33.prototype.SetM = function (m) {
+ this.col1.SetV(m.col1);
+ this.col2.SetV(m.col2);
+ this.col3.SetV(m.col3);
+ }
+ b2Mat33.prototype.AddM = function (m) {
+ this.col1.x += m.col1.x;
+ this.col1.y += m.col1.y;
+ this.col1.z += m.col1.z;
+ this.col2.x += m.col2.x;
+ this.col2.y += m.col2.y;
+ this.col2.z += m.col2.z;
+ this.col3.x += m.col3.x;
+ this.col3.y += m.col3.y;
+ this.col3.z += m.col3.z;
+ }
+ b2Mat33.prototype.SetIdentity = function () {
+ this.col1.x = 1.0;
+ this.col2.x = 0.0;
+ this.col3.x = 0.0;
+ this.col1.y = 0.0;
+ this.col2.y = 1.0;
+ this.col3.y = 0.0;
+ this.col1.z = 0.0;
+ this.col2.z = 0.0;
+ this.col3.z = 1.0;
+ }
+ b2Mat33.prototype.SetZero = function () {
+ this.col1.x = 0.0;
+ this.col2.x = 0.0;
+ this.col3.x = 0.0;
+ this.col1.y = 0.0;
+ this.col2.y = 0.0;
+ this.col3.y = 0.0;
+ this.col1.z = 0.0;
+ this.col2.z = 0.0;
+ this.col3.z = 0.0;
+ }
+ b2Mat33.prototype.Solve22 = function (out, bX, bY) {
+ if (bX === undefined) bX = 0;
+ if (bY === undefined) bY = 0;
+ var a11 = this.col1.x;
+ var a12 = this.col2.x;
+ var a21 = this.col1.y;
+ var a22 = this.col2.y;
+ var det = a11 * a22 - a12 * a21;
+ if (det != 0.0) {
+ det = 1.0 / det;
+ }
+ out.x = det * (a22 * bX - a12 * bY);
+ out.y = det * (a11 * bY - a21 * bX);
+ return out;
+ }
+ b2Mat33.prototype.Solve33 = function (out, bX, bY, bZ) {
+ if (bX === undefined) bX = 0;
+ if (bY === undefined) bY = 0;
+ if (bZ === undefined) bZ = 0;
+ var a11 = this.col1.x;
+ var a21 = this.col1.y;
+ var a31 = this.col1.z;
+ var a12 = this.col2.x;
+ var a22 = this.col2.y;
+ var a32 = this.col2.z;
+ var a13 = this.col3.x;
+ var a23 = this.col3.y;
+ var a33 = this.col3.z;
+ var det = a11 * (a22 * a33 - a32 * a23) + a21 * (a32 * a13 - a12 * a33) + a31 * (a12 * a23 - a22 * a13);
+ if (det != 0.0) {
+ det = 1.0 / det;
+ }
+ out.x = det * (bX * (a22 * a33 - a32 * a23) + bY * (a32 * a13 - a12 * a33) + bZ * (a12 * a23 - a22 * a13));
+ out.y = det * (a11 * (bY * a33 - bZ * a23) + a21 * (bZ * a13 - bX * a33) + a31 * (bX * a23 - bY * a13));
+ out.z = det * (a11 * (a22 * bZ - a32 * bY) + a21 * (a32 * bX - a12 * bZ) + a31 * (a12 * bY - a22 * bX));
+ return out;
+ }
+ b2Math.b2Math = function () {};
+ b2Math.IsValid = function (x) {
+ if (x === undefined) x = 0;
+ return isFinite(x);
+ }
+ b2Math.Dot = function (a, b) {
+ return a.x * b.x + a.y * b.y;
+ }
+ b2Math.CrossVV = function (a, b) {
+ return a.x * b.y - a.y * b.x;
+ }
+ b2Math.CrossVF = function (a, s) {
+ if (s === undefined) s = 0;
+ var v = new b2Vec2(s * a.y, (-s * a.x));
+ return v;
+ }
+ b2Math.CrossFV = function (s, a) {
+ if (s === undefined) s = 0;
+ var v = new b2Vec2((-s * a.y), s * a.x);
+ return v;
+ }
+ b2Math.MulMV = function (A, v) {
+ var u = new b2Vec2(A.col1.x * v.x + A.col2.x * v.y, A.col1.y * v.x + A.col2.y * v.y);
+ return u;
+ }
+ b2Math.MulTMV = function (A, v) {
+ var u = new b2Vec2(b2Math.Dot(v, A.col1), b2Math.Dot(v, A.col2));
+ return u;
+ }
+ b2Math.MulX = function (T, v) {
+ var a = b2Math.MulMV(T.R, v);
+ a.x += T.position.x;
+ a.y += T.position.y;
+ return a;
+ }
+ b2Math.MulXT = function (T, v) {
+ var a = b2Math.SubtractVV(v, T.position);
+ var tX = (a.x * T.R.col1.x + a.y * T.R.col1.y);
+ a.y = (a.x * T.R.col2.x + a.y * T.R.col2.y);
+ a.x = tX;
+ return a;
+ }
+ b2Math.AddVV = function (a, b) {
+ var v = new b2Vec2(a.x + b.x, a.y + b.y);
+ return v;
+ }
+ b2Math.SubtractVV = function (a, b) {
+ var v = new b2Vec2(a.x - b.x, a.y - b.y);
+ return v;
+ }
+ b2Math.Distance = function (a, b) {
+ var cX = a.x - b.x;
+ var cY = a.y - b.y;
+ return Math.sqrt(cX * cX + cY * cY);
+ }
+ b2Math.DistanceSquared = function (a, b) {
+ var cX = a.x - b.x;
+ var cY = a.y - b.y;
+ return (cX * cX + cY * cY);
+ }
+ b2Math.MulFV = function (s, a) {
+ if (s === undefined) s = 0;
+ var v = new b2Vec2(s * a.x, s * a.y);
+ return v;
+ }
+ b2Math.AddMM = function (A, B) {
+ var C = b2Mat22.FromVV(b2Math.AddVV(A.col1, B.col1), b2Math.AddVV(A.col2, B.col2));
+ return C;
+ }
+ b2Math.MulMM = function (A, B) {
+ var C = b2Mat22.FromVV(b2Math.MulMV(A, B.col1), b2Math.MulMV(A, B.col2));
+ return C;
+ }
+ b2Math.MulTMM = function (A, B) {
+ var c1 = new b2Vec2(b2Math.Dot(A.col1, B.col1), b2Math.Dot(A.col2, B.col1));
+ var c2 = new b2Vec2(b2Math.Dot(A.col1, B.col2), b2Math.Dot(A.col2, B.col2));
+ var C = b2Mat22.FromVV(c1, c2);
+ return C;
+ }
+ b2Math.Abs = function (a) {
+ if (a === undefined) a = 0;
+ return a > 0.0 ? a : (-a);
+ }
+ b2Math.AbsV = function (a) {
+ var b = new b2Vec2(b2Math.Abs(a.x), b2Math.Abs(a.y));
+ return b;
+ }
+ b2Math.AbsM = function (A) {
+ var B = b2Mat22.FromVV(b2Math.AbsV(A.col1), b2Math.AbsV(A.col2));
+ return B;
+ }
+ b2Math.Min = function (a, b) {
+ if (a === undefined) a = 0;
+ if (b === undefined) b = 0;
+ return a < b ? a : b;
+ }
+ b2Math.MinV = function (a, b) {
+ var c = new b2Vec2(b2Math.Min(a.x, b.x), b2Math.Min(a.y, b.y));
+ return c;
+ }
+ b2Math.Max = function (a, b) {
+ if (a === undefined) a = 0;
+ if (b === undefined) b = 0;
+ return a > b ? a : b;
+ }
+ b2Math.MaxV = function (a, b) {
+ var c = new b2Vec2(b2Math.Max(a.x, b.x), b2Math.Max(a.y, b.y));
+ return c;
+ }
+ b2Math.Clamp = function (a, low, high) {
+ if (a === undefined) a = 0;
+ if (low === undefined) low = 0;
+ if (high === undefined) high = 0;
+ return a < low ? low : a > high ? high : a;
+ }
+ b2Math.ClampV = function (a, low, high) {
+ return b2Math.MaxV(low, b2Math.MinV(a, high));
+ }
+ b2Math.Swap = function (a, b) {
+ var tmp = a[0];
+ a[0] = b[0];
+ b[0] = tmp;
+ }
+ b2Math.Random = function () {
+ return Math.random() * 2 - 1;
+ }
+ b2Math.RandomRange = function (lo, hi) {
+ if (lo === undefined) lo = 0;
+ if (hi === undefined) hi = 0;
+ var r = Math.random();
+ r = (hi - lo) * r + lo;
+ return r;
+ }
+ b2Math.NextPowerOfTwo = function (x) {
+ if (x === undefined) x = 0;
+ x |= (x >> 1) & 0x7FFFFFFF;
+ x |= (x >> 2) & 0x3FFFFFFF;
+ x |= (x >> 4) & 0x0FFFFFFF;
+ x |= (x >> 8) & 0x00FFFFFF;
+ x |= (x >> 16) & 0x0000FFFF;
+ return x + 1;
+ }
+ b2Math.IsPowerOfTwo = function (x) {
+ if (x === undefined) x = 0;
+ var result = x > 0 && (x & (x - 1)) == 0;
+ return result;
+ }
+ Box2D.postDefs.push(function () {
+ Box2D.Common.Math.b2Math.b2Vec2_zero = new b2Vec2(0.0, 0.0);
+ Box2D.Common.Math.b2Math.b2Mat22_identity = b2Mat22.FromVV(new b2Vec2(1.0, 0.0), new b2Vec2(0.0, 1.0));
+ Box2D.Common.Math.b2Math.b2Transform_identity = new b2Transform(b2Math.b2Vec2_zero, b2Math.b2Mat22_identity);
+ });
+ b2Sweep.b2Sweep = function () {
+ this.localCenter = new b2Vec2();
+ this.c0 = new b2Vec2;
+ this.c = new b2Vec2();
+ };
+ b2Sweep.prototype.Set = function (other) {
+ this.localCenter.SetV(other.localCenter);
+ this.c0.SetV(other.c0);
+ this.c.SetV(other.c);
+ this.a0 = other.a0;
+ this.a = other.a;
+ this.t0 = other.t0;
+ }
+ b2Sweep.prototype.Copy = function () {
+ var copy = new b2Sweep();
+ copy.localCenter.SetV(this.localCenter);
+ copy.c0.SetV(this.c0);
+ copy.c.SetV(this.c);
+ copy.a0 = this.a0;
+ copy.a = this.a;
+ copy.t0 = this.t0;
+ return copy;
+ }
+ b2Sweep.prototype.GetTransform = function (xf, alpha) {
+ if (alpha === undefined) alpha = 0;
+ xf.position.x = (1.0 - alpha) * this.c0.x + alpha * this.c.x;
+ xf.position.y = (1.0 - alpha) * this.c0.y + alpha * this.c.y;
+ var angle = (1.0 - alpha) * this.a0 + alpha * this.a;
+ xf.R.Set(angle);
+ var tMat = xf.R;
+ xf.position.x -= (tMat.col1.x * this.localCenter.x + tMat.col2.x * this.localCenter.y);
+ xf.position.y -= (tMat.col1.y * this.localCenter.x + tMat.col2.y * this.localCenter.y);
+ }
+ b2Sweep.prototype.Advance = function (t) {
+ if (t === undefined) t = 0;
+ if (this.t0 < t && 1.0 - this.t0 > Number.MIN_VALUE) {
+ var alpha = (t - this.t0) / (1.0 - this.t0);
+ this.c0.x = (1.0 - alpha) * this.c0.x + alpha * this.c.x;
+ this.c0.y = (1.0 - alpha) * this.c0.y + alpha * this.c.y;
+ this.a0 = (1.0 - alpha) * this.a0 + alpha * this.a;
+ this.t0 = t;
+ }
+ }
+ b2Transform.b2Transform = function () {
+ this.position = new b2Vec2;
+ this.R = new b2Mat22();
+ };
+ b2Transform.prototype.b2Transform = function (pos, r) {
+ if (pos === undefined) pos = null;
+ if (r === undefined) r = null;
+ if (pos) {
+ this.position.SetV(pos);
+ this.R.SetM(r);
+ }
+ }
+ b2Transform.prototype.Initialize = function (pos, r) {
+ this.position.SetV(pos);
+ this.R.SetM(r);
+ }
+ b2Transform.prototype.SetIdentity = function () {
+ this.position.SetZero();
+ this.R.SetIdentity();
+ }
+ b2Transform.prototype.Set = function (x) {
+ this.position.SetV(x.position);
+ this.R.SetM(x.R);
+ }
+ b2Transform.prototype.GetAngle = function () {
+ return Math.atan2(this.R.col1.y, this.R.col1.x);
+ }
+ b2Vec2.b2Vec2 = function () {};
+ b2Vec2.prototype.b2Vec2 = function (x_, y_) {
+ if (x_ === undefined) x_ = 0;
+ if (y_ === undefined) y_ = 0;
+ this.x = x_;
+ this.y = y_;
+ }
+ b2Vec2.prototype.SetZero = function () {
+ this.x = 0.0;
+ this.y = 0.0;
+ }
+ b2Vec2.prototype.Set = function (x_, y_) {
+ if (x_ === undefined) x_ = 0;
+ if (y_ === undefined) y_ = 0;
+ this.x = x_;
+ this.y = y_;
+ }
+ b2Vec2.prototype.SetV = function (v) {
+ this.x = v.x;
+ this.y = v.y;
+ }
+ b2Vec2.prototype.GetNegative = function () {
+ return new b2Vec2((-this.x), (-this.y));
+ }
+ b2Vec2.prototype.NegativeSelf = function () {
+ this.x = (-this.x);
+ this.y = (-this.y);
+ }
+ b2Vec2.Make = function (x_, y_) {
+ if (x_ === undefined) x_ = 0;
+ if (y_ === undefined) y_ = 0;
+ return new b2Vec2(x_, y_);
+ }
+ b2Vec2.prototype.Copy = function () {
+ return new b2Vec2(this.x, this.y);
+ }
+ b2Vec2.prototype.Add = function (v) {
+ this.x += v.x;
+ this.y += v.y;
+ }
+ b2Vec2.prototype.Subtract = function (v) {
+ this.x -= v.x;
+ this.y -= v.y;
+ }
+ b2Vec2.prototype.Multiply = function (a) {
+ if (a === undefined) a = 0;
+ this.x *= a;
+ this.y *= a;
+ }
+ b2Vec2.prototype.MulM = function (A) {
+ var tX = this.x;
+ this.x = A.col1.x * tX + A.col2.x * this.y;
+ this.y = A.col1.y * tX + A.col2.y * this.y;
+ }
+ b2Vec2.prototype.MulTM = function (A) {
+ var tX = b2Math.Dot(this, A.col1);
+ this.y = b2Math.Dot(this, A.col2);
+ this.x = tX;
+ }
+ b2Vec2.prototype.CrossVF = function (s) {
+ if (s === undefined) s = 0;
+ var tX = this.x;
+ this.x = s * this.y;
+ this.y = (-s * tX);
+ }
+ b2Vec2.prototype.CrossFV = function (s) {
+ if (s === undefined) s = 0;
+ var tX = this.x;
+ this.x = (-s * this.y);
+ this.y = s * tX;
+ }
+ b2Vec2.prototype.MinV = function (b) {
+ this.x = this.x < b.x ? this.x : b.x;
+ this.y = this.y < b.y ? this.y : b.y;
+ }
+ b2Vec2.prototype.MaxV = function (b) {
+ this.x = this.x > b.x ? this.x : b.x;
+ this.y = this.y > b.y ? this.y : b.y;
+ }
+ b2Vec2.prototype.Abs = function () {
+ if (this.x < 0) this.x = (-this.x);
+ if (this.y < 0) this.y = (-this.y);
+ }
+ b2Vec2.prototype.Length = function () {
+ return Math.sqrt(this.x * this.x + this.y * this.y);
+ }
+ b2Vec2.prototype.LengthSquared = function () {
+ return (this.x * this.x + this.y * this.y);
+ }
+ b2Vec2.prototype.Normalize = function () {
+ var length = Math.sqrt(this.x * this.x + this.y * this.y);
+ if (length < Number.MIN_VALUE) {
+ return 0.0;
+ }
+ var invLength = 1.0 / length;
+ this.x *= invLength;
+ this.y *= invLength;
+ return length;
+ }
+ b2Vec2.prototype.IsValid = function () {
+ return b2Math.IsValid(this.x) && b2Math.IsValid(this.y);
+ }
+ b2Vec3.b2Vec3 = function () {};
+ b2Vec3.prototype.b2Vec3 = function (x, y, z) {
+ if (x === undefined) x = 0;
+ if (y === undefined) y = 0;
+ if (z === undefined) z = 0;
+ this.x = x;
+ this.y = y;
+ this.z = z;
+ }
+ b2Vec3.prototype.SetZero = function () {
+ this.x = this.y = this.z = 0.0;
+ }
+ b2Vec3.prototype.Set = function (x, y, z) {
+ if (x === undefined) x = 0;
+ if (y === undefined) y = 0;
+ if (z === undefined) z = 0;
+ this.x = x;
+ this.y = y;
+ this.z = z;
+ }
+ b2Vec3.prototype.SetV = function (v) {
+ this.x = v.x;
+ this.y = v.y;
+ this.z = v.z;
+ }
+ b2Vec3.prototype.GetNegative = function () {
+ return new b2Vec3((-this.x), (-this.y), (-this.z));
+ }
+ b2Vec3.prototype.NegativeSelf = function () {
+ this.x = (-this.x);
+ this.y = (-this.y);
+ this.z = (-this.z);
+ }
+ b2Vec3.prototype.Copy = function () {
+ return new b2Vec3(this.x, this.y, this.z);
+ }
+ b2Vec3.prototype.Add = function (v) {
+ this.x += v.x;
+ this.y += v.y;
+ this.z += v.z;
+ }
+ b2Vec3.prototype.Subtract = function (v) {
+ this.x -= v.x;
+ this.y -= v.y;
+ this.z -= v.z;
+ }
+ b2Vec3.prototype.Multiply = function (a) {
+ if (a === undefined) a = 0;
+ this.x *= a;
+ this.y *= a;
+ this.z *= a;
+ }
+})();
+(function () {
+ var b2ControllerEdge = Box2D.Dynamics.Controllers.b2ControllerEdge,
+ b2Mat22 = Box2D.Common.Math.b2Mat22,
+ b2Mat33 = Box2D.Common.Math.b2Mat33,
+ b2Math = Box2D.Common.Math.b2Math,
+ b2Sweep = Box2D.Common.Math.b2Sweep,
+ b2Transform = Box2D.Common.Math.b2Transform,
+ b2Vec2 = Box2D.Common.Math.b2Vec2,
+ b2Vec3 = Box2D.Common.Math.b2Vec3,
+ b2Color = Box2D.Common.b2Color,
+ b2internal = Box2D.Common.b2internal,
+ b2Settings = Box2D.Common.b2Settings,
+ b2AABB = Box2D.Collision.b2AABB,
+ b2Bound = Box2D.Collision.b2Bound,
+ b2BoundValues = Box2D.Collision.b2BoundValues,
+ b2Collision = Box2D.Collision.b2Collision,
+ b2ContactID = Box2D.Collision.b2ContactID,
+ b2ContactPoint = Box2D.Collision.b2ContactPoint,
+ b2Distance = Box2D.Collision.b2Distance,
+ b2DistanceInput = Box2D.Collision.b2DistanceInput,
+ b2DistanceOutput = Box2D.Collision.b2DistanceOutput,
+ b2DistanceProxy = Box2D.Collision.b2DistanceProxy,
+ b2DynamicTree = Box2D.Collision.b2DynamicTree,
+ b2DynamicTreeBroadPhase = Box2D.Collision.b2DynamicTreeBroadPhase,
+ b2DynamicTreeNode = Box2D.Collision.b2DynamicTreeNode,
+ b2DynamicTreePair = Box2D.Collision.b2DynamicTreePair,
+ b2Manifold = Box2D.Collision.b2Manifold,
+ b2ManifoldPoint = Box2D.Collision.b2ManifoldPoint,
+ b2Point = Box2D.Collision.b2Point,
+ b2RayCastInput = Box2D.Collision.b2RayCastInput,
+ b2RayCastOutput = Box2D.Collision.b2RayCastOutput,
+ b2Segment = Box2D.Collision.b2Segment,
+ b2SeparationFunction = Box2D.Collision.b2SeparationFunction,
+ b2Simplex = Box2D.Collision.b2Simplex,
+ b2SimplexCache = Box2D.Collision.b2SimplexCache,
+ b2SimplexVertex = Box2D.Collision.b2SimplexVertex,
+ b2TimeOfImpact = Box2D.Collision.b2TimeOfImpact,
+ b2TOIInput = Box2D.Collision.b2TOIInput,
+ b2WorldManifold = Box2D.Collision.b2WorldManifold,
+ ClipVertex = Box2D.Collision.ClipVertex,
+ Features = Box2D.Collision.Features,
+ IBroadPhase = Box2D.Collision.IBroadPhase,
+ b2CircleShape = Box2D.Collision.Shapes.b2CircleShape,
+ b2EdgeChainDef = Box2D.Collision.Shapes.b2EdgeChainDef,
+ b2EdgeShape = Box2D.Collision.Shapes.b2EdgeShape,
+ b2MassData = Box2D.Collision.Shapes.b2MassData,
+ b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape,
+ b2Shape = Box2D.Collision.Shapes.b2Shape,
+ b2Body = Box2D.Dynamics.b2Body,
+ b2BodyDef = Box2D.Dynamics.b2BodyDef,
+ b2ContactFilter = Box2D.Dynamics.b2ContactFilter,
+ b2ContactImpulse = Box2D.Dynamics.b2ContactImpulse,
+ b2ContactListener = Box2D.Dynamics.b2ContactListener,
+ b2ContactManager = Box2D.Dynamics.b2ContactManager,
+ b2DebugDraw = Box2D.Dynamics.b2DebugDraw,
+ b2DestructionListener = Box2D.Dynamics.b2DestructionListener,
+ b2FilterData = Box2D.Dynamics.b2FilterData,
+ b2Fixture = Box2D.Dynamics.b2Fixture,
+ b2FixtureDef = Box2D.Dynamics.b2FixtureDef,
+ b2Island = Box2D.Dynamics.b2Island,
+ b2TimeStep = Box2D.Dynamics.b2TimeStep,
+ b2World = Box2D.Dynamics.b2World,
+ b2CircleContact = Box2D.Dynamics.Contacts.b2CircleContact,
+ b2Contact = Box2D.Dynamics.Contacts.b2Contact,
+ b2ContactConstraint = Box2D.Dynamics.Contacts.b2ContactConstraint,
+ b2ContactConstraintPoint = Box2D.Dynamics.Contacts.b2ContactConstraintPoint,
+ b2ContactEdge = Box2D.Dynamics.Contacts.b2ContactEdge,
+ b2ContactFactory = Box2D.Dynamics.Contacts.b2ContactFactory,
+ b2ContactRegister = Box2D.Dynamics.Contacts.b2ContactRegister,
+ b2ContactResult = Box2D.Dynamics.Contacts.b2ContactResult,
+ b2ContactSolver = Box2D.Dynamics.Contacts.b2ContactSolver,
+ b2EdgeAndCircleContact = Box2D.Dynamics.Contacts.b2EdgeAndCircleContact,
+ b2NullContact = Box2D.Dynamics.Contacts.b2NullContact,
+ b2PolyAndCircleContact = Box2D.Dynamics.Contacts.b2PolyAndCircleContact,
+ b2PolyAndEdgeContact = Box2D.Dynamics.Contacts.b2PolyAndEdgeContact,
+ b2PolygonContact = Box2D.Dynamics.Contacts.b2PolygonContact,
+ b2PositionSolverManifold = Box2D.Dynamics.Contacts.b2PositionSolverManifold,
+ b2Controller = Box2D.Dynamics.Controllers.b2Controller,
+ b2DistanceJoint = Box2D.Dynamics.Joints.b2DistanceJoint,
+ b2DistanceJointDef = Box2D.Dynamics.Joints.b2DistanceJointDef,
+ b2FrictionJoint = Box2D.Dynamics.Joints.b2FrictionJoint,
+ b2FrictionJointDef = Box2D.Dynamics.Joints.b2FrictionJointDef,
+ b2GearJoint = Box2D.Dynamics.Joints.b2GearJoint,
+ b2GearJointDef = Box2D.Dynamics.Joints.b2GearJointDef,
+ b2Jacobian = Box2D.Dynamics.Joints.b2Jacobian,
+ b2Joint = Box2D.Dynamics.Joints.b2Joint,
+ b2JointDef = Box2D.Dynamics.Joints.b2JointDef,
+ b2JointEdge = Box2D.Dynamics.Joints.b2JointEdge,
+ b2LineJoint = Box2D.Dynamics.Joints.b2LineJoint,
+ b2LineJointDef = Box2D.Dynamics.Joints.b2LineJointDef,
+ b2MouseJoint = Box2D.Dynamics.Joints.b2MouseJoint,
+ b2MouseJointDef = Box2D.Dynamics.Joints.b2MouseJointDef,
+ b2PrismaticJoint = Box2D.Dynamics.Joints.b2PrismaticJoint,
+ b2PrismaticJointDef = Box2D.Dynamics.Joints.b2PrismaticJointDef,
+ b2PulleyJoint = Box2D.Dynamics.Joints.b2PulleyJoint,
+ b2PulleyJointDef = Box2D.Dynamics.Joints.b2PulleyJointDef,
+ b2RevoluteJoint = Box2D.Dynamics.Joints.b2RevoluteJoint,
+ b2RevoluteJointDef = Box2D.Dynamics.Joints.b2RevoluteJointDef,
+ b2WeldJoint = Box2D.Dynamics.Joints.b2WeldJoint,
+ b2WeldJointDef = Box2D.Dynamics.Joints.b2WeldJointDef;
+
+ b2Body.b2Body = function () {
+ this.m_xf = new b2Transform();
+ this.m_sweep = new b2Sweep();
+ this.m_linearVelocity = new b2Vec2();
+ this.m_force = new b2Vec2();
+ };
+ b2Body.prototype.connectEdges = function (s1, s2, angle1) {
+ if (angle1 === undefined) angle1 = 0;
+ var angle2 = Math.atan2(s2.GetDirectionVector().y, s2.GetDirectionVector().x);
+ var coreOffset = Math.tan((angle2 - angle1) * 0.5);
+ var core = b2Math.MulFV(coreOffset, s2.GetDirectionVector());
+ core = b2Math.SubtractVV(core, s2.GetNormalVector());
+ core = b2Math.MulFV(b2Settings.b2_toiSlop, core);
+ core = b2Math.AddVV(core, s2.GetVertex1());
+ var cornerDir = b2Math.AddVV(s1.GetDirectionVector(), s2.GetDirectionVector());
+ cornerDir.Normalize();
+ var convex = b2Math.Dot(s1.GetDirectionVector(), s2.GetNormalVector()) > 0.0;
+ s1.SetNextEdge(s2, core, cornerDir, convex);
+ s2.SetPrevEdge(s1, core, cornerDir, convex);
+ return angle2;
+ }
+ b2Body.prototype.CreateFixture = function (def) {
+ if (this.m_world.IsLocked() == true) {
+ return null;
+ }
+ var fixture = new b2Fixture();
+ fixture.Create(this, this.m_xf, def);
+ if (this.m_flags & b2Body.e_activeFlag) {
+ var broadPhase = this.m_world.m_contactManager.m_broadPhase;
+ fixture.CreateProxy(broadPhase, this.m_xf);
+ }
+ fixture.m_next = this.m_fixtureList;
+ this.m_fixtureList = fixture;
+ ++this.m_fixtureCount;
+ fixture.m_body = this;
+ if (fixture.m_density > 0.0) {
+ this.ResetMassData();
+ }
+ this.m_world.m_flags |= b2World.e_newFixture;
+ return fixture;
+ }
+ b2Body.prototype.CreateFixture2 = function (shape, density) {
+ if (density === undefined) density = 0.0;
+ var def = new b2FixtureDef();
+ def.shape = shape;
+ def.density = density;
+ return this.CreateFixture(def);
+ }
+ b2Body.prototype.DestroyFixture = function (fixture) {
+ if (this.m_world.IsLocked() == true) {
+ return;
+ }
+ var node = this.m_fixtureList;
+ var ppF = null;
+ var found = false;
+ while (node != null) {
+ if (node == fixture) {
+ if (ppF) ppF.m_next = fixture.m_next;
+ else this.m_fixtureList = fixture.m_next;
+ found = true;
+ break;
+ }
+ ppF = node;
+ node = node.m_next;
+ }
+ var edge = this.m_contactList;
+ while (edge) {
+ var c = edge.contact;
+ edge = edge.next;
+ var fixtureA = c.GetFixtureA();
+ var fixtureB = c.GetFixtureB();
+ if (fixture == fixtureA || fixture == fixtureB) {
+ this.m_world.m_contactManager.Destroy(c);
+ }
+ }
+ if (this.m_flags & b2Body.e_activeFlag) {
+ var broadPhase = this.m_world.m_contactManager.m_broadPhase;
+ fixture.DestroyProxy(broadPhase);
+ }
+ else {}
+ fixture.Destroy();
+ fixture.m_body = null;
+ fixture.m_next = null;
+ --this.m_fixtureCount;
+ this.ResetMassData();
+ }
+ b2Body.prototype.SetPositionAndAngle = function (position, angle) {
+ if (angle === undefined) angle = 0;
+ var f;
+ if (this.m_world.IsLocked() == true) {
+ return;
+ }
+ this.m_xf.R.Set(angle);
+ this.m_xf.position.SetV(position);
+ var tMat = this.m_xf.R;
+ var tVec = this.m_sweep.localCenter;
+ this.m_sweep.c.x = (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ this.m_sweep.c.y = (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ this.m_sweep.c.x += this.m_xf.position.x;
+ this.m_sweep.c.y += this.m_xf.position.y;
+ this.m_sweep.c0.SetV(this.m_sweep.c);
+ this.m_sweep.a0 = this.m_sweep.a = angle;
+ var broadPhase = this.m_world.m_contactManager.m_broadPhase;
+ for (f = this.m_fixtureList;
+ f; f = f.m_next) {
+ f.Synchronize(broadPhase, this.m_xf, this.m_xf);
+ }
+ this.m_world.m_contactManager.FindNewContacts();
+ }
+ b2Body.prototype.SetTransform = function (xf) {
+ this.SetPositionAndAngle(xf.position, xf.GetAngle());
+ }
+ b2Body.prototype.GetTransform = function () {
+ return this.m_xf;
+ }
+ b2Body.prototype.GetPosition = function () {
+ return this.m_xf.position;
+ }
+ b2Body.prototype.SetPosition = function (position) {
+ this.SetPositionAndAngle(position, this.GetAngle());
+ }
+ b2Body.prototype.GetAngle = function () {
+ return this.m_sweep.a;
+ }
+ b2Body.prototype.SetAngle = function (angle) {
+ if (angle === undefined) angle = 0;
+ this.SetPositionAndAngle(this.GetPosition(), angle);
+ }
+ b2Body.prototype.GetWorldCenter = function () {
+ return this.m_sweep.c;
+ }
+ b2Body.prototype.GetLocalCenter = function () {
+ return this.m_sweep.localCenter;
+ }
+ b2Body.prototype.SetLinearVelocity = function (v) {
+ if (this.m_type == b2Body.b2_staticBody) {
+ return;
+ }
+ this.m_linearVelocity.SetV(v);
+ }
+ b2Body.prototype.GetLinearVelocity = function () {
+ return this.m_linearVelocity;
+ }
+ b2Body.prototype.SetAngularVelocity = function (omega) {
+ if (omega === undefined) omega = 0;
+ if (this.m_type == b2Body.b2_staticBody) {
+ return;
+ }
+ this.m_angularVelocity = omega;
+ }
+ b2Body.prototype.GetAngularVelocity = function () {
+ return this.m_angularVelocity;
+ }
+ b2Body.prototype.GetDefinition = function () {
+ var bd = new b2BodyDef();
+ bd.type = this.GetType();
+ bd.allowSleep = (this.m_flags & b2Body.e_allowSleepFlag) == b2Body.e_allowSleepFlag;
+ bd.angle = this.GetAngle();
+ bd.angularDamping = this.m_angularDamping;
+ bd.angularVelocity = this.m_angularVelocity;
+ bd.fixedRotation = (this.m_flags & b2Body.e_fixedRotationFlag) == b2Body.e_fixedRotationFlag;
+ bd.bullet = (this.m_flags & b2Body.e_bulletFlag) == b2Body.e_bulletFlag;
+ bd.awake = (this.m_flags & b2Body.e_awakeFlag) == b2Body.e_awakeFlag;
+ bd.linearDamping = this.m_linearDamping;
+ bd.linearVelocity.SetV(this.GetLinearVelocity());
+ bd.position = this.GetPosition();
+ bd.userData = this.GetUserData();
+ return bd;
+ }
+ b2Body.prototype.ApplyForce = function (force, point) {
+ if (this.m_type != b2Body.b2_dynamicBody) {
+ return;
+ }
+ if (this.IsAwake() == false) {
+ this.SetAwake(true);
+ }
+ this.m_force.x += force.x;
+ this.m_force.y += force.y;
+ this.m_torque += ((point.x - this.m_sweep.c.x) * force.y - (point.y - this.m_sweep.c.y) * force.x);
+ }
+ b2Body.prototype.ApplyTorque = function (torque) {
+ if (torque === undefined) torque = 0;
+ if (this.m_type != b2Body.b2_dynamicBody) {
+ return;
+ }
+ if (this.IsAwake() == false) {
+ this.SetAwake(true);
+ }
+ this.m_torque += torque;
+ }
+ b2Body.prototype.ApplyImpulse = function (impulse, point) {
+ if (this.m_type != b2Body.b2_dynamicBody) {
+ return;
+ }
+ if (this.IsAwake() == false) {
+ this.SetAwake(true);
+ }
+ this.m_linearVelocity.x += this.m_invMass * impulse.x;
+ this.m_linearVelocity.y += this.m_invMass * impulse.y;
+ this.m_angularVelocity += this.m_invI * ((point.x - this.m_sweep.c.x) * impulse.y - (point.y - this.m_sweep.c.y) * impulse.x);
+ }
+ b2Body.prototype.Split = function (callback) {
+ var linearVelocity = this.GetLinearVelocity().Copy();
+ var angularVelocity = this.GetAngularVelocity();
+ var center = this.GetWorldCenter();
+ var body1 = this;
+ var body2 = this.m_world.CreateBody(this.GetDefinition());
+ var prev;
+ for (var f = body1.m_fixtureList; f;) {
+ if (callback(f)) {
+ var next = f.m_next;
+ if (prev) {
+ prev.m_next = next;
+ }
+ else {
+ body1.m_fixtureList = next;
+ }
+ body1.m_fixtureCount--;
+ f.m_next = body2.m_fixtureList;
+ body2.m_fixtureList = f;
+ body2.m_fixtureCount++;
+ f.m_body = body2;
+ f = next;
+ }
+ else {
+ prev = f;
+ f = f.m_next;
+ }
+ }
+ body1.ResetMassData();
+ body2.ResetMassData();
+ var center1 = body1.GetWorldCenter();
+ var center2 = body2.GetWorldCenter();
+ var velocity1 = b2Math.AddVV(linearVelocity, b2Math.CrossFV(angularVelocity, b2Math.SubtractVV(center1, center)));
+ var velocity2 = b2Math.AddVV(linearVelocity, b2Math.CrossFV(angularVelocity, b2Math.SubtractVV(center2, center)));
+ body1.SetLinearVelocity(velocity1);
+ body2.SetLinearVelocity(velocity2);
+ body1.SetAngularVelocity(angularVelocity);
+ body2.SetAngularVelocity(angularVelocity);
+ body1.SynchronizeFixtures();
+ body2.SynchronizeFixtures();
+ return body2;
+ }
+ b2Body.prototype.Merge = function (other) {
+ var f;
+ for (f = other.m_fixtureList;
+ f;) {
+ var next = f.m_next;
+ other.m_fixtureCount--;
+ f.m_next = this.m_fixtureList;
+ this.m_fixtureList = f;
+ this.m_fixtureCount++;
+ f.m_body = body2;
+ f = next;
+ }
+ body1.m_fixtureCount = 0;
+ var body1 = this;
+ var body2 = other;
+ var center1 = body1.GetWorldCenter();
+ var center2 = body2.GetWorldCenter();
+ var velocity1 = body1.GetLinearVelocity().Copy();
+ var velocity2 = body2.GetLinearVelocity().Copy();
+ var angular1 = body1.GetAngularVelocity();
+ var angular = body2.GetAngularVelocity();
+ body1.ResetMassData();
+ this.SynchronizeFixtures();
+ }
+ b2Body.prototype.GetMass = function () {
+ return this.m_mass;
+ }
+ b2Body.prototype.GetInertia = function () {
+ return this.m_I;
+ }
+ b2Body.prototype.GetMassData = function (data) {
+ data.mass = this.m_mass;
+ data.I = this.m_I;
+ data.center.SetV(this.m_sweep.localCenter);
+ }
+ b2Body.prototype.SetMassData = function (massData) {
+ b2Settings.b2Assert(this.m_world.IsLocked() == false);
+ if (this.m_world.IsLocked() == true) {
+ return;
+ }
+ if (this.m_type != b2Body.b2_dynamicBody) {
+ return;
+ }
+ this.m_invMass = 0.0;
+ this.m_I = 0.0;
+ this.m_invI = 0.0;
+ this.m_mass = massData.mass;
+ if (this.m_mass <= 0.0) {
+ this.m_mass = 1.0;
+ }
+ this.m_invMass = 1.0 / this.m_mass;
+ if (massData.I > 0.0 && (this.m_flags & b2Body.e_fixedRotationFlag) == 0) {
+ this.m_I = massData.I - this.m_mass * (massData.center.x * massData.center.x + massData.center.y * massData.center.y);
+ this.m_invI = 1.0 / this.m_I;
+ }
+ var oldCenter = this.m_sweep.c.Copy();
+ this.m_sweep.localCenter.SetV(massData.center);
+ this.m_sweep.c0.SetV(b2Math.MulX(this.m_xf, this.m_sweep.localCenter));
+ this.m_sweep.c.SetV(this.m_sweep.c0);
+ this.m_linearVelocity.x += this.m_angularVelocity * (-(this.m_sweep.c.y - oldCenter.y));
+ this.m_linearVelocity.y += this.m_angularVelocity * (+(this.m_sweep.c.x - oldCenter.x));
+ }
+ b2Body.prototype.ResetMassData = function () {
+ this.m_mass = 0.0;
+ this.m_invMass = 0.0;
+ this.m_I = 0.0;
+ this.m_invI = 0.0;
+ this.m_sweep.localCenter.SetZero();
+ if (this.m_type == b2Body.b2_staticBody || this.m_type == b2Body.b2_kinematicBody) {
+ return;
+ }
+ var center = b2Vec2.Make(0, 0);
+ for (var f = this.m_fixtureList; f; f = f.m_next) {
+ if (f.m_density == 0.0) {
+ continue;
+ }
+ var massData = f.GetMassData();
+ this.m_mass += massData.mass;
+ center.x += massData.center.x * massData.mass;
+ center.y += massData.center.y * massData.mass;
+ this.m_I += massData.I;
+ }
+ if (this.m_mass > 0.0) {
+ this.m_invMass = 1.0 / this.m_mass;
+ center.x *= this.m_invMass;
+ center.y *= this.m_invMass;
+ }
+ else {
+ this.m_mass = 1.0;
+ this.m_invMass = 1.0;
+ }
+ if (this.m_I > 0.0 && (this.m_flags & b2Body.e_fixedRotationFlag) == 0) {
+ this.m_I -= this.m_mass * (center.x * center.x + center.y * center.y);
+ this.m_I *= this.m_inertiaScale;
+ b2Settings.b2Assert(this.m_I > 0);
+ this.m_invI = 1.0 / this.m_I;
+ }
+ else {
+ this.m_I = 0.0;
+ this.m_invI = 0.0;
+ }
+ var oldCenter = this.m_sweep.c.Copy();
+ this.m_sweep.localCenter.SetV(center);
+ this.m_sweep.c0.SetV(b2Math.MulX(this.m_xf, this.m_sweep.localCenter));
+ this.m_sweep.c.SetV(this.m_sweep.c0);
+ this.m_linearVelocity.x += this.m_angularVelocity * (-(this.m_sweep.c.y - oldCenter.y));
+ this.m_linearVelocity.y += this.m_angularVelocity * (+(this.m_sweep.c.x - oldCenter.x));
+ }
+ b2Body.prototype.GetWorldPoint = function (localPoint) {
+ var A = this.m_xf.R;
+ var u = new b2Vec2(A.col1.x * localPoint.x + A.col2.x * localPoint.y, A.col1.y * localPoint.x + A.col2.y * localPoint.y);
+ u.x += this.m_xf.position.x;
+ u.y += this.m_xf.position.y;
+ return u;
+ }
+ b2Body.prototype.GetWorldVector = function (localVector) {
+ return b2Math.MulMV(this.m_xf.R, localVector);
+ }
+ b2Body.prototype.GetLocalPoint = function (worldPoint) {
+ return b2Math.MulXT(this.m_xf, worldPoint);
+ }
+ b2Body.prototype.GetLocalVector = function (worldVector) {
+ return b2Math.MulTMV(this.m_xf.R, worldVector);
+ }
+ b2Body.prototype.GetLinearVelocityFromWorldPoint = function (worldPoint) {
+ return new b2Vec2(this.m_linearVelocity.x - this.m_angularVelocity * (worldPoint.y - this.m_sweep.c.y), this.m_linearVelocity.y + this.m_angularVelocity * (worldPoint.x - this.m_sweep.c.x));
+ }
+ b2Body.prototype.GetLinearVelocityFromLocalPoint = function (localPoint) {
+ var A = this.m_xf.R;
+ var worldPoint = new b2Vec2(A.col1.x * localPoint.x + A.col2.x * localPoint.y, A.col1.y * localPoint.x + A.col2.y * localPoint.y);
+ worldPoint.x += this.m_xf.position.x;
+ worldPoint.y += this.m_xf.position.y;
+ return new b2Vec2(this.m_linearVelocity.x - this.m_angularVelocity * (worldPoint.y - this.m_sweep.c.y), this.m_linearVelocity.y + this.m_angularVelocity * (worldPoint.x - this.m_sweep.c.x));
+ }
+ b2Body.prototype.GetLinearDamping = function () {
+ return this.m_linearDamping;
+ }
+ b2Body.prototype.SetLinearDamping = function (linearDamping) {
+ if (linearDamping === undefined) linearDamping = 0;
+ this.m_linearDamping = linearDamping;
+ }
+ b2Body.prototype.GetAngularDamping = function () {
+ return this.m_angularDamping;
+ }
+ b2Body.prototype.SetAngularDamping = function (angularDamping) {
+ if (angularDamping === undefined) angularDamping = 0;
+ this.m_angularDamping = angularDamping;
+ }
+ b2Body.prototype.SetType = function (type) {
+ if (type === undefined) type = 0;
+ if (this.m_type == type) {
+ return;
+ }
+ this.m_type = type;
+ this.ResetMassData();
+ if (this.m_type == b2Body.b2_staticBody) {
+ this.m_linearVelocity.SetZero();
+ this.m_angularVelocity = 0.0;
+ }
+ this.SetAwake(true);
+ this.m_force.SetZero();
+ this.m_torque = 0.0;
+ for (var ce = this.m_contactList; ce; ce = ce.next) {
+ ce.contact.FlagForFiltering();
+ }
+ }
+ b2Body.prototype.GetType = function () {
+ return this.m_type;
+ }
+ b2Body.prototype.SetBullet = function (flag) {
+ if (flag) {
+ this.m_flags |= b2Body.e_bulletFlag;
+ }
+ else {
+ this.m_flags &= ~b2Body.e_bulletFlag;
+ }
+ }
+ b2Body.prototype.IsBullet = function () {
+ return (this.m_flags & b2Body.e_bulletFlag) == b2Body.e_bulletFlag;
+ }
+ b2Body.prototype.SetSleepingAllowed = function (flag) {
+ if (flag) {
+ this.m_flags |= b2Body.e_allowSleepFlag;
+ }
+ else {
+ this.m_flags &= ~b2Body.e_allowSleepFlag;
+ this.SetAwake(true);
+ }
+ }
+ b2Body.prototype.SetAwake = function (flag) {
+ if (flag) {
+ this.m_flags |= b2Body.e_awakeFlag;
+ this.m_sleepTime = 0.0;
+ }
+ else {
+ this.m_flags &= ~b2Body.e_awakeFlag;
+ this.m_sleepTime = 0.0;
+ this.m_linearVelocity.SetZero();
+ this.m_angularVelocity = 0.0;
+ this.m_force.SetZero();
+ this.m_torque = 0.0;
+ }
+ }
+ b2Body.prototype.IsAwake = function () {
+ return (this.m_flags & b2Body.e_awakeFlag) == b2Body.e_awakeFlag;
+ }
+ b2Body.prototype.SetFixedRotation = function (fixed) {
+ if (fixed) {
+ this.m_flags |= b2Body.e_fixedRotationFlag;
+ }
+ else {
+ this.m_flags &= ~b2Body.e_fixedRotationFlag;
+ }
+ this.ResetMassData();
+ }
+ b2Body.prototype.IsFixedRotation = function () {
+ return (this.m_flags & b2Body.e_fixedRotationFlag) == b2Body.e_fixedRotationFlag;
+ }
+ b2Body.prototype.SetActive = function (flag) {
+ if (flag == this.IsActive()) {
+ return;
+ }
+ var broadPhase;
+ var f;
+ if (flag) {
+ this.m_flags |= b2Body.e_activeFlag;
+ broadPhase = this.m_world.m_contactManager.m_broadPhase;
+ for (f = this.m_fixtureList;
+ f; f = f.m_next) {
+ f.CreateProxy(broadPhase, this.m_xf);
+ }
+ }
+ else {
+ this.m_flags &= ~b2Body.e_activeFlag;
+ broadPhase = this.m_world.m_contactManager.m_broadPhase;
+ for (f = this.m_fixtureList;
+ f; f = f.m_next) {
+ f.DestroyProxy(broadPhase);
+ }
+ var ce = this.m_contactList;
+ while (ce) {
+ var ce0 = ce;
+ ce = ce.next;
+ this.m_world.m_contactManager.Destroy(ce0.contact);
+ }
+ this.m_contactList = null;
+ }
+ }
+ b2Body.prototype.IsActive = function () {
+ return (this.m_flags & b2Body.e_activeFlag) == b2Body.e_activeFlag;
+ }
+ b2Body.prototype.IsSleepingAllowed = function () {
+ return (this.m_flags & b2Body.e_allowSleepFlag) == b2Body.e_allowSleepFlag;
+ }
+ b2Body.prototype.GetFixtureList = function () {
+ return this.m_fixtureList;
+ }
+ b2Body.prototype.GetJointList = function () {
+ return this.m_jointList;
+ }
+ b2Body.prototype.GetControllerList = function () {
+ return this.m_controllerList;
+ }
+ b2Body.prototype.GetContactList = function () {
+ return this.m_contactList;
+ }
+ b2Body.prototype.GetNext = function () {
+ return this.m_next;
+ }
+ b2Body.prototype.GetUserData = function () {
+ return this.m_userData;
+ }
+ b2Body.prototype.SetUserData = function (data) {
+ this.m_userData = data;
+ }
+ b2Body.prototype.GetWorld = function () {
+ return this.m_world;
+ }
+ b2Body.prototype.b2Body = function (bd, world) {
+ this.m_flags = 0;
+ if (bd.bullet) {
+ this.m_flags |= b2Body.e_bulletFlag;
+ }
+ if (bd.fixedRotation) {
+ this.m_flags |= b2Body.e_fixedRotationFlag;
+ }
+ if (bd.allowSleep) {
+ this.m_flags |= b2Body.e_allowSleepFlag;
+ }
+ if (bd.awake) {
+ this.m_flags |= b2Body.e_awakeFlag;
+ }
+ if (bd.active) {
+ this.m_flags |= b2Body.e_activeFlag;
+ }
+ this.m_world = world;
+ this.m_xf.position.SetV(bd.position);
+ this.m_xf.R.Set(bd.angle);
+ this.m_sweep.localCenter.SetZero();
+ this.m_sweep.t0 = 1.0;
+ this.m_sweep.a0 = this.m_sweep.a = bd.angle;
+ var tMat = this.m_xf.R;
+ var tVec = this.m_sweep.localCenter;
+ this.m_sweep.c.x = (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ this.m_sweep.c.y = (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ this.m_sweep.c.x += this.m_xf.position.x;
+ this.m_sweep.c.y += this.m_xf.position.y;
+ this.m_sweep.c0.SetV(this.m_sweep.c);
+ this.m_jointList = null;
+ this.m_controllerList = null;
+ this.m_contactList = null;
+ this.m_controllerCount = 0;
+ this.m_prev = null;
+ this.m_next = null;
+ this.m_linearVelocity.SetV(bd.linearVelocity);
+ this.m_angularVelocity = bd.angularVelocity;
+ this.m_linearDamping = bd.linearDamping;
+ this.m_angularDamping = bd.angularDamping;
+ this.m_force.Set(0.0, 0.0);
+ this.m_torque = 0.0;
+ this.m_sleepTime = 0.0;
+ this.m_type = bd.type;
+ if (this.m_type == b2Body.b2_dynamicBody) {
+ this.m_mass = 1.0;
+ this.m_invMass = 1.0;
+ }
+ else {
+ this.m_mass = 0.0;
+ this.m_invMass = 0.0;
+ }
+ this.m_I = 0.0;
+ this.m_invI = 0.0;
+ this.m_inertiaScale = bd.inertiaScale;
+ this.m_userData = bd.userData;
+ this.m_fixtureList = null;
+ this.m_fixtureCount = 0;
+ }
+ b2Body.prototype.SynchronizeFixtures = function () {
+ var xf1 = b2Body.s_xf1;
+ xf1.R.Set(this.m_sweep.a0);
+ var tMat = xf1.R;
+ var tVec = this.m_sweep.localCenter;
+ xf1.position.x = this.m_sweep.c0.x - (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ xf1.position.y = this.m_sweep.c0.y - (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ var f;
+ var broadPhase = this.m_world.m_contactManager.m_broadPhase;
+ for (f = this.m_fixtureList;
+ f; f = f.m_next) {
+ f.Synchronize(broadPhase, xf1, this.m_xf);
+ }
+ }
+ b2Body.prototype.SynchronizeTransform = function () {
+ this.m_xf.R.Set(this.m_sweep.a);
+ var tMat = this.m_xf.R;
+ var tVec = this.m_sweep.localCenter;
+ this.m_xf.position.x = this.m_sweep.c.x - (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ this.m_xf.position.y = this.m_sweep.c.y - (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ }
+ b2Body.prototype.ShouldCollide = function (other) {
+ if (this.m_type != b2Body.b2_dynamicBody && other.m_type != b2Body.b2_dynamicBody) {
+ return false;
+ }
+ for (var jn = this.m_jointList; jn; jn = jn.next) {
+ if (jn.other == other) if (jn.joint.m_collideConnected == false) {
+ return false;
+ }
+ }
+ return true;
+ }
+ b2Body.prototype.Advance = function (t) {
+ if (t === undefined) t = 0;
+ this.m_sweep.Advance(t);
+ this.m_sweep.c.SetV(this.m_sweep.c0);
+ this.m_sweep.a = this.m_sweep.a0;
+ this.SynchronizeTransform();
+ }
+ Box2D.postDefs.push(function () {
+ Box2D.Dynamics.b2Body.s_xf1 = new b2Transform();
+ Box2D.Dynamics.b2Body.e_islandFlag = 0x0001;
+ Box2D.Dynamics.b2Body.e_awakeFlag = 0x0002;
+ Box2D.Dynamics.b2Body.e_allowSleepFlag = 0x0004;
+ Box2D.Dynamics.b2Body.e_bulletFlag = 0x0008;
+ Box2D.Dynamics.b2Body.e_fixedRotationFlag = 0x0010;
+ Box2D.Dynamics.b2Body.e_activeFlag = 0x0020;
+ Box2D.Dynamics.b2Body.b2_staticBody = 0;
+ Box2D.Dynamics.b2Body.b2_kinematicBody = 1;
+ Box2D.Dynamics.b2Body.b2_dynamicBody = 2;
+ });
+ b2BodyDef.b2BodyDef = function () {
+ this.position = new b2Vec2();
+ this.linearVelocity = new b2Vec2();
+ };
+ b2BodyDef.prototype.b2BodyDef = function () {
+ this.userData = null;
+ this.position.Set(0.0, 0.0);
+ this.angle = 0.0;
+ this.linearVelocity.Set(0, 0);
+ this.angularVelocity = 0.0;
+ this.linearDamping = 0.0;
+ this.angularDamping = 0.0;
+ this.allowSleep = true;
+ this.awake = true;
+ this.fixedRotation = false;
+ this.bullet = false;
+ this.type = b2Body.b2_staticBody;
+ this.active = true;
+ this.inertiaScale = 1.0;
+ }
+ b2ContactFilter.b2ContactFilter = function () {};
+ b2ContactFilter.prototype.ShouldCollide = function (fixtureA, fixtureB) {
+ var filter1 = fixtureA.GetFilterData();
+ var filter2 = fixtureB.GetFilterData();
+ if (filter1.groupIndex == filter2.groupIndex && filter1.groupIndex != 0) {
+ return filter1.groupIndex > 0;
+ }
+ var collide = (filter1.maskBits & filter2.categoryBits) != 0 && (filter1.categoryBits & filter2.maskBits) != 0;
+ return collide;
+ }
+ b2ContactFilter.prototype.RayCollide = function (userData, fixture) {
+ if (!userData) return true;
+ return this.ShouldCollide((userData instanceof b2Fixture ? userData : null), fixture);
+ }
+ Box2D.postDefs.push(function () {
+ Box2D.Dynamics.b2ContactFilter.b2_defaultFilter = new b2ContactFilter();
+ });
+ b2ContactImpulse.b2ContactImpulse = function () {
+ this.normalImpulses = new Vector_a2j_Number(b2Settings.b2_maxManifoldPoints);
+ this.tangentImpulses = new Vector_a2j_Number(b2Settings.b2_maxManifoldPoints);
+ };
+ b2ContactListener.b2ContactListener = function () {};
+ b2ContactListener.prototype.BeginContact = function (contact) {}
+ b2ContactListener.prototype.EndContact = function (contact) {}
+ b2ContactListener.prototype.PreSolve = function (contact, oldManifold) {}
+ b2ContactListener.prototype.PostSolve = function (contact, impulse) {}
+ Box2D.postDefs.push(function () {
+ Box2D.Dynamics.b2ContactListener.b2_defaultListener = new b2ContactListener();
+ });
+ b2ContactManager.b2ContactManager = function () {};
+ b2ContactManager.prototype.b2ContactManager = function () {
+ this.m_world = null;
+ this.m_contactCount = 0;
+ this.m_contactFilter = b2ContactFilter.b2_defaultFilter;
+ this.m_contactListener = b2ContactListener.b2_defaultListener;
+ this.m_contactFactory = new b2ContactFactory(this.m_allocator);
+ this.m_broadPhase = new b2DynamicTreeBroadPhase();
+ }
+ b2ContactManager.prototype.AddPair = function (proxyUserDataA, proxyUserDataB) {
+ var fixtureA = (proxyUserDataA instanceof b2Fixture ? proxyUserDataA : null);
+ var fixtureB = (proxyUserDataB instanceof b2Fixture ? proxyUserDataB : null);
+ var bodyA = fixtureA.GetBody();
+ var bodyB = fixtureB.GetBody();
+ if (bodyA == bodyB) return;
+ var edge = bodyB.GetContactList();
+ while (edge) {
+ if (edge.other == bodyA) {
+ var fA = edge.contact.GetFixtureA();
+ var fB = edge.contact.GetFixtureB();
+ if (fA == fixtureA && fB == fixtureB) return;
+ if (fA == fixtureB && fB == fixtureA) return;
+ }
+ edge = edge.next;
+ }
+ if (bodyB.ShouldCollide(bodyA) == false) {
+ return;
+ }
+ if (this.m_contactFilter.ShouldCollide(fixtureA, fixtureB) == false) {
+ return;
+ }
+ var c = this.m_contactFactory.Create(fixtureA, fixtureB);
+ fixtureA = c.GetFixtureA();
+ fixtureB = c.GetFixtureB();
+ bodyA = fixtureA.m_body;
+ bodyB = fixtureB.m_body;
+ c.m_prev = null;
+ c.m_next = this.m_world.m_contactList;
+ if (this.m_world.m_contactList != null) {
+ this.m_world.m_contactList.m_prev = c;
+ }
+ this.m_world.m_contactList = c;
+ c.m_nodeA.contact = c;
+ c.m_nodeA.other = bodyB;
+ c.m_nodeA.prev = null;
+ c.m_nodeA.next = bodyA.m_contactList;
+ if (bodyA.m_contactList != null) {
+ bodyA.m_contactList.prev = c.m_nodeA;
+ }
+ bodyA.m_contactList = c.m_nodeA;
+ c.m_nodeB.contact = c;
+ c.m_nodeB.other = bodyA;
+ c.m_nodeB.prev = null;
+ c.m_nodeB.next = bodyB.m_contactList;
+ if (bodyB.m_contactList != null) {
+ bodyB.m_contactList.prev = c.m_nodeB;
+ }
+ bodyB.m_contactList = c.m_nodeB;
+ ++this.m_world.m_contactCount;
+ return;
+ }
+ b2ContactManager.prototype.FindNewContacts = function () {
+ this.m_broadPhase.UpdatePairs(Box2D.generateCallback(this, this.AddPair));
+ }
+ b2ContactManager.prototype.Destroy = function (c) {
+ var fixtureA = c.GetFixtureA();
+ var fixtureB = c.GetFixtureB();
+ var bodyA = fixtureA.GetBody();
+ var bodyB = fixtureB.GetBody();
+ if (c.IsTouching()) {
+ this.m_contactListener.EndContact(c);
+ }
+ if (c.m_prev) {
+ c.m_prev.m_next = c.m_next;
+ }
+ if (c.m_next) {
+ c.m_next.m_prev = c.m_prev;
+ }
+ if (c == this.m_world.m_contactList) {
+ this.m_world.m_contactList = c.m_next;
+ }
+ if (c.m_nodeA.prev) {
+ c.m_nodeA.prev.next = c.m_nodeA.next;
+ }
+ if (c.m_nodeA.next) {
+ c.m_nodeA.next.prev = c.m_nodeA.prev;
+ }
+ if (c.m_nodeA == bodyA.m_contactList) {
+ bodyA.m_contactList = c.m_nodeA.next;
+ }
+ if (c.m_nodeB.prev) {
+ c.m_nodeB.prev.next = c.m_nodeB.next;
+ }
+ if (c.m_nodeB.next) {
+ c.m_nodeB.next.prev = c.m_nodeB.prev;
+ }
+ if (c.m_nodeB == bodyB.m_contactList) {
+ bodyB.m_contactList = c.m_nodeB.next;
+ }
+ this.m_contactFactory.Destroy(c);
+ --this.m_contactCount;
+ }
+ b2ContactManager.prototype.Collide = function () {
+ var c = this.m_world.m_contactList;
+ while (c) {
+ var fixtureA = c.GetFixtureA();
+ var fixtureB = c.GetFixtureB();
+ var bodyA = fixtureA.GetBody();
+ var bodyB = fixtureB.GetBody();
+ if (bodyA.IsAwake() == false && bodyB.IsAwake() == false) {
+ c = c.GetNext();
+ continue;
+ }
+ if (c.m_flags & b2Contact.e_filterFlag) {
+ if (bodyB.ShouldCollide(bodyA) == false) {
+ var cNuke = c;
+ c = cNuke.GetNext();
+ this.Destroy(cNuke);
+ continue;
+ }
+ if (this.m_contactFilter.ShouldCollide(fixtureA, fixtureB) == false) {
+ cNuke = c;
+ c = cNuke.GetNext();
+ this.Destroy(cNuke);
+ continue;
+ }
+ c.m_flags &= ~b2Contact.e_filterFlag;
+ }
+ var proxyA = fixtureA.m_proxy;
+ var proxyB = fixtureB.m_proxy;
+ var overlap = this.m_broadPhase.TestOverlap(proxyA, proxyB);
+ if (overlap == false) {
+ cNuke = c;
+ c = cNuke.GetNext();
+ this.Destroy(cNuke);
+ continue;
+ }
+ c.Update(this.m_contactListener);
+ c = c.GetNext();
+ }
+ }
+ Box2D.postDefs.push(function () {
+ Box2D.Dynamics.b2ContactManager.s_evalCP = new b2ContactPoint();
+ });
+ b2DebugDraw.b2DebugDraw = function () {};
+ b2DebugDraw.prototype.b2DebugDraw = function () {}
+ b2DebugDraw.prototype.SetFlags = function (flags) {
+ if (flags === undefined) flags = 0;
+ }
+ b2DebugDraw.prototype.GetFlags = function () {}
+ b2DebugDraw.prototype.AppendFlags = function (flags) {
+ if (flags === undefined) flags = 0;
+ }
+ b2DebugDraw.prototype.ClearFlags = function (flags) {
+ if (flags === undefined) flags = 0;
+ }
+ b2DebugDraw.prototype.SetSprite = function (sprite) {}
+ b2DebugDraw.prototype.GetSprite = function () {}
+ b2DebugDraw.prototype.SetDrawScale = function (drawScale) {
+ if (drawScale === undefined) drawScale = 0;
+ }
+ b2DebugDraw.prototype.GetDrawScale = function () {}
+ b2DebugDraw.prototype.SetLineThickness = function (lineThickness) {
+ if (lineThickness === undefined) lineThickness = 0;
+ }
+ b2DebugDraw.prototype.GetLineThickness = function () {}
+ b2DebugDraw.prototype.SetAlpha = function (alpha) {
+ if (alpha === undefined) alpha = 0;
+ }
+ b2DebugDraw.prototype.GetAlpha = function () {}
+ b2DebugDraw.prototype.SetFillAlpha = function (alpha) {
+ if (alpha === undefined) alpha = 0;
+ }
+ b2DebugDraw.prototype.GetFillAlpha = function () {}
+ b2DebugDraw.prototype.SetXFormScale = function (xformScale) {
+ if (xformScale === undefined) xformScale = 0;
+ }
+ b2DebugDraw.prototype.GetXFormScale = function () {}
+ b2DebugDraw.prototype.DrawPolygon = function (vertices, vertexCount, color) {
+ if (vertexCount === undefined) vertexCount = 0;
+ }
+ b2DebugDraw.prototype.DrawSolidPolygon = function (vertices, vertexCount, color) {
+ if (vertexCount === undefined) vertexCount = 0;
+ }
+ b2DebugDraw.prototype.DrawCircle = function (center, radius, color) {
+ if (radius === undefined) radius = 0;
+ }
+ b2DebugDraw.prototype.DrawSolidCircle = function (center, radius, axis, color) {
+ if (radius === undefined) radius = 0;
+ }
+ b2DebugDraw.prototype.DrawSegment = function (p1, p2, color) {}
+ b2DebugDraw.prototype.DrawTransform = function (xf) {}
+ Box2D.postDefs.push(function () {
+ Box2D.Dynamics.b2DebugDraw.e_shapeBit = 0x0001;
+ Box2D.Dynamics.b2DebugDraw.e_jointBit = 0x0002;
+ Box2D.Dynamics.b2DebugDraw.e_aabbBit = 0x0004;
+ Box2D.Dynamics.b2DebugDraw.e_pairBit = 0x0008;
+ Box2D.Dynamics.b2DebugDraw.e_centerOfMassBit = 0x0010;
+ Box2D.Dynamics.b2DebugDraw.e_controllerBit = 0x0020;
+ });
+ b2DestructionListener.b2DestructionListener = function () {};
+ b2DestructionListener.prototype.SayGoodbyeJoint = function (joint) {}
+ b2DestructionListener.prototype.SayGoodbyeFixture = function (fixture) {}
+ b2FilterData.b2FilterData = function () {
+ this.categoryBits = 0x0001;
+ this.maskBits = 0xFFFF;
+ this.groupIndex = 0;
+ };
+ b2FilterData.prototype.Copy = function () {
+ var copy = new b2FilterData();
+ copy.categoryBits = this.categoryBits;
+ copy.maskBits = this.maskBits;
+ copy.groupIndex = this.groupIndex;
+ return copy;
+ }
+ b2Fixture.b2Fixture = function () {
+ this.m_filter = new b2FilterData();
+ };
+ b2Fixture.prototype.GetType = function () {
+ return this.m_shape.GetType();
+ }
+ b2Fixture.prototype.GetShape = function () {
+ return this.m_shape;
+ }
+ b2Fixture.prototype.SetSensor = function (sensor) {
+ if (this.m_isSensor == sensor) return;
+ this.m_isSensor = sensor;
+ if (this.m_body == null) return;
+ var edge = this.m_body.GetContactList();
+ while (edge) {
+ var contact = edge.contact;
+ var fixtureA = contact.GetFixtureA();
+ var fixtureB = contact.GetFixtureB();
+ if (fixtureA == this || fixtureB == this) contact.SetSensor(fixtureA.IsSensor() || fixtureB.IsSensor());
+ edge = edge.next;
+ }
+ }
+ b2Fixture.prototype.IsSensor = function () {
+ return this.m_isSensor;
+ }
+ b2Fixture.prototype.SetFilterData = function (filter) {
+ this.m_filter = filter.Copy();
+ if (this.m_body) return;
+ var edge = this.m_body.GetContactList();
+ while (edge) {
+ var contact = edge.contact;
+ var fixtureA = contact.GetFixtureA();
+ var fixtureB = contact.GetFixtureB();
+ if (fixtureA == this || fixtureB == this) contact.FlagForFiltering();
+ edge = edge.next;
+ }
+ }
+ b2Fixture.prototype.GetFilterData = function () {
+ return this.m_filter.Copy();
+ }
+ b2Fixture.prototype.GetBody = function () {
+ return this.m_body;
+ }
+ b2Fixture.prototype.GetNext = function () {
+ return this.m_next;
+ }
+ b2Fixture.prototype.GetUserData = function () {
+ return this.m_userData;
+ }
+ b2Fixture.prototype.SetUserData = function (data) {
+ this.m_userData = data;
+ }
+ b2Fixture.prototype.TestPoint = function (p) {
+ return this.m_shape.TestPoint(this.m_body.GetTransform(), p);
+ }
+ b2Fixture.prototype.RayCast = function (output, input) {
+ return this.m_shape.RayCast(output, input, this.m_body.GetTransform());
+ }
+ b2Fixture.prototype.GetMassData = function (massData) {
+ if (massData === undefined) massData = null;
+ if (massData == null) {
+ massData = new b2MassData();
+ }
+ this.m_shape.ComputeMass(massData, this.m_density);
+ return massData;
+ }
+ b2Fixture.prototype.SetDensity = function (density) {
+ if (density === undefined) density = 0;
+ this.m_density = density;
+ }
+ b2Fixture.prototype.GetDensity = function () {
+ return this.m_density;
+ }
+ b2Fixture.prototype.GetFriction = function () {
+ return this.m_friction;
+ }
+ b2Fixture.prototype.SetFriction = function (friction) {
+ if (friction === undefined) friction = 0;
+ this.m_friction = friction;
+ }
+ b2Fixture.prototype.GetRestitution = function () {
+ return this.m_restitution;
+ }
+ b2Fixture.prototype.SetRestitution = function (restitution) {
+ if (restitution === undefined) restitution = 0;
+ this.m_restitution = restitution;
+ }
+ b2Fixture.prototype.GetAABB = function () {
+ return this.m_aabb;
+ }
+ b2Fixture.prototype.b2Fixture = function () {
+ this.m_aabb = new b2AABB();
+ this.m_userData = null;
+ this.m_body = null;
+ this.m_next = null;
+ this.m_shape = null;
+ this.m_density = 0.0;
+ this.m_friction = 0.0;
+ this.m_restitution = 0.0;
+ }
+ b2Fixture.prototype.Create = function (body, xf, def) {
+ this.m_userData = def.userData;
+ this.m_friction = def.friction;
+ this.m_restitution = def.restitution;
+ this.m_body = body;
+ this.m_next = null;
+ this.m_filter = def.filter.Copy();
+ this.m_isSensor = def.isSensor;
+ this.m_shape = def.shape.Copy();
+ this.m_density = def.density;
+ }
+ b2Fixture.prototype.Destroy = function () {
+ this.m_shape = null;
+ }
+ b2Fixture.prototype.CreateProxy = function (broadPhase, xf) {
+ this.m_shape.ComputeAABB(this.m_aabb, xf);
+ this.m_proxy = broadPhase.CreateProxy(this.m_aabb, this);
+ }
+ b2Fixture.prototype.DestroyProxy = function (broadPhase) {
+ if (this.m_proxy == null) {
+ return;
+ }
+ broadPhase.DestroyProxy(this.m_proxy);
+ this.m_proxy = null;
+ }
+ b2Fixture.prototype.Synchronize = function (broadPhase, transform1, transform2) {
+ if (!this.m_proxy) return;
+ var aabb1 = new b2AABB();
+ var aabb2 = new b2AABB();
+ this.m_shape.ComputeAABB(aabb1, transform1);
+ this.m_shape.ComputeAABB(aabb2, transform2);
+ this.m_aabb.Combine(aabb1, aabb2);
+ var displacement = b2Math.SubtractVV(transform2.position, transform1.position);
+ broadPhase.MoveProxy(this.m_proxy, this.m_aabb, displacement);
+ }
+ b2FixtureDef.b2FixtureDef = function () {
+ this.filter = new b2FilterData();
+ };
+ b2FixtureDef.prototype.b2FixtureDef = function () {
+ this.shape = null;
+ this.userData = null;
+ this.friction = 0.2;
+ this.restitution = 0.0;
+ this.density = 0.0;
+ this.filter.categoryBits = 0x0001;
+ this.filter.maskBits = 0xFFFF;
+ this.filter.groupIndex = 0;
+ this.isSensor = false;
+ }
+ b2Island.b2Island = function () {};
+ b2Island.prototype.b2Island = function () {
+ this.m_bodies = new Vector();
+ this.m_contacts = new Vector();
+ this.m_joints = new Vector();
+ }
+ b2Island.prototype.Initialize = function (bodyCapacity, contactCapacity, jointCapacity, allocator, listener, contactSolver) {
+ if (bodyCapacity === undefined) bodyCapacity = 0;
+ if (contactCapacity === undefined) contactCapacity = 0;
+ if (jointCapacity === undefined) jointCapacity = 0;
+ var i = 0;
+ this.m_bodyCapacity = bodyCapacity;
+ this.m_contactCapacity = contactCapacity;
+ this.m_jointCapacity = jointCapacity;
+ this.m_bodyCount = 0;
+ this.m_contactCount = 0;
+ this.m_jointCount = 0;
+ this.m_allocator = allocator;
+ this.m_listener = listener;
+ this.m_contactSolver = contactSolver;
+ for (i = this.m_bodies.length;
+ i < bodyCapacity; i++)
+ this.m_bodies[i] = null;
+ for (i = this.m_contacts.length;
+ i < contactCapacity; i++)
+ this.m_contacts[i] = null;
+ for (i = this.m_joints.length;
+ i < jointCapacity; i++)
+ this.m_joints[i] = null;
+ }
+ b2Island.prototype.Clear = function () {
+ this.m_bodyCount = 0;
+ this.m_contactCount = 0;
+ this.m_jointCount = 0;
+ }
+ b2Island.prototype.Solve = function (step, gravity, allowSleep) {
+ var i = 0;
+ var j = 0;
+ var b;
+ var joint;
+ for (i = 0;
+ i < this.m_bodyCount; ++i) {
+ b = this.m_bodies[i];
+ if (b.GetType() != b2Body.b2_dynamicBody) continue;
+ b.m_linearVelocity.x += step.dt * (gravity.x + b.m_invMass * b.m_force.x);
+ b.m_linearVelocity.y += step.dt * (gravity.y + b.m_invMass * b.m_force.y);
+ b.m_angularVelocity += step.dt * b.m_invI * b.m_torque;
+ b.m_linearVelocity.Multiply(b2Math.Clamp(1.0 - step.dt * b.m_linearDamping, 0.0, 1.0));
+ b.m_angularVelocity *= b2Math.Clamp(1.0 - step.dt * b.m_angularDamping, 0.0, 1.0);
+ }
+ this.m_contactSolver.Initialize(step, this.m_contacts, this.m_contactCount, this.m_allocator);
+ var contactSolver = this.m_contactSolver;
+ contactSolver.InitVelocityConstraints(step);
+ for (i = 0;
+ i < this.m_jointCount; ++i) {
+ joint = this.m_joints[i];
+ joint.InitVelocityConstraints(step);
+ }
+ for (i = 0;
+ i < step.velocityIterations; ++i) {
+ for (j = 0;
+ j < this.m_jointCount; ++j) {
+ joint = this.m_joints[j];
+ joint.SolveVelocityConstraints(step);
+ }
+ contactSolver.SolveVelocityConstraints();
+ }
+ for (i = 0;
+ i < this.m_jointCount; ++i) {
+ joint = this.m_joints[i];
+ joint.FinalizeVelocityConstraints();
+ }
+ contactSolver.FinalizeVelocityConstraints();
+ for (i = 0;
+ i < this.m_bodyCount; ++i) {
+ b = this.m_bodies[i];
+ if (b.GetType() == b2Body.b2_staticBody) continue;
+ var translationX = step.dt * b.m_linearVelocity.x;
+ var translationY = step.dt * b.m_linearVelocity.y;
+ if ((translationX * translationX + translationY * translationY) > b2Settings.b2_maxTranslationSquared) {
+ b.m_linearVelocity.Normalize();
+ b.m_linearVelocity.x *= b2Settings.b2_maxTranslation * step.inv_dt;
+ b.m_linearVelocity.y *= b2Settings.b2_maxTranslation * step.inv_dt;
+ }
+ var rotation = step.dt * b.m_angularVelocity;
+ if (rotation * rotation > b2Settings.b2_maxRotationSquared) {
+ if (b.m_angularVelocity < 0.0) {
+ b.m_angularVelocity = (-b2Settings.b2_maxRotation * step.inv_dt);
+ }
+ else {
+ b.m_angularVelocity = b2Settings.b2_maxRotation * step.inv_dt;
+ }
+ }
+ b.m_sweep.c0.SetV(b.m_sweep.c);
+ b.m_sweep.a0 = b.m_sweep.a;
+ b.m_sweep.c.x += step.dt * b.m_linearVelocity.x;
+ b.m_sweep.c.y += step.dt * b.m_linearVelocity.y;
+ b.m_sweep.a += step.dt * b.m_angularVelocity;
+ b.SynchronizeTransform();
+ }
+ for (i = 0;
+ i < step.positionIterations; ++i) {
+ var contactsOkay = contactSolver.SolvePositionConstraints(b2Settings.b2_contactBaumgarte);
+ var jointsOkay = true;
+ for (j = 0;
+ j < this.m_jointCount; ++j) {
+ joint = this.m_joints[j];
+ var jointOkay = joint.SolvePositionConstraints(b2Settings.b2_contactBaumgarte);
+ jointsOkay = jointsOkay && jointOkay;
+ }
+ if (contactsOkay && jointsOkay) {
+ break;
+ }
+ }
+ this.Report(contactSolver.m_constraints);
+ if (allowSleep) {
+ var minSleepTime = Number.MAX_VALUE;
+ var linTolSqr = b2Settings.b2_linearSleepTolerance * b2Settings.b2_linearSleepTolerance;
+ var angTolSqr = b2Settings.b2_angularSleepTolerance * b2Settings.b2_angularSleepTolerance;
+ for (i = 0;
+ i < this.m_bodyCount; ++i) {
+ b = this.m_bodies[i];
+ if (b.GetType() == b2Body.b2_staticBody) {
+ continue;
+ }
+ if ((b.m_flags & b2Body.e_allowSleepFlag) == 0) {
+ b.m_sleepTime = 0.0;
+ minSleepTime = 0.0;
+ }
+ if ((b.m_flags & b2Body.e_allowSleepFlag) == 0 || b.m_angularVelocity * b.m_angularVelocity > angTolSqr || b2Math.Dot(b.m_linearVelocity, b.m_linearVelocity) > linTolSqr) {
+ b.m_sleepTime = 0.0;
+ minSleepTime = 0.0;
+ }
+ else {
+ b.m_sleepTime += step.dt;
+ minSleepTime = b2Math.Min(minSleepTime, b.m_sleepTime);
+ }
+ }
+ if (minSleepTime >= b2Settings.b2_timeToSleep) {
+ for (i = 0;
+ i < this.m_bodyCount; ++i) {
+ b = this.m_bodies[i];
+ b.SetAwake(false);
+ }
+ }
+ }
+ }
+ b2Island.prototype.SolveTOI = function (subStep) {
+ var i = 0;
+ var j = 0;
+ this.m_contactSolver.Initialize(subStep, this.m_contacts, this.m_contactCount, this.m_allocator);
+ var contactSolver = this.m_contactSolver;
+ for (i = 0;
+ i < this.m_jointCount; ++i) {
+ this.m_joints[i].InitVelocityConstraints(subStep);
+ }
+ for (i = 0;
+ i < subStep.velocityIterations; ++i) {
+ contactSolver.SolveVelocityConstraints();
+ for (j = 0;
+ j < this.m_jointCount; ++j) {
+ this.m_joints[j].SolveVelocityConstraints(subStep);
+ }
+ }
+ for (i = 0;
+ i < this.m_bodyCount; ++i) {
+ var b = this.m_bodies[i];
+ if (b.GetType() == b2Body.b2_staticBody) continue;
+ var translationX = subStep.dt * b.m_linearVelocity.x;
+ var translationY = subStep.dt * b.m_linearVelocity.y;
+ if ((translationX * translationX + translationY * translationY) > b2Settings.b2_maxTranslationSquared) {
+ b.m_linearVelocity.Normalize();
+ b.m_linearVelocity.x *= b2Settings.b2_maxTranslation * subStep.inv_dt;
+ b.m_linearVelocity.y *= b2Settings.b2_maxTranslation * subStep.inv_dt;
+ }
+ var rotation = subStep.dt * b.m_angularVelocity;
+ if (rotation * rotation > b2Settings.b2_maxRotationSquared) {
+ if (b.m_angularVelocity < 0.0) {
+ b.m_angularVelocity = (-b2Settings.b2_maxRotation * subStep.inv_dt);
+ }
+ else {
+ b.m_angularVelocity = b2Settings.b2_maxRotation * subStep.inv_dt;
+ }
+ }
+ b.m_sweep.c0.SetV(b.m_sweep.c);
+ b.m_sweep.a0 = b.m_sweep.a;
+ b.m_sweep.c.x += subStep.dt * b.m_linearVelocity.x;
+ b.m_sweep.c.y += subStep.dt * b.m_linearVelocity.y;
+ b.m_sweep.a += subStep.dt * b.m_angularVelocity;
+ b.SynchronizeTransform();
+ }
+ var k_toiBaumgarte = 0.75;
+ for (i = 0;
+ i < subStep.positionIterations; ++i) {
+ var contactsOkay = contactSolver.SolvePositionConstraints(k_toiBaumgarte);
+ var jointsOkay = true;
+ for (j = 0;
+ j < this.m_jointCount; ++j) {
+ var jointOkay = this.m_joints[j].SolvePositionConstraints(b2Settings.b2_contactBaumgarte);
+ jointsOkay = jointsOkay && jointOkay;
+ }
+ if (contactsOkay && jointsOkay) {
+ break;
+ }
+ }
+ this.Report(contactSolver.m_constraints);
+ }
+ b2Island.prototype.Report = function (constraints) {
+ if (this.m_listener == null) {
+ return;
+ }
+ for (var i = 0; i < this.m_contactCount; ++i) {
+ var c = this.m_contacts[i];
+ var cc = constraints[i];
+ for (var j = 0; j < cc.pointCount; ++j) {
+ b2Island.s_impulse.normalImpulses[j] = cc.points[j].normalImpulse;
+ b2Island.s_impulse.tangentImpulses[j] = cc.points[j].tangentImpulse;
+ }
+ this.m_listener.PostSolve(c, b2Island.s_impulse);
+ }
+ }
+ b2Island.prototype.AddBody = function (body) {
+ body.m_islandIndex = this.m_bodyCount;
+ this.m_bodies[this.m_bodyCount++] = body;
+ }
+ b2Island.prototype.AddContact = function (contact) {
+ this.m_contacts[this.m_contactCount++] = contact;
+ }
+ b2Island.prototype.AddJoint = function (joint) {
+ this.m_joints[this.m_jointCount++] = joint;
+ }
+ Box2D.postDefs.push(function () {
+ Box2D.Dynamics.b2Island.s_impulse = new b2ContactImpulse();
+ });
+ b2TimeStep.b2TimeStep = function () {};
+ b2TimeStep.prototype.Set = function (step) {
+ this.dt = step.dt;
+ this.inv_dt = step.inv_dt;
+ this.positionIterations = step.positionIterations;
+ this.velocityIterations = step.velocityIterations;
+ this.warmStarting = step.warmStarting;
+ }
+ b2World.b2World = function () {
+ this.s_stack = new Vector();
+ this.m_contactManager = new b2ContactManager();
+ this.m_contactSolver = new b2ContactSolver();
+ this.m_island = new b2Island();
+ };
+ b2World.prototype.b2World = function (gravity, doSleep) {
+ this.m_destructionListener = null;
+ this.m_debugDraw = null;
+ this.m_bodyList = null;
+ this.m_contactList = null;
+ this.m_jointList = null;
+ this.m_controllerList = null;
+ this.m_bodyCount = 0;
+ this.m_contactCount = 0;
+ this.m_jointCount = 0;
+ this.m_controllerCount = 0;
+ b2World.m_warmStarting = true;
+ b2World.m_continuousPhysics = true;
+ this.m_allowSleep = doSleep;
+ gravity.y = gravity.y;
+ this.m_gravity = gravity;
+ this.m_inv_dt0 = 0.0;
+ this.m_contactManager.m_world = this;
+ var bd = new b2BodyDef();
+ this.m_groundBody = this.CreateBody(bd);
+ }
+ b2World.prototype.SetDestructionListener = function (listener) {
+ this.m_destructionListener = listener;
+ }
+ b2World.prototype.SetContactFilter = function (filter) {
+ this.m_contactManager.m_contactFilter = filter;
+ }
+ b2World.prototype.SetContactListener = function (listener) {
+ this.m_contactManager.m_contactListener = listener;
+ }
+ b2World.prototype.SetDebugDraw = function (debugDraw) {
+ this.m_debugDraw = debugDraw;
+ }
+ b2World.prototype.SetBroadPhase = function (broadPhase) {
+ var oldBroadPhase = this.m_contactManager.m_broadPhase;
+ this.m_contactManager.m_broadPhase = broadPhase;
+ for (var b = this.m_bodyList; b; b = b.m_next) {
+ for (var f = b.m_fixtureList; f; f = f.m_next) {
+ f.m_proxy = broadPhase.CreateProxy(oldBroadPhase.GetFatAABB(f.m_proxy), f);
+ }
+ }
+ }
+ b2World.prototype.Validate = function () {
+ this.m_contactManager.m_broadPhase.Validate();
+ }
+ b2World.prototype.GetProxyCount = function () {
+ return this.m_contactManager.m_broadPhase.GetProxyCount();
+ }
+ b2World.prototype.CreateBody = function (def) {
+ if (this.IsLocked() == true) {
+ return null;
+ }
+ var b = new b2Body(def, this);
+ b.m_prev = null;
+ b.m_next = this.m_bodyList;
+ if (this.m_bodyList) {
+ this.m_bodyList.m_prev = b;
+ }
+ this.m_bodyList = b;
+ ++this.m_bodyCount;
+ return b;
+ }
+ b2World.prototype.DestroyBody = function (b) {
+ if (this.IsLocked() == true) {
+ return;
+ }
+ var jn = b.m_jointList;
+ while (jn) {
+ var jn0 = jn;
+ jn = jn.next;
+ if (this.m_destructionListener) {
+ this.m_destructionListener.SayGoodbyeJoint(jn0.joint);
+ }
+ this.DestroyJoint(jn0.joint);
+ }
+ var coe = b.m_controllerList;
+ while (coe) {
+ var coe0 = coe;
+ coe = coe.nextController;
+ coe0.controller.RemoveBody(b);
+ }
+ var ce = b.m_contactList;
+ while (ce) {
+ var ce0 = ce;
+ ce = ce.next;
+ this.m_contactManager.Destroy(ce0.contact);
+ }
+ b.m_contactList = null;
+ var f = b.m_fixtureList;
+ while (f) {
+ var f0 = f;
+ f = f.m_next;
+ if (this.m_destructionListener) {
+ this.m_destructionListener.SayGoodbyeFixture(f0);
+ }
+ f0.DestroyProxy(this.m_contactManager.m_broadPhase);
+ f0.Destroy();
+ }
+ b.m_fixtureList = null;
+ b.m_fixtureCount = 0;
+ if (b.m_prev) {
+ b.m_prev.m_next = b.m_next;
+ }
+ if (b.m_next) {
+ b.m_next.m_prev = b.m_prev;
+ }
+ if (b == this.m_bodyList) {
+ this.m_bodyList = b.m_next;
+ }--this.m_bodyCount;
+ }
+ b2World.prototype.CreateJoint = function (def) {
+ var j = b2Joint.Create(def, null);
+ j.m_prev = null;
+ j.m_next = this.m_jointList;
+ if (this.m_jointList) {
+ this.m_jointList.m_prev = j;
+ }
+ this.m_jointList = j;
+ ++this.m_jointCount;
+ j.m_edgeA.joint = j;
+ j.m_edgeA.other = j.m_bodyB;
+ j.m_edgeA.prev = null;
+ j.m_edgeA.next = j.m_bodyA.m_jointList;
+ if (j.m_bodyA.m_jointList) j.m_bodyA.m_jointList.prev = j.m_edgeA;
+ j.m_bodyA.m_jointList = j.m_edgeA;
+ j.m_edgeB.joint = j;
+ j.m_edgeB.other = j.m_bodyA;
+ j.m_edgeB.prev = null;
+ j.m_edgeB.next = j.m_bodyB.m_jointList;
+ if (j.m_bodyB.m_jointList) j.m_bodyB.m_jointList.prev = j.m_edgeB;
+ j.m_bodyB.m_jointList = j.m_edgeB;
+ var bodyA = def.bodyA;
+ var bodyB = def.bodyB;
+ if (def.collideConnected == false) {
+ var edge = bodyB.GetContactList();
+ while (edge) {
+ if (edge.other == bodyA) {
+ edge.contact.FlagForFiltering();
+ }
+ edge = edge.next;
+ }
+ }
+ return j;
+ }
+ b2World.prototype.DestroyJoint = function (j) {
+ var collideConnected = j.m_collideConnected;
+ if (j.m_prev) {
+ j.m_prev.m_next = j.m_next;
+ }
+ if (j.m_next) {
+ j.m_next.m_prev = j.m_prev;
+ }
+ if (j == this.m_jointList) {
+ this.m_jointList = j.m_next;
+ }
+ var bodyA = j.m_bodyA;
+ var bodyB = j.m_bodyB;
+ bodyA.SetAwake(true);
+ bodyB.SetAwake(true);
+ if (j.m_edgeA.prev) {
+ j.m_edgeA.prev.next = j.m_edgeA.next;
+ }
+ if (j.m_edgeA.next) {
+ j.m_edgeA.next.prev = j.m_edgeA.prev;
+ }
+ if (j.m_edgeA == bodyA.m_jointList) {
+ bodyA.m_jointList = j.m_edgeA.next;
+ }
+ j.m_edgeA.prev = null;
+ j.m_edgeA.next = null;
+ if (j.m_edgeB.prev) {
+ j.m_edgeB.prev.next = j.m_edgeB.next;
+ }
+ if (j.m_edgeB.next) {
+ j.m_edgeB.next.prev = j.m_edgeB.prev;
+ }
+ if (j.m_edgeB == bodyB.m_jointList) {
+ bodyB.m_jointList = j.m_edgeB.next;
+ }
+ j.m_edgeB.prev = null;
+ j.m_edgeB.next = null;
+ b2Joint.Destroy(j, null);
+ --this.m_jointCount;
+ if (collideConnected == false) {
+ var edge = bodyB.GetContactList();
+ while (edge) {
+ if (edge.other == bodyA) {
+ edge.contact.FlagForFiltering();
+ }
+ edge = edge.next;
+ }
+ }
+ }
+ b2World.prototype.AddController = function (c) {
+ c.m_next = this.m_controllerList;
+ c.m_prev = null;
+ this.m_controllerList = c;
+ c.m_world = this;
+ this.m_controllerCount++;
+ return c;
+ }
+ b2World.prototype.RemoveController = function (c) {
+ if (c.m_prev) c.m_prev.m_next = c.m_next;
+ if (c.m_next) c.m_next.m_prev = c.m_prev;
+ if (this.m_controllerList == c) this.m_controllerList = c.m_next;
+ this.m_controllerCount--;
+ }
+ b2World.prototype.CreateController = function (controller) {
+ if (controller.m_world != this) throw new Error("Controller can only be a member of one world");
+ controller.m_next = this.m_controllerList;
+ controller.m_prev = null;
+ if (this.m_controllerList) this.m_controllerList.m_prev = controller;
+ this.m_controllerList = controller;
+ ++this.m_controllerCount;
+ controller.m_world = this;
+ return controller;
+ }
+ b2World.prototype.DestroyController = function (controller) {
+ controller.Clear();
+ if (controller.m_next) controller.m_next.m_prev = controller.m_prev;
+ if (controller.m_prev) controller.m_prev.m_next = controller.m_next;
+ if (controller == this.m_controllerList) this.m_controllerList = controller.m_next;
+ --this.m_controllerCount;
+ }
+ b2World.prototype.SetWarmStarting = function (flag) {
+ b2World.m_warmStarting = flag;
+ }
+ b2World.prototype.SetContinuousPhysics = function (flag) {
+ b2World.m_continuousPhysics = flag;
+ }
+ b2World.prototype.GetBodyCount = function () {
+ return this.m_bodyCount;
+ }
+ b2World.prototype.GetJointCount = function () {
+ return this.m_jointCount;
+ }
+ b2World.prototype.GetContactCount = function () {
+ return this.m_contactCount;
+ }
+ b2World.prototype.SetGravity = function (gravity) {
+ this.m_gravity = gravity;
+ }
+ b2World.prototype.GetGravity = function () {
+ return this.m_gravity;
+ }
+ b2World.prototype.GetGroundBody = function () {
+ return this.m_groundBody;
+ }
+ b2World.prototype.Step = function (dt, velocityIterations, positionIterations) {
+ if (dt === undefined) dt = 0;
+ if (velocityIterations === undefined) velocityIterations = 0;
+ if (positionIterations === undefined) positionIterations = 0;
+ if (this.m_flags & b2World.e_newFixture) {
+ this.m_contactManager.FindNewContacts();
+ this.m_flags &= ~b2World.e_newFixture;
+ }
+ this.m_flags |= b2World.e_locked;
+ var step = b2World.s_timestep2;
+ step.dt = dt;
+ step.velocityIterations = velocityIterations;
+ step.positionIterations = positionIterations;
+ if (dt > 0.0) {
+ step.inv_dt = 1.0 / dt;
+ }
+ else {
+ step.inv_dt = 0.0;
+ }
+ step.dtRatio = this.m_inv_dt0 * dt;
+ step.warmStarting = b2World.m_warmStarting;
+ this.m_contactManager.Collide();
+ if (step.dt > 0.0) {
+ this.Solve(step);
+ }
+ if (b2World.m_continuousPhysics && step.dt > 0.0) {
+ this.SolveTOI(step);
+ }
+ if (step.dt > 0.0) {
+ this.m_inv_dt0 = step.inv_dt;
+ }
+ this.m_flags &= ~b2World.e_locked;
+ }
+ b2World.prototype.ClearForces = function () {
+ for (var body = this.m_bodyList; body; body = body.m_next) {
+ body.m_force.SetZero();
+ body.m_torque = 0.0;
+ }
+ }
+ b2World.prototype.DrawDebugData = function () {
+ if (this.m_debugDraw == null) {
+ return;
+ }
+ this.m_debugDraw.m_sprite.graphics.clear();
+ var flags = this.m_debugDraw.GetFlags();
+ var i = 0;
+ var b;
+ var f;
+ var s;
+ var j;
+ var bp;
+ var invQ = new b2Vec2;
+ var x1 = new b2Vec2;
+ var x2 = new b2Vec2;
+ var xf;
+ var b1 = new b2AABB();
+ var b2 = new b2AABB();
+ var vs = [new b2Vec2(), new b2Vec2(), new b2Vec2(), new b2Vec2()];
+ var color = new b2Color(0, 0, 0);
+ if (flags & b2DebugDraw.e_shapeBit) {
+ for (b = this.m_bodyList;
+ b; b = b.m_next) {
+ xf = b.m_xf;
+ for (f = b.GetFixtureList();
+ f; f = f.m_next) {
+ s = f.GetShape();
+ if (b.IsActive() == false) {
+ color.Set(0.5, 0.5, 0.3);
+ this.DrawShape(s, xf, color);
+ }
+ else if (b.GetType() == b2Body.b2_staticBody) {
+ color.Set(0.5, 0.9, 0.5);
+ this.DrawShape(s, xf, color);
+ }
+ else if (b.GetType() == b2Body.b2_kinematicBody) {
+ color.Set(0.5, 0.5, 0.9);
+ this.DrawShape(s, xf, color);
+ }
+ else if (b.IsAwake() == false) {
+ color.Set(0.6, 0.6, 0.6);
+ this.DrawShape(s, xf, color);
+ }
+ else {
+ color.Set(0.9, 0.7, 0.7);
+ this.DrawShape(s, xf, color);
+ }
+ }
+ }
+ }
+ if (flags & b2DebugDraw.e_jointBit) {
+ for (j = this.m_jointList;
+ j; j = j.m_next) {
+ this.DrawJoint(j);
+ }
+ }
+ if (flags & b2DebugDraw.e_controllerBit) {
+ for (var c = this.m_controllerList; c; c = c.m_next) {
+ c.Draw(this.m_debugDraw);
+ }
+ }
+ if (flags & b2DebugDraw.e_pairBit) {
+ color.Set(0.3, 0.9, 0.9);
+ for (var contact = this.m_contactManager.m_contactList; contact; contact = contact.GetNext()) {
+ var fixtureA = contact.GetFixtureA();
+ var fixtureB = contact.GetFixtureB();
+ var cA = fixtureA.GetAABB().GetCenter();
+ var cB = fixtureB.GetAABB().GetCenter();
+ this.m_debugDraw.DrawSegment(cA, cB, color);
+ }
+ }
+ if (flags & b2DebugDraw.e_aabbBit) {
+ bp = this.m_contactManager.m_broadPhase;
+ vs = [new b2Vec2(), new b2Vec2(), new b2Vec2(), new b2Vec2()];
+ for (b = this.m_bodyList;
+ b; b = b.GetNext()) {
+ if (b.IsActive() == false) {
+ continue;
+ }
+ for (f = b.GetFixtureList();
+ f; f = f.GetNext()) {
+ var aabb = bp.GetFatAABB(f.m_proxy);
+ vs[0].Set(aabb.lowerBound.x, aabb.lowerBound.y);
+ vs[1].Set(aabb.upperBound.x, aabb.lowerBound.y);
+ vs[2].Set(aabb.upperBound.x, aabb.upperBound.y);
+ vs[3].Set(aabb.lowerBound.x, aabb.upperBound.y);
+ this.m_debugDraw.DrawPolygon(vs, 4, color);
+ }
+ }
+ }
+ if (flags & b2DebugDraw.e_centerOfMassBit) {
+ for (b = this.m_bodyList;
+ b; b = b.m_next) {
+ xf = b2World.s_xf;
+ xf.R = b.m_xf.R;
+ xf.position = b.GetWorldCenter();
+ this.m_debugDraw.DrawTransform(xf);
+ }
+ }
+ }
+ b2World.prototype.QueryAABB = function (callback, aabb) {
+ var __this = this;
+ var broadPhase = __this.m_contactManager.m_broadPhase;
+
+ function WorldQueryWrapper(proxy) {
+ return callback(broadPhase.GetUserData(proxy));
+ };
+ broadPhase.Query(WorldQueryWrapper, aabb);
+ }
+ b2World.prototype.QueryShape = function (callback, shape, transform) {
+ var __this = this;
+ if (transform === undefined) transform = null;
+ if (transform == null) {
+ transform = new b2Transform();
+ transform.SetIdentity();
+ }
+ var broadPhase = __this.m_contactManager.m_broadPhase;
+
+ function WorldQueryWrapper(proxy) {
+ var fixture = (broadPhase.GetUserData(proxy) instanceof b2Fixture ? broadPhase.GetUserData(proxy) : null);
+ if (b2Shape.TestOverlap(shape, transform, fixture.GetShape(), fixture.GetBody().GetTransform())) return callback(fixture);
+ return true;
+ };
+ var aabb = new b2AABB();
+ shape.ComputeAABB(aabb, transform);
+ broadPhase.Query(WorldQueryWrapper, aabb);
+ }
+ b2World.prototype.QueryPoint = function (callback, p) {
+ var __this = this;
+ var broadPhase = __this.m_contactManager.m_broadPhase;
+
+ function WorldQueryWrapper(proxy) {
+ var fixture = (broadPhase.GetUserData(proxy) instanceof b2Fixture ? broadPhase.GetUserData(proxy) : null);
+ if (fixture.TestPoint(p)) return callback(fixture);
+ return true;
+ };
+ var aabb = new b2AABB();
+ aabb.lowerBound.Set(p.x - b2Settings.b2_linearSlop, p.y - b2Settings.b2_linearSlop);
+ aabb.upperBound.Set(p.x + b2Settings.b2_linearSlop, p.y + b2Settings.b2_linearSlop);
+ broadPhase.Query(WorldQueryWrapper, aabb);
+ }
+ b2World.prototype.RayCast = function (callback, point1, point2) {
+ var __this = this;
+ var broadPhase = __this.m_contactManager.m_broadPhase;
+ var output = new b2RayCastOutput;
+
+ function RayCastWrapper(input, proxy) {
+ var userData = broadPhase.GetUserData(proxy);
+ var fixture = (userData instanceof b2Fixture ? userData : null);
+ var hit = fixture.RayCast(output, input);
+ if (hit) {
+ var fraction = output.fraction;
+ var point = new b2Vec2((1.0 - fraction) * point1.x + fraction * point2.x, (1.0 - fraction) * point1.y + fraction * point2.y);
+ return callback(fixture, point, output.normal, fraction);
+ }
+ return input.maxFraction;
+ };
+ var input = new b2RayCastInput(point1, point2);
+ broadPhase.RayCast(RayCastWrapper, input);
+ }
+ b2World.prototype.RayCastOne = function (point1, point2) {
+ var __this = this;
+ var result;
+
+ function RayCastOneWrapper(fixture, point, normal, fraction) {
+ if (fraction === undefined) fraction = 0;
+ result = fixture;
+ return fraction;
+ };
+ __this.RayCast(RayCastOneWrapper, point1, point2);
+ return result;
+ }
+ b2World.prototype.RayCastAll = function (point1, point2) {
+ var __this = this;
+ var result = new Vector();
+
+ function RayCastAllWrapper(fixture, point, normal, fraction) {
+ if (fraction === undefined) fraction = 0;
+ result[result.length] = fixture;
+ return 1;
+ };
+ __this.RayCast(RayCastAllWrapper, point1, point2);
+ return result;
+ }
+ b2World.prototype.GetBodyList = function () {
+ return this.m_bodyList;
+ }
+ b2World.prototype.GetJointList = function () {
+ return this.m_jointList;
+ }
+ b2World.prototype.GetContactList = function () {
+ return this.m_contactList;
+ }
+ b2World.prototype.IsLocked = function () {
+ return (this.m_flags & b2World.e_locked) > 0;
+ }
+ b2World.prototype.Solve = function (step) {
+ var b;
+ for (var controller = this.m_controllerList; controller; controller = controller.m_next) {
+ controller.Step(step);
+ }
+ var island = this.m_island;
+ island.Initialize(this.m_bodyCount, this.m_contactCount, this.m_jointCount, null, this.m_contactManager.m_contactListener, this.m_contactSolver);
+ for (b = this.m_bodyList;
+ b; b = b.m_next) {
+ b.m_flags &= ~b2Body.e_islandFlag;
+ }
+ for (var c = this.m_contactList; c; c = c.m_next) {
+ c.m_flags &= ~b2Contact.e_islandFlag;
+ }
+ for (var j = this.m_jointList; j; j = j.m_next) {
+ j.m_islandFlag = false;
+ }
+ var stackSize = parseInt(this.m_bodyCount);
+ var stack = this.s_stack;
+ for (var seed = this.m_bodyList; seed; seed = seed.m_next) {
+ if (seed.m_flags & b2Body.e_islandFlag) {
+ continue;
+ }
+ if (seed.IsAwake() == false || seed.IsActive() == false) {
+ continue;
+ }
+ if (seed.GetType() == b2Body.b2_staticBody) {
+ continue;
+ }
+ island.Clear();
+ var stackCount = 0;
+ stack[stackCount++] = seed;
+ seed.m_flags |= b2Body.e_islandFlag;
+ while (stackCount > 0) {
+ b = stack[--stackCount];
+ island.AddBody(b);
+ if (b.IsAwake() == false) {
+ b.SetAwake(true);
+ }
+ if (b.GetType() == b2Body.b2_staticBody) {
+ continue;
+ }
+ var other;
+ for (var ce = b.m_contactList; ce; ce = ce.next) {
+ if (ce.contact.m_flags & b2Contact.e_islandFlag) {
+ continue;
+ }
+ if (ce.contact.IsSensor() == true || ce.contact.IsEnabled() == false || ce.contact.IsTouching() == false) {
+ continue;
+ }
+ island.AddContact(ce.contact);
+ ce.contact.m_flags |= b2Contact.e_islandFlag;
+ other = ce.other;
+ if (other.m_flags & b2Body.e_islandFlag) {
+ continue;
+ }
+ stack[stackCount++] = other;
+ other.m_flags |= b2Body.e_islandFlag;
+ }
+ for (var jn = b.m_jointList; jn; jn = jn.next) {
+ if (jn.joint.m_islandFlag == true) {
+ continue;
+ }
+ other = jn.other;
+ if (other.IsActive() == false) {
+ continue;
+ }
+ island.AddJoint(jn.joint);
+ jn.joint.m_islandFlag = true;
+ if (other.m_flags & b2Body.e_islandFlag) {
+ continue;
+ }
+ stack[stackCount++] = other;
+ other.m_flags |= b2Body.e_islandFlag;
+ }
+ }
+ island.Solve(step, this.m_gravity, this.m_allowSleep);
+ for (var i = 0; i < island.m_bodyCount; ++i) {
+ b = island.m_bodies[i];
+ if (b.GetType() == b2Body.b2_staticBody) {
+ b.m_flags &= ~b2Body.e_islandFlag;
+ }
+ }
+ }
+ for (i = 0;
+ i < stack.length; ++i) {
+ if (!stack[i]) break;
+ stack[i] = null;
+ }
+ for (b = this.m_bodyList;
+ b; b = b.m_next) {
+ if (b.IsAwake() == false || b.IsActive() == false) {
+ continue;
+ }
+ if (b.GetType() == b2Body.b2_staticBody) {
+ continue;
+ }
+ b.SynchronizeFixtures();
+ }
+ this.m_contactManager.FindNewContacts();
+ }
+ b2World.prototype.SolveTOI = function (step) {
+ var b;
+ var fA;
+ var fB;
+ var bA;
+ var bB;
+ var cEdge;
+ var j;
+ var island = this.m_island;
+ island.Initialize(this.m_bodyCount, b2Settings.b2_maxTOIContactsPerIsland, b2Settings.b2_maxTOIJointsPerIsland, null, this.m_contactManager.m_contactListener, this.m_contactSolver);
+ var queue = b2World.s_queue;
+ for (b = this.m_bodyList;
+ b; b = b.m_next) {
+ b.m_flags &= ~b2Body.e_islandFlag;
+ b.m_sweep.t0 = 0.0;
+ }
+ var c;
+ for (c = this.m_contactList;
+ c; c = c.m_next) {
+ c.m_flags &= ~ (b2Contact.e_toiFlag | b2Contact.e_islandFlag);
+ }
+ for (j = this.m_jointList;
+ j; j = j.m_next) {
+ j.m_islandFlag = false;
+ }
+ for (;;) {
+ var minContact = null;
+ var minTOI = 1.0;
+ for (c = this.m_contactList;
+ c; c = c.m_next) {
+ if (c.IsSensor() == true || c.IsEnabled() == false || c.IsContinuous() == false) {
+ continue;
+ }
+ var toi = 1.0;
+ if (c.m_flags & b2Contact.e_toiFlag) {
+ toi = c.m_toi;
+ }
+ else {
+ fA = c.m_fixtureA;
+ fB = c.m_fixtureB;
+ bA = fA.m_body;
+ bB = fB.m_body;
+ if ((bA.GetType() != b2Body.b2_dynamicBody || bA.IsAwake() == false) && (bB.GetType() != b2Body.b2_dynamicBody || bB.IsAwake() == false)) {
+ continue;
+ }
+ var t0 = bA.m_sweep.t0;
+ if (bA.m_sweep.t0 < bB.m_sweep.t0) {
+ t0 = bB.m_sweep.t0;
+ bA.m_sweep.Advance(t0);
+ }
+ else if (bB.m_sweep.t0 < bA.m_sweep.t0) {
+ t0 = bA.m_sweep.t0;
+ bB.m_sweep.Advance(t0);
+ }
+ toi = c.ComputeTOI(bA.m_sweep, bB.m_sweep);
+ b2Settings.b2Assert(0.0 <= toi && toi <= 1.0);
+ if (toi > 0.0 && toi < 1.0) {
+ toi = (1.0 - toi) * t0 + toi;
+ if (toi > 1) toi = 1;
+ }
+ c.m_toi = toi;
+ c.m_flags |= b2Contact.e_toiFlag;
+ }
+ if (Number.MIN_VALUE < toi && toi < minTOI) {
+ minContact = c;
+ minTOI = toi;
+ }
+ }
+ if (minContact == null || 1.0 - 100.0 * Number.MIN_VALUE < minTOI) {
+ break;
+ }
+ fA = minContact.m_fixtureA;
+ fB = minContact.m_fixtureB;
+ bA = fA.m_body;
+ bB = fB.m_body;
+ b2World.s_backupA.Set(bA.m_sweep);
+ b2World.s_backupB.Set(bB.m_sweep);
+ bA.Advance(minTOI);
+ bB.Advance(minTOI);
+ minContact.Update(this.m_contactManager.m_contactListener);
+ minContact.m_flags &= ~b2Contact.e_toiFlag;
+ if (minContact.IsSensor() == true || minContact.IsEnabled() == false) {
+ bA.m_sweep.Set(b2World.s_backupA);
+ bB.m_sweep.Set(b2World.s_backupB);
+ bA.SynchronizeTransform();
+ bB.SynchronizeTransform();
+ continue;
+ }
+ if (minContact.IsTouching() == false) {
+ continue;
+ }
+ var seed = bA;
+ if (seed.GetType() != b2Body.b2_dynamicBody) {
+ seed = bB;
+ }
+ island.Clear();
+ var queueStart = 0;
+ var queueSize = 0;
+ queue[queueStart + queueSize++] = seed;
+ seed.m_flags |= b2Body.e_islandFlag;
+ while (queueSize > 0) {
+ b = queue[queueStart++];
+ --queueSize;
+ island.AddBody(b);
+ if (b.IsAwake() == false) {
+ b.SetAwake(true);
+ }
+ if (b.GetType() != b2Body.b2_dynamicBody) {
+ continue;
+ }
+ for (cEdge = b.m_contactList;
+ cEdge; cEdge = cEdge.next) {
+ if (island.m_contactCount == island.m_contactCapacity) {
+ break;
+ }
+ if (cEdge.contact.m_flags & b2Contact.e_islandFlag) {
+ continue;
+ }
+ if (cEdge.contact.IsSensor() == true || cEdge.contact.IsEnabled() == false || cEdge.contact.IsTouching() == false) {
+ continue;
+ }
+ island.AddContact(cEdge.contact);
+ cEdge.contact.m_flags |= b2Contact.e_islandFlag;
+ var other = cEdge.other;
+ if (other.m_flags & b2Body.e_islandFlag) {
+ continue;
+ }
+ if (other.GetType() != b2Body.b2_staticBody) {
+ other.Advance(minTOI);
+ other.SetAwake(true);
+ }
+ queue[queueStart + queueSize] = other;
+ ++queueSize;
+ other.m_flags |= b2Body.e_islandFlag;
+ }
+ for (var jEdge = b.m_jointList; jEdge; jEdge = jEdge.next) {
+ if (island.m_jointCount == island.m_jointCapacity) continue;
+ if (jEdge.joint.m_islandFlag == true) continue;
+ other = jEdge.other;
+ if (other.IsActive() == false) {
+ continue;
+ }
+ island.AddJoint(jEdge.joint);
+ jEdge.joint.m_islandFlag = true;
+ if (other.m_flags & b2Body.e_islandFlag) continue;
+ if (other.GetType() != b2Body.b2_staticBody) {
+ other.Advance(minTOI);
+ other.SetAwake(true);
+ }
+ queue[queueStart + queueSize] = other;
+ ++queueSize;
+ other.m_flags |= b2Body.e_islandFlag;
+ }
+ }
+ var subStep = b2World.s_timestep;
+ subStep.warmStarting = false;
+ subStep.dt = (1.0 - minTOI) * step.dt;
+ subStep.inv_dt = 1.0 / subStep.dt;
+ subStep.dtRatio = 0.0;
+ subStep.velocityIterations = step.velocityIterations;
+ subStep.positionIterations = step.positionIterations;
+ island.SolveTOI(subStep);
+ var i = 0;
+ for (i = 0;
+ i < island.m_bodyCount; ++i) {
+ b = island.m_bodies[i];
+ b.m_flags &= ~b2Body.e_islandFlag;
+ if (b.IsAwake() == false) {
+ continue;
+ }
+ if (b.GetType() != b2Body.b2_dynamicBody) {
+ continue;
+ }
+ b.SynchronizeFixtures();
+ for (cEdge = b.m_contactList;
+ cEdge; cEdge = cEdge.next) {
+ cEdge.contact.m_flags &= ~b2Contact.e_toiFlag;
+ }
+ }
+ for (i = 0;
+ i < island.m_contactCount; ++i) {
+ c = island.m_contacts[i];
+ c.m_flags &= ~ (b2Contact.e_toiFlag | b2Contact.e_islandFlag);
+ }
+ for (i = 0;
+ i < island.m_jointCount; ++i) {
+ j = island.m_joints[i];
+ j.m_islandFlag = false;
+ }
+ this.m_contactManager.FindNewContacts();
+ }
+ }
+ b2World.prototype.DrawJoint = function (joint) {
+ var b1 = joint.GetBodyA();
+ var b2 = joint.GetBodyB();
+ var xf1 = b1.m_xf;
+ var xf2 = b2.m_xf;
+ var x1 = xf1.position;
+ var x2 = xf2.position;
+ var p1 = joint.GetAnchorA();
+ var p2 = joint.GetAnchorB();
+ var color = b2World.s_jointColor;
+ switch (joint.m_type) {
+ case b2Joint.e_distanceJoint:
+ this.m_debugDraw.DrawSegment(p1, p2, color);
+ break;
+ case b2Joint.e_pulleyJoint:
+ {
+ var pulley = ((joint instanceof b2PulleyJoint ? joint : null));
+ var s1 = pulley.GetGroundAnchorA();
+ var s2 = pulley.GetGroundAnchorB();
+ this.m_debugDraw.DrawSegment(s1, p1, color);
+ this.m_debugDraw.DrawSegment(s2, p2, color);
+ this.m_debugDraw.DrawSegment(s1, s2, color);
+ }
+ break;
+ case b2Joint.e_mouseJoint:
+ this.m_debugDraw.DrawSegment(p1, p2, color);
+ break;
+ default:
+ if (b1 != this.m_groundBody) this.m_debugDraw.DrawSegment(x1, p1, color);
+ this.m_debugDraw.DrawSegment(p1, p2, color);
+ if (b2 != this.m_groundBody) this.m_debugDraw.DrawSegment(x2, p2, color);
+ }
+ }
+ b2World.prototype.DrawShape = function (shape, xf, color) {
+ switch (shape.m_type) {
+ case b2Shape.e_circleShape:
+ {
+ var circle = ((shape instanceof b2CircleShape ? shape : null));
+ var center = b2Math.MulX(xf, circle.m_p);
+ var radius = circle.m_radius;
+ var axis = xf.R.col1;
+ this.m_debugDraw.DrawSolidCircle(center, radius, axis, color);
+ }
+ break;
+ case b2Shape.e_polygonShape:
+ {
+ var i = 0;
+ var poly = ((shape instanceof b2PolygonShape ? shape : null));
+ var vertexCount = parseInt(poly.GetVertexCount());
+ var localVertices = poly.GetVertices();
+ var vertices = new Vector(vertexCount);
+ for (i = 0;
+ i < vertexCount; ++i) {
+ vertices[i] = b2Math.MulX(xf, localVertices[i]);
+ }
+ this.m_debugDraw.DrawSolidPolygon(vertices, vertexCount, color);
+ }
+ break;
+ case b2Shape.e_edgeShape:
+ {
+ var edge = (shape instanceof b2EdgeShape ? shape : null);
+ this.m_debugDraw.DrawSegment(b2Math.MulX(xf, edge.GetVertex1()), b2Math.MulX(xf, edge.GetVertex2()), color);
+ }
+ break;
+ }
+ }
+ Box2D.postDefs.push(function () {
+ Box2D.Dynamics.b2World.s_timestep2 = new b2TimeStep();
+ Box2D.Dynamics.b2World.s_xf = new b2Transform();
+ Box2D.Dynamics.b2World.s_backupA = new b2Sweep();
+ Box2D.Dynamics.b2World.s_backupB = new b2Sweep();
+ Box2D.Dynamics.b2World.s_timestep = new b2TimeStep();
+ Box2D.Dynamics.b2World.s_queue = new Vector();
+ Box2D.Dynamics.b2World.s_jointColor = new b2Color(0.5, 0.8, 0.8);
+ Box2D.Dynamics.b2World.e_newFixture = 0x0001;
+ Box2D.Dynamics.b2World.e_locked = 0x0002;
+ });
+})();
+(function () {
+ var b2CircleShape = Box2D.Collision.Shapes.b2CircleShape,
+ b2EdgeChainDef = Box2D.Collision.Shapes.b2EdgeChainDef,
+ b2EdgeShape = Box2D.Collision.Shapes.b2EdgeShape,
+ b2MassData = Box2D.Collision.Shapes.b2MassData,
+ b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape,
+ b2Shape = Box2D.Collision.Shapes.b2Shape,
+ b2CircleContact = Box2D.Dynamics.Contacts.b2CircleContact,
+ b2Contact = Box2D.Dynamics.Contacts.b2Contact,
+ b2ContactConstraint = Box2D.Dynamics.Contacts.b2ContactConstraint,
+ b2ContactConstraintPoint = Box2D.Dynamics.Contacts.b2ContactConstraintPoint,
+ b2ContactEdge = Box2D.Dynamics.Contacts.b2ContactEdge,
+ b2ContactFactory = Box2D.Dynamics.Contacts.b2ContactFactory,
+ b2ContactRegister = Box2D.Dynamics.Contacts.b2ContactRegister,
+ b2ContactResult = Box2D.Dynamics.Contacts.b2ContactResult,
+ b2ContactSolver = Box2D.Dynamics.Contacts.b2ContactSolver,
+ b2EdgeAndCircleContact = Box2D.Dynamics.Contacts.b2EdgeAndCircleContact,
+ b2NullContact = Box2D.Dynamics.Contacts.b2NullContact,
+ b2PolyAndCircleContact = Box2D.Dynamics.Contacts.b2PolyAndCircleContact,
+ b2PolyAndEdgeContact = Box2D.Dynamics.Contacts.b2PolyAndEdgeContact,
+ b2PolygonContact = Box2D.Dynamics.Contacts.b2PolygonContact,
+ b2PositionSolverManifold = Box2D.Dynamics.Contacts.b2PositionSolverManifold,
+ b2Body = Box2D.Dynamics.b2Body,
+ b2BodyDef = Box2D.Dynamics.b2BodyDef,
+ b2ContactFilter = Box2D.Dynamics.b2ContactFilter,
+ b2ContactImpulse = Box2D.Dynamics.b2ContactImpulse,
+ b2ContactListener = Box2D.Dynamics.b2ContactListener,
+ b2ContactManager = Box2D.Dynamics.b2ContactManager,
+ b2DebugDraw = Box2D.Dynamics.b2DebugDraw,
+ b2DestructionListener = Box2D.Dynamics.b2DestructionListener,
+ b2FilterData = Box2D.Dynamics.b2FilterData,
+ b2Fixture = Box2D.Dynamics.b2Fixture,
+ b2FixtureDef = Box2D.Dynamics.b2FixtureDef,
+ b2Island = Box2D.Dynamics.b2Island,
+ b2TimeStep = Box2D.Dynamics.b2TimeStep,
+ b2World = Box2D.Dynamics.b2World,
+ b2Color = Box2D.Common.b2Color,
+ b2internal = Box2D.Common.b2internal,
+ b2Settings = Box2D.Common.b2Settings,
+ b2Mat22 = Box2D.Common.Math.b2Mat22,
+ b2Mat33 = Box2D.Common.Math.b2Mat33,
+ b2Math = Box2D.Common.Math.b2Math,
+ b2Sweep = Box2D.Common.Math.b2Sweep,
+ b2Transform = Box2D.Common.Math.b2Transform,
+ b2Vec2 = Box2D.Common.Math.b2Vec2,
+ b2Vec3 = Box2D.Common.Math.b2Vec3,
+ b2AABB = Box2D.Collision.b2AABB,
+ b2Bound = Box2D.Collision.b2Bound,
+ b2BoundValues = Box2D.Collision.b2BoundValues,
+ b2Collision = Box2D.Collision.b2Collision,
+ b2ContactID = Box2D.Collision.b2ContactID,
+ b2ContactPoint = Box2D.Collision.b2ContactPoint,
+ b2Distance = Box2D.Collision.b2Distance,
+ b2DistanceInput = Box2D.Collision.b2DistanceInput,
+ b2DistanceOutput = Box2D.Collision.b2DistanceOutput,
+ b2DistanceProxy = Box2D.Collision.b2DistanceProxy,
+ b2DynamicTree = Box2D.Collision.b2DynamicTree,
+ b2DynamicTreeBroadPhase = Box2D.Collision.b2DynamicTreeBroadPhase,
+ b2DynamicTreeNode = Box2D.Collision.b2DynamicTreeNode,
+ b2DynamicTreePair = Box2D.Collision.b2DynamicTreePair,
+ b2Manifold = Box2D.Collision.b2Manifold,
+ b2ManifoldPoint = Box2D.Collision.b2ManifoldPoint,
+ b2Point = Box2D.Collision.b2Point,
+ b2RayCastInput = Box2D.Collision.b2RayCastInput,
+ b2RayCastOutput = Box2D.Collision.b2RayCastOutput,
+ b2Segment = Box2D.Collision.b2Segment,
+ b2SeparationFunction = Box2D.Collision.b2SeparationFunction,
+ b2Simplex = Box2D.Collision.b2Simplex,
+ b2SimplexCache = Box2D.Collision.b2SimplexCache,
+ b2SimplexVertex = Box2D.Collision.b2SimplexVertex,
+ b2TimeOfImpact = Box2D.Collision.b2TimeOfImpact,
+ b2TOIInput = Box2D.Collision.b2TOIInput,
+ b2WorldManifold = Box2D.Collision.b2WorldManifold,
+ ClipVertex = Box2D.Collision.ClipVertex,
+ Features = Box2D.Collision.Features,
+ IBroadPhase = Box2D.Collision.IBroadPhase;
+
+ Box2D.inherit(b2CircleContact, Box2D.Dynamics.Contacts.b2Contact);
+ b2CircleContact.prototype.__super = Box2D.Dynamics.Contacts.b2Contact.prototype;
+ b2CircleContact.b2CircleContact = function () {
+ Box2D.Dynamics.Contacts.b2Contact.b2Contact.apply(this, arguments);
+ };
+ b2CircleContact.Create = function (allocator) {
+ return new b2CircleContact();
+ }
+ b2CircleContact.Destroy = function (contact, allocator) {}
+ b2CircleContact.prototype.Reset = function (fixtureA, fixtureB) {
+ this.__super.Reset.call(this, fixtureA, fixtureB);
+ }
+ b2CircleContact.prototype.Evaluate = function () {
+ var bA = this.m_fixtureA.GetBody();
+ var bB = this.m_fixtureB.GetBody();
+ b2Collision.CollideCircles(this.m_manifold, (this.m_fixtureA.GetShape() instanceof b2CircleShape ? this.m_fixtureA.GetShape() : null), bA.m_xf, (this.m_fixtureB.GetShape() instanceof b2CircleShape ? this.m_fixtureB.GetShape() : null), bB.m_xf);
+ }
+ b2Contact.b2Contact = function () {
+ this.m_nodeA = new b2ContactEdge();
+ this.m_nodeB = new b2ContactEdge();
+ this.m_manifold = new b2Manifold();
+ this.m_oldManifold = new b2Manifold();
+ };
+ b2Contact.prototype.GetManifold = function () {
+ return this.m_manifold;
+ }
+ b2Contact.prototype.GetWorldManifold = function (worldManifold) {
+ var bodyA = this.m_fixtureA.GetBody();
+ var bodyB = this.m_fixtureB.GetBody();
+ var shapeA = this.m_fixtureA.GetShape();
+ var shapeB = this.m_fixtureB.GetShape();
+ worldManifold.Initialize(this.m_manifold, bodyA.GetTransform(), shapeA.m_radius, bodyB.GetTransform(), shapeB.m_radius);
+ }
+ b2Contact.prototype.IsTouching = function () {
+ return (this.m_flags & b2Contact.e_touchingFlag) == b2Contact.e_touchingFlag;
+ }
+ b2Contact.prototype.IsContinuous = function () {
+ return (this.m_flags & b2Contact.e_continuousFlag) == b2Contact.e_continuousFlag;
+ }
+ b2Contact.prototype.SetSensor = function (sensor) {
+ if (sensor) {
+ this.m_flags |= b2Contact.e_sensorFlag;
+ }
+ else {
+ this.m_flags &= ~b2Contact.e_sensorFlag;
+ }
+ }
+ b2Contact.prototype.IsSensor = function () {
+ return (this.m_flags & b2Contact.e_sensorFlag) == b2Contact.e_sensorFlag;
+ }
+ b2Contact.prototype.SetEnabled = function (flag) {
+ if (flag) {
+ this.m_flags |= b2Contact.e_enabledFlag;
+ }
+ else {
+ this.m_flags &= ~b2Contact.e_enabledFlag;
+ }
+ }
+ b2Contact.prototype.IsEnabled = function () {
+ return (this.m_flags & b2Contact.e_enabledFlag) == b2Contact.e_enabledFlag;
+ }
+ b2Contact.prototype.GetNext = function () {
+ return this.m_next;
+ }
+ b2Contact.prototype.GetFixtureA = function () {
+ return this.m_fixtureA;
+ }
+ b2Contact.prototype.GetFixtureB = function () {
+ return this.m_fixtureB;
+ }
+ b2Contact.prototype.FlagForFiltering = function () {
+ this.m_flags |= b2Contact.e_filterFlag;
+ }
+ b2Contact.prototype.b2Contact = function () {}
+ b2Contact.prototype.Reset = function (fixtureA, fixtureB) {
+ if (fixtureA === undefined) fixtureA = null;
+ if (fixtureB === undefined) fixtureB = null;
+ this.m_flags = b2Contact.e_enabledFlag;
+ if (!fixtureA || !fixtureB) {
+ this.m_fixtureA = null;
+ this.m_fixtureB = null;
+ return;
+ }
+ if (fixtureA.IsSensor() || fixtureB.IsSensor()) {
+ this.m_flags |= b2Contact.e_sensorFlag;
+ }
+ var bodyA = fixtureA.GetBody();
+ var bodyB = fixtureB.GetBody();
+ if (bodyA.GetType() != b2Body.b2_dynamicBody || bodyA.IsBullet() || bodyB.GetType() != b2Body.b2_dynamicBody || bodyB.IsBullet()) {
+ this.m_flags |= b2Contact.e_continuousFlag;
+ }
+ this.m_fixtureA = fixtureA;
+ this.m_fixtureB = fixtureB;
+ this.m_manifold.m_pointCount = 0;
+ this.m_prev = null;
+ this.m_next = null;
+ this.m_nodeA.contact = null;
+ this.m_nodeA.prev = null;
+ this.m_nodeA.next = null;
+ this.m_nodeA.other = null;
+ this.m_nodeB.contact = null;
+ this.m_nodeB.prev = null;
+ this.m_nodeB.next = null;
+ this.m_nodeB.other = null;
+ }
+ b2Contact.prototype.Update = function (listener) {
+ var tManifold = this.m_oldManifold;
+ this.m_oldManifold = this.m_manifold;
+ this.m_manifold = tManifold;
+ this.m_flags |= b2Contact.e_enabledFlag;
+ var touching = false;
+ var wasTouching = (this.m_flags & b2Contact.e_touchingFlag) == b2Contact.e_touchingFlag;
+ var bodyA = this.m_fixtureA.m_body;
+ var bodyB = this.m_fixtureB.m_body;
+ var aabbOverlap = this.m_fixtureA.m_aabb.TestOverlap(this.m_fixtureB.m_aabb);
+ if (this.m_flags & b2Contact.e_sensorFlag) {
+ if (aabbOverlap) {
+ var shapeA = this.m_fixtureA.GetShape();
+ var shapeB = this.m_fixtureB.GetShape();
+ var xfA = bodyA.GetTransform();
+ var xfB = bodyB.GetTransform();
+ touching = b2Shape.TestOverlap(shapeA, xfA, shapeB, xfB);
+ }
+ this.m_manifold.m_pointCount = 0;
+ }
+ else {
+ if (bodyA.GetType() != b2Body.b2_dynamicBody || bodyA.IsBullet() || bodyB.GetType() != b2Body.b2_dynamicBody || bodyB.IsBullet()) {
+ this.m_flags |= b2Contact.e_continuousFlag;
+ }
+ else {
+ this.m_flags &= ~b2Contact.e_continuousFlag;
+ }
+ if (aabbOverlap) {
+ this.Evaluate();
+ touching = this.m_manifold.m_pointCount > 0;
+ for (var i = 0; i < this.m_manifold.m_pointCount; ++i) {
+ var mp2 = this.m_manifold.m_points[i];
+ mp2.m_normalImpulse = 0.0;
+ mp2.m_tangentImpulse = 0.0;
+ var id2 = mp2.m_id;
+ for (var j = 0; j < this.m_oldManifold.m_pointCount; ++j) {
+ var mp1 = this.m_oldManifold.m_points[j];
+ if (mp1.m_id.key == id2.key) {
+ mp2.m_normalImpulse = mp1.m_normalImpulse;
+ mp2.m_tangentImpulse = mp1.m_tangentImpulse;
+ break;
+ }
+ }
+ }
+ }
+ else {
+ this.m_manifold.m_pointCount = 0;
+ }
+ if (touching != wasTouching) {
+ bodyA.SetAwake(true);
+ bodyB.SetAwake(true);
+ }
+ }
+ if (touching) {
+ this.m_flags |= b2Contact.e_touchingFlag;
+ }
+ else {
+ this.m_flags &= ~b2Contact.e_touchingFlag;
+ }
+ if (wasTouching == false && touching == true) {
+ listener.BeginContact(this);
+ }
+ if (wasTouching == true && touching == false) {
+ listener.EndContact(this);
+ }
+ if ((this.m_flags & b2Contact.e_sensorFlag) == 0) {
+ listener.PreSolve(this, this.m_oldManifold);
+ }
+ }
+ b2Contact.prototype.Evaluate = function () {}
+ b2Contact.prototype.ComputeTOI = function (sweepA, sweepB) {
+ b2Contact.s_input.proxyA.Set(this.m_fixtureA.GetShape());
+ b2Contact.s_input.proxyB.Set(this.m_fixtureB.GetShape());
+ b2Contact.s_input.sweepA = sweepA;
+ b2Contact.s_input.sweepB = sweepB;
+ b2Contact.s_input.tolerance = b2Settings.b2_linearSlop;
+ return b2TimeOfImpact.TimeOfImpact(b2Contact.s_input);
+ }
+ Box2D.postDefs.push(function () {
+ Box2D.Dynamics.Contacts.b2Contact.e_sensorFlag = 0x0001;
+ Box2D.Dynamics.Contacts.b2Contact.e_continuousFlag = 0x0002;
+ Box2D.Dynamics.Contacts.b2Contact.e_islandFlag = 0x0004;
+ Box2D.Dynamics.Contacts.b2Contact.e_toiFlag = 0x0008;
+ Box2D.Dynamics.Contacts.b2Contact.e_touchingFlag = 0x0010;
+ Box2D.Dynamics.Contacts.b2Contact.e_enabledFlag = 0x0020;
+ Box2D.Dynamics.Contacts.b2Contact.e_filterFlag = 0x0040;
+ Box2D.Dynamics.Contacts.b2Contact.s_input = new b2TOIInput();
+ });
+ b2ContactConstraint.b2ContactConstraint = function () {
+ this.localPlaneNormal = new b2Vec2();
+ this.localPoint = new b2Vec2();
+ this.normal = new b2Vec2();
+ this.normalMass = new b2Mat22();
+ this.K = new b2Mat22();
+ };
+ b2ContactConstraint.prototype.b2ContactConstraint = function () {
+ this.points = new Vector(b2Settings.b2_maxManifoldPoints);
+ for (var i = 0; i < b2Settings.b2_maxManifoldPoints; i++) {
+ this.points[i] = new b2ContactConstraintPoint();
+ }
+ }
+ b2ContactConstraintPoint.b2ContactConstraintPoint = function () {
+ this.localPoint = new b2Vec2();
+ this.rA = new b2Vec2();
+ this.rB = new b2Vec2();
+ };
+ b2ContactEdge.b2ContactEdge = function () {};
+ b2ContactFactory.b2ContactFactory = function () {};
+ b2ContactFactory.prototype.b2ContactFactory = function (allocator) {
+ this.m_allocator = allocator;
+ this.InitializeRegisters();
+ }
+ b2ContactFactory.prototype.AddType = function (createFcn, destroyFcn, type1, type2) {
+ if (type1 === undefined) type1 = 0;
+ if (type2 === undefined) type2 = 0;
+ this.m_registers[type1][type2].createFcn = createFcn;
+ this.m_registers[type1][type2].destroyFcn = destroyFcn;
+ this.m_registers[type1][type2].primary = true;
+ if (type1 != type2) {
+ this.m_registers[type2][type1].createFcn = createFcn;
+ this.m_registers[type2][type1].destroyFcn = destroyFcn;
+ this.m_registers[type2][type1].primary = false;
+ }
+ }
+ b2ContactFactory.prototype.InitializeRegisters = function () {
+ this.m_registers = new Vector(b2Shape.e_shapeTypeCount);
+ for (var i = 0; i < b2Shape.e_shapeTypeCount; i++) {
+ this.m_registers[i] = new Vector(b2Shape.e_shapeTypeCount);
+ for (var j = 0; j < b2Shape.e_shapeTypeCount; j++) {
+ this.m_registers[i][j] = new b2ContactRegister();
+ }
+ }
+ this.AddType(b2CircleContact.Create, b2CircleContact.Destroy, b2Shape.e_circleShape, b2Shape.e_circleShape);
+ this.AddType(b2PolyAndCircleContact.Create, b2PolyAndCircleContact.Destroy, b2Shape.e_polygonShape, b2Shape.e_circleShape);
+ this.AddType(b2PolygonContact.Create, b2PolygonContact.Destroy, b2Shape.e_polygonShape, b2Shape.e_polygonShape);
+ this.AddType(b2EdgeAndCircleContact.Create, b2EdgeAndCircleContact.Destroy, b2Shape.e_edgeShape, b2Shape.e_circleShape);
+ this.AddType(b2PolyAndEdgeContact.Create, b2PolyAndEdgeContact.Destroy, b2Shape.e_polygonShape, b2Shape.e_edgeShape);
+ }
+ b2ContactFactory.prototype.Create = function (fixtureA, fixtureB) {
+ var type1 = parseInt(fixtureA.GetType());
+ var type2 = parseInt(fixtureB.GetType());
+ var reg = this.m_registers[type1][type2];
+ var c;
+ if (reg.pool) {
+ c = reg.pool;
+ reg.pool = c.m_next;
+ reg.poolCount--;
+ c.Reset(fixtureA, fixtureB);
+ return c;
+ }
+ var createFcn = reg.createFcn;
+ if (createFcn != null) {
+ if (reg.primary) {
+ c = createFcn(this.m_allocator);
+ c.Reset(fixtureA, fixtureB);
+ return c;
+ }
+ else {
+ c = createFcn(this.m_allocator);
+ c.Reset(fixtureB, fixtureA);
+ return c;
+ }
+ }
+ else {
+ return null;
+ }
+ }
+ b2ContactFactory.prototype.Destroy = function (contact) {
+ if (contact.m_manifold.m_pointCount > 0) {
+ contact.m_fixtureA.m_body.SetAwake(true);
+ contact.m_fixtureB.m_body.SetAwake(true);
+ }
+ var type1 = parseInt(contact.m_fixtureA.GetType());
+ var type2 = parseInt(contact.m_fixtureB.GetType());
+ var reg = this.m_registers[type1][type2];
+ if (true) {
+ reg.poolCount++;
+ contact.m_next = reg.pool;
+ reg.pool = contact;
+ }
+ var destroyFcn = reg.destroyFcn;
+ destroyFcn(contact, this.m_allocator);
+ }
+ b2ContactRegister.b2ContactRegister = function () {};
+ b2ContactResult.b2ContactResult = function () {
+ this.position = new b2Vec2();
+ this.normal = new b2Vec2();
+ this.id = new b2ContactID();
+ };
+ b2ContactSolver.b2ContactSolver = function () {
+ this.m_step = new b2TimeStep();
+ this.m_constraints = new Vector();
+ };
+ b2ContactSolver.prototype.b2ContactSolver = function () {}
+ b2ContactSolver.prototype.Initialize = function (step, contacts, contactCount, allocator) {
+ if (contactCount === undefined) contactCount = 0;
+ var contact;
+ this.m_step.Set(step);
+ this.m_allocator = allocator;
+ var i = 0;
+ var tVec;
+ var tMat;
+ this.m_constraintCount = contactCount;
+ while (this.m_constraints.length < this.m_constraintCount) {
+ this.m_constraints[this.m_constraints.length] = new b2ContactConstraint();
+ }
+ for (i = 0;
+ i < contactCount; ++i) {
+ contact = contacts[i];
+ var fixtureA = contact.m_fixtureA;
+ var fixtureB = contact.m_fixtureB;
+ var shapeA = fixtureA.m_shape;
+ var shapeB = fixtureB.m_shape;
+ var radiusA = shapeA.m_radius;
+ var radiusB = shapeB.m_radius;
+ var bodyA = fixtureA.m_body;
+ var bodyB = fixtureB.m_body;
+ var manifold = contact.GetManifold();
+ var friction = b2Settings.b2MixFriction(fixtureA.GetFriction(), fixtureB.GetFriction());
+ var restitution = b2Settings.b2MixRestitution(fixtureA.GetRestitution(), fixtureB.GetRestitution());
+ var vAX = bodyA.m_linearVelocity.x;
+ var vAY = bodyA.m_linearVelocity.y;
+ var vBX = bodyB.m_linearVelocity.x;
+ var vBY = bodyB.m_linearVelocity.y;
+ var wA = bodyA.m_angularVelocity;
+ var wB = bodyB.m_angularVelocity;
+ b2Settings.b2Assert(manifold.m_pointCount > 0);
+ b2ContactSolver.s_worldManifold.Initialize(manifold, bodyA.m_xf, radiusA, bodyB.m_xf, radiusB);
+ var normalX = b2ContactSolver.s_worldManifold.m_normal.x;
+ var normalY = b2ContactSolver.s_worldManifold.m_normal.y;
+ var cc = this.m_constraints[i];
+ cc.bodyA = bodyA;
+ cc.bodyB = bodyB;
+ cc.manifold = manifold;
+ cc.normal.x = normalX;
+ cc.normal.y = normalY;
+ cc.pointCount = manifold.m_pointCount;
+ cc.friction = friction;
+ cc.restitution = restitution;
+ cc.localPlaneNormal.x = manifold.m_localPlaneNormal.x;
+ cc.localPlaneNormal.y = manifold.m_localPlaneNormal.y;
+ cc.localPoint.x = manifold.m_localPoint.x;
+ cc.localPoint.y = manifold.m_localPoint.y;
+ cc.radius = radiusA + radiusB;
+ cc.type = manifold.m_type;
+ for (var k = 0; k < cc.pointCount; ++k) {
+ var cp = manifold.m_points[k];
+ var ccp = cc.points[k];
+ ccp.normalImpulse = cp.m_normalImpulse;
+ ccp.tangentImpulse = cp.m_tangentImpulse;
+ ccp.localPoint.SetV(cp.m_localPoint);
+ var rAX = ccp.rA.x = b2ContactSolver.s_worldManifold.m_points[k].x - bodyA.m_sweep.c.x;
+ var rAY = ccp.rA.y = b2ContactSolver.s_worldManifold.m_points[k].y - bodyA.m_sweep.c.y;
+ var rBX = ccp.rB.x = b2ContactSolver.s_worldManifold.m_points[k].x - bodyB.m_sweep.c.x;
+ var rBY = ccp.rB.y = b2ContactSolver.s_worldManifold.m_points[k].y - bodyB.m_sweep.c.y;
+ var rnA = rAX * normalY - rAY * normalX;
+ var rnB = rBX * normalY - rBY * normalX;
+ rnA *= rnA;
+ rnB *= rnB;
+ var kNormal = bodyA.m_invMass + bodyB.m_invMass + bodyA.m_invI * rnA + bodyB.m_invI * rnB;
+ ccp.normalMass = 1.0 / kNormal;
+ var kEqualized = bodyA.m_mass * bodyA.m_invMass + bodyB.m_mass * bodyB.m_invMass;
+ kEqualized += bodyA.m_mass * bodyA.m_invI * rnA + bodyB.m_mass * bodyB.m_invI * rnB;
+ ccp.equalizedMass = 1.0 / kEqualized;
+ var tangentX = normalY;
+ var tangentY = (-normalX);
+ var rtA = rAX * tangentY - rAY * tangentX;
+ var rtB = rBX * tangentY - rBY * tangentX;
+ rtA *= rtA;
+ rtB *= rtB;
+ var kTangent = bodyA.m_invMass + bodyB.m_invMass + bodyA.m_invI * rtA + bodyB.m_invI * rtB;
+ ccp.tangentMass = 1.0 / kTangent;
+ ccp.velocityBias = 0.0;
+ var tX = vBX + ((-wB * rBY)) - vAX - ((-wA * rAY));
+ var tY = vBY + (wB * rBX) - vAY - (wA * rAX);
+ var vRel = cc.normal.x * tX + cc.normal.y * tY;
+ if (vRel < (-b2Settings.b2_velocityThreshold)) {
+ ccp.velocityBias += (-cc.restitution * vRel);
+ }
+ }
+ if (cc.pointCount == 2) {
+ var ccp1 = cc.points[0];
+ var ccp2 = cc.points[1];
+ var invMassA = bodyA.m_invMass;
+ var invIA = bodyA.m_invI;
+ var invMassB = bodyB.m_invMass;
+ var invIB = bodyB.m_invI;
+ var rn1A = ccp1.rA.x * normalY - ccp1.rA.y * normalX;
+ var rn1B = ccp1.rB.x * normalY - ccp1.rB.y * normalX;
+ var rn2A = ccp2.rA.x * normalY - ccp2.rA.y * normalX;
+ var rn2B = ccp2.rB.x * normalY - ccp2.rB.y * normalX;
+ var k11 = invMassA + invMassB + invIA * rn1A * rn1A + invIB * rn1B * rn1B;
+ var k22 = invMassA + invMassB + invIA * rn2A * rn2A + invIB * rn2B * rn2B;
+ var k12 = invMassA + invMassB + invIA * rn1A * rn2A + invIB * rn1B * rn2B;
+ var k_maxConditionNumber = 100.0;
+ if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12)) {
+ cc.K.col1.Set(k11, k12);
+ cc.K.col2.Set(k12, k22);
+ cc.K.GetInverse(cc.normalMass);
+ }
+ else {
+ cc.pointCount = 1;
+ }
+ }
+ }
+ }
+ b2ContactSolver.prototype.InitVelocityConstraints = function (step) {
+ var tVec;
+ var tVec2;
+ var tMat;
+ for (var i = 0; i < this.m_constraintCount; ++i) {
+ var c = this.m_constraints[i];
+ var bodyA = c.bodyA;
+ var bodyB = c.bodyB;
+ var invMassA = bodyA.m_invMass;
+ var invIA = bodyA.m_invI;
+ var invMassB = bodyB.m_invMass;
+ var invIB = bodyB.m_invI;
+ var normalX = c.normal.x;
+ var normalY = c.normal.y;
+ var tangentX = normalY;
+ var tangentY = (-normalX);
+ var tX = 0;
+ var j = 0;
+ var tCount = 0;
+ if (step.warmStarting) {
+ tCount = c.pointCount;
+ for (j = 0;
+ j < tCount; ++j) {
+ var ccp = c.points[j];
+ ccp.normalImpulse *= step.dtRatio;
+ ccp.tangentImpulse *= step.dtRatio;
+ var PX = ccp.normalImpulse * normalX + ccp.tangentImpulse * tangentX;
+ var PY = ccp.normalImpulse * normalY + ccp.tangentImpulse * tangentY;
+ bodyA.m_angularVelocity -= invIA * (ccp.rA.x * PY - ccp.rA.y * PX);
+ bodyA.m_linearVelocity.x -= invMassA * PX;
+ bodyA.m_linearVelocity.y -= invMassA * PY;
+ bodyB.m_angularVelocity += invIB * (ccp.rB.x * PY - ccp.rB.y * PX);
+ bodyB.m_linearVelocity.x += invMassB * PX;
+ bodyB.m_linearVelocity.y += invMassB * PY;
+ }
+ }
+ else {
+ tCount = c.pointCount;
+ for (j = 0;
+ j < tCount; ++j) {
+ var ccp2 = c.points[j];
+ ccp2.normalImpulse = 0.0;
+ ccp2.tangentImpulse = 0.0;
+ }
+ }
+ }
+ }
+ b2ContactSolver.prototype.SolveVelocityConstraints = function () {
+ var j = 0;
+ var ccp;
+ var rAX = 0;
+ var rAY = 0;
+ var rBX = 0;
+ var rBY = 0;
+ var dvX = 0;
+ var dvY = 0;
+ var vn = 0;
+ var vt = 0;
+ var lambda = 0;
+ var maxFriction = 0;
+ var newImpulse = 0;
+ var PX = 0;
+ var PY = 0;
+ var dX = 0;
+ var dY = 0;
+ var P1X = 0;
+ var P1Y = 0;
+ var P2X = 0;
+ var P2Y = 0;
+ var tMat;
+ var tVec;
+ for (var i = 0; i < this.m_constraintCount; ++i) {
+ var c = this.m_constraints[i];
+ var bodyA = c.bodyA;
+ var bodyB = c.bodyB;
+ var wA = bodyA.m_angularVelocity;
+ var wB = bodyB.m_angularVelocity;
+ var vA = bodyA.m_linearVelocity;
+ var vB = bodyB.m_linearVelocity;
+ var invMassA = bodyA.m_invMass;
+ var invIA = bodyA.m_invI;
+ var invMassB = bodyB.m_invMass;
+ var invIB = bodyB.m_invI;
+ var normalX = c.normal.x;
+ var normalY = c.normal.y;
+ var tangentX = normalY;
+ var tangentY = (-normalX);
+ var friction = c.friction;
+ var tX = 0;
+ for (j = 0;
+ j < c.pointCount; j++) {
+ ccp = c.points[j];
+ dvX = vB.x - wB * ccp.rB.y - vA.x + wA * ccp.rA.y;
+ dvY = vB.y + wB * ccp.rB.x - vA.y - wA * ccp.rA.x;
+ vt = dvX * tangentX + dvY * tangentY;
+ lambda = ccp.tangentMass * (-vt);
+ maxFriction = friction * ccp.normalImpulse;
+ newImpulse = b2Math.Clamp(ccp.tangentImpulse + lambda, (-maxFriction), maxFriction);
+ lambda = newImpulse - ccp.tangentImpulse;
+ PX = lambda * tangentX;
+ PY = lambda * tangentY;
+ vA.x -= invMassA * PX;
+ vA.y -= invMassA * PY;
+ wA -= invIA * (ccp.rA.x * PY - ccp.rA.y * PX);
+ vB.x += invMassB * PX;
+ vB.y += invMassB * PY;
+ wB += invIB * (ccp.rB.x * PY - ccp.rB.y * PX);
+ ccp.tangentImpulse = newImpulse;
+ }
+ var tCount = parseInt(c.pointCount);
+ if (c.pointCount == 1) {
+ ccp = c.points[0];
+ dvX = vB.x + ((-wB * ccp.rB.y)) - vA.x - ((-wA * ccp.rA.y));
+ dvY = vB.y + (wB * ccp.rB.x) - vA.y - (wA * ccp.rA.x);
+ vn = dvX * normalX + dvY * normalY;
+ lambda = (-ccp.normalMass * (vn - ccp.velocityBias));
+ newImpulse = ccp.normalImpulse + lambda;
+ newImpulse = newImpulse > 0 ? newImpulse : 0.0;
+ lambda = newImpulse - ccp.normalImpulse;
+ PX = lambda * normalX;
+ PY = lambda * normalY;
+ vA.x -= invMassA * PX;
+ vA.y -= invMassA * PY;
+ wA -= invIA * (ccp.rA.x * PY - ccp.rA.y * PX);
+ vB.x += invMassB * PX;
+ vB.y += invMassB * PY;
+ wB += invIB * (ccp.rB.x * PY - ccp.rB.y * PX);
+ ccp.normalImpulse = newImpulse;
+ }
+ else {
+ var cp1 = c.points[0];
+ var cp2 = c.points[1];
+ var aX = cp1.normalImpulse;
+ var aY = cp2.normalImpulse;
+ var dv1X = vB.x - wB * cp1.rB.y - vA.x + wA * cp1.rA.y;
+ var dv1Y = vB.y + wB * cp1.rB.x - vA.y - wA * cp1.rA.x;
+ var dv2X = vB.x - wB * cp2.rB.y - vA.x + wA * cp2.rA.y;
+ var dv2Y = vB.y + wB * cp2.rB.x - vA.y - wA * cp2.rA.x;
+ var vn1 = dv1X * normalX + dv1Y * normalY;
+ var vn2 = dv2X * normalX + dv2Y * normalY;
+ var bX = vn1 - cp1.velocityBias;
+ var bY = vn2 - cp2.velocityBias;
+ tMat = c.K;
+ bX -= tMat.col1.x * aX + tMat.col2.x * aY;
+ bY -= tMat.col1.y * aX + tMat.col2.y * aY;
+ var k_errorTol = 0.001;
+ for (;;) {
+ tMat = c.normalMass;
+ var xX = (-(tMat.col1.x * bX + tMat.col2.x * bY));
+ var xY = (-(tMat.col1.y * bX + tMat.col2.y * bY));
+ if (xX >= 0.0 && xY >= 0.0) {
+ dX = xX - aX;
+ dY = xY - aY;
+ P1X = dX * normalX;
+ P1Y = dX * normalY;
+ P2X = dY * normalX;
+ P2Y = dY * normalY;
+ vA.x -= invMassA * (P1X + P2X);
+ vA.y -= invMassA * (P1Y + P2Y);
+ wA -= invIA * (cp1.rA.x * P1Y - cp1.rA.y * P1X + cp2.rA.x * P2Y - cp2.rA.y * P2X);
+ vB.x += invMassB * (P1X + P2X);
+ vB.y += invMassB * (P1Y + P2Y);
+ wB += invIB * (cp1.rB.x * P1Y - cp1.rB.y * P1X + cp2.rB.x * P2Y - cp2.rB.y * P2X);
+ cp1.normalImpulse = xX;
+ cp2.normalImpulse = xY;
+ break;
+ }
+ xX = (-cp1.normalMass * bX);
+ xY = 0.0;
+ vn1 = 0.0;
+ vn2 = c.K.col1.y * xX + bY;
+ if (xX >= 0.0 && vn2 >= 0.0) {
+ dX = xX - aX;
+ dY = xY - aY;
+ P1X = dX * normalX;
+ P1Y = dX * normalY;
+ P2X = dY * normalX;
+ P2Y = dY * normalY;
+ vA.x -= invMassA * (P1X + P2X);
+ vA.y -= invMassA * (P1Y + P2Y);
+ wA -= invIA * (cp1.rA.x * P1Y - cp1.rA.y * P1X + cp2.rA.x * P2Y - cp2.rA.y * P2X);
+ vB.x += invMassB * (P1X + P2X);
+ vB.y += invMassB * (P1Y + P2Y);
+ wB += invIB * (cp1.rB.x * P1Y - cp1.rB.y * P1X + cp2.rB.x * P2Y - cp2.rB.y * P2X);
+ cp1.normalImpulse = xX;
+ cp2.normalImpulse = xY;
+ break;
+ }
+ xX = 0.0;
+ xY = (-cp2.normalMass * bY);
+ vn1 = c.K.col2.x * xY + bX;
+ vn2 = 0.0;
+ if (xY >= 0.0 && vn1 >= 0.0) {
+ dX = xX - aX;
+ dY = xY - aY;
+ P1X = dX * normalX;
+ P1Y = dX * normalY;
+ P2X = dY * normalX;
+ P2Y = dY * normalY;
+ vA.x -= invMassA * (P1X + P2X);
+ vA.y -= invMassA * (P1Y + P2Y);
+ wA -= invIA * (cp1.rA.x * P1Y - cp1.rA.y * P1X + cp2.rA.x * P2Y - cp2.rA.y * P2X);
+ vB.x += invMassB * (P1X + P2X);
+ vB.y += invMassB * (P1Y + P2Y);
+ wB += invIB * (cp1.rB.x * P1Y - cp1.rB.y * P1X + cp2.rB.x * P2Y - cp2.rB.y * P2X);
+ cp1.normalImpulse = xX;
+ cp2.normalImpulse = xY;
+ break;
+ }
+ xX = 0.0;
+ xY = 0.0;
+ vn1 = bX;
+ vn2 = bY;
+ if (vn1 >= 0.0 && vn2 >= 0.0) {
+ dX = xX - aX;
+ dY = xY - aY;
+ P1X = dX * normalX;
+ P1Y = dX * normalY;
+ P2X = dY * normalX;
+ P2Y = dY * normalY;
+ vA.x -= invMassA * (P1X + P2X);
+ vA.y -= invMassA * (P1Y + P2Y);
+ wA -= invIA * (cp1.rA.x * P1Y - cp1.rA.y * P1X + cp2.rA.x * P2Y - cp2.rA.y * P2X);
+ vB.x += invMassB * (P1X + P2X);
+ vB.y += invMassB * (P1Y + P2Y);
+ wB += invIB * (cp1.rB.x * P1Y - cp1.rB.y * P1X + cp2.rB.x * P2Y - cp2.rB.y * P2X);
+ cp1.normalImpulse = xX;
+ cp2.normalImpulse = xY;
+ break;
+ }
+ break;
+ }
+ }
+ bodyA.m_angularVelocity = wA;
+ bodyB.m_angularVelocity = wB;
+ }
+ }
+ b2ContactSolver.prototype.FinalizeVelocityConstraints = function () {
+ for (var i = 0; i < this.m_constraintCount; ++i) {
+ var c = this.m_constraints[i];
+ var m = c.manifold;
+ for (var j = 0; j < c.pointCount; ++j) {
+ var point1 = m.m_points[j];
+ var point2 = c.points[j];
+ point1.m_normalImpulse = point2.normalImpulse;
+ point1.m_tangentImpulse = point2.tangentImpulse;
+ }
+ }
+ }
+ b2ContactSolver.prototype.SolvePositionConstraints = function (baumgarte) {
+ if (baumgarte === undefined) baumgarte = 0;
+ var minSeparation = 0.0;
+ for (var i = 0; i < this.m_constraintCount; i++) {
+ var c = this.m_constraints[i];
+ var bodyA = c.bodyA;
+ var bodyB = c.bodyB;
+ var invMassA = bodyA.m_mass * bodyA.m_invMass;
+ var invIA = bodyA.m_mass * bodyA.m_invI;
+ var invMassB = bodyB.m_mass * bodyB.m_invMass;
+ var invIB = bodyB.m_mass * bodyB.m_invI;
+ b2ContactSolver.s_psm.Initialize(c);
+ var normal = b2ContactSolver.s_psm.m_normal;
+ for (var j = 0; j < c.pointCount; j++) {
+ var ccp = c.points[j];
+ var point = b2ContactSolver.s_psm.m_points[j];
+ var separation = b2ContactSolver.s_psm.m_separations[j];
+ var rAX = point.x - bodyA.m_sweep.c.x;
+ var rAY = point.y - bodyA.m_sweep.c.y;
+ var rBX = point.x - bodyB.m_sweep.c.x;
+ var rBY = point.y - bodyB.m_sweep.c.y;
+ minSeparation = minSeparation < separation ? minSeparation : separation;
+ var C = b2Math.Clamp(baumgarte * (separation + b2Settings.b2_linearSlop), (-b2Settings.b2_maxLinearCorrection), 0.0);
+ var impulse = (-ccp.equalizedMass * C);
+ var PX = impulse * normal.x;
+ var PY = impulse * normal.y;bodyA.m_sweep.c.x -= invMassA * PX;
+ bodyA.m_sweep.c.y -= invMassA * PY;
+ bodyA.m_sweep.a -= invIA * (rAX * PY - rAY * PX);
+ bodyA.SynchronizeTransform();
+ bodyB.m_sweep.c.x += invMassB * PX;
+ bodyB.m_sweep.c.y += invMassB * PY;
+ bodyB.m_sweep.a += invIB * (rBX * PY - rBY * PX);
+ bodyB.SynchronizeTransform();
+ }
+ }
+ return minSeparation > (-1.5 * b2Settings.b2_linearSlop);
+ }
+ Box2D.postDefs.push(function () {
+ Box2D.Dynamics.Contacts.b2ContactSolver.s_worldManifold = new b2WorldManifold();
+ Box2D.Dynamics.Contacts.b2ContactSolver.s_psm = new b2PositionSolverManifold();
+ });
+ Box2D.inherit(b2EdgeAndCircleContact, Box2D.Dynamics.Contacts.b2Contact);
+ b2EdgeAndCircleContact.prototype.__super = Box2D.Dynamics.Contacts.b2Contact.prototype;
+ b2EdgeAndCircleContact.b2EdgeAndCircleContact = function () {
+ Box2D.Dynamics.Contacts.b2Contact.b2Contact.apply(this, arguments);
+ };
+ b2EdgeAndCircleContact.Create = function (allocator) {
+ return new b2EdgeAndCircleContact();
+ }
+ b2EdgeAndCircleContact.Destroy = function (contact, allocator) {}
+ b2EdgeAndCircleContact.prototype.Reset = function (fixtureA, fixtureB) {
+ this.__super.Reset.call(this, fixtureA, fixtureB);
+ }
+ b2EdgeAndCircleContact.prototype.Evaluate = function () {
+ var bA = this.m_fixtureA.GetBody();
+ var bB = this.m_fixtureB.GetBody();
+ this.b2CollideEdgeAndCircle(this.m_manifold, (this.m_fixtureA.GetShape() instanceof b2EdgeShape ? this.m_fixtureA.GetShape() : null), bA.m_xf, (this.m_fixtureB.GetShape() instanceof b2CircleShape ? this.m_fixtureB.GetShape() : null), bB.m_xf);
+ }
+ b2EdgeAndCircleContact.prototype.b2CollideEdgeAndCircle = function (manifold, edge, xf1, circle, xf2) {}
+ Box2D.inherit(b2NullContact, Box2D.Dynamics.Contacts.b2Contact);
+ b2NullContact.prototype.__super = Box2D.Dynamics.Contacts.b2Contact.prototype;
+ b2NullContact.b2NullContact = function () {
+ Box2D.Dynamics.Contacts.b2Contact.b2Contact.apply(this, arguments);
+ };
+ b2NullContact.prototype.b2NullContact = function () {
+ this.__super.b2Contact.call(this);
+ }
+ b2NullContact.prototype.Evaluate = function () {}
+ Box2D.inherit(b2PolyAndCircleContact, Box2D.Dynamics.Contacts.b2Contact);
+ b2PolyAndCircleContact.prototype.__super = Box2D.Dynamics.Contacts.b2Contact.prototype;
+ b2PolyAndCircleContact.b2PolyAndCircleContact = function () {
+ Box2D.Dynamics.Contacts.b2Contact.b2Contact.apply(this, arguments);
+ };
+ b2PolyAndCircleContact.Create = function (allocator) {
+ return new b2PolyAndCircleContact();
+ }
+ b2PolyAndCircleContact.Destroy = function (contact, allocator) {}
+ b2PolyAndCircleContact.prototype.Reset = function (fixtureA, fixtureB) {
+ this.__super.Reset.call(this, fixtureA, fixtureB);
+ b2Settings.b2Assert(fixtureA.GetType() == b2Shape.e_polygonShape);
+ b2Settings.b2Assert(fixtureB.GetType() == b2Shape.e_circleShape);
+ }
+ b2PolyAndCircleContact.prototype.Evaluate = function () {
+ var bA = this.m_fixtureA.m_body;
+ var bB = this.m_fixtureB.m_body;
+ b2Collision.CollidePolygonAndCircle(this.m_manifold, (this.m_fixtureA.GetShape() instanceof b2PolygonShape ? this.m_fixtureA.GetShape() : null), bA.m_xf, (this.m_fixtureB.GetShape() instanceof b2CircleShape ? this.m_fixtureB.GetShape() : null), bB.m_xf);
+ }
+ Box2D.inherit(b2PolyAndEdgeContact, Box2D.Dynamics.Contacts.b2Contact);
+ b2PolyAndEdgeContact.prototype.__super = Box2D.Dynamics.Contacts.b2Contact.prototype;
+ b2PolyAndEdgeContact.b2PolyAndEdgeContact = function () {
+ Box2D.Dynamics.Contacts.b2Contact.b2Contact.apply(this, arguments);
+ };
+ b2PolyAndEdgeContact.Create = function (allocator) {
+ return new b2PolyAndEdgeContact();
+ }
+ b2PolyAndEdgeContact.Destroy = function (contact, allocator) {}
+ b2PolyAndEdgeContact.prototype.Reset = function (fixtureA, fixtureB) {
+ this.__super.Reset.call(this, fixtureA, fixtureB);
+ b2Settings.b2Assert(fixtureA.GetType() == b2Shape.e_polygonShape);
+ b2Settings.b2Assert(fixtureB.GetType() == b2Shape.e_edgeShape);
+ }
+ b2PolyAndEdgeContact.prototype.Evaluate = function () {
+ var bA = this.m_fixtureA.GetBody();
+ var bB = this.m_fixtureB.GetBody();
+ this.b2CollidePolyAndEdge(this.m_manifold, (this.m_fixtureA.GetShape() instanceof b2PolygonShape ? this.m_fixtureA.GetShape() : null), bA.m_xf, (this.m_fixtureB.GetShape() instanceof b2EdgeShape ? this.m_fixtureB.GetShape() : null), bB.m_xf);
+ }
+ b2PolyAndEdgeContact.prototype.b2CollidePolyAndEdge = function (manifold, polygon, xf1, edge, xf2) {}
+ Box2D.inherit(b2PolygonContact, Box2D.Dynamics.Contacts.b2Contact);
+ b2PolygonContact.prototype.__super = Box2D.Dynamics.Contacts.b2Contact.prototype;
+ b2PolygonContact.b2PolygonContact = function () {
+ Box2D.Dynamics.Contacts.b2Contact.b2Contact.apply(this, arguments);
+ };
+ b2PolygonContact.Create = function (allocator) {
+ return new b2PolygonContact();
+ }
+ b2PolygonContact.Destroy = function (contact, allocator) {}
+ b2PolygonContact.prototype.Reset = function (fixtureA, fixtureB) {
+ this.__super.Reset.call(this, fixtureA, fixtureB);
+ }
+ b2PolygonContact.prototype.Evaluate = function () {
+ var bA = this.m_fixtureA.GetBody();
+ var bB = this.m_fixtureB.GetBody();
+ b2Collision.CollidePolygons(this.m_manifold, (this.m_fixtureA.GetShape() instanceof b2PolygonShape ? this.m_fixtureA.GetShape() : null), bA.m_xf, (this.m_fixtureB.GetShape() instanceof b2PolygonShape ? this.m_fixtureB.GetShape() : null), bB.m_xf);
+ }
+ b2PositionSolverManifold.b2PositionSolverManifold = function () {};
+ b2PositionSolverManifold.prototype.b2PositionSolverManifold = function () {
+ this.m_normal = new b2Vec2();
+ this.m_separations = new Vector_a2j_Number(b2Settings.b2_maxManifoldPoints);
+ this.m_points = new Vector(b2Settings.b2_maxManifoldPoints);
+ for (var i = 0; i < b2Settings.b2_maxManifoldPoints; i++) {
+ this.m_points[i] = new b2Vec2();
+ }
+ }
+ b2PositionSolverManifold.prototype.Initialize = function (cc) {
+ b2Settings.b2Assert(cc.pointCount > 0);
+ var i = 0;
+ var clipPointX = 0;
+ var clipPointY = 0;
+ var tMat;
+ var tVec;
+ var planePointX = 0;
+ var planePointY = 0;
+ switch (cc.type) {
+ case b2Manifold.e_circles:
+ {
+ tMat = cc.bodyA.m_xf.R;
+ tVec = cc.localPoint;
+ var pointAX = cc.bodyA.m_xf.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ var pointAY = cc.bodyA.m_xf.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ tMat = cc.bodyB.m_xf.R;
+ tVec = cc.points[0].localPoint;
+ var pointBX = cc.bodyB.m_xf.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ var pointBY = cc.bodyB.m_xf.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ var dX = pointBX - pointAX;
+ var dY = pointBY - pointAY;
+ var d2 = dX * dX + dY * dY;
+ if (d2 > Number.MIN_VALUE * Number.MIN_VALUE) {
+ var d = Math.sqrt(d2);
+ this.m_normal.x = dX / d;
+ this.m_normal.y = dY / d;
+ }
+ else {
+ this.m_normal.x = 1.0;
+ this.m_normal.y = 0.0;
+ }
+ this.m_points[0].x = 0.5 * (pointAX + pointBX);
+ this.m_points[0].y = 0.5 * (pointAY + pointBY);
+ this.m_separations[0] = dX * this.m_normal.x + dY * this.m_normal.y - cc.radius;
+ }
+ break;
+ case b2Manifold.e_faceA:
+ {
+ tMat = cc.bodyA.m_xf.R;
+ tVec = cc.localPlaneNormal;
+ this.m_normal.x = tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
+ this.m_normal.y = tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
+ tMat = cc.bodyA.m_xf.R;
+ tVec = cc.localPoint;
+ planePointX = cc.bodyA.m_xf.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ planePointY = cc.bodyA.m_xf.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ tMat = cc.bodyB.m_xf.R;
+ for (i = 0;
+ i < cc.pointCount; ++i) {
+ tVec = cc.points[i].localPoint;
+ clipPointX = cc.bodyB.m_xf.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ clipPointY = cc.bodyB.m_xf.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ this.m_separations[i] = (clipPointX - planePointX) * this.m_normal.x + (clipPointY - planePointY) * this.m_normal.y - cc.radius;
+ this.m_points[i].x = clipPointX;
+ this.m_points[i].y = clipPointY;
+ }
+ }
+ break;
+ case b2Manifold.e_faceB:
+ {
+ tMat = cc.bodyB.m_xf.R;
+ tVec = cc.localPlaneNormal;
+ this.m_normal.x = tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
+ this.m_normal.y = tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
+ tMat = cc.bodyB.m_xf.R;
+ tVec = cc.localPoint;
+ planePointX = cc.bodyB.m_xf.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ planePointY = cc.bodyB.m_xf.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ tMat = cc.bodyA.m_xf.R;
+ for (i = 0;
+ i < cc.pointCount; ++i) {
+ tVec = cc.points[i].localPoint;
+ clipPointX = cc.bodyA.m_xf.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ clipPointY = cc.bodyA.m_xf.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ this.m_separations[i] = (clipPointX - planePointX) * this.m_normal.x + (clipPointY - planePointY) * this.m_normal.y - cc.radius;
+ this.m_points[i].Set(clipPointX, clipPointY);
+ }
+ this.m_normal.x *= (-1);
+ this.m_normal.y *= (-1);
+ }
+ break;
+ }
+ }
+ Box2D.postDefs.push(function () {
+ Box2D.Dynamics.Contacts.b2PositionSolverManifold.circlePointA = new b2Vec2();
+ Box2D.Dynamics.Contacts.b2PositionSolverManifold.circlePointB = new b2Vec2();
+ });
+})();
+(function () {
+ var b2Body = Box2D.Dynamics.b2Body,
+ b2BodyDef = Box2D.Dynamics.b2BodyDef,
+ b2ContactFilter = Box2D.Dynamics.b2ContactFilter,
+ b2ContactImpulse = Box2D.Dynamics.b2ContactImpulse,
+ b2ContactListener = Box2D.Dynamics.b2ContactListener,
+ b2ContactManager = Box2D.Dynamics.b2ContactManager,
+ b2DebugDraw = Box2D.Dynamics.b2DebugDraw,
+ b2DestructionListener = Box2D.Dynamics.b2DestructionListener,
+ b2FilterData = Box2D.Dynamics.b2FilterData,
+ b2Fixture = Box2D.Dynamics.b2Fixture,
+ b2FixtureDef = Box2D.Dynamics.b2FixtureDef,
+ b2Island = Box2D.Dynamics.b2Island,
+ b2TimeStep = Box2D.Dynamics.b2TimeStep,
+ b2World = Box2D.Dynamics.b2World,
+ b2Mat22 = Box2D.Common.Math.b2Mat22,
+ b2Mat33 = Box2D.Common.Math.b2Mat33,
+ b2Math = Box2D.Common.Math.b2Math,
+ b2Sweep = Box2D.Common.Math.b2Sweep,
+ b2Transform = Box2D.Common.Math.b2Transform,
+ b2Vec2 = Box2D.Common.Math.b2Vec2,
+ b2Vec3 = Box2D.Common.Math.b2Vec3,
+ b2Color = Box2D.Common.b2Color,
+ b2internal = Box2D.Common.b2internal,
+ b2Settings = Box2D.Common.b2Settings,
+ b2CircleShape = Box2D.Collision.Shapes.b2CircleShape,
+ b2EdgeChainDef = Box2D.Collision.Shapes.b2EdgeChainDef,
+ b2EdgeShape = Box2D.Collision.Shapes.b2EdgeShape,
+ b2MassData = Box2D.Collision.Shapes.b2MassData,
+ b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape,
+ b2Shape = Box2D.Collision.Shapes.b2Shape,
+ b2BuoyancyController = Box2D.Dynamics.Controllers.b2BuoyancyController,
+ b2ConstantAccelController = Box2D.Dynamics.Controllers.b2ConstantAccelController,
+ b2ConstantForceController = Box2D.Dynamics.Controllers.b2ConstantForceController,
+ b2Controller = Box2D.Dynamics.Controllers.b2Controller,
+ b2ControllerEdge = Box2D.Dynamics.Controllers.b2ControllerEdge,
+ b2GravityController = Box2D.Dynamics.Controllers.b2GravityController,
+ b2TensorDampingController = Box2D.Dynamics.Controllers.b2TensorDampingController;
+
+ Box2D.inherit(b2BuoyancyController, Box2D.Dynamics.Controllers.b2Controller);
+ b2BuoyancyController.prototype.__super = Box2D.Dynamics.Controllers.b2Controller.prototype;
+ b2BuoyancyController.b2BuoyancyController = function () {
+ Box2D.Dynamics.Controllers.b2Controller.b2Controller.apply(this, arguments);
+ this.normal = new b2Vec2(0, (-1));
+ this.offset = 0;
+ this.density = 0;
+ this.velocity = new b2Vec2(0, 0);
+ this.linearDrag = 2;
+ this.angularDrag = 1;
+ this.useDensity = false;
+ this.useWorldGravity = true;
+ this.gravity = null;
+ };
+ b2BuoyancyController.prototype.Step = function (step) {
+ if (!this.m_bodyList) return;
+ if (this.useWorldGravity) {
+ this.gravity = this.GetWorld().GetGravity().Copy();
+ }
+ for (var i = this.m_bodyList; i; i = i.nextBody) {
+ var body = i.body;
+ if (body.IsAwake() == false) {
+ continue;
+ }
+ var areac = new b2Vec2();
+ var massc = new b2Vec2();
+ var area = 0.0;
+ var mass = 0.0;
+ for (var fixture = body.GetFixtureList(); fixture; fixture = fixture.GetNext()) {
+ var sc = new b2Vec2();
+ var sarea = fixture.GetShape().ComputeSubmergedArea(this.normal, this.offset, body.GetTransform(), sc);
+ area += sarea;
+ areac.x += sarea * sc.x;
+ areac.y += sarea * sc.y;
+ var shapeDensity = 0;
+ if (this.useDensity) {
+ shapeDensity = 1;
+ }
+ else {
+ shapeDensity = 1;
+ }
+ mass += sarea * shapeDensity;
+ massc.x += sarea * sc.x * shapeDensity;
+ massc.y += sarea * sc.y * shapeDensity;
+ }
+ areac.x /= area;
+ areac.y /= area;
+ massc.x /= mass;
+ massc.y /= mass;
+ if (area < Number.MIN_VALUE) continue;
+ var buoyancyForce = this.gravity.GetNegative();
+ buoyancyForce.Multiply(this.density * area);
+ body.ApplyForce(buoyancyForce, massc);
+ var dragForce = body.GetLinearVelocityFromWorldPoint(areac);
+ dragForce.Subtract(this.velocity);
+ dragForce.Multiply((-this.linearDrag * area));
+ body.ApplyForce(dragForce, areac);
+ body.ApplyTorque((-body.GetInertia() / body.GetMass() * area * body.GetAngularVelocity() * this.angularDrag));
+ }
+ }
+ b2BuoyancyController.prototype.Draw = function (debugDraw) {
+ var r = 1000;
+ var p1 = new b2Vec2();
+ var p2 = new b2Vec2();
+ p1.x = this.normal.x * this.offset + this.normal.y * r;
+ p1.y = this.normal.y * this.offset - this.normal.x * r;
+ p2.x = this.normal.x * this.offset - this.normal.y * r;
+ p2.y = this.normal.y * this.offset + this.normal.x * r;
+ var color = new b2Color(0, 0, 1);
+ debugDraw.DrawSegment(p1, p2, color);
+ }
+ Box2D.inherit(b2ConstantAccelController, Box2D.Dynamics.Controllers.b2Controller);
+ b2ConstantAccelController.prototype.__super = Box2D.Dynamics.Controllers.b2Controller.prototype;
+ b2ConstantAccelController.b2ConstantAccelController = function () {
+ Box2D.Dynamics.Controllers.b2Controller.b2Controller.apply(this, arguments);
+ this.A = new b2Vec2(0, 0);
+ };
+ b2ConstantAccelController.prototype.Step = function (step) {
+ var smallA = new b2Vec2(this.A.x * step.dt, this.A.y * step.dt);
+ for (var i = this.m_bodyList; i; i = i.nextBody) {
+ var body = i.body;
+ if (!body.IsAwake()) continue;
+ body.SetLinearVelocity(new b2Vec2(body.GetLinearVelocity().x + smallA.x, body.GetLinearVelocity().y + smallA.y));
+ }
+ }
+ Box2D.inherit(b2ConstantForceController, Box2D.Dynamics.Controllers.b2Controller);
+ b2ConstantForceController.prototype.__super = Box2D.Dynamics.Controllers.b2Controller.prototype;
+ b2ConstantForceController.b2ConstantForceController = function () {
+ Box2D.Dynamics.Controllers.b2Controller.b2Controller.apply(this, arguments);
+ this.F = new b2Vec2(0, 0);
+ };
+ b2ConstantForceController.prototype.Step = function (step) {
+ for (var i = this.m_bodyList; i; i = i.nextBody) {
+ var body = i.body;
+ if (!body.IsAwake()) continue;
+ body.ApplyForce(this.F, body.GetWorldCenter());
+ }
+ }
+ b2Controller.b2Controller = function () {};
+ b2Controller.prototype.Step = function (step) {}
+ b2Controller.prototype.Draw = function (debugDraw) {}
+ b2Controller.prototype.AddBody = function (body) {
+ var edge = new b2ControllerEdge();
+ edge.controller = this;
+ edge.body = body;
+ edge.nextBody = this.m_bodyList;
+ edge.prevBody = null;
+ this.m_bodyList = edge;
+ if (edge.nextBody) edge.nextBody.prevBody = edge;
+ this.m_bodyCount++;
+ edge.nextController = body.m_controllerList;
+ edge.prevController = null;
+ body.m_controllerList = edge;
+ if (edge.nextController) edge.nextController.prevController = edge;
+ body.m_controllerCount++;
+ }
+ b2Controller.prototype.RemoveBody = function (body) {
+ var edge = body.m_controllerList;
+ while (edge && edge.controller != this)
+ edge = edge.nextController;
+ if (edge.prevBody) edge.prevBody.nextBody = edge.nextBody;
+ if (edge.nextBody) edge.nextBody.prevBody = edge.prevBody;
+ if (edge.nextController) edge.nextController.prevController = edge.prevController;
+ if (edge.prevController) edge.prevController.nextController = edge.nextController;
+ if (this.m_bodyList == edge) this.m_bodyList = edge.nextBody;
+ if (body.m_controllerList == edge) body.m_controllerList = edge.nextController;
+ body.m_controllerCount--;
+ this.m_bodyCount--;
+ }
+ b2Controller.prototype.Clear = function () {
+ while (this.m_bodyList)
+ this.RemoveBody(this.m_bodyList.body);
+ }
+ b2Controller.prototype.GetNext = function () {
+ return this.m_next;
+ }
+ b2Controller.prototype.GetWorld = function () {
+ return this.m_world;
+ }
+ b2Controller.prototype.GetBodyList = function () {
+ return this.m_bodyList;
+ }
+ b2ControllerEdge.b2ControllerEdge = function () {};
+ Box2D.inherit(b2GravityController, Box2D.Dynamics.Controllers.b2Controller);
+ b2GravityController.prototype.__super = Box2D.Dynamics.Controllers.b2Controller.prototype;
+ b2GravityController.b2GravityController = function () {
+ Box2D.Dynamics.Controllers.b2Controller.b2Controller.apply(this, arguments);
+ this.G = 1;
+ this.invSqr = true;
+ };
+ b2GravityController.prototype.Step = function (step) {
+ var i = null;
+ var body1 = null;
+ var p1 = null;
+ var mass1 = 0;
+ var j = null;
+ var body2 = null;
+ var p2 = null;
+ var dx = 0;
+ var dy = 0;
+ var r2 = 0;
+ var f = null;
+ if (this.invSqr) {
+ for (i = this.m_bodyList;
+ i; i = i.nextBody) {
+ body1 = i.body;
+ p1 = body1.GetWorldCenter();
+ mass1 = body1.GetMass();
+ for (j = this.m_bodyList;
+ j != i; j = j.nextBody) {
+ body2 = j.body;
+ p2 = body2.GetWorldCenter();
+ dx = p2.x - p1.x;
+ dy = p2.y - p1.y;
+ r2 = dx * dx + dy * dy;
+ if (r2 < Number.MIN_VALUE) continue;
+ f = new b2Vec2(dx, dy);
+ f.Multiply(this.G / r2 / Math.sqrt(r2) * mass1 * body2.GetMass());
+ if (body1.IsAwake()) body1.ApplyForce(f, p1);
+ f.Multiply((-1));
+ if (body2.IsAwake()) body2.ApplyForce(f, p2);
+ }
+ }
+ }
+ else {
+ for (i = this.m_bodyList;
+ i; i = i.nextBody) {
+ body1 = i.body;
+ p1 = body1.GetWorldCenter();
+ mass1 = body1.GetMass();
+ for (j = this.m_bodyList;
+ j != i; j = j.nextBody) {
+ body2 = j.body;
+ p2 = body2.GetWorldCenter();
+ dx = p2.x - p1.x;
+ dy = p2.y - p1.y;
+ r2 = dx * dx + dy * dy;
+ if (r2 < Number.MIN_VALUE) continue;
+ f = new b2Vec2(dx, dy);
+ f.Multiply(this.G / r2 * mass1 * body2.GetMass());
+ if (body1.IsAwake()) body1.ApplyForce(f, p1);
+ f.Multiply((-1));
+ if (body2.IsAwake()) body2.ApplyForce(f, p2);
+ }
+ }
+ }
+ }
+ Box2D.inherit(b2TensorDampingController, Box2D.Dynamics.Controllers.b2Controller);
+ b2TensorDampingController.prototype.__super = Box2D.Dynamics.Controllers.b2Controller.prototype;
+ b2TensorDampingController.b2TensorDampingController = function () {
+ Box2D.Dynamics.Controllers.b2Controller.b2Controller.apply(this, arguments);
+ this.T = new b2Mat22();
+ this.maxTimestep = 0;
+ };
+ b2TensorDampingController.prototype.SetAxisAligned = function (xDamping, yDamping) {
+ if (xDamping === undefined) xDamping = 0;
+ if (yDamping === undefined) yDamping = 0;
+ this.T.col1.x = (-xDamping);
+ this.T.col1.y = 0;
+ this.T.col2.x = 0;
+ this.T.col2.y = (-yDamping);
+ if (xDamping > 0 || yDamping > 0) {
+ this.maxTimestep = 1 / Math.max(xDamping, yDamping);
+ }
+ else {
+ this.maxTimestep = 0;
+ }
+ }
+ b2TensorDampingController.prototype.Step = function (step) {
+ var timestep = step.dt;
+ if (timestep <= Number.MIN_VALUE) return;
+ if (timestep > this.maxTimestep && this.maxTimestep > 0) timestep = this.maxTimestep;
+ for (var i = this.m_bodyList; i; i = i.nextBody) {
+ var body = i.body;
+ if (!body.IsAwake()) {
+ continue;
+ }
+ var damping = body.GetWorldVector(b2Math.MulMV(this.T, body.GetLocalVector(body.GetLinearVelocity())));
+ body.SetLinearVelocity(new b2Vec2(body.GetLinearVelocity().x + damping.x * timestep, body.GetLinearVelocity().y + damping.y * timestep));
+ }
+ }
+})();
+(function () {
+ var b2Color = Box2D.Common.b2Color,
+ b2internal = Box2D.Common.b2internal,
+ b2Settings = Box2D.Common.b2Settings,
+ b2Mat22 = Box2D.Common.Math.b2Mat22,
+ b2Mat33 = Box2D.Common.Math.b2Mat33,
+ b2Math = Box2D.Common.Math.b2Math,
+ b2Sweep = Box2D.Common.Math.b2Sweep,
+ b2Transform = Box2D.Common.Math.b2Transform,
+ b2Vec2 = Box2D.Common.Math.b2Vec2,
+ b2Vec3 = Box2D.Common.Math.b2Vec3,
+ b2DistanceJoint = Box2D.Dynamics.Joints.b2DistanceJoint,
+ b2DistanceJointDef = Box2D.Dynamics.Joints.b2DistanceJointDef,
+ b2FrictionJoint = Box2D.Dynamics.Joints.b2FrictionJoint,
+ b2FrictionJointDef = Box2D.Dynamics.Joints.b2FrictionJointDef,
+ b2GearJoint = Box2D.Dynamics.Joints.b2GearJoint,
+ b2GearJointDef = Box2D.Dynamics.Joints.b2GearJointDef,
+ b2Jacobian = Box2D.Dynamics.Joints.b2Jacobian,
+ b2Joint = Box2D.Dynamics.Joints.b2Joint,
+ b2JointDef = Box2D.Dynamics.Joints.b2JointDef,
+ b2JointEdge = Box2D.Dynamics.Joints.b2JointEdge,
+ b2LineJoint = Box2D.Dynamics.Joints.b2LineJoint,
+ b2LineJointDef = Box2D.Dynamics.Joints.b2LineJointDef,
+ b2MouseJoint = Box2D.Dynamics.Joints.b2MouseJoint,
+ b2MouseJointDef = Box2D.Dynamics.Joints.b2MouseJointDef,
+ b2PrismaticJoint = Box2D.Dynamics.Joints.b2PrismaticJoint,
+ b2PrismaticJointDef = Box2D.Dynamics.Joints.b2PrismaticJointDef,
+ b2PulleyJoint = Box2D.Dynamics.Joints.b2PulleyJoint,
+ b2PulleyJointDef = Box2D.Dynamics.Joints.b2PulleyJointDef,
+ b2RevoluteJoint = Box2D.Dynamics.Joints.b2RevoluteJoint,
+ b2RevoluteJointDef = Box2D.Dynamics.Joints.b2RevoluteJointDef,
+ b2WeldJoint = Box2D.Dynamics.Joints.b2WeldJoint,
+ b2WeldJointDef = Box2D.Dynamics.Joints.b2WeldJointDef,
+ b2Body = Box2D.Dynamics.b2Body,
+ b2BodyDef = Box2D.Dynamics.b2BodyDef,
+ b2ContactFilter = Box2D.Dynamics.b2ContactFilter,
+ b2ContactImpulse = Box2D.Dynamics.b2ContactImpulse,
+ b2ContactListener = Box2D.Dynamics.b2ContactListener,
+ b2ContactManager = Box2D.Dynamics.b2ContactManager,
+ b2DebugDraw = Box2D.Dynamics.b2DebugDraw,
+ b2DestructionListener = Box2D.Dynamics.b2DestructionListener,
+ b2FilterData = Box2D.Dynamics.b2FilterData,
+ b2Fixture = Box2D.Dynamics.b2Fixture,
+ b2FixtureDef = Box2D.Dynamics.b2FixtureDef,
+ b2Island = Box2D.Dynamics.b2Island,
+ b2TimeStep = Box2D.Dynamics.b2TimeStep,
+ b2World = Box2D.Dynamics.b2World;
+
+ Box2D.inherit(b2DistanceJoint, Box2D.Dynamics.Joints.b2Joint);
+ b2DistanceJoint.prototype.__super = Box2D.Dynamics.Joints.b2Joint.prototype;
+ b2DistanceJoint.b2DistanceJoint = function () {
+ Box2D.Dynamics.Joints.b2Joint.b2Joint.apply(this, arguments);
+ this.m_localAnchor1 = new b2Vec2();
+ this.m_localAnchor2 = new b2Vec2();
+ this.m_u = new b2Vec2();
+ };
+ b2DistanceJoint.prototype.GetAnchorA = function () {
+ return this.m_bodyA.GetWorldPoint(this.m_localAnchor1);
+ }
+ b2DistanceJoint.prototype.GetAnchorB = function () {
+ return this.m_bodyB.GetWorldPoint(this.m_localAnchor2);
+ }
+ b2DistanceJoint.prototype.GetReactionForce = function (inv_dt) {
+ if (inv_dt === undefined) inv_dt = 0;
+ return new b2Vec2(inv_dt * this.m_impulse * this.m_u.x, inv_dt * this.m_impulse * this.m_u.y);
+ }
+ b2DistanceJoint.prototype.GetReactionTorque = function (inv_dt) {
+ if (inv_dt === undefined) inv_dt = 0;
+ return 0.0;
+ }
+ b2DistanceJoint.prototype.GetLength = function () {
+ return this.m_length;
+ }
+ b2DistanceJoint.prototype.SetLength = function (length) {
+ if (length === undefined) length = 0;
+ this.m_length = length;
+ }
+ b2DistanceJoint.prototype.GetFrequency = function () {
+ return this.m_frequencyHz;
+ }
+ b2DistanceJoint.prototype.SetFrequency = function (hz) {
+ if (hz === undefined) hz = 0;
+ this.m_frequencyHz = hz;
+ }
+ b2DistanceJoint.prototype.GetDampingRatio = function () {
+ return this.m_dampingRatio;
+ }
+ b2DistanceJoint.prototype.SetDampingRatio = function (ratio) {
+ if (ratio === undefined) ratio = 0;
+ this.m_dampingRatio = ratio;
+ }
+ b2DistanceJoint.prototype.b2DistanceJoint = function (def) {
+ this.__super.b2Joint.call(this, def);
+ var tMat;
+ var tX = 0;
+ var tY = 0;
+ this.m_localAnchor1.SetV(def.localAnchorA);
+ this.m_localAnchor2.SetV(def.localAnchorB);
+ this.m_length = def.length;
+ this.m_frequencyHz = def.frequencyHz;
+ this.m_dampingRatio = def.dampingRatio;
+ this.m_impulse = 0.0;
+ this.m_gamma = 0.0;
+ this.m_bias = 0.0;
+ }
+ b2DistanceJoint.prototype.InitVelocityConstraints = function (step) {
+ var tMat;
+ var tX = 0;
+ var bA = this.m_bodyA;
+ var bB = this.m_bodyB;
+ tMat = bA.m_xf.R;
+ var r1X = this.m_localAnchor1.x - bA.m_sweep.localCenter.x;
+ var r1Y = this.m_localAnchor1.y - bA.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
+ r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
+ r1X = tX;
+ tMat = bB.m_xf.R;
+ var r2X = this.m_localAnchor2.x - bB.m_sweep.localCenter.x;
+ var r2Y = this.m_localAnchor2.y - bB.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
+ r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
+ r2X = tX;
+ this.m_u.x = bB.m_sweep.c.x + r2X - bA.m_sweep.c.x - r1X;
+ this.m_u.y = bB.m_sweep.c.y + r2Y - bA.m_sweep.c.y - r1Y;
+ var length = Math.sqrt(this.m_u.x * this.m_u.x + this.m_u.y * this.m_u.y);
+ if (length > b2Settings.b2_linearSlop) {
+ this.m_u.Multiply(1.0 / length);
+ }
+ else {
+ this.m_u.SetZero();
+ }
+ var cr1u = (r1X * this.m_u.y - r1Y * this.m_u.x);
+ var cr2u = (r2X * this.m_u.y - r2Y * this.m_u.x);
+ var invMass = bA.m_invMass + bA.m_invI * cr1u * cr1u + bB.m_invMass + bB.m_invI * cr2u * cr2u;
+ this.m_mass = invMass != 0.0 ? 1.0 / invMass : 0.0;
+ if (this.m_frequencyHz > 0.0) {
+ var C = length - this.m_length;
+ var omega = 2.0 * Math.PI * this.m_frequencyHz;
+ var d = 2.0 * this.m_mass * this.m_dampingRatio * omega;
+ var k = this.m_mass * omega * omega;
+ this.m_gamma = step.dt * (d + step.dt * k);
+ this.m_gamma = this.m_gamma != 0.0 ? 1 / this.m_gamma : 0.0;
+ this.m_bias = C * step.dt * k * this.m_gamma;
+ this.m_mass = invMass + this.m_gamma;
+ this.m_mass = this.m_mass != 0.0 ? 1.0 / this.m_mass : 0.0;
+ }
+ if (step.warmStarting) {
+ this.m_impulse *= step.dtRatio;
+ var PX = this.m_impulse * this.m_u.x;
+ var PY = this.m_impulse * this.m_u.y;
+ bA.m_linearVelocity.x -= bA.m_invMass * PX;
+ bA.m_linearVelocity.y -= bA.m_invMass * PY;
+ bA.m_angularVelocity -= bA.m_invI * (r1X * PY - r1Y * PX);
+ bB.m_linearVelocity.x += bB.m_invMass * PX;
+ bB.m_linearVelocity.y += bB.m_invMass * PY;
+ bB.m_angularVelocity += bB.m_invI * (r2X * PY - r2Y * PX);
+ }
+ else {
+ this.m_impulse = 0.0;
+ }
+ }
+ b2DistanceJoint.prototype.SolveVelocityConstraints = function (step) {
+ var tMat;
+ var bA = this.m_bodyA;
+ var bB = this.m_bodyB;
+ tMat = bA.m_xf.R;
+ var r1X = this.m_localAnchor1.x - bA.m_sweep.localCenter.x;
+ var r1Y = this.m_localAnchor1.y - bA.m_sweep.localCenter.y;
+ var tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
+ r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
+ r1X = tX;
+ tMat = bB.m_xf.R;
+ var r2X = this.m_localAnchor2.x - bB.m_sweep.localCenter.x;
+ var r2Y = this.m_localAnchor2.y - bB.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
+ r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
+ r2X = tX;
+ var v1X = bA.m_linearVelocity.x + ((-bA.m_angularVelocity * r1Y));
+ var v1Y = bA.m_linearVelocity.y + (bA.m_angularVelocity * r1X);
+ var v2X = bB.m_linearVelocity.x + ((-bB.m_angularVelocity * r2Y));
+ var v2Y = bB.m_linearVelocity.y + (bB.m_angularVelocity * r2X);
+ var Cdot = (this.m_u.x * (v2X - v1X) + this.m_u.y * (v2Y - v1Y));
+ var impulse = (-this.m_mass * (Cdot + this.m_bias + this.m_gamma * this.m_impulse));
+ this.m_impulse += impulse;
+ var PX = impulse * this.m_u.x;
+ var PY = impulse * this.m_u.y;
+ bA.m_linearVelocity.x -= bA.m_invMass * PX;
+ bA.m_linearVelocity.y -= bA.m_invMass * PY;
+ bA.m_angularVelocity -= bA.m_invI * (r1X * PY - r1Y * PX);
+ bB.m_linearVelocity.x += bB.m_invMass * PX;
+ bB.m_linearVelocity.y += bB.m_invMass * PY;
+ bB.m_angularVelocity += bB.m_invI * (r2X * PY - r2Y * PX);
+ }
+ b2DistanceJoint.prototype.SolvePositionConstraints = function (baumgarte) {
+ if (baumgarte === undefined) baumgarte = 0;
+ var tMat;
+ if (this.m_frequencyHz > 0.0) {
+ return true;
+ }
+ var bA = this.m_bodyA;
+ var bB = this.m_bodyB;
+ tMat = bA.m_xf.R;
+ var r1X = this.m_localAnchor1.x - bA.m_sweep.localCenter.x;
+ var r1Y = this.m_localAnchor1.y - bA.m_sweep.localCenter.y;
+ var tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
+ r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
+ r1X = tX;
+ tMat = bB.m_xf.R;
+ var r2X = this.m_localAnchor2.x - bB.m_sweep.localCenter.x;
+ var r2Y = this.m_localAnchor2.y - bB.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
+ r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
+ r2X = tX;
+ var dX = bB.m_sweep.c.x + r2X - bA.m_sweep.c.x - r1X;
+ var dY = bB.m_sweep.c.y + r2Y - bA.m_sweep.c.y - r1Y;
+ var length = Math.sqrt(dX * dX + dY * dY);
+ dX /= length;
+ dY /= length;
+ var C = length - this.m_length;
+ C = b2Math.Clamp(C, (-b2Settings.b2_maxLinearCorrection), b2Settings.b2_maxLinearCorrection);
+ var impulse = (-this.m_mass * C);
+ this.m_u.Set(dX, dY);
+ var PX = impulse * this.m_u.x;
+ var PY = impulse * this.m_u.y;
+ bA.m_sweep.c.x -= bA.m_invMass * PX;
+ bA.m_sweep.c.y -= bA.m_invMass * PY;
+ bA.m_sweep.a -= bA.m_invI * (r1X * PY - r1Y * PX);
+ bB.m_sweep.c.x += bB.m_invMass * PX;
+ bB.m_sweep.c.y += bB.m_invMass * PY;
+ bB.m_sweep.a += bB.m_invI * (r2X * PY - r2Y * PX);
+ bA.SynchronizeTransform();
+ bB.SynchronizeTransform();
+ return b2Math.Abs(C) < b2Settings.b2_linearSlop;
+ }
+ Box2D.inherit(b2DistanceJointDef, Box2D.Dynamics.Joints.b2JointDef);
+ b2DistanceJointDef.prototype.__super = Box2D.Dynamics.Joints.b2JointDef.prototype;
+ b2DistanceJointDef.b2DistanceJointDef = function () {
+ Box2D.Dynamics.Joints.b2JointDef.b2JointDef.apply(this, arguments);
+ this.localAnchorA = new b2Vec2();
+ this.localAnchorB = new b2Vec2();
+ };
+ b2DistanceJointDef.prototype.b2DistanceJointDef = function () {
+ this.__super.b2JointDef.call(this);
+ this.type = b2Joint.e_distanceJoint;
+ this.length = 1.0;
+ this.frequencyHz = 0.0;
+ this.dampingRatio = 0.0;
+ }
+ b2DistanceJointDef.prototype.Initialize = function (bA, bB, anchorA, anchorB) {
+ this.bodyA = bA;
+ this.bodyB = bB;
+ this.localAnchorA.SetV(this.bodyA.GetLocalPoint(anchorA));
+ this.localAnchorB.SetV(this.bodyB.GetLocalPoint(anchorB));
+ var dX = anchorB.x - anchorA.x;
+ var dY = anchorB.y - anchorA.y;
+ this.length = Math.sqrt(dX * dX + dY * dY);
+ this.frequencyHz = 0.0;
+ this.dampingRatio = 0.0;
+ }
+ Box2D.inherit(b2FrictionJoint, Box2D.Dynamics.Joints.b2Joint);
+ b2FrictionJoint.prototype.__super = Box2D.Dynamics.Joints.b2Joint.prototype;
+ b2FrictionJoint.b2FrictionJoint = function () {
+ Box2D.Dynamics.Joints.b2Joint.b2Joint.apply(this, arguments);
+ this.m_localAnchorA = new b2Vec2();
+ this.m_localAnchorB = new b2Vec2();
+ this.m_linearMass = new b2Mat22();
+ this.m_linearImpulse = new b2Vec2();
+ };
+ b2FrictionJoint.prototype.GetAnchorA = function () {
+ return this.m_bodyA.GetWorldPoint(this.m_localAnchorA);
+ }
+ b2FrictionJoint.prototype.GetAnchorB = function () {
+ return this.m_bodyB.GetWorldPoint(this.m_localAnchorB);
+ }
+ b2FrictionJoint.prototype.GetReactionForce = function (inv_dt) {
+ if (inv_dt === undefined) inv_dt = 0;
+ return new b2Vec2(inv_dt * this.m_linearImpulse.x, inv_dt * this.m_linearImpulse.y);
+ }
+ b2FrictionJoint.prototype.GetReactionTorque = function (inv_dt) {
+ if (inv_dt === undefined) inv_dt = 0;
+ return inv_dt * this.m_angularImpulse;
+ }
+ b2FrictionJoint.prototype.SetMaxForce = function (force) {
+ if (force === undefined) force = 0;
+ this.m_maxForce = force;
+ }
+ b2FrictionJoint.prototype.GetMaxForce = function () {
+ return this.m_maxForce;
+ }
+ b2FrictionJoint.prototype.SetMaxTorque = function (torque) {
+ if (torque === undefined) torque = 0;
+ this.m_maxTorque = torque;
+ }
+ b2FrictionJoint.prototype.GetMaxTorque = function () {
+ return this.m_maxTorque;
+ }
+ b2FrictionJoint.prototype.b2FrictionJoint = function (def) {
+ this.__super.b2Joint.call(this, def);
+ this.m_localAnchorA.SetV(def.localAnchorA);
+ this.m_localAnchorB.SetV(def.localAnchorB);
+ this.m_linearMass.SetZero();
+ this.m_angularMass = 0.0;
+ this.m_linearImpulse.SetZero();
+ this.m_angularImpulse = 0.0;
+ this.m_maxForce = def.maxForce;
+ this.m_maxTorque = def.maxTorque;
+ }
+ b2FrictionJoint.prototype.InitVelocityConstraints = function (step) {
+ var tMat;
+ var tX = 0;
+ var bA = this.m_bodyA;
+ var bB = this.m_bodyB;
+ tMat = bA.m_xf.R;
+ var rAX = this.m_localAnchorA.x - bA.m_sweep.localCenter.x;
+ var rAY = this.m_localAnchorA.y - bA.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * rAX + tMat.col2.x * rAY);
+ rAY = (tMat.col1.y * rAX + tMat.col2.y * rAY);
+ rAX = tX;
+ tMat = bB.m_xf.R;
+ var rBX = this.m_localAnchorB.x - bB.m_sweep.localCenter.x;
+ var rBY = this.m_localAnchorB.y - bB.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * rBX + tMat.col2.x * rBY);
+ rBY = (tMat.col1.y * rBX + tMat.col2.y * rBY);
+ rBX = tX;
+ var mA = bA.m_invMass;
+ var mB = bB.m_invMass;
+ var iA = bA.m_invI;
+ var iB = bB.m_invI;
+ var K = new b2Mat22();
+ K.col1.x = mA + mB;
+ K.col2.x = 0.0;
+ K.col1.y = 0.0;
+ K.col2.y = mA + mB;
+ K.col1.x += iA * rAY * rAY;
+ K.col2.x += (-iA * rAX * rAY);
+ K.col1.y += (-iA * rAX * rAY);
+ K.col2.y += iA * rAX * rAX;
+ K.col1.x += iB * rBY * rBY;
+ K.col2.x += (-iB * rBX * rBY);
+ K.col1.y += (-iB * rBX * rBY);
+ K.col2.y += iB * rBX * rBX;
+ K.GetInverse(this.m_linearMass);
+ this.m_angularMass = iA + iB;
+ if (this.m_angularMass > 0.0) {
+ this.m_angularMass = 1.0 / this.m_angularMass;
+ }
+ if (step.warmStarting) {
+ this.m_linearImpulse.x *= step.dtRatio;
+ this.m_linearImpulse.y *= step.dtRatio;
+ this.m_angularImpulse *= step.dtRatio;
+ var P = this.m_linearImpulse;
+ bA.m_linearVelocity.x -= mA * P.x;
+ bA.m_linearVelocity.y -= mA * P.y;
+ bA.m_angularVelocity -= iA * (rAX * P.y - rAY * P.x + this.m_angularImpulse);
+ bB.m_linearVelocity.x += mB * P.x;
+ bB.m_linearVelocity.y += mB * P.y;
+ bB.m_angularVelocity += iB * (rBX * P.y - rBY * P.x + this.m_angularImpulse);
+ }
+ else {
+ this.m_linearImpulse.SetZero();
+ this.m_angularImpulse = 0.0;
+ }
+ }
+ b2FrictionJoint.prototype.SolveVelocityConstraints = function (step) {
+ var tMat;
+ var tX = 0;
+ var bA = this.m_bodyA;
+ var bB = this.m_bodyB;
+ var vA = bA.m_linearVelocity;
+ var wA = bA.m_angularVelocity;
+ var vB = bB.m_linearVelocity;
+ var wB = bB.m_angularVelocity;
+ var mA = bA.m_invMass;
+ var mB = bB.m_invMass;
+ var iA = bA.m_invI;
+ var iB = bB.m_invI;
+ tMat = bA.m_xf.R;
+ var rAX = this.m_localAnchorA.x - bA.m_sweep.localCenter.x;
+ var rAY = this.m_localAnchorA.y - bA.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * rAX + tMat.col2.x * rAY);
+ rAY = (tMat.col1.y * rAX + tMat.col2.y * rAY);
+ rAX = tX;
+ tMat = bB.m_xf.R;
+ var rBX = this.m_localAnchorB.x - bB.m_sweep.localCenter.x;
+ var rBY = this.m_localAnchorB.y - bB.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * rBX + tMat.col2.x * rBY);
+ rBY = (tMat.col1.y * rBX + tMat.col2.y * rBY);
+ rBX = tX;
+ var maxImpulse = 0; {
+ var Cdot = wB - wA;
+ var impulse = (-this.m_angularMass * Cdot);
+ var oldImpulse = this.m_angularImpulse;
+ maxImpulse = step.dt * this.m_maxTorque;
+ this.m_angularImpulse = b2Math.Clamp(this.m_angularImpulse + impulse, (-maxImpulse), maxImpulse);
+ impulse = this.m_angularImpulse - oldImpulse;
+ wA -= iA * impulse;
+ wB += iB * impulse;
+ } {
+ var CdotX = vB.x - wB * rBY - vA.x + wA * rAY;
+ var CdotY = vB.y + wB * rBX - vA.y - wA * rAX;
+ var impulseV = b2Math.MulMV(this.m_linearMass, new b2Vec2((-CdotX), (-CdotY)));
+ var oldImpulseV = this.m_linearImpulse.Copy();
+ this.m_linearImpulse.Add(impulseV);
+ maxImpulse = step.dt * this.m_maxForce;
+ if (this.m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse) {
+ this.m_linearImpulse.Normalize();
+ this.m_linearImpulse.Multiply(maxImpulse);
+ }
+ impulseV = b2Math.SubtractVV(this.m_linearImpulse, oldImpulseV);
+ vA.x -= mA * impulseV.x;
+ vA.y -= mA * impulseV.y;
+ wA -= iA * (rAX * impulseV.y - rAY * impulseV.x);
+ vB.x += mB * impulseV.x;
+ vB.y += mB * impulseV.y;
+ wB += iB * (rBX * impulseV.y - rBY * impulseV.x);
+ }
+ bA.m_angularVelocity = wA;
+ bB.m_angularVelocity = wB;
+ }
+ b2FrictionJoint.prototype.SolvePositionConstraints = function (baumgarte) {
+ if (baumgarte === undefined) baumgarte = 0;
+ return true;
+ }
+ Box2D.inherit(b2FrictionJointDef, Box2D.Dynamics.Joints.b2JointDef);
+ b2FrictionJointDef.prototype.__super = Box2D.Dynamics.Joints.b2JointDef.prototype;
+ b2FrictionJointDef.b2FrictionJointDef = function () {
+ Box2D.Dynamics.Joints.b2JointDef.b2JointDef.apply(this, arguments);
+ this.localAnchorA = new b2Vec2();
+ this.localAnchorB = new b2Vec2();
+ };
+ b2FrictionJointDef.prototype.b2FrictionJointDef = function () {
+ this.__super.b2JointDef.call(this);
+ this.type = b2Joint.e_frictionJoint;
+ this.maxForce = 0.0;
+ this.maxTorque = 0.0;
+ }
+ b2FrictionJointDef.prototype.Initialize = function (bA, bB, anchor) {
+ this.bodyA = bA;
+ this.bodyB = bB;
+ this.localAnchorA.SetV(this.bodyA.GetLocalPoint(anchor));
+ this.localAnchorB.SetV(this.bodyB.GetLocalPoint(anchor));
+ }
+ Box2D.inherit(b2GearJoint, Box2D.Dynamics.Joints.b2Joint);
+ b2GearJoint.prototype.__super = Box2D.Dynamics.Joints.b2Joint.prototype;
+ b2GearJoint.b2GearJoint = function () {
+ Box2D.Dynamics.Joints.b2Joint.b2Joint.apply(this, arguments);
+ this.m_groundAnchor1 = new b2Vec2();
+ this.m_groundAnchor2 = new b2Vec2();
+ this.m_localAnchor1 = new b2Vec2();
+ this.m_localAnchor2 = new b2Vec2();
+ this.m_J = new b2Jacobian();
+ };
+ b2GearJoint.prototype.GetAnchorA = function () {
+ return this.m_bodyA.GetWorldPoint(this.m_localAnchor1);
+ }
+ b2GearJoint.prototype.GetAnchorB = function () {
+ return this.m_bodyB.GetWorldPoint(this.m_localAnchor2);
+ }
+ b2GearJoint.prototype.GetReactionForce = function (inv_dt) {
+ if (inv_dt === undefined) inv_dt = 0;
+ return new b2Vec2(inv_dt * this.m_impulse * this.m_J.linearB.x, inv_dt * this.m_impulse * this.m_J.linearB.y);
+ }
+ b2GearJoint.prototype.GetReactionTorque = function (inv_dt) {
+ if (inv_dt === undefined) inv_dt = 0;
+ var tMat = this.m_bodyB.m_xf.R;
+ var rX = this.m_localAnchor1.x - this.m_bodyB.m_sweep.localCenter.x;
+ var rY = this.m_localAnchor1.y - this.m_bodyB.m_sweep.localCenter.y;
+ var tX = tMat.col1.x * rX + tMat.col2.x * rY;
+ rY = tMat.col1.y * rX + tMat.col2.y * rY;
+ rX = tX;
+ var PX = this.m_impulse * this.m_J.linearB.x;
+ var PY = this.m_impulse * this.m_J.linearB.y;
+ return inv_dt * (this.m_impulse * this.m_J.angularB - rX * PY + rY * PX);
+ }
+ b2GearJoint.prototype.GetRatio = function () {
+ return this.m_ratio;
+ }
+ b2GearJoint.prototype.SetRatio = function (ratio) {
+ if (ratio === undefined) ratio = 0;
+ this.m_ratio = ratio;
+ }
+ b2GearJoint.prototype.b2GearJoint = function (def) {
+ this.__super.b2Joint.call(this, def);
+ var type1 = parseInt(def.joint1.m_type);
+ var type2 = parseInt(def.joint2.m_type);
+ this.m_revolute1 = null;
+ this.m_prismatic1 = null;
+ this.m_revolute2 = null;
+ this.m_prismatic2 = null;
+ var coordinate1 = 0;
+ var coordinate2 = 0;
+ this.m_ground1 = def.joint1.GetBodyA();
+ this.m_bodyA = def.joint1.GetBodyB();
+ if (type1 == b2Joint.e_revoluteJoint) {
+ this.m_revolute1 = (def.joint1 instanceof b2RevoluteJoint ? def.joint1 : null);
+ this.m_groundAnchor1.SetV(this.m_revolute1.m_localAnchor1);
+ this.m_localAnchor1.SetV(this.m_revolute1.m_localAnchor2);
+ coordinate1 = this.m_revolute1.GetJointAngle();
+ }
+ else {
+ this.m_prismatic1 = (def.joint1 instanceof b2PrismaticJoint ? def.joint1 : null);
+ this.m_groundAnchor1.SetV(this.m_prismatic1.m_localAnchor1);
+ this.m_localAnchor1.SetV(this.m_prismatic1.m_localAnchor2);
+ coordinate1 = this.m_prismatic1.GetJointTranslation();
+ }
+ this.m_ground2 = def.joint2.GetBodyA();
+ this.m_bodyB = def.joint2.GetBodyB();
+ if (type2 == b2Joint.e_revoluteJoint) {
+ this.m_revolute2 = (def.joint2 instanceof b2RevoluteJoint ? def.joint2 : null);
+ this.m_groundAnchor2.SetV(this.m_revolute2.m_localAnchor1);
+ this.m_localAnchor2.SetV(this.m_revolute2.m_localAnchor2);
+ coordinate2 = this.m_revolute2.GetJointAngle();
+ }
+ else {
+ this.m_prismatic2 = (def.joint2 instanceof b2PrismaticJoint ? def.joint2 : null);
+ this.m_groundAnchor2.SetV(this.m_prismatic2.m_localAnchor1);
+ this.m_localAnchor2.SetV(this.m_prismatic2.m_localAnchor2);
+ coordinate2 = this.m_prismatic2.GetJointTranslation();
+ }
+ this.m_ratio = def.ratio;
+ this.m_constant = coordinate1 + this.m_ratio * coordinate2;
+ this.m_impulse = 0.0;
+ }
+ b2GearJoint.prototype.InitVelocityConstraints = function (step) {
+ var g1 = this.m_ground1;
+ var g2 = this.m_ground2;
+ var bA = this.m_bodyA;
+ var bB = this.m_bodyB;
+ var ugX = 0;
+ var ugY = 0;
+ var rX = 0;
+ var rY = 0;
+ var tMat;
+ var tVec;
+ var crug = 0;
+ var tX = 0;
+ var K = 0.0;
+ this.m_J.SetZero();
+ if (this.m_revolute1) {
+ this.m_J.angularA = (-1.0);
+ K += bA.m_invI;
+ }
+ else {
+ tMat = g1.m_xf.R;
+ tVec = this.m_prismatic1.m_localXAxis1;
+ ugX = tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
+ ugY = tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
+ tMat = bA.m_xf.R;
+ rX = this.m_localAnchor1.x - bA.m_sweep.localCenter.x;
+ rY = this.m_localAnchor1.y - bA.m_sweep.localCenter.y;
+ tX = tMat.col1.x * rX + tMat.col2.x * rY;
+ rY = tMat.col1.y * rX + tMat.col2.y * rY;
+ rX = tX;
+ crug = rX * ugY - rY * ugX;
+ this.m_J.linearA.Set((-ugX), (-ugY));
+ this.m_J.angularA = (-crug);
+ K += bA.m_invMass + bA.m_invI * crug * crug;
+ }
+ if (this.m_revolute2) {
+ this.m_J.angularB = (-this.m_ratio);
+ K += this.m_ratio * this.m_ratio * bB.m_invI;
+ }
+ else {
+ tMat = g2.m_xf.R;
+ tVec = this.m_prismatic2.m_localXAxis1;
+ ugX = tMat.col1.x * tVec.x + tMat.col2.x * tVec.y;
+ ugY = tMat.col1.y * tVec.x + tMat.col2.y * tVec.y;
+ tMat = bB.m_xf.R;
+ rX = this.m_localAnchor2.x - bB.m_sweep.localCenter.x;
+ rY = this.m_localAnchor2.y - bB.m_sweep.localCenter.y;
+ tX = tMat.col1.x * rX + tMat.col2.x * rY;
+ rY = tMat.col1.y * rX + tMat.col2.y * rY;
+ rX = tX;
+ crug = rX * ugY - rY * ugX;
+ this.m_J.linearB.Set((-this.m_ratio * ugX), (-this.m_ratio * ugY));
+ this.m_J.angularB = (-this.m_ratio * crug);
+ K += this.m_ratio * this.m_ratio * (bB.m_invMass + bB.m_invI * crug * crug);
+ }
+ this.m_mass = K > 0.0 ? 1.0 / K : 0.0;
+ if (step.warmStarting) {
+ bA.m_linearVelocity.x += bA.m_invMass * this.m_impulse * this.m_J.linearA.x;
+ bA.m_linearVelocity.y += bA.m_invMass * this.m_impulse * this.m_J.linearA.y;
+ bA.m_angularVelocity += bA.m_invI * this.m_impulse * this.m_J.angularA;
+ bB.m_linearVelocity.x += bB.m_invMass * this.m_impulse * this.m_J.linearB.x;
+ bB.m_linearVelocity.y += bB.m_invMass * this.m_impulse * this.m_J.linearB.y;
+ bB.m_angularVelocity += bB.m_invI * this.m_impulse * this.m_J.angularB;
+ }
+ else {
+ this.m_impulse = 0.0;
+ }
+ }
+ b2GearJoint.prototype.SolveVelocityConstraints = function (step) {
+ var bA = this.m_bodyA;
+ var bB = this.m_bodyB;
+ var Cdot = this.m_J.Compute(bA.m_linearVelocity, bA.m_angularVelocity, bB.m_linearVelocity, bB.m_angularVelocity);
+ var impulse = (-this.m_mass * Cdot);
+ this.m_impulse += impulse;
+ bA.m_linearVelocity.x += bA.m_invMass * impulse * this.m_J.linearA.x;
+ bA.m_linearVelocity.y += bA.m_invMass * impulse * this.m_J.linearA.y;
+ bA.m_angularVelocity += bA.m_invI * impulse * this.m_J.angularA;
+ bB.m_linearVelocity.x += bB.m_invMass * impulse * this.m_J.linearB.x;
+ bB.m_linearVelocity.y += bB.m_invMass * impulse * this.m_J.linearB.y;
+ bB.m_angularVelocity += bB.m_invI * impulse * this.m_J.angularB;
+ }
+ b2GearJoint.prototype.SolvePositionConstraints = function (baumgarte) {
+ if (baumgarte === undefined) baumgarte = 0;
+ var linearError = 0.0;
+ var bA = this.m_bodyA;
+ var bB = this.m_bodyB;
+ var coordinate1 = 0;
+ var coordinate2 = 0;
+ if (this.m_revolute1) {
+ coordinate1 = this.m_revolute1.GetJointAngle();
+ }
+ else {
+ coordinate1 = this.m_prismatic1.GetJointTranslation();
+ }
+ if (this.m_revolute2) {
+ coordinate2 = this.m_revolute2.GetJointAngle();
+ }
+ else {
+ coordinate2 = this.m_prismatic2.GetJointTranslation();
+ }
+ var C = this.m_constant - (coordinate1 + this.m_ratio * coordinate2);
+ var impulse = (-this.m_mass * C);
+ bA.m_sweep.c.x += bA.m_invMass * impulse * this.m_J.linearA.x;
+ bA.m_sweep.c.y += bA.m_invMass * impulse * this.m_J.linearA.y;
+ bA.m_sweep.a += bA.m_invI * impulse * this.m_J.angularA;
+ bB.m_sweep.c.x += bB.m_invMass * impulse * this.m_J.linearB.x;
+ bB.m_sweep.c.y += bB.m_invMass * impulse * this.m_J.linearB.y;
+ bB.m_sweep.a += bB.m_invI * impulse * this.m_J.angularB;
+ bA.SynchronizeTransform();
+ bB.SynchronizeTransform();
+ return linearError < b2Settings.b2_linearSlop;
+ }
+ Box2D.inherit(b2GearJointDef, Box2D.Dynamics.Joints.b2JointDef);
+ b2GearJointDef.prototype.__super = Box2D.Dynamics.Joints.b2JointDef.prototype;
+ b2GearJointDef.b2GearJointDef = function () {
+ Box2D.Dynamics.Joints.b2JointDef.b2JointDef.apply(this, arguments);
+ };
+ b2GearJointDef.prototype.b2GearJointDef = function () {
+ this.__super.b2JointDef.call(this);
+ this.type = b2Joint.e_gearJoint;
+ this.joint1 = null;
+ this.joint2 = null;
+ this.ratio = 1.0;
+ }
+ b2Jacobian.b2Jacobian = function () {
+ this.linearA = new b2Vec2();
+ this.linearB = new b2Vec2();
+ };
+ b2Jacobian.prototype.SetZero = function () {
+ this.linearA.SetZero();
+ this.angularA = 0.0;
+ this.linearB.SetZero();
+ this.angularB = 0.0;
+ }
+ b2Jacobian.prototype.Set = function (x1, a1, x2, a2) {
+ if (a1 === undefined) a1 = 0;
+ if (a2 === undefined) a2 = 0;
+ this.linearA.SetV(x1);
+ this.angularA = a1;
+ this.linearB.SetV(x2);
+ this.angularB = a2;
+ }
+ b2Jacobian.prototype.Compute = function (x1, a1, x2, a2) {
+ if (a1 === undefined) a1 = 0;
+ if (a2 === undefined) a2 = 0;
+ return (this.linearA.x * x1.x + this.linearA.y * x1.y) + this.angularA * a1 + (this.linearB.x * x2.x + this.linearB.y * x2.y) + this.angularB * a2;
+ }
+ b2Joint.b2Joint = function () {
+ this.m_edgeA = new b2JointEdge();
+ this.m_edgeB = new b2JointEdge();
+ this.m_localCenterA = new b2Vec2();
+ this.m_localCenterB = new b2Vec2();
+ };
+ b2Joint.prototype.GetType = function () {
+ return this.m_type;
+ }
+ b2Joint.prototype.GetAnchorA = function () {
+ return null;
+ }
+ b2Joint.prototype.GetAnchorB = function () {
+ return null;
+ }
+ b2Joint.prototype.GetReactionForce = function (inv_dt) {
+ if (inv_dt === undefined) inv_dt = 0;
+ return null;
+ }
+ b2Joint.prototype.GetReactionTorque = function (inv_dt) {
+ if (inv_dt === undefined) inv_dt = 0;
+ return 0.0;
+ }
+ b2Joint.prototype.GetBodyA = function () {
+ return this.m_bodyA;
+ }
+ b2Joint.prototype.GetBodyB = function () {
+ return this.m_bodyB;
+ }
+ b2Joint.prototype.GetNext = function () {
+ return this.m_next;
+ }
+ b2Joint.prototype.GetUserData = function () {
+ return this.m_userData;
+ }
+ b2Joint.prototype.SetUserData = function (data) {
+ this.m_userData = data;
+ }
+ b2Joint.prototype.IsActive = function () {
+ return this.m_bodyA.IsActive() && this.m_bodyB.IsActive();
+ }
+ b2Joint.Create = function (def, allocator) {
+ var joint = null;
+ switch (def.type) {
+ case b2Joint.e_distanceJoint:
+ {
+ joint = new b2DistanceJoint((def instanceof b2DistanceJointDef ? def : null));
+ }
+ break;
+ case b2Joint.e_mouseJoint:
+ {
+ joint = new b2MouseJoint((def instanceof b2MouseJointDef ? def : null));
+ }
+ break;
+ case b2Joint.e_prismaticJoint:
+ {
+ joint = new b2PrismaticJoint((def instanceof b2PrismaticJointDef ? def : null));
+ }
+ break;
+ case b2Joint.e_revoluteJoint:
+ {
+ joint = new b2RevoluteJoint((def instanceof b2RevoluteJointDef ? def : null));
+ }
+ break;
+ case b2Joint.e_pulleyJoint:
+ {
+ joint = new b2PulleyJoint((def instanceof b2PulleyJointDef ? def : null));
+ }
+ break;
+ case b2Joint.e_gearJoint:
+ {
+ joint = new b2GearJoint((def instanceof b2GearJointDef ? def : null));
+ }
+ break;
+ case b2Joint.e_lineJoint:
+ {
+ joint = new b2LineJoint((def instanceof b2LineJointDef ? def : null));
+ }
+ break;
+ case b2Joint.e_weldJoint:
+ {
+ joint = new b2WeldJoint((def instanceof b2WeldJointDef ? def : null));
+ }
+ break;
+ case b2Joint.e_frictionJoint:
+ {
+ joint = new b2FrictionJoint((def instanceof b2FrictionJointDef ? def : null));
+ }
+ break;
+ default:
+ break;
+ }
+ return joint;
+ }
+ b2Joint.Destroy = function (joint, allocator) {}
+ b2Joint.prototype.b2Joint = function (def) {
+ b2Settings.b2Assert(def.bodyA != def.bodyB);
+ this.m_type = def.type;
+ this.m_prev = null;
+ this.m_next = null;
+ this.m_bodyA = def.bodyA;
+ this.m_bodyB = def.bodyB;
+ this.m_collideConnected = def.collideConnected;
+ this.m_islandFlag = false;
+ this.m_userData = def.userData;
+ }
+ b2Joint.prototype.InitVelocityConstraints = function (step) {}
+ b2Joint.prototype.SolveVelocityConstraints = function (step) {}
+ b2Joint.prototype.FinalizeVelocityConstraints = function () {}
+ b2Joint.prototype.SolvePositionConstraints = function (baumgarte) {
+ if (baumgarte === undefined) baumgarte = 0;
+ return false;
+ }
+ Box2D.postDefs.push(function () {
+ Box2D.Dynamics.Joints.b2Joint.e_unknownJoint = 0;
+ Box2D.Dynamics.Joints.b2Joint.e_revoluteJoint = 1;
+ Box2D.Dynamics.Joints.b2Joint.e_prismaticJoint = 2;
+ Box2D.Dynamics.Joints.b2Joint.e_distanceJoint = 3;
+ Box2D.Dynamics.Joints.b2Joint.e_pulleyJoint = 4;
+ Box2D.Dynamics.Joints.b2Joint.e_mouseJoint = 5;
+ Box2D.Dynamics.Joints.b2Joint.e_gearJoint = 6;
+ Box2D.Dynamics.Joints.b2Joint.e_lineJoint = 7;
+ Box2D.Dynamics.Joints.b2Joint.e_weldJoint = 8;
+ Box2D.Dynamics.Joints.b2Joint.e_frictionJoint = 9;
+ Box2D.Dynamics.Joints.b2Joint.e_inactiveLimit = 0;
+ Box2D.Dynamics.Joints.b2Joint.e_atLowerLimit = 1;
+ Box2D.Dynamics.Joints.b2Joint.e_atUpperLimit = 2;
+ Box2D.Dynamics.Joints.b2Joint.e_equalLimits = 3;
+ });
+ b2JointDef.b2JointDef = function () {};
+ b2JointDef.prototype.b2JointDef = function () {
+ this.type = b2Joint.e_unknownJoint;
+ this.userData = null;
+ this.bodyA = null;
+ this.bodyB = null;
+ this.collideConnected = false;
+ }
+ b2JointEdge.b2JointEdge = function () {};
+ Box2D.inherit(b2LineJoint, Box2D.Dynamics.Joints.b2Joint);
+ b2LineJoint.prototype.__super = Box2D.Dynamics.Joints.b2Joint.prototype;
+ b2LineJoint.b2LineJoint = function () {
+ Box2D.Dynamics.Joints.b2Joint.b2Joint.apply(this, arguments);
+ this.m_localAnchor1 = new b2Vec2();
+ this.m_localAnchor2 = new b2Vec2();
+ this.m_localXAxis1 = new b2Vec2();
+ this.m_localYAxis1 = new b2Vec2();
+ this.m_axis = new b2Vec2();
+ this.m_perp = new b2Vec2();
+ this.m_K = new b2Mat22();
+ this.m_impulse = new b2Vec2();
+ };
+ b2LineJoint.prototype.GetAnchorA = function () {
+ return this.m_bodyA.GetWorldPoint(this.m_localAnchor1);
+ }
+ b2LineJoint.prototype.GetAnchorB = function () {
+ return this.m_bodyB.GetWorldPoint(this.m_localAnchor2);
+ }
+ b2LineJoint.prototype.GetReactionForce = function (inv_dt) {
+ if (inv_dt === undefined) inv_dt = 0;
+ return new b2Vec2(inv_dt * (this.m_impulse.x * this.m_perp.x + (this.m_motorImpulse + this.m_impulse.y) * this.m_axis.x), inv_dt * (this.m_impulse.x * this.m_perp.y + (this.m_motorImpulse + this.m_impulse.y) * this.m_axis.y));
+ }
+ b2LineJoint.prototype.GetReactionTorque = function (inv_dt) {
+ if (inv_dt === undefined) inv_dt = 0;
+ return inv_dt * this.m_impulse.y;
+ }
+ b2LineJoint.prototype.GetJointTranslation = function () {
+ var bA = this.m_bodyA;
+ var bB = this.m_bodyB;
+ var tMat;
+ var p1 = bA.GetWorldPoint(this.m_localAnchor1);
+ var p2 = bB.GetWorldPoint(this.m_localAnchor2);
+ var dX = p2.x - p1.x;
+ var dY = p2.y - p1.y;
+ var axis = bA.GetWorldVector(this.m_localXAxis1);
+ var translation = axis.x * dX + axis.y * dY;
+ return translation;
+ }
+ b2LineJoint.prototype.GetJointSpeed = function () {
+ var bA = this.m_bodyA;
+ var bB = this.m_bodyB;
+ var tMat;
+ tMat = bA.m_xf.R;
+ var r1X = this.m_localAnchor1.x - bA.m_sweep.localCenter.x;
+ var r1Y = this.m_localAnchor1.y - bA.m_sweep.localCenter.y;
+ var tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
+ r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
+ r1X = tX;
+ tMat = bB.m_xf.R;
+ var r2X = this.m_localAnchor2.x - bB.m_sweep.localCenter.x;
+ var r2Y = this.m_localAnchor2.y - bB.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
+ r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
+ r2X = tX;
+ var p1X = bA.m_sweep.c.x + r1X;
+ var p1Y = bA.m_sweep.c.y + r1Y;
+ var p2X = bB.m_sweep.c.x + r2X;
+ var p2Y = bB.m_sweep.c.y + r2Y;
+ var dX = p2X - p1X;
+ var dY = p2Y - p1Y;
+ var axis = bA.GetWorldVector(this.m_localXAxis1);
+ var v1 = bA.m_linearVelocity;
+ var v2 = bB.m_linearVelocity;
+ var w1 = bA.m_angularVelocity;
+ var w2 = bB.m_angularVelocity;
+ var speed = (dX * ((-w1 * axis.y)) + dY * (w1 * axis.x)) + (axis.x * (((v2.x + ((-w2 * r2Y))) - v1.x) - ((-w1 * r1Y))) + axis.y * (((v2.y + (w2 * r2X)) - v1.y) - (w1 * r1X)));
+ return speed;
+ }
+ b2LineJoint.prototype.IsLimitEnabled = function () {
+ return this.m_enableLimit;
+ }
+ b2LineJoint.prototype.EnableLimit = function (flag) {
+ this.m_bodyA.SetAwake(true);
+ this.m_bodyB.SetAwake(true);
+ this.m_enableLimit = flag;
+ }
+ b2LineJoint.prototype.GetLowerLimit = function () {
+ return this.m_lowerTranslation;
+ }
+ b2LineJoint.prototype.GetUpperLimit = function () {
+ return this.m_upperTranslation;
+ }
+ b2LineJoint.prototype.SetLimits = function (lower, upper) {
+ if (lower === undefined) lower = 0;
+ if (upper === undefined) upper = 0;
+ this.m_bodyA.SetAwake(true);
+ this.m_bodyB.SetAwake(true);
+ this.m_lowerTranslation = lower;
+ this.m_upperTranslation = upper;
+ }
+ b2LineJoint.prototype.IsMotorEnabled = function () {
+ return this.m_enableMotor;
+ }
+ b2LineJoint.prototype.EnableMotor = function (flag) {
+ this.m_bodyA.SetAwake(true);
+ this.m_bodyB.SetAwake(true);
+ this.m_enableMotor = flag;
+ }
+ b2LineJoint.prototype.SetMotorSpeed = function (speed) {
+ if (speed === undefined) speed = 0;
+ this.m_bodyA.SetAwake(true);
+ this.m_bodyB.SetAwake(true);
+ this.m_motorSpeed = speed;
+ }
+ b2LineJoint.prototype.GetMotorSpeed = function () {
+ return this.m_motorSpeed;
+ }
+ b2LineJoint.prototype.SetMaxMotorForce = function (force) {
+ if (force === undefined) force = 0;
+ this.m_bodyA.SetAwake(true);
+ this.m_bodyB.SetAwake(true);
+ this.m_maxMotorForce = force;
+ }
+ b2LineJoint.prototype.GetMaxMotorForce = function () {
+ return this.m_maxMotorForce;
+ }
+ b2LineJoint.prototype.GetMotorForce = function () {
+ return this.m_motorImpulse;
+ }
+ b2LineJoint.prototype.b2LineJoint = function (def) {
+ this.__super.b2Joint.call(this, def);
+ var tMat;
+ var tX = 0;
+ var tY = 0;
+ this.m_localAnchor1.SetV(def.localAnchorA);
+ this.m_localAnchor2.SetV(def.localAnchorB);
+ this.m_localXAxis1.SetV(def.localAxisA);
+ this.m_localYAxis1.x = (-this.m_localXAxis1.y);
+ this.m_localYAxis1.y = this.m_localXAxis1.x;
+ this.m_impulse.SetZero();
+ this.m_motorMass = 0.0;
+ this.m_motorImpulse = 0.0;
+ this.m_lowerTranslation = def.lowerTranslation;
+ this.m_upperTranslation = def.upperTranslation;
+ this.m_maxMotorForce = def.maxMotorForce;
+ this.m_motorSpeed = def.motorSpeed;
+ this.m_enableLimit = def.enableLimit;
+ this.m_enableMotor = def.enableMotor;
+ this.m_limitState = b2Joint.e_inactiveLimit;
+ this.m_axis.SetZero();
+ this.m_perp.SetZero();
+ }
+ b2LineJoint.prototype.InitVelocityConstraints = function (step) {
+ var bA = this.m_bodyA;
+ var bB = this.m_bodyB;
+ var tMat;
+ var tX = 0;
+ this.m_localCenterA.SetV(bA.GetLocalCenter());
+ this.m_localCenterB.SetV(bB.GetLocalCenter());
+ var xf1 = bA.GetTransform();
+ var xf2 = bB.GetTransform();
+ tMat = bA.m_xf.R;
+ var r1X = this.m_localAnchor1.x - this.m_localCenterA.x;
+ var r1Y = this.m_localAnchor1.y - this.m_localCenterA.y;
+ tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
+ r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
+ r1X = tX;
+ tMat = bB.m_xf.R;
+ var r2X = this.m_localAnchor2.x - this.m_localCenterB.x;
+ var r2Y = this.m_localAnchor2.y - this.m_localCenterB.y;
+ tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
+ r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
+ r2X = tX;
+ var dX = bB.m_sweep.c.x + r2X - bA.m_sweep.c.x - r1X;
+ var dY = bB.m_sweep.c.y + r2Y - bA.m_sweep.c.y - r1Y;
+ this.m_invMassA = bA.m_invMass;
+ this.m_invMassB = bB.m_invMass;
+ this.m_invIA = bA.m_invI;
+ this.m_invIB = bB.m_invI; {
+ this.m_axis.SetV(b2Math.MulMV(xf1.R, this.m_localXAxis1));
+ this.m_a1 = (dX + r1X) * this.m_axis.y - (dY + r1Y) * this.m_axis.x;
+ this.m_a2 = r2X * this.m_axis.y - r2Y * this.m_axis.x;
+ this.m_motorMass = this.m_invMassA + this.m_invMassB + this.m_invIA * this.m_a1 * this.m_a1 + this.m_invIB * this.m_a2 * this.m_a2;
+ this.m_motorMass = this.m_motorMass > Number.MIN_VALUE ? 1.0 / this.m_motorMass : 0.0;
+ } {
+ this.m_perp.SetV(b2Math.MulMV(xf1.R, this.m_localYAxis1));
+ this.m_s1 = (dX + r1X) * this.m_perp.y - (dY + r1Y) * this.m_perp.x;
+ this.m_s2 = r2X * this.m_perp.y - r2Y * this.m_perp.x;
+ var m1 = this.m_invMassA;
+ var m2 = this.m_invMassB;
+ var i1 = this.m_invIA;
+ var i2 = this.m_invIB;
+ this.m_K.col1.x = m1 + m2 + i1 * this.m_s1 * this.m_s1 + i2 * this.m_s2 * this.m_s2;
+ this.m_K.col1.y = i1 * this.m_s1 * this.m_a1 + i2 * this.m_s2 * this.m_a2;
+ this.m_K.col2.x = this.m_K.col1.y;
+ this.m_K.col2.y = m1 + m2 + i1 * this.m_a1 * this.m_a1 + i2 * this.m_a2 * this.m_a2;
+ }
+ if (this.m_enableLimit) {
+ var jointTransition = this.m_axis.x * dX + this.m_axis.y * dY;
+ if (b2Math.Abs(this.m_upperTranslation - this.m_lowerTranslation) < 2.0 * b2Settings.b2_linearSlop) {
+ this.m_limitState = b2Joint.e_equalLimits;
+ }
+ else if (jointTransition <= this.m_lowerTranslation) {
+ if (this.m_limitState != b2Joint.e_atLowerLimit) {
+ this.m_limitState = b2Joint.e_atLowerLimit;
+ this.m_impulse.y = 0.0;
+ }
+ }
+ else if (jointTransition >= this.m_upperTranslation) {
+ if (this.m_limitState != b2Joint.e_atUpperLimit) {
+ this.m_limitState = b2Joint.e_atUpperLimit;
+ this.m_impulse.y = 0.0;
+ }
+ }
+ else {
+ this.m_limitState = b2Joint.e_inactiveLimit;
+ this.m_impulse.y = 0.0;
+ }
+ }
+ else {
+ this.m_limitState = b2Joint.e_inactiveLimit;
+ }
+ if (this.m_enableMotor == false) {
+ this.m_motorImpulse = 0.0;
+ }
+ if (step.warmStarting) {
+ this.m_impulse.x *= step.dtRatio;
+ this.m_impulse.y *= step.dtRatio;
+ this.m_motorImpulse *= step.dtRatio;
+ var PX = this.m_impulse.x * this.m_perp.x + (this.m_motorImpulse + this.m_impulse.y) * this.m_axis.x;
+ var PY = this.m_impulse.x * this.m_perp.y + (this.m_motorImpulse + this.m_impulse.y) * this.m_axis.y;
+ var L1 = this.m_impulse.x * this.m_s1 + (this.m_motorImpulse + this.m_impulse.y) * this.m_a1;
+ var L2 = this.m_impulse.x * this.m_s2 + (this.m_motorImpulse + this.m_impulse.y) * this.m_a2;
+ bA.m_linearVelocity.x -= this.m_invMassA * PX;
+ bA.m_linearVelocity.y -= this.m_invMassA * PY;
+ bA.m_angularVelocity -= this.m_invIA * L1;
+ bB.m_linearVelocity.x += this.m_invMassB * PX;
+ bB.m_linearVelocity.y += this.m_invMassB * PY;
+ bB.m_angularVelocity += this.m_invIB * L2;
+ }
+ else {
+ this.m_impulse.SetZero();
+ this.m_motorImpulse = 0.0;
+ }
+ }
+ b2LineJoint.prototype.SolveVelocityConstraints = function (step) {
+ var bA = this.m_bodyA;
+ var bB = this.m_bodyB;
+ var v1 = bA.m_linearVelocity;
+ var w1 = bA.m_angularVelocity;
+ var v2 = bB.m_linearVelocity;
+ var w2 = bB.m_angularVelocity;
+ var PX = 0;
+ var PY = 0;
+ var L1 = 0;
+ var L2 = 0;
+ if (this.m_enableMotor && this.m_limitState != b2Joint.e_equalLimits) {
+ var Cdot = this.m_axis.x * (v2.x - v1.x) + this.m_axis.y * (v2.y - v1.y) + this.m_a2 * w2 - this.m_a1 * w1;
+ var impulse = this.m_motorMass * (this.m_motorSpeed - Cdot);
+ var oldImpulse = this.m_motorImpulse;
+ var maxImpulse = step.dt * this.m_maxMotorForce;
+ this.m_motorImpulse = b2Math.Clamp(this.m_motorImpulse + impulse, (-maxImpulse), maxImpulse);
+ impulse = this.m_motorImpulse - oldImpulse;
+ PX = impulse * this.m_axis.x;
+ PY = impulse * this.m_axis.y;
+ L1 = impulse * this.m_a1;
+ L2 = impulse * this.m_a2;
+ v1.x -= this.m_invMassA * PX;
+ v1.y -= this.m_invMassA * PY;
+ w1 -= this.m_invIA * L1;
+ v2.x += this.m_invMassB * PX;
+ v2.y += this.m_invMassB * PY;
+ w2 += this.m_invIB * L2;
+ }
+ var Cdot1 = this.m_perp.x * (v2.x - v1.x) + this.m_perp.y * (v2.y - v1.y) + this.m_s2 * w2 - this.m_s1 * w1;
+ if (this.m_enableLimit && this.m_limitState != b2Joint.e_inactiveLimit) {
+ var Cdot2 = this.m_axis.x * (v2.x - v1.x) + this.m_axis.y * (v2.y - v1.y) + this.m_a2 * w2 - this.m_a1 * w1;
+ var f1 = this.m_impulse.Copy();
+ var df = this.m_K.Solve(new b2Vec2(), (-Cdot1), (-Cdot2));
+ this.m_impulse.Add(df);
+ if (this.m_limitState == b2Joint.e_atLowerLimit) {
+ this.m_impulse.y = b2Math.Max(this.m_impulse.y, 0.0);
+ }
+ else if (this.m_limitState == b2Joint.e_atUpperLimit) {
+ this.m_impulse.y = b2Math.Min(this.m_impulse.y, 0.0);
+ }
+ var b = (-Cdot1) - (this.m_impulse.y - f1.y) * this.m_K.col2.x;
+ var f2r = 0;
+ if (this.m_K.col1.x != 0.0) {
+ f2r = b / this.m_K.col1.x + f1.x;
+ }
+ else {
+ f2r = f1.x;
+ }
+ this.m_impulse.x = f2r;
+ df.x = this.m_impulse.x - f1.x;
+ df.y = this.m_impulse.y - f1.y;
+ PX = df.x * this.m_perp.x + df.y * this.m_axis.x;
+ PY = df.x * this.m_perp.y + df.y * this.m_axis.y;
+ L1 = df.x * this.m_s1 + df.y * this.m_a1;
+ L2 = df.x * this.m_s2 + df.y * this.m_a2;
+ v1.x -= this.m_invMassA * PX;
+ v1.y -= this.m_invMassA * PY;
+ w1 -= this.m_invIA * L1;
+ v2.x += this.m_invMassB * PX;
+ v2.y += this.m_invMassB * PY;
+ w2 += this.m_invIB * L2;
+ }
+ else {
+ var df2 = 0;
+ if (this.m_K.col1.x != 0.0) {
+ df2 = ((-Cdot1)) / this.m_K.col1.x;
+ }
+ else {
+ df2 = 0.0;
+ }
+ this.m_impulse.x += df2;
+ PX = df2 * this.m_perp.x;
+ PY = df2 * this.m_perp.y;
+ L1 = df2 * this.m_s1;
+ L2 = df2 * this.m_s2;
+ v1.x -= this.m_invMassA * PX;
+ v1.y -= this.m_invMassA * PY;
+ w1 -= this.m_invIA * L1;
+ v2.x += this.m_invMassB * PX;
+ v2.y += this.m_invMassB * PY;
+ w2 += this.m_invIB * L2;
+ }
+ bA.m_linearVelocity.SetV(v1);
+ bA.m_angularVelocity = w1;
+ bB.m_linearVelocity.SetV(v2);
+ bB.m_angularVelocity = w2;
+ }
+ b2LineJoint.prototype.SolvePositionConstraints = function (baumgarte) {
+ if (baumgarte === undefined) baumgarte = 0;
+ var limitC = 0;
+ var oldLimitImpulse = 0;
+ var bA = this.m_bodyA;
+ var bB = this.m_bodyB;
+ var c1 = bA.m_sweep.c;
+ var a1 = bA.m_sweep.a;
+ var c2 = bB.m_sweep.c;
+ var a2 = bB.m_sweep.a;
+ var tMat;
+ var tX = 0;
+ var m1 = 0;
+ var m2 = 0;
+ var i1 = 0;
+ var i2 = 0;
+ var linearError = 0.0;
+ var angularError = 0.0;
+ var active = false;
+ var C2 = 0.0;
+ var R1 = b2Mat22.FromAngle(a1);
+ var R2 = b2Mat22.FromAngle(a2);
+ tMat = R1;
+ var r1X = this.m_localAnchor1.x - this.m_localCenterA.x;
+ var r1Y = this.m_localAnchor1.y - this.m_localCenterA.y;
+ tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
+ r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
+ r1X = tX;
+ tMat = R2;
+ var r2X = this.m_localAnchor2.x - this.m_localCenterB.x;
+ var r2Y = this.m_localAnchor2.y - this.m_localCenterB.y;
+ tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
+ r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
+ r2X = tX;
+ var dX = c2.x + r2X - c1.x - r1X;
+ var dY = c2.y + r2Y - c1.y - r1Y;
+ if (this.m_enableLimit) {
+ this.m_axis = b2Math.MulMV(R1, this.m_localXAxis1);
+ this.m_a1 = (dX + r1X) * this.m_axis.y - (dY + r1Y) * this.m_axis.x;
+ this.m_a2 = r2X * this.m_axis.y - r2Y * this.m_axis.x;
+ var translation = this.m_axis.x * dX + this.m_axis.y * dY;
+ if (b2Math.Abs(this.m_upperTranslation - this.m_lowerTranslation) < 2.0 * b2Settings.b2_linearSlop) {
+ C2 = b2Math.Clamp(translation, (-b2Settings.b2_maxLinearCorrection), b2Settings.b2_maxLinearCorrection);
+ linearError = b2Math.Abs(translation);
+ active = true;
+ }
+ else if (translation <= this.m_lowerTranslation) {
+ C2 = b2Math.Clamp(translation - this.m_lowerTranslation + b2Settings.b2_linearSlop, (-b2Settings.b2_maxLinearCorrection), 0.0);
+ linearError = this.m_lowerTranslation - translation;
+ active = true;
+ }
+ else if (translation >= this.m_upperTranslation) {
+ C2 = b2Math.Clamp(translation - this.m_upperTranslation + b2Settings.b2_linearSlop, 0.0, b2Settings.b2_maxLinearCorrection);
+ linearError = translation - this.m_upperTranslation;
+ active = true;
+ }
+ }
+ this.m_perp = b2Math.MulMV(R1, this.m_localYAxis1);
+ this.m_s1 = (dX + r1X) * this.m_perp.y - (dY + r1Y) * this.m_perp.x;
+ this.m_s2 = r2X * this.m_perp.y - r2Y * this.m_perp.x;
+ var impulse = new b2Vec2();
+ var C1 = this.m_perp.x * dX + this.m_perp.y * dY;
+ linearError = b2Math.Max(linearError, b2Math.Abs(C1));
+ angularError = 0.0;
+ if (active) {
+ m1 = this.m_invMassA;
+ m2 = this.m_invMassB;
+ i1 = this.m_invIA;
+ i2 = this.m_invIB;
+ this.m_K.col1.x = m1 + m2 + i1 * this.m_s1 * this.m_s1 + i2 * this.m_s2 * this.m_s2;
+ this.m_K.col1.y = i1 * this.m_s1 * this.m_a1 + i2 * this.m_s2 * this.m_a2;
+ this.m_K.col2.x = this.m_K.col1.y;
+ this.m_K.col2.y = m1 + m2 + i1 * this.m_a1 * this.m_a1 + i2 * this.m_a2 * this.m_a2;
+ this.m_K.Solve(impulse, (-C1), (-C2));
+ }
+ else {
+ m1 = this.m_invMassA;
+ m2 = this.m_invMassB;
+ i1 = this.m_invIA;
+ i2 = this.m_invIB;
+ var k11 = m1 + m2 + i1 * this.m_s1 * this.m_s1 + i2 * this.m_s2 * this.m_s2;
+ var impulse1 = 0;
+ if (k11 != 0.0) {
+ impulse1 = ((-C1)) / k11;
+ }
+ else {
+ impulse1 = 0.0;
+ }
+ impulse.x = impulse1;
+ impulse.y = 0.0;
+ }
+ var PX = impulse.x * this.m_perp.x + impulse.y * this.m_axis.x;
+ var PY = impulse.x * this.m_perp.y + impulse.y * this.m_axis.y;
+ var L1 = impulse.x * this.m_s1 + impulse.y * this.m_a1;
+ var L2 = impulse.x * this.m_s2 + impulse.y * this.m_a2;
+ c1.x -= this.m_invMassA * PX;
+ c1.y -= this.m_invMassA * PY;
+ a1 -= this.m_invIA * L1;
+ c2.x += this.m_invMassB * PX;
+ c2.y += this.m_invMassB * PY;
+ a2 += this.m_invIB * L2;
+ bA.m_sweep.a = a1;
+ bB.m_sweep.a = a2;
+ bA.SynchronizeTransform();
+ bB.SynchronizeTransform();
+ return linearError <= b2Settings.b2_linearSlop && angularError <= b2Settings.b2_angularSlop;
+ }
+ Box2D.inherit(b2LineJointDef, Box2D.Dynamics.Joints.b2JointDef);
+ b2LineJointDef.prototype.__super = Box2D.Dynamics.Joints.b2JointDef.prototype;
+ b2LineJointDef.b2LineJointDef = function () {
+ Box2D.Dynamics.Joints.b2JointDef.b2JointDef.apply(this, arguments);
+ this.localAnchorA = new b2Vec2();
+ this.localAnchorB = new b2Vec2();
+ this.localAxisA = new b2Vec2();
+ };
+ b2LineJointDef.prototype.b2LineJointDef = function () {
+ this.__super.b2JointDef.call(this);
+ this.type = b2Joint.e_lineJoint;
+ this.localAxisA.Set(1.0, 0.0);
+ this.enableLimit = false;
+ this.lowerTranslation = 0.0;
+ this.upperTranslation = 0.0;
+ this.enableMotor = false;
+ this.maxMotorForce = 0.0;
+ this.motorSpeed = 0.0;
+ }
+ b2LineJointDef.prototype.Initialize = function (bA, bB, anchor, axis) {
+ this.bodyA = bA;
+ this.bodyB = bB;
+ this.localAnchorA = this.bodyA.GetLocalPoint(anchor);
+ this.localAnchorB = this.bodyB.GetLocalPoint(anchor);
+ this.localAxisA = this.bodyA.GetLocalVector(axis);
+ }
+ Box2D.inherit(b2MouseJoint, Box2D.Dynamics.Joints.b2Joint);
+ b2MouseJoint.prototype.__super = Box2D.Dynamics.Joints.b2Joint.prototype;
+ b2MouseJoint.b2MouseJoint = function () {
+ Box2D.Dynamics.Joints.b2Joint.b2Joint.apply(this, arguments);
+ this.K = new b2Mat22();
+ this.K1 = new b2Mat22();
+ this.K2 = new b2Mat22();
+ this.m_localAnchor = new b2Vec2();
+ this.m_target = new b2Vec2();
+ this.m_impulse = new b2Vec2();
+ this.m_mass = new b2Mat22();
+ this.m_C = new b2Vec2();
+ };
+ b2MouseJoint.prototype.GetAnchorA = function () {
+ return this.m_target;
+ }
+ b2MouseJoint.prototype.GetAnchorB = function () {
+ return this.m_bodyB.GetWorldPoint(this.m_localAnchor);
+ }
+ b2MouseJoint.prototype.GetReactionForce = function (inv_dt) {
+ if (inv_dt === undefined) inv_dt = 0;
+ return new b2Vec2(inv_dt * this.m_impulse.x, inv_dt * this.m_impulse.y);
+ }
+ b2MouseJoint.prototype.GetReactionTorque = function (inv_dt) {
+ if (inv_dt === undefined) inv_dt = 0;
+ return 0.0;
+ }
+ b2MouseJoint.prototype.GetTarget = function () {
+ return this.m_target;
+ }
+ b2MouseJoint.prototype.SetTarget = function (target) {
+ if (this.m_bodyB.IsAwake() == false) {
+ this.m_bodyB.SetAwake(true);
+ }
+ this.m_target = target;
+ }
+ b2MouseJoint.prototype.GetMaxForce = function () {
+ return this.m_maxForce;
+ }
+ b2MouseJoint.prototype.SetMaxForce = function (maxForce) {
+ if (maxForce === undefined) maxForce = 0;
+ this.m_maxForce = maxForce;
+ }
+ b2MouseJoint.prototype.GetFrequency = function () {
+ return this.m_frequencyHz;
+ }
+ b2MouseJoint.prototype.SetFrequency = function (hz) {
+ if (hz === undefined) hz = 0;
+ this.m_frequencyHz = hz;
+ }
+ b2MouseJoint.prototype.GetDampingRatio = function () {
+ return this.m_dampingRatio;
+ }
+ b2MouseJoint.prototype.SetDampingRatio = function (ratio) {
+ if (ratio === undefined) ratio = 0;
+ this.m_dampingRatio = ratio;
+ }
+ b2MouseJoint.prototype.b2MouseJoint = function (def) {
+ this.__super.b2Joint.call(this, def);
+ this.m_target.SetV(def.target);
+ var tX = this.m_target.x - this.m_bodyB.m_xf.position.x;
+ var tY = this.m_target.y - this.m_bodyB.m_xf.position.y;
+ var tMat = this.m_bodyB.m_xf.R;
+ this.m_localAnchor.x = (tX * tMat.col1.x + tY * tMat.col1.y);
+ this.m_localAnchor.y = (tX * tMat.col2.x + tY * tMat.col2.y);
+ this.m_maxForce = def.maxForce;
+ this.m_impulse.SetZero();
+ this.m_frequencyHz = def.frequencyHz;
+ this.m_dampingRatio = def.dampingRatio;
+ this.m_beta = 0.0;
+ this.m_gamma = 0.0;
+ }
+ b2MouseJoint.prototype.InitVelocityConstraints = function (step) {
+ var b = this.m_bodyB;
+ var mass = b.GetMass();
+ var omega = 2.0 * Math.PI * this.m_frequencyHz;
+ var d = 2.0 * mass * this.m_dampingRatio * omega;
+ var k = mass * omega * omega;
+ this.m_gamma = step.dt * (d + step.dt * k);
+ this.m_gamma = this.m_gamma != 0 ? 1 / this.m_gamma : 0.0;
+ this.m_beta = step.dt * k * this.m_gamma;
+ var tMat;tMat = b.m_xf.R;
+ var rX = this.m_localAnchor.x - b.m_sweep.localCenter.x;
+ var rY = this.m_localAnchor.y - b.m_sweep.localCenter.y;
+ var tX = (tMat.col1.x * rX + tMat.col2.x * rY);rY = (tMat.col1.y * rX + tMat.col2.y * rY);
+ rX = tX;
+ var invMass = b.m_invMass;
+ var invI = b.m_invI;this.K1.col1.x = invMass;
+ this.K1.col2.x = 0.0;
+ this.K1.col1.y = 0.0;
+ this.K1.col2.y = invMass;
+ this.K2.col1.x = invI * rY * rY;
+ this.K2.col2.x = (-invI * rX * rY);
+ this.K2.col1.y = (-invI * rX * rY);
+ this.K2.col2.y = invI * rX * rX;
+ this.K.SetM(this.K1);
+ this.K.AddM(this.K2);
+ this.K.col1.x += this.m_gamma;
+ this.K.col2.y += this.m_gamma;
+ this.K.GetInverse(this.m_mass);
+ this.m_C.x = b.m_sweep.c.x + rX - this.m_target.x;
+ this.m_C.y = b.m_sweep.c.y + rY - this.m_target.y;
+ b.m_angularVelocity *= 0.98;
+ this.m_impulse.x *= step.dtRatio;
+ this.m_impulse.y *= step.dtRatio;
+ b.m_linearVelocity.x += invMass * this.m_impulse.x;
+ b.m_linearVelocity.y += invMass * this.m_impulse.y;
+ b.m_angularVelocity += invI * (rX * this.m_impulse.y - rY * this.m_impulse.x);
+ }
+ b2MouseJoint.prototype.SolveVelocityConstraints = function (step) {
+ var b = this.m_bodyB;
+ var tMat;
+ var tX = 0;
+ var tY = 0;
+ tMat = b.m_xf.R;
+ var rX = this.m_localAnchor.x - b.m_sweep.localCenter.x;
+ var rY = this.m_localAnchor.y - b.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * rX + tMat.col2.x * rY);
+ rY = (tMat.col1.y * rX + tMat.col2.y * rY);
+ rX = tX;
+ var CdotX = b.m_linearVelocity.x + ((-b.m_angularVelocity * rY));
+ var CdotY = b.m_linearVelocity.y + (b.m_angularVelocity * rX);
+ tMat = this.m_mass;
+ tX = CdotX + this.m_beta * this.m_C.x + this.m_gamma * this.m_impulse.x;
+ tY = CdotY + this.m_beta * this.m_C.y + this.m_gamma * this.m_impulse.y;
+ var impulseX = (-(tMat.col1.x * tX + tMat.col2.x * tY));
+ var impulseY = (-(tMat.col1.y * tX + tMat.col2.y * tY));
+ var oldImpulseX = this.m_impulse.x;
+ var oldImpulseY = this.m_impulse.y;
+ this.m_impulse.x += impulseX;
+ this.m_impulse.y += impulseY;
+ var maxImpulse = step.dt * this.m_maxForce;
+ if (this.m_impulse.LengthSquared() > maxImpulse * maxImpulse) {
+ this.m_impulse.Multiply(maxImpulse / this.m_impulse.Length());
+ }
+ impulseX = this.m_impulse.x - oldImpulseX;
+ impulseY = this.m_impulse.y - oldImpulseY;
+ b.m_linearVelocity.x += b.m_invMass * impulseX;
+ b.m_linearVelocity.y += b.m_invMass * impulseY;
+ b.m_angularVelocity += b.m_invI * (rX * impulseY - rY * impulseX);
+ }
+ b2MouseJoint.prototype.SolvePositionConstraints = function (baumgarte) {
+ if (baumgarte === undefined) baumgarte = 0;
+ return true;
+ }
+ Box2D.inherit(b2MouseJointDef, Box2D.Dynamics.Joints.b2JointDef);
+ b2MouseJointDef.prototype.__super = Box2D.Dynamics.Joints.b2JointDef.prototype;
+ b2MouseJointDef.b2MouseJointDef = function () {
+ Box2D.Dynamics.Joints.b2JointDef.b2JointDef.apply(this, arguments);
+ this.target = new b2Vec2();
+ };
+ b2MouseJointDef.prototype.b2MouseJointDef = function () {
+ this.__super.b2JointDef.call(this);
+ this.type = b2Joint.e_mouseJoint;
+ this.maxForce = 0.0;
+ this.frequencyHz = 5.0;
+ this.dampingRatio = 0.7;
+ }
+ Box2D.inherit(b2PrismaticJoint, Box2D.Dynamics.Joints.b2Joint);
+ b2PrismaticJoint.prototype.__super = Box2D.Dynamics.Joints.b2Joint.prototype;
+ b2PrismaticJoint.b2PrismaticJoint = function () {
+ Box2D.Dynamics.Joints.b2Joint.b2Joint.apply(this, arguments);
+ this.m_localAnchor1 = new b2Vec2();
+ this.m_localAnchor2 = new b2Vec2();
+ this.m_localXAxis1 = new b2Vec2();
+ this.m_localYAxis1 = new b2Vec2();
+ this.m_axis = new b2Vec2();
+ this.m_perp = new b2Vec2();
+ this.m_K = new b2Mat33();
+ this.m_impulse = new b2Vec3();
+ };
+ b2PrismaticJoint.prototype.GetAnchorA = function () {
+ return this.m_bodyA.GetWorldPoint(this.m_localAnchor1);
+ }
+ b2PrismaticJoint.prototype.GetAnchorB = function () {
+ return this.m_bodyB.GetWorldPoint(this.m_localAnchor2);
+ }
+ b2PrismaticJoint.prototype.GetReactionForce = function (inv_dt) {
+ if (inv_dt === undefined) inv_dt = 0;
+ return new b2Vec2(inv_dt * (this.m_impulse.x * this.m_perp.x + (this.m_motorImpulse + this.m_impulse.z) * this.m_axis.x), inv_dt * (this.m_impulse.x * this.m_perp.y + (this.m_motorImpulse + this.m_impulse.z) * this.m_axis.y));
+ }
+ b2PrismaticJoint.prototype.GetReactionTorque = function (inv_dt) {
+ if (inv_dt === undefined) inv_dt = 0;
+ return inv_dt * this.m_impulse.y;
+ }
+ b2PrismaticJoint.prototype.GetJointTranslation = function () {
+ var bA = this.m_bodyA;
+ var bB = this.m_bodyB;
+ var tMat;
+ var p1 = bA.GetWorldPoint(this.m_localAnchor1);
+ var p2 = bB.GetWorldPoint(this.m_localAnchor2);
+ var dX = p2.x - p1.x;
+ var dY = p2.y - p1.y;
+ var axis = bA.GetWorldVector(this.m_localXAxis1);
+ var translation = axis.x * dX + axis.y * dY;
+ return translation;
+ }
+ b2PrismaticJoint.prototype.GetJointSpeed = function () {
+ var bA = this.m_bodyA;
+ var bB = this.m_bodyB;
+ var tMat;
+ tMat = bA.m_xf.R;
+ var r1X = this.m_localAnchor1.x - bA.m_sweep.localCenter.x;
+ var r1Y = this.m_localAnchor1.y - bA.m_sweep.localCenter.y;
+ var tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
+ r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
+ r1X = tX;
+ tMat = bB.m_xf.R;
+ var r2X = this.m_localAnchor2.x - bB.m_sweep.localCenter.x;
+ var r2Y = this.m_localAnchor2.y - bB.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
+ r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
+ r2X = tX;
+ var p1X = bA.m_sweep.c.x + r1X;
+ var p1Y = bA.m_sweep.c.y + r1Y;
+ var p2X = bB.m_sweep.c.x + r2X;
+ var p2Y = bB.m_sweep.c.y + r2Y;
+ var dX = p2X - p1X;
+ var dY = p2Y - p1Y;
+ var axis = bA.GetWorldVector(this.m_localXAxis1);
+ var v1 = bA.m_linearVelocity;
+ var v2 = bB.m_linearVelocity;
+ var w1 = bA.m_angularVelocity;
+ var w2 = bB.m_angularVelocity;
+ var speed = (dX * ((-w1 * axis.y)) + dY * (w1 * axis.x)) + (axis.x * (((v2.x + ((-w2 * r2Y))) - v1.x) - ((-w1 * r1Y))) + axis.y * (((v2.y + (w2 * r2X)) - v1.y) - (w1 * r1X)));
+ return speed;
+ }
+ b2PrismaticJoint.prototype.IsLimitEnabled = function () {
+ return this.m_enableLimit;
+ }
+ b2PrismaticJoint.prototype.EnableLimit = function (flag) {
+ this.m_bodyA.SetAwake(true);
+ this.m_bodyB.SetAwake(true);
+ this.m_enableLimit = flag;
+ }
+ b2PrismaticJoint.prototype.GetLowerLimit = function () {
+ return this.m_lowerTranslation;
+ }
+ b2PrismaticJoint.prototype.GetUpperLimit = function () {
+ return this.m_upperTranslation;
+ }
+ b2PrismaticJoint.prototype.SetLimits = function (lower, upper) {
+ if (lower === undefined) lower = 0;
+ if (upper === undefined) upper = 0;
+ this.m_bodyA.SetAwake(true);
+ this.m_bodyB.SetAwake(true);
+ this.m_lowerTranslation = lower;
+ this.m_upperTranslation = upper;
+ }
+ b2PrismaticJoint.prototype.IsMotorEnabled = function () {
+ return this.m_enableMotor;
+ }
+ b2PrismaticJoint.prototype.EnableMotor = function (flag) {
+ this.m_bodyA.SetAwake(true);
+ this.m_bodyB.SetAwake(true);
+ this.m_enableMotor = flag;
+ }
+ b2PrismaticJoint.prototype.SetMotorSpeed = function (speed) {
+ if (speed === undefined) speed = 0;
+ this.m_bodyA.SetAwake(true);
+ this.m_bodyB.SetAwake(true);
+ this.m_motorSpeed = speed;
+ }
+ b2PrismaticJoint.prototype.GetMotorSpeed = function () {
+ return this.m_motorSpeed;
+ }
+ b2PrismaticJoint.prototype.SetMaxMotorForce = function (force) {
+ if (force === undefined) force = 0;
+ this.m_bodyA.SetAwake(true);
+ this.m_bodyB.SetAwake(true);
+ this.m_maxMotorForce = force;
+ }
+ b2PrismaticJoint.prototype.GetMotorForce = function () {
+ return this.m_motorImpulse;
+ }
+ b2PrismaticJoint.prototype.b2PrismaticJoint = function (def) {
+ this.__super.b2Joint.call(this, def);
+ var tMat;
+ var tX = 0;
+ var tY = 0;
+ this.m_localAnchor1.SetV(def.localAnchorA);
+ this.m_localAnchor2.SetV(def.localAnchorB);
+ this.m_localXAxis1.SetV(def.localAxisA);
+ this.m_localYAxis1.x = (-this.m_localXAxis1.y);
+ this.m_localYAxis1.y = this.m_localXAxis1.x;
+ this.m_refAngle = def.referenceAngle;
+ this.m_impulse.SetZero();
+ this.m_motorMass = 0.0;
+ this.m_motorImpulse = 0.0;
+ this.m_lowerTranslation = def.lowerTranslation;
+ this.m_upperTranslation = def.upperTranslation;
+ this.m_maxMotorForce = def.maxMotorForce;
+ this.m_motorSpeed = def.motorSpeed;
+ this.m_enableLimit = def.enableLimit;
+ this.m_enableMotor = def.enableMotor;
+ this.m_limitState = b2Joint.e_inactiveLimit;
+ this.m_axis.SetZero();
+ this.m_perp.SetZero();
+ }
+ b2PrismaticJoint.prototype.InitVelocityConstraints = function (step) {
+ var bA = this.m_bodyA;
+ var bB = this.m_bodyB;
+ var tMat;
+ var tX = 0;
+ this.m_localCenterA.SetV(bA.GetLocalCenter());
+ this.m_localCenterB.SetV(bB.GetLocalCenter());
+ var xf1 = bA.GetTransform();
+ var xf2 = bB.GetTransform();
+ tMat = bA.m_xf.R;
+ var r1X = this.m_localAnchor1.x - this.m_localCenterA.x;
+ var r1Y = this.m_localAnchor1.y - this.m_localCenterA.y;
+ tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
+ r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
+ r1X = tX;
+ tMat = bB.m_xf.R;
+ var r2X = this.m_localAnchor2.x - this.m_localCenterB.x;
+ var r2Y = this.m_localAnchor2.y - this.m_localCenterB.y;
+ tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
+ r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
+ r2X = tX;
+ var dX = bB.m_sweep.c.x + r2X - bA.m_sweep.c.x - r1X;
+ var dY = bB.m_sweep.c.y + r2Y - bA.m_sweep.c.y - r1Y;
+ this.m_invMassA = bA.m_invMass;
+ this.m_invMassB = bB.m_invMass;
+ this.m_invIA = bA.m_invI;
+ this.m_invIB = bB.m_invI; {
+ this.m_axis.SetV(b2Math.MulMV(xf1.R, this.m_localXAxis1));
+ this.m_a1 = (dX + r1X) * this.m_axis.y - (dY + r1Y) * this.m_axis.x;
+ this.m_a2 = r2X * this.m_axis.y - r2Y * this.m_axis.x;
+ this.m_motorMass = this.m_invMassA + this.m_invMassB + this.m_invIA * this.m_a1 * this.m_a1 + this.m_invIB * this.m_a2 * this.m_a2;
+ if (this.m_motorMass > Number.MIN_VALUE) this.m_motorMass = 1.0 / this.m_motorMass;
+ } {
+ this.m_perp.SetV(b2Math.MulMV(xf1.R, this.m_localYAxis1));
+ this.m_s1 = (dX + r1X) * this.m_perp.y - (dY + r1Y) * this.m_perp.x;
+ this.m_s2 = r2X * this.m_perp.y - r2Y * this.m_perp.x;
+ var m1 = this.m_invMassA;
+ var m2 = this.m_invMassB;
+ var i1 = this.m_invIA;
+ var i2 = this.m_invIB;
+ this.m_K.col1.x = m1 + m2 + i1 * this.m_s1 * this.m_s1 + i2 * this.m_s2 * this.m_s2;
+ this.m_K.col1.y = i1 * this.m_s1 + i2 * this.m_s2;
+ this.m_K.col1.z = i1 * this.m_s1 * this.m_a1 + i2 * this.m_s2 * this.m_a2;
+ this.m_K.col2.x = this.m_K.col1.y;
+ this.m_K.col2.y = i1 + i2;
+ this.m_K.col2.z = i1 * this.m_a1 + i2 * this.m_a2;
+ this.m_K.col3.x = this.m_K.col1.z;
+ this.m_K.col3.y = this.m_K.col2.z;
+ this.m_K.col3.z = m1 + m2 + i1 * this.m_a1 * this.m_a1 + i2 * this.m_a2 * this.m_a2;
+ }
+ if (this.m_enableLimit) {
+ var jointTransition = this.m_axis.x * dX + this.m_axis.y * dY;
+ if (b2Math.Abs(this.m_upperTranslation - this.m_lowerTranslation) < 2.0 * b2Settings.b2_linearSlop) {
+ this.m_limitState = b2Joint.e_equalLimits;
+ }
+ else if (jointTransition <= this.m_lowerTranslation) {
+ if (this.m_limitState != b2Joint.e_atLowerLimit) {
+ this.m_limitState = b2Joint.e_atLowerLimit;
+ this.m_impulse.z = 0.0;
+ }
+ }
+ else if (jointTransition >= this.m_upperTranslation) {
+ if (this.m_limitState != b2Joint.e_atUpperLimit) {
+ this.m_limitState = b2Joint.e_atUpperLimit;
+ this.m_impulse.z = 0.0;
+ }
+ }
+ else {
+ this.m_limitState = b2Joint.e_inactiveLimit;
+ this.m_impulse.z = 0.0;
+ }
+ }
+ else {
+ this.m_limitState = b2Joint.e_inactiveLimit;
+ }
+ if (this.m_enableMotor == false) {
+ this.m_motorImpulse = 0.0;
+ }
+ if (step.warmStarting) {
+ this.m_impulse.x *= step.dtRatio;
+ this.m_impulse.y *= step.dtRatio;
+ this.m_motorImpulse *= step.dtRatio;
+ var PX = this.m_impulse.x * this.m_perp.x + (this.m_motorImpulse + this.m_impulse.z) * this.m_axis.x;
+ var PY = this.m_impulse.x * this.m_perp.y + (this.m_motorImpulse + this.m_impulse.z) * this.m_axis.y;
+ var L1 = this.m_impulse.x * this.m_s1 + this.m_impulse.y + (this.m_motorImpulse + this.m_impulse.z) * this.m_a1;
+ var L2 = this.m_impulse.x * this.m_s2 + this.m_impulse.y + (this.m_motorImpulse + this.m_impulse.z) * this.m_a2;
+ bA.m_linearVelocity.x -= this.m_invMassA * PX;
+ bA.m_linearVelocity.y -= this.m_invMassA * PY;
+ bA.m_angularVelocity -= this.m_invIA * L1;
+ bB.m_linearVelocity.x += this.m_invMassB * PX;
+ bB.m_linearVelocity.y += this.m_invMassB * PY;
+ bB.m_angularVelocity += this.m_invIB * L2;
+ }
+ else {
+ this.m_impulse.SetZero();
+ this.m_motorImpulse = 0.0;
+ }
+ }
+ b2PrismaticJoint.prototype.SolveVelocityConstraints = function (step) {
+ var bA = this.m_bodyA;
+ var bB = this.m_bodyB;
+ var v1 = bA.m_linearVelocity;
+ var w1 = bA.m_angularVelocity;
+ var v2 = bB.m_linearVelocity;
+ var w2 = bB.m_angularVelocity;
+ var PX = 0;
+ var PY = 0;
+ var L1 = 0;
+ var L2 = 0;
+ if (this.m_enableMotor && this.m_limitState != b2Joint.e_equalLimits) {
+ var Cdot = this.m_axis.x * (v2.x - v1.x) + this.m_axis.y * (v2.y - v1.y) + this.m_a2 * w2 - this.m_a1 * w1;
+ var impulse = this.m_motorMass * (this.m_motorSpeed - Cdot);
+ var oldImpulse = this.m_motorImpulse;
+ var maxImpulse = step.dt * this.m_maxMotorForce;
+ this.m_motorImpulse = b2Math.Clamp(this.m_motorImpulse + impulse, (-maxImpulse), maxImpulse);
+ impulse = this.m_motorImpulse - oldImpulse;
+ PX = impulse * this.m_axis.x;
+ PY = impulse * this.m_axis.y;
+ L1 = impulse * this.m_a1;
+ L2 = impulse * this.m_a2;
+ v1.x -= this.m_invMassA * PX;
+ v1.y -= this.m_invMassA * PY;
+ w1 -= this.m_invIA * L1;
+ v2.x += this.m_invMassB * PX;
+ v2.y += this.m_invMassB * PY;
+ w2 += this.m_invIB * L2;
+ }
+ var Cdot1X = this.m_perp.x * (v2.x - v1.x) + this.m_perp.y * (v2.y - v1.y) + this.m_s2 * w2 - this.m_s1 * w1;
+ var Cdot1Y = w2 - w1;
+ if (this.m_enableLimit && this.m_limitState != b2Joint.e_inactiveLimit) {
+ var Cdot2 = this.m_axis.x * (v2.x - v1.x) + this.m_axis.y * (v2.y - v1.y) + this.m_a2 * w2 - this.m_a1 * w1;
+ var f1 = this.m_impulse.Copy();
+ var df = this.m_K.Solve33(new b2Vec3(), (-Cdot1X), (-Cdot1Y), (-Cdot2));
+ this.m_impulse.Add(df);
+ if (this.m_limitState == b2Joint.e_atLowerLimit) {
+ this.m_impulse.z = b2Math.Max(this.m_impulse.z, 0.0);
+ }
+ else if (this.m_limitState == b2Joint.e_atUpperLimit) {
+ this.m_impulse.z = b2Math.Min(this.m_impulse.z, 0.0);
+ }
+ var bX = (-Cdot1X) - (this.m_impulse.z - f1.z) * this.m_K.col3.x;
+ var bY = (-Cdot1Y) - (this.m_impulse.z - f1.z) * this.m_K.col3.y;
+ var f2r = this.m_K.Solve22(new b2Vec2(), bX, bY);
+ f2r.x += f1.x;
+ f2r.y += f1.y;
+ this.m_impulse.x = f2r.x;
+ this.m_impulse.y = f2r.y;
+ df.x = this.m_impulse.x - f1.x;
+ df.y = this.m_impulse.y - f1.y;
+ df.z = this.m_impulse.z - f1.z;
+ PX = df.x * this.m_perp.x + df.z * this.m_axis.x;
+ PY = df.x * this.m_perp.y + df.z * this.m_axis.y;
+ L1 = df.x * this.m_s1 + df.y + df.z * this.m_a1;
+ L2 = df.x * this.m_s2 + df.y + df.z * this.m_a2;
+ v1.x -= this.m_invMassA * PX;
+ v1.y -= this.m_invMassA * PY;
+ w1 -= this.m_invIA * L1;
+ v2.x += this.m_invMassB * PX;
+ v2.y += this.m_invMassB * PY;
+ w2 += this.m_invIB * L2;
+ }
+ else {
+ var df2 = this.m_K.Solve22(new b2Vec2(), (-Cdot1X), (-Cdot1Y));
+ this.m_impulse.x += df2.x;
+ this.m_impulse.y += df2.y;
+ PX = df2.x * this.m_perp.x;
+ PY = df2.x * this.m_perp.y;
+ L1 = df2.x * this.m_s1 + df2.y;
+ L2 = df2.x * this.m_s2 + df2.y;
+ v1.x -= this.m_invMassA * PX;
+ v1.y -= this.m_invMassA * PY;
+ w1 -= this.m_invIA * L1;
+ v2.x += this.m_invMassB * PX;
+ v2.y += this.m_invMassB * PY;
+ w2 += this.m_invIB * L2;
+ }
+ bA.m_linearVelocity.SetV(v1);
+ bA.m_angularVelocity = w1;
+ bB.m_linearVelocity.SetV(v2);
+ bB.m_angularVelocity = w2;
+ }
+ b2PrismaticJoint.prototype.SolvePositionConstraints = function (baumgarte) {
+ if (baumgarte === undefined) baumgarte = 0;
+ var limitC = 0;
+ var oldLimitImpulse = 0;
+ var bA = this.m_bodyA;
+ var bB = this.m_bodyB;
+ var c1 = bA.m_sweep.c;
+ var a1 = bA.m_sweep.a;
+ var c2 = bB.m_sweep.c;
+ var a2 = bB.m_sweep.a;
+ var tMat;
+ var tX = 0;
+ var m1 = 0;
+ var m2 = 0;
+ var i1 = 0;
+ var i2 = 0;
+ var linearError = 0.0;
+ var angularError = 0.0;
+ var active = false;
+ var C2 = 0.0;
+ var R1 = b2Mat22.FromAngle(a1);
+ var R2 = b2Mat22.FromAngle(a2);
+ tMat = R1;
+ var r1X = this.m_localAnchor1.x - this.m_localCenterA.x;
+ var r1Y = this.m_localAnchor1.y - this.m_localCenterA.y;
+ tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
+ r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
+ r1X = tX;
+ tMat = R2;
+ var r2X = this.m_localAnchor2.x - this.m_localCenterB.x;
+ var r2Y = this.m_localAnchor2.y - this.m_localCenterB.y;
+ tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
+ r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
+ r2X = tX;
+ var dX = c2.x + r2X - c1.x - r1X;
+ var dY = c2.y + r2Y - c1.y - r1Y;
+ if (this.m_enableLimit) {
+ this.m_axis = b2Math.MulMV(R1, this.m_localXAxis1);
+ this.m_a1 = (dX + r1X) * this.m_axis.y - (dY + r1Y) * this.m_axis.x;
+ this.m_a2 = r2X * this.m_axis.y - r2Y * this.m_axis.x;
+ var translation = this.m_axis.x * dX + this.m_axis.y * dY;
+ if (b2Math.Abs(this.m_upperTranslation - this.m_lowerTranslation) < 2.0 * b2Settings.b2_linearSlop) {
+ C2 = b2Math.Clamp(translation, (-b2Settings.b2_maxLinearCorrection), b2Settings.b2_maxLinearCorrection);
+ linearError = b2Math.Abs(translation);
+ active = true;
+ }
+ else if (translation <= this.m_lowerTranslation) {
+ C2 = b2Math.Clamp(translation - this.m_lowerTranslation + b2Settings.b2_linearSlop, (-b2Settings.b2_maxLinearCorrection), 0.0);
+ linearError = this.m_lowerTranslation - translation;
+ active = true;
+ }
+ else if (translation >= this.m_upperTranslation) {
+ C2 = b2Math.Clamp(translation - this.m_upperTranslation + b2Settings.b2_linearSlop, 0.0, b2Settings.b2_maxLinearCorrection);
+ linearError = translation - this.m_upperTranslation;
+ active = true;
+ }
+ }
+ this.m_perp = b2Math.MulMV(R1, this.m_localYAxis1);
+ this.m_s1 = (dX + r1X) * this.m_perp.y - (dY + r1Y) * this.m_perp.x;
+ this.m_s2 = r2X * this.m_perp.y - r2Y * this.m_perp.x;
+ var impulse = new b2Vec3();
+ var C1X = this.m_perp.x * dX + this.m_perp.y * dY;
+ var C1Y = a2 - a1 - this.m_refAngle;
+ linearError = b2Math.Max(linearError, b2Math.Abs(C1X));
+ angularError = b2Math.Abs(C1Y);
+ if (active) {
+ m1 = this.m_invMassA;
+ m2 = this.m_invMassB;
+ i1 = this.m_invIA;
+ i2 = this.m_invIB;
+ this.m_K.col1.x = m1 + m2 + i1 * this.m_s1 * this.m_s1 + i2 * this.m_s2 * this.m_s2;
+ this.m_K.col1.y = i1 * this.m_s1 + i2 * this.m_s2;
+ this.m_K.col1.z = i1 * this.m_s1 * this.m_a1 + i2 * this.m_s2 * this.m_a2;
+ this.m_K.col2.x = this.m_K.col1.y;
+ this.m_K.col2.y = i1 + i2;
+ this.m_K.col2.z = i1 * this.m_a1 + i2 * this.m_a2;
+ this.m_K.col3.x = this.m_K.col1.z;
+ this.m_K.col3.y = this.m_K.col2.z;
+ this.m_K.col3.z = m1 + m2 + i1 * this.m_a1 * this.m_a1 + i2 * this.m_a2 * this.m_a2;
+ this.m_K.Solve33(impulse, (-C1X), (-C1Y), (-C2));
+ }
+ else {
+ m1 = this.m_invMassA;
+ m2 = this.m_invMassB;
+ i1 = this.m_invIA;
+ i2 = this.m_invIB;
+ var k11 = m1 + m2 + i1 * this.m_s1 * this.m_s1 + i2 * this.m_s2 * this.m_s2;
+ var k12 = i1 * this.m_s1 + i2 * this.m_s2;
+ var k22 = i1 + i2;
+ this.m_K.col1.Set(k11, k12, 0.0);
+ this.m_K.col2.Set(k12, k22, 0.0);
+ var impulse1 = this.m_K.Solve22(new b2Vec2(), (-C1X), (-C1Y));
+ impulse.x = impulse1.x;
+ impulse.y = impulse1.y;
+ impulse.z = 0.0;
+ }
+ var PX = impulse.x * this.m_perp.x + impulse.z * this.m_axis.x;
+ var PY = impulse.x * this.m_perp.y + impulse.z * this.m_axis.y;
+ var L1 = impulse.x * this.m_s1 + impulse.y + impulse.z * this.m_a1;
+ var L2 = impulse.x * this.m_s2 + impulse.y + impulse.z * this.m_a2;
+ c1.x -= this.m_invMassA * PX;
+ c1.y -= this.m_invMassA * PY;
+ a1 -= this.m_invIA * L1;
+ c2.x += this.m_invMassB * PX;
+ c2.y += this.m_invMassB * PY;
+ a2 += this.m_invIB * L2;
+ bA.m_sweep.a = a1;
+ bB.m_sweep.a = a2;
+ bA.SynchronizeTransform();
+ bB.SynchronizeTransform();
+ return linearError <= b2Settings.b2_linearSlop && angularError <= b2Settings.b2_angularSlop;
+ }
+ Box2D.inherit(b2PrismaticJointDef, Box2D.Dynamics.Joints.b2JointDef);
+ b2PrismaticJointDef.prototype.__super = Box2D.Dynamics.Joints.b2JointDef.prototype;
+ b2PrismaticJointDef.b2PrismaticJointDef = function () {
+ Box2D.Dynamics.Joints.b2JointDef.b2JointDef.apply(this, arguments);
+ this.localAnchorA = new b2Vec2();
+ this.localAnchorB = new b2Vec2();
+ this.localAxisA = new b2Vec2();
+ };
+ b2PrismaticJointDef.prototype.b2PrismaticJointDef = function () {
+ this.__super.b2JointDef.call(this);
+ this.type = b2Joint.e_prismaticJoint;
+ this.localAxisA.Set(1.0, 0.0);
+ this.referenceAngle = 0.0;
+ this.enableLimit = false;
+ this.lowerTranslation = 0.0;
+ this.upperTranslation = 0.0;
+ this.enableMotor = false;
+ this.maxMotorForce = 0.0;
+ this.motorSpeed = 0.0;
+ }
+ b2PrismaticJointDef.prototype.Initialize = function (bA, bB, anchor, axis) {
+ this.bodyA = bA;
+ this.bodyB = bB;
+ this.localAnchorA = this.bodyA.GetLocalPoint(anchor);
+ this.localAnchorB = this.bodyB.GetLocalPoint(anchor);
+ this.localAxisA = this.bodyA.GetLocalVector(axis);
+ this.referenceAngle = this.bodyB.GetAngle() - this.bodyA.GetAngle();
+ }
+ Box2D.inherit(b2PulleyJoint, Box2D.Dynamics.Joints.b2Joint);
+ b2PulleyJoint.prototype.__super = Box2D.Dynamics.Joints.b2Joint.prototype;
+ b2PulleyJoint.b2PulleyJoint = function () {
+ Box2D.Dynamics.Joints.b2Joint.b2Joint.apply(this, arguments);
+ this.m_groundAnchor1 = new b2Vec2();
+ this.m_groundAnchor2 = new b2Vec2();
+ this.m_localAnchor1 = new b2Vec2();
+ this.m_localAnchor2 = new b2Vec2();
+ this.m_u1 = new b2Vec2();
+ this.m_u2 = new b2Vec2();
+ };
+ b2PulleyJoint.prototype.GetAnchorA = function () {
+ return this.m_bodyA.GetWorldPoint(this.m_localAnchor1);
+ }
+ b2PulleyJoint.prototype.GetAnchorB = function () {
+ return this.m_bodyB.GetWorldPoint(this.m_localAnchor2);
+ }
+ b2PulleyJoint.prototype.GetReactionForce = function (inv_dt) {
+ if (inv_dt === undefined) inv_dt = 0;
+ return new b2Vec2(inv_dt * this.m_impulse * this.m_u2.x, inv_dt * this.m_impulse * this.m_u2.y);
+ }
+ b2PulleyJoint.prototype.GetReactionTorque = function (inv_dt) {
+ if (inv_dt === undefined) inv_dt = 0;
+ return 0.0;
+ }
+ b2PulleyJoint.prototype.GetGroundAnchorA = function () {
+ var a = this.m_ground.m_xf.position.Copy();
+ a.Add(this.m_groundAnchor1);
+ return a;
+ }
+ b2PulleyJoint.prototype.GetGroundAnchorB = function () {
+ var a = this.m_ground.m_xf.position.Copy();
+ a.Add(this.m_groundAnchor2);
+ return a;
+ }
+ b2PulleyJoint.prototype.GetLength1 = function () {
+ var p = this.m_bodyA.GetWorldPoint(this.m_localAnchor1);
+ var sX = this.m_ground.m_xf.position.x + this.m_groundAnchor1.x;
+ var sY = this.m_ground.m_xf.position.y + this.m_groundAnchor1.y;
+ var dX = p.x - sX;
+ var dY = p.y - sY;
+ return Math.sqrt(dX * dX + dY * dY);
+ }
+ b2PulleyJoint.prototype.GetLength2 = function () {
+ var p = this.m_bodyB.GetWorldPoint(this.m_localAnchor2);
+ var sX = this.m_ground.m_xf.position.x + this.m_groundAnchor2.x;
+ var sY = this.m_ground.m_xf.position.y + this.m_groundAnchor2.y;
+ var dX = p.x - sX;
+ var dY = p.y - sY;
+ return Math.sqrt(dX * dX + dY * dY);
+ }
+ b2PulleyJoint.prototype.GetRatio = function () {
+ return this.m_ratio;
+ }
+ b2PulleyJoint.prototype.b2PulleyJoint = function (def) {
+ this.__super.b2Joint.call(this, def);
+ var tMat;
+ var tX = 0;
+ var tY = 0;
+ this.m_ground = this.m_bodyA.m_world.m_groundBody;
+ this.m_groundAnchor1.x = def.groundAnchorA.x - this.m_ground.m_xf.position.x;
+ this.m_groundAnchor1.y = def.groundAnchorA.y - this.m_ground.m_xf.position.y;
+ this.m_groundAnchor2.x = def.groundAnchorB.x - this.m_ground.m_xf.position.x;
+ this.m_groundAnchor2.y = def.groundAnchorB.y - this.m_ground.m_xf.position.y;
+ this.m_localAnchor1.SetV(def.localAnchorA);
+ this.m_localAnchor2.SetV(def.localAnchorB);
+ this.m_ratio = def.ratio;
+ this.m_constant = def.lengthA + this.m_ratio * def.lengthB;
+ this.m_maxLength1 = b2Math.Min(def.maxLengthA, this.m_constant - this.m_ratio * b2PulleyJoint.b2_minPulleyLength);
+ this.m_maxLength2 = b2Math.Min(def.maxLengthB, (this.m_constant - b2PulleyJoint.b2_minPulleyLength) / this.m_ratio);
+ this.m_impulse = 0.0;
+ this.m_limitImpulse1 = 0.0;
+ this.m_limitImpulse2 = 0.0;
+ }
+ b2PulleyJoint.prototype.InitVelocityConstraints = function (step) {
+ var bA = this.m_bodyA;
+ var bB = this.m_bodyB;
+ var tMat;
+ tMat = bA.m_xf.R;
+ var r1X = this.m_localAnchor1.x - bA.m_sweep.localCenter.x;
+ var r1Y = this.m_localAnchor1.y - bA.m_sweep.localCenter.y;
+ var tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
+ r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
+ r1X = tX;
+ tMat = bB.m_xf.R;
+ var r2X = this.m_localAnchor2.x - bB.m_sweep.localCenter.x;
+ var r2Y = this.m_localAnchor2.y - bB.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
+ r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
+ r2X = tX;
+ var p1X = bA.m_sweep.c.x + r1X;
+ var p1Y = bA.m_sweep.c.y + r1Y;
+ var p2X = bB.m_sweep.c.x + r2X;
+ var p2Y = bB.m_sweep.c.y + r2Y;
+ var s1X = this.m_ground.m_xf.position.x + this.m_groundAnchor1.x;
+ var s1Y = this.m_ground.m_xf.position.y + this.m_groundAnchor1.y;
+ var s2X = this.m_ground.m_xf.position.x + this.m_groundAnchor2.x;
+ var s2Y = this.m_ground.m_xf.position.y + this.m_groundAnchor2.y;
+ this.m_u1.Set(p1X - s1X, p1Y - s1Y);
+ this.m_u2.Set(p2X - s2X, p2Y - s2Y);
+ var length1 = this.m_u1.Length();
+ var length2 = this.m_u2.Length();
+ if (length1 > b2Settings.b2_linearSlop) {
+ this.m_u1.Multiply(1.0 / length1);
+ }
+ else {
+ this.m_u1.SetZero();
+ }
+ if (length2 > b2Settings.b2_linearSlop) {
+ this.m_u2.Multiply(1.0 / length2);
+ }
+ else {
+ this.m_u2.SetZero();
+ }
+ var C = this.m_constant - length1 - this.m_ratio * length2;
+ if (C > 0.0) {
+ this.m_state = b2Joint.e_inactiveLimit;
+ this.m_impulse = 0.0;
+ }
+ else {
+ this.m_state = b2Joint.e_atUpperLimit;
+ }
+ if (length1 < this.m_maxLength1) {
+ this.m_limitState1 = b2Joint.e_inactiveLimit;
+ this.m_limitImpulse1 = 0.0;
+ }
+ else {
+ this.m_limitState1 = b2Joint.e_atUpperLimit;
+ }
+ if (length2 < this.m_maxLength2) {
+ this.m_limitState2 = b2Joint.e_inactiveLimit;
+ this.m_limitImpulse2 = 0.0;
+ }
+ else {
+ this.m_limitState2 = b2Joint.e_atUpperLimit;
+ }
+ var cr1u1 = r1X * this.m_u1.y - r1Y * this.m_u1.x;
+ var cr2u2 = r2X * this.m_u2.y - r2Y * this.m_u2.x;
+ this.m_limitMass1 = bA.m_invMass + bA.m_invI * cr1u1 * cr1u1;
+ this.m_limitMass2 = bB.m_invMass + bB.m_invI * cr2u2 * cr2u2;
+ this.m_pulleyMass = this.m_limitMass1 + this.m_ratio * this.m_ratio * this.m_limitMass2;
+ this.m_limitMass1 = 1.0 / this.m_limitMass1;
+ this.m_limitMass2 = 1.0 / this.m_limitMass2;
+ this.m_pulleyMass = 1.0 / this.m_pulleyMass;
+ if (step.warmStarting) {
+ this.m_impulse *= step.dtRatio;
+ this.m_limitImpulse1 *= step.dtRatio;
+ this.m_limitImpulse2 *= step.dtRatio;
+ var P1X = ((-this.m_impulse) - this.m_limitImpulse1) * this.m_u1.x;
+ var P1Y = ((-this.m_impulse) - this.m_limitImpulse1) * this.m_u1.y;
+ var P2X = ((-this.m_ratio * this.m_impulse) - this.m_limitImpulse2) * this.m_u2.x;
+ var P2Y = ((-this.m_ratio * this.m_impulse) - this.m_limitImpulse2) * this.m_u2.y;
+ bA.m_linearVelocity.x += bA.m_invMass * P1X;
+ bA.m_linearVelocity.y += bA.m_invMass * P1Y;
+ bA.m_angularVelocity += bA.m_invI * (r1X * P1Y - r1Y * P1X);
+ bB.m_linearVelocity.x += bB.m_invMass * P2X;
+ bB.m_linearVelocity.y += bB.m_invMass * P2Y;
+ bB.m_angularVelocity += bB.m_invI * (r2X * P2Y - r2Y * P2X);
+ }
+ else {
+ this.m_impulse = 0.0;
+ this.m_limitImpulse1 = 0.0;
+ this.m_limitImpulse2 = 0.0;
+ }
+ }
+ b2PulleyJoint.prototype.SolveVelocityConstraints = function (step) {
+ var bA = this.m_bodyA;
+ var bB = this.m_bodyB;
+ var tMat;
+ tMat = bA.m_xf.R;
+ var r1X = this.m_localAnchor1.x - bA.m_sweep.localCenter.x;
+ var r1Y = this.m_localAnchor1.y - bA.m_sweep.localCenter.y;
+ var tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
+ r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
+ r1X = tX;
+ tMat = bB.m_xf.R;
+ var r2X = this.m_localAnchor2.x - bB.m_sweep.localCenter.x;
+ var r2Y = this.m_localAnchor2.y - bB.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
+ r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
+ r2X = tX;
+ var v1X = 0;
+ var v1Y = 0;
+ var v2X = 0;
+ var v2Y = 0;
+ var P1X = 0;
+ var P1Y = 0;
+ var P2X = 0;
+ var P2Y = 0;
+ var Cdot = 0;
+ var impulse = 0;
+ var oldImpulse = 0;
+ if (this.m_state == b2Joint.e_atUpperLimit) {
+ v1X = bA.m_linearVelocity.x + ((-bA.m_angularVelocity * r1Y));
+ v1Y = bA.m_linearVelocity.y + (bA.m_angularVelocity * r1X);
+ v2X = bB.m_linearVelocity.x + ((-bB.m_angularVelocity * r2Y));
+ v2Y = bB.m_linearVelocity.y + (bB.m_angularVelocity * r2X);
+ Cdot = (-(this.m_u1.x * v1X + this.m_u1.y * v1Y)) - this.m_ratio * (this.m_u2.x * v2X + this.m_u2.y * v2Y);
+ impulse = this.m_pulleyMass * ((-Cdot));
+ oldImpulse = this.m_impulse;
+ this.m_impulse = b2Math.Max(0.0, this.m_impulse + impulse);
+ impulse = this.m_impulse - oldImpulse;
+ P1X = (-impulse * this.m_u1.x);
+ P1Y = (-impulse * this.m_u1.y);
+ P2X = (-this.m_ratio * impulse * this.m_u2.x);
+ P2Y = (-this.m_ratio * impulse * this.m_u2.y);
+ bA.m_linearVelocity.x += bA.m_invMass * P1X;
+ bA.m_linearVelocity.y += bA.m_invMass * P1Y;
+ bA.m_angularVelocity += bA.m_invI * (r1X * P1Y - r1Y * P1X);
+ bB.m_linearVelocity.x += bB.m_invMass * P2X;
+ bB.m_linearVelocity.y += bB.m_invMass * P2Y;
+ bB.m_angularVelocity += bB.m_invI * (r2X * P2Y - r2Y * P2X);
+ }
+ if (this.m_limitState1 == b2Joint.e_atUpperLimit) {
+ v1X = bA.m_linearVelocity.x + ((-bA.m_angularVelocity * r1Y));
+ v1Y = bA.m_linearVelocity.y + (bA.m_angularVelocity * r1X);
+ Cdot = (-(this.m_u1.x * v1X + this.m_u1.y * v1Y));
+ impulse = (-this.m_limitMass1 * Cdot);
+ oldImpulse = this.m_limitImpulse1;
+ this.m_limitImpulse1 = b2Math.Max(0.0, this.m_limitImpulse1 + impulse);
+ impulse = this.m_limitImpulse1 - oldImpulse;
+ P1X = (-impulse * this.m_u1.x);
+ P1Y = (-impulse * this.m_u1.y);
+ bA.m_linearVelocity.x += bA.m_invMass * P1X;
+ bA.m_linearVelocity.y += bA.m_invMass * P1Y;
+ bA.m_angularVelocity += bA.m_invI * (r1X * P1Y - r1Y * P1X);
+ }
+ if (this.m_limitState2 == b2Joint.e_atUpperLimit) {
+ v2X = bB.m_linearVelocity.x + ((-bB.m_angularVelocity * r2Y));
+ v2Y = bB.m_linearVelocity.y + (bB.m_angularVelocity * r2X);
+ Cdot = (-(this.m_u2.x * v2X + this.m_u2.y * v2Y));
+ impulse = (-this.m_limitMass2 * Cdot);
+ oldImpulse = this.m_limitImpulse2;
+ this.m_limitImpulse2 = b2Math.Max(0.0, this.m_limitImpulse2 + impulse);
+ impulse = this.m_limitImpulse2 - oldImpulse;
+ P2X = (-impulse * this.m_u2.x);
+ P2Y = (-impulse * this.m_u2.y);
+ bB.m_linearVelocity.x += bB.m_invMass * P2X;
+ bB.m_linearVelocity.y += bB.m_invMass * P2Y;
+ bB.m_angularVelocity += bB.m_invI * (r2X * P2Y - r2Y * P2X);
+ }
+ }
+ b2PulleyJoint.prototype.SolvePositionConstraints = function (baumgarte) {
+ if (baumgarte === undefined) baumgarte = 0;
+ var bA = this.m_bodyA;
+ var bB = this.m_bodyB;
+ var tMat;
+ var s1X = this.m_ground.m_xf.position.x + this.m_groundAnchor1.x;
+ var s1Y = this.m_ground.m_xf.position.y + this.m_groundAnchor1.y;
+ var s2X = this.m_ground.m_xf.position.x + this.m_groundAnchor2.x;
+ var s2Y = this.m_ground.m_xf.position.y + this.m_groundAnchor2.y;
+ var r1X = 0;
+ var r1Y = 0;
+ var r2X = 0;
+ var r2Y = 0;
+ var p1X = 0;
+ var p1Y = 0;
+ var p2X = 0;
+ var p2Y = 0;
+ var length1 = 0;
+ var length2 = 0;
+ var C = 0;
+ var impulse = 0;
+ var oldImpulse = 0;
+ var oldLimitPositionImpulse = 0;
+ var tX = 0;
+ var linearError = 0.0;
+ if (this.m_state == b2Joint.e_atUpperLimit) {
+ tMat = bA.m_xf.R;
+ r1X = this.m_localAnchor1.x - bA.m_sweep.localCenter.x;
+ r1Y = this.m_localAnchor1.y - bA.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
+ r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
+ r1X = tX;
+ tMat = bB.m_xf.R;
+ r2X = this.m_localAnchor2.x - bB.m_sweep.localCenter.x;
+ r2Y = this.m_localAnchor2.y - bB.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
+ r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
+ r2X = tX;
+ p1X = bA.m_sweep.c.x + r1X;
+ p1Y = bA.m_sweep.c.y + r1Y;
+ p2X = bB.m_sweep.c.x + r2X;
+ p2Y = bB.m_sweep.c.y + r2Y;
+ this.m_u1.Set(p1X - s1X, p1Y - s1Y);
+ this.m_u2.Set(p2X - s2X, p2Y - s2Y);
+ length1 = this.m_u1.Length();
+ length2 = this.m_u2.Length();
+ if (length1 > b2Settings.b2_linearSlop) {
+ this.m_u1.Multiply(1.0 / length1);
+ }
+ else {
+ this.m_u1.SetZero();
+ }
+ if (length2 > b2Settings.b2_linearSlop) {
+ this.m_u2.Multiply(1.0 / length2);
+ }
+ else {
+ this.m_u2.SetZero();
+ }
+ C = this.m_constant - length1 - this.m_ratio * length2;
+ linearError = b2Math.Max(linearError, (-C));
+ C = b2Math.Clamp(C + b2Settings.b2_linearSlop, (-b2Settings.b2_maxLinearCorrection), 0.0);
+ impulse = (-this.m_pulleyMass * C);
+ p1X = (-impulse * this.m_u1.x);
+ p1Y = (-impulse * this.m_u1.y);
+ p2X = (-this.m_ratio * impulse * this.m_u2.x);
+ p2Y = (-this.m_ratio * impulse * this.m_u2.y);
+ bA.m_sweep.c.x += bA.m_invMass * p1X;
+ bA.m_sweep.c.y += bA.m_invMass * p1Y;
+ bA.m_sweep.a += bA.m_invI * (r1X * p1Y - r1Y * p1X);
+ bB.m_sweep.c.x += bB.m_invMass * p2X;
+ bB.m_sweep.c.y += bB.m_invMass * p2Y;
+ bB.m_sweep.a += bB.m_invI * (r2X * p2Y - r2Y * p2X);
+ bA.SynchronizeTransform();
+ bB.SynchronizeTransform();
+ }
+ if (this.m_limitState1 == b2Joint.e_atUpperLimit) {
+ tMat = bA.m_xf.R;
+ r1X = this.m_localAnchor1.x - bA.m_sweep.localCenter.x;
+ r1Y = this.m_localAnchor1.y - bA.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
+ r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
+ r1X = tX;
+ p1X = bA.m_sweep.c.x + r1X;
+ p1Y = bA.m_sweep.c.y + r1Y;
+ this.m_u1.Set(p1X - s1X, p1Y - s1Y);
+ length1 = this.m_u1.Length();
+ if (length1 > b2Settings.b2_linearSlop) {
+ this.m_u1.x *= 1.0 / length1;
+ this.m_u1.y *= 1.0 / length1;
+ }
+ else {
+ this.m_u1.SetZero();
+ }
+ C = this.m_maxLength1 - length1;
+ linearError = b2Math.Max(linearError, (-C));
+ C = b2Math.Clamp(C + b2Settings.b2_linearSlop, (-b2Settings.b2_maxLinearCorrection), 0.0);
+ impulse = (-this.m_limitMass1 * C);
+ p1X = (-impulse * this.m_u1.x);
+ p1Y = (-impulse * this.m_u1.y);
+ bA.m_sweep.c.x += bA.m_invMass * p1X;
+ bA.m_sweep.c.y += bA.m_invMass * p1Y;
+ bA.m_sweep.a += bA.m_invI * (r1X * p1Y - r1Y * p1X);
+ bA.SynchronizeTransform();
+ }
+ if (this.m_limitState2 == b2Joint.e_atUpperLimit) {
+ tMat = bB.m_xf.R;
+ r2X = this.m_localAnchor2.x - bB.m_sweep.localCenter.x;
+ r2Y = this.m_localAnchor2.y - bB.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
+ r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
+ r2X = tX;
+ p2X = bB.m_sweep.c.x + r2X;
+ p2Y = bB.m_sweep.c.y + r2Y;
+ this.m_u2.Set(p2X - s2X, p2Y - s2Y);
+ length2 = this.m_u2.Length();
+ if (length2 > b2Settings.b2_linearSlop) {
+ this.m_u2.x *= 1.0 / length2;
+ this.m_u2.y *= 1.0 / length2;
+ }
+ else {
+ this.m_u2.SetZero();
+ }
+ C = this.m_maxLength2 - length2;
+ linearError = b2Math.Max(linearError, (-C));
+ C = b2Math.Clamp(C + b2Settings.b2_linearSlop, (-b2Settings.b2_maxLinearCorrection), 0.0);
+ impulse = (-this.m_limitMass2 * C);
+ p2X = (-impulse * this.m_u2.x);
+ p2Y = (-impulse * this.m_u2.y);
+ bB.m_sweep.c.x += bB.m_invMass * p2X;
+ bB.m_sweep.c.y += bB.m_invMass * p2Y;
+ bB.m_sweep.a += bB.m_invI * (r2X * p2Y - r2Y * p2X);
+ bB.SynchronizeTransform();
+ }
+ return linearError < b2Settings.b2_linearSlop;
+ }
+ Box2D.postDefs.push(function () {
+ Box2D.Dynamics.Joints.b2PulleyJoint.b2_minPulleyLength = 2.0;
+ });
+ Box2D.inherit(b2PulleyJointDef, Box2D.Dynamics.Joints.b2JointDef);
+ b2PulleyJointDef.prototype.__super = Box2D.Dynamics.Joints.b2JointDef.prototype;
+ b2PulleyJointDef.b2PulleyJointDef = function () {
+ Box2D.Dynamics.Joints.b2JointDef.b2JointDef.apply(this, arguments);
+ this.groundAnchorA = new b2Vec2();
+ this.groundAnchorB = new b2Vec2();
+ this.localAnchorA = new b2Vec2();
+ this.localAnchorB = new b2Vec2();
+ };
+ b2PulleyJointDef.prototype.b2PulleyJointDef = function () {
+ this.__super.b2JointDef.call(this);
+ this.type = b2Joint.e_pulleyJoint;
+ this.groundAnchorA.Set((-1.0), 1.0);
+ this.groundAnchorB.Set(1.0, 1.0);
+ this.localAnchorA.Set((-1.0), 0.0);
+ this.localAnchorB.Set(1.0, 0.0);
+ this.lengthA = 0.0;
+ this.maxLengthA = 0.0;
+ this.lengthB = 0.0;
+ this.maxLengthB = 0.0;
+ this.ratio = 1.0;
+ this.collideConnected = true;
+ }
+ b2PulleyJointDef.prototype.Initialize = function (bA, bB, gaA, gaB, anchorA, anchorB, r) {
+ if (r === undefined) r = 0;
+ this.bodyA = bA;
+ this.bodyB = bB;
+ this.groundAnchorA.SetV(gaA);
+ this.groundAnchorB.SetV(gaB);
+ this.localAnchorA = this.bodyA.GetLocalPoint(anchorA);
+ this.localAnchorB = this.bodyB.GetLocalPoint(anchorB);
+ var d1X = anchorA.x - gaA.x;
+ var d1Y = anchorA.y - gaA.y;
+ this.lengthA = Math.sqrt(d1X * d1X + d1Y * d1Y);
+ var d2X = anchorB.x - gaB.x;
+ var d2Y = anchorB.y - gaB.y;
+ this.lengthB = Math.sqrt(d2X * d2X + d2Y * d2Y);
+ this.ratio = r;
+ var C = this.lengthA + this.ratio * this.lengthB;
+ this.maxLengthA = C - this.ratio * b2PulleyJoint.b2_minPulleyLength;
+ this.maxLengthB = (C - b2PulleyJoint.b2_minPulleyLength) / this.ratio;
+ }
+ Box2D.inherit(b2RevoluteJoint, Box2D.Dynamics.Joints.b2Joint);
+ b2RevoluteJoint.prototype.__super = Box2D.Dynamics.Joints.b2Joint.prototype;
+ b2RevoluteJoint.b2RevoluteJoint = function () {
+ Box2D.Dynamics.Joints.b2Joint.b2Joint.apply(this, arguments);
+ this.K = new b2Mat22();
+ this.K1 = new b2Mat22();
+ this.K2 = new b2Mat22();
+ this.K3 = new b2Mat22();
+ this.impulse3 = new b2Vec3();
+ this.impulse2 = new b2Vec2();
+ this.reduced = new b2Vec2();
+ this.m_localAnchor1 = new b2Vec2();
+ this.m_localAnchor2 = new b2Vec2();
+ this.m_impulse = new b2Vec3();
+ this.m_mass = new b2Mat33();
+ };
+ b2RevoluteJoint.prototype.GetAnchorA = function () {
+ return this.m_bodyA.GetWorldPoint(this.m_localAnchor1);
+ }
+ b2RevoluteJoint.prototype.GetAnchorB = function () {
+ return this.m_bodyB.GetWorldPoint(this.m_localAnchor2);
+ }
+ b2RevoluteJoint.prototype.GetReactionForce = function (inv_dt) {
+ if (inv_dt === undefined) inv_dt = 0;
+ return new b2Vec2(inv_dt * this.m_impulse.x, inv_dt * this.m_impulse.y);
+ }
+ b2RevoluteJoint.prototype.GetReactionTorque = function (inv_dt) {
+ if (inv_dt === undefined) inv_dt = 0;
+ return inv_dt * this.m_impulse.z;
+ }
+ b2RevoluteJoint.prototype.GetJointAngle = function () {
+ return this.m_bodyB.m_sweep.a - this.m_bodyA.m_sweep.a - this.m_referenceAngle;
+ }
+ b2RevoluteJoint.prototype.GetJointSpeed = function () {
+ return this.m_bodyB.m_angularVelocity - this.m_bodyA.m_angularVelocity;
+ }
+ b2RevoluteJoint.prototype.IsLimitEnabled = function () {
+ return this.m_enableLimit;
+ }
+ b2RevoluteJoint.prototype.EnableLimit = function (flag) {
+ this.m_enableLimit = flag;
+ }
+ b2RevoluteJoint.prototype.GetLowerLimit = function () {
+ return this.m_lowerAngle;
+ }
+ b2RevoluteJoint.prototype.GetUpperLimit = function () {
+ return this.m_upperAngle;
+ }
+ b2RevoluteJoint.prototype.SetLimits = function (lower, upper) {
+ if (lower === undefined) lower = 0;
+ if (upper === undefined) upper = 0;
+ this.m_lowerAngle = lower;
+ this.m_upperAngle = upper;
+ }
+ b2RevoluteJoint.prototype.IsMotorEnabled = function () {
+ this.m_bodyA.SetAwake(true);
+ this.m_bodyB.SetAwake(true);
+ return this.m_enableMotor;
+ }
+ b2RevoluteJoint.prototype.EnableMotor = function (flag) {
+ this.m_enableMotor = flag;
+ }
+ b2RevoluteJoint.prototype.SetMotorSpeed = function (speed) {
+ if (speed === undefined) speed = 0;
+ this.m_bodyA.SetAwake(true);
+ this.m_bodyB.SetAwake(true);
+ this.m_motorSpeed = speed;
+ }
+ b2RevoluteJoint.prototype.GetMotorSpeed = function () {
+ return this.m_motorSpeed;
+ }
+ b2RevoluteJoint.prototype.SetMaxMotorTorque = function (torque) {
+ if (torque === undefined) torque = 0;
+ this.m_maxMotorTorque = torque;
+ }
+ b2RevoluteJoint.prototype.GetMotorTorque = function () {
+ return this.m_maxMotorTorque;
+ }
+ b2RevoluteJoint.prototype.b2RevoluteJoint = function (def) {
+ this.__super.b2Joint.call(this, def);
+ this.m_localAnchor1.SetV(def.localAnchorA);
+ this.m_localAnchor2.SetV(def.localAnchorB);
+ this.m_referenceAngle = def.referenceAngle;
+ this.m_impulse.SetZero();
+ this.m_motorImpulse = 0.0;
+ this.m_lowerAngle = def.lowerAngle;
+ this.m_upperAngle = def.upperAngle;
+ this.m_maxMotorTorque = def.maxMotorTorque;
+ this.m_motorSpeed = def.motorSpeed;
+ this.m_enableLimit = def.enableLimit;
+ this.m_enableMotor = def.enableMotor;
+ this.m_limitState = b2Joint.e_inactiveLimit;
+ }
+ b2RevoluteJoint.prototype.InitVelocityConstraints = function (step) {
+ var bA = this.m_bodyA;
+ var bB = this.m_bodyB;
+ var tMat;
+ var tX = 0;
+ if (this.m_enableMotor || this.m_enableLimit) {}
+ tMat = bA.m_xf.R;
+ var r1X = this.m_localAnchor1.x - bA.m_sweep.localCenter.x;
+ var r1Y = this.m_localAnchor1.y - bA.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
+ r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
+ r1X = tX;
+ tMat = bB.m_xf.R;
+ var r2X = this.m_localAnchor2.x - bB.m_sweep.localCenter.x;
+ var r2Y = this.m_localAnchor2.y - bB.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
+ r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
+ r2X = tX;
+ var m1 = bA.m_invMass;
+ var m2 = bB.m_invMass;
+ var i1 = bA.m_invI;
+ var i2 = bB.m_invI;
+ this.m_mass.col1.x = m1 + m2 + r1Y * r1Y * i1 + r2Y * r2Y * i2;
+ this.m_mass.col2.x = (-r1Y * r1X * i1) - r2Y * r2X * i2;
+ this.m_mass.col3.x = (-r1Y * i1) - r2Y * i2;
+ this.m_mass.col1.y = this.m_mass.col2.x;
+ this.m_mass.col2.y = m1 + m2 + r1X * r1X * i1 + r2X * r2X * i2;
+ this.m_mass.col3.y = r1X * i1 + r2X * i2;
+ this.m_mass.col1.z = this.m_mass.col3.x;
+ this.m_mass.col2.z = this.m_mass.col3.y;
+ this.m_mass.col3.z = i1 + i2;
+ this.m_motorMass = 1.0 / (i1 + i2);
+ if (this.m_enableMotor == false) {
+ this.m_motorImpulse = 0.0;
+ }
+ if (this.m_enableLimit) {
+ var jointAngle = bB.m_sweep.a - bA.m_sweep.a - this.m_referenceAngle;
+ if (b2Math.Abs(this.m_upperAngle - this.m_lowerAngle) < 2.0 * b2Settings.b2_angularSlop) {
+ this.m_limitState = b2Joint.e_equalLimits;
+ }
+ else if (jointAngle <= this.m_lowerAngle) {
+ if (this.m_limitState != b2Joint.e_atLowerLimit) {
+ this.m_impulse.z = 0.0;
+ }
+ this.m_limitState = b2Joint.e_atLowerLimit;
+ }
+ else if (jointAngle >= this.m_upperAngle) {
+ if (this.m_limitState != b2Joint.e_atUpperLimit) {
+ this.m_impulse.z = 0.0;
+ }
+ this.m_limitState = b2Joint.e_atUpperLimit;
+ }
+ else {
+ this.m_limitState = b2Joint.e_inactiveLimit;
+ this.m_impulse.z = 0.0;
+ }
+ }
+ else {
+ this.m_limitState = b2Joint.e_inactiveLimit;
+ }
+ if (step.warmStarting) {
+ this.m_impulse.x *= step.dtRatio;
+ this.m_impulse.y *= step.dtRatio;
+ this.m_motorImpulse *= step.dtRatio;
+ var PX = this.m_impulse.x;
+ var PY = this.m_impulse.y;
+ bA.m_linearVelocity.x -= m1 * PX;
+ bA.m_linearVelocity.y -= m1 * PY;
+ bA.m_angularVelocity -= i1 * ((r1X * PY - r1Y * PX) + this.m_motorImpulse + this.m_impulse.z);
+ bB.m_linearVelocity.x += m2 * PX;
+ bB.m_linearVelocity.y += m2 * PY;
+ bB.m_angularVelocity += i2 * ((r2X * PY - r2Y * PX) + this.m_motorImpulse + this.m_impulse.z);
+ }
+ else {
+ this.m_impulse.SetZero();
+ this.m_motorImpulse = 0.0;
+ }
+ }
+ b2RevoluteJoint.prototype.SolveVelocityConstraints = function (step) {
+ var bA = this.m_bodyA;
+ var bB = this.m_bodyB;
+ var tMat;
+ var tX = 0;
+ var newImpulse = 0;
+ var r1X = 0;
+ var r1Y = 0;
+ var r2X = 0;
+ var r2Y = 0;
+ var v1 = bA.m_linearVelocity;
+ var w1 = bA.m_angularVelocity;
+ var v2 = bB.m_linearVelocity;
+ var w2 = bB.m_angularVelocity;
+ var m1 = bA.m_invMass;
+ var m2 = bB.m_invMass;
+ var i1 = bA.m_invI;
+ var i2 = bB.m_invI;
+ if (this.m_enableMotor && this.m_limitState != b2Joint.e_equalLimits) {
+ var Cdot = w2 - w1 - this.m_motorSpeed;
+ var impulse = this.m_motorMass * ((-Cdot));
+ var oldImpulse = this.m_motorImpulse;
+ var maxImpulse = step.dt * this.m_maxMotorTorque;
+ this.m_motorImpulse = b2Math.Clamp(this.m_motorImpulse + impulse, (-maxImpulse), maxImpulse);
+ impulse = this.m_motorImpulse - oldImpulse;
+ w1 -= i1 * impulse;
+ w2 += i2 * impulse;
+ }
+ if (this.m_enableLimit && this.m_limitState != b2Joint.e_inactiveLimit) {
+ tMat = bA.m_xf.R;
+ r1X = this.m_localAnchor1.x - bA.m_sweep.localCenter.x;
+ r1Y = this.m_localAnchor1.y - bA.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
+ r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
+ r1X = tX;
+ tMat = bB.m_xf.R;
+ r2X = this.m_localAnchor2.x - bB.m_sweep.localCenter.x;
+ r2Y = this.m_localAnchor2.y - bB.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
+ r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
+ r2X = tX;
+ var Cdot1X = v2.x + ((-w2 * r2Y)) - v1.x - ((-w1 * r1Y));
+ var Cdot1Y = v2.y + (w2 * r2X) - v1.y - (w1 * r1X);
+ var Cdot2 = w2 - w1;
+ this.m_mass.Solve33(this.impulse3, (-Cdot1X), (-Cdot1Y), (-Cdot2));
+ if (this.m_limitState == b2Joint.e_equalLimits) {
+ this.m_impulse.Add(this.impulse3);
+ }
+ else if (this.m_limitState == b2Joint.e_atLowerLimit) {
+ newImpulse = this.m_impulse.z + this.impulse3.z;
+ if (newImpulse < 0.0) {
+ this.m_mass.Solve22(this.reduced, (-Cdot1X), (-Cdot1Y));
+ this.impulse3.x = this.reduced.x;
+ this.impulse3.y = this.reduced.y;
+ this.impulse3.z = (-this.m_impulse.z);
+ this.m_impulse.x += this.reduced.x;
+ this.m_impulse.y += this.reduced.y;
+ this.m_impulse.z = 0.0;
+ }
+ }
+ else if (this.m_limitState == b2Joint.e_atUpperLimit) {
+ newImpulse = this.m_impulse.z + this.impulse3.z;
+ if (newImpulse > 0.0) {
+ this.m_mass.Solve22(this.reduced, (-Cdot1X), (-Cdot1Y));
+ this.impulse3.x = this.reduced.x;
+ this.impulse3.y = this.reduced.y;
+ this.impulse3.z = (-this.m_impulse.z);
+ this.m_impulse.x += this.reduced.x;
+ this.m_impulse.y += this.reduced.y;
+ this.m_impulse.z = 0.0;
+ }
+ }
+ v1.x -= m1 * this.impulse3.x;
+ v1.y -= m1 * this.impulse3.y;
+ w1 -= i1 * (r1X * this.impulse3.y - r1Y * this.impulse3.x + this.impulse3.z);
+ v2.x += m2 * this.impulse3.x;
+ v2.y += m2 * this.impulse3.y;
+ w2 += i2 * (r2X * this.impulse3.y - r2Y * this.impulse3.x + this.impulse3.z);
+ }
+ else {
+ tMat = bA.m_xf.R;
+ r1X = this.m_localAnchor1.x - bA.m_sweep.localCenter.x;
+ r1Y = this.m_localAnchor1.y - bA.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
+ r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
+ r1X = tX;
+ tMat = bB.m_xf.R;
+ r2X = this.m_localAnchor2.x - bB.m_sweep.localCenter.x;
+ r2Y = this.m_localAnchor2.y - bB.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
+ r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
+ r2X = tX;
+ var CdotX = v2.x + ((-w2 * r2Y)) - v1.x - ((-w1 * r1Y));
+ var CdotY = v2.y + (w2 * r2X) - v1.y - (w1 * r1X);
+ this.m_mass.Solve22(this.impulse2, (-CdotX), (-CdotY));
+ this.m_impulse.x += this.impulse2.x;
+ this.m_impulse.y += this.impulse2.y;
+ v1.x -= m1 * this.impulse2.x;
+ v1.y -= m1 * this.impulse2.y;
+ w1 -= i1 * (r1X * this.impulse2.y - r1Y * this.impulse2.x);
+ v2.x += m2 * this.impulse2.x;
+ v2.y += m2 * this.impulse2.y;
+ w2 += i2 * (r2X * this.impulse2.y - r2Y * this.impulse2.x);
+ }
+ bA.m_linearVelocity.SetV(v1);
+ bA.m_angularVelocity = w1;
+ bB.m_linearVelocity.SetV(v2);
+ bB.m_angularVelocity = w2;
+ }
+ b2RevoluteJoint.prototype.SolvePositionConstraints = function (baumgarte) {
+ if (baumgarte === undefined) baumgarte = 0;
+ var oldLimitImpulse = 0;
+ var C = 0;
+ var tMat;
+ var bA = this.m_bodyA;
+ var bB = this.m_bodyB;
+ var angularError = 0.0;
+ var positionError = 0.0;
+ var tX = 0;
+ var impulseX = 0;
+ var impulseY = 0;
+ if (this.m_enableLimit && this.m_limitState != b2Joint.e_inactiveLimit) {
+ var angle = bB.m_sweep.a - bA.m_sweep.a - this.m_referenceAngle;
+ var limitImpulse = 0.0;
+ if (this.m_limitState == b2Joint.e_equalLimits) {
+ C = b2Math.Clamp(angle - this.m_lowerAngle, (-b2Settings.b2_maxAngularCorrection), b2Settings.b2_maxAngularCorrection);
+ limitImpulse = (-this.m_motorMass * C);
+ angularError = b2Math.Abs(C);
+ }
+ else if (this.m_limitState == b2Joint.e_atLowerLimit) {
+ C = angle - this.m_lowerAngle;
+ angularError = (-C);
+ C = b2Math.Clamp(C + b2Settings.b2_angularSlop, (-b2Settings.b2_maxAngularCorrection), 0.0);
+ limitImpulse = (-this.m_motorMass * C);
+ }
+ else if (this.m_limitState == b2Joint.e_atUpperLimit) {
+ C = angle - this.m_upperAngle;
+ angularError = C;
+ C = b2Math.Clamp(C - b2Settings.b2_angularSlop, 0.0, b2Settings.b2_maxAngularCorrection);
+ limitImpulse = (-this.m_motorMass * C);
+ }
+ bA.m_sweep.a -= bA.m_invI * limitImpulse;
+ bB.m_sweep.a += bB.m_invI * limitImpulse;
+ bA.SynchronizeTransform();
+ bB.SynchronizeTransform();
+ } {
+ tMat = bA.m_xf.R;
+ var r1X = this.m_localAnchor1.x - bA.m_sweep.localCenter.x;
+ var r1Y = this.m_localAnchor1.y - bA.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y);
+ r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y);
+ r1X = tX;
+ tMat = bB.m_xf.R;
+ var r2X = this.m_localAnchor2.x - bB.m_sweep.localCenter.x;
+ var r2Y = this.m_localAnchor2.y - bB.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y);
+ r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y);
+ r2X = tX;
+ var CX = bB.m_sweep.c.x + r2X - bA.m_sweep.c.x - r1X;
+ var CY = bB.m_sweep.c.y + r2Y - bA.m_sweep.c.y - r1Y;
+ var CLengthSquared = CX * CX + CY * CY;
+ var CLength = Math.sqrt(CLengthSquared);
+ positionError = CLength;
+ var invMass1 = bA.m_invMass;
+ var invMass2 = bB.m_invMass;
+ var invI1 = bA.m_invI;
+ var invI2 = bB.m_invI;
+ var k_allowedStretch = 10.0 * b2Settings.b2_linearSlop;
+ if (CLengthSquared > k_allowedStretch * k_allowedStretch) {
+ var uX = CX / CLength;
+ var uY = CY / CLength;
+ var k = invMass1 + invMass2;
+ var m = 1.0 / k;
+ impulseX = m * ((-CX));
+ impulseY = m * ((-CY));
+ var k_beta = 0.5;
+ bA.m_sweep.c.x -= k_beta * invMass1 * impulseX;
+ bA.m_sweep.c.y -= k_beta * invMass1 * impulseY;
+ bB.m_sweep.c.x += k_beta * invMass2 * impulseX;
+ bB.m_sweep.c.y += k_beta * invMass2 * impulseY;
+ CX = bB.m_sweep.c.x + r2X - bA.m_sweep.c.x - r1X;
+ CY = bB.m_sweep.c.y + r2Y - bA.m_sweep.c.y - r1Y;
+ }
+ this.K1.col1.x = invMass1 + invMass2;
+ this.K1.col2.x = 0.0;
+ this.K1.col1.y = 0.0;
+ this.K1.col2.y = invMass1 + invMass2;
+ this.K2.col1.x = invI1 * r1Y * r1Y;
+ this.K2.col2.x = (-invI1 * r1X * r1Y);
+ this.K2.col1.y = (-invI1 * r1X * r1Y);
+ this.K2.col2.y = invI1 * r1X * r1X;
+ this.K3.col1.x = invI2 * r2Y * r2Y;
+ this.K3.col2.x = (-invI2 * r2X * r2Y);
+ this.K3.col1.y = (-invI2 * r2X * r2Y);
+ this.K3.col2.y = invI2 * r2X * r2X;
+ this.K.SetM(this.K1);
+ this.K.AddM(this.K2);
+ this.K.AddM(this.K3);
+ this.K.Solve(b2RevoluteJoint.tImpulse, (-CX), (-CY));
+ impulseX = b2RevoluteJoint.tImpulse.x;
+ impulseY = b2RevoluteJoint.tImpulse.y;
+ bA.m_sweep.c.x -= bA.m_invMass * impulseX;
+ bA.m_sweep.c.y -= bA.m_invMass * impulseY;
+ bA.m_sweep.a -= bA.m_invI * (r1X * impulseY - r1Y * impulseX);
+ bB.m_sweep.c.x += bB.m_invMass * impulseX;
+ bB.m_sweep.c.y += bB.m_invMass * impulseY;
+ bB.m_sweep.a += bB.m_invI * (r2X * impulseY - r2Y * impulseX);
+ bA.SynchronizeTransform();
+ bB.SynchronizeTransform();
+ }
+ return positionError <= b2Settings.b2_linearSlop && angularError <= b2Settings.b2_angularSlop;
+ }
+ Box2D.postDefs.push(function () {
+ Box2D.Dynamics.Joints.b2RevoluteJoint.tImpulse = new b2Vec2();
+ });
+ Box2D.inherit(b2RevoluteJointDef, Box2D.Dynamics.Joints.b2JointDef);
+ b2RevoluteJointDef.prototype.__super = Box2D.Dynamics.Joints.b2JointDef.prototype;
+ b2RevoluteJointDef.b2RevoluteJointDef = function () {
+ Box2D.Dynamics.Joints.b2JointDef.b2JointDef.apply(this, arguments);
+ this.localAnchorA = new b2Vec2();
+ this.localAnchorB = new b2Vec2();
+ };
+ b2RevoluteJointDef.prototype.b2RevoluteJointDef = function () {
+ this.__super.b2JointDef.call(this);
+ this.type = b2Joint.e_revoluteJoint;
+ this.localAnchorA.Set(0.0, 0.0);
+ this.localAnchorB.Set(0.0, 0.0);
+ this.referenceAngle = 0.0;
+ this.lowerAngle = 0.0;
+ this.upperAngle = 0.0;
+ this.maxMotorTorque = 0.0;
+ this.motorSpeed = 0.0;
+ this.enableLimit = false;
+ this.enableMotor = false;
+ }
+ b2RevoluteJointDef.prototype.Initialize = function (bA, bB, anchor) {
+ this.bodyA = bA;
+ this.bodyB = bB;
+ this.localAnchorA = this.bodyA.GetLocalPoint(anchor);
+ this.localAnchorB = this.bodyB.GetLocalPoint(anchor);
+ this.referenceAngle = this.bodyB.GetAngle() - this.bodyA.GetAngle();
+ }
+ Box2D.inherit(b2WeldJoint, Box2D.Dynamics.Joints.b2Joint);
+ b2WeldJoint.prototype.__super = Box2D.Dynamics.Joints.b2Joint.prototype;
+ b2WeldJoint.b2WeldJoint = function () {
+ Box2D.Dynamics.Joints.b2Joint.b2Joint.apply(this, arguments);
+ this.m_localAnchorA = new b2Vec2();
+ this.m_localAnchorB = new b2Vec2();
+ this.m_impulse = new b2Vec3();
+ this.m_mass = new b2Mat33();
+ };
+ b2WeldJoint.prototype.GetAnchorA = function () {
+ return this.m_bodyA.GetWorldPoint(this.m_localAnchorA);
+ }
+ b2WeldJoint.prototype.GetAnchorB = function () {
+ return this.m_bodyB.GetWorldPoint(this.m_localAnchorB);
+ }
+ b2WeldJoint.prototype.GetReactionForce = function (inv_dt) {
+ if (inv_dt === undefined) inv_dt = 0;
+ return new b2Vec2(inv_dt * this.m_impulse.x, inv_dt * this.m_impulse.y);
+ }
+ b2WeldJoint.prototype.GetReactionTorque = function (inv_dt) {
+ if (inv_dt === undefined) inv_dt = 0;
+ return inv_dt * this.m_impulse.z;
+ }
+ b2WeldJoint.prototype.b2WeldJoint = function (def) {
+ this.__super.b2Joint.call(this, def);
+ this.m_localAnchorA.SetV(def.localAnchorA);
+ this.m_localAnchorB.SetV(def.localAnchorB);
+ this.m_referenceAngle = def.referenceAngle;
+ this.m_impulse.SetZero();
+ this.m_mass = new b2Mat33();
+ }
+ b2WeldJoint.prototype.InitVelocityConstraints = function (step) {
+ var tMat;
+ var tX = 0;
+ var bA = this.m_bodyA;
+ var bB = this.m_bodyB;
+ tMat = bA.m_xf.R;
+ var rAX = this.m_localAnchorA.x - bA.m_sweep.localCenter.x;
+ var rAY = this.m_localAnchorA.y - bA.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * rAX + tMat.col2.x * rAY);
+ rAY = (tMat.col1.y * rAX + tMat.col2.y * rAY);
+ rAX = tX;
+ tMat = bB.m_xf.R;
+ var rBX = this.m_localAnchorB.x - bB.m_sweep.localCenter.x;
+ var rBY = this.m_localAnchorB.y - bB.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * rBX + tMat.col2.x * rBY);
+ rBY = (tMat.col1.y * rBX + tMat.col2.y * rBY);
+ rBX = tX;
+ var mA = bA.m_invMass;
+ var mB = bB.m_invMass;
+ var iA = bA.m_invI;
+ var iB = bB.m_invI;
+ this.m_mass.col1.x = mA + mB + rAY * rAY * iA + rBY * rBY * iB;
+ this.m_mass.col2.x = (-rAY * rAX * iA) - rBY * rBX * iB;
+ this.m_mass.col3.x = (-rAY * iA) - rBY * iB;
+ this.m_mass.col1.y = this.m_mass.col2.x;
+ this.m_mass.col2.y = mA + mB + rAX * rAX * iA + rBX * rBX * iB;
+ this.m_mass.col3.y = rAX * iA + rBX * iB;
+ this.m_mass.col1.z = this.m_mass.col3.x;
+ this.m_mass.col2.z = this.m_mass.col3.y;
+ this.m_mass.col3.z = iA + iB;
+ if (step.warmStarting) {
+ this.m_impulse.x *= step.dtRatio;
+ this.m_impulse.y *= step.dtRatio;
+ this.m_impulse.z *= step.dtRatio;
+ bA.m_linearVelocity.x -= mA * this.m_impulse.x;
+ bA.m_linearVelocity.y -= mA * this.m_impulse.y;
+ bA.m_angularVelocity -= iA * (rAX * this.m_impulse.y - rAY * this.m_impulse.x + this.m_impulse.z);
+ bB.m_linearVelocity.x += mB * this.m_impulse.x;
+ bB.m_linearVelocity.y += mB * this.m_impulse.y;
+ bB.m_angularVelocity += iB * (rBX * this.m_impulse.y - rBY * this.m_impulse.x + this.m_impulse.z);
+ }
+ else {
+ this.m_impulse.SetZero();
+ }
+ }
+ b2WeldJoint.prototype.SolveVelocityConstraints = function (step) {
+ var tMat;
+ var tX = 0;
+ var bA = this.m_bodyA;
+ var bB = this.m_bodyB;
+ var vA = bA.m_linearVelocity;
+ var wA = bA.m_angularVelocity;
+ var vB = bB.m_linearVelocity;
+ var wB = bB.m_angularVelocity;
+ var mA = bA.m_invMass;
+ var mB = bB.m_invMass;
+ var iA = bA.m_invI;
+ var iB = bB.m_invI;
+ tMat = bA.m_xf.R;
+ var rAX = this.m_localAnchorA.x - bA.m_sweep.localCenter.x;
+ var rAY = this.m_localAnchorA.y - bA.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * rAX + tMat.col2.x * rAY);
+ rAY = (tMat.col1.y * rAX + tMat.col2.y * rAY);
+ rAX = tX;
+ tMat = bB.m_xf.R;
+ var rBX = this.m_localAnchorB.x - bB.m_sweep.localCenter.x;
+ var rBY = this.m_localAnchorB.y - bB.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * rBX + tMat.col2.x * rBY);
+ rBY = (tMat.col1.y * rBX + tMat.col2.y * rBY);
+ rBX = tX;
+ var Cdot1X = vB.x - wB * rBY - vA.x + wA * rAY;
+ var Cdot1Y = vB.y + wB * rBX - vA.y - wA * rAX;
+ var Cdot2 = wB - wA;
+ var impulse = new b2Vec3();
+ this.m_mass.Solve33(impulse, (-Cdot1X), (-Cdot1Y), (-Cdot2));
+ this.m_impulse.Add(impulse);
+ vA.x -= mA * impulse.x;
+ vA.y -= mA * impulse.y;
+ wA -= iA * (rAX * impulse.y - rAY * impulse.x + impulse.z);
+ vB.x += mB * impulse.x;
+ vB.y += mB * impulse.y;
+ wB += iB * (rBX * impulse.y - rBY * impulse.x + impulse.z);
+ bA.m_angularVelocity = wA;
+ bB.m_angularVelocity = wB;
+ }
+ b2WeldJoint.prototype.SolvePositionConstraints = function (baumgarte) {
+ if (baumgarte === undefined) baumgarte = 0;
+ var tMat;
+ var tX = 0;
+ var bA = this.m_bodyA;
+ var bB = this.m_bodyB;
+ tMat = bA.m_xf.R;
+ var rAX = this.m_localAnchorA.x - bA.m_sweep.localCenter.x;
+ var rAY = this.m_localAnchorA.y - bA.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * rAX + tMat.col2.x * rAY);
+ rAY = (tMat.col1.y * rAX + tMat.col2.y * rAY);
+ rAX = tX;
+ tMat = bB.m_xf.R;
+ var rBX = this.m_localAnchorB.x - bB.m_sweep.localCenter.x;
+ var rBY = this.m_localAnchorB.y - bB.m_sweep.localCenter.y;
+ tX = (tMat.col1.x * rBX + tMat.col2.x * rBY);
+ rBY = (tMat.col1.y * rBX + tMat.col2.y * rBY);
+ rBX = tX;
+ var mA = bA.m_invMass;
+ var mB = bB.m_invMass;
+ var iA = bA.m_invI;
+ var iB = bB.m_invI;
+ var C1X = bB.m_sweep.c.x + rBX - bA.m_sweep.c.x - rAX;
+ var C1Y = bB.m_sweep.c.y + rBY - bA.m_sweep.c.y - rAY;
+ var C2 = bB.m_sweep.a - bA.m_sweep.a - this.m_referenceAngle;
+ var k_allowedStretch = 10.0 * b2Settings.b2_linearSlop;
+ var positionError = Math.sqrt(C1X * C1X + C1Y * C1Y);
+ var angularError = b2Math.Abs(C2);
+ if (positionError > k_allowedStretch) {
+ iA *= 1.0;
+ iB *= 1.0;
+ }
+ this.m_mass.col1.x = mA + mB + rAY * rAY * iA + rBY * rBY * iB;
+ this.m_mass.col2.x = (-rAY * rAX * iA) - rBY * rBX * iB;
+ this.m_mass.col3.x = (-rAY * iA) - rBY * iB;
+ this.m_mass.col1.y = this.m_mass.col2.x;
+ this.m_mass.col2.y = mA + mB + rAX * rAX * iA + rBX * rBX * iB;
+ this.m_mass.col3.y = rAX * iA + rBX * iB;
+ this.m_mass.col1.z = this.m_mass.col3.x;
+ this.m_mass.col2.z = this.m_mass.col3.y;
+ this.m_mass.col3.z = iA + iB;
+ var impulse = new b2Vec3();
+ this.m_mass.Solve33(impulse, (-C1X), (-C1Y), (-C2));
+ bA.m_sweep.c.x -= mA * impulse.x;
+ bA.m_sweep.c.y -= mA * impulse.y;
+ bA.m_sweep.a -= iA * (rAX * impulse.y - rAY * impulse.x + impulse.z);
+ bB.m_sweep.c.x += mB * impulse.x;
+ bB.m_sweep.c.y += mB * impulse.y;
+ bB.m_sweep.a += iB * (rBX * impulse.y - rBY * impulse.x + impulse.z);
+ bA.SynchronizeTransform();
+ bB.SynchronizeTransform();
+ return positionError <= b2Settings.b2_linearSlop && angularError <= b2Settings.b2_angularSlop;
+ }
+ Box2D.inherit(b2WeldJointDef, Box2D.Dynamics.Joints.b2JointDef);
+ b2WeldJointDef.prototype.__super = Box2D.Dynamics.Joints.b2JointDef.prototype;
+ b2WeldJointDef.b2WeldJointDef = function () {
+ Box2D.Dynamics.Joints.b2JointDef.b2JointDef.apply(this, arguments);
+ this.localAnchorA = new b2Vec2();
+ this.localAnchorB = new b2Vec2();
+ };
+ b2WeldJointDef.prototype.b2WeldJointDef = function () {
+ this.__super.b2JointDef.call(this);
+ this.type = b2Joint.e_weldJoint;
+ this.referenceAngle = 0.0;
+ }
+ b2WeldJointDef.prototype.Initialize = function (bA, bB, anchor) {
+ this.bodyA = bA;
+ this.bodyB = bB;
+ this.localAnchorA.SetV(this.bodyA.GetLocalPoint(anchor));
+ this.localAnchorB.SetV(this.bodyB.GetLocalPoint(anchor));
+ this.referenceAngle = this.bodyB.GetAngle() - this.bodyA.GetAngle();
+ }
+})();
+(function () {
+ var b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
+ b2DebugDraw.b2DebugDraw = function () {
+ this.m_drawScale = 1.0;
+ this.m_lineThickness = 1.0;
+ this.m_alpha = 1.0;
+ this.m_fillAlpha = 1.0;
+ this.m_xformScale = 1.0;
+ var __this = this;
+ //#WORKAROUND
+ this.m_sprite = {
+ graphics: {
+ clear: function () {
+ __this.m_ctx.clearRect(0, 0, __this.m_ctx.canvas.width, __this.m_ctx.canvas.height)
+ }
+ }
+ };
+ };
+ b2DebugDraw.prototype._color = function (color, alpha) {
+ return "rgba(" + ((color & 0xFF0000) >> 16) + "," + ((color & 0xFF00) >> 8) + "," + (color & 0xFF) + "," + alpha + ")";
+ };
+ b2DebugDraw.prototype.b2DebugDraw = function () {
+ this.m_drawFlags = 0;
+ };
+ b2DebugDraw.prototype.SetFlags = function (flags) {
+ if (flags === undefined) flags = 0;
+ this.m_drawFlags = flags;
+ };
+ b2DebugDraw.prototype.GetFlags = function () {
+ return this.m_drawFlags;
+ };
+ b2DebugDraw.prototype.AppendFlags = function (flags) {
+ if (flags === undefined) flags = 0;
+ this.m_drawFlags |= flags;
+ };
+ b2DebugDraw.prototype.ClearFlags = function (flags) {
+ if (flags === undefined) flags = 0;
+ this.m_drawFlags &= ~flags;
+ };
+ b2DebugDraw.prototype.SetSprite = function (sprite) {
+ this.m_ctx = sprite;
+ };
+ b2DebugDraw.prototype.GetSprite = function () {
+ return this.m_ctx;
+ };
+ b2DebugDraw.prototype.SetDrawScale = function (drawScale) {
+ if (drawScale === undefined) drawScale = 0;
+ this.m_drawScale = drawScale;
+ };
+ b2DebugDraw.prototype.GetDrawScale = function () {
+ return this.m_drawScale;
+ };
+ b2DebugDraw.prototype.SetLineThickness = function (lineThickness) {
+ if (lineThickness === undefined) lineThickness = 0;
+ this.m_lineThickness = lineThickness;
+ this.m_ctx.strokeWidth = lineThickness;
+ };
+ b2DebugDraw.prototype.GetLineThickness = function () {
+ return this.m_lineThickness;
+ };
+ b2DebugDraw.prototype.SetAlpha = function (alpha) {
+ if (alpha === undefined) alpha = 0;
+ this.m_alpha = alpha;
+ };
+ b2DebugDraw.prototype.GetAlpha = function () {
+ return this.m_alpha;
+ };
+ b2DebugDraw.prototype.SetFillAlpha = function (alpha) {
+ if (alpha === undefined) alpha = 0;
+ this.m_fillAlpha = alpha;
+ };
+ b2DebugDraw.prototype.GetFillAlpha = function () {
+ return this.m_fillAlpha;
+ };
+ b2DebugDraw.prototype.SetXFormScale = function (xformScale) {
+ if (xformScale === undefined) xformScale = 0;
+ this.m_xformScale = xformScale;
+ };
+ b2DebugDraw.prototype.GetXFormScale = function () {
+ return this.m_xformScale;
+ };
+ b2DebugDraw.prototype.DrawPolygon = function (vertices, vertexCount, color) {
+ if (!vertexCount) return;
+ var s = this.m_ctx;
+ var drawScale = this.m_drawScale;
+ s.beginPath();
+ s.strokeStyle = this._color(color.color, this.m_alpha);
+ s.moveTo(vertices[0].x * drawScale, vertices[0].y * drawScale);
+ for (var i = 1; i < vertexCount; i++) {
+ s.lineTo(vertices[i].x * drawScale, vertices[i].y * drawScale);
+ }
+ s.lineTo(vertices[0].x * drawScale, vertices[0].y * drawScale);
+ s.closePath();
+ s.stroke();
+ };
+ b2DebugDraw.prototype.DrawSolidPolygon = function (vertices, vertexCount, color) {
+ if (!vertexCount) return;
+ var s = this.m_ctx;
+ var drawScale = this.m_drawScale;
+ s.beginPath();
+ s.strokeStyle = this._color(color.color, this.m_alpha);
+ s.fillStyle = this._color(color.color, this.m_fillAlpha);
+ s.moveTo(vertices[0].x * drawScale, vertices[0].y * drawScale);
+ for (var i = 1; i < vertexCount; i++) {
+ s.lineTo(vertices[i].x * drawScale, vertices[i].y * drawScale);
+ }
+ s.lineTo(vertices[0].x * drawScale, vertices[0].y * drawScale);
+ s.closePath();
+ s.fill();
+ s.stroke();
+ };
+ b2DebugDraw.prototype.DrawCircle = function (center, radius, color) {
+ if (!radius) return;
+ var s = this.m_ctx;
+ var drawScale = this.m_drawScale;
+ s.beginPath();
+ s.strokeStyle = this._color(color.color, this.m_alpha);
+ s.arc(center.x * drawScale, center.y * drawScale, radius * drawScale, 0, Math.PI * 2, true);
+ s.closePath();
+ s.stroke();
+ };
+ b2DebugDraw.prototype.DrawSolidCircle = function (center, radius, axis, color) {
+ if (!radius) return;
+ var s = this.m_ctx,
+ drawScale = this.m_drawScale,
+ cx = center.x * drawScale,
+ cy = center.y * drawScale;
+ s.moveTo(0, 0);
+ s.beginPath();
+ s.strokeStyle = this._color(color.color, this.m_alpha);
+ s.fillStyle = this._color(color.color, this.m_fillAlpha);
+ s.arc(cx, cy, radius * drawScale, 0, Math.PI * 2, true);
+ s.moveTo(cx, cy);
+ s.lineTo((center.x + axis.x * radius) * drawScale, (center.y + axis.y * radius) * drawScale);
+ s.closePath();
+ s.fill();
+ s.stroke();
+ };
+ b2DebugDraw.prototype.DrawSegment = function (p1, p2, color) {
+ var s = this.m_ctx,
+ drawScale = this.m_drawScale;
+ s.strokeStyle = this._color(color.color, this.m_alpha);
+ s.beginPath();
+ s.moveTo(p1.x * drawScale, p1.y * drawScale);
+ s.lineTo(p2.x * drawScale, p2.y * drawScale);
+ s.closePath();
+ s.stroke();
+ };
+ b2DebugDraw.prototype.DrawTransform = function (xf) {
+ var s = this.m_ctx,
+ drawScale = this.m_drawScale;
+ s.beginPath();
+ s.strokeStyle = this._color(0xff0000, this.m_alpha);
+ s.moveTo(xf.position.x * drawScale, xf.position.y * drawScale);
+ s.lineTo((xf.position.x + this.m_xformScale * xf.R.col1.x) * drawScale, (xf.position.y + this.m_xformScale * xf.R.col1.y) * drawScale);
+
+ s.strokeStyle = this._color(0xff00, this.m_alpha);
+ s.moveTo(xf.position.x * drawScale, xf.position.y * drawScale);
+ s.lineTo((xf.position.x + this.m_xformScale * xf.R.col2.x) * drawScale, (xf.position.y + this.m_xformScale * xf.R.col2.y) * drawScale);
+ s.closePath();
+ s.stroke();
+ };
+})(); //post-definitions
+var i;
+for (i = 0; i < Box2D.postDefs.length; ++i) Box2D.postDefs[i]();
+delete Box2D.postDefs;
+
+if (typeof require !== 'undefined' && typeof module !== 'undefined') {
+ module.exports = Box2D;
+}
diff --git a/external/chipmunk/chipmunk.js b/external/chipmunk/chipmunk.js
new file mode 100644
index 0000000000..3be84bfc61
--- /dev/null
+++ b/external/chipmunk/chipmunk.js
@@ -0,0 +1,6196 @@
+(function(){
+/* Copyright (c) 2007 Scott Lembcke
+ *
+ * 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.
+ */
+
+Object.create = Object.create || function(o) {
+ function F() {}
+ F.prototype = o;
+ return new F();
+};
+
+//var VERSION = CP_VERSION_MAJOR + "." + CP_VERSION_MINOR + "." + CP_VERSION_RELEASE;
+
+var cp;
+if(typeof exports === 'undefined'){
+ cp = {};
+
+ if(typeof window === 'object'){
+ window["cp"] = cp;
+ }
+} else {
+ cp = exports;
+}
+
+var assert = function(value, message)
+{
+ if (!value) {
+ throw new Error('Assertion failed: ' + message);
+ }
+};
+
+var assertSoft = function(value, message)
+{
+ if(!value && console && console.warn) {
+ console.warn("ASSERTION FAILED: " + message);
+ if(console.trace) {
+ console.trace();
+ }
+ }
+};
+
+var mymin = function(a, b)
+{
+ return a < b ? a : b;
+};
+var mymax = function(a, b)
+{
+ return a > b ? a : b;
+};
+
+var min, max;
+if (typeof window === 'object' && window.navigator.userAgent.indexOf('Firefox') > -1){
+ // On firefox, Math.min and Math.max are really fast:
+ // http://jsperf.com/math-vs-greater-than/8
+ min = Math.min;
+ max = Math.max;
+} else {
+ // On chrome and safari, Math.min / max are slooow. The ternery operator above is faster
+ // than the builtins because we only have to deal with 2 arguments that are always numbers.
+ min = mymin;
+ max = mymax;
+}
+
+/* The hashpair function takes two numbers and returns a hash code for them.
+ * Required that hashPair(a, b) === hashPair(b, a).
+ * Chipmunk's hashPair function is defined as:
+ * #define CP_HASH_COEF (3344921057ul)
+ * #define CP_HASH_PAIR(A, B) ((cpHashValue)(A)*CP_HASH_COEF ^ (cpHashValue)(B)*CP_HASH_COEF)
+ * But thats not suitable in javascript because multiplying by a large number will make the number
+ * a large float.
+ *
+ * The result of hashPair is used as the key in objects, so it returns a string.
+ */
+var hashPair = function(a, b)
+{
+ //assert(typeof(a) === 'number', "HashPair used on something not a number");
+ return a < b ? a + ' ' + b : b + ' ' + a;
+};
+
+var deleteObjFromList = function(arr, obj)
+{
+ for(var i=0; i> 1;
+ for(var i=1; i maxx || (x == maxx && y > maxy)){
+ maxx = x;
+ maxy = y;
+ end = i;
+ }
+ }
+ return [start, end];
+};
+
+var SWAP = function(arr, idx1, idx2)
+{
+ var tmp = arr[idx1*2];
+ arr[idx1*2] = arr[idx2*2];
+ arr[idx2*2] = tmp;
+
+ tmp = arr[idx1*2+1];
+ arr[idx1*2+1] = arr[idx2*2+1];
+ arr[idx2*2+1] = tmp;
+};
+
+var QHullPartition = function(verts, offs, count, a, b, tol)
+{
+ if(count === 0) return 0;
+
+ var max = 0;
+ var pivot = offs;
+
+ var delta = vsub(b, a);
+ var valueTol = tol * vlength(delta);
+
+ var head = offs;
+ for(var tail = offs+count-1; head <= tail;){
+ var v = new Vect(verts[head * 2], verts[head * 2 + 1]);
+ var value = vcross(delta, vsub(v, a));
+ if(value > valueTol){
+ if(value > max){
+ max = value;
+ pivot = head;
+ }
+
+ head++;
+ } else {
+ SWAP(verts, head, tail);
+ tail--;
+ }
+ }
+
+ // move the new pivot to the front if it's not already there.
+ if(pivot != offs) SWAP(verts, offs, pivot);
+ return head - offs;
+};
+
+var QHullReduce = function(tol, verts, offs, count, a, pivot, b, resultPos)
+{
+ if(count < 0){
+ return 0;
+ } else if(count == 0) {
+ verts[resultPos*2] = pivot.x;
+ verts[resultPos*2+1] = pivot.y;
+ return 1;
+ } else {
+ var left_count = QHullPartition(verts, offs, count, a, pivot, tol);
+ var left = new Vect(verts[offs*2], verts[offs*2+1]);
+ var index = QHullReduce(tol, verts, offs + 1, left_count - 1, a, left, pivot, resultPos);
+
+ var pivotPos = resultPos + index++;
+ verts[pivotPos*2] = pivot.x;
+ verts[pivotPos*2+1] = pivot.y;
+
+ var right_count = QHullPartition(verts, offs + left_count, count - left_count, pivot, b, tol);
+ var right = new Vect(verts[(offs+left_count)*2], verts[(offs+left_count)*2+1]);
+ return index + QHullReduce(tol, verts, offs + left_count + 1, right_count - 1, pivot, right, b, resultPos + index);
+ }
+};
+
+// QuickHull seemed like a neat algorithm, and efficient-ish for large input sets.
+// My implementation performs an in place reduction using the result array as scratch space.
+//
+// Pass an Array into result to put the result of the calculation there. Otherwise, pass null
+// and the verts list will be edited in-place.
+//
+// Expects the verts to be described in the same way as cpPolyShape - which is to say, it should
+// be a list of [x1,y1,x2,y2,x3,y3,...].
+//
+// tolerance is in world coordinates. Eg, 2.
+cp.convexHull = function(verts, result, tolerance)
+{
+ if(result){
+ // Copy the line vertexes into the empty part of the result polyline to use as a scratch buffer.
+ for (var i = 0; i < verts.length; i++){
+ result[i] = verts[i];
+ }
+ } else {
+ // If a result array was not specified, reduce the input instead.
+ result = verts;
+ }
+
+ // Degenerate case, all points are the same.
+ var indexes = loopIndexes(verts);
+ var start = indexes[0], end = indexes[1];
+ if(start == end){
+ //if(first) (*first) = 0;
+ result.length = 2;
+ return result;
+ }
+
+ SWAP(result, 0, start);
+ SWAP(result, 1, end == 0 ? start : end);
+
+ var a = new Vect(result[0], result[1]);
+ var b = new Vect(result[2], result[3]);
+
+ var count = verts.length >> 1;
+ //if(first) (*first) = start;
+ var resultCount = QHullReduce(tolerance, result, 2, count - 2, a, b, a, 1) + 1;
+ result.length = resultCount*2;
+
+ assertSoft(polyValidate(result),
+ "Internal error: cpConvexHull() and cpPolyValidate() did not agree." +
+ "Please report this error with as much info as you can.");
+ return result;
+};
+
+/// Clamp @c f to be between @c min and @c max.
+var clamp = function(f, minv, maxv)
+{
+ return min(max(f, minv), maxv);
+};
+
+/// Clamp @c f to be between 0 and 1.
+var clamp01 = function(f)
+{
+ return max(0, min(f, 1));
+};
+
+/// Linearly interpolate (or extrapolate) between @c f1 and @c f2 by @c t percent.
+var lerp = function(f1, f2, t)
+{
+ return f1*(1 - t) + f2*t;
+};
+
+/// Linearly interpolate from @c f1 to @c f2 by no more than @c d.
+var lerpconst = function(f1, f2, d)
+{
+ return f1 + clamp(f2 - f1, -d, d);
+};
+
+/* Copyright (c) 2007 Scott Lembcke
+ *
+ * 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.
+ */
+
+// I'm using an array tuple here because (at time of writing) its about 3x faster
+// than an object on firefox, and the same speed on chrome.
+
+//var numVects = 0;
+
+var Vect = cp.Vect = function(x, y)
+{
+ this.x = x;
+ this.y = y;
+ //numVects++;
+
+// var s = new Error().stack;
+// traces[s] = traces[s] ? traces[s]+1 : 1;
+};
+
+cp.v = function (x,y) { return new Vect(x, y) };
+
+var vzero = cp.vzero = new Vect(0,0);
+
+// The functions below *could* be rewritten to be instance methods on Vect. I don't
+// know how that would effect performance. For now, I'm keeping the JS similar to
+// the original C code.
+
+/// Vector dot product.
+var vdot = cp.v.dot = function(v1, v2)
+{
+ return v1.x*v2.x + v1.y*v2.y;
+};
+
+var vdot2 = function(x1, y1, x2, y2)
+{
+ return x1*x2 + y1*y2;
+};
+
+/// Returns the length of v.
+var vlength = cp.v.len = function(v)
+{
+ return Math.sqrt(vdot(v, v));
+};
+
+var vlength2 = cp.v.len2 = function(x, y)
+{
+ return Math.sqrt(x*x + y*y);
+};
+
+/// Check if two vectors are equal. (Be careful when comparing floating point numbers!)
+var veql = cp.v.eql = function(v1, v2)
+{
+ return (v1.x === v2.x && v1.y === v2.y);
+};
+
+/// Add two vectors
+var vadd = cp.v.add = function(v1, v2)
+{
+ return new Vect(v1.x + v2.x, v1.y + v2.y);
+};
+
+Vect.prototype.add = function(v2)
+{
+ this.x += v2.x;
+ this.y += v2.y;
+ return this;
+};
+
+/// Subtract two vectors.
+var vsub = cp.v.sub = function(v1, v2)
+{
+ return new Vect(v1.x - v2.x, v1.y - v2.y);
+};
+
+Vect.prototype.sub = function(v2)
+{
+ this.x -= v2.x;
+ this.y -= v2.y;
+ return this;
+};
+
+/// Negate a vector.
+var vneg = cp.v.neg = function(v)
+{
+ return new Vect(-v.x, -v.y);
+};
+
+Vect.prototype.neg = function()
+{
+ this.x = -this.x;
+ this.y = -this.y;
+ return this;
+};
+
+/// Scalar multiplication.
+var vmult = cp.v.mult = function(v, s)
+{
+ return new Vect(v.x*s, v.y*s);
+};
+
+Vect.prototype.mult = function(s)
+{
+ this.x *= s;
+ this.y *= s;
+ return this;
+};
+
+/// 2D vector cross product analog.
+/// The cross product of 2D vectors results in a 3D vector with only a z component.
+/// This function returns the magnitude of the z value.
+var vcross = cp.v.cross = function(v1, v2)
+{
+ return v1.x*v2.y - v1.y*v2.x;
+};
+
+var vcross2 = function(x1, y1, x2, y2)
+{
+ return x1*y2 - y1*x2;
+};
+
+/// Returns a perpendicular vector. (90 degree rotation)
+var vperp = cp.v.perp = function(v)
+{
+ return new Vect(-v.y, v.x);
+};
+
+/// Returns a perpendicular vector. (-90 degree rotation)
+var vpvrperp = cp.v.pvrperp = function(v)
+{
+ return new Vect(v.y, -v.x);
+};
+
+/// Returns the vector projection of v1 onto v2.
+var vproject = cp.v.project = function(v1, v2)
+{
+ return vmult(v2, vdot(v1, v2)/vlengthsq(v2));
+};
+
+Vect.prototype.project = function(v2)
+{
+ this.mult(vdot(this, v2) / vlengthsq(v2));
+ return this;
+};
+
+/// Uses complex number multiplication to rotate v1 by v2. Scaling will occur if v1 is not a unit vector.
+var vrotate = cp.v.rotate = function(v1, v2)
+{
+ return new Vect(v1.x*v2.x - v1.y*v2.y, v1.x*v2.y + v1.y*v2.x);
+};
+
+Vect.prototype.rotate = function(v2)
+{
+ this.x = this.x * v2.x - this.y * v2.y;
+ this.y = this.x * v2.y + this.y * v2.x;
+ return this;
+};
+
+/// Inverse of vrotate().
+var vunrotate = cp.v.unrotate = function(v1, v2)
+{
+ return new Vect(v1.x*v2.x + v1.y*v2.y, v1.y*v2.x - v1.x*v2.y);
+};
+
+/// Returns the squared length of v. Faster than vlength() when you only need to compare lengths.
+var vlengthsq = cp.v.lengthsq = function(v)
+{
+ return vdot(v, v);
+};
+
+var vlengthsq2 = cp.v.lengthsq2 = function(x, y)
+{
+ return x*x + y*y;
+};
+
+/// Linearly interpolate between v1 and v2.
+var vlerp = cp.v.lerp = function(v1, v2, t)
+{
+ return vadd(vmult(v1, 1 - t), vmult(v2, t));
+};
+
+/// Returns a normalized copy of v.
+var vnormalize = cp.v.normalize = function(v)
+{
+ return vmult(v, 1/vlength(v));
+};
+
+/// Returns a normalized copy of v or vzero if v was already vzero. Protects against divide by zero errors.
+var vnormalize_safe = cp.v.normalize_safe = function(v)
+{
+ return (v.x === 0 && v.y === 0 ? vzero : vnormalize(v));
+};
+
+/// Clamp v to length len.
+var vclamp = cp.v.clamp = function(v, len)
+{
+ return (vdot(v,v) > len*len) ? vmult(vnormalize(v), len) : v;
+};
+
+/// Linearly interpolate between v1 towards v2 by distance d.
+var vlerpconst = cp.v.lerpconst = function(v1, v2, d)
+{
+ return vadd(v1, vclamp(vsub(v2, v1), d));
+};
+
+/// Returns the distance between v1 and v2.
+var vdist = cp.v.dist = function(v1, v2)
+{
+ return vlength(vsub(v1, v2));
+};
+
+/// Returns the squared distance between v1 and v2. Faster than vdist() when you only need to compare distances.
+var vdistsq = cp.v.distsq = function(v1, v2)
+{
+ return vlengthsq(vsub(v1, v2));
+};
+
+/// Returns true if the distance between v1 and v2 is less than dist.
+var vnear = cp.v.near = function(v1, v2, dist)
+{
+ return vdistsq(v1, v2) < dist*dist;
+};
+
+/// Spherical linearly interpolate between v1 and v2.
+var vslerp = cp.v.slerp = function(v1, v2, t)
+{
+ var omega = Math.acos(vdot(v1, v2));
+
+ if(omega) {
+ var denom = 1/Math.sin(omega);
+ return vadd(vmult(v1, Math.sin((1 - t)*omega)*denom), vmult(v2, Math.sin(t*omega)*denom));
+ } else {
+ return v1;
+ }
+};
+
+/// Spherical linearly interpolate between v1 towards v2 by no more than angle a radians
+var vslerpconst = cp.v.slerpconst = function(v1, v2, a)
+{
+ var angle = Math.acos(vdot(v1, v2));
+ return vslerp(v1, v2, min(a, angle)/angle);
+};
+
+/// Returns the unit length vector for the given angle (in radians).
+var vforangle = cp.v.forangle = function(a)
+{
+ return new Vect(Math.cos(a), Math.sin(a));
+};
+
+/// Returns the angular direction v is pointing in (in radians).
+var vtoangle = cp.v.toangle = function(v)
+{
+ return Math.atan2(v.y, v.x);
+};
+
+/// Returns a string representation of v. Intended mostly for debugging purposes and not production use.
+var vstr = cp.v.str = function(v)
+{
+ return "(" + v.x.toFixed(3) + ", " + v.y.toFixed(3) + ")";
+};
+
+/* Copyright (c) 2007 Scott Lembcke
+ *
+ * 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.
+ */
+
+/// Chipmunk's axis-aligned 2D bounding box type along with a few handy routines.
+
+var numBB = 0;
+
+// Bounding boxes are JS objects with {l, b, r, t} = left, bottom, right, top, respectively.
+var BB = cp.BB = function(l, b, r, t)
+{
+ this.l = l;
+ this.b = b;
+ this.r = r;
+ this.t = t;
+
+ numBB++;
+};
+
+cp.bb = function(l, b, r, t) { return new BB(l, b, r, t); };
+
+var bbNewForCircle = function(p, r)
+{
+ return new BB(
+ p.x - r,
+ p.y - r,
+ p.x + r,
+ p.y + r
+ );
+};
+
+/// Returns true if @c a and @c b intersect.
+var bbIntersects = function(a, b)
+{
+ return (a.l <= b.r && b.l <= a.r && a.b <= b.t && b.b <= a.t);
+};
+var bbIntersects2 = function(bb, l, b, r, t)
+{
+ return (bb.l <= r && l <= bb.r && bb.b <= t && b <= bb.t);
+};
+
+/// Returns true if @c other lies completely within @c bb.
+var bbContainsBB = function(bb, other)
+{
+ return (bb.l <= other.l && bb.r >= other.r && bb.b <= other.b && bb.t >= other.t);
+};
+
+/// Returns true if @c bb contains @c v.
+var bbContainsVect = function(bb, v)
+{
+ return (bb.l <= v.x && bb.r >= v.x && bb.b <= v.y && bb.t >= v.y);
+};
+var bbContainsVect2 = function(l, b, r, t, v)
+{
+ return (l <= v.x && r >= v.x && b <= v.y && t >= v.y);
+};
+
+/// Returns a bounding box that holds both bounding boxes.
+var bbMerge = function(a, b){
+ return new BB(
+ min(a.l, b.l),
+ min(a.b, b.b),
+ max(a.r, b.r),
+ max(a.t, b.t)
+ );
+};
+
+/// Returns a bounding box that holds both @c bb and @c v.
+var bbExpand = function(bb, v){
+ return new BB(
+ min(bb.l, v.x),
+ min(bb.b, v.y),
+ max(bb.r, v.x),
+ max(bb.t, v.y)
+ );
+};
+
+/// Returns the area of the bounding box.
+var bbArea = function(bb)
+{
+ return (bb.r - bb.l)*(bb.t - bb.b);
+};
+
+/// Merges @c a and @c b and returns the area of the merged bounding box.
+var bbMergedArea = function(a, b)
+{
+ return (max(a.r, b.r) - min(a.l, b.l))*(max(a.t, b.t) - min(a.b, b.b));
+};
+
+var bbMergedArea2 = function(bb, l, b, r, t)
+{
+ return (max(bb.r, r) - min(bb.l, l))*(max(bb.t, t) - min(bb.b, b));
+};
+
+/// Return true if the bounding box intersects the line segment with ends @c a and @c b.
+var bbIntersectsSegment = function(bb, a, b)
+{
+ return (bbSegmentQuery(bb, a, b) != Infinity);
+};
+
+/// Clamp a vector to a bounding box.
+var bbClampVect = function(bb, v)
+{
+ var x = min(max(bb.l, v.x), bb.r);
+ var y = min(max(bb.b, v.y), bb.t);
+ return new Vect(x, y);
+};
+
+// TODO edge case issue
+/// Wrap a vector to a bounding box.
+var bbWrapVect = function(bb, v)
+{
+ var ix = Math.abs(bb.r - bb.l);
+ var modx = (v.x - bb.l) % ix;
+ var x = (modx > 0) ? modx : modx + ix;
+
+ var iy = Math.abs(bb.t - bb.b);
+ var mody = (v.y - bb.b) % iy;
+ var y = (mody > 0) ? mody : mody + iy;
+
+ return new Vect(x + bb.l, y + bb.b);
+};
+/* Copyright (c) 2007 Scott Lembcke
+ *
+ * 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.
+ */
+
+/// Segment query info struct.
+/* These are created using literals where needed.
+typedef struct cpSegmentQueryInfo {
+ /// The shape that was hit, null if no collision occured.
+ cpShape *shape;
+ /// The normalized distance along the query segment in the range [0, 1].
+ cpFloat t;
+ /// The normal of the surface hit.
+ cpVect n;
+} cpSegmentQueryInfo;
+*/
+
+var shapeIDCounter = 0;
+
+var CP_NO_GROUP = cp.NO_GROUP = 0;
+var CP_ALL_LAYERS = cp.ALL_LAYERS = ~0;
+
+cp.resetShapeIdCounter = function()
+{
+ shapeIDCounter = 0;
+};
+
+/// The cpShape struct defines the shape of a rigid body.
+//
+/// Opaque collision shape struct. Do not create directly - instead use
+/// PolyShape, CircleShape and SegmentShape.
+var Shape = cp.Shape = function(body) {
+ /// The rigid body this collision shape is attached to.
+ this.body = body;
+
+ /// The current bounding box of the shape.
+ this.bb_l = this.bb_b = this.bb_r = this.bb_t = 0;
+
+ this.hashid = shapeIDCounter++;
+
+ /// Sensor flag.
+ /// Sensor shapes call collision callbacks but don't produce collisions.
+ this.sensor = false;
+
+ /// Coefficient of restitution. (elasticity)
+ this.e = 0;
+ /// Coefficient of friction.
+ this.u = 0;
+ /// Surface velocity used when solving for friction.
+ this.surface_v = vzero;
+
+ /// Collision type of this shape used when picking collision handlers.
+ this.collision_type = 0;
+ /// Group of this shape. Shapes in the same group don't collide.
+ this.group = 0;
+ // Layer bitmask for this shape. Shapes only collide if the bitwise and of their layers is non-zero.
+ this.layers = CP_ALL_LAYERS;
+
+ this.space = null;
+
+ // Copy the collision code from the prototype into the actual object. This makes collision
+ // function lookups slightly faster.
+ this.collisionCode = this.collisionCode;
+};
+
+Shape.prototype.setElasticity = function(e) { this.e = e; };
+Shape.prototype.setFriction = function(u) { this.body.activate(); this.u = u; };
+Shape.prototype.setLayers = function(layers) { this.body.activate(); this.layers = layers; };
+Shape.prototype.setSensor = function(sensor) { this.body.activate(); this.sensor = sensor; };
+Shape.prototype.setCollisionType = function(collision_type) { this.body.activate(); this.collision_type = collision_type; };
+Shape.prototype.getBody = function() { return this.body; };
+
+Shape.prototype.active = function()
+{
+// return shape->prev || (shape->body && shape->body->shapeList == shape);
+ return this.body && this.body.shapeList.indexOf(this) !== -1;
+};
+
+Shape.prototype.setBody = function(body)
+{
+ assert(!this.active(), "You cannot change the body on an active shape. You must remove the shape from the space before changing the body.");
+ this.body = body;
+};
+
+Shape.prototype.cacheBB = function()
+{
+ return this.update(this.body.p, this.body.rot);
+};
+
+Shape.prototype.update = function(pos, rot)
+{
+ assert(!isNaN(rot.x), 'Rotation is NaN');
+ assert(!isNaN(pos.x), 'Position is NaN');
+ this.cacheData(pos, rot);
+};
+
+Shape.prototype.pointQuery = function(p)
+{
+ var info = this.nearestPointQuery(p);
+ if (info.d < 0) return info;
+};
+
+Shape.prototype.getBB = function()
+{
+ return new BB(this.bb_l, this.bb_b, this.bb_r, this.bb_t);
+};
+
+/* Not implemented - all these getters and setters. Just edit the object directly.
+CP_DefineShapeStructGetter(cpBody*, body, Body);
+void cpShapeSetBody(cpShape *shape, cpBody *body);
+
+CP_DefineShapeStructGetter(cpBB, bb, BB);
+CP_DefineShapeStructProperty(cpBool, sensor, Sensor, cpTrue);
+CP_DefineShapeStructProperty(cpFloat, e, Elasticity, cpFalse);
+CP_DefineShapeStructProperty(cpFloat, u, Friction, cpTrue);
+CP_DefineShapeStructProperty(cpVect, surface_v, SurfaceVelocity, cpTrue);
+CP_DefineShapeStructProperty(cpDataPointer, data, UserData, cpFalse);
+CP_DefineShapeStructProperty(cpCollisionType, collision_type, CollisionType, cpTrue);
+CP_DefineShapeStructProperty(cpGroup, group, Group, cpTrue);
+CP_DefineShapeStructProperty(cpLayers, layers, Layers, cpTrue);
+*/
+
+/// Extended point query info struct. Returned from calling pointQuery on a shape.
+var PointQueryExtendedInfo = function(shape)
+{
+ /// Shape that was hit, NULL if no collision occurred.
+ this.shape = shape;
+ /// Depth of the point inside the shape.
+ this.d = Infinity;
+ /// Direction of minimum norm to the shape's surface.
+ this.n = vzero;
+};
+
+var NearestPointQueryInfo = function(shape, p, d)
+{
+ /// The nearest shape, NULL if no shape was within range.
+ this.shape = shape;
+ /// The closest point on the shape's surface. (in world space coordinates)
+ this.p = p;
+ /// The distance to the point. The distance is negative if the point is inside the shape.
+ this.d = d;
+};
+
+var SegmentQueryInfo = function(shape, t, n)
+{
+ /// The shape that was hit, NULL if no collision occured.
+ this.shape = shape;
+ /// The normalized distance along the query segment in the range [0, 1].
+ this.t = t;
+ /// The normal of the surface hit.
+ this.n = n;
+};
+
+/// Get the hit point for a segment query.
+SegmentQueryInfo.prototype.hitPoint = function(start, end)
+{
+ return vlerp(start, end, this.t);
+};
+
+/// Get the hit distance for a segment query.
+SegmentQueryInfo.prototype.hitDist = function(start, end)
+{
+ return vdist(start, end) * this.t;
+};
+
+// Circles.
+
+var CircleShape = cp.CircleShape = function(body, radius, offset)
+{
+ this.c = this.tc = offset;
+ this.r = radius;
+
+ this.type = 'circle';
+
+ Shape.call(this, body);
+};
+
+CircleShape.prototype = Object.create(Shape.prototype);
+
+CircleShape.prototype.cacheData = function(p, rot)
+{
+ //var c = this.tc = vadd(p, vrotate(this.c, rot));
+ var c = this.tc = vrotate(this.c, rot).add(p);
+ //this.bb = bbNewForCircle(c, this.r);
+ var r = this.r;
+ this.bb_l = c.x - r;
+ this.bb_b = c.y - r;
+ this.bb_r = c.x + r;
+ this.bb_t = c.y + r;
+};
+
+/// Test if a point lies within a shape.
+/*CircleShape.prototype.pointQuery = function(p)
+{
+ var delta = vsub(p, this.tc);
+ var distsq = vlengthsq(delta);
+ var r = this.r;
+
+ if(distsq < r*r){
+ var info = new PointQueryExtendedInfo(this);
+
+ var dist = Math.sqrt(distsq);
+ info.d = r - dist;
+ info.n = vmult(delta, 1/dist);
+ return info;
+ }
+};*/
+
+CircleShape.prototype.nearestPointQuery = function(p)
+{
+ var deltax = p.x - this.tc.x;
+ var deltay = p.y - this.tc.y;
+ var d = vlength2(deltax, deltay);
+ var r = this.r;
+
+ var nearestp = new Vect(this.tc.x + deltax * r/d, this.tc.y + deltay * r/d);
+ return new NearestPointQueryInfo(this, nearestp, d - r);
+};
+
+var circleSegmentQuery = function(shape, center, r, a, b, info)
+{
+ // offset the line to be relative to the circle
+ a = vsub(a, center);
+ b = vsub(b, center);
+
+ var qa = vdot(a, a) - 2*vdot(a, b) + vdot(b, b);
+ var qb = -2*vdot(a, a) + 2*vdot(a, b);
+ var qc = vdot(a, a) - r*r;
+
+ var det = qb*qb - 4*qa*qc;
+
+ if(det >= 0)
+ {
+ var t = (-qb - Math.sqrt(det))/(2*qa);
+ if(0 <= t && t <= 1){
+ return new SegmentQueryInfo(shape, t, vnormalize(vlerp(a, b, t)));
+ }
+ }
+};
+
+CircleShape.prototype.segmentQuery = function(a, b)
+{
+ return circleSegmentQuery(this, this.tc, this.r, a, b);
+};
+
+// The C API has these, and also getters. Its not idiomatic to
+// write getters and setters in JS.
+/*
+CircleShape.prototype.setRadius = function(radius)
+{
+ this.r = radius;
+}
+
+CircleShape.prototype.setOffset = function(offset)
+{
+ this.c = offset;
+}*/
+
+// Segment shape
+
+var SegmentShape = cp.SegmentShape = function(body, a, b, r)
+{
+ this.a = a;
+ this.b = b;
+ this.n = vperp(vnormalize(vsub(b, a)));
+
+ this.ta = this.tb = this.tn = null;
+
+ this.r = r;
+
+ this.a_tangent = vzero;
+ this.b_tangent = vzero;
+
+ this.type = 'segment';
+ Shape.call(this, body);
+};
+
+SegmentShape.prototype = Object.create(Shape.prototype);
+
+SegmentShape.prototype.cacheData = function(p, rot)
+{
+ this.ta = vadd(p, vrotate(this.a, rot));
+ this.tb = vadd(p, vrotate(this.b, rot));
+ this.tn = vrotate(this.n, rot);
+
+ var l,r,b,t;
+
+ if(this.ta.x < this.tb.x){
+ l = this.ta.x;
+ r = this.tb.x;
+ } else {
+ l = this.tb.x;
+ r = this.ta.x;
+ }
+
+ if(this.ta.y < this.tb.y){
+ b = this.ta.y;
+ t = this.tb.y;
+ } else {
+ b = this.tb.y;
+ t = this.ta.y;
+ }
+
+ var rad = this.r;
+
+ this.bb_l = l - rad;
+ this.bb_b = b - rad;
+ this.bb_r = r + rad;
+ this.bb_t = t + rad;
+};
+
+SegmentShape.prototype.nearestPointQuery = function(p)
+{
+ var closest = closestPointOnSegment(p, this.ta, this.tb);
+
+ var deltax = p.x - closest.x;
+ var deltay = p.y - closest.y;
+ var d = vlength2(deltax, deltay);
+ var r = this.r;
+
+ var nearestp = (d ? vadd(closest, vmult(new Vect(deltax, deltay), r/d)) : closest);
+ return new NearestPointQueryInfo(this, nearestp, d - r);
+};
+
+SegmentShape.prototype.segmentQuery = function(a, b)
+{
+ var n = this.tn;
+ var d = vdot(vsub(this.ta, a), n);
+ var r = this.r;
+
+ var flipped_n = (d > 0 ? vneg(n) : n);
+ var n_offset = vsub(vmult(flipped_n, r), a);
+
+ var seg_a = vadd(this.ta, n_offset);
+ var seg_b = vadd(this.tb, n_offset);
+ var delta = vsub(b, a);
+
+ if(vcross(delta, seg_a)*vcross(delta, seg_b) <= 0){
+ var d_offset = d + (d > 0 ? -r : r);
+ var ad = -d_offset;
+ var bd = vdot(delta, n) - d_offset;
+
+ if(ad*bd < 0){
+ return new SegmentQueryInfo(this, ad/(ad - bd), flipped_n);
+ }
+ } else if(r !== 0){
+ var info1 = circleSegmentQuery(this, this.ta, this.r, a, b);
+ var info2 = circleSegmentQuery(this, this.tb, this.r, a, b);
+
+ if (info1){
+ return info2 && info2.t < info1.t ? info2 : info1;
+ } else {
+ return info2;
+ }
+ }
+};
+
+SegmentShape.prototype.setNeighbors = function(prev, next)
+{
+ this.a_tangent = vsub(prev, this.a);
+ this.b_tangent = vsub(next, this.b);
+};
+
+SegmentShape.prototype.setEndpoints = function(a, b)
+{
+ this.a = a;
+ this.b = b;
+ this.n = vperp(vnormalize(vsub(b, a)));
+};
+
+/*
+cpSegmentShapeSetRadius(cpShape *shape, cpFloat radius)
+{
+ this.r = radius;
+}*/
+
+/*
+CP_DeclareShapeGetter(cpSegmentShape, cpVect, A);
+CP_DeclareShapeGetter(cpSegmentShape, cpVect, B);
+CP_DeclareShapeGetter(cpSegmentShape, cpVect, Normal);
+CP_DeclareShapeGetter(cpSegmentShape, cpFloat, Radius);
+*/
+
+/* Copyright (c) 2007 Scott Lembcke
+ *
+ * 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.
+ */
+
+/// Check that a set of vertexes is convex and has a clockwise winding.
+var polyValidate = function(verts)
+{
+ var len = verts.length;
+ for(var i=0; i 0){
+ if(vcross2(bx - ax, by - ay, cx - bx, cy - by) > 0){
+ return false;
+ }
+ }
+
+ return true;
+};
+
+/// Initialize a polygon shape.
+/// The vertexes must be convex and have a clockwise winding.
+var PolyShape = cp.PolyShape = function(body, verts, offset)
+{
+ this.setVerts(verts, offset);
+ this.type = 'poly';
+ Shape.call(this, body);
+};
+
+PolyShape.prototype = Object.create(Shape.prototype);
+
+var SplittingPlane = function(n, d)
+{
+ this.n = n;
+ this.d = d;
+};
+
+SplittingPlane.prototype.compare = function(v)
+{
+ return vdot(this.n, v) - this.d;
+};
+
+PolyShape.prototype.setVerts = function(verts, offset)
+{
+ assert(verts.length >= 4, "Polygons require some verts");
+ assert(typeof(verts[0]) === 'number',
+ 'Polygon verticies should be specified in a flattened list (eg [x1,y1,x2,y2,x3,y3,...])');
+
+ // Fail if the user attempts to pass a concave poly, or a bad winding.
+ assert(polyValidate(verts), "Polygon is concave or has a reversed winding. Consider using cpConvexHull()");
+
+ var len = verts.length;
+ var numVerts = len >> 1;
+
+ // This a pretty bad way to do this in javascript. As a first pass, I want to keep
+ // the code similar to the C.
+ this.verts = new Array(len);
+ this.tVerts = new Array(len);
+ this.planes = new Array(numVerts);
+ this.tPlanes = new Array(numVerts);
+
+ for(var i=0; i>1] = new SplittingPlane(n, vdot2(n.x, n.y, ax, ay));
+ this.tPlanes[i>>1] = new SplittingPlane(new Vect(0,0), 0);
+ }
+};
+
+/// Initialize a box shaped polygon shape.
+var BoxShape = cp.BoxShape = function(body, width, height)
+{
+ var hw = width/2;
+ var hh = height/2;
+
+ return BoxShape2(body, new BB(-hw, -hh, hw, hh));
+};
+
+/// Initialize an offset box shaped polygon shape.
+var BoxShape2 = cp.BoxShape2 = function(body, box)
+{
+ var verts = [
+ box.l, box.b,
+ box.l, box.t,
+ box.r, box.t,
+ box.r, box.b
+ ];
+
+ return new PolyShape(body, verts, vzero);
+};
+
+PolyShape.prototype.transformVerts = function(p, rot)
+{
+ var src = this.verts;
+ var dst = this.tVerts;
+
+ var l = Infinity, r = -Infinity;
+ var b = Infinity, t = -Infinity;
+
+ for(var i=0; i (' + vx + ',' + vy + ')');
+
+ dst[i] = vx;
+ dst[i+1] = vy;
+
+ l = min(l, vx);
+ r = max(r, vx);
+ b = min(b, vy);
+ t = max(t, vy);
+ }
+
+ this.bb_l = l;
+ this.bb_b = b;
+ this.bb_r = r;
+ this.bb_t = t;
+};
+
+PolyShape.prototype.transformAxes = function(p, rot)
+{
+ var src = this.planes;
+ var dst = this.tPlanes;
+
+ for(var i=0; i 0) outside = true;
+
+ var v1x = verts[i*2];
+ var v1y = verts[i*2 + 1];
+ var closest = closestPointOnSegment2(p.x, p.y, v0x, v0y, v1x, v1y);
+
+ var dist = vdist(p, closest);
+ if(dist < minDist){
+ minDist = dist;
+ closestPoint = closest;
+ }
+
+ v0x = v1x;
+ v0y = v1y;
+ }
+
+ return new NearestPointQueryInfo(this, closestPoint, (outside ? minDist : -minDist));
+};
+
+PolyShape.prototype.segmentQuery = function(a, b)
+{
+ var axes = this.tPlanes;
+ var verts = this.tVerts;
+ var numVerts = axes.length;
+ var len = numVerts * 2;
+
+ for(var i=0; i an) continue;
+
+ var bn = vdot(b, n);
+ var t = (axes[i].d - an)/(bn - an);
+ if(t < 0 || 1 < t) continue;
+
+ var point = vlerp(a, b, t);
+ var dt = -vcross(n, point);
+ var dtMin = -vcross2(n.x, n.y, verts[i*2], verts[i*2+1]);
+ var dtMax = -vcross2(n.x, n.y, verts[(i*2+2)%len], verts[(i*2+3)%len]);
+
+ if(dtMin <= dt && dt <= dtMax){
+ // josephg: In the original C code, this function keeps
+ // looping through axes after finding a match. I *think*
+ // this code is equivalent...
+ return new SegmentQueryInfo(this, t, n);
+ }
+ }
+};
+
+PolyShape.prototype.valueOnAxis = function(n, d)
+{
+ var verts = this.tVerts;
+ var m = vdot2(n.x, n.y, verts[0], verts[1]);
+
+ for(var i=2; i 0) return false;
+ }
+
+ return true;
+};
+
+PolyShape.prototype.containsVertPartial = function(vx, vy, n)
+{
+ var planes = this.tPlanes;
+
+ for(var i=0; i 0) return false;
+ }
+
+ return true;
+};
+
+// These methods are provided for API compatibility with Chipmunk. I recommend against using
+// them - just access the poly.verts list directly.
+PolyShape.prototype.getNumVerts = function() { return this.verts.length / 2; };
+PolyShape.prototype.getVert = function(i)
+{
+ return new Vect(this.verts[i * 2], this.verts[i * 2 + 1]);
+};
+
+/* Copyright (c) 2007 Scott Lembcke
+ *
+ * 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.
+ */
+
+/// @defgroup cpBody cpBody
+/// Chipmunk's rigid body type. Rigid bodies hold the physical properties of an object like
+/// it's mass, and position and velocity of it's center of gravity. They don't have an shape on their own.
+/// They are given a shape by creating collision shapes (cpShape) that point to the body.
+/// @{
+
+var Body = cp.Body = function(m, i) {
+ /// Mass of the body.
+ /// Must agree with cpBody.m_inv! Use body.setMass() when changing the mass for this reason.
+ //this.m;
+ /// Mass inverse.
+ //this.m_inv;
+
+ /// Moment of inertia of the body.
+ /// Must agree with cpBody.i_inv! Use body.setMoment() when changing the moment for this reason.
+ //this.i;
+ /// Moment of inertia inverse.
+ //this.i_inv;
+
+ /// Position of the rigid body's center of gravity.
+ this.p = new Vect(0,0);
+ /// Velocity of the rigid body's center of gravity.
+ this.vx = this.vy = 0;
+ /// Force acting on the rigid body's center of gravity.
+ this.f = new Vect(0,0);
+
+ /// Rotation of the body around it's center of gravity in radians.
+ /// Must agree with cpBody.rot! Use cpBodySetAngle() when changing the angle for this reason.
+ //this.a;
+ /// Angular velocity of the body around it's center of gravity in radians/second.
+ this.w = 0;
+ /// Torque applied to the body around it's center of gravity.
+ this.t = 0;
+
+ /// Cached unit length vector representing the angle of the body.
+ /// Used for fast rotations using cpvrotate().
+ //cpVect rot;
+
+ /// Maximum velocity allowed when updating the velocity.
+ this.v_limit = Infinity;
+ /// Maximum rotational rate (in radians/second) allowed when updating the angular velocity.
+ this.w_limit = Infinity;
+
+ // This stuff is all private.
+ this.v_biasx = this.v_biasy = 0;
+ this.w_bias = 0;
+
+ this.space = null;
+
+ this.shapeList = [];
+ this.arbiterList = null; // These are both wacky linked lists.
+ this.constraintList = null;
+
+ // This stuff is used to track information on the collision graph.
+ this.nodeRoot = null;
+ this.nodeNext = null;
+ this.nodeIdleTime = 0;
+
+ // Set this.m and this.m_inv
+ this.setMass(m);
+
+ // Set this.i and this.i_inv
+ this.setMoment(i);
+
+ // Set this.a and this.rot
+ this.rot = new Vect(0,0);
+ this.setAngle(0);
+};
+
+// I wonder if this should use the constructor style like Body...
+var createStaticBody = function()
+{
+ var body = new Body(Infinity, Infinity);
+ body.nodeIdleTime = Infinity;
+
+ return body;
+};
+ cp.StaticBody = createStaticBody;
+
+if (typeof DEBUG !== 'undefined' && DEBUG) {
+ var v_assert_nan = function(v, message){assert(v.x == v.x && v.y == v.y, message); };
+ var v_assert_infinite = function(v, message){assert(Math.abs(v.x) !== Infinity && Math.abs(v.y) !== Infinity, message);};
+ var v_assert_sane = function(v, message){v_assert_nan(v, message); v_assert_infinite(v, message);};
+
+ Body.prototype.sanityCheck = function()
+ {
+ assert(this.m === this.m && this.m_inv === this.m_inv, "Body's mass is invalid.");
+ assert(this.i === this.i && this.i_inv === this.i_inv, "Body's moment is invalid.");
+
+ v_assert_sane(this.p, "Body's position is invalid.");
+ v_assert_sane(this.f, "Body's force is invalid.");
+ assert(this.vx === this.vx && Math.abs(this.vx) !== Infinity, "Body's velocity is invalid.");
+ assert(this.vy === this.vy && Math.abs(this.vy) !== Infinity, "Body's velocity is invalid.");
+
+ assert(this.a === this.a && Math.abs(this.a) !== Infinity, "Body's angle is invalid.");
+ assert(this.w === this.w && Math.abs(this.w) !== Infinity, "Body's angular velocity is invalid.");
+ assert(this.t === this.t && Math.abs(this.t) !== Infinity, "Body's torque is invalid.");
+
+ v_assert_sane(this.rot, "Body's rotation vector is invalid.");
+
+ assert(this.v_limit === this.v_limit, "Body's velocity limit is invalid.");
+ assert(this.w_limit === this.w_limit, "Body's angular velocity limit is invalid.");
+ };
+} else {
+ Body.prototype.sanityCheck = function(){};
+}
+
+Body.prototype.getPos = function() { return this.p; };
+Body.prototype.getVel = function() { return new Vect(this.vx, this.vy); };
+Body.prototype.getAngVel = function() { return this.w; };
+
+/// Returns true if the body is sleeping.
+Body.prototype.isSleeping = function()
+{
+ return this.nodeRoot !== null;
+};
+
+/// Returns true if the body is static.
+Body.prototype.isStatic = function()
+{
+ return this.nodeIdleTime === Infinity;
+};
+
+/// Returns true if the body has not been added to a space.
+Body.prototype.isRogue = function()
+{
+ return this.space === null;
+};
+
+// It would be nicer to use defineProperty for this, but its about 30x slower:
+// http://jsperf.com/defineproperty-vs-setter
+Body.prototype.setMass = function(mass)
+{
+ assert(mass > 0, "Mass must be positive and non-zero.");
+
+ //activate is defined in cpSpaceComponent
+ this.activate();
+ this.m = mass;
+ this.m_inv = 1/mass;
+};
+
+Body.prototype.setMoment = function(moment)
+{
+ assert(moment > 0, "Moment of Inertia must be positive and non-zero.");
+
+ this.activate();
+ this.i = moment;
+ this.i_inv = 1/moment;
+};
+
+Body.prototype.addShape = function(shape)
+{
+ this.shapeList.push(shape);
+};
+
+Body.prototype.removeShape = function(shape)
+{
+ // This implementation has a linear time complexity with the number of shapes.
+ // The original implementation used linked lists instead, which might be faster if
+ // you're constantly editing the shape of a body. I expect most bodies will never
+ // have their shape edited, so I'm just going to use the simplest possible implemention.
+ deleteObjFromList(this.shapeList, shape);
+};
+
+var filterConstraints = function(node, body, filter)
+{
+ if(node === filter){
+ return node.next(body);
+ } else if(node.a === body){
+ node.next_a = filterConstraints(node.next_a, body, filter);
+ } else {
+ node.next_b = filterConstraints(node.next_b, body, filter);
+ }
+
+ return node;
+};
+
+Body.prototype.removeConstraint = function(constraint)
+{
+ // The constraint must be in the constraints list when this is called.
+ this.constraintList = filterConstraints(this.constraintList, this, constraint);
+};
+
+Body.prototype.setPos = function(pos)
+{
+ this.activate();
+ this.sanityCheck();
+ // If I allow the position to be set to vzero, vzero will get changed.
+ if (pos === vzero) {
+ pos = cp.v(0,0);
+ }
+ this.p = pos;
+};
+
+Body.prototype.setVel = function(velocity)
+{
+ this.activate();
+ this.vx = velocity.x;
+ this.vy = velocity.y;
+};
+
+Body.prototype.setAngVel = function(w)
+{
+ this.activate();
+ this.w = w;
+};
+
+Body.prototype.setAngleInternal = function(angle)
+{
+ assert(!isNaN(angle), "Internal Error: Attempting to set body's angle to NaN");
+ this.a = angle;//fmod(a, (cpFloat)M_PI*2.0f);
+
+ //this.rot = vforangle(angle);
+ this.rot.x = Math.cos(angle);
+ this.rot.y = Math.sin(angle);
+};
+
+Body.prototype.setAngle = function(angle)
+{
+ this.activate();
+ this.sanityCheck();
+ this.setAngleInternal(angle);
+};
+
+Body.prototype.velocity_func = function(gravity, damping, dt)
+{
+ //this.v = vclamp(vadd(vmult(this.v, damping), vmult(vadd(gravity, vmult(this.f, this.m_inv)), dt)), this.v_limit);
+ var vx = this.vx * damping + (gravity.x + this.f.x * this.m_inv) * dt;
+ var vy = this.vy * damping + (gravity.y + this.f.y * this.m_inv) * dt;
+
+ //var v = vclamp(new Vect(vx, vy), this.v_limit);
+ //this.vx = v.x; this.vy = v.y;
+ var v_limit = this.v_limit;
+ var lensq = vx * vx + vy * vy;
+ var scale = (lensq > v_limit*v_limit) ? v_limit / Math.sqrt(lensq) : 1;
+ this.vx = vx * scale;
+ this.vy = vy * scale;
+
+ var w_limit = this.w_limit;
+ this.w = clamp(this.w*damping + this.t*this.i_inv*dt, -w_limit, w_limit);
+
+ this.sanityCheck();
+};
+
+Body.prototype.position_func = function(dt)
+{
+ //this.p = vadd(this.p, vmult(vadd(this.v, this.v_bias), dt));
+
+ //this.p = this.p + (this.v + this.v_bias) * dt;
+ this.p.x += (this.vx + this.v_biasx) * dt;
+ this.p.y += (this.vy + this.v_biasy) * dt;
+
+ this.setAngleInternal(this.a + (this.w + this.w_bias)*dt);
+
+ this.v_biasx = this.v_biasy = 0;
+ this.w_bias = 0;
+
+ this.sanityCheck();
+};
+
+Body.prototype.resetForces = function()
+{
+ this.activate();
+ this.f = new Vect(0,0);
+ this.t = 0;
+};
+
+Body.prototype.applyForce = function(force, r)
+{
+ this.activate();
+ this.f = vadd(this.f, force);
+ this.t += vcross(r, force);
+};
+
+Body.prototype.applyImpulse = function(j, r)
+{
+ this.activate();
+ apply_impulse(this, j.x, j.y, r);
+};
+
+Body.prototype.getVelAtPoint = function(r)
+{
+ return vadd(new Vect(this.vx, this.vy), vmult(vperp(r), this.w));
+};
+
+/// Get the velocity on a body (in world units) at a point on the body in world coordinates.
+Body.prototype.getVelAtWorldPoint = function(point)
+{
+ return this.getVelAtPoint(vsub(point, this.p));
+};
+
+/// Get the velocity on a body (in world units) at a point on the body in local coordinates.
+Body.prototype.getVelAtLocalPoint = function(point)
+{
+ return this.getVelAtPoint(vrotate(point, this.rot));
+};
+
+Body.prototype.eachShape = function(func)
+{
+ for(var i = 0, len = this.shapeList.length; i < len; i++) {
+ func(this.shapeList[i]);
+ }
+};
+
+Body.prototype.eachConstraint = function(func)
+{
+ var constraint = this.constraintList;
+ while(constraint) {
+ var next = constraint.next(this);
+ func(constraint);
+ constraint = next;
+ }
+};
+
+Body.prototype.eachArbiter = function(func)
+{
+ var arb = this.arbiterList;
+ while(arb){
+ var next = arb.next(this);
+
+ arb.swappedColl = (this === arb.body_b);
+ func(arb);
+
+ arb = next;
+ }
+};
+
+/// Convert body relative/local coordinates to absolute/world coordinates.
+Body.prototype.local2World = function(v)
+{
+ return vadd(this.p, vrotate(v, this.rot));
+};
+
+/// Convert body absolute/world coordinates to relative/local coordinates.
+Body.prototype.world2Local = function(v)
+{
+ return vunrotate(vsub(v, this.p), this.rot);
+};
+
+/// Get the kinetic energy of a body.
+Body.prototype.kineticEnergy = function()
+{
+ // Need to do some fudging to avoid NaNs
+ var vsq = this.vx*this.vx + this.vy*this.vy;
+ var wsq = this.w * this.w;
+ return (vsq ? vsq*this.m : 0) + (wsq ? wsq*this.i : 0);
+};
+
+/* Copyright (c) 2010 Scott Lembcke
+ *
+ * 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.
+ */
+
+/**
+ @defgroup cpSpatialIndex cpSpatialIndex
+
+ Spatial indexes are data structures that are used to accelerate collision detection
+ and spatial queries. Chipmunk provides a number of spatial index algorithms to pick from
+ and they are programmed in a generic way so that you can use them for holding more than
+ just Shapes.
+
+ It works by using pointers to the objects you add and using a callback to ask your code
+ for bounding boxes when it needs them. Several types of queries can be performed an index as well
+ as reindexing and full collision information. All communication to the spatial indexes is performed
+ through callback functions.
+
+ Spatial indexes should be treated as opaque structs.
+ This means you shouldn't be reading any of the fields directly.
+
+ All spatial indexes define the following methods:
+
+ // The number of objects in the spatial index.
+ count = 0;
+
+ // Iterate the objects in the spatial index. @c func will be called once for each object.
+ each(func);
+
+ // Returns true if the spatial index contains the given object.
+ // Most spatial indexes use hashed storage, so you must provide a hash value too.
+ contains(obj, hashid);
+
+ // Add an object to a spatial index.
+ insert(obj, hashid);
+
+ // Remove an object from a spatial index.
+ remove(obj, hashid);
+
+ // Perform a full reindex of a spatial index.
+ reindex();
+
+ // Reindex a single object in the spatial index.
+ reindexObject(obj, hashid);
+
+ // Perform a point query against the spatial index, calling @c func for each potential match.
+ // A pointer to the point will be passed as @c obj1 of @c func.
+ // func(shape);
+ pointQuery(point, func);
+
+ // Perform a segment query against the spatial index, calling @c func for each potential match.
+ // func(shape);
+ segmentQuery(vect a, vect b, t_exit, func);
+
+ // Perform a rectangle query against the spatial index, calling @c func for each potential match.
+ // func(shape);
+ query(bb, func);
+
+ // Simultaneously reindex and find all colliding objects.
+ // @c func will be called once for each potentially overlapping pair of objects found.
+ // If the spatial index was initialized with a static index, it will collide it's objects against that as well.
+ reindexQuery(func);
+*/
+
+var SpatialIndex = cp.SpatialIndex = function(staticIndex)
+{
+ this.staticIndex = staticIndex;
+
+
+ if(staticIndex){
+ if(staticIndex.dynamicIndex){
+ throw new Error("This static index is already associated with a dynamic index.");
+ }
+ staticIndex.dynamicIndex = this;
+ }
+};
+
+// Collide the objects in an index against the objects in a staticIndex using the query callback function.
+SpatialIndex.prototype.collideStatic = function(staticIndex, func)
+{
+ if(staticIndex.count > 0){
+ var query = staticIndex.query;
+
+ this.each(function(obj) {
+ query(obj, new BB(obj.bb_l, obj.bb_b, obj.bb_r, obj.bb_t), func);
+ });
+ }
+};
+
+
+/* Copyright (c) 2009 Scott Lembcke
+ *
+ * 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.
+ */
+
+// This file implements a modified AABB tree for collision detection.
+
+var BBTree = cp.BBTree = function(staticIndex)
+{
+ SpatialIndex.call(this, staticIndex);
+
+ this.velocityFunc = null;
+
+ // This is a hash from object ID -> object for the objects stored in the BBTree.
+ this.leaves = {};
+ // A count of the number of leaves in the BBTree.
+ this.count = 0;
+
+ this.root = null;
+
+ // A linked list containing an object pool of tree nodes and pairs.
+ this.pooledNodes = null;
+ this.pooledPairs = null;
+
+ this.stamp = 0;
+};
+
+BBTree.prototype = Object.create(SpatialIndex.prototype);
+
+var numNodes = 0;
+
+var Node = function(tree, a, b)
+{
+ this.obj = null;
+ this.bb_l = min(a.bb_l, b.bb_l);
+ this.bb_b = min(a.bb_b, b.bb_b);
+ this.bb_r = max(a.bb_r, b.bb_r);
+ this.bb_t = max(a.bb_t, b.bb_t);
+ this.parent = null;
+
+ this.setA(a);
+ this.setB(b);
+};
+
+BBTree.prototype.makeNode = function(a, b)
+{
+ var node = this.pooledNodes;
+ if(node){
+ this.pooledNodes = node.parent;
+ node.constructor(this, a, b);
+ return node;
+ } else {
+ numNodes++;
+ return new Node(this, a, b);
+ }
+};
+
+var numLeaves = 0;
+var Leaf = function(tree, obj)
+{
+ this.obj = obj;
+ tree.getBB(obj, this);
+
+ this.parent = null;
+
+ this.stamp = 1;
+ this.pairs = null;
+ numLeaves++;
+};
+
+// **** Misc Functions
+
+BBTree.prototype.getBB = function(obj, dest)
+{
+ var velocityFunc = this.velocityFunc;
+ if(velocityFunc){
+ var coef = 0.1;
+ var x = (obj.bb_r - obj.bb_l)*coef;
+ var y = (obj.bb_t - obj.bb_b)*coef;
+
+ var v = vmult(velocityFunc(obj), 0.1);
+
+ dest.bb_l = obj.bb_l + min(-x, v.x);
+ dest.bb_b = obj.bb_b + min(-y, v.y);
+ dest.bb_r = obj.bb_r + max( x, v.x);
+ dest.bb_t = obj.bb_t + max( y, v.y);
+ } else {
+ dest.bb_l = obj.bb_l;
+ dest.bb_b = obj.bb_b;
+ dest.bb_r = obj.bb_r;
+ dest.bb_t = obj.bb_t;
+ }
+};
+
+BBTree.prototype.getStamp = function()
+{
+ var dynamic = this.dynamicIndex;
+ return (dynamic && dynamic.stamp ? dynamic.stamp : this.stamp);
+};
+
+BBTree.prototype.incrementStamp = function()
+{
+ if(this.dynamicIndex && this.dynamicIndex.stamp){
+ this.dynamicIndex.stamp++;
+ } else {
+ this.stamp++;
+ }
+}
+
+// **** Pair/Thread Functions
+
+var numPairs = 0;
+// Objects created with constructors are faster than object literals. :(
+var Pair = function(leafA, nextA, leafB, nextB)
+{
+ this.prevA = null;
+ this.leafA = leafA;
+ this.nextA = nextA;
+
+ this.prevB = null;
+ this.leafB = leafB;
+ this.nextB = nextB;
+};
+
+BBTree.prototype.makePair = function(leafA, nextA, leafB, nextB)
+{
+ //return new Pair(leafA, nextA, leafB, nextB);
+ var pair = this.pooledPairs;
+ if (pair)
+ {
+ this.pooledPairs = pair.prevA;
+
+ pair.prevA = null;
+ pair.leafA = leafA;
+ pair.nextA = nextA;
+
+ pair.prevB = null;
+ pair.leafB = leafB;
+ pair.nextB = nextB;
+
+ //pair.constructor(leafA, nextA, leafB, nextB);
+ return pair;
+ } else {
+ numPairs++;
+ return new Pair(leafA, nextA, leafB, nextB);
+ }
+};
+
+Pair.prototype.recycle = function(tree)
+{
+ this.prevA = tree.pooledPairs;
+ tree.pooledPairs = this;
+};
+
+var unlinkThread = function(prev, leaf, next)
+{
+ if(next){
+ if(next.leafA === leaf) next.prevA = prev; else next.prevB = prev;
+ }
+
+ if(prev){
+ if(prev.leafA === leaf) prev.nextA = next; else prev.nextB = next;
+ } else {
+ leaf.pairs = next;
+ }
+};
+
+Leaf.prototype.clearPairs = function(tree)
+{
+ var pair = this.pairs,
+ next;
+
+ this.pairs = null;
+
+ while(pair){
+ if(pair.leafA === this){
+ next = pair.nextA;
+ unlinkThread(pair.prevB, pair.leafB, pair.nextB);
+ } else {
+ next = pair.nextB;
+ unlinkThread(pair.prevA, pair.leafA, pair.nextA);
+ }
+ pair.recycle(tree);
+ pair = next;
+ }
+};
+
+var pairInsert = function(a, b, tree)
+{
+ var nextA = a.pairs, nextB = b.pairs;
+ var pair = tree.makePair(a, nextA, b, nextB);
+ a.pairs = b.pairs = pair;
+
+ if(nextA){
+ if(nextA.leafA === a) nextA.prevA = pair; else nextA.prevB = pair;
+ }
+
+ if(nextB){
+ if(nextB.leafA === b) nextB.prevA = pair; else nextB.prevB = pair;
+ }
+};
+
+// **** Node Functions
+
+Node.prototype.recycle = function(tree)
+{
+ this.parent = tree.pooledNodes;
+ tree.pooledNodes = this;
+};
+
+Leaf.prototype.recycle = function(tree)
+{
+ // Its not worth the overhead to recycle leaves.
+};
+
+Node.prototype.setA = function(value)
+{
+ this.A = value;
+ value.parent = this;
+};
+
+Node.prototype.setB = function(value)
+{
+ this.B = value;
+ value.parent = this;
+};
+
+Leaf.prototype.isLeaf = true;
+Node.prototype.isLeaf = false;
+
+Node.prototype.otherChild = function(child)
+{
+ return (this.A == child ? this.B : this.A);
+};
+
+Node.prototype.replaceChild = function(child, value, tree)
+{
+ assertSoft(child == this.A || child == this.B, "Node is not a child of parent.");
+
+ if(this.A == child){
+ this.A.recycle(tree);
+ this.setA(value);
+ } else {
+ this.B.recycle(tree);
+ this.setB(value);
+ }
+
+ for(var node=this; node; node = node.parent){
+ //node.bb = bbMerge(node.A.bb, node.B.bb);
+ var a = node.A;
+ var b = node.B;
+ node.bb_l = min(a.bb_l, b.bb_l);
+ node.bb_b = min(a.bb_b, b.bb_b);
+ node.bb_r = max(a.bb_r, b.bb_r);
+ node.bb_t = max(a.bb_t, b.bb_t);
+ }
+};
+
+Node.prototype.bbArea = Leaf.prototype.bbArea = function()
+{
+ return (this.bb_r - this.bb_l)*(this.bb_t - this.bb_b);
+};
+
+var bbTreeMergedArea = function(a, b)
+{
+ return (max(a.bb_r, b.bb_r) - min(a.bb_l, b.bb_l))*(max(a.bb_t, b.bb_t) - min(a.bb_b, b.bb_b));
+};
+
+// **** Subtree Functions
+
+// Would it be better to make these functions instance methods on Node and Leaf?
+
+var bbProximity = function(a, b)
+{
+ return Math.abs(a.bb_l + a.bb_r - b.bb_l - b.bb_r) + Math.abs(a.bb_b + a.bb_t - b.bb_b - b.bb_t);
+};
+
+var subtreeInsert = function(subtree, leaf, tree)
+{
+// var s = new Error().stack;
+// traces[s] = traces[s] ? traces[s]+1 : 1;
+
+ if(subtree == null){
+ return leaf;
+ } else if(subtree.isLeaf){
+ return tree.makeNode(leaf, subtree);
+ } else {
+ var cost_a = subtree.B.bbArea() + bbTreeMergedArea(subtree.A, leaf);
+ var cost_b = subtree.A.bbArea() + bbTreeMergedArea(subtree.B, leaf);
+
+ if(cost_a === cost_b){
+ cost_a = bbProximity(subtree.A, leaf);
+ cost_b = bbProximity(subtree.B, leaf);
+ }
+
+ if(cost_b < cost_a){
+ subtree.setB(subtreeInsert(subtree.B, leaf, tree));
+ } else {
+ subtree.setA(subtreeInsert(subtree.A, leaf, tree));
+ }
+
+// subtree.bb = bbMerge(subtree.bb, leaf.bb);
+ subtree.bb_l = min(subtree.bb_l, leaf.bb_l);
+ subtree.bb_b = min(subtree.bb_b, leaf.bb_b);
+ subtree.bb_r = max(subtree.bb_r, leaf.bb_r);
+ subtree.bb_t = max(subtree.bb_t, leaf.bb_t);
+
+ return subtree;
+ }
+};
+
+Node.prototype.intersectsBB = Leaf.prototype.intersectsBB = function(bb)
+{
+ return (this.bb_l <= bb.r && bb.l <= this.bb_r && this.bb_b <= bb.t && bb.b <= this.bb_t);
+};
+
+var subtreeQuery = function(subtree, bb, func)
+{
+ //if(bbIntersectsBB(subtree.bb, bb)){
+ if(subtree.intersectsBB(bb)){
+ if(subtree.isLeaf){
+ func(subtree.obj);
+ } else {
+ subtreeQuery(subtree.A, bb, func);
+ subtreeQuery(subtree.B, bb, func);
+ }
+ }
+};
+
+/// Returns the fraction along the segment query the node hits. Returns Infinity if it doesn't hit.
+var nodeSegmentQuery = function(node, a, b)
+{
+ var idx = 1/(b.x - a.x);
+ var tx1 = (node.bb_l == a.x ? -Infinity : (node.bb_l - a.x)*idx);
+ var tx2 = (node.bb_r == a.x ? Infinity : (node.bb_r - a.x)*idx);
+ var txmin = min(tx1, tx2);
+ var txmax = max(tx1, tx2);
+
+ var idy = 1/(b.y - a.y);
+ var ty1 = (node.bb_b == a.y ? -Infinity : (node.bb_b - a.y)*idy);
+ var ty2 = (node.bb_t == a.y ? Infinity : (node.bb_t - a.y)*idy);
+ var tymin = min(ty1, ty2);
+ var tymax = max(ty1, ty2);
+
+ if(tymin <= txmax && txmin <= tymax){
+ var min_ = max(txmin, tymin);
+ var max_ = min(txmax, tymax);
+
+ if(0.0 <= max_ && min_ <= 1.0) return max(min_, 0.0);
+ }
+
+ return Infinity;
+};
+
+var subtreeSegmentQuery = function(subtree, a, b, t_exit, func)
+{
+ if(subtree.isLeaf){
+ return func(subtree.obj);
+ } else {
+ var t_a = nodeSegmentQuery(subtree.A, a, b);
+ var t_b = nodeSegmentQuery(subtree.B, a, b);
+
+ if(t_a < t_b){
+ if(t_a < t_exit) t_exit = min(t_exit, subtreeSegmentQuery(subtree.A, a, b, t_exit, func));
+ if(t_b < t_exit) t_exit = min(t_exit, subtreeSegmentQuery(subtree.B, a, b, t_exit, func));
+ } else {
+ if(t_b < t_exit) t_exit = min(t_exit, subtreeSegmentQuery(subtree.B, a, b, t_exit, func));
+ if(t_a < t_exit) t_exit = min(t_exit, subtreeSegmentQuery(subtree.A, a, b, t_exit, func));
+ }
+
+ return t_exit;
+ }
+};
+
+BBTree.prototype.subtreeRecycle = function(node)
+{
+ if(node.isLeaf){
+ this.subtreeRecycle(node.A);
+ this.subtreeRecycle(node.B);
+ node.recycle(this);
+ }
+};
+
+var subtreeRemove = function(subtree, leaf, tree)
+{
+ if(leaf == subtree){
+ return null;
+ } else {
+ var parent = leaf.parent;
+ if(parent == subtree){
+ var other = subtree.otherChild(leaf);
+ other.parent = subtree.parent;
+ subtree.recycle(tree);
+ return other;
+ } else {
+ parent.parent.replaceChild(parent, parent.otherChild(leaf), tree);
+ return subtree;
+ }
+ }
+};
+
+// **** Marking Functions
+
+/*
+typedef struct MarkContext {
+ bbTree *tree;
+ Node *staticRoot;
+ cpSpatialIndexQueryFunc func;
+} MarkContext;
+*/
+
+var bbTreeIntersectsNode = function(a, b)
+{
+ return (a.bb_l <= b.bb_r && b.bb_l <= a.bb_r && a.bb_b <= b.bb_t && b.bb_b <= a.bb_t);
+};
+
+Leaf.prototype.markLeafQuery = function(leaf, left, tree, func)
+{
+ if(bbTreeIntersectsNode(leaf, this)){
+ if(left){
+ pairInsert(leaf, this, tree);
+ } else {
+ if(this.stamp < leaf.stamp) pairInsert(this, leaf, tree);
+ if(func) func(leaf.obj, this.obj);
+ }
+ }
+};
+
+Node.prototype.markLeafQuery = function(leaf, left, tree, func)
+{
+ if(bbTreeIntersectsNode(leaf, this)){
+ this.A.markLeafQuery(leaf, left, tree, func);
+ this.B.markLeafQuery(leaf, left, tree, func);
+ }
+};
+
+Leaf.prototype.markSubtree = function(tree, staticRoot, func)
+{
+ if(this.stamp == tree.getStamp()){
+ if(staticRoot) staticRoot.markLeafQuery(this, false, tree, func);
+
+ for(var node = this; node.parent; node = node.parent){
+ if(node == node.parent.A){
+ node.parent.B.markLeafQuery(this, true, tree, func);
+ } else {
+ node.parent.A.markLeafQuery(this, false, tree, func);
+ }
+ }
+ } else {
+ var pair = this.pairs;
+ while(pair){
+ if(this === pair.leafB){
+ if(func) func(pair.leafA.obj, this.obj);
+ pair = pair.nextB;
+ } else {
+ pair = pair.nextA;
+ }
+ }
+ }
+};
+
+Node.prototype.markSubtree = function(tree, staticRoot, func)
+{
+ this.A.markSubtree(tree, staticRoot, func);
+ this.B.markSubtree(tree, staticRoot, func);
+};
+
+// **** Leaf Functions
+
+Leaf.prototype.containsObj = function(obj)
+{
+ return (this.bb_l <= obj.bb_l && this.bb_r >= obj.bb_r && this.bb_b <= obj.bb_b && this.bb_t >= obj.bb_t);
+};
+
+Leaf.prototype.update = function(tree)
+{
+ var root = tree.root;
+ var obj = this.obj;
+
+ //if(!bbContainsBB(this.bb, bb)){
+ if(!this.containsObj(obj)){
+ tree.getBB(this.obj, this);
+
+ root = subtreeRemove(root, this, tree);
+ tree.root = subtreeInsert(root, this, tree);
+
+ this.clearPairs(tree);
+ this.stamp = tree.getStamp();
+
+ return true;
+ }
+
+ return false;
+};
+
+Leaf.prototype.addPairs = function(tree)
+{
+ var dynamicIndex = tree.dynamicIndex;
+ if(dynamicIndex){
+ var dynamicRoot = dynamicIndex.root;
+ if(dynamicRoot){
+ dynamicRoot.markLeafQuery(this, true, dynamicIndex, null);
+ }
+ } else {
+ var staticRoot = tree.staticIndex.root;
+ this.markSubtree(tree, staticRoot, null);
+ }
+};
+
+// **** Insert/Remove
+
+BBTree.prototype.insert = function(obj, hashid)
+{
+ var leaf = new Leaf(this, obj);
+
+ this.leaves[hashid] = leaf;
+ this.root = subtreeInsert(this.root, leaf, this);
+ this.count++;
+
+ leaf.stamp = this.getStamp();
+ leaf.addPairs(this);
+ this.incrementStamp();
+};
+
+BBTree.prototype.remove = function(obj, hashid)
+{
+ var leaf = this.leaves[hashid];
+
+ delete this.leaves[hashid];
+ this.root = subtreeRemove(this.root, leaf, this);
+ this.count--;
+
+ leaf.clearPairs(this);
+ leaf.recycle(this);
+};
+
+BBTree.prototype.contains = function(obj, hashid)
+{
+ return this.leaves[hashid] != null;
+};
+
+// **** Reindex
+var voidQueryFunc = function(obj1, obj2){};
+
+BBTree.prototype.reindexQuery = function(func)
+{
+ if(!this.root) return;
+
+ // LeafUpdate() may modify this.root. Don't cache it.
+ var hashid,
+ leaves = this.leaves;
+ for (hashid in leaves)
+ {
+ leaves[hashid].update(this);
+ }
+
+ var staticIndex = this.staticIndex;
+ var staticRoot = staticIndex && staticIndex.root;
+
+ this.root.markSubtree(this, staticRoot, func);
+ if(staticIndex && !staticRoot) this.collideStatic(this, staticIndex, func);
+
+ this.incrementStamp();
+};
+
+BBTree.prototype.reindex = function()
+{
+ this.reindexQuery(voidQueryFunc);
+};
+
+BBTree.prototype.reindexObject = function(obj, hashid)
+{
+ var leaf = this.leaves[hashid];
+ if(leaf){
+ if(leaf.update(this)) leaf.addPairs(this);
+ this.incrementStamp();
+ }
+};
+
+// **** Query
+
+// This has since been removed from upstream Chipmunk - which recommends you just use query() below
+// directly.
+BBTree.prototype.pointQuery = function(point, func)
+{
+ this.query(new BB(point.x, point.y, point.x, point.y), func);
+};
+
+BBTree.prototype.segmentQuery = function(a, b, t_exit, func)
+{
+ if(this.root) subtreeSegmentQuery(this.root, a, b, t_exit, func);
+};
+
+BBTree.prototype.query = function(bb, func)
+{
+ if(this.root) subtreeQuery(this.root, bb, func);
+};
+
+// **** Misc
+
+BBTree.prototype.count = function()
+{
+ return this.count;
+};
+
+BBTree.prototype.each = function(func)
+{
+ var hashid;
+ for(hashid in this.leaves)
+ {
+ func(this.leaves[hashid].obj);
+ }
+};
+
+// **** Tree Optimization
+
+var bbTreeMergedArea2 = function(node, l, b, r, t)
+{
+ return (max(node.bb_r, r) - min(node.bb_l, l))*(max(node.bb_t, t) - min(node.bb_b, b));
+};
+
+var partitionNodes = function(tree, nodes, offset, count)
+{
+ if(count == 1){
+ return nodes[offset];
+ } else if(count == 2) {
+ return tree.makeNode(nodes[offset], nodes[offset + 1]);
+ }
+
+ // Find the AABB for these nodes
+ //var bb = nodes[offset].bb;
+ var node = nodes[offset];
+ var bb_l = node.bb_l,
+ bb_b = node.bb_b,
+ bb_r = node.bb_r,
+ bb_t = node.bb_t;
+
+ var end = offset + count;
+ for(var i=offset + 1; i bb_t - bb_b);
+
+ // Sort the bounds and use the median as the splitting point
+ var bounds = new Array(count*2);
+ if(splitWidth){
+ for(var i=offset; inext = next;
+ if(prev.body_a === body) {
+ prev.thread_a_next = next;
+ } else {
+ prev.thread_b_next = next;
+ }
+ } else {
+ body.arbiterList = next;
+ }
+
+ if(next){
+ // cpArbiterThreadForBody(next, body)->prev = prev;
+ if(next.body_a === body){
+ next.thread_a_prev = prev;
+ } else {
+ next.thread_b_prev = prev;
+ }
+ }
+};
+
+Arbiter.prototype.unthread = function()
+{
+ unthreadHelper(this, this.body_a, this.thread_a_prev, this.thread_a_next);
+ unthreadHelper(this, this.body_b, this.thread_b_prev, this.thread_b_next);
+ this.thread_a_prev = this.thread_a_next = null;
+ this.thread_b_prev = this.thread_b_next = null;
+};
+
+//cpFloat
+//cpContactsEstimateCrushingImpulse(cpContact *contacts, int numContacts)
+//{
+// cpFloat fsum = 0;
+// cpVect vsum = vzero;
+//
+// for(int i=0; i= mindist*mindist) return;
+
+ var dist = Math.sqrt(distsq);
+
+ // Allocate and initialize the contact.
+ return new Contact(
+ vadd(p1, vmult(delta, 0.5 + (r1 - 0.5*mindist)/(dist ? dist : Infinity))),
+ (dist ? vmult(delta, 1/dist) : new Vect(1, 0)),
+ dist - mindist,
+ 0
+ );
+};
+
+// Collide circle shapes.
+var circle2circle = function(circ1, circ2)
+{
+ var contact = circle2circleQuery(circ1.tc, circ2.tc, circ1.r, circ2.r);
+ return contact ? [contact] : NONE;
+};
+
+var circle2segment = function(circleShape, segmentShape)
+{
+ var seg_a = segmentShape.ta;
+ var seg_b = segmentShape.tb;
+ var center = circleShape.tc;
+
+ var seg_delta = vsub(seg_b, seg_a);
+ var closest_t = clamp01(vdot(seg_delta, vsub(center, seg_a))/vlengthsq(seg_delta));
+ var closest = vadd(seg_a, vmult(seg_delta, closest_t));
+
+ var contact = circle2circleQuery(center, closest, circleShape.r, segmentShape.r);
+ if(contact){
+ var n = contact.n;
+
+ // Reject endcap collisions if tangents are provided.
+ return (
+ (closest_t === 0 && vdot(n, segmentShape.a_tangent) < 0) ||
+ (closest_t === 1 && vdot(n, segmentShape.b_tangent) < 0)
+ ) ? NONE : [contact];
+ } else {
+ return NONE;
+ }
+}
+
+// Find the minimum separating axis for the given poly and axis list.
+//
+// This function needs to return two values - the index of the min. separating axis and
+// the value itself. Short of inlining MSA, returning values through a global like this
+// is the fastest implementation.
+//
+// See: http://jsperf.com/return-two-values-from-function/2
+var last_MSA_min = 0;
+var findMSA = function(poly, planes)
+{
+ var min_index = 0;
+ var min = poly.valueOnAxis(planes[0].n, planes[0].d);
+ if(min > 0) return -1;
+
+ for(var i=1; i 0) {
+ return -1;
+ } else if(dist > min){
+ min = dist;
+ min_index = i;
+ }
+ }
+
+ last_MSA_min = min;
+ return min_index;
+};
+
+// Add contacts for probably penetrating vertexes.
+// This handles the degenerate case where an overlap was detected, but no vertexes fall inside
+// the opposing polygon. (like a star of david)
+var findVertsFallback = function(poly1, poly2, n, dist)
+{
+ var arr = [];
+
+ var verts1 = poly1.tVerts;
+ for(var i=0; i>1)));
+ }
+ }
+
+ var verts2 = poly2.tVerts;
+ for(var i=0; i>1)));
+ }
+ }
+
+ return (arr.length ? arr : findVertsFallback(poly1, poly2, n, dist));
+};
+
+// Collide poly shapes together.
+var poly2poly = function(poly1, poly2)
+{
+ var mini1 = findMSA(poly2, poly1.tPlanes);
+ if(mini1 == -1) return NONE;
+ var min1 = last_MSA_min;
+
+ var mini2 = findMSA(poly1, poly2.tPlanes);
+ if(mini2 == -1) return NONE;
+ var min2 = last_MSA_min;
+
+ // There is overlap, find the penetrating verts
+ if(min1 > min2)
+ return findVerts(poly1, poly2, poly1.tPlanes[mini1].n, min1);
+ else
+ return findVerts(poly1, poly2, vneg(poly2.tPlanes[mini2].n), min2);
+};
+
+// Like cpPolyValueOnAxis(), but for segments.
+var segValueOnAxis = function(seg, n, d)
+{
+ var a = vdot(n, seg.ta) - seg.r;
+ var b = vdot(n, seg.tb) - seg.r;
+ return min(a, b) - d;
+};
+
+// Identify vertexes that have penetrated the segment.
+var findPointsBehindSeg = function(arr, seg, poly, pDist, coef)
+{
+ var dta = vcross(seg.tn, seg.ta);
+ var dtb = vcross(seg.tn, seg.tb);
+ var n = vmult(seg.tn, coef);
+
+ var verts = poly.tVerts;
+ for(var i=0; i= dt && dt >= dtb){
+ arr.push(new Contact(new Vect(vx, vy), n, pDist, hashPair(poly.hashid, i)));
+ }
+ }
+ }
+};
+
+// This one is complicated and gross. Just don't go there...
+// TODO: Comment me!
+var seg2poly = function(seg, poly)
+{
+ var arr = [];
+
+ var planes = poly.tPlanes;
+ var numVerts = planes.length;
+
+ var segD = vdot(seg.tn, seg.ta);
+ var minNorm = poly.valueOnAxis(seg.tn, segD) - seg.r;
+ var minNeg = poly.valueOnAxis(vneg(seg.tn), -segD) - seg.r;
+ if(minNeg > 0 || minNorm > 0) return NONE;
+
+ var mini = 0;
+ var poly_min = segValueOnAxis(seg, planes[0].n, planes[0].d);
+ if(poly_min > 0) return NONE;
+ for(var i=0; i 0){
+ return NONE;
+ } else if(dist > poly_min){
+ poly_min = dist;
+ mini = i;
+ }
+ }
+
+ var poly_n = vneg(planes[mini].n);
+
+ var va = vadd(seg.ta, vmult(poly_n, seg.r));
+ var vb = vadd(seg.tb, vmult(poly_n, seg.r));
+ if(poly.containsVert(va.x, va.y))
+ arr.push(new Contact(va, poly_n, poly_min, hashPair(seg.hashid, 0)));
+ if(poly.containsVert(vb.x, vb.y))
+ arr.push(new Contact(vb, poly_n, poly_min, hashPair(seg.hashid, 1)));
+
+ // Floating point precision problems here.
+ // This will have to do for now.
+// poly_min -= cp_collision_slop; // TODO is this needed anymore?
+
+ if(minNorm >= poly_min || minNeg >= poly_min) {
+ if(minNorm > minNeg)
+ findPointsBehindSeg(arr, seg, poly, minNorm, 1);
+ else
+ findPointsBehindSeg(arr, seg, poly, minNeg, -1);
+ }
+
+ // If no other collision points are found, try colliding endpoints.
+ if(arr.length === 0){
+ var mini2 = mini * 2;
+ var verts = poly.tVerts;
+
+ var poly_a = new Vect(verts[mini2], verts[mini2+1]);
+
+ var con;
+ if((con = circle2circleQuery(seg.ta, poly_a, seg.r, 0, arr))) return [con];
+ if((con = circle2circleQuery(seg.tb, poly_a, seg.r, 0, arr))) return [con];
+
+ var len = numVerts * 2;
+ var poly_b = new Vect(verts[(mini2+2)%len], verts[(mini2+3)%len]);
+ if((con = circle2circleQuery(seg.ta, poly_b, seg.r, 0, arr))) return [con];
+ if((con = circle2circleQuery(seg.tb, poly_b, seg.r, 0, arr))) return [con];
+ }
+
+// console.log(poly.tVerts, poly.tPlanes);
+// console.log('seg2poly', arr);
+ return arr;
+};
+
+// This one is less gross, but still gross.
+// TODO: Comment me!
+var circle2poly = function(circ, poly)
+{
+ var planes = poly.tPlanes;
+
+ var mini = 0;
+ var min = vdot(planes[0].n, circ.tc) - planes[0].d - circ.r;
+ for(var i=0; i 0){
+ return NONE;
+ } else if(dist > min) {
+ min = dist;
+ mini = i;
+ }
+ }
+
+ var n = planes[mini].n;
+
+ var verts = poly.tVerts;
+ var len = verts.length;
+ var mini2 = mini<<1;
+
+ //var a = poly.tVerts[mini];
+ //var b = poly.tVerts[(mini + 1)%poly.tVerts.length];
+ var ax = verts[mini2];
+ var ay = verts[mini2+1];
+ var bx = verts[(mini2+2)%len];
+ var by = verts[(mini2+3)%len];
+
+ var dta = vcross2(n.x, n.y, ax, ay);
+ var dtb = vcross2(n.x, n.y, bx, by);
+ var dt = vcross(n, circ.tc);
+
+ if(dt < dtb){
+ var con = circle2circleQuery(circ.tc, new Vect(bx, by), circ.r, 0, con);
+ return con ? [con] : NONE;
+ } else if(dt < dta) {
+ return [new Contact(
+ vsub(circ.tc, vmult(n, circ.r + min/2)),
+ vneg(n),
+ min,
+ 0
+ )];
+ } else {
+ var con = circle2circleQuery(circ.tc, new Vect(ax, ay), circ.r, 0, con);
+ return con ? [con] : NONE;
+ }
+};
+
+// The javascripty way to do this would be either nested object or methods on the prototypes.
+//
+// However, the *fastest* way is the method below.
+// See: http://jsperf.com/dispatch
+
+// These are copied from the prototypes into the actual objects in the Shape constructor.
+CircleShape.prototype.collisionCode = 0;
+SegmentShape.prototype.collisionCode = 1;
+PolyShape.prototype.collisionCode = 2;
+
+CircleShape.prototype.collisionTable = [
+ circle2circle,
+ circle2segment,
+ circle2poly
+];
+
+SegmentShape.prototype.collisionTable = [
+ null,
+ function(segA, segB) { return NONE; }, // seg2seg
+ seg2poly
+];
+
+PolyShape.prototype.collisionTable = [
+ null,
+ null,
+ poly2poly
+];
+
+var collideShapes = cp.collideShapes = function(a, b)
+{
+ assert(a.collisionCode <= b.collisionCode, 'Collided shapes must be sorted by type');
+ return a.collisionTable[b.collisionCode](a, b);
+};
+
+/* Copyright (c) 2007 Scott Lembcke
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+var defaultCollisionHandler = new CollisionHandler();
+
+/// Basic Unit of Simulation in Chipmunk
+var Space = cp.Space = function() {
+ this.stamp = 0;
+ this.curr_dt = 0;
+
+ this.bodies = [];
+ this.rousedBodies = [];
+ this.sleepingComponents = [];
+
+ this.staticShapes = new BBTree(null);
+ this.activeShapes = new BBTree(this.staticShapes);
+
+ this.arbiters = [];
+ this.contactBuffersHead = null;
+ this.cachedArbiters = {};
+ //this.pooledArbiters = [];
+
+ this.constraints = [];
+
+ this.locked = 0;
+
+ this.collisionHandlers = {};
+ this.defaultHandler = defaultCollisionHandler;
+
+ this.postStepCallbacks = [];
+
+ /// Number of iterations to use in the impulse solver to solve contacts.
+ this.iterations = 10;
+
+ /// Gravity to pass to rigid bodies when integrating velocity.
+ this.gravity = vzero;
+
+ /// Damping rate expressed as the fraction of velocity bodies retain each second.
+ /// A value of 0.9 would mean that each body's velocity will drop 10% per second.
+ /// The default value is 1.0, meaning no damping is applied.
+ /// @note This damping value is different than those of cpDampedSpring and cpDampedRotarySpring.
+ this.damping = 1;
+
+ /// Speed threshold for a body to be considered idle.
+ /// The default value of 0 means to let the space guess a good threshold based on gravity.
+ this.idleSpeedThreshold = 0;
+
+ /// Time a group of bodies must remain idle in order to fall asleep.
+ /// Enabling sleeping also implicitly enables the the contact graph.
+ /// The default value of Infinity disables the sleeping algorithm.
+ this.sleepTimeThreshold = Infinity;
+
+ /// Amount of encouraged penetration between colliding shapes..
+ /// Used to reduce oscillating contacts and keep the collision cache warm.
+ /// Defaults to 0.1. If you have poor simulation quality,
+ /// increase this number as much as possible without allowing visible amounts of overlap.
+ this.collisionSlop = 0.1;
+
+ /// Determines how fast overlapping shapes are pushed apart.
+ /// Expressed as a fraction of the error remaining after each second.
+ /// Defaults to pow(1.0 - 0.1, 60.0) meaning that Chipmunk fixes 10% of overlap each frame at 60Hz.
+ this.collisionBias = Math.pow(1 - 0.1, 60);
+
+ /// Number of frames that contact information should persist.
+ /// Defaults to 3. There is probably never a reason to change this value.
+ this.collisionPersistence = 3;
+
+ /// Rebuild the contact graph during each step. Must be enabled to use the cpBodyEachArbiter() function.
+ /// Disabled by default for a small performance boost. Enabled implicitly when the sleeping feature is enabled.
+ this.enableContactGraph = false;
+
+ /// The designated static body for this space.
+ /// You can modify this body, or replace it with your own static body.
+ /// By default it points to a statically allocated cpBody in the cpSpace struct.
+ this.staticBody = new Body(Infinity, Infinity);
+ this.staticBody.nodeIdleTime = Infinity;
+
+ // Cache the collideShapes callback function for the space.
+ this.collideShapes = this.makeCollideShapes();
+};
+
+Space.prototype.getCurrentTimeStep = function() { return this.curr_dt; };
+
+Space.prototype.setIterations = function(iter) { this.iterations = iter; };
+
+/// returns true from inside a callback and objects cannot be added/removed.
+Space.prototype.isLocked = function()
+{
+ return this.locked;
+};
+
+var assertSpaceUnlocked = function(space)
+{
+ assert(!space.locked, "This addition/removal cannot be done safely during a call to cpSpaceStep() \
+ or during a query. Put these calls into a post-step callback.");
+};
+
+// **** Collision handler function management
+
+/// Set a collision handler to be used whenever the two shapes with the given collision types collide.
+/// You can pass null for any function you don't want to implement.
+Space.prototype.addCollisionHandler = function(a, b, begin, preSolve, postSolve, separate)
+{
+ assertSpaceUnlocked(this);
+
+ // Remove any old function so the new one will get added.
+ this.removeCollisionHandler(a, b);
+
+ var handler = new CollisionHandler();
+ handler.a = a;
+ handler.b = b;
+ if(begin) handler.begin = begin;
+ if(preSolve) handler.preSolve = preSolve;
+ if(postSolve) handler.postSolve = postSolve;
+ if(separate) handler.separate = separate;
+
+ this.collisionHandlers[hashPair(a, b)] = handler;
+};
+
+/// Unset a collision handler.
+Space.prototype.removeCollisionHandler = function(a, b)
+{
+ assertSpaceUnlocked(this);
+
+ delete this.collisionHandlers[hashPair(a, b)];
+};
+
+/// Set a default collision handler for this space.
+/// The default collision handler is invoked for each colliding pair of shapes
+/// that isn't explicitly handled by a specific collision handler.
+/// You can pass null for any function you don't want to implement.
+Space.prototype.setDefaultCollisionHandler = function(begin, preSolve, postSolve, separate)
+{
+ assertSpaceUnlocked(this);
+
+ var handler = new CollisionHandler();
+ if(begin) handler.begin = begin;
+ if(preSolve) handler.preSolve = preSolve;
+ if(postSolve) handler.postSolve = postSolve;
+ if(separate) handler.separate = separate;
+
+ this.defaultHandler = handler;
+};
+
+Space.prototype.lookupHandler = function(a, b)
+{
+ return this.collisionHandlers[hashPair(a, b)] || this.defaultHandler;
+};
+
+// **** Body, Shape, and Joint Management
+
+/// Add a collision shape to the simulation.
+/// If the shape is attached to a static body, it will be added as a static shape.
+Space.prototype.addShape = function(shape)
+{
+ var body = shape.body;
+ if(body.isStatic()) return this.addStaticShape(shape);
+
+ assert(!shape.space, "This shape is already added to a space and cannot be added to another.");
+ assertSpaceUnlocked(this);
+
+ body.activate();
+ body.addShape(shape);
+
+ shape.update(body.p, body.rot);
+ this.activeShapes.insert(shape, shape.hashid);
+ shape.space = this;
+
+ return shape;
+};
+
+/// Explicity add a shape as a static shape to the simulation.
+Space.prototype.addStaticShape = function(shape)
+{
+ assert(!shape.space, "This shape is already added to a space and cannot be added to another.");
+ assertSpaceUnlocked(this);
+
+ var body = shape.body;
+ body.addShape(shape);
+
+ shape.update(body.p, body.rot);
+ this.staticShapes.insert(shape, shape.hashid);
+ shape.space = this;
+
+ return shape;
+};
+
+/// Add a rigid body to the simulation.
+Space.prototype.addBody = function(body)
+{
+ assert(!body.isStatic(), "Static bodies cannot be added to a space as they are not meant to be simulated.");
+ assert(!body.space, "This body is already added to a space and cannot be added to another.");
+ assertSpaceUnlocked(this);
+
+ this.bodies.push(body);
+ body.space = this;
+
+ return body;
+};
+
+/// Add a constraint to the simulation.
+Space.prototype.addConstraint = function(constraint)
+{
+ assert(!constraint.space, "This shape is already added to a space and cannot be added to another.");
+ assertSpaceUnlocked(this);
+
+ var a = constraint.a, b = constraint.b;
+
+ a.activate();
+ b.activate();
+ this.constraints.push(constraint);
+
+ // Push onto the heads of the bodies' constraint lists
+ constraint.next_a = a.constraintList; a.constraintList = constraint;
+ constraint.next_b = b.constraintList; b.constraintList = constraint;
+ constraint.space = this;
+
+ return constraint;
+};
+
+Space.prototype.filterArbiters = function(body, filter)
+{
+ for (var hash in this.cachedArbiters)
+ {
+ var arb = this.cachedArbiters[hash];
+
+ // Match on the filter shape, or if it's null the filter body
+ if(
+ (body === arb.body_a && (filter === arb.a || filter === null)) ||
+ (body === arb.body_b && (filter === arb.b || filter === null))
+ ){
+ // Call separate when removing shapes.
+ if(filter && arb.state !== 'cached') arb.callSeparate(this);
+
+ arb.unthread();
+
+ deleteObjFromList(this.arbiters, arb);
+ //this.pooledArbiters.push(arb);
+
+ delete this.cachedArbiters[hash];
+ }
+ }
+};
+
+/// Remove a collision shape from the simulation.
+Space.prototype.removeShape = function(shape)
+{
+ var body = shape.body;
+ if(body.isStatic()){
+ this.removeStaticShape(shape);
+ } else {
+ assert(this.containsShape(shape),
+ "Cannot remove a shape that was not added to the space. (Removed twice maybe?)");
+ assertSpaceUnlocked(this);
+
+ body.activate();
+ body.removeShape(shape);
+ this.filterArbiters(body, shape);
+ this.activeShapes.remove(shape, shape.hashid);
+ shape.space = null;
+ }
+};
+
+/// Remove a collision shape added using addStaticShape() from the simulation.
+Space.prototype.removeStaticShape = function(shape)
+{
+ assert(this.containsShape(shape),
+ "Cannot remove a static or sleeping shape that was not added to the space. (Removed twice maybe?)");
+ assertSpaceUnlocked(this);
+
+ var body = shape.body;
+ if(body.isStatic()) body.activateStatic(shape);
+ body.removeShape(shape);
+ this.filterArbiters(body, shape);
+ this.staticShapes.remove(shape, shape.hashid);
+ shape.space = null;
+};
+
+/// Remove a rigid body from the simulation.
+Space.prototype.removeBody = function(body)
+{
+ assert(this.containsBody(body),
+ "Cannot remove a body that was not added to the space. (Removed twice maybe?)");
+ assertSpaceUnlocked(this);
+
+ body.activate();
+// this.filterArbiters(body, null);
+ deleteObjFromList(this.bodies, body);
+ body.space = null;
+};
+
+/// Remove a constraint from the simulation.
+Space.prototype.removeConstraint = function(constraint)
+{
+ assert(this.containsConstraint(constraint),
+ "Cannot remove a constraint that was not added to the space. (Removed twice maybe?)");
+ assertSpaceUnlocked(this);
+
+ constraint.a.activate();
+ constraint.b.activate();
+ deleteObjFromList(this.constraints, constraint);
+
+ constraint.a.removeConstraint(constraint);
+ constraint.b.removeConstraint(constraint);
+ constraint.space = null;
+};
+
+/// Test if a collision shape has been added to the space.
+Space.prototype.containsShape = function(shape)
+{
+ return (shape.space === this);
+};
+
+/// Test if a rigid body has been added to the space.
+Space.prototype.containsBody = function(body)
+{
+ return (body.space == this);
+};
+
+/// Test if a constraint has been added to the space.
+Space.prototype.containsConstraint = function(constraint)
+{
+ return (constraint.space == this);
+};
+
+Space.prototype.uncacheArbiter = function(arb)
+{
+ delete this.cachedArbiters[hashPair(arb.a.hashid, arb.b.hashid)];
+ deleteObjFromList(this.arbiters, arb);
+};
+
+
+// **** Iteration
+
+/// Call @c func for each body in the space.
+Space.prototype.eachBody = function(func)
+{
+ this.lock(); {
+ var bodies = this.bodies;
+
+ for(var i=0; i keThreshold ? 0 : body.nodeIdleTime + dt);
+ }
+ }
+
+ // Awaken any sleeping bodies found and then push arbiters to the bodies' lists.
+ var arbiters = this.arbiters;
+ for(var i=0, count=arbiters.length; i= 0, "Internal Error: Space lock underflow.");
+
+ if(this.locked === 0 && runPostStep){
+ var waking = this.rousedBodies;
+ for(var i=0; i this.collisionPersistence){
+ // The tail buffer is available, rotate the ring
+ var tail = head.next;
+ tail.stamp = stamp;
+ tail.contacts.length = 0;
+ this.contactBuffersHead = tail;
+ } else {
+ // Allocate a new buffer and push it into the ring
+ var buffer = new ContactBuffer(stamp, head);
+ this.contactBuffersHead = head.next = buffer;
+ }
+};
+
+cpContact *
+cpContactBufferGetArray(cpSpace *space)
+{
+ if(space.contactBuffersHead.numContacts + CP_MAX_CONTACTS_PER_ARBITER > CP_CONTACTS_BUFFER_SIZE){
+ // contact buffer could overflow on the next collision, push a fresh one.
+ space.pushFreshContactBuffer();
+ }
+
+ cpContactBufferHeader *head = space.contactBuffersHead;
+ return ((cpContactBuffer *)head)->contacts + head.numContacts;
+}
+
+void
+cpSpacePushContacts(cpSpace *space, int count)
+{
+ cpAssertHard(count <= CP_MAX_CONTACTS_PER_ARBITER, "Internal Error: Contact buffer overflow!");
+ space.contactBuffersHead.numContacts += count;
+}
+
+static void
+cpSpacePopContacts(cpSpace *space, int count){
+ space.contactBuffersHead.numContacts -= count;
+}
+*/
+
+// **** Collision Detection Functions
+
+/* Use this to re-enable object pools.
+static void *
+cpSpaceArbiterSetTrans(cpShape **shapes, cpSpace *space)
+{
+ if(space.pooledArbiters.num == 0){
+ // arbiter pool is exhausted, make more
+ int count = CP_BUFFER_BYTES/sizeof(cpArbiter);
+ cpAssertHard(count, "Internal Error: Buffer size too small.");
+
+ cpArbiter *buffer = (cpArbiter *)cpcalloc(1, CP_BUFFER_BYTES);
+ cpArrayPush(space.allocatedBuffers, buffer);
+
+ for(int i=0; i b.collisionCode){
+ var temp = a;
+ a = b;
+ b = temp;
+ }
+
+ // Narrow-phase collision detection.
+ //cpContact *contacts = cpContactBufferGetArray(space);
+ //int numContacts = cpCollideShapes(a, b, contacts);
+ var contacts = collideShapes(a, b);
+ if(contacts.length === 0) return; // Shapes are not colliding.
+ //cpSpacePushContacts(space, numContacts);
+
+ // Get an arbiter from space.arbiterSet for the two shapes.
+ // This is where the persistant contact magic comes from.
+ var arbHash = hashPair(a.hashid, b.hashid);
+ var arb = space.cachedArbiters[arbHash];
+ if (!arb){
+ arb = space.cachedArbiters[arbHash] = new Arbiter(a, b);
+ }
+
+ arb.update(contacts, handler, a, b);
+
+ // Call the begin function first if it's the first step
+ if(arb.state == 'first coll' && !handler.begin(arb, space)){
+ arb.ignore(); // permanently ignore the collision until separation
+ }
+
+ if(
+ // Ignore the arbiter if it has been flagged
+ (arb.state !== 'ignore') &&
+ // Call preSolve
+ handler.preSolve(arb, space) &&
+ // Process, but don't add collisions for sensors.
+ !sensor
+ ){
+ space.arbiters.push(arb);
+ } else {
+ //cpSpacePopContacts(space, numContacts);
+
+ arb.contacts = null;
+
+ // Normally arbiters are set as used after calling the post-solve callback.
+ // However, post-solve callbacks are not called for sensors or arbiters rejected from pre-solve.
+ if(arb.state !== 'ignore') arb.state = 'normal';
+ }
+
+ // Time stamp the arbiter so we know it was used recently.
+ arb.stamp = space.stamp;
+ };
+};
+
+// Hashset filter func to throw away old arbiters.
+Space.prototype.arbiterSetFilter = function(arb)
+{
+ var ticks = this.stamp - arb.stamp;
+
+ var a = arb.body_a, b = arb.body_b;
+
+ // TODO should make an arbiter state for this so it doesn't require filtering arbiters for
+ // dangling body pointers on body removal.
+ // Preserve arbiters on sensors and rejected arbiters for sleeping objects.
+ // This prevents errant separate callbacks from happenening.
+ if(
+ (a.isStatic() || a.isSleeping()) &&
+ (b.isStatic() || b.isSleeping())
+ ){
+ return true;
+ }
+
+ // Arbiter was used last frame, but not this one
+ if(ticks >= 1 && arb.state != 'cached'){
+ arb.callSeparate(this);
+ arb.state = 'cached';
+ }
+
+ if(ticks >= this.collisionPersistence){
+ arb.contacts = null;
+
+ //cpArrayPush(this.pooledArbiters, arb);
+ return false;
+ }
+
+ return true;
+};
+
+// **** All Important cpSpaceStep() Function
+
+var updateFunc = function(shape)
+{
+ var body = shape.body;
+ shape.update(body.p, body.rot);
+};
+
+/// Step the space forward in time by @c dt.
+Space.prototype.step = function(dt)
+{
+ // don't step if the timestep is 0!
+ if(dt === 0) return;
+
+ assert(vzero.x === 0 && vzero.y === 0, "vzero is invalid");
+
+ this.stamp++;
+
+ var prev_dt = this.curr_dt;
+ this.curr_dt = dt;
+
+ var i;
+ var j;
+ var hash;
+ var bodies = this.bodies;
+ var constraints = this.constraints;
+ var arbiters = this.arbiters;
+
+ // Reset and empty the arbiter lists.
+ for(i=0; imaxForce*(dt))
+
+// a and b are bodies.
+var relative_velocity = function(a, b, r1, r2){
+ //var v1_sum = vadd(a.v, vmult(vperp(r1), a.w));
+ var v1_sumx = a.vx + (-r1.y) * a.w;
+ var v1_sumy = a.vy + ( r1.x) * a.w;
+
+ //var v2_sum = vadd(b.v, vmult(vperp(r2), b.w));
+ var v2_sumx = b.vx + (-r2.y) * b.w;
+ var v2_sumy = b.vy + ( r2.x) * b.w;
+
+// return vsub(v2_sum, v1_sum);
+ return new Vect(v2_sumx - v1_sumx, v2_sumy - v1_sumy);
+};
+
+var normal_relative_velocity = function(a, b, r1, r2, n){
+ //return vdot(relative_velocity(a, b, r1, r2), n);
+ var v1_sumx = a.vx + (-r1.y) * a.w;
+ var v1_sumy = a.vy + ( r1.x) * a.w;
+ var v2_sumx = b.vx + (-r2.y) * b.w;
+ var v2_sumy = b.vy + ( r2.x) * b.w;
+
+ return vdot2(v2_sumx - v1_sumx, v2_sumy - v1_sumy, n.x, n.y);
+};
+
+/*
+var apply_impulse = function(body, j, r){
+ body.v = vadd(body.v, vmult(j, body.m_inv));
+ body.w += body.i_inv*vcross(r, j);
+};
+
+var apply_impulses = function(a, b, r1, r2, j)
+{
+ apply_impulse(a, vneg(j), r1);
+ apply_impulse(b, j, r2);
+};
+*/
+
+var apply_impulse = function(body, jx, jy, r){
+// body.v = body.v.add(vmult(j, body.m_inv));
+ body.vx += jx * body.m_inv;
+ body.vy += jy * body.m_inv;
+// body.w += body.i_inv*vcross(r, j);
+ body.w += body.i_inv*(r.x*jy - r.y*jx);
+};
+
+var apply_impulses = function(a, b, r1, r2, jx, jy)
+{
+ apply_impulse(a, -jx, -jy, r1);
+ apply_impulse(b, jx, jy, r2);
+};
+
+var apply_bias_impulse = function(body, jx, jy, r)
+{
+ //body.v_bias = vadd(body.v_bias, vmult(j, body.m_inv));
+ body.v_biasx += jx * body.m_inv;
+ body.v_biasy += jy * body.m_inv;
+ body.w_bias += body.i_inv*vcross2(r.x, r.y, jx, jy);
+};
+
+/*
+var apply_bias_impulses = function(a, b, r1, r2, j)
+{
+ apply_bias_impulse(a, vneg(j), r1);
+ apply_bias_impulse(b, j, r2);
+};*/
+
+var k_scalar_body = function(body, r, n)
+{
+ var rcn = vcross(r, n);
+ return body.m_inv + body.i_inv*rcn*rcn;
+};
+
+var k_scalar = function(a, b, r1, r2, n)
+{
+ var value = k_scalar_body(a, r1, n) + k_scalar_body(b, r2, n);
+ assertSoft(value !== 0, "Unsolvable collision or constraint.");
+
+ return value;
+};
+
+// k1 and k2 are modified by the function to contain the outputs.
+var k_tensor = function(a, b, r1, r2, k1, k2)
+{
+ // calculate mass matrix
+ // If I wasn't lazy and wrote a proper matrix class, this wouldn't be so gross...
+ var k11, k12, k21, k22;
+ var m_sum = a.m_inv + b.m_inv;
+
+ // start with I*m_sum
+ k11 = m_sum; k12 = 0;
+ k21 = 0; k22 = m_sum;
+
+ // add the influence from r1
+ var a_i_inv = a.i_inv;
+ var r1xsq = r1.x * r1.x * a_i_inv;
+ var r1ysq = r1.y * r1.y * a_i_inv;
+ var r1nxy = -r1.x * r1.y * a_i_inv;
+ k11 += r1ysq; k12 += r1nxy;
+ k21 += r1nxy; k22 += r1xsq;
+
+ // add the influnce from r2
+ var b_i_inv = b.i_inv;
+ var r2xsq = r2.x * r2.x * b_i_inv;
+ var r2ysq = r2.y * r2.y * b_i_inv;
+ var r2nxy = -r2.x * r2.y * b_i_inv;
+ k11 += r2ysq; k12 += r2nxy;
+ k21 += r2nxy; k22 += r2xsq;
+
+ // invert
+ var determinant = k11*k22 - k12*k21;
+ assertSoft(determinant !== 0, "Unsolvable constraint.");
+
+ var det_inv = 1/determinant;
+
+ k1.x = k22*det_inv; k1.y = -k12*det_inv;
+ k2.x = -k21*det_inv; k2.y = k11*det_inv;
+};
+
+var mult_k = function(vr, k1, k2)
+{
+ return new Vect(vdot(vr, k1), vdot(vr, k2));
+};
+
+var bias_coef = function(errorBias, dt)
+{
+ return 1 - Math.pow(errorBias, dt);
+};
+
+/* Copyright (c) 2007 Scott Lembcke
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+// TODO: Comment me!
+
+// a and b are bodies that the constraint applies to.
+var Constraint = cp.Constraint = function(a, b)
+{
+ /// The first body connected to this constraint.
+ this.a = a;
+ /// The second body connected to this constraint.
+ this.b = b;
+
+ this.space = null;
+
+ this.next_a = null;
+ this.next_b = null;
+
+ /// The maximum force that this constraint is allowed to use.
+ this.maxForce = Infinity;
+ /// The rate at which joint error is corrected.
+ /// Defaults to pow(1 - 0.1, 60) meaning that it will
+ /// correct 10% of the error every 1/60th of a second.
+ this.errorBias = Math.pow(1 - 0.1, 60);
+ /// The maximum rate at which joint error is corrected.
+ this.maxBias = Infinity;
+};
+
+Constraint.prototype.activateBodies = function()
+{
+ if(this.a) this.a.activate();
+ if(this.b) this.b.activate();
+};
+
+/// These methods are overridden by the constraint itself.
+Constraint.prototype.preStep = function(dt) {};
+Constraint.prototype.applyCachedImpulse = function(dt_coef) {};
+Constraint.prototype.applyImpulse = function() {};
+Constraint.prototype.getImpulse = function() { return 0; };
+
+/// Function called before the solver runs. This can be overridden by the user
+/// to customize the constraint.
+/// Animate your joint anchors, update your motor torque, etc.
+Constraint.prototype.preSolve = function(space) {};
+
+/// Function called after the solver runs. This can be overridden by the user
+/// to customize the constraint.
+/// Use the applied impulse to perform effects like breakable joints.
+Constraint.prototype.postSolve = function(space) {};
+
+Constraint.prototype.next = function(body)
+{
+ return (this.a === body ? this.next_a : this.next_b);
+};
+
+/* Copyright (c) 2007 Scott Lembcke
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+var PinJoint = cp.PinJoint = function(a, b, anchr1, anchr2)
+{
+ Constraint.call(this, a, b);
+
+ this.anchr1 = anchr1;
+ this.anchr2 = anchr2;
+
+ // STATIC_BODY_CHECK
+ var p1 = (a ? vadd(a.p, vrotate(anchr1, a.rot)) : anchr1);
+ var p2 = (b ? vadd(b.p, vrotate(anchr2, b.rot)) : anchr2);
+ this.dist = vlength(vsub(p2, p1));
+
+ assertSoft(this.dist > 0, "You created a 0 length pin joint. A pivot joint will be much more stable.");
+
+ this.r1 = this.r2 = null;
+ this.n = null;
+ this.nMass = 0;
+
+ this.jnAcc = this.jnMax = 0;
+ this.bias = 0;
+};
+
+PinJoint.prototype = Object.create(Constraint.prototype);
+
+PinJoint.prototype.preStep = function(dt)
+{
+ var a = this.a;
+ var b = this.b;
+
+ this.r1 = vrotate(this.anchr1, a.rot);
+ this.r2 = vrotate(this.anchr2, b.rot);
+
+ var delta = vsub(vadd(b.p, this.r2), vadd(a.p, this.r1));
+ var dist = vlength(delta);
+ this.n = vmult(delta, 1/(dist ? dist : Infinity));
+
+ // calculate mass normal
+ this.nMass = 1/k_scalar(a, b, this.r1, this.r2, this.n);
+
+ // calculate bias velocity
+ var maxBias = this.maxBias;
+ this.bias = clamp(-bias_coef(this.errorBias, dt)*(dist - this.dist)/dt, -maxBias, maxBias);
+
+ // compute max impulse
+ this.jnMax = this.maxForce * dt;
+};
+
+PinJoint.prototype.applyCachedImpulse = function(dt_coef)
+{
+ var j = vmult(this.n, this.jnAcc*dt_coef);
+ apply_impulses(this.a, this.b, this.r1, this.r2, j.x, j.y);
+};
+
+PinJoint.prototype.applyImpulse = function()
+{
+ var a = this.a;
+ var b = this.b;
+ var n = this.n;
+
+ // compute relative velocity
+ var vrn = normal_relative_velocity(a, b, this.r1, this.r2, n);
+
+ // compute normal impulse
+ var jn = (this.bias - vrn)*this.nMass;
+ var jnOld = this.jnAcc;
+ this.jnAcc = clamp(jnOld + jn, -this.jnMax, this.jnMax);
+ jn = this.jnAcc - jnOld;
+
+ // apply impulse
+ apply_impulses(a, b, this.r1, this.r2, n.x*jn, n.y*jn);
+};
+
+PinJoint.prototype.getImpulse = function()
+{
+ return Math.abs(this.jnAcc);
+};
+
+/* Copyright (c) 2007 Scott Lembcke
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+var SlideJoint = cp.SlideJoint = function(a, b, anchr1, anchr2, min, max)
+{
+ Constraint.call(this, a, b);
+
+ this.anchr1 = anchr1;
+ this.anchr2 = anchr2;
+ this.min = min;
+ this.max = max;
+
+ this.r1 = this.r2 = this.n = null;
+ this.nMass = 0;
+
+ this.jnAcc = this.jnMax = 0;
+ this.bias = 0;
+};
+
+SlideJoint.prototype = Object.create(Constraint.prototype);
+
+SlideJoint.prototype.preStep = function(dt)
+{
+ var a = this.a;
+ var b = this.b;
+
+ this.r1 = vrotate(this.anchr1, a.rot);
+ this.r2 = vrotate(this.anchr2, b.rot);
+
+ var delta = vsub(vadd(b.p, this.r2), vadd(a.p, this.r1));
+ var dist = vlength(delta);
+ var pdist = 0;
+ if(dist > this.max) {
+ pdist = dist - this.max;
+ this.n = vnormalize_safe(delta);
+ } else if(dist < this.min) {
+ pdist = this.min - dist;
+ this.n = vneg(vnormalize_safe(delta));
+ } else {
+ this.n = vzero;
+ this.jnAcc = 0;
+ }
+
+ // calculate mass normal
+ this.nMass = 1/k_scalar(a, b, this.r1, this.r2, this.n);
+
+ // calculate bias velocity
+ var maxBias = this.maxBias;
+ this.bias = clamp(-bias_coef(this.errorBias, dt)*pdist/dt, -maxBias, maxBias);
+
+ // compute max impulse
+ this.jnMax = this.maxForce * dt;
+};
+
+SlideJoint.prototype.applyCachedImpulse = function(dt_coef)
+{
+ var jn = this.jnAcc * dt_coef;
+ apply_impulses(this.a, this.b, this.r1, this.r2, this.n.x * jn, this.n.y * jn);
+};
+
+SlideJoint.prototype.applyImpulse = function()
+{
+ if(this.n.x === 0 && this.n.y === 0) return; // early exit
+
+ var a = this.a;
+ var b = this.b;
+
+ var n = this.n;
+ var r1 = this.r1;
+ var r2 = this.r2;
+
+ // compute relative velocity
+ var vr = relative_velocity(a, b, r1, r2);
+ var vrn = vdot(vr, n);
+
+ // compute normal impulse
+ var jn = (this.bias - vrn)*this.nMass;
+ var jnOld = this.jnAcc;
+ this.jnAcc = clamp(jnOld + jn, -this.jnMax, 0);
+ jn = this.jnAcc - jnOld;
+
+ // apply impulse
+ apply_impulses(a, b, this.r1, this.r2, n.x * jn, n.y * jn);
+};
+
+SlideJoint.prototype.getImpulse = function()
+{
+ return Math.abs(this.jnAcc);
+};
+
+/* Copyright (c) 2007 Scott Lembcke
+ *
+ * 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.
+ */
+
+// Pivot joints can also be created with (a, b, pivot);
+var PivotJoint = cp.PivotJoint = function(a, b, anchr1, anchr2)
+{
+ Constraint.call(this, a, b);
+
+ if(typeof anchr2 === 'undefined') {
+ var pivot = anchr1;
+
+ anchr1 = (a ? a.world2Local(pivot) : pivot);
+ anchr2 = (b ? b.world2Local(pivot) : pivot);
+ }
+
+ this.anchr1 = anchr1;
+ this.anchr2 = anchr2;
+
+ this.r1 = this.r2 = vzero;
+
+ this.k1 = new Vect(0,0); this.k2 = new Vect(0,0);
+
+ this.jAcc = vzero;
+
+ this.jMaxLen = 0;
+ this.bias = vzero;
+};
+
+PivotJoint.prototype = Object.create(Constraint.prototype);
+
+PivotJoint.prototype.preStep = function(dt)
+{
+ var a = this.a;
+ var b = this.b;
+
+ this.r1 = vrotate(this.anchr1, a.rot);
+ this.r2 = vrotate(this.anchr2, b.rot);
+
+ // Calculate mass tensor. Result is stored into this.k1 & this.k2.
+ k_tensor(a, b, this.r1, this.r2, this.k1, this.k2);
+
+ // compute max impulse
+ this.jMaxLen = this.maxForce * dt;
+
+ // calculate bias velocity
+ var delta = vsub(vadd(b.p, this.r2), vadd(a.p, this.r1));
+ this.bias = vclamp(vmult(delta, -bias_coef(this.errorBias, dt)/dt), this.maxBias);
+};
+
+PivotJoint.prototype.applyCachedImpulse = function(dt_coef)
+{
+ apply_impulses(this.a, this.b, this.r1, this.r2, this.jAcc.x * dt_coef, this.jAcc.y * dt_coef);
+};
+
+PivotJoint.prototype.applyImpulse = function()
+{
+ var a = this.a;
+ var b = this.b;
+
+ var r1 = this.r1;
+ var r2 = this.r2;
+
+ // compute relative velocity
+ var vr = relative_velocity(a, b, r1, r2);
+
+ // compute normal impulse
+ var j = mult_k(vsub(this.bias, vr), this.k1, this.k2);
+ var jOld = this.jAcc;
+ this.jAcc = vclamp(vadd(this.jAcc, j), this.jMaxLen);
+
+ // apply impulse
+ apply_impulses(a, b, this.r1, this.r2, this.jAcc.x - jOld.x, this.jAcc.y - jOld.y);
+};
+
+PivotJoint.prototype.getImpulse = function()
+{
+ return vlength(this.jAcc);
+};
+
+/* Copyright (c) 2007 Scott Lembcke
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+var GrooveJoint = cp.GrooveJoint = function(a, b, groove_a, groove_b, anchr2)
+{
+ Constraint.call(this, a, b);
+
+ this.grv_a = groove_a;
+ this.grv_b = groove_b;
+ this.grv_n = vperp(vnormalize(vsub(groove_b, groove_a)));
+ this.anchr2 = anchr2;
+
+ this.grv_tn = null;
+ this.clamp = 0;
+ this.r1 = this.r2 = null;
+
+ this.k1 = new Vect(0,0);
+ this.k2 = new Vect(0,0);
+
+ this.jAcc = vzero;
+ this.jMaxLen = 0;
+ this.bias = null;
+};
+
+GrooveJoint.prototype = Object.create(Constraint.prototype);
+
+GrooveJoint.prototype.preStep = function(dt)
+{
+ var a = this.a;
+ var b = this.b;
+
+ // calculate endpoints in worldspace
+ var ta = a.local2World(this.grv_a);
+ var tb = a.local2World(this.grv_b);
+
+ // calculate axis
+ var n = vrotate(this.grv_n, a.rot);
+ var d = vdot(ta, n);
+
+ this.grv_tn = n;
+ this.r2 = vrotate(this.anchr2, b.rot);
+
+ // calculate tangential distance along the axis of r2
+ var td = vcross(vadd(b.p, this.r2), n);
+ // calculate clamping factor and r2
+ if(td <= vcross(ta, n)){
+ this.clamp = 1;
+ this.r1 = vsub(ta, a.p);
+ } else if(td >= vcross(tb, n)){
+ this.clamp = -1;
+ this.r1 = vsub(tb, a.p);
+ } else {
+ this.clamp = 0;
+ this.r1 = vsub(vadd(vmult(vperp(n), -td), vmult(n, d)), a.p);
+ }
+
+ // Calculate mass tensor
+ k_tensor(a, b, this.r1, this.r2, this.k1, this.k2);
+
+ // compute max impulse
+ this.jMaxLen = this.maxForce * dt;
+
+ // calculate bias velocity
+ var delta = vsub(vadd(b.p, this.r2), vadd(a.p, this.r1));
+ this.bias = vclamp(vmult(delta, -bias_coef(this.errorBias, dt)/dt), this.maxBias);
+};
+
+GrooveJoint.prototype.applyCachedImpulse = function(dt_coef)
+{
+ apply_impulses(this.a, this.b, this.r1, this.r2, this.jAcc.x * dt_coef, this.jAcc.y * dt_coef);
+};
+
+GrooveJoint.prototype.grooveConstrain = function(j){
+ var n = this.grv_tn;
+ var jClamp = (this.clamp*vcross(j, n) > 0) ? j : vproject(j, n);
+ return vclamp(jClamp, this.jMaxLen);
+};
+
+GrooveJoint.prototype.applyImpulse = function()
+{
+ var a = this.a;
+ var b = this.b;
+
+ var r1 = this.r1;
+ var r2 = this.r2;
+
+ // compute impulse
+ var vr = relative_velocity(a, b, r1, r2);
+
+ var j = mult_k(vsub(this.bias, vr), this.k1, this.k2);
+ var jOld = this.jAcc;
+ this.jAcc = this.grooveConstrain(vadd(jOld, j));
+
+ // apply impulse
+ apply_impulses(a, b, this.r1, this.r2, this.jAcc.x - jOld.x, this.jAcc.y - jOld.y);
+};
+
+GrooveJoint.prototype.getImpulse = function()
+{
+ return vlength(this.jAcc);
+};
+
+GrooveJoint.prototype.setGrooveA = function(value)
+{
+ this.grv_a = value;
+ this.grv_n = vperp(vnormalize(vsub(this.grv_b, value)));
+
+ this.activateBodies();
+};
+
+GrooveJoint.prototype.setGrooveB = function(value)
+{
+ this.grv_b = value;
+ this.grv_n = vperp(vnormalize(vsub(value, this.grv_a)));
+
+ this.activateBodies();
+};
+
+/* Copyright (c) 2007 Scott Lembcke
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+var defaultSpringForce = function(spring, dist){
+ return (spring.restLength - dist)*spring.stiffness;
+};
+
+var DampedSpring = cp.DampedSpring = function(a, b, anchr1, anchr2, restLength, stiffness, damping)
+{
+ Constraint.call(this, a, b);
+
+ this.anchr1 = anchr1;
+ this.anchr2 = anchr2;
+
+ this.restLength = restLength;
+ this.stiffness = stiffness;
+ this.damping = damping;
+ this.springForceFunc = defaultSpringForce;
+
+ this.target_vrn = this.v_coef = 0;
+
+ this.r1 = this.r2 = null;
+ this.nMass = 0;
+ this.n = null;
+};
+
+DampedSpring.prototype = Object.create(Constraint.prototype);
+
+DampedSpring.prototype.preStep = function(dt)
+{
+ var a = this.a;
+ var b = this.b;
+
+ this.r1 = vrotate(this.anchr1, a.rot);
+ this.r2 = vrotate(this.anchr2, b.rot);
+
+ var delta = vsub(vadd(b.p, this.r2), vadd(a.p, this.r1));
+ var dist = vlength(delta);
+ this.n = vmult(delta, 1/(dist ? dist : Infinity));
+
+ var k = k_scalar(a, b, this.r1, this.r2, this.n);
+ assertSoft(k !== 0, "Unsolvable this.");
+ this.nMass = 1/k;
+
+ this.target_vrn = 0;
+ this.v_coef = 1 - Math.exp(-this.damping*dt*k);
+
+ // apply this force
+ var f_spring = this.springForceFunc(this, dist);
+ apply_impulses(a, b, this.r1, this.r2, this.n.x * f_spring * dt, this.n.y * f_spring * dt);
+};
+
+DampedSpring.prototype.applyCachedImpulse = function(dt_coef){};
+
+DampedSpring.prototype.applyImpulse = function()
+{
+ var a = this.a;
+ var b = this.b;
+
+ var n = this.n;
+ var r1 = this.r1;
+ var r2 = this.r2;
+
+ // compute relative velocity
+ var vrn = normal_relative_velocity(a, b, r1, r2, n);
+
+ // compute velocity loss from drag
+ var v_damp = (this.target_vrn - vrn)*this.v_coef;
+ this.target_vrn = vrn + v_damp;
+
+ v_damp *= this.nMass;
+ apply_impulses(a, b, this.r1, this.r2, this.n.x * v_damp, this.n.y * v_damp);
+};
+
+DampedSpring.prototype.getImpulse = function()
+{
+ return 0;
+};
+
+/* Copyright (c) 2007 Scott Lembcke
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+var defaultSpringTorque = function(spring, relativeAngle){
+ return (relativeAngle - spring.restAngle)*spring.stiffness;
+}
+
+var DampedRotarySpring = cp.DampedRotarySpring = function(a, b, restAngle, stiffness, damping)
+{
+ Constraint.call(this, a, b);
+
+ this.restAngle = restAngle;
+ this.stiffness = stiffness;
+ this.damping = damping;
+ this.springTorqueFunc = defaultSpringTorque;
+
+ this.target_wrn = 0;
+ this.w_coef = 0;
+ this.iSum = 0;
+};
+
+DampedRotarySpring.prototype = Object.create(Constraint.prototype);
+
+DampedRotarySpring.prototype.preStep = function(dt)
+{
+ var a = this.a;
+ var b = this.b;
+
+ var moment = a.i_inv + b.i_inv;
+ assertSoft(moment !== 0, "Unsolvable spring.");
+ this.iSum = 1/moment;
+
+ this.w_coef = 1 - Math.exp(-this.damping*dt*moment);
+ this.target_wrn = 0;
+
+ // apply this torque
+ var j_spring = this.springTorqueFunc(this, a.a - b.a)*dt;
+ a.w -= j_spring*a.i_inv;
+ b.w += j_spring*b.i_inv;
+};
+
+// DampedRotarySpring.prototype.applyCachedImpulse = function(dt_coef){};
+
+DampedRotarySpring.prototype.applyImpulse = function()
+{
+ var a = this.a;
+ var b = this.b;
+
+ // compute relative velocity
+ var wrn = a.w - b.w;//normal_relative_velocity(a, b, r1, r2, n) - this.target_vrn;
+
+ // compute velocity loss from drag
+ // not 100% certain spring is derived correctly, though it makes sense
+ var w_damp = (this.target_wrn - wrn)*this.w_coef;
+ this.target_wrn = wrn + w_damp;
+
+ //apply_impulses(a, b, this.r1, this.r2, vmult(this.n, v_damp*this.nMass));
+ var j_damp = w_damp*this.iSum;
+ a.w += j_damp*a.i_inv;
+ b.w -= j_damp*b.i_inv;
+};
+
+// DampedRotarySpring.prototype.getImpulse = function(){ return 0; };
+
+/* Copyright (c) 2007 Scott Lembcke
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+var RotaryLimitJoint = cp.RotaryLimitJoint = function(a, b, min, max)
+{
+ Constraint.call(this, a, b);
+
+ this.min = min;
+ this.max = max;
+
+ this.jAcc = 0;
+
+ this.iSum = this.bias = this.jMax = 0;
+};
+
+RotaryLimitJoint.prototype = Object.create(Constraint.prototype);
+
+RotaryLimitJoint.prototype.preStep = function(dt)
+{
+ var a = this.a;
+ var b = this.b;
+
+ var dist = b.a - a.a;
+ var pdist = 0;
+ if(dist > this.max) {
+ pdist = this.max - dist;
+ } else if(dist < this.min) {
+ pdist = this.min - dist;
+ }
+
+ // calculate moment of inertia coefficient.
+ this.iSum = 1/(1/a.i + 1/b.i);
+
+ // calculate bias velocity
+ var maxBias = this.maxBias;
+ this.bias = clamp(-bias_coef(this.errorBias, dt)*pdist/dt, -maxBias, maxBias);
+
+ // compute max impulse
+ this.jMax = this.maxForce * dt;
+
+ // If the bias is 0, the joint is not at a limit. Reset the impulse.
+ if(!this.bias) this.jAcc = 0;
+};
+
+RotaryLimitJoint.prototype.applyCachedImpulse = function(dt_coef)
+{
+ var a = this.a;
+ var b = this.b;
+
+ var j = this.jAcc*dt_coef;
+ a.w -= j*a.i_inv;
+ b.w += j*b.i_inv;
+};
+
+RotaryLimitJoint.prototype.applyImpulse = function()
+{
+ if(!this.bias) return; // early exit
+
+ var a = this.a;
+ var b = this.b;
+
+ // compute relative rotational velocity
+ var wr = b.w - a.w;
+
+ // compute normal impulse
+ var j = -(this.bias + wr)*this.iSum;
+ var jOld = this.jAcc;
+ if(this.bias < 0){
+ this.jAcc = clamp(jOld + j, 0, this.jMax);
+ } else {
+ this.jAcc = clamp(jOld + j, -this.jMax, 0);
+ }
+ j = this.jAcc - jOld;
+
+ // apply impulse
+ a.w -= j*a.i_inv;
+ b.w += j*b.i_inv;
+};
+
+RotaryLimitJoint.prototype.getImpulse = function()
+{
+ return Math.abs(joint.jAcc);
+};
+
+/* Copyright (c) 2007 Scott Lembcke
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+var RatchetJoint = cp.RatchetJoint = function(a, b, phase, ratchet)
+{
+ Constraint.call(this, a, b);
+
+ this.angle = 0;
+ this.phase = phase;
+ this.ratchet = ratchet;
+
+ // STATIC_BODY_CHECK
+ this.angle = (b ? b.a : 0) - (a ? a.a : 0);
+
+ this.iSum = this.bias = this.jAcc = this.jMax = 0;
+};
+
+RatchetJoint.prototype = Object.create(Constraint.prototype);
+
+RatchetJoint.prototype.preStep = function(dt)
+{
+ var a = this.a;
+ var b = this.b;
+
+ var angle = this.angle;
+ var phase = this.phase;
+ var ratchet = this.ratchet;
+
+ var delta = b.a - a.a;
+ var diff = angle - delta;
+ var pdist = 0;
+
+ if(diff*ratchet > 0){
+ pdist = diff;
+ } else {
+ this.angle = Math.floor((delta - phase)/ratchet)*ratchet + phase;
+ }
+
+ // calculate moment of inertia coefficient.
+ this.iSum = 1/(a.i_inv + b.i_inv);
+
+ // calculate bias velocity
+ var maxBias = this.maxBias;
+ this.bias = clamp(-bias_coef(this.errorBias, dt)*pdist/dt, -maxBias, maxBias);
+
+ // compute max impulse
+ this.jMax = this.maxForce * dt;
+
+ // If the bias is 0, the joint is not at a limit. Reset the impulse.
+ if(!this.bias) this.jAcc = 0;
+};
+
+RatchetJoint.prototype.applyCachedImpulse = function(dt_coef)
+{
+ var a = this.a;
+ var b = this.b;
+
+ var j = this.jAcc*dt_coef;
+ a.w -= j*a.i_inv;
+ b.w += j*b.i_inv;
+};
+
+RatchetJoint.prototype.applyImpulse = function()
+{
+ if(!this.bias) return; // early exit
+
+ var a = this.a;
+ var b = this.b;
+
+ // compute relative rotational velocity
+ var wr = b.w - a.w;
+ var ratchet = this.ratchet;
+
+ // compute normal impulse
+ var j = -(this.bias + wr)*this.iSum;
+ var jOld = this.jAcc;
+ this.jAcc = clamp((jOld + j)*ratchet, 0, this.jMax*Math.abs(ratchet))/ratchet;
+ j = this.jAcc - jOld;
+
+ // apply impulse
+ a.w -= j*a.i_inv;
+ b.w += j*b.i_inv;
+};
+
+RatchetJoint.prototype.getImpulse = function(joint)
+{
+ return Math.abs(joint.jAcc);
+};
+
+/* Copyright (c) 2007 Scott Lembcke
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+var GearJoint = cp.GearJoint = function(a, b, phase, ratio)
+{
+ Constraint.call(this, a, b);
+
+ this.phase = phase;
+ this.ratio = ratio;
+ this.ratio_inv = 1/ratio;
+
+ this.jAcc = 0;
+
+ this.iSum = this.bias = this.jMax = 0;
+};
+
+GearJoint.prototype = Object.create(Constraint.prototype);
+
+GearJoint.prototype.preStep = function(dt)
+{
+ var a = this.a;
+ var b = this.b;
+
+ // calculate moment of inertia coefficient.
+ this.iSum = 1/(a.i_inv*this.ratio_inv + this.ratio*b.i_inv);
+
+ // calculate bias velocity
+ var maxBias = this.maxBias;
+ this.bias = clamp(-bias_coef(this.errorBias, dt)*(b.a*this.ratio - a.a - this.phase)/dt, -maxBias, maxBias);
+
+ // compute max impulse
+ this.jMax = this.maxForce * dt;
+};
+
+GearJoint.prototype.applyCachedImpulse = function(dt_coef)
+{
+ var a = this.a;
+ var b = this.b;
+
+ var j = this.jAcc*dt_coef;
+ a.w -= j*a.i_inv*this.ratio_inv;
+ b.w += j*b.i_inv;
+};
+
+GearJoint.prototype.applyImpulse = function()
+{
+ var a = this.a;
+ var b = this.b;
+
+ // compute relative rotational velocity
+ var wr = b.w*this.ratio - a.w;
+
+ // compute normal impulse
+ var j = (this.bias - wr)*this.iSum;
+ var jOld = this.jAcc;
+ this.jAcc = clamp(jOld + j, -this.jMax, this.jMax);
+ j = this.jAcc - jOld;
+
+ // apply impulse
+ a.w -= j*a.i_inv*this.ratio_inv;
+ b.w += j*b.i_inv;
+};
+
+GearJoint.prototype.getImpulse = function()
+{
+ return Math.abs(this.jAcc);
+};
+
+GearJoint.prototype.setRatio = function(value)
+{
+ this.ratio = value;
+ this.ratio_inv = 1/value;
+ this.activateBodies();
+};
+
+/* Copyright (c) 2007 Scott Lembcke
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+var SimpleMotor = cp.SimpleMotor = function(a, b, rate)
+{
+ Constraint.call(this, a, b);
+
+ this.rate = rate;
+
+ this.jAcc = 0;
+
+ this.iSum = this.jMax = 0;
+};
+
+SimpleMotor.prototype = Object.create(Constraint.prototype);
+
+SimpleMotor.prototype.preStep = function(dt)
+{
+ // calculate moment of inertia coefficient.
+ this.iSum = 1/(this.a.i_inv + this.b.i_inv);
+
+ // compute max impulse
+ this.jMax = this.maxForce * dt;
+};
+
+SimpleMotor.prototype.applyCachedImpulse = function(dt_coef)
+{
+ var a = this.a;
+ var b = this.b;
+
+ var j = this.jAcc*dt_coef;
+ a.w -= j*a.i_inv;
+ b.w += j*b.i_inv;
+};
+
+SimpleMotor.prototype.applyImpulse = function()
+{
+ var a = this.a;
+ var b = this.b;
+
+ // compute relative rotational velocity
+ var wr = b.w - a.w + this.rate;
+
+ // compute normal impulse
+ var j = -wr*this.iSum;
+ var jOld = this.jAcc;
+ this.jAcc = clamp(jOld + j, -this.jMax, this.jMax);
+ j = this.jAcc - jOld;
+
+ // apply impulse
+ a.w -= j*a.i_inv;
+ b.w += j*b.i_inv;
+};
+
+SimpleMotor.prototype.getImpulse = function()
+{
+ return Math.abs(this.jAcc);
+};
+
+})();
diff --git a/external/gaf/GAFBoot.js b/external/gaf/GAFBoot.js
new file mode 100644
index 0000000000..0baccc7ecd
--- /dev/null
+++ b/external/gaf/GAFBoot.js
@@ -0,0 +1,24 @@
+var gaf = gaf || {};
+gaf._tmp = gaf._tmp || {};
+gaf._initialized = false;
+
+gaf.CCGAFLoader = function()
+{
+ this.load = function(realUrl, url, item, cb)
+ {
+ if(!gaf._initialized)
+ {
+ gaf._setup();
+ }
+ var loader = new gaf.Loader();
+ loader.LoadFile(realUrl, function(data){cb(null, data)});
+ };
+};
+
+gaf._setup = function()
+{
+ gaf._setupShaders();
+ gaf._initialized = true;
+};
+
+cc.loader.register('.gaf', new gaf.CCGAFLoader());
diff --git a/external/gaf/GAFMacros.js b/external/gaf/GAFMacros.js
new file mode 100644
index 0000000000..ef34cc8f5d
--- /dev/null
+++ b/external/gaf/GAFMacros.js
@@ -0,0 +1,33 @@
+var gaf = gaf || {};
+
+gaf.COMPRESSION_NONE = 0x00474146;
+gaf.COMPRESSION_ZIP = 0x00474143;
+
+gaf.IDNONE = 0xffffffff;
+gaf.FIRST_FRAME_INDEX = 0;
+
+gaf.EFFECT_DROP_SHADOW = 0;
+gaf.EFFECT_BLUR = 1;
+gaf.EFFECT_GLOW = 2;
+gaf.EFFECT_COLOR_MATRIX = 6;
+
+gaf.ACTION_STOP = 0;
+gaf.ACTION_PLAY = 1;
+gaf.ACTION_GO_TO_AND_STOP = 2;
+gaf.ACTION_GO_TO_AND_PLAY = 3;
+gaf.ACTION_DISPATCH_EVENT = 4;
+
+gaf.PI_FRAME = 0;
+gaf.PI_EVENT_TYPE = 0;
+
+gaf.TYPE_TEXTURE = 0;
+gaf.TYPE_TEXT_FIELD = 1;
+gaf.TYPE_TIME_LINE = 2;
+
+gaf.UNIFORM_BLUR_TEXEL_OFFSET = "u_step";
+gaf.UNIFORM_GLOW_TEXEL_OFFSET = "u_step";
+gaf.UNIFORM_GLOW_COLOR = "u_glowColor";
+gaf.UNIFORM_ALPHA_TINT_MULT = "colorTransformMult";
+gaf.UNIFORM_ALPHA_TINT_OFFSET = "colorTransformOffsets";
+gaf.UNIFORM_ALPHA_COLOR_MATRIX_BODY = "colorMatrix";
+gaf.UNIFORM_ALPHA_COLOR_MATRIX_APPENDIX = "colorMatrix2";
diff --git a/external/gaf/Library/GAFAsset.js b/external/gaf/Library/GAFAsset.js
new file mode 100644
index 0000000000..c66fddde39
--- /dev/null
+++ b/external/gaf/Library/GAFAsset.js
@@ -0,0 +1,428 @@
+EventTarget = require("../cocos2d/core/event/event-target");
+
+var gaf = gaf || {};
+
+gaf.Asset = cc._Class.extend
+({
+ _className: "GAFAsset",
+
+ // Private members
+ _header: null,
+ _timeLines: null,
+ _textFields: null,
+ _protos: null,
+ _objects: null,
+ _masks: null,
+
+ _rootTimeLine: null,
+ _textureLoadDelegate: null,
+ _sceneFps: 60,
+ _sceneWidth: 0,
+ _sceneHeight: 0,
+ _sceneColor: 0,
+ _gafData: null,
+ _desiredAtlasScale: 1,
+ _usedAtlasScale: 0,
+
+ _atlases: null,
+ _onLoadTasks: null,
+ _atlasScales: null,
+ _textureLoaded: false, // For async loading with cc.event manager
+ _atlasesToLoad: null, // Atlases that are not yet loaded
+ _gafName: null,
+
+ /**
+ * @method initWithGAFFile
+ * @param {String} filePath - path to .gaf file
+ * @param {String function(String)} textureLoadDelegate - is used to change atlas path, e.g. to load `atlas.tga` instead of `atlas.png`
+ * @return {bool}
+ */
+ initWithGAFFile: function (filePath, textureLoadDelegate) {
+ var self = this;
+ this._textureLoadDelegate = textureLoadDelegate;
+ this._gafName = filePath;
+ var gafData = cc.loader.getRes(filePath);
+ if(!gafData)
+ {
+ cc.loader.load(filePath, function(err, data){
+ if(!err)
+ {
+ self._init(data[0]);
+ }
+ });
+ }
+ else {
+ return this._init(gafData);
+ }
+ return false;
+ },
+
+ /**
+ * @method initWithGAFBundle
+ * @param {String} zipFilePath - path to the archive with .gaf and its textures
+ * @param {String} entryFile - name of the .gaf file in archive
+ * @param {function({path:String})} delegate - is used to change atlas path, e.g. to load `atlas.tga` instead of `atlas.png`
+ * @return {bool}
+ */
+ initWithGAFBundle: function (zipFilePath, entryFile, delegate)
+ {
+ cc.assert(false, "initWithGAFBundle is not yet implemented");
+ return false;
+ },
+
+ /**
+ * @method setRootTimelineWithName
+ * @param {String} name
+ */
+ setRootTimelineWithName: function (name)
+ {
+ for(var i = 0, end = this._timeLines.length; i < end; ++i)
+ {
+ var object = this._timeLines[i];
+ if (object && object.getLinkageName() === name)
+ {
+ this._setRootTimeline(object);
+ return;
+ }
+ }
+ },
+
+ isAssetVersionPlayable: function ()
+ {
+ return true;
+ },
+
+ /**
+ * Desired atlas scale.
+ * Default is 1.0f
+ * @returns {number}
+ */
+ desiredAtlasScale : function(){
+ return this._desiredAtlasScale;
+ },
+
+ /**
+ * Sets desired atlas scale. Will choose nearest atlas scale from available.
+ * Default is 1.0f
+ * @param scale
+ */
+ setDesiredAtlasScale : function(desiredAtlasScale){
+ this._desiredAtlasScale = desiredAtlasScale;
+ for(var currentScale in this._atlasScales)if(this._atlasScales.hasOwnProperty(currentScale))
+ {
+ if( (this._usedAtlasScale === 0) ||
+ (Math.abs(this._usedAtlasScale - desiredAtlasScale) > Math.abs(currentScale - desiredAtlasScale) ))
+ {
+ this._usedAtlasScale = currentScale;
+ }
+
+ }
+ },
+
+ /**
+ * @method createObject
+ * @return {gaf.Object}
+ */
+ createObject: function ()
+ {
+ return this._instantiateGaf(this._gafData);
+ },
+
+ /**
+ * @method createObjectAndRun
+ * @param {boolean} arg0 - run looped
+ * @return {gaf.Object}
+ */
+ createObjectAndRun: function (looped)
+ {
+ cc.assert(arguments.length === 1, "GAFAsset::createObjectAndRun should have one param");
+ var object = this._instantiateGaf(this._gafData);
+ object.setLooped(looped, true);
+ object.start();
+ return object;
+ },
+
+ /**
+ * @method setTextureLoadDelegate
+ * @param {function} delegate
+ */
+ setTextureLoadDelegate: function (delegate)
+ {
+ debugger;
+ },
+
+
+ /**
+ * @method getSceneFps
+ * @return {uint}
+ */
+ getSceneFps: function ()
+ {
+ return this._sceneFps;
+ },
+
+ /**
+ * @method getSceneWidth
+ * @return {uint}
+ */
+ getSceneWidth: function ()
+ {
+ debugger;
+ },
+
+ /**
+ * @method getSceneHeight
+ * @return {uint}
+ */
+ getSceneHeight: function ()
+ {
+ debugger;
+ },
+
+ /**
+ * @method getSceneColor
+ * @return {cc.color4b}
+ */
+ getSceneColor: function ()
+ {
+ debugger;
+ },
+
+ /**
+ * @method setSceneFps
+ * @param {uint} fps
+ */
+ setSceneFps: function (fps)
+ {
+ this._sceneFps = fps;
+ },
+
+ /**
+ * @method setSceneWidth
+ * @param {uint} width
+ */
+ setSceneWidth: function (width)
+ {
+ debugger;
+ },
+
+ /**
+ * @method setSceneHeight
+ * @param {uint} height
+ */
+ setSceneHeight: function (height)
+ {
+ debugger;
+ },
+
+ /**
+ * @method setSceneColor
+ * @param {color4b_object} arg0
+ */
+ setSceneColor: function (color4B)
+ {
+ debugger;
+ },
+
+ /**
+ * @method getHeader
+ * @return {GAFHeader}
+ */
+ getHeader: function ()
+ {
+ return this._header;
+ },
+
+ getGAFFileName: function()
+ {
+ return this._gafName;
+ },
+
+ // Private
+
+ ctor : function()
+ {
+ this._header = {};
+ this._timeLines = [];
+ this._textFields = [];
+ this._objects = [];
+ this._masks = [];
+ this._protos = [];
+ this._atlases = {};
+ this._onLoadTasks = [];
+ this._atlasScales = {};
+ this._atlasesToLoad = {};
+
+ if(arguments.length > 0)
+ this.initWithGAFFile.apply(this, arguments);
+ },
+
+ _getProtos: function()
+ {
+ return this._protos;
+ },
+
+ _setRootTimeline : function(timeLine)
+ {
+ this._rootTimeLine = timeLine;
+ this._header.pivot = timeLine.getPivot();
+ this._header.frameSize = timeLine.getRect();
+ },
+
+ _setHeader : function (gafHeader)
+ {
+ for(var prop in gafHeader)
+ {
+ if(gafHeader.hasOwnProperty(prop))
+ {
+ this._header[prop] = gafHeader[prop];
+ }
+ }
+ },
+
+ _getMajorVerison : function()
+ {
+ return this._header.versionMajor;
+ },
+
+ _init : function(gafData)
+ {
+ var self = this;
+ this._gafData = gafData;
+ this._setHeader(gafData.header);
+ this._timeLinesToLink = [];
+ if(this._getMajorVerison() < 4)
+ {
+ this._pushTimeLine(new gaf._TimeLineProto(this, this._header.framesCount, this._header.frameSize, this._header.pivot));
+ }
+ gaf._AssetPreload.Tags(this, gafData.tags, this._rootTimeLine);
+
+ //Link and create
+ this._objects.forEach(function(item)
+ {
+ switch(item.type)
+ {
+ case gaf.TYPE_TEXTURE:
+ // Create gaf sprite proto if it is not yet created
+ if(!self._protos[item.objectId])
+ {
+ self._protos[item.objectId] = new gaf._SpriteProto(self, self._atlasScales, item.elementAtlasIdRef);
+ }
+ break;
+ case gaf.TYPE_TIME_LINE:
+ // All time line protos are already created, just copy reference
+ self._protos[item.objectId] = self._timeLines[item.elementAtlasIdRef];
+ break;
+ case gaf.TYPE_TEXT_FIELD:
+ // All text field protos are already created, just copy reference
+ self._protos[item.objectId] = self._textFields[item.elementAtlasIdRef];
+ break;
+ default:
+ cc.log("Unknown object type: " + item.type);
+ break;
+ }
+ });
+ this._masks.forEach(function(item)
+ {
+ if(self._protos[item.objectId])
+ {
+ return; // this is continue
+ }
+ var proto = null;
+ switch(item.type)
+ {
+ case gaf.TYPE_TEXTURE:
+ // Create gaf sprite proto if it is not yet created
+ proto = new gaf._SpriteProto(self, self._atlasScales, item.elementAtlasIdRef);
+ break;
+ case gaf.TYPE_TIME_LINE:
+ // All time line protos are already created, just copy reference
+ proto = self._timeLines[item.elementAtlasIdRef];
+ break;
+ case gaf.TYPE_TEXT_FIELD:
+ // All text field protos are already created, just copy reference
+ proto = self._textFields[item.elementAtlasIdRef];
+ break;
+ }
+ self._protos[item.objectId] = new gaf._MaskProto(self, proto, item.elementAtlasIdRef);
+ });
+ this.setDesiredAtlasScale(this._desiredAtlasScale);
+
+ if(Object.keys(this._atlasesToLoad).length === 0)
+ {
+ this._textureLoaded = true;
+ this.emit("load");
+ }
+ },
+
+ _pushTimeLine : function(timeLine)
+ {
+ this._timeLines[timeLine.getId()] = timeLine;
+
+ if(timeLine.getId() === 0)
+ {
+ this._setRootTimeline(timeLine);
+ }
+ },
+
+ _instantiateGaf : function()
+ {
+ var root = null;
+ root = this._rootTimeLine._gafConstruct();
+ return root;
+ },
+
+ _onAtlasLoaded : function(id, atlas)
+ {
+ this._atlases[id] = atlas;
+ delete this._atlasesToLoad[id];
+ if(Object.keys(this._atlasesToLoad).length === 0)
+ {
+ this._onLoadTasks.forEach(function(fn){fn()});
+ this._onLoadTasks.length = 0;
+ this._textureLoaded = true;
+ this.emit("load");
+ }
+ },
+
+ isLoaded : function()
+ {
+ return this._textureLoaded;
+ },
+
+ _getSearchPaths: function(imageUrl)
+ {
+ var extendedPath = this.getGAFFileName().split('/');
+ extendedPath[extendedPath.length-1] = imageUrl;
+ var alternativeUrl = extendedPath.join('/');
+
+ return [imageUrl, alternativeUrl];
+ }
+});
+
+/**
+ * @method initWithGAFFile
+ * @param {String} gafFilePath - path to .gaf file
+ * @param {function({path:String})} delegate - is used to change atlas path, e.g. to load `atlas.tga` instead of `atlas.png`
+ * @return {gaf.Asset}
+ */
+gaf.Asset.create = function (gafFilePath, delegate)
+{
+ return new gaf.Asset(gafFilePath, delegate);
+};
+
+/**
+ * @method createWithBundle
+ * @param {String} zipFilePath - path to the archive with .gaf and its textures
+ * @param {String} entryFile - name of the .gaf file in archive
+ * @param {function({path:String})} delegate - is used to change atlas path, e.g. to load `atlas.tga` instead of `atlas.png`
+ * @return {gaf.Asset}
+ */
+gaf.Asset.createWithBundle = function (zipFilePath, entryFile, delegate)
+{
+ var asset = new gaf.Asset();
+ asset.initWithGAFBundle(zipFilePath, entryFile, delegate);
+ return asset;
+};
+
+EventTarget.polyfill(gaf.Asset.prototype);
diff --git a/external/gaf/Library/GAFAssetPreload.js b/external/gaf/Library/GAFAssetPreload.js
new file mode 100644
index 0000000000..8514e09f2d
--- /dev/null
+++ b/external/gaf/Library/GAFAssetPreload.js
@@ -0,0 +1,270 @@
+
+gaf.CGAffineTransformCocosFormatFromFlashFormat = function(transform)
+{
+ var t = {};
+ t.a = transform.a;
+ t.b = -transform.b;
+ t.c = -transform.c;
+ t.d = transform.d;
+ t.tx = transform.tx;
+ t.ty = -transform.ty;
+ return t;
+};
+
+gaf._AssetPreload = function()
+{
+ this["0"] = this.End;
+ this["1"] = this.Atlases;
+ this["2"] = this.AnimationMasks;
+ this["3"] = this.AnimationObjects;
+ this["4"] = this.AnimationFrames;
+ this["5"] = this.NamedParts;
+ this["6"] = this.Sequences;
+ this["7"] = this.TextFields;
+ this["8"] = this.Atlases; // 2
+ this["9"] = this.Stage;
+ this["10"] = this.AnimationObjects; //2
+ this["11"] = this.AnimationMasks; // 2
+ this["12"] = this.AnimationFrames; // 2
+ this["13"] = this.TimeLine;
+};
+
+gaf._AssetPreload.prototype.End = function(asset, content, timeLine){
+ if(timeLine)
+ {
+ timeLine.getFps = function()
+ {
+ return asset.getSceneFps();
+ };
+ }
+};
+
+gaf._AssetPreload.prototype.Tag = function(asset, tag, timeLine)
+{
+ (this[tag.tagId]).call(this, asset, tag.content, timeLine);
+};
+
+gaf._AssetPreload.prototype.Tags = function(asset, tags, timeLine)
+{
+ var self = this;
+ tags.forEach(function(tag)
+ {
+ self.Tag(asset, tag, timeLine);
+ });
+};
+
+gaf._AssetPreload.prototype.AtlasCreateFrames = function(elements, asset, spriteFrames)
+{
+ elements.forEach(function (item) {
+ var texture = asset._atlases[item.atlasId];
+ var rect = cc.rect(item.origin.x, item.origin.y, item.size.x, item.size.y);
+ var frame = new cc.SpriteFrame(texture, rect);
+ frame._gafAnchor =
+ {
+ x: (0 - (0 - (item.pivot.x / item.size.x))),
+ y: (0 + (1 - (item.pivot.y / item.size.y)))
+ };
+ spriteFrames[item.elementAtlasId] = frame;
+ // 9 grid
+ });
+};
+
+
+
+gaf._AssetPreload.prototype.Atlases = function(asset, content, timeLine)
+{
+ var spriteFrames = asset._atlasScales[content.scale] = asset._atlasScales[content.scale] || [];
+ var csf = cc.Director._getInstance().getContentScaleFactor();
+
+ content.atlases.forEach(function(item)
+ {
+ var atlasId = item.id;
+ var finalizeLoading = function()
+ {
+ gaf._AssetPreload.AtlasCreateFrames(content.elements, asset, spriteFrames);
+ };
+
+ var atlasPath = "";
+ item.sources.forEach(function(atlasSource)
+ {
+ if(atlasSource.csf === csf)
+ {
+ atlasPath = atlasSource.source;
+ }
+ });
+ cc.assert(atlasPath, "GAF Error. Texture for current CSF not found. Reconvert animation with correct parameters.");
+
+ if(asset._textureLoadDelegate)
+ {
+ atlasPath = asset._textureLoadDelegate(atlasPath);
+ }
+
+ var loaded = false;
+ var paths = asset._getSearchPaths(atlasPath);
+ for(var i = 0, len = paths.length; i < len; ++i){
+ var path = paths[i];
+ var atlas = cc.textureCache.getTextureForKey(path);
+ if(atlas && atlas.isLoaded())
+ {
+ atlas.handleLoadedTexture(true);
+ loaded = true;
+ asset._atlases[atlasId] = atlas;
+ finalizeLoading();
+ break;
+ }
+ }
+ // Need to load atlases async
+ if(!loaded)
+ {
+ var success = function (atlas) {
+ atlas.handleLoadedTexture(true);
+ asset._onAtlasLoaded(atlasId, atlas);
+ };
+
+ var fail = function () {
+ cc.log("GAF Error. Couldn't find `" + atlasPath + "` required by `" + asset.getGAFFileName() + "`");
+ };
+
+ if(!asset._atlasesToLoad.hasOwnProperty(atlasId))
+ {
+ gaf._AtlasLoader.loadArray(paths, success, fail);
+ asset._atlasesToLoad[atlasId] = {};
+ }
+ asset._onLoadTasks.push(finalizeLoading);
+ }
+ });
+};
+
+gaf._AssetPreload.prototype.AnimationObjects = function(asset, content, timeLine)
+{
+ content.forEach(function(item)
+ {
+ item.type = (item.type === undefined) ? gaf.TYPE_TEXTURE : item.type;
+ timeLine._objects.push(item.objectId);
+ asset._objects[item.objectId] = item;
+ });
+};
+
+gaf._AssetPreload.prototype.convertTint = function(mat, alpha)
+{
+ if(!mat)
+ return null;
+ return {
+ mult:
+ {
+ r: mat.redMultiplier * 255,
+ g: mat.greenMultiplier * 255,
+ b: mat.blueMultiplier * 255,
+ a: alpha * 255
+ },
+ offset:
+ {
+ r: mat.redOffset * 255,
+ g: mat.greenOffset * 255,
+ b: mat.blueOffset * 255,
+ a: mat.alphaOffset * 255
+ }
+ };
+};
+
+gaf._AssetPreload.prototype.convertState = function(state)
+{
+ return {
+ hasColorTransform: state.hasColorTransform,
+ hasMask: state.hasMask,
+ hasEffect: state.hasEffect,
+ objectIdRef: state.objectIdRef,
+ depth: state.depth,
+ alpha: state.alpha * 255,
+ matrix: gaf.CGAffineTransformCocosFormatFromFlashFormat(state.matrix),
+ colorTransform: this.convertTint(state.colorTransform, state.alpha),
+ effect: state.effect,
+ maskObjectIdRef: state.maskObjectIdRef
+ };
+};
+
+gaf._AssetPreload.prototype.AnimationFrames = function(asset, content, timeLine)
+{
+ var self = this;
+ cc.assert(timeLine, "Error. Time Line should not be null.");
+ var statesForId = {};
+ var frames = [];
+ var lastFrame = {};
+ for(var i = 0, len = content.length; i < len; ++i)
+ {
+ var frame = content[i];
+ if(frame.state)
+ {
+ frame.state.forEach(function (state)
+ {
+ if (state.alpha !== 0)
+ {
+ statesForId[state.objectIdRef] = self.convertState(state);
+ }
+ else
+ {
+ statesForId[state.objectIdRef] = null;
+ }
+ });
+ }
+ var stateArray = [];
+ for(var obj in statesForId){ if(statesForId.hasOwnProperty(obj) && statesForId[obj])
+ {
+ stateArray.push(statesForId[obj]);
+ }}
+ lastFrame = frame;
+ frames[frame.frame - 1] = {states: stateArray, actions: frame.actions || null};
+ }
+ timeLine.getFrames = function(){return frames};
+};
+
+gaf._AssetPreload.prototype.NamedParts = function(asset, content, timeLine)
+{
+ var parts = {};
+ content.forEach(function(item)
+ {
+ parts[item.name] = item.objectId;
+ });
+ timeLine.getNamedParts = function(){return parts};
+};
+
+gaf._AssetPreload.prototype.Sequences = function(asset, content, timeLine)
+{
+ var sequences = {};
+ content.forEach(function(item){
+ sequences[item.id] = {start: item.start - 1, end: item.end};
+ });
+ timeLine.getSequences = function(){return sequences};
+};
+
+gaf._AssetPreload.prototype.TextFields = function(asset, content, timeLine)
+{
+ debugger;
+};
+
+gaf._AssetPreload.prototype.Stage = function(asset, content, timeLine)
+{
+ asset._sceneFps = content.fps;
+ asset._sceneColor = content.color;
+ asset._sceneWidth = content.width;
+ asset._sceneHeight = content.height;
+};
+
+gaf._AssetPreload.prototype.AnimationMasks = function(asset, content, timeLine)
+{
+ content.forEach(function(item)
+ {
+ item.type = (item.type === undefined) ? gaf.TYPE_TEXTURE : item.type;
+ timeLine._objects.push(item.objectId);
+ asset._masks[item.objectId] = item;
+ });
+};
+
+gaf._AssetPreload.prototype.TimeLine = function(asset, content, timeLine)
+{
+ var result = new gaf._TimeLineProto(asset, content.animationFrameCount, content.boundingBox, content.pivotPoint, content.id, content.linkageName);
+ asset._pushTimeLine(result);
+ this.Tags(asset, content.tags, result);
+};
+
+gaf._AssetPreload = new gaf._AssetPreload();
diff --git a/external/gaf/Library/GAFAtlasLoader.js b/external/gaf/Library/GAFAtlasLoader.js
new file mode 100644
index 0000000000..152bba0788
--- /dev/null
+++ b/external/gaf/Library/GAFAtlasLoader.js
@@ -0,0 +1,50 @@
+/**
+ * Created by admiral on 19.02.2015.
+ */
+
+gaf._AtlasLoader = {};
+gaf._AtlasLoader.execute = function(condition, success, fail)
+{
+ condition() ? success() : fail();
+};
+
+gaf._AtlasLoader.checkAtlas = function(atlas) // curried function
+{
+ return function(){return atlas && typeof atlas !== "string" && atlas.isLoaded()};
+};
+
+gaf._AtlasLoader.load = function(path, success, fail)
+{
+ cc.textureCache.addImage(path, function(atlas){
+ gaf._AtlasLoader.execute(
+ gaf._AtlasLoader.checkAtlas(atlas),
+ function(){success(atlas)},
+ fail
+ );
+ });
+};
+
+gaf._AtlasLoader.loadFront = function(arr, success, fail)
+{
+ // Call recursively this function for each element starting from the first
+ // stops on first success, or fails after last element
+ return function()
+ {
+ if (arr.length > 0){
+ gaf._AtlasLoader.load(
+ arr[0],
+ success,
+ gaf._AtlasLoader.loadFront(
+ arr.slice(1),
+ success,
+ fail
+ ));}
+ else
+ fail();
+ }
+};
+
+gaf._AtlasLoader.loadArray = function(array, success, fail)
+{
+ gaf._AtlasLoader.loadFront(array, success, fail)();
+};
diff --git a/external/gaf/Library/GAFDataReader.js b/external/gaf/Library/GAFDataReader.js
new file mode 100644
index 0000000000..3affbe1335
--- /dev/null
+++ b/external/gaf/Library/GAFDataReader.js
@@ -0,0 +1,229 @@
+gaf.DataReader = function(data) {
+ this.dataRaw = data;
+ this.buf = new DataView(data);
+ this.offset = [0];
+};
+
+gaf.DataReader.prototype.constructor = gaf.DataReader;
+
+gaf.DataReader.prototype.newOffset = function(size){
+ this.offset[this.offset.length - 1] += size;
+ if(this.getOffset() > this.maxOffset()){
+ throw new Error("GAF format error");
+ }
+ return this.offset[this.offset.length - 1] - size;
+};
+
+gaf.DataReader.prototype.maxOffset = function(){
+ if(this.offset.length == 1){
+ return this.buf.byteLength;
+ }
+ else{
+ return this.offset[this.offset.length - 2];
+ }
+};
+
+gaf.DataReader.prototype.getOffset = function(size){
+ return this.offset[this.offset.length - 1];
+};
+
+gaf.DataReader.prototype.Ubyte = function() {
+ return this.buf.getUint8(this.newOffset(1));
+};
+
+gaf.DataReader.prototype.Boolean = function() {
+ var result = this.buf.getUint8(this.newOffset(1));
+ if(result > 1){
+ throw new Error("GAF format error");
+ }
+ return result;
+};
+
+gaf.DataReader.prototype.Uint = function() {
+ return this.buf.getUint32(this.newOffset(4), true);
+};
+
+gaf.DataReader.prototype.Int = function() {
+ return this.buf.getInt32(this.newOffset(4), true);
+};
+
+gaf.DataReader.prototype.color = function() {
+ return {
+ b: this.Ubyte(),
+ g: this.Ubyte(),
+ r: this.Ubyte(),
+ a: this.Ubyte()
+ };
+};
+
+gaf.DataReader.prototype.Ushort = function() {
+ return this.buf.getUint16(this.newOffset(2), true);
+};
+
+gaf.DataReader.prototype.Float = function() {
+ return this.buf.getFloat32(this.newOffset(4), true);
+};
+
+gaf.DataReader.prototype.String = function() {
+ var strLen = this.Ushort();
+ var from = this.newOffset(strLen);
+ var to = this.getOffset();
+
+ try
+ {
+ var str = this.dataRaw.slice(from, to);
+ }
+ catch(e)
+ {
+ // Internet Explorer 10 T.T
+ if(e.message == "Object doesn't support property or method 'slice'")
+ {
+ str = [];
+ for(var i = from; i < to; ++i)
+ str.push(this.buf.getUint8(i));
+ }
+ else
+ {
+ throw(e);
+ }
+ }
+ return decodeURIComponent(escape(String.fromCharCode.apply(null, new Uint8Array(str))));
+
+};
+
+gaf.DataReader.prototype.startNestedBuffer = function(length) {
+ this.offset.push(this.offset[this.offset.length-1]);
+ this.offset[this.offset.length-2] += length;
+};
+
+gaf.DataReader.prototype.endNestedBuffer = function() {
+ if (this.offset.length == 1) throw new Error('No nested buffer available');
+ this.offset.pop();
+};
+
+gaf.DataReader.prototype.Point = function(){
+ return {
+ x: this.Float(),
+ y: this.Float()
+ };
+};
+
+gaf.DataReader.prototype.Rect = function(){
+ return {
+ x: this.Float(),
+ y: this.Float(),
+ width: this.Float(),
+ height: this.Float()
+ };
+};
+
+gaf.DataReader.prototype.Matrix = function(){
+ return {
+ a: this.Float(),
+ b: this.Float(),
+ c: this.Float(),
+ d: this.Float(),
+ tx: this.Float(),
+ ty: this.Float()
+ };
+};
+
+gaf.DataReader.prototype.seek = function(pos){
+ this.offset[this.offset.length-1] = pos;
+};
+
+gaf.DataReader.prototype.tell = function(){
+ return this.offset[this.offset.length-1];
+};
+
+/* Creates a fields parsing function
+* @ returns a function that will read from DataReader `field` of type `type`
+* @`key` - key for read data to be stored
+* @`data` - data to store. Can be DataReader function name or a function that will return a value
+* Note. Parameters pair `key` and `data` can be repeated any number of times*/
+
+gaf.DataReader.prototype.fields = function(){
+ var self = this;
+ var arguments_ = arguments;
+ return function(){
+ arguments.callee.result = {};
+ var i = 0;
+ if(arguments_.length % 2){
+ throw new Error('Number of arguments is not even');
+ }
+ while(i < arguments_.length){
+ var field = arguments_[i++];
+ var func = arguments_[i++];
+ if(typeof func === 'function'){
+ arguments.callee.result[field] = func();
+ }
+ else if (func in self && typeof self[func] === 'function'){
+ arguments.callee.result[field] = self[func].call(self);
+ }
+ else{
+ throw new Error('Object DataReader has no function `' + func + '`');
+ }
+ }
+ return arguments.callee.result;
+ }
+};
+
+/*
+* Creates a parsing function
+* @ returns function that will execute expression if caller's `result` field has `key` equal to `value` parameter
+* @ `key` - key in caller's `result` element
+* @ `value` - expected value of the `key` or a comparator function
+* @ `func` - function to execute if condition is true
+* */
+
+gaf.DataReader.prototype.condition = function(key, value, func){
+ var arguments_ = arguments;
+ return function() {
+ if(arguments_.length != 3){
+ throw new Error('Condition function');
+ }
+ var parent = arguments.callee.caller;
+ if(!('result' in parent)){
+ throw new Error('Condition function caller has no key `result`');
+ }
+ var container = parent.result;
+ var field = arguments_[0];
+ var value = arguments_[1];
+ var exec = arguments_[2];
+
+ var evaluate = null;
+ if(typeof value === 'function'){
+ evaluate = function(){return value(container[field]);};
+ }
+ else{
+ evaluate = function(){return value == container[field];};
+ }
+ if(evaluate()){
+ return exec();
+ }
+ else{
+ return null;
+ }
+ }
+};
+
+/*
+* Creates an array parsing function
+* @ returns function that will execute `func` number of times read from DataReader
+* @ `type` - type of count number
+* @ `func` - function to be executed
+* */
+
+gaf.DataReader.prototype.array = function(){
+ var self = this;
+ var arguments_ = arguments;
+ return function() {
+ arguments.callee.result = [];
+ var length = self[arguments_[0]].call(self);
+ for (var i = 0; i < length; ++i) {
+ var r = arguments_[1].call();
+ arguments.callee.result.push(r);
+ }
+ return arguments.callee.result;
+ }
+};
diff --git a/external/gaf/Library/GAFLoader.js b/external/gaf/Library/GAFLoader.js
new file mode 100644
index 0000000000..3e40c33947
--- /dev/null
+++ b/external/gaf/Library/GAFLoader.js
@@ -0,0 +1,75 @@
+var gaf = gaf || {};
+
+//@Private class
+gaf.Loader = function(){
+
+ var readHeaderBegin = function(stream, header){
+ header.compression = stream.Uint();
+ header.versionMajor = stream.Ubyte();
+ header.versionMinor = stream.Ubyte();
+ header.fileLength = stream.Uint();
+ };
+
+ var readHeaderEndV3 = function(stream, header) {
+ header.framesCount = stream.Ushort();
+ header.frameSize = stream.Rect();
+ header.pivot = stream.Point();
+ };
+
+ var readHeaderEndV4 = function(stream, header){
+ var scaleCount = stream.Uint();
+ header.scaleValues = [];
+ for(var i = 0; i < scaleCount; ++i){
+ header.scaleValues.push(stream.Float());
+ }
+ var csfCount = stream.Uint();
+ header.csfValues = [];
+ for(var i = 0; i < csfCount; ++i){
+ header.csfValues.push(stream.Float());
+ }
+ };
+
+ this.LoadFile = function(filePath, onLoaded){
+ var oReq = new XMLHttpRequest();
+ oReq.open("GET", filePath, true);
+ var self = this;
+ oReq.responseType = "arraybuffer";
+ oReq.onload = function(oEvent) {
+ var gaf_data = new gaf.DataReader(oReq.response);
+ var gafFile = self.LoadStream(gaf_data);
+ if(onLoaded)
+ onLoaded(gafFile);
+ };
+ oReq.send();
+ };
+
+ this.LoadStream = function(stream){
+ var header = {};
+ readHeaderBegin(stream, header);
+ if(header.compression == gaf.COMPRESSION_NONE) { // GAF
+ }
+ else if(header.compression == gaf.COMPRESSION_ZIP){ // GAC
+ var compressed = stream.dataRaw.slice(stream.tell());
+
+ var inflate = new window.Zlib.Inflate(new Uint8Array(compressed));
+ var decompressed = inflate.decompress();
+ stream = new gaf.DataReader(decompressed.buffer);
+ }
+ else{
+ throw new Error("GAF syntax error.");
+ }
+
+ if(header.versionMajor < 4){
+ readHeaderEndV3(stream, header);
+ }
+ else{
+ readHeaderEndV4(stream, header);
+ }
+
+ var tags = gaf.ReadTags(stream);
+ return {
+ header: header,
+ tags: tags
+ };
+ };
+};
diff --git a/external/gaf/Library/GAFMask.js b/external/gaf/Library/GAFMask.js
new file mode 100644
index 0000000000..34ca20681c
--- /dev/null
+++ b/external/gaf/Library/GAFMask.js
@@ -0,0 +1,36 @@
+
+gaf.Mask = gaf.Object.extend
+({
+ _className: "GAFMask",
+ _clippingNode: null,
+
+ ctor : function(gafSpriteProto)
+ {
+ this._super();
+ cc.assert(gafSpriteProto, "Error! Missing mandatory parameter.");
+ this._gafproto = gafSpriteProto;
+ },
+
+ _init : function()
+ {
+ var maskNodeProto = this._gafproto.getMaskNodeProto();
+ cc.assert(maskNodeProto, "Error. Mask node for id ref " + this._gafproto.getIdRef() + " not found.");
+ this._maskNode = maskNodeProto._gafConstruct();
+ this._clippingNode = cc.ClippingNode.create(this._maskNode);
+ this._clippingNode.setAlphaThreshold(0.5);
+ this.addChild(this._clippingNode);
+ },
+
+ setExternalTransform : function(affineTransform)
+ {
+ if(!cc.affineTransformEqualToTransform(this._maskNode._additionalTransform, affineTransform))
+ {
+ this._maskNode.setAdditionalTransform(affineTransform);
+ }
+ },
+
+ _getNode : function()
+ {
+ return this._clippingNode;
+ }
+});
\ No newline at end of file
diff --git a/external/gaf/Library/GAFMaskProto.js b/external/gaf/Library/GAFMaskProto.js
new file mode 100644
index 0000000000..6074fd1279
--- /dev/null
+++ b/external/gaf/Library/GAFMaskProto.js
@@ -0,0 +1,16 @@
+
+gaf._MaskProto = function(asset, mask, idRef)
+{
+ this.getIdRef = function(){return idRef};
+ this.getMaskNodeProto = function() {return mask};
+
+ /*
+ * Will construct GAFMask
+ */
+ this._gafConstruct = function()
+ {
+ var ret = new gaf.Mask(this);
+ ret._init();
+ return ret;
+ };
+};
diff --git a/external/gaf/Library/GAFObject.js b/external/gaf/Library/GAFObject.js
new file mode 100644
index 0000000000..7d5375abe5
--- /dev/null
+++ b/external/gaf/Library/GAFObject.js
@@ -0,0 +1,426 @@
+var gaf = gaf || {};
+
+gaf._stateHasCtx = function(state)
+{
+ // Check for tint color offset
+ if( state.hasColorTransform &&
+ (state.colorTransform.offset.r > 0 ||
+ state.colorTransform.offset.g > 0 ||
+ state.colorTransform.offset.b > 0 ||
+ state.colorTransform.offset.a > 0)
+ )
+ {
+ return true;
+ }
+
+ // Check for color transform filter
+ if(state.hasEffect)
+ {
+ for(var i = 0, total = state.effect.length; i < total; ++i)
+ {
+ if(state.effect[i].type === gaf.EFFECT_COLOR_MATRIX)
+ return true;
+ }
+ }
+ return false;
+};
+
+gaf.Object = cc.Node.extend
+({
+ _asset : null,
+ _className : "GAFObject",
+ _id : gaf.IDNONE,
+ _gafproto : null,
+ _parentTimeLine : null,
+ _lastVisibleInFrame : 0,
+ _filterStack : null,
+ _cascadeColorMult : null,
+ _cascadeColorOffset : null,
+ _needsCtx : false,
+ _usedAtlasScale: 1,
+
+ // Public methods
+ ctor: function(scale)
+ {
+ if(arguments.length == 1)
+ {
+ this._usedAtlasScale = scale;
+ }
+ this._super();
+ this._cascadeColorMult = cc.color(255, 255, 255, 255);
+ this._cascadeColorOffset = cc.color(0, 0, 0, 0);
+ this._filterStack = [];
+ },
+
+ /**
+ * @method setAnimationStartedNextLoopDelegate
+ * @param {function(Object)} delegate
+ */
+ setAnimationStartedNextLoopDelegate : function (delegate) {},
+
+ /**
+ * @method setAnimationFinishedPlayDelegate
+ * @param {function(Object)} delegate
+ */
+ setAnimationFinishedPlayDelegate : function (delegate) {},
+
+ /**
+ * @method setLooped
+ * @param {bool} looped
+ */
+ setLooped : function (looped) {},
+
+ /**
+ * @method getBoundingBoxForCurrentFrame
+ * @return {cc.Rect}
+ */
+ getBoundingBoxForCurrentFrame : function () {return null;},
+
+ /**
+ * @method setFps
+ * @param {uint} fps
+ */
+ setFps : function (fps) {},
+
+ /**
+ * @method getObjectByName
+ * @param {String} name - name of the object to find
+ * @return {gaf.Object}
+ */
+ getObjectByName : function (name) {return null;},
+
+ /**
+ * @method clearSequence
+ */
+ clearSequence : function () {},
+
+ /**
+ * @method getIsAnimationRunning
+ * @return {bool}
+ */
+ getIsAnimationRunning : function () {return false;},
+
+ /**
+ * @method getSequences
+ * @return [string] - list of sequences if has any
+ */
+ getSequences : function(){return [];},
+
+
+ /**
+ * @method gotoAndStop
+ * @param {uint|String} value - label ot frame number
+ * @return {bool}
+ */
+ gotoAndStop : function (value) {},
+
+ /**
+ * @method getStartFrame
+ * @param {String} frameLabel
+ * @return {uint}
+ */
+ getStartFrame : function (frameLabel) {return gaf.IDNONE;},
+
+ /**
+ * @method setFramePlayedDelegate
+ * @param {function(Object, frame)} delegate
+ */
+ setFramePlayedDelegate : function (delegate) {},
+
+ /**
+ * @method getCurrentFrameIndex
+ * @return {uint}
+ */
+ getCurrentFrameIndex : function () {
+ return gaf.IDNONE;
+ },
+
+ /**
+ * @method getTotalFrameCount
+ * @return {uint}
+ */
+ getTotalFrameCount : function () {return 0;},
+
+ /**
+ * @method start
+ */
+ start : function () {},
+
+ /**
+ * @method stop
+ */
+ stop : function () {},
+
+ /**
+ * @method isVisibleInCurrentFrame
+ * @return {bool}
+ */
+ isVisibleInCurrentFrame : function ()
+ {
+ /*if (this._parentTimeLine &&
+ ((this._parentTimeLine.getCurrentFrameIndex() + 1) != this._lastVisibleInFrame))
+ {
+ return false;
+ }
+ else
+ {
+ return true;
+ }*/
+ return !(this._parentTimeLine && ((this._parentTimeLine.getCurrentFrameIndex() + 1) != this._lastVisibleInFrame));
+ },
+
+ /**
+ * @method isDone
+ * @return {bool}
+ */
+ isDone : function () {return true;},
+
+ /**
+ * @method playSequence
+ * @param {String} name - name of the sequence to play
+ * @param {bool} looped - play looped
+ * @param {bool} resume - whether to resume animation if stopped. True by default
+ * @return {bool}
+ */
+ playSequence : function (name, looped, resume) {return false;},
+
+ /**
+ * @method isReversed
+ * @return {bool}
+ */
+ isReversed : function () {return false;},
+
+ /**
+ * @method setSequenceDelegate
+ * @param {function(Object, sequenceName)} delegate
+ */
+ setSequenceDelegate : function (delegate) {},
+
+ /**
+ * @method setFrame
+ * @param {uint} index
+ * @return {bool}
+ */
+ setFrame : function (index) {return false;},
+
+ /**
+ * @method setControlDelegate
+ * @param {function} func
+ */
+ setControlDelegate : function (func) {},
+
+ /**
+ * @method getEndFrame
+ * @param {String} frameLabel
+ * @return {uint}
+ */
+ getEndFrame : function (frameLabel) {return gaf.IDNONE;},
+
+ /**
+ * @method pauseAnimation
+ */
+ pauseAnimation : function () {},
+
+ /**
+ * @method gotoAndPlay
+ * @param {uint|String} value - label ot frame number
+ * @return {bool}
+ */
+ gotoAndPlay : function (value) {},
+
+ /**
+ * @method isLooped
+ * @return {bool}
+ */
+ isLooped : function () {return false;},
+
+ /**
+ * @method resumeAnimation
+ */
+ resumeAnimation : function () {},
+
+ /**
+ * @method setReversed
+ * @param {bool} reversed
+ */
+ setReversed : function (reversed) {},
+
+ /**
+ * @method hasSequences
+ * @return {bool}
+ */
+ hasSequences : function () {return false;},
+
+ /**
+ * @method getFps
+ * @return {uint}
+ */
+ getFps : function () {return 60;},
+
+ /**
+ * @method setLocator
+ * @param {bool} locator
+ * Locator object will not draw itself, but its children will be drawn
+ */
+ setLocator : function (locator){},
+
+ setExternalTransform : function(affineTransform)
+ {
+ if(!cc.affineTransformEqualToTransform(this._additionalTransform, affineTransform))
+ {
+ this.setAdditionalTransform(affineTransform);
+ }
+ },
+
+ getExternalTransform : function()
+ {
+ return this._additionalTransform;
+ },
+
+ setAnimationRunning: function () {},
+
+ ////////////////
+ // Private
+ ////////////////
+ _enableTick: function(val){},
+
+ _resetState : function()
+ {},
+
+ _updateVisibility : function(state, parent)
+ {
+ var alphaOffset = state.hasColorTransform ? state.colorTransform.offset.a : 0;
+ this.setOpacity(state.alpha + alphaOffset);
+ //return this.isVisible();
+ },
+
+ // @Override
+ isVisible : function()
+ {
+ return this.getOpacity() > 0;
+ },
+
+ // @Override
+ visit: function(parentCmd)
+ {
+ if(this.isVisibleInCurrentFrame())
+ {
+ this._super(parentCmd);
+ }
+ },
+
+ _getFilters : function(){return null},
+
+ _processAnimation : function(){},
+
+
+ _applyState : function(state, parent)
+ {
+ this._applyStateSuper(state, parent);
+ },
+
+ _applyStateSuper : function(state, parent)
+ {
+ this._needsCtx = parent._needsCtx;
+ this._filterStack.length = 0; // clear
+ this._parentTimeLine = parent; // only gaf time line can call applyState. Assign it as parent
+ if(this._usedAtlasScale != 1)
+ {
+ var newMat = cc.clone(state.matrix);
+ newMat.tx *= this._usedAtlasScale;
+ newMat.ty *= this._usedAtlasScale;
+ this.setExternalTransform(newMat); // apply transformations of the state
+ }
+ else
+ {
+ this.setExternalTransform(state.matrix); // apply transformations of the state
+ }
+ // Cascade filters
+ // TODO: apply more than one filter
+ if (state.hasEffect) {
+ this._filterStack = this._filterStack.concat(state.effect);
+ this._needsCtx = true;
+ }
+ if (parent._filterStack && parent._filterStack.length > 0) {
+ this._filterStack = this._filterStack.concat(parent._filterStack);
+ }
+
+ if(this._filterStack.length > 0 && this._filterStack[0].type === gaf.EFFECT_COLOR_MATRIX)
+ {
+ this._needsCtx = true;
+ }
+
+ // Cascade color transformations
+
+ // If state has a tint, then we should process it
+ if (state.hasColorTransform)
+ {
+ this._cascadeColorMult.r = state.colorTransform.mult.r * parent._cascadeColorMult.r / 255;
+ this._cascadeColorMult.g = state.colorTransform.mult.g * parent._cascadeColorMult.g / 255;
+ this._cascadeColorMult.b = state.colorTransform.mult.b * parent._cascadeColorMult.b / 255;
+ this._cascadeColorMult.a = state.colorTransform.mult.a * parent._cascadeColorMult.a / 255;
+
+ this._cascadeColorOffset.r = state.colorTransform.offset.r + parent._cascadeColorOffset.r;
+ this._cascadeColorOffset.g = state.colorTransform.offset.g + parent._cascadeColorOffset.g;
+ this._cascadeColorOffset.b = state.colorTransform.offset.b + parent._cascadeColorOffset.b;
+ this._cascadeColorOffset.a = state.colorTransform.offset.a + parent._cascadeColorOffset.a;
+ }
+ else
+ {
+ this._cascadeColorMult.r = parent._cascadeColorMult.r;
+ this._cascadeColorMult.g = parent._cascadeColorMult.g;
+ this._cascadeColorMult.b = parent._cascadeColorMult.b;
+ this._cascadeColorMult.a = state.alpha * (parent._cascadeColorMult.a / 255);
+
+ this._cascadeColorOffset.r = parent._cascadeColorOffset.r;
+ this._cascadeColorOffset.g = parent._cascadeColorOffset.g;
+ this._cascadeColorOffset.b = parent._cascadeColorOffset.b;
+ this._cascadeColorOffset.a = parent._cascadeColorOffset.a;
+ }
+
+ if (this._cascadeColorOffset.r > 0 ||
+ this._cascadeColorOffset.g > 0 ||
+ this._cascadeColorOffset.b > 0 ||
+ this._cascadeColorOffset.a > 0)
+ {
+ this._needsCtx = true;
+ }
+ },
+
+ _initRendererCmd: function()
+ {
+ this._renderCmd = cc.renderer.getRenderCmd(this);
+ this._renderCmd._visit = this._renderCmd.visit;
+ var self = this;
+ this._renderCmd.visit = function(parentCmd) {
+ if(self.isVisibleInCurrentFrame()){
+ this._visit(parentCmd);
+ }
+ }
+ },
+
+ _getNode : function()
+ {
+ return this;
+ },
+
+ setAnchorPoint : function(point, y)
+ {
+ if (y === undefined)
+ {
+ this._super(point.x, point.y - 1);
+ }
+ else
+ {
+ this._super(point, y - 1);
+ }
+ }
+
+});
+
+gaf.Object._createNullObject = function()
+{
+ var ret = new gaf.Object();
+ ret.isVisible = function(){return true};
+ return ret;
+};
diff --git a/external/gaf/Library/GAFShaderManager.js b/external/gaf/Library/GAFShaderManager.js
new file mode 100644
index 0000000000..49b7ffba0f
--- /dev/null
+++ b/external/gaf/Library/GAFShaderManager.js
@@ -0,0 +1,63 @@
+
+gaf._glShaderInit = function() {
+ gaf._Uniforms = {
+ ColorTransformMult: -1,
+ ColorTransformOffset: -1,
+ ColorMatrixBody: -1,
+ ColorMatrixAppendix: -1,
+ BlurTexelOffset: -1,
+ GlowTexelOffset: -1,
+ GlowColor: -1
+ };
+
+ gaf._shaderCreate = function (fs, vs) {
+ var program = new cc.GLProgram();
+ var result = program.initWithVertexShaderByteArray(vs, fs);
+ cc.assert(result, "Shader init error");
+ program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
+ program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR);
+ program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
+ result = program.link();
+ cc.assert(result, "Shader linking error");
+ program.updateUniforms();
+ return program;
+ };
+
+ gaf._shaderCreateAlpha = function () {
+ var program = gaf._shaderCreate(gaf.SHADER_COLOR_MATRIX_FRAG, cc.SHADER_POSITION_TEXTURE_COLOR_VERT);
+ gaf._Uniforms.ColorTransformMult = program.getUniformLocationForName(gaf.UNIFORM_ALPHA_TINT_MULT);
+ gaf._Uniforms.ColorTransformOffset = program.getUniformLocationForName(gaf.UNIFORM_ALPHA_TINT_OFFSET);
+ gaf._Uniforms.ColorMatrixBody = program.getUniformLocationForName(gaf.UNIFORM_ALPHA_COLOR_MATRIX_BODY);
+ gaf._Uniforms.ColorMatrixAppendix = program.getUniformLocationForName(gaf.UNIFORM_ALPHA_COLOR_MATRIX_APPENDIX);
+ return program;
+ };
+
+ gaf._shaderCreateBlur = function () {
+ var program = gaf._shaderCreate(gaf.SHADER_GAUSSIAN_BLUR_FRAG, cc.SHADER_POSITION_TEXTURE_COLOR_VERT);
+ gaf._Uniforms.BlurTexelOffset = program._glContext.getUniformLocation(program._programObj, gaf.UNIFORM_BLUR_TEXEL_OFFSET);
+
+ return program;
+ };
+
+ gaf._shaderCreateGlow = function () {
+ var program = gaf._shaderCreate(gaf.SHADER_GLOW_FRAG, cc.SHADER_POSITION_TEXTURE_COLOR_VERT);
+ gaf._Uniforms.GlowTexelOffset = program._glContext.getUniformLocation(program._programObj, gaf.UNIFORM_GLOW_TEXEL_OFFSET);
+ gaf._Uniforms.GlowColor = program._glContext.getUniformLocation(program._programObj, gaf.UNIFORM_GLOW_COLOR);
+ return program;
+ };
+
+ gaf._Shaders = {
+ Alpha: gaf._shaderCreateAlpha(),
+ Blur: gaf._shaderCreateBlur(),
+ Glow: gaf._shaderCreateGlow()
+ };
+};
+
+gaf._setupShaders = function() {
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
+ gaf._glShaderInit();
+ }
+ else {
+ delete gaf._glShaderInit;
+ }
+};
diff --git a/external/gaf/Library/GAFShaders.js b/external/gaf/Library/GAFShaders.js
new file mode 100644
index 0000000000..7d91537285
--- /dev/null
+++ b/external/gaf/Library/GAFShaders.js
@@ -0,0 +1,58 @@
+gaf.SHADER_GAUSSIAN_BLUR_FRAG =
+ "varying mediump vec2 v_texCoord;\n"
+ + "uniform mediump vec2 u_step;\n"
+ + "void main()\n"
+ + "{ \n"
+ + " mediump vec4 sum = vec4(0.0); \n"
+ + " sum += texture2D(CC_Texture0, v_texCoord - u_step * 4.0) * 0.05; \n"
+ + " sum += texture2D(CC_Texture0, v_texCoord - u_step * 3.0) * 0.09; \n"
+ + " sum += texture2D(CC_Texture0, v_texCoord - u_step * 2.0) * 0.12; \n"
+ + " sum += texture2D(CC_Texture0, v_texCoord - u_step * 1.0) * 0.15; \n"
+ + " sum += texture2D(CC_Texture0, v_texCoord + u_step * 0.0) * 0.18; \n"
+ + " sum += texture2D(CC_Texture0, v_texCoord + u_step * 1.0) * 0.15; \n"
+ + " sum += texture2D(CC_Texture0, v_texCoord + u_step * 2.0) * 0.12; \n"
+ + " sum += texture2D(CC_Texture0, v_texCoord + u_step * 3.0) * 0.09; \n"
+ + " sum += texture2D(CC_Texture0, v_texCoord + u_step * 4.0) * 0.05; \n"
+ + " gl_FragColor = sum; \n"
+ + "} \n";
+
+gaf.SHADER_GLOW_FRAG =
+ "varying mediump vec2 v_texCoord;\n"
+ + "uniform mediump vec2 u_step;\n"
+ + "uniform mediump vec4 u_glowColor;\n"
+ + "void main()\n"
+ + "{ \n"
+ + " mediump vec4 sum = vec4(0.0); \n"
+ + " sum += texture2D(CC_Texture0, v_texCoord - u_step * 4.0) * 0.05; \n"
+ + " sum += texture2D(CC_Texture0, v_texCoord - u_step * 3.0) * 0.09; \n"
+ + " sum += texture2D(CC_Texture0, v_texCoord - u_step * 2.0) * 0.12; \n"
+ + " sum += texture2D(CC_Texture0, v_texCoord - u_step * 1.0) * 0.15; \n"
+ + " sum += texture2D(CC_Texture0, v_texCoord + u_step * 0.0) * 0.18; \n"
+ + " sum += texture2D(CC_Texture0, v_texCoord + u_step * 1.0) * 0.15; \n"
+ + " sum += texture2D(CC_Texture0, v_texCoord + u_step * 2.0) * 0.12; \n"
+ + " sum += texture2D(CC_Texture0, v_texCoord + u_step * 3.0) * 0.09; \n"
+ + " sum += texture2D(CC_Texture0, v_texCoord + u_step * 4.0) * 0.05; \n"
+ + " gl_FragColor = sum * u_glowColor; \n"
+ + "} \n";
+
+gaf.SHADER_COLOR_MATRIX_FRAG =
+ "varying mediump vec2 v_texCoord;\n"
+ + "varying mediump vec4 v_fragmentColor;\n"
+ + "uniform mediump vec4 colorTransformMult;\n"
+ + "uniform mediump vec4 colorTransformOffsets;\n"
+ + "uniform mediump mat4 colorMatrix;\n"
+ + "uniform mediump vec4 colorMatrix2;\n"
+ + "void main()\n"
+ + "{ \n"
+ + " vec4 texColor = texture2D(CC_Texture0, v_texCoord); \n"
+ + " const float kMinimalAlphaAllowed = 1.0e-8; \n"
+ + " if (texColor.a > kMinimalAlphaAllowed) \n"
+ + " { \n"
+ + " texColor = vec4(texColor.rgb / texColor.a, texColor.a); \n"
+ + " vec4 ctxColor = texColor * colorTransformMult + colorTransformOffsets; \n"
+ + " vec4 adjustColor = colorMatrix * ctxColor + colorMatrix2; \n"
+ + " adjustColor *= v_fragmentColor; \n"
+ + " texColor = vec4(adjustColor.rgb * adjustColor.a, adjustColor.a); \n"
+ + " } \n"
+ + " gl_FragColor = texColor; \n"
+ + "}\n";
diff --git a/external/gaf/Library/GAFSprite.js b/external/gaf/Library/GAFSprite.js
new file mode 100644
index 0000000000..2387bf92df
--- /dev/null
+++ b/external/gaf/Library/GAFSprite.js
@@ -0,0 +1,100 @@
+
+gaf.Sprite = gaf.Object.extend
+({
+ _className: "GAFSprite",
+
+ _hasCtx: false,
+ _hasFilter: false,
+
+ ctor : function(gafSpriteProto, usedScale)
+ {
+ this._super(usedScale);
+ cc.assert(gafSpriteProto, "Error! Missing mandatory parameter.");
+ this._gafproto = gafSpriteProto;
+ },
+
+ // Private
+
+ _init : function()
+ {
+ var frame = this._gafproto.getFrame();
+ cc.assert(frame instanceof cc.SpriteFrame, "Error. Wrong object type.");
+
+ // Create sprite with custom render command from frame
+ this._sprite = new cc.Sprite();
+ this._sprite._renderCmd = this._gafCreateRenderCmd(this._sprite);
+ this._sprite.initWithSpriteFrame(frame);
+
+ this._sprite.setAnchorPoint(this._gafproto.getAnchor());
+ this.addChild(this._sprite);
+ //this._sprite.setCascadeColorEnabled(true);
+ //this._sprite.setCascadeOpacityEnabled(true);
+ this._sprite.setOpacityModifyRGB(true);
+
+ if(cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ this._sprite.setBlendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ },
+
+ _applyState : function(state, parent)
+ {
+ this._applyStateSuper(state, parent);
+ if(this._needsCtx)
+ {
+ // Enable ctx state if wasn't enabled
+ if(!this._hasCtx)
+ {
+ this._enableCtx();
+ this._hasCtx = true;
+ }
+ // Set ctx shader
+ this._applyCtxState(state);
+ }
+ else
+ {
+ // Disable ctx state if was enabled
+ if(this._hasCtx)
+ {
+ this._disableCtx();
+ this._hasCtx = false;
+ }
+ // Apply color
+ if(!cc.colorEqual(this._sprite._realColor, this._cascadeColorMult))
+ {
+ this._sprite.setColor(this._cascadeColorMult);
+ }
+ // Apply opacity
+ if(this._sprite.getOpacity() != this._cascadeColorMult.a)
+ {
+ this._sprite.setOpacity(this._cascadeColorMult.a);
+ }
+
+ }
+ },
+
+ _enableCtx: function()
+ {
+ this._sprite._renderCmd._enableCtx();
+ },
+
+ _disableCtx: function()
+ {
+ this._sprite._renderCmd._disableCtx();
+ },
+
+ _applyCtxState: function(state){
+ this._sprite._renderCmd._applyCtxState(this);
+ },
+
+ getBoundingBoxForCurrentFrame: function ()
+ {
+ var result = this._sprite.getBoundingBox();
+ return cc._rectApplyAffineTransformIn(result, this.getNodeToParentTransform());
+ },
+
+ _gafCreateRenderCmd: function(item){
+ if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ return new gaf.Sprite.CanvasRenderCmd(item);
+ else
+ return new gaf.Sprite.WebGLRenderCmd(item);
+ }
+});
diff --git a/external/gaf/Library/GAFSpriteCanvasRenderCmd.js b/external/gaf/Library/GAFSpriteCanvasRenderCmd.js
new file mode 100644
index 0000000000..bb807cc220
--- /dev/null
+++ b/external/gaf/Library/GAFSpriteCanvasRenderCmd.js
@@ -0,0 +1,233 @@
+
+(function() {
+ gaf.Sprite.CanvasRenderCmd = function (renderable) {
+ cc.Sprite.CanvasRenderCmd.call(this, renderable);
+ this._hasTintMult = false;
+ this._hasTintOffset = false;
+ this._hasCtx = false;
+ this._tintMult = cc.color(255,255,255,255);
+ this._tintOffset = cc.color(0,0,0,0);
+ this._textureDirty = false;
+ };
+ var proto = gaf.Sprite.CanvasRenderCmd.prototype = Object.create(cc.Sprite.CanvasRenderCmd.prototype);
+ proto.constructor = gaf.Sprite.CanvasRenderCmd;
+
+ proto._disableCtx = function(){
+ this._hasTintOffset = false;
+ this._hasCtx = false;
+ this._textureDirty = true;
+ this.setDirtyFlag(cc.Node._dirtyFlags.colorDirty);
+ this._tintMult = cc.color(255,255,255,255);
+ this._tintOffset = cc.color(0,0,0,0);
+ };
+
+ proto._enableCtx = function(){
+
+ };
+
+ proto._applyCtxState = function(gafObject){
+
+ var tintMult = gafObject._cascadeColorMult;
+ var tintOffset = gafObject._cascadeColorOffset;
+ var opacity = tintMult.a;
+
+ // Apply opacity
+ if(this._node.getOpacity() != opacity)
+ {
+ this._node.setOpacity(opacity);
+ }
+
+ // Check Tint multiplicator
+ var multDirty = !cc.colorEqual(this._tintMult, tintMult);
+ if(multDirty)
+ {
+ this._node.setColor(tintMult);
+ this._tintMult = tintMult;
+ this._hasTintMult =
+ (tintMult.r !== 255 ||
+ tintMult.g !== 255 ||
+ tintMult.b !== 255 );
+ }
+
+ // Check Tint offset
+ var offfsetDirty =
+ (this._tintOffset.r != tintOffset.r) ||
+ (this._tintOffset.g != tintOffset.g) ||
+ (this._tintOffset.b != tintOffset.b) ||
+ (this._tintOffset.a != tintOffset.a);
+
+ if(offfsetDirty)
+ {
+ this._tintOffset = tintOffset;
+ this._hasTintOffset =
+ (tintOffset.r !== 0 ||
+ tintOffset.g !== 0 ||
+ tintOffset.b !== 0 ||
+ tintOffset.a !== 0 );
+ }
+
+ // Update dirty flag
+ this._textureDirty = multDirty || offfsetDirty;
+ if(this._textureDirty)
+ {
+ this.setDirtyFlag(cc.Node._dirtyFlags.colorDirty);
+ }
+
+
+ this._hasCtx = gafObject._filterStack.length > 0 && gafObject._filterStack[0].type === gaf.EFFECT_COLOR_MATRIX;
+
+ };
+
+ proto.rendering = function(ctx, scaleX, scaleY)
+ {
+ var node = this._node;
+ var locTextureCoord = this._textureCoord,
+ alpha = (this._displayedOpacity / 255);
+
+ if ((node._texture && ((locTextureCoord.width === 0 || locTextureCoord.height === 0) //set texture but the texture isn't loaded.
+ || !node._texture._textureLoaded)) || alpha === 0)
+ return;
+
+ var wrapper = ctx || cc._renderContext,
+ context = wrapper.getContext();
+ var locX = node._offsetPosition.x,
+ locHeight = node._rect.height,
+ locWidth = node._rect.width,
+ locY = -node._offsetPosition.y - locHeight,
+ image;
+
+ wrapper.setTransform(this._worldTransform, scaleX, scaleY);
+ wrapper.setCompositeOperation(this._blendFuncStr);
+ wrapper.setGlobalAlpha(alpha);
+
+ if(node._flippedX || node._flippedY)
+ wrapper.save();
+ if (node._flippedX) {
+ locX = -locX - locWidth;
+ context.scale(-1, 1);
+ }
+ if (node._flippedY) {
+ locY = node._offsetPosition.y;
+ context.scale(1, -1);
+ }
+
+ image = node._texture._htmlElementObj;
+
+ if (this._colorized) {
+ context.drawImage(image,
+ 0, 0, locTextureCoord.width,locTextureCoord.height,
+ locX * scaleX,locY * scaleY, locWidth * scaleX, locHeight * scaleY);
+ } else {
+ context.drawImage(image,
+ locTextureCoord.renderX, locTextureCoord.renderY, locTextureCoord.width, locTextureCoord.height,
+ locX * scaleX, locY * scaleY, locWidth * scaleX, locHeight * scaleY);
+ }
+
+ if(node._flippedX || node._flippedY)
+ wrapper.restore();
+ cc.g_NumberOfDraws++;
+ };
+
+ if(cc.sys._supportCanvasNewBlendModes){
+ proto._updateColor = function () {
+ var displayedColor = this._displayedColor, node = this._node;
+ this._hasTintMult |= (displayedColor.r !== 255 || displayedColor.g !== 255 || displayedColor.b !== 255);
+
+ // If no color changes
+ if(this._textureDirty)
+ {
+ this._textureDirty = false;
+ if (this._colorized) {
+ this._colorized = false;
+ node.texture = this._originalTexture;
+ }
+ }
+ else
+ {
+ return;
+ }
+
+ var locElement, locTexture = node._texture, locRect = this._textureCoord;
+ if(this._hasTintMult)
+ {
+ if (locTexture && locRect.validRect && this._originalTexture) {
+ locElement = locTexture.getHtmlElementObj();
+ if (!locElement)
+ return;
+
+ this._colorized = true;
+ if (this._hasTintOffset || this._hasCtx) displayedColor = this._tintMult;
+
+ locElement = cc.Sprite.CanvasRenderCmd._generateTintImageWithMultiply(this._originalTexture._htmlElementObj, displayedColor, locRect);
+ locTexture = new cc.Texture2D();
+ locTexture.initWithElement(locElement);
+ locTexture.handleLoadedTexture();
+ node.texture = locTexture;
+ }
+ }
+
+ locTexture = node._texture;
+ if(this._hasTintOffset)
+ {
+ var cacheTextureForColor = cc.textureCache.getTextureColors(this._originalTexture.getHtmlElementObj());
+ if (locTexture && locRect.validRect && this._originalTexture) {
+ locElement = locTexture.getHtmlElementObj();
+ if (!locElement)
+ return;
+ if(this._colorized)
+ var texRect = cc.rect(0,0,locRect.width, locRect.height);
+ else
+ texRect = locRect;
+ locElement = this._gafGenerateTintImage(node.texture._htmlElementObj, texRect, cacheTextureForColor, this._tintOffset, locRect);
+ locTexture = new cc.Texture2D();
+ locTexture.initWithElement(locElement);
+ locTexture.handleLoadedTexture();
+ node.texture = locTexture;
+ this._colorized = true;
+ }
+ }
+
+
+ };
+
+ proto._gafGenerateTintImage = function(texture, texRect, tintedImgCache, color, rect, renderCanvas){
+ if (!rect)
+ rect = cc.rect(0, 0, texture.width, texture.height);
+
+ // Create a new buffer if required
+ var w = Math.min(rect.width, tintedImgCache[0].width);
+ var h = Math.min(rect.height, tintedImgCache[0].height);
+ var buff = renderCanvas, ctx;
+ if (!buff) {
+ buff = document.createElement("canvas");
+ buff.width = w;
+ buff.height = h;
+ ctx = buff.getContext("2d");
+ } else {
+ ctx = buff.getContext("2d");
+ ctx.clearRect(0, 0, w, h);
+ }
+ ctx.save();
+
+ // draw a channel with alpha of the original image
+ ctx.globalCompositeOperation = 'source-over';
+ //ctx.globalAlpha = 1;
+ ctx.drawImage(tintedImgCache[2], rect.x, rect.y, w, h, 0, 0, w, h);
+
+ // draw a rect of specified color
+ ctx.globalCompositeOperation = 'source-in';
+ ctx.fillStyle = 'rgba(' + Math.round(color.r) + ',' + Math.round(color.g) + ',' + Math.round(color.b) + ',1)';
+ ctx.fillRect(0, 0, w, h);
+
+ // add the desired image to the drawn
+ ctx.globalCompositeOperation = 'lighter';
+ ctx.drawImage(texture, texRect.x, texRect.y, w, h, 0, 0, w, h);
+
+
+ ctx.restore();
+ return buff;
+
+ };
+ }
+
+})();
diff --git a/external/gaf/Library/GAFSpriteProto.js b/external/gaf/Library/GAFSpriteProto.js
new file mode 100644
index 0000000000..6e33fa7d5f
--- /dev/null
+++ b/external/gaf/Library/GAFSpriteProto.js
@@ -0,0 +1,36 @@
+
+gaf._SpriteProto = function(asset, atlasFrames, elementAtlasIdRef)
+{
+ //this._anchor = atlasFrame._gafAnchor;
+ //delete atlasFrame._gafAnchor;
+
+ this.getFrames = function(){return atlasFrames};
+ this.getIdRef = function(){return elementAtlasIdRef};
+ //this.getAnchor = function() {return this._anchor};
+ this.getAsset = function() {return asset};
+
+ /*
+ * Will construct GAFSprite
+ */
+ this._gafConstruct = function()
+ {
+ var usedScale = this.getAsset()._usedAtlasScale;
+ var ret = new gaf.Sprite(this, usedScale);
+ ret._init();
+ return ret;
+ };
+};
+
+gaf._SpriteProto.prototype.getFrame = function()
+{
+ var usedScale = this.getAsset()._usedAtlasScale;
+ cc.assert(usedScale, "Error. Atlas scale zero.");
+ var frames = this.getFrames()[usedScale];
+ cc.assert(frames, "Error. No frames found for used scale `"+usedScale+"`");
+ return frames[this.getIdRef()];
+};
+
+gaf._SpriteProto.prototype.getAnchor = function()
+{
+ return this.getFrame()._gafAnchor;
+};
diff --git a/external/gaf/Library/GAFSpriteWebGLRenderCmd.js b/external/gaf/Library/GAFSpriteWebGLRenderCmd.js
new file mode 100644
index 0000000000..eabe25b0c9
--- /dev/null
+++ b/external/gaf/Library/GAFSpriteWebGLRenderCmd.js
@@ -0,0 +1,132 @@
+
+(function(){
+ gaf.Sprite.WebGLRenderCmd = function (renderable) {
+ cc.Sprite.WebGLRenderCmd.call(this, renderable);
+ this._defualtShader = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURECOLOR);
+ this._customShader = gaf._Shaders.Alpha;
+
+ //this._shaderProgram = this._defualtShader;
+
+ this._tintMult = null;
+ this._tintOffset = null;
+ this._ctxMatrixBody = null;
+ this._ctxMatrixAppendix = null;
+ };
+
+ var proto = gaf.Sprite.WebGLRenderCmd.prototype = Object.create(cc.Sprite.WebGLRenderCmd.prototype);
+ proto.constructor = gaf.Sprite.WebGLRenderCmd;
+
+ proto._identityVec = [1.0, 1.0, 1.0, 1.0];
+ proto._zeroVec = [0.0, 0.0, 0.0, 0.0];
+ proto._identityMat = [
+ 1, 0, 0, 0,
+ 0, 1, 0, 0,
+ 0, 0, 1, 0,
+ 0, 0, 0, 1
+ ];
+
+ proto._disableCtx = function(){
+ this.setShaderProgram(this._defualtShader);
+ };
+
+ proto._enableCtx = function(){
+ this.setShaderProgram(this._customShader);
+ };
+
+ proto._applyCtxState = function(gafObject){
+ var tintMult = gafObject._cascadeColorMult;
+ this._tintMult = [
+ tintMult.r / 255,
+ tintMult.g / 255,
+ tintMult.b / 255,
+ tintMult.a / 255
+ ];
+
+ var tintOffset = gafObject._cascadeColorOffset;
+ this._tintOffset = [
+ tintOffset.r / 255,
+ tintOffset.g / 255,
+ tintOffset.b / 255,
+ tintOffset.a / 255
+ ];
+
+ var filterStack = gafObject._filterStack;
+ if(filterStack && filterStack.length > 0 && filterStack[0].type === gaf.EFFECT_COLOR_MATRIX)
+ {
+ var m = filterStack[0].colorMatrix;
+ this._ctxMatrixBody = [
+ m.rr, m.rg, m.rb, m.ra,
+ m.gr, m.gg, m.gb, m.ga,
+ m.br, m.bg, m.bb, m.ba,
+ m.ar, m.ag, m.ab, m.aa
+ ];
+ this._ctxMatrixAppendix = [
+ m.r / 255,
+ m.g / 255,
+ m.b / 255,
+ m.a / 255
+ ];
+ }
+ else
+ {
+ this._ctxMatrixBody = null;
+ this._ctxMatrixAppendix = null;
+ }
+ };
+
+ proto._setUniforms = function()
+ {
+ if(this._shaderProgram === this._customShader)
+ {
+ this._shaderProgram.use();
+ {
+ this._shaderProgram.setUniformLocationWith4fv(
+ gaf._Uniforms.ColorTransformMult,
+ this._tintMult,
+ 1
+ );
+ this._shaderProgram.setUniformLocationWith4fv(
+ gaf._Uniforms.ColorTransformOffset,
+ this._tintOffset,
+ 1
+ );
+ }
+
+ if(this._ctxMatrixBody && this._ctxMatrixAppendix)
+ {
+ this._shaderProgram.setUniformLocationWithMatrix4fv(
+ gaf._Uniforms.ColorMatrixBody,
+ this._ctxMatrixBody,
+ 1
+ );
+ this._shaderProgram.setUniformLocationWith4fv(
+ gaf._Uniforms.ColorMatrixAppendix,
+ this._ctxMatrixAppendix,
+ 1
+ );
+ }
+ else
+ {
+ this._shaderProgram.setUniformLocationWithMatrix4fv(
+ gaf._Uniforms.ColorMatrixBody,
+ this._identityMat,
+ 1
+ );
+ this._shaderProgram.setUniformLocationWith4fv(
+ gaf._Uniforms.ColorMatrixAppendix,
+ this._zeroVec,
+ 1
+ );
+ }
+ }
+ };
+
+ proto.rendering = function(ctx)
+ {
+ this._setUniforms();
+
+ // Super call
+ cc.Sprite.WebGLRenderCmd.prototype.rendering.call(this, ctx);
+ };
+
+})();
diff --git a/external/gaf/Library/GAFTags.js b/external/gaf/Library/GAFTags.js
new file mode 100644
index 0000000000..09f8186538
--- /dev/null
+++ b/external/gaf/Library/GAFTags.js
@@ -0,0 +1,378 @@
+
+gaf.ReadSingleTag = function(stream){
+ var tagId = stream.Ushort();
+ var tag = gaf.Tags[tagId];
+ var result = {};
+ if(typeof tag === "undefined"){
+ console.log("GAF. Non implemented tag detected.");
+ gaf.Tags.Default.parse(stream, tagId);
+ }
+ else{
+ //console.log("tag " + tag.tagName);
+ result = tag.parse(stream, tagId);
+ }
+ return result;
+};
+
+gaf.ReadTags = function(stream){
+ var tags = [];
+ try {
+ do {
+ var tag = gaf.ReadSingleTag(stream);
+ tags.push(tag);
+ } while (tag.tagId != 0);
+ }
+ catch (e){
+ if (e instanceof Error && e.message == "GAF format error"){
+ console.log("GAF format error:\n" + e.stack);
+ // Tag will be closed and parser will continue from where it should.
+ }
+ else{
+ console.log(e.stack);
+ throw e;
+ }
+ }
+ return tags;
+};
+
+
+gaf.Tag = function(){
+ this.Default = Object.create(gaf.Tag.base);
+ this["0"] = Object.create(gaf.Tag.End);
+ this["1"] = Object.create(gaf.Tag.DefineAtlas);
+ this["2"] = Object.create(gaf.Tag.DefineAnimationMasks);
+ this["3"] = Object.create(gaf.Tag.DefineAnimationObjects);
+ this["4"] = Object.create(gaf.Tag.DefineAnimationFrames);
+ this["5"] = Object.create(gaf.Tag.DefineNamedParts);
+ this["6"] = Object.create(gaf.Tag.DefineSequences);
+ this["7"] = Object.create(gaf.Tag.DefineTextFields);
+ this["8"] = Object.create(gaf.Tag.DefineAtlas2);
+ this["9"] = Object.create(gaf.Tag.DefineStage);
+ this["10"] = Object.create(gaf.Tag.DefineAnimationObjects2);
+ this["11"] = Object.create(gaf.Tag.DefineAnimationMasks2);
+ this["12"] = Object.create(gaf.Tag.DefineAnimationFrames2);
+ this["13"] = Object.create(gaf.Tag.DefineTimeline);
+};
+
+gaf.Tag.base = function() {};
+gaf.Tag.base.parse = function(stream, tagId){
+ var size = stream.Uint();
+
+ stream.startNestedBuffer(size);
+ var result = this.doParse(stream);
+ stream.endNestedBuffer();
+
+ result.tagName = this.tagName;
+ result.tagId = tagId;
+ return result;
+};
+gaf.Tag.base.doParse = function(stream){
+ return {};
+ };
+
+gaf.Tag.End = Object.create(gaf.Tag.base);
+gaf.Tag.End.tagName = "TagEnd";
+
+gaf.Tag.DefineAtlas = Object.create(gaf.Tag.base);
+gaf.Tag.DefineAtlas.tagName = "TagDefineAtlas";
+gaf.Tag.DefineAtlas.doParse = function (s) {
+ var exec = s.fields(
+ 'scale', 'Float',
+ 'atlases', s.array('Ubyte', s.fields(
+ 'id', 'Uint',
+ 'sources', s.array('Ubyte', s.fields(
+ 'source', 'String',
+ 'csf', 'Float'
+ ))
+ )),
+ 'elements', s.array('Uint', s.fields(
+ 'pivot', 'Point',
+ 'origin', 'Point',
+ 'scale', 'Float',
+ 'size', 'Point',
+ 'atlasId', 'Uint',
+ 'elementAtlasId', 'Uint'
+ ))
+ );
+ return {'content': exec()};
+};
+
+gaf.Tag.DefineAnimationMasks = Object.create(gaf.Tag.base);
+gaf.Tag.DefineAnimationMasks.tagName = "TagDefineAnimationMasks";
+gaf.Tag.DefineAnimationMasks.doParse = function (s) {
+ var exec = s.array('Uint', s.fields(
+ 'objectId', 'Uint',
+ 'elementAtlasIdRef', 'Uint'
+ ));
+ var result = {'content': exec()};
+ debugger;
+ return result;
+};
+
+gaf.Tag.DefineAnimationObjects = Object.create(gaf.Tag.base);
+gaf.Tag.DefineAnimationObjects.tagName = "TagDefineAnimationObjects";
+gaf.Tag.DefineAnimationObjects.doParse = function (s) {
+ var exec = s.array('Uint', s.fields(
+ 'objectId', 'Uint',
+ 'elementAtlasIdRef', 'Uint'
+ ));
+ return {'content': exec()};
+};
+
+gaf.Tag.DefineAnimationFrames = Object.create(gaf.Tag.base);
+gaf.Tag.DefineAnimationFrames.tagName = "TagDefineAnimationFrames";
+gaf.Tag.DefineAnimationFrames.doParse = function(s){
+ var exec = s.array('Uint', s.fields(
+ 'frame', 'Uint',
+ 'state', s.array('Uint', s.fields(
+ 'hasColorTransform', 'Ubyte',
+ 'hasMask', 'Ubyte',
+ 'hasEffect', 'Ubyte',
+ 'objectIdRef', 'Uint',
+ 'depth', 'Int',
+ 'alpha', 'Float',
+ 'matrix', 'Matrix',
+ 'colorTransform', s.condition('hasColorTransform', 1, s.fields(
+ 'alphaOffset', 'Float',
+ 'redMultiplier', 'Float',
+ 'redOffset', 'Float',
+ 'greenMultiplier', 'Float',
+ 'greenOffset', 'Float',
+ 'blueMultiplier', 'Float',
+ 'blueOffset', 'Float'
+ )),
+ 'effect', s.condition('hasEffect', 1, s.array('Ubyte', gaf.Tag._readFilter(s))),
+ 'maskObjectIdRef', s.condition('hasMask', 1, s.fields(
+ 'maskObjectIdRef', 'Uint'
+ ))
+ ))
+ ));
+ return {'content': exec()};
+};
+
+gaf.Tag.DefineNamedParts = Object.create(gaf.Tag.base);
+gaf.Tag.DefineNamedParts.tagName = "TagDefineNamedParts";
+gaf.Tag.DefineNamedParts.doParse = function(s) {
+ var exec = s.array('Uint', s.fields(
+ 'objectId', 'Uint',
+ 'name', 'String'
+ ));
+ return {'content': exec()};
+};
+
+gaf.Tag.DefineSequences = Object.create(gaf.Tag.base);
+gaf.Tag.DefineSequences.tagName = "TagDefineSequences";
+gaf.Tag.DefineSequences.doParse = function(s) {
+ var exec = s.array('Uint', s.fields(
+ 'id', 'String',
+ 'start', 'Ushort',
+ 'end', 'Ushort'
+ ));
+ return {'content': exec()};
+};
+
+gaf.Tag.DefineTextFields = Object.create(gaf.Tag.base);
+gaf.Tag.DefineTextFields.tagName = "TagDefineTextFields";
+gaf.Tag.DefineTextFields.doParse = function(s) {
+ var exec = s.array('Uint', s.fields(
+ 'id', 'Uint',
+ 'pivot', 'Point',
+ 'end', 'Ushort',
+ 'width', 'Float',
+ 'height', 'Float',
+ 'text', 'String',
+ 'embedFonts', 'Boolean',
+ 'multiline', 'Boolean',
+ 'wordWrap', 'Boolean',
+ 'hasRestrict', 'Boolean',
+ 'restrict', s.condition('hasRestrict', 1, function (){return s['String'];}),
+ 'editable', 'Boolean',
+ 'selectable', 'Boolean',
+ 'displayAsPassword', 'Boolean',
+ 'maxChars', 'Uint',
+ 'align', 'Uint',
+ 'blockIndent', 'Uint',
+ 'bold', 'Boolean',
+ 'bullet', 'Boolean',
+ 'color', 'color',
+ 'font', 'String',
+ 'indent', 'Uint',
+ 'italic', 'Boolean',
+ 'kerning', 'Boolean',
+ 'leading', 'Uint',
+ 'leftMargin', 'Uint',
+ 'letterSpacing', 'Float',
+ 'rightMargin', 'Uint',
+ 'size', 'Uint',
+ 'tabStops', s.array('Uint', s.fields(
+ 'value', 'Uint'
+ )),
+ 'target', 'string',
+ 'underline', 'Boolean',
+ 'url', 'String'
+ ));
+ return {'content': exec()};
+};
+
+gaf.Tag.DefineAtlas2 = Object.create(gaf.Tag.base);
+gaf.Tag.DefineAtlas2.tagName = "TagDefineAtlas2";
+gaf.Tag.DefineAtlas2.doParse = function(s) {
+ var exec = s.fields(
+ 'scale', 'Float',
+ 'atlases', s.array('Ubyte', s.fields(
+ 'id', 'Uint',
+ 'sources', s.array('Ubyte', s.fields(
+ 'source', 'String',
+ 'csf', 'Float'
+ ))
+ )),
+ 'elements', s.array('Uint', s.fields(
+ 'pivot', 'Point',
+ 'origin', 'Point',
+ 'scale', 'Float',
+ 'size', 'Point',
+ 'atlasId', 'Uint',
+ 'elementAtlasId', 'Uint',
+ 'hasScale9Grid', 'Boolean',
+ 'scale9GridRect', s.condition('hasScale9Grid', 1, function(){return s.Rect();})
+ ))
+ );
+ return {'content': exec()};
+};
+
+gaf.Tag.DefineStage = Object.create(gaf.Tag.base);
+gaf.Tag.DefineStage.tagName = "TagDefineStage";
+gaf.Tag.DefineStage.doParse = function(s) {
+ var exec = s.fields(
+ 'fps', 'Ubyte',
+ 'color', 'color',
+ 'width', 'Ushort',
+ 'height', 'Ushort'
+ );
+ return {'content': exec()};
+};
+
+gaf.Tag.DefineAnimationObjects2 = Object.create(gaf.Tag.base);
+gaf.Tag.DefineAnimationObjects2.tagName = "TagDefineAnimationObjects2";
+gaf.Tag.DefineAnimationObjects2.doParse = function(s) {
+ var exec = s.array('Uint', s.fields(
+ 'objectId', 'Uint',
+ 'elementAtlasIdRef', 'Uint',
+ 'type', 'Ushort'
+ ));
+ return {'content': exec()};
+};
+
+gaf.Tag.DefineAnimationMasks2 = Object.create(gaf.Tag.base);
+gaf.Tag.DefineAnimationMasks2.tagName = "TagDefineAnimationMasks2";
+gaf.Tag.DefineAnimationMasks2.doParse = function(s) {
+ var exec = s.array('Uint', s.fields(
+ 'objectId', 'Uint',
+ 'elementAtlasIdRef', 'Uint',
+ 'type', 'Ushort'
+ ));
+ return {'content': exec()};
+};
+
+gaf.Tag.DefineAnimationFrames2 = Object.create(gaf.Tag.base);
+gaf.Tag.DefineAnimationFrames2.tagName = "TagDefineAnimationFrames2";
+gaf.Tag.DefineAnimationFrames2.doParse = function(s) {
+ var exec = s.array('Uint', s.fields(
+ 'frame', 'Uint',
+ 'hasChangesInDisplayList', 'Boolean',
+ 'hasActions', 'Boolean',
+ 'state', s.condition('hasChangesInDisplayList', 1, s.array('Uint', s.fields(
+ 'hasColorTransform', 'Boolean',
+ 'hasMask', 'Boolean',
+ 'hasEffect', 'Boolean',
+ 'objectIdRef', 'Uint',
+ 'depth', 'Int',
+ 'alpha', 'Float',
+ 'matrix', 'Matrix',
+ 'colorTransform', s.condition('hasColorTransform', 1, s.fields(
+ 'alphaOffset', 'Float',
+ 'redMultiplier', 'Float',
+ 'redOffset', 'Float',
+ 'greenMultiplier', 'Float',
+ 'greenOffset', 'Float',
+ 'blueMultiplier', 'Float',
+ 'blueOffset', 'Float'
+ )),
+ 'effect', s.condition('hasEffect', 1, s.array('Ubyte', gaf.Tag._readFilter(s))),
+ 'maskObjectIdRef', s.condition('hasMask', 1, function(){return s.Uint()})
+ ))),
+ 'actions', s.condition('hasActions', 1, s.array('Uint', s.fields(
+ 'type', 'Uint',
+ 'scope', 'String',
+ 'params', gaf.Tag._readActionArguments(s)
+ )))
+ ));
+ return {'content': exec()};
+};
+
+gaf.Tag.DefineTimeline = Object.create(gaf.Tag.base);
+gaf.Tag.DefineTimeline.tagName = "TagDefineTimeline";
+gaf.Tag.DefineTimeline.doParse = function(s) {
+ var exec = s.fields(
+ 'id', 'Uint',
+ 'animationFrameCount', 'Uint',
+ 'boundingBox', 'Rect',
+ 'pivotPoint', 'Point',
+ 'hasLinkage', 'Boolean',
+ 'linkageName', s.condition('hasLinkage', 1, function () {
+ return s.String();
+ })
+ );
+ var result = {'content': exec()};
+ result.content.tags = gaf.ReadTags(s);
+ return result;
+};
+
+gaf.Tag._readActionArguments = function(s){
+ return function(){
+ var size = s.Uint();
+ var ret = [];
+ s.startNestedBuffer(size);
+ while(s.maxOffset() < s.tell()){
+ ret.push(s.String());
+ }
+ s.endNestedBuffer();
+ return ret;
+ };
+};
+
+gaf.Tag._readFilter = function(s){
+ return s.fields(
+ 'type', 'Uint',
+ 'dropShadow', s.condition('type', gaf.EFFECT_DROP_SHADOW, s.fields( // DropShadow
+ 'color', 'color',
+ 'blurX', 'Float',
+ 'blurY', 'Float',
+ 'angle', 'Float',
+ 'distance', 'Float',
+ 'strength', 'Float',
+ 'inner', 'Boolean',
+ 'knockout', 'Boolean'
+ )),
+ 'blur', s.condition('type', gaf.EFFECT_BLUR, s.fields( // Blur
+ 'blurX', 'Float',
+ 'blurY', 'Float'
+ )),
+ 'glow', s.condition('type', gaf.EFFECT_GLOW, s.fields( // Glow
+ 'color', 'color',
+ 'blurX', 'Float',
+ 'blurY', 'Float',
+ 'strength', 'Float',
+ 'inner', 'Boolean',
+ 'knockout', 'Boolean'
+ )),
+ 'colorMatrix', s.condition('type', gaf.EFFECT_COLOR_MATRIX, s.fields( // ColorMatrix
+ 'rr', 'Float', 'gr', 'Float', 'br', 'Float', 'ar', 'Float', 'r', 'Float',
+ 'rg', 'Float', 'gg', 'Float', 'bg', 'Float', 'ag', 'Float', 'g', 'Float',
+ 'rb', 'Float', 'gb', 'Float', 'bb', 'Float', 'ab', 'Float', 'b', 'Float',
+ 'ra', 'Float', 'ga', 'Float', 'ba', 'Float', 'aa', 'Float', 'a', 'Float'
+ ))
+ )
+};
+
+gaf.Tags = new gaf.Tag();
diff --git a/external/gaf/Library/GAFTextField.js b/external/gaf/Library/GAFTextField.js
new file mode 100644
index 0000000000..04f9744920
--- /dev/null
+++ b/external/gaf/Library/GAFTextField.js
@@ -0,0 +1,6 @@
+
+gaf.TextField = gaf.Object.extend
+({
+ _className: "GAFTextField"
+
+});
\ No newline at end of file
diff --git a/external/gaf/Library/GAFTimeLine.js b/external/gaf/Library/GAFTimeLine.js
new file mode 100644
index 0000000000..ef9387aa46
--- /dev/null
+++ b/external/gaf/Library/GAFTimeLine.js
@@ -0,0 +1,547 @@
+
+gaf.TimeLine = gaf.Object.extend
+({
+ _className: "GAFTimeLine",
+ _objects: null,
+ _container: null,
+ _animationStartedNextLoopDelegate: null,
+ _animationFinishedPlayDelegate: null,
+ _framePlayedDelegate: null,
+ _sequenceDelegate: null,
+ _fps: 60,
+ _frameTime: 1/60,
+ _currentSequenceStart: gaf.FIRST_FRAME_INDEX,
+ _currentSequenceEnd: gaf.FIRST_FRAME_INDEX,
+ _totalFrameCount: 0,
+ _isRunning: false,
+ _isLooped: false,
+ _isReversed: false,
+ _timeDelta: 0,
+ _animationsSelectorScheduled: false,
+ _currentFrame: gaf.FIRST_FRAME_INDEX,
+
+
+ setAnimationStartedNextLoopDelegate: function (delegate)
+ {
+ this._animationStartedNextLoopDelegate = delegate;
+ },
+ setAnimationFinishedPlayDelegate: function (delegate)
+ {
+ this._animationFinishedPlayDelegate = delegate;
+ },
+ setLooped: function (looped, recursively)
+ {
+ this._isLooped = looped;
+ if (recursively)
+ {
+ this._objects.forEach(function (item)
+ {
+ item.setLooped(looped, recursively);
+ });
+ }
+ },
+ getBoundingBoxForCurrentFrame: function ()
+ {
+ var result = null;//cc.rect();
+ var isFirstObj = true;
+ this._objects.forEach(function (item) {
+ if(item.isVisibleInCurrentFrame() && item.isVisible())
+ {
+ var bb = item.getBoundingBoxForCurrentFrame();
+ if(!bb)
+ {
+ bb = item.getBoundingBox();
+ }
+ if (isFirstObj)
+ {
+ isFirstObj = false;
+ result = bb;
+ }
+ else
+ {
+ result = cc.rectUnion(result, bb);
+ }
+ }
+ });
+ return cc._rectApplyAffineTransformIn(result, this._container.getNodeToParentTransform());
+ },
+ setFps: function (fps)
+ {
+ cc.assert(fps !== 0, 'Error! Fps is set to zero.');
+ this._fps = fps;
+ this._frameTime = 1/fps;
+ },
+ getObjectByName: function (name)
+ {
+ var elements = name.split('.');
+ var result = null;
+ var retId = -1;
+ var timeLine = this;
+ var BreakException = {};
+ try
+ {
+ elements.forEach(function(element)
+ {
+ var parts = timeLine._gafproto.getNamedParts();
+ if(parts.hasOwnProperty(element))
+ {
+ retId = parts[element];
+ }
+ else
+ {
+ // Sequence is incorrect
+ BreakException.lastElement = element;
+ throw BreakException;
+ }
+ result = timeLine._objects[retId];
+ timeLine = result;
+ });
+ }
+ catch (e)
+ {
+ if (e!==BreakException)
+ {
+ throw e;
+ }
+ cc.log("Sequence incorrect: `" + name + "` At: `" + BreakException.lastElement + "`");
+ return null;
+ }
+ return result;
+ },
+ clearSequence: function ()
+ {
+ this._currentSequenceStart = gaf.FIRST_FRAME_INDEX;
+ this._currentSequenceEnd = this._gafproto.getTotalFrames();
+ },
+ getIsAnimationRunning: function ()
+ {
+ return this._isRunning;
+ },
+ gotoAndStop: function (value)
+ {
+ var frame = 0;
+ if (typeof value === 'string')
+ {
+ frame = this.getStartFrame(value);
+ }
+ else
+ {
+ frame = value;
+ }
+ if (this.setFrame(frame))
+ {
+ this.setAnimationRunning(false, false);
+ return true;
+ }
+ return false;
+ },
+ gotoAndPlay: function (value)
+ {
+ var frame = 0;
+ if (typeof value === 'string')
+ {
+ frame = this.getStartFrame(value);
+ }
+ else
+ {
+ frame = value;
+ }
+ if (this.setFrame(frame))
+ {
+ this.setAnimationRunning(true, false);
+ return true;
+ }
+ return false;
+ },
+ getStartFrame: function (frameLabel)
+ {
+ var seq = this._gafproto.getSequences()[frameLabel];
+ if (seq)
+ {
+ return seq.start;
+ }
+ return gaf.IDNONE;
+ },
+ getEndFrame: function (frameLabel)
+ {
+ var seq = this._gafproto.getSequences()[frameLabel];
+ if (seq)
+ {
+ return seq.end;
+ }
+ return gaf.IDNONE;
+ },
+ setFramePlayedDelegate: function (delegate)
+ {
+ this._framePlayedDelegate = delegate;
+ },
+ getCurrentFrameIndex: function ()
+ {
+ return this._showingFrame;
+ },
+ getTotalFrameCount: function ()
+ {
+ return this._gafproto.getTotalFrames();
+ },
+ start: function ()
+ {
+ this._enableTick(true);
+ if (!this._isRunning)
+ {
+ this._currentFrame = gaf.FIRST_FRAME_INDEX;
+ this.setAnimationRunning(true, true);
+ }
+ },
+ stop: function ()
+ {
+ this._enableTick(false);
+ if (this._isRunning)
+ {
+ this._currentFrame = gaf.FIRST_FRAME_INDEX;
+ this.setAnimationRunning(false, true);
+ }
+ },
+ isDone: function ()
+ {
+ if (this._isLooped)
+ {
+ return false;
+ }
+ else
+ {
+ if (!this._isReversed)
+ {
+ return this._currentFrame > this._totalFrameCount;
+ }
+ else
+ {
+ return this._currentFrame < gaf.FIRST_FRAME_INDEX - 1;
+ }
+ }
+ },
+ getSequences: function()
+ {
+ return this._gafproto.getSequences();
+ },
+ playSequence: function (name, looped)
+ {
+ var s = this.getStartFrame(name);
+ var e = this.getEndFrame(name);
+ if (gaf.IDNONE === s || gaf.IDNONE === e)
+ {
+ return false;
+ }
+ this._currentSequenceStart = s;
+ this._currentSequenceEnd = e;
+ if (this._currentFrame < this._currentSequenceStart || this._currentFrame > this._currentSequenceEnd)
+ {
+ this._currentFrame = this._currentSequenceStart;
+ }
+ else
+ {
+ this._currentFrame = this._currentSequenceStart;
+ }
+ this.setLooped(looped, false);
+ this.resumeAnimation();
+ return true;
+ },
+ isReversed: function ()
+ {
+ return this._isReversed;
+ },
+ setSequenceDelegate: function (delegate)
+ {
+ this._sequenceDelegate = delegate;
+ },
+ setFrame: function (index)
+ {
+ if (index >= gaf.FIRST_FRAME_INDEX && index < this._totalFrameCount)
+ {
+ this._showingFrame = index;
+ this._currentFrame = index;
+ this._processAnimation();
+ return true;
+ }
+ return false;
+ },
+
+ pauseAnimation: function ()
+ {
+ if (this._isRunning)
+ {
+ this.setAnimationRunning(false, false);
+ }
+ },
+ isLooped: function ()
+ {
+ return this._isLooped;
+ },
+ resumeAnimation: function ()
+ {
+ if (!this._isRunning)
+ {
+ this.setAnimationRunning(true, false);
+ }
+ },
+ setReversed: function (reversed)
+ {
+ this._isReversed = reversed;
+ },
+ hasSequences: function ()
+ {
+ return this._gafproto.getSequences().length > 0;
+ },
+ getFps: function ()
+ {
+ return this._fps;
+ },
+
+
+ // Private
+
+ ctor: function(gafTimeLineProto, scale)
+ {
+ this._super(scale);
+ this._objects = [];
+ cc.assert(gafTimeLineProto, "Error! Missing mandatory parameter.");
+ this._gafproto = gafTimeLineProto;
+ },
+
+ setExternalTransform: function(affineTransform)
+ {
+ if(!cc.affineTransformEqualToTransform(this._container._additionalTransform, affineTransform))
+ {
+ this._container.setAdditionalTransform(affineTransform);
+ }
+ },
+
+ _init: function()
+ {
+ this.setContentSize(this._gafproto.getBoundingBox());
+ this._currentSequenceEnd = this._gafproto.getTotalFrames();
+ this._totalFrameCount = this._currentSequenceEnd;
+ this.setFps(this._gafproto.getFps());
+ this._container = new cc.Node();
+ this.addChild(this._container);
+
+ var self = this;
+ var asset = this._gafproto.getAsset();
+
+ // Construct objects for current time line
+ this._gafproto.getObjects().forEach(function(object)
+ {
+ var objectProto = asset._getProtos()[object];
+ cc.assert(objectProto, "Error. GAF proto for type: " + object.type + " and reference id: " + object + " not found.");
+ self._objects[object] = objectProto._gafConstruct();
+ });
+ },
+
+ _enableTick: function(val)
+ {
+ if (!this._animationsSelectorScheduled && val)
+ {
+ this.schedule(this._processAnimations);
+ this._animationsSelectorScheduled = true;
+ }
+ else if (this._animationsSelectorScheduled && !val)
+ {
+ this.unschedule(this._processAnimations);
+ this._animationsSelectorScheduled = false;
+ }
+ },
+
+ _processAnimations: function (dt)
+ {
+ this._timeDelta += dt;
+ while (this._timeDelta >= this._frameTime)
+ {
+ this._timeDelta -= this._frameTime;
+ this._step();
+ }
+ },
+
+ _step: function ()
+ {
+ this._showingFrame = this._currentFrame;
+
+ if(!this.getIsAnimationRunning())
+ {
+ this._processAnimation();
+ return;
+ }
+
+ if(this._sequenceDelegate)
+ {
+ var seq;
+ if(!this._isReversed)
+ {
+ seq = this._getSequenceByLastFrame(this._currentFrame);
+ }
+ else
+ {
+ seq = this._getSequenceByFirstFrame(this._currentFrame + 1);
+ }
+
+ if (seq)
+ {
+ this._sequenceDelegate(this, seq);
+ }
+ }
+ if (this._isCurrentFrameLastInSequence())
+ {
+ if(this._isLooped)
+ {
+ if(this._animationStartedNextLoopDelegate)
+ this._animationStartedNextLoopDelegate(this);
+ }
+ else
+ {
+ this.setAnimationRunning(false, false);
+ if(this._animationFinishedPlayDelegate)
+ this._animationFinishedPlayDelegate(this);
+ }
+ }
+ this._processAnimation();
+ this._currentFrame = this._nextFrame();
+ },
+
+ _isCurrentFrameLastInSequence: function()
+ {
+ if (this._isReversed)
+ return this._currentFrame == this._currentSequenceStart;
+ return this._currentFrame == this._currentSequenceEnd - 1;
+ },
+
+ _nextFrame: function()
+ {
+ if (this._isCurrentFrameLastInSequence())
+ {
+ if (!this._isLooped)
+ return this._currentFrame;
+
+ if (this._isReversed)
+ return this._currentSequenceEnd - 1;
+ else
+ return this._currentSequenceStart;
+ }
+
+ return this._currentFrame + (this._isReversed ? -1 : 1);
+ },
+
+ _processAnimation: function ()
+ {
+ //var id = this._gafproto.getId();
+ this._realizeFrame(this._container, this._currentFrame);
+ if (this._framePlayedDelegate)
+ {
+ this._framePlayedDelegate(this, this._currentFrame);
+ }
+ },
+ _realizeFrame: function(out, frameIndex)
+ {
+ var self = this;
+ var objects = self._objects;
+ var frames = self._gafproto.getFrames();
+ if(frameIndex > frames.length)
+ {
+ return;
+ }
+ var currentFrame = frames[frameIndex];
+ if(!currentFrame)
+ {
+ return;
+ }
+ var states = currentFrame.states;
+ for(var stateIdx = 0, total = states.length; stateIdx < total; ++stateIdx)
+ {
+ var state = states[stateIdx];
+ var object = objects[state.objectIdRef];
+ if(!object)
+ {
+ return;
+ }
+ if(state.alpha < 0)
+ {
+ object._resetState();
+ }
+ object._updateVisibility(state, self);
+ if(!object.isVisible())
+ {
+ continue;
+ }
+ object._applyState(state, self);
+ var parent = out;
+ if(state.hasMask)
+ {
+ parent = objects[state.maskObjectIdRef]._getNode();
+ cc.assert(parent, "Error! Mask not found.");
+ }
+ object._lastVisibleInFrame = 1 + frameIndex;
+ gaf.TimeLine.rearrangeSubobject(parent, object, state.depth);
+ if(object._step)
+ {
+ object._step();
+ }
+ }
+ },
+ setAnimationRunning: function (value, recursively)
+ {
+ this._isRunning = value;
+ if(recursively)
+ {
+ this._objects.forEach(function (obj)
+ {
+ if (obj && obj.setAnimationRunning)
+ {
+ obj.setAnimationRunning(value, recursively);
+ }
+ });
+ }
+ },
+
+ _getSequenceByLastFrame: function(){
+ var sequences = this._gafproto.getSequences();
+ for(var item in sequences){
+ if(sequences.hasOwnProperty(item)){
+ if(sequences[item].end === frame + 1)
+ {
+ return item;
+ }
+ }
+ }
+ return "";
+ },
+
+ _resetState : function()
+ {
+ this._super();
+ this._currentFrame = this._currentSequenceStart;
+ },
+
+ _getSequenceByFirstFrame: function(){
+ var sequences = this._gafproto.getSequences();
+ for(var item in sequences){
+ if(sequences.hasOwnProperty(item)){
+ if(sequences[item].start === frame)
+ {
+ return item;
+ }
+ }
+ }
+ return "";
+ }
+});
+
+gaf.TimeLine.rearrangeSubobject = function(out, object, depth)
+{
+ var parent = object.getParent();
+ if (parent !== out)
+ {
+ object.removeFromParent(false);
+ out.addChild(object, depth);
+ }
+ else
+ {
+ object.setLocalZOrder(depth);
+ }
+};
diff --git a/external/gaf/Library/GAFTimeLineProto.js b/external/gaf/Library/GAFTimeLineProto.js
new file mode 100644
index 0000000000..9d78b219d9
--- /dev/null
+++ b/external/gaf/Library/GAFTimeLineProto.js
@@ -0,0 +1,32 @@
+
+gaf._TimeLineProto = function(asset, animationFrameCount, boundingBox, pivotPoint, id, linkageName)
+{
+ id = typeof id != 'undefined' ? id : 0;
+ linkageName = linkageName || "";
+
+ this._objects = [];
+
+ this.getTotalFrames = function(){return animationFrameCount};
+ this.getBoundingBox = function() {return boundingBox};
+ this.getId = function() {return id};
+ this.getLinkageName = function() {return linkageName};
+ this.getPivot = function(){return pivotPoint};
+ this.getRect = function(){return boundingBox};
+ this.getNamedParts = function() {return {}}; // Map name -> id
+ this.getSequences = function() {return {}}; // Map name -> {start, end}
+ this.getFrames = function(){return []}; // Array {states, actions}
+ this.getFps = function(){return 60};
+ this.getObjects = function(){return this._objects};
+ this.getAsset = function(){return asset};
+
+ /*
+ * Will construct GAFTimeLine
+ */
+ this._gafConstruct = function()
+ {
+ var usedScale = this.getAsset()._usedAtlasScale;
+ var ret = new gaf.TimeLine(this, usedScale);
+ ret._init();
+ return ret;
+ };
+};
diff --git a/external/gaf/gaf_viewer.css b/external/gaf/gaf_viewer.css
new file mode 100644
index 0000000000..60933161d2
--- /dev/null
+++ b/external/gaf/gaf_viewer.css
@@ -0,0 +1,42 @@
+#drop_zone {
+ border: 2px dashed #bbb;
+ -moz-border-radius: 5px;
+ -webkit-border-radius: 5px;
+ border-radius: 5px;
+ padding: 25px;
+ text-align: center;
+ font: 20pt bold 'Vollkorn';
+ color: #bbb;
+
+}
+.renderjson a {
+ text-decoration: none;
+}
+.renderjson .disclosure {
+ color: crimson;
+ font-size: 150%;
+}
+.renderjson .syntax {
+ color: grey;
+}
+.renderjson .string {
+ color: darkred;
+}
+.renderjson .number {
+ color: darkcyan;
+}
+.renderjson .boolean {
+ color: blueviolet;
+}
+.renderjson .key {
+ color: darkblue;
+}
+.renderjson .keyword {
+ color: blue;
+}
+.renderjson .object.syntax {
+ color: lightseagreen;
+}
+.renderjson .array.syntax {
+ color: orange;
+}
diff --git a/external/gaf/gaf_viewer.html b/external/gaf/gaf_viewer.html
new file mode 100644
index 0000000000..2c66aeb05f
--- /dev/null
+++ b/external/gaf/gaf_viewer.html
@@ -0,0 +1,21 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Drop GAF here
+
+
+
+
+
+
\ No newline at end of file
diff --git a/external/gaf/gaf_viewer.js b/external/gaf/gaf_viewer.js
new file mode 100644
index 0000000000..db5bdbea7f
--- /dev/null
+++ b/external/gaf/gaf_viewer.js
@@ -0,0 +1,219 @@
+ /*
+ * Created by Teivaz on 29.11.2014.
+ * Thanks to David Caldwell for `renderjson`
+ */
+function handleFileSelect(evt) {
+ evt.stopPropagation();
+ evt.preventDefault();
+
+ var files = evt.dataTransfer.files;
+
+ var output = [];
+ for (var i = 0, f; f = files[i]; i++) {
+ var name = escape(f.name);
+ var ext = name.split('.').pop();
+ if (ext == 'gaf') {
+ var reader = new FileReader();
+ reader.onload = (function(theFile) {
+ return function(req) {
+ var arrayBuffer = new gaf.DataReader(req.target.result);
+ var loader = new gaf.Loader();
+ var data = loader.LoadStream(arrayBuffer);
+ document.getElementById('list').appendChild(renderjson(data));
+ };
+ })(f);
+ reader.readAsArrayBuffer(f);
+ }
+ }
+}
+
+function handleDragOver(evt) {
+ evt.stopPropagation();
+ evt.preventDefault();
+ evt.dataTransfer.dropEffect = 'copy';
+}
+
+var dropZone = document.getElementById('drop_zone');
+dropZone.addEventListener('dragover', handleDragOver, false);
+dropZone.addEventListener('drop', handleFileSelect, false);
+
+var module;
+(module || {}).exports = renderjson = (function() {
+ var themetext = function( /* [class, text]+ */ ) {
+ var spans = [];
+ while (arguments.length)
+ spans.push(append(span(Array.prototype.shift.call(arguments)),
+ text(Array.prototype.shift.call(arguments))));
+ return spans;
+ };
+ var append = function( /* el, ... */ ) {
+ var el = Array.prototype.shift.call(arguments);
+ for (var a = 0; a < arguments.length; a++)
+ if (arguments[a].constructor == Array)
+ append.apply(this, [el].concat(arguments[a]));
+ else
+ el.appendChild(arguments[a]);
+ return el;
+ };
+ var prepend = function(el, child) {
+ el.insertBefore(child, el.firstChild);
+ return el;
+ };
+ var isempty = function(obj) {
+ for (var k in obj)
+ if (obj.hasOwnProperty(k)) return false;
+ return true;
+ };
+ var text = function(txt) {
+ return document.createTextNode(txt)
+ };
+ var div = function() {
+ return document.createElement("div")
+ };
+ var span = function(classname) {
+ var s = document.createElement("span");
+ if (classname) s.className = classname;
+ return s;
+ };
+ var A = function A(txt, classname, callback) {
+ var a = document.createElement("a");
+ if (classname) a.className = classname;
+ a.appendChild(text(txt));
+ a.href = '#';
+ a.onclick = function() {
+ callback();
+ return false;
+ };
+ return a;
+ };
+
+ function _renderjson(json, indent, dont_indent, show_level, sort_objects) {
+ var my_indent = dont_indent ? "" : indent;
+
+ if (json === null) return themetext(null, my_indent, "keyword", "null");
+ if (json === void 0) return themetext(null, my_indent, "keyword", "undefined");
+ if (typeof(json) != "object") // Strings, numbers and bools
+ return themetext(null, my_indent, typeof(json), JSON.stringify(json));
+
+ var disclosure = function(open, close, type, builder) {
+ var content;
+ var empty = span(type);
+ var show = function() {
+ if (!content) append(empty.parentNode,
+ content = prepend(builder(),
+ A(renderjson.hide, "disclosure",
+ function() {
+ content.style.display = "none";
+ empty.style.display = "inline";
+ })));
+ content.style.display = "inline";
+ empty.style.display = "none";
+ };
+
+ function isColor(a){
+ return a.hasOwnProperty('a') && a.hasOwnProperty('r') && a.hasOwnProperty('g') && a.hasOwnProperty('b');
+ }
+
+ var color_rect = span();
+ if (json.hasOwnProperty("tagName"))
+ var placeholder = json.tagName;
+ else if (json.hasOwnProperty("header"))
+ placeholder = " GAF v" + json.header.versionMajor + "." + json.header.versionMinor + " ";
+ else if (json.constructor == Array)
+ placeholder = " " + json.length + " ";
+ else if (json.hasOwnProperty("id"))
+ placeholder = " id:" + json.id + " ... ";
+ else if (json.hasOwnProperty("objectId"))
+ placeholder = " id:" + json.objectId + " ... ";
+ else if (json.hasOwnProperty("frame"))
+ placeholder = " frame:" + json.frame + " ... ";
+ else if(isColor(json)){
+ color_rect.style.backgroundColor = "rgba("+json.r+","+json.g+","+json.b+","+json.a / 255.0+")";// parseInt(json.r).toString(16) + parseInt(json.g).toString(16) + parseInt(json.b).toString(16);
+ color_rect.style.height = '10px';
+ color_rect.style.width = '10px';
+ color_rect.style.display = 'inline-block';
+ color_rect.style.margin = '0 4px';
+ color_rect.style.border = '1px solid #7f7f7f';
+ }
+
+ placeholder = placeholder || ' ... ';
+ append(empty,
+ A(renderjson.show, "disclosure", show),
+ color_rect,
+ themetext(type + " syntax", open),
+ A(placeholder, null, show),
+ themetext(type + " syntax", close));
+
+ var el = append(span(), text(my_indent.slice(0, -1)), empty);
+ if (show_level > 0)
+ show();
+ return el;
+ };
+
+ if (json.constructor == Array) {
+ if (json.length == 0) return themetext(null, my_indent, "array syntax", "[]");
+
+ return disclosure("[", "]", "array", function() {
+ var as = append(span("array"), themetext("array syntax", "[", null, "\n"));
+ for (var i = 0; i < json.length; i++)
+ append(as,
+ _renderjson(json[i], indent + " ", false, show_level - 1, sort_objects),
+ i != json.length - 1 ? themetext("syntax", ",") : [],
+ text("\n"));
+ append(as, themetext(null, indent, "array syntax", "]"));
+ return as;
+ });
+ }
+
+ // object
+ if (isempty(json))
+ return themetext(null, my_indent, "object syntax", "{}");
+
+
+ return disclosure("{", "}", "object", function() {
+ var os = append(span("object"), themetext("object syntax", "{", null, "\n"));
+ for (var k in json) var last = k;
+ var keys = Object.keys(json);
+ if (sort_objects)
+ keys = keys.sort();
+ for (var i in keys) {
+ var k = keys[i];
+ append(os, themetext(null, indent + " ", "key", '"' + k + '"', "object syntax", ': '),
+ _renderjson(json[k], indent + " ", true, show_level - 1, sort_objects),
+ k != last ? themetext("syntax", ",") : [],
+ text("\n"));
+ }
+ append(os, themetext(null, indent, "object syntax", "}"));
+ return os;
+ });
+ }
+
+ var renderjson = function renderjson(json) {
+ var pre = append(document.createElement("pre"), _renderjson(json, "", false, renderjson.show_to_level, renderjson.sort_objects));
+ pre.className = "renderjson";
+ return pre;
+ };
+ renderjson.set_icons = function(show, hide) {
+ renderjson.show = show;
+ renderjson.hide = hide;
+ return renderjson;
+ };
+ renderjson.set_show_to_level = function(level) {
+ renderjson.show_to_level = typeof level == "string" &&
+ level.toLowerCase() === "all" ? Number.MAX_VALUE : level;
+ return renderjson;
+ };
+ renderjson.set_sort_objects = function(sort_bool) {
+ renderjson.sort_objects = sort_bool;
+ return renderjson;
+ };
+ // Backwards compatiblity. Use set_show_to_level() for new code.
+ renderjson.set_show_by_default = function(show) {
+ renderjson.show_to_level = show ? Number.MAX_VALUE : 0;
+ return renderjson;
+ };
+ renderjson.set_icons('â', 'â');
+ renderjson.set_show_by_default(false);
+ renderjson.set_sort_objects(false);
+ return renderjson;
+})();
\ No newline at end of file
diff --git a/external/pluginx/Plugin.js b/external/pluginx/Plugin.js
new file mode 100644
index 0000000000..1a2aaced03
--- /dev/null
+++ b/external/pluginx/Plugin.js
@@ -0,0 +1,254 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+/**
+ * plugin manager
+ * @class
+ *
+ */
+(function(){
+
+ if(cc === undefined){
+ return;
+ }
+
+ var config = cc.game.config.plugin || {};
+
+ //Native plugin usage
+ var PluginManager = function(){};
+
+ PluginManager.prototype = {
+ constructor: PluginManager,
+
+ /**
+ * @returns {PluginManager}
+ * @expose
+ */
+ getInstance: function(){
+ return this;
+ },
+
+ /**
+ * @param {String} pluginName
+ * @expose
+ */
+ loadPlugin: function(pluginName){
+
+ },
+
+ /**
+ *
+ * @param pluginName
+ * @expose
+ */
+ unloadPlugin: function(pluginName){
+
+ }
+ };
+
+ var PluginAssembly = function(){};
+
+ PluginAssembly.prototype = {
+ constructor: PluginAssembly,
+
+ /**
+ * @param {Boolean} debug
+ * @expose
+ */
+ setDebugMode: function(debug){},
+
+ /**
+ * @param {String} appKey
+ * @expose
+ */
+ startSession: function(appKey){},
+
+ /**
+ * @param {Boolean} Capture
+ * @expose
+ */
+ setCaptureUncaughtException: function(Capture){},
+
+ /**
+ * @param {String} funName
+ * @param {All} Params
+ * @expose
+ */
+ callFuncWithParam: function(funName){
+ if(typeof this[funName] === 'function'){
+ return this[funName].apply(this, Array.prototype.splice.call(arguments, 1));
+ }else{
+ cc.log("function is not define");
+ }
+ },
+
+ /**
+ * @param {String} funName
+ * @param {All} Params
+ * @expose
+ */
+ callStringFuncWithParam: function(funName){
+ this.callFuncWithParam.apply(arguments);
+ },
+
+ /**
+ * @returns {String}
+ * @expose
+ */
+ getPluginName: function(){
+ return this._name;
+ },
+
+ /**
+ * @returns {String}
+ * @expose
+ */
+ getPluginVersion: function(){
+ return this._version;
+ }
+ };
+
+ /** @expose */
+ PluginAssembly.extend = function(name, porp){
+ var p, prototype = {};
+ for(p in PluginAssembly.prototype){
+ prototype[p] = PluginAssembly.prototype[p];
+ }
+ for(p in porp){
+ prototype[p] = porp[p];
+ }
+ var tmp = eval("(function " + name + "Plugin(){})");
+ prototype.constructor = tmp;
+ tmp.prototype = prototype;
+ return tmp;
+ };
+
+ //Param
+ var Param = function(type, value){
+ var paramType = plugin.PluginParam.ParamType,tmpValue;
+ switch(type){
+ case paramType.TypeInt:
+ tmpValue = parseInt(value);
+ break;
+ case paramType.TypeFloat:
+ tmpValue = parseFloat(value);
+ break;
+ case paramType.TypeBool:
+ tmpValue = Boolean(value);
+ break;
+ case paramType.TypeString:
+ tmpValue = String(value);
+ break;
+ case paramType.TypeStringMap:
+ tmpValue = value//JSON.stringify(value);
+ break;
+ default:
+ tmpValue = value;
+ }
+ return tmpValue
+ };
+
+ /** @expose */
+ Param.ParamType = {
+ /** @expose */
+ TypeInt:1,
+ /** @expose */
+ TypeFloat:2,
+ /** @expose */
+ TypeBool:3,
+ /** @expose */
+ TypeString:4,
+ /** @expose */
+ TypeStringMap:5
+ };
+
+ /** @expose */
+ Param.AdsResultCode = {
+ /** @expose */
+ AdsReceived:0,
+ /** @expose */
+ FullScreenViewShown:1,
+ /** @expose */
+ FullScreenViewDismissed:2,
+ /** @expose */
+ PointsSpendSucceed:3,
+ /** @expose */
+ PointsSpendFailed:4,
+ /** @expose */
+ NetworkError:5,
+ /** @expose */
+ UnknownError:6
+ };
+
+ /** @expose */
+ Param.PayResultCode = {
+ /** @expose */
+ PaySuccess:0,
+ /** @expose */
+ PayFail:1,
+ /** @expose */
+ PayCancel:2,
+ /** @expose */
+ PayTimeOut:3
+ };
+
+ /** @expose */
+ Param.ShareResultCode = {
+ /** @expose */
+ ShareSuccess:0,
+ /** @expose */
+ ShareFail:1,
+ /** @expose */
+ ShareCancel:2,
+ /** @expose */
+ ShareTimeOut:3
+ };
+
+ /** @expose */
+ var PluginList = {};
+
+ /** @expose */
+ var Plugin = {
+
+ /** @expose */
+ extend: function(name, extend){
+ PluginList[name] = new (PluginAssembly.extend(name, extend));
+ typeof PluginList[name].ctor === "function" && PluginList[name].ctor(config[name]);
+ },
+
+ /** @expose */
+ PluginList: PluginList,
+
+ /** @expose */
+ PluginParam: Param,
+
+ /** @expose */
+ PluginManager: new PluginManager()
+
+ };
+
+ /** @expose */
+ window.plugin = Plugin;
+
+})();
\ No newline at end of file
diff --git a/external/pluginx/platform/facebook.js b/external/pluginx/platform/facebook.js
new file mode 100644
index 0000000000..190115951a
--- /dev/null
+++ b/external/pluginx/platform/facebook.js
@@ -0,0 +1,557 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+/**
+ * Facebook SDK for Web Platform
+ * FacebookAgent...
+ *
+ * @property {String} name - plugin name
+ * @property {String} version - API version
+ */
+plugin.extend('facebook', {
+ name: "",
+ version: "",
+ _userInfo: null,
+ _isLoggedIn: false,
+
+ /**
+ * HTTP methods constants
+ * @constant
+ * @type {Object}
+ */
+ HttpMethod: {
+ 'GET': 'get',
+ 'POST': 'post',
+ 'DELETE': 'delete'
+ },
+
+ /**
+ * Succeed code returned in callbacks
+ * @constant
+ * @type {Number}
+ */
+ CODE_SUCCEED: 0,
+
+ /**
+ * App event names constants
+ * @constant
+ * @type {Object}
+ */
+ AppEvent: {
+ 'ACTIVATED_APP': FB.AppEvents.EventNames.ACTIVATED_APP,
+ 'COMPLETED_REGISTRATION': FB.AppEvents.EventNames.COMPLETED_REGISTRATION,
+ 'VIEWED_CONTENT': FB.AppEvents.EventNames.VIEWED_CONTENT,
+ 'SEARCHED': FB.AppEvents.EventNames.SEARCHED,
+ 'RATED': FB.AppEvents.EventNames.RATED,
+ 'COMPLETED_TUTORIAL': FB.AppEvents.EventNames.COMPLETED_TUTORIAL,
+ 'ADDED_TO_CART': FB.AppEvents.EventNames.ADDED_TO_CART,
+ 'ADDED_TO_WISHLIST': FB.AppEvents.EventNames.ADDED_TO_WISHLIST,
+ 'INITIATED_CHECKOUT': FB.AppEvents.EventNames.INITIATED_CHECKOUT,
+ 'ADDED_PAYMENT_INFO': FB.AppEvents.EventNames.ADDED_PAYMENT_INFO,
+ 'PURCHASED': FB.AppEvents.EventNames.PURCHASED,
+ 'ACHIEVED_LEVEL': FB.AppEvents.EventNames.ACHIEVED_LEVEL,
+ 'UNLOCKED_ACHIEVEMENT': FB.AppEvents.EventNames.UNLOCKED_ACHIEVEMENT,
+ 'SPENT_CREDITS': FB.AppEvents.EventNames.SPENT_CREDITS
+ },
+
+ /**
+ * App event parameter names constants
+ * @constant
+ * @type {Object}
+ */
+ AppEventParam: {
+ 'CURRENCY': FB.AppEvents.ParameterNames.CURRENCY,
+ 'REGISTRATION_METHOD': FB.AppEvents.ParameterNames.REGISTRATION_METHOD,
+ 'CONTENT_TYPE': FB.AppEvents.ParameterNames.CONTENT_TYPE,
+ 'CONTENT_ID': FB.AppEvents.ParameterNames.CONTENT_ID,
+ 'SEARCH_STRING': FB.AppEvents.ParameterNames.SEARCH_STRING,
+ 'SUCCESS': FB.AppEvents.ParameterNames.SUCCESS,
+ 'MAX_RATING_VALUE': FB.AppEvents.ParameterNames.MAX_RATING_VALUE,
+ 'PAYMENT_INFO_AVAILABLE': FB.AppEvents.ParameterNames.PAYMENT_INFO_AVAILABLE,
+ 'NUM_ITEMS': FB.AppEvents.ParameterNames.NUM_ITEMS,
+ 'LEVEL': FB.AppEvents.ParameterNames.LEVEL,
+ 'DESCRIPTION': FB.AppEvents.ParameterNames.DESCRIPTION
+ },
+
+ /**
+ * App event parameter values constants
+ * @constant
+ * @type {Object}
+ */
+ AppEventParamValue: {
+ 'VALUE_YES': "1",
+ 'VALUE_NO': "0"
+ },
+
+ _checkLoginStatus: function() {
+ var self = this;
+ FB.getLoginStatus(function (response) {
+ if (response && response.status === 'connected') {
+ //login
+ self._isLoggedIn = true;
+ //save user info
+ self._userInfo = response['authResponse'];
+ } else {
+ // Reset cached status
+ self._isLoggedIn = false;
+ self._userInfo = {};
+ }
+ });
+ },
+
+ ctor: function (config) {
+ this.name = "facebook";
+ this.version = "1.0";
+ this._userInfo = {};
+ this._isLoggedIn = false;
+
+ if (!FB) {
+ return;
+ }
+
+ //This configuration will be read from the project.json.
+ FB.init(config);
+ this._checkLoginStatus();
+
+ plugin.FacebookAgent = this;
+ },
+ /**
+ * Gets the current object
+ * @returns {FacebookAgent}
+ */
+ getInstance: function () {
+ return this;
+ },
+ /**
+ * Login to facebook
+ * @param {Function} callback
+ * @param {Array} permissions
+ * @example
+ * //example
+ * plugin.FacebookAgent.login();
+ */
+ login: function (permissions, callback) {
+ var self = this;
+ if (typeof permissions == 'function') {
+ callback = permissions;
+ permissions = [];
+ }
+ if (permissions.every(function (item) {
+ if (item != 'public_profile')
+ return true;
+ })) {
+ permissions.push("public_profile");
+ }
+ var permissionsStr = permissions.join(',');
+ FB.login(function (response) {
+ if (response['authResponse']) {
+ //save user info
+ self._isLoggedIn = true;
+ self._userInfo = response['authResponse'];
+ var permissList = response['authResponse']['grantedScopes'].split(",");
+ typeof callback === 'function' && callback(0, {
+ accessToken: response['authResponse']['accessToken'],
+ permissions: permissList
+ });
+ } else {
+ self._isLoggedIn = false;
+ self._userInfo = {};
+ typeof callback === 'function' && callback(response['error_code'] || 1, {
+ error_message: response['error_message'] || "Unknown error"
+ });
+ }
+ }, {
+ scope: permissionsStr,
+ return_scopes: true
+ });
+ },
+ /**
+ * Checking login status
+ * @return {Bool} Whether user is logged in
+ * @example
+ * //example
+ * plugin.FacebookAgent.isLoggedIn(type, msg);
+ */
+ isLoggedIn: function () {
+ //this._checkLoginStatus();
+ return this._isLoggedIn;
+ },
+
+ /**
+ * Logout of facebook
+ * @param {Function} callback
+ * @example
+ * //example
+ * plugin.FacebookAgent.logout(callback);
+ */
+ logout: function (callback) {
+ var self = this;
+ FB.logout(function (response) {
+ if (response['authResponse']) {
+ // user is now logged out
+ self._isLoggedIn = false;
+ self._userInfo = {};
+ typeof callback === 'function' && callback(0, {"isLoggedIn": false});
+ } else {
+ typeof callback === 'function' && callback(response['error_code'] || 1, {
+ error_message: response['error_message'] || "Unknown error"
+ });
+ }
+ });
+ },
+
+ /**
+ * Acquiring new permissions
+ * @deprecated since v3.0
+ * @param permissions
+ * @param callback
+ * @example
+ * //example
+ * plugin.FacebookAgent.requestPermissions(["manage_pages"], callback);
+ */
+ _requestPermissions: function (permissions, callback) {
+ var permissionsStr = permissions.join(',');
+ var self = this;
+ FB.login(function (response) {
+ if (response['authResponse']) {
+ var permissList = response['authResponse']['grantedScopes'].split(",");
+ //save user info
+ self._isLoggedIn = true;
+ self._userInfo = response['authResponse'];
+ typeof callback === 'function' && callback(0, {
+ permissions: permissList
+ });
+ } else {
+ self._isLoggedIn = false;
+ self._userInfo = {};
+ typeof callback === 'function' && callback(response['error_code'] || 1, {
+ error_message: response['error_message'] || "Unknown error"
+ });
+ }
+ }, {
+ scope: permissionsStr,
+ return_scopes: true
+ });
+ },
+
+ /**
+ * Acquiring AccessToken
+ * @return {String}
+ * @example
+ * //example
+ * var accessToken = plugin.FacebookAgent.getAccessToken();
+ */
+ getAccessToken: function () {
+ return this._userInfo ? this._userInfo['accessToken'] : null;
+ },
+
+ /**
+ * Acquiring User ID
+ * @return {String}
+ * @example
+ * //example
+ * var userID = plugin.FacebookAgent.getUserID();
+ */
+ getUserID: function () {
+ return this._userInfo ? this._userInfo['userID'] : null;
+ },
+
+ _share: function (info, callback) {
+ FB.ui({
+ method: 'share',
+ name: info['title'],
+ caption: info['caption'],
+ description: info['text'],
+ href: info['link'],
+ picture: info['imageUrl']
+ },
+ function (response) {
+ if (response) {
+ if (response['post_id'])
+ typeof callback === 'function' && callback(0, {
+ didComplete: true,
+ post_id: response['post_id']
+ });
+ else
+ typeof callback === 'function' && callback(response['error_code'] || 1, {
+ error_message: response['error_message'] || "Unknown error"
+ });
+ } else {
+ typeof callback === 'function' && callback(1, {
+ error_message: "Unknown error"
+ });
+ }
+ });
+ },
+
+ /**
+ * Request a web dialog for Facebook sharing
+ * @param info
+ * @param callback
+ */
+ dialog: function (info, callback) {
+ if (!info) {
+ typeof callback === 'function' && callback(1, {
+ error_message: "No info parameter provided"
+ });
+ return;
+ }
+ if (!this.canPresentDialog(info)) {
+ typeof callback === 'function' && callback(1, {
+ error_message: "The requested dialog: " + info['dialog'] + " can not be presented on Web"
+ });
+ return;
+ }
+
+ // Preprocess properties
+ info['name'] = info['name'] || info['site'];
+ delete info['site'];
+
+ info['href'] = info['href'] || info['link'] || info['siteUrl'];
+ delete info['siteUrl'];
+ delete info['link'];
+
+ info['picture'] = info['picture'] || info['image'] || info['photo'] || info['imageUrl'] || info['imagePath'];
+ delete info['imageUrl'];
+ delete info['imagePath'];
+ delete info['photo'];
+ delete info['image'];
+
+ info['caption'] = info['title'] || info['caption'];
+ delete info['title'];
+
+ info['description'] = info['text'] || info['description'];
+ delete info['text'];
+
+ var method = info['dialog'];
+ delete info['dialog'];
+
+ if (method === 'shareLink' || method == 'feedDialog') {
+ info['method'] = 'share';
+ } else if (method == 'messageLink') {
+ info['method'] = 'send';
+ info['link'] = info['href'];
+ } else if (method == 'shareOpenGraph') {
+ info['method'] = 'share_open_graph';
+
+ if (info['url']) {
+ var obj = {};
+ if (info["preview_property_name"])
+ obj[info["preview_property_name"]] = info["url"];
+ else
+ obj["object"] = info["url"];
+
+ for (var p in info) {
+ if (p != "method" && p != "action_type" && p != "action_properties") {
+ info[p] && (obj[p] = info[p]);
+ delete info[p];
+ }
+ }
+
+ info['action_properties'] = JSON.stringify(obj);
+ }
+ }
+
+ FB.ui(info,
+ function (response) {
+ if (response && typeof callback === 'function') {
+ if (response['post_id'] || response['success']) {
+ callback(0, {
+ didComplete: true,
+ post_id: response['post_id'] || ""
+ });
+ }
+ else {
+ if (response['error_code']) {
+ callback(response['error_code'], {
+ error_message : response['error_message'] || 'Unknown error'
+ });
+ }
+ else callback(0, response);
+ }
+ } else if (response == undefined && typeof callback === 'function') {
+ callback(1, {
+ error_message: "Unknown error"
+ });
+ }
+ });
+ },
+
+ /**
+ * Check whether the share request can be achieved
+ * @param info
+ */
+ canPresentDialog: function (info) {
+ if (info && info['dialog'] && (
+ info['dialog'] === 'shareLink' ||
+ info['dialog'] === 'feedDialog' ||
+ info['dialog'] === 'shareOpenGraph' ||
+ info['dialog'] === 'messageLink'))
+ return true;
+ else
+ return false;
+ },
+ /**
+ * FB.api
+ * @param {String} path
+ * @param {Number} httpmethod
+ * @param {Object} params
+ * @param {Function} callback
+ */
+ api: function (path, httpmethod, params, callback) {
+ if (typeof params === 'function') {
+ callback = params;
+ params = {};
+ }
+ FB.api(path, httpmethod, params, function (response) {
+ if (response.error) {
+ typeof callback === 'function' && callback(response['error']['code'], {
+ error_message: response['error']['message'] || 'Unknown error'
+ })
+ } else {
+ typeof callback === 'function' && callback(0, response);
+ }
+ });
+ },
+
+ _getPermissionList: function (callback) {
+ FB.api("/me/permissions", function (response) {
+ if (response['data']) {
+ var permissionList = [];
+ for (var i = 0; i < response['data'].length; i++) {
+ if (response['data'][i]["status"] == "granted") {
+ permissionList.push(response['data'][i]['permission']);
+ }
+ }
+ typeof callback == 'function' && callback(0, {
+ permissions: permissionList
+ });
+ } else {
+ if (!response['error'])
+ response['error'] = {};
+ typeof callback == 'function' && callback(response['error']['code'] || 1, {
+ error_message: response['error']['message'] || 'Unknown error'
+ });
+ }
+ })
+ },
+
+ destroyInstance: function () {
+ },
+ canvas:{
+ /**
+ * Payment request
+ * @param {Object} info
+ * @param {Function} callback
+ */
+ pay: function (info, callback) {
+ /*
+ * Reference document
+ * https://developers.facebook.com/docs/payments/reference/paydialog
+ */
+ info['method'] = 'pay';
+ info['action'] = 'purchaseitem';
+
+ FB.ui(info, function (response) {
+ if (response['error_code']) {
+ callback(response['error_code'] || 1, {
+ error_message: response['error_message'] || response['error_msg'] || 'Unknown error'
+ });
+ } else {
+ callback(0, response);
+ }
+ })
+ }
+ },
+
+ /**
+ * Send an app requests to friends
+ * @param {Object} info
+ * @param {Function} callback
+ */
+ appRequest: function (info, callback) {
+ if (!info) {
+ typeof callback === 'function' && callback(1, {
+ error_message: "No info parameter provided"
+ });
+ return;
+ }
+
+ info['method'] = "apprequests";
+
+ FB.ui(info,
+ function (response) {
+ if (response) {
+ if (response['error_code']) {
+ typeof callback === 'function' && callback(response['error_code'], {
+ error_message : response['error_message'] || 'Unknown error'
+ });
+ }
+ else {
+ typeof callback === 'function' && callback(0, response);
+ }
+ } else {
+ typeof callback === 'function' && callback(1, {
+ error_message: "Unknown error"
+ });
+ }
+ });
+ },
+
+ /**
+ * Log an event
+ * @param {String} eventName
+ * @param {Number} valueToSum
+ * @param {Object} parameters
+ */
+ logEvent: function (eventName, valueToSum, parameters) {
+ if (eventName == undefined) return;
+ if (valueToSum === undefined && parameters === undefined) {
+ FB.AppEvents.logEvent(eventName, null, null);
+ } else if (typeof valueToSum === "number" && parameters === undefined) {
+ FB.AppEvents.logEvent(eventName, valueToSum);
+ } else if (typeof valueToSum === "object" && parameters === undefined) {
+ FB.AppEvents.logEvent(eventName, null, valueToSum);
+ } else {
+ FB.AppEvents.logEvent(eventName, valueToSum, parameters);
+ }
+ },
+
+ /**
+ * Activate App
+ */
+ activateApp: function () {
+ FB.AppEvents.activateApp();
+ },
+
+ /**
+ * Log a purchase
+ * @param {Number} amount Amount of the purchase
+ * @param {String} currency The currency
+ * @param {Object} param Supplemental parameters
+ */
+ logPurchase:function(amount, currency, param){
+ FB.AppEvents.logPurchase(amount, currency, param);
+ }
+});
diff --git a/external/pluginx/platform/facebook_sdk.js b/external/pluginx/platform/facebook_sdk.js
new file mode 100644
index 0000000000..bc05068323
--- /dev/null
+++ b/external/pluginx/platform/facebook_sdk.js
@@ -0,0 +1,151 @@
+
+/*1411456395,,JIT Construction: v1425205,zh_CN*/
+
+/**
+ * Copyright Facebook Inc.
+ *
+ * Licensed under the Apache License, Version 2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
+ */
+try {window.FB || (function(window) {
+ var self = window, document = window.document;
+ var setTimeout = window.setTimeout, setInterval = window.setInterval,clearTimeout = window.clearTimeout,clearInterval = window.clearInterval;var __DEV__ = 0;
+ function emptyFunction() {};
+ var __w, __t;
+ __t=function(a){return a[0];};__w=function(a){return a;};
+ var require,__d;(function(a){var b={},c={},d=['global','require','requireDynamic','requireLazy','module','exports'];require=function(e,f){if(c.hasOwnProperty(e))return c[e];if(!b.hasOwnProperty(e)){if(f)return null;throw new Error('Module '+e+' has not been defined');}var g=b[e],h=g.deps,i=g.factory.length,j,k=[];for(var l=0;l1?Number(arguments[1]):0;if(isNaN(j))j=0;var k=Math.min(Math.max(j,0),i.length);return i.indexOf(String(h),j)==k;};g.endsWith=function(h){var i=String(this);if(this==null)throw new TypeError('String.prototype.endsWith called on null or undefined');var j=i.length,k=String(h),l=arguments.length>1?Number(arguments[1]):j;if(isNaN(l))l=0;var m=Math.min(Math.max(l,0),j),n=m-k.length;if(n<0)return false;return i.lastIndexOf(k,n)==n;};g.contains=function(h){if(this==null)throw new TypeError('String.prototype.contains called on null or undefined');var i=String(this),j=arguments.length>1?Number(arguments[1]):0;if(isNaN(j))j=0;return i.indexOf(String(h),j)!=-1;};g.repeat=function(h){if(this==null)throw new TypeError('String.prototype.repeat called on null or undefined');var i=String(this),j=h?Number(h):0;if(isNaN(j))j=0;if(j<0||j===Infinity)throw RangeError();if(j===1)return i;if(j===0)return '';var k='';while(j){if(j&1)k+=i;if((j>>=1))i+=i;}return k;};e.exports=g;},null);
+ __d("ES5Array",[],function(a,b,c,d,e,f){var g={};g.isArray=function(h){return Object.prototype.toString.call(h)=='[object Array]';};e.exports=g;},null);
+ __d("ie8DontEnum",[],function(a,b,c,d,e,f){var g=['toString','toLocaleString','valueOf','hasOwnProperty','isPrototypeOf','prototypeIsEnumerable','constructor'],h=({}).hasOwnProperty,i=function(){};if(({toString:true}).propertyIsEnumerable('toString'))i=function(j,k){for(var l=0;l1)))/4)-ca((ga-1901+ha)/100)+ca((ga-1601+ha)/400);};}if(typeof JSON=="object"&&JSON){k.stringify=JSON.stringify;k.parse=JSON.parse;}if((m=typeof k.stringify=="function"&&!ea)){(ba=function(){return 1;}).toJSON=ba;try{m=k.stringify(0)==="0"&&k.stringify(new Number())==="0"&&k.stringify(new String())=='""'&&k.stringify(g)===j&&k.stringify(j)===j&&k.stringify()===j&&k.stringify(ba)==="1"&&k.stringify([ba])=="[1]"&&k.stringify([j])=="[null]"&&k.stringify(null)=="null"&&k.stringify([j,g,null])=="[null,null,null]"&&k.stringify({result:[ba,true,false,null,"\0\b\n\f\r\t"]})==l&&k.stringify(null,ba)==="1"&&k.stringify([1,2],null,1)=="[\n 1,\n 2\n]"&&k.stringify(new Date(-8.64e+15))=='"-271821-04-20T00:00:00.000Z"'&&k.stringify(new Date(8.64e+15))=='"+275760-09-13T00:00:00.000Z"'&&k.stringify(new Date(-62198755200000))=='"-000001-01-01T00:00:00.000Z"'&&k.stringify(new Date(-1))=='"1969-12-31T23:59:59.999Z"';}catch(fa){m=false;}}if(typeof k.parse=="function")try{if(k.parse("0")===0&&!k.parse(false)){ba=k.parse(l);if((r=ba.A.length==5&&ba.A[0]==1)){try{r=!k.parse('"\t"');}catch(fa){}if(r)try{r=k.parse("01")!=1;}catch(fa){}}}}catch(fa){r=false;}ba=l=null;if(!m||!r){if(!(h={}.hasOwnProperty))h=function(ga){var ha={},ia;if((ha.__proto__=null,ha.__proto__={toString:1},ha).toString!=g){h=function(ja){var ka=this.__proto__,la=ja in (this.__proto__=null,this);this.__proto__=ka;return la;};}else{ia=ha.constructor;h=function(ja){var ka=(this.constructor||ia).prototype;return ja in this&&!(ja in ka&&this[ja]===ka[ja]);};}ha=null;return h.call(this,ga);};i=function(ga,ha){var ia=0,ja,ka,la,ma;(ja=function(){this.valueOf=0;}).prototype.valueOf=0;ka=new ja();for(la in ka)if(h.call(ka,la))ia++;ja=ka=null;if(!ia){ka=["valueOf","toString","toLocaleString","propertyIsEnumerable","isPrototypeOf","hasOwnProperty","constructor"];ma=function(na,oa){var pa=g.call(na)=="[object Function]",qa,ra;for(qa in na)if(!(pa&&qa=="prototype")&&h.call(na,qa))oa(qa);for(ra=ka.length;qa=ka[--ra];h.call(na,qa)&&oa(qa));};}else if(ia==2){ma=function(na,oa){var pa={},qa=g.call(na)=="[object Function]",ra;for(ra in na)if(!(qa&&ra=="prototype")&&!h.call(pa,ra)&&(pa[ra]=1)&&h.call(na,ra))oa(ra);};}else ma=function(na,oa){var pa=g.call(na)=="[object Function]",qa,ra;for(qa in na)if(!(pa&&qa=="prototype")&&h.call(na,qa)&&!(ra=qa==="constructor"))oa(qa);if(ra||h.call(na,(qa="constructor")))oa(qa);};return ma(ga,ha);};if(!m){n={"\\":"\\\\",'"':'\\"',"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t"};o=function(ga,ha){return ("000000"+(ha||0)).slice(-ga);};p=function(ga){var ha='"',ia=0,ja;for(;ja=ga.charAt(ia);ia++)ha+='\\"\b\f\n\r\t'.indexOf(ja)>-1?n[ja]:ja<" "?"\\u00"+o(2,ja.charCodeAt(0).toString(16)):ja;return ha+'"';};q=function(ga,ha,ia,ja,ka,la,ma){var na=ha[ga],oa,pa,qa,ra,sa,ta,ua,va,wa,xa,ya,za,ab,bb,cb;if(typeof na=="object"&&na){oa=g.call(na);if(oa=="[object Date]"&&!h.call(na,"toJSON")){if(na>-1/0&&na<1/0){if(ea){ra=ca(na/86400000);for(pa=ca(ra/365.2425)+1970-1;ea(pa+1,0)<=ra;pa++);for(qa=ca((ra-ea(pa,0))/30.42);ea(pa,qa+1)<=ra;qa++);ra=1+ra-ea(pa,qa);sa=(na%86400000+86400000)%86400000;ta=ca(sa/3600000)%24;ua=ca(sa/60000)%60;va=ca(sa/1000)%60;wa=sa%1000;}else{pa=na.getUTCFullYear();qa=na.getUTCMonth();ra=na.getUTCDate();ta=na.getUTCHours();ua=na.getUTCMinutes();va=na.getUTCSeconds();wa=na.getUTCMilliseconds();}na=(pa<=0||pa>=10000?(pa<0?"-":"+")+o(6,pa<0?-pa:pa):o(4,pa))+"-"+o(2,qa+1)+"-"+o(2,ra)+"T"+o(2,ta)+":"+o(2,ua)+":"+o(2,va)+"."+o(3,wa)+"Z";}else na=null;}else if(typeof na.toJSON=="function"&&((oa!="[object Number]"&&oa!="[object String]"&&oa!="[object Array]")||h.call(na,"toJSON")))na=na.toJSON(ga);}if(ia)na=ia.call(ha,ga,na);if(na===null)return "null";oa=g.call(na);if(oa=="[object Boolean]"){return ""+na;}else if(oa=="[object Number]"){return na>-1/0&&na<1/0?""+na:"null";}else if(oa=="[object String]")return p(na);if(typeof na=="object"){for(ab=ma.length;ab--;)if(ma[ab]===na)throw TypeError();ma.push(na);xa=[];bb=la;la+=ka;if(oa=="[object Array]"){for(za=0,ab=na.length;za0)for(ja="",ia>10&&(ia=10);ja.length-1){z++;}else if("{}[]:,".indexOf(ia)>-1){z++;return ia;}else if(ia=='"'){for(ja="@",z++;z-1){ja+=t[ia];z++;}else if(ia=="u"){ka=++z;for(la=z+4;z="0"&&ia<="9"||ia>="a"&&ia<="f"||ia>="A"&&ia<="F"))u();}ja+=s("0x"+ga.slice(ka,z));}else u();}else{if(ia=='"')break;ja+=ia;z++;}}if(ga.charAt(z)=='"'){z++;return ja;}u();}else{ka=z;if(ia=="-"){ma=true;ia=ga.charAt(++z);}if(ia>="0"&&ia<="9"){if(ia=="0"&&(ia=ga.charAt(z+1),ia>="0"&&ia<="9"))u();ma=false;for(;z="0"&&ia<="9");z++);if(ga.charAt(z)=="."){la=++z;for(;la="0"&&ia<="9");la++);if(la==z)u();z=la;}ia=ga.charAt(z);if(ia=="e"||ia=="E"){ia=ga.charAt(++z);if(ia=="+"||ia=="-")z++;for(la=z;la="0"&&ia<="9");la++);if(la==z)u();z=la;}return +ga.slice(ka,z);}if(ma)u();if(ga.slice(z,z+4)=="true"){z+=4;return true;}else if(ga.slice(z,z+5)=="false"){z+=5;return false;}else if(ga.slice(z,z+4)=="null"){z+=4;return null;}u();}}return "$";};w=function(ga){var ha,ia,ja;if(ga=="$")u();if(typeof ga=="string"){if(ga.charAt(0)=="@")return ga.slice(1);if(ga=="["){ha=[];for(;;ia||(ia=true)){ga=v();if(ga=="]")break;if(ia)if(ga==","){ga=v();if(ga=="]")u();}else u();if(ga==",")u();ha.push(w(ga));}return ha;}else if(ga=="{"){ha={};for(;;ia||(ia=true)){ga=v();if(ga=="}")break;if(ia)if(ga==","){ga=v();if(ga=="}")u();}else u();if(ga==","||typeof ga!="string"||ga.charAt(0)!="@"||v()!=":")u();ha[ga.slice(1)]=w(v());}return ha;}u();}return ga;};y=function(ga,ha,ia){var ja=x(ga,ha,ia);if(ja===j){delete ga[ha];}else ga[ha]=ja;};x=function(ga,ha,ia){var ja=ga[ha],ka;if(typeof ja=="object"&&ja)if(g.call(ja)=="[object Array]"){for(ka=ja.length;ka--;)y(ja,ka,ia);}else i(ja,function(la){y(ja,la,ia);});return ia.call(ga,ha,ja);};k.parse=function(ga,ha){z=0;aa=ga;var ia=w(v());if(v()!="$")u();z=aa=null;return ha&&g.call(ha)=="[object Function]"?x((ba={},ba[""]=ia,ba),"",ha):ia;};}}}).call(this);},null);
+ __d("ES6Object",["ie8DontEnum"],function(a,b,c,d,e,f,g){var h=({}).hasOwnProperty,i={assign:function(j){var k=Array.prototype.slice.call(arguments,1);if(j==null)throw new TypeError('Object.assign target cannot be null or undefined');j=Object(j);for(var l=0;l>>0;for(var l=0;l9999?'+':''))+('00000'+Math.abs(i)).slice(0<=i&&i<=9999?-4:-6);return i+'-'+g(this.getUTCMonth()+1)+'-'+g(this.getUTCDate())+'T'+g(this.getUTCHours())+':'+g(this.getUTCMinutes())+':'+g(this.getUTCSeconds())+'.'+(this.getUTCMilliseconds()/1000).toFixed(3).slice(2,5)+'Z';}};e.exports=h;},null);
+ __d("ES6Number",[],function(a,b,c,d,e,f){var g={isFinite:function(h){return (typeof h=='number')&&isFinite(h);},isNaN:function(h){return (typeof h=='number')&&isNaN(h);}};e.exports=g;},null);
+ __d("ES",["ES5ArrayPrototype","ES5FunctionPrototype","ES5StringPrototype","ES5Array","ES5Object","ES5Date","JSON3","ES6Object","ES6ArrayPrototype","ES6DatePrototype","ES6Number"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q){var r=({}).toString,s={'JSON.stringify':m.stringify,'JSON.parse':m.parse},t={'Array.prototype':g,'Function.prototype':h,'String.prototype':i,Object:k,Array:j,Date:l},u={Object:n,'Array.prototype':o,'Date.prototype':p,Number:q};function v(x){for(var y in x){if(!x.hasOwnProperty(y))continue;var z=x[y],aa=y.split('.'),ba=aa.length==2?window[aa[0]][aa[1]]:window[y];for(var ca in z){if(!z.hasOwnProperty(ca))continue;var da=ba[ca];s[y+'.'+ca]=da&&/\{\s+\[native code\]\s\}/.test(da)?da:z[ca];}}}v(t);v(u);function w(x,y,z){var aa=Array.prototype.slice.call(arguments,3),ba=z?r.call(x).slice(8,-1)+'.prototype':x,ca=s[ba+'.'+y]||x[y];if(typeof ca==='function')return ca.apply(x,aa);}e.exports=w;},null);
+ var ES = require('ES');
+ __d("JSSDKRuntimeConfig",[],{"locale":"zh_CN","rtl":false,"revision":"1425205"});__d("JSSDKConfig",[],{"bustCache":true,"tagCountLogRate":0.01,"errorHandling":{"rate":4},"usePluginPipe":true,"features":{"allow_non_canvas_app_events":false,"event_subscriptions_log":{"rate":0.01,"value":10000},"kill_fragment":true,"xfbml_profile_pic_server":true,"error_handling":{"rate":4},"e2e_ping_tracking":{"rate":1.0e-6},"xd_timeout":{"rate":4,"value":30000},"use_bundle":true,"launch_payment_dialog_via_pac":{"rate":100}},"api":{"mode":"warn","whitelist":["Canvas","Canvas.Prefetcher","Canvas.Prefetcher.addStaticResource","Canvas.Prefetcher.setCollectionMode","Canvas.getPageInfo","Canvas.hideFlashElement","Canvas.scrollTo","Canvas.setAutoGrow","Canvas.setDoneLoading","Canvas.setSize","Canvas.setUrlHandler","Canvas.showFlashElement","Canvas.startTimer","Canvas.stopTimer","Data","Data.process","Data.query","Data.query:wait","Data.waitOn","Data.waitOn:wait","Event","Event.subscribe","Event.unsubscribe","Music.flashCallback","Music.init","Music.send","Payment","Payment.cancelFlow","Payment.continueFlow","Payment.init","Payment.lockForProcessing","Payment.unlockForProcessing","Payment.parse","Payment.setSize","ThirdPartyProvider","ThirdPartyProvider.init","ThirdPartyProvider.sendData","UA","UA.nativeApp","XFBML","XFBML.RecommendationsBar","XFBML.RecommendationsBar.markRead","XFBML.parse","addFriend","api","getAccessToken","getAuthResponse","getLoginStatus","getUserID","init","login","logout","publish","share","ui","ui:subscribe","AppEvents","AppEvents.activateApp","AppEvents.logEvent","AppEvents.logPurchase","AppEvents.EventNames","AppEvents.ParameterNames"]},"initSitevars":{"enableMobileComments":1,"iframePermissions":{"read_stream":false,"manage_mailbox":false,"manage_friendlists":false,"read_mailbox":false,"publish_checkins":true,"status_update":true,"photo_upload":true,"video_upload":true,"sms":false,"create_event":true,"rsvp_event":true,"offline_access":true,"email":true,"xmpp_login":false,"create_note":true,"share_item":true,"export_stream":false,"publish_stream":true,"publish_likes":true,"ads_management":false,"contact_email":true,"access_private_data":false,"read_insights":false,"read_requests":false,"read_friendlists":true,"manage_pages":false,"physical_login":false,"manage_groups":false,"read_deals":false}}});__d("UrlMapConfig",[],{"www":"www.facebook.com","m":"m.facebook.com","connect":"connect.facebook.net","business":"business.facebook.com","api_https":"api.facebook.com","api_read_https":"api-read.facebook.com","graph_https":"graph.facebook.com","fbcdn_http":"static.ak.fbcdn.net","fbcdn_https":"fbstatic-a.akamaihd.net","cdn_http":"static.ak.facebook.com","cdn_https":"s-static.ak.facebook.com"});__d("JSSDKXDConfig",[],{"XdUrl":"\/connect\/xd_arbiter.php?version=41","XdBundleUrl":"\/connect\/xd_arbiter\/ZEbdHPQfV3x.js?version=41","Flash":{"path":"https:\/\/connect.facebook.net\/rsrc.php\/v1\/yR\/r\/ks_9ZXiQ0GL.swf"},"useCdn":true});__d("JSSDKCssConfig",[],{"rules":".fb_hidden{position:absolute;top:-10000px;z-index:10001}.fb_invisible{display:none}.fb_reset{background:none;border:0;border-spacing:0;color:#000;cursor:auto;direction:ltr;font-family:\"lucida grande\", tahoma, verdana, arial, sans-serif;font-size:12px;font-style:normal;font-variant:normal;font-weight:normal;letter-spacing:normal;line-height:1;margin:0;overflow:visible;padding:0;text-align:left;text-decoration:none;text-indent:0;text-shadow:none;text-transform:none;visibility:visible;white-space:normal;word-spacing:normal}.fb_reset>div{overflow:hidden}.fb_link img{border:none}\n.fb_dialog{background:rgba(82, 82, 82, .7);position:absolute;top:-10000px;z-index:10001}.fb_reset .fb_dialog_legacy{overflow:visible}.fb_dialog_advanced{padding:10px;-moz-border-radius:8px;-webkit-border-radius:8px;border-radius:8px}.fb_dialog_content{background:#fff;color:#333}.fb_dialog_close_icon{background:url(http:\/\/static.ak.fbcdn.net\/rsrc.php\/v2\/yq\/r\/IE9JII6Z1Ys.png) no-repeat scroll 0 0 transparent;_background-image:url(http:\/\/static.ak.fbcdn.net\/rsrc.php\/v2\/yL\/r\/s816eWC-2sl.gif);cursor:pointer;display:block;height:15px;position:absolute;right:18px;top:17px;width:15px}.fb_dialog_mobile .fb_dialog_close_icon{top:5px;left:5px;right:auto}.fb_dialog_padding{background-color:transparent;position:absolute;width:1px;z-index:-1}.fb_dialog_close_icon:hover{background:url(http:\/\/static.ak.fbcdn.net\/rsrc.php\/v2\/yq\/r\/IE9JII6Z1Ys.png) no-repeat scroll 0 -15px transparent;_background-image:url(http:\/\/static.ak.fbcdn.net\/rsrc.php\/v2\/yL\/r\/s816eWC-2sl.gif)}.fb_dialog_close_icon:active{background:url(http:\/\/static.ak.fbcdn.net\/rsrc.php\/v2\/yq\/r\/IE9JII6Z1Ys.png) no-repeat scroll 0 -30px transparent;_background-image:url(http:\/\/static.ak.fbcdn.net\/rsrc.php\/v2\/yL\/r\/s816eWC-2sl.gif)}.fb_dialog_loader{background-color:#f2f2f2;border:1px solid #606060;font-size:25px;padding:20px}.fb_dialog_top_left,.fb_dialog_top_right,.fb_dialog_bottom_left,.fb_dialog_bottom_right{height:10px;width:10px;overflow:hidden;position:absolute}.fb_dialog_top_left{background:url(http:\/\/static.ak.fbcdn.net\/rsrc.php\/v2\/ye\/r\/8YeTNIlTZjm.png) no-repeat 0 0;left:-10px;top:-10px}.fb_dialog_top_right{background:url(http:\/\/static.ak.fbcdn.net\/rsrc.php\/v2\/ye\/r\/8YeTNIlTZjm.png) no-repeat 0 -10px;right:-10px;top:-10px}.fb_dialog_bottom_left{background:url(http:\/\/static.ak.fbcdn.net\/rsrc.php\/v2\/ye\/r\/8YeTNIlTZjm.png) no-repeat 0 -20px;bottom:-10px;left:-10px}.fb_dialog_bottom_right{background:url(http:\/\/static.ak.fbcdn.net\/rsrc.php\/v2\/ye\/r\/8YeTNIlTZjm.png) no-repeat 0 -30px;right:-10px;bottom:-10px}.fb_dialog_vert_left,.fb_dialog_vert_right,.fb_dialog_horiz_top,.fb_dialog_horiz_bottom{position:absolute;background:#525252;filter:alpha(opacity=70);opacity:.7}.fb_dialog_vert_left,.fb_dialog_vert_right{width:10px;height:100\u0025}.fb_dialog_vert_left{margin-left:-10px}.fb_dialog_vert_right{right:0;margin-right:-10px}.fb_dialog_horiz_top,.fb_dialog_horiz_bottom{width:100\u0025;height:10px}.fb_dialog_horiz_top{margin-top:-10px}.fb_dialog_horiz_bottom{bottom:0;margin-bottom:-10px}.fb_dialog_iframe{line-height:0}.fb_dialog_content .dialog_title{background:#6d84b4;border:1px solid #3b5998;color:#fff;font-size:15px;font-weight:bold;margin:0}.fb_dialog_content .dialog_title>span{background:url(http:\/\/static.ak.fbcdn.net\/rsrc.php\/v2\/yd\/r\/Cou7n-nqK52.gif) no-repeat 5px 50\u0025;float:left;padding:5px 0 7px 26px}body.fb_hidden{-webkit-transform:none;height:100\u0025;margin:0;overflow:visible;position:absolute;top:-10000px;left:0;width:100\u0025}.fb_dialog.fb_dialog_mobile.loading{background:url(http:\/\/static.ak.fbcdn.net\/rsrc.php\/v2\/ya\/r\/3rhSv5V8j3o.gif) white no-repeat 50\u0025 50\u0025;min-height:100\u0025;min-width:100\u0025;overflow:hidden;position:absolute;top:0;z-index:10001}.fb_dialog.fb_dialog_mobile.loading.centered{max-height:590px;min-height:590px;max-width:500px;min-width:500px}#fb-root #fb_dialog_ipad_overlay{background:rgba(0, 0, 0, .45);position:absolute;left:0;top:0;width:100\u0025;min-height:100\u0025;z-index:10000}#fb-root #fb_dialog_ipad_overlay.hidden{display:none}.fb_dialog.fb_dialog_mobile.loading iframe{visibility:hidden}.fb_dialog_content .dialog_header{-webkit-box-shadow:white 0 1px 1px -1px inset;background:-webkit-gradient(linear, 0\u0025 0\u0025, 0\u0025 100\u0025, from(#738ABA), to(#2C4987));border-bottom:1px solid;border-color:#1d4088;color:#fff;font:14px Helvetica, sans-serif;font-weight:bold;text-overflow:ellipsis;text-shadow:rgba(0, 30, 84, .296875) 0 -1px 0;vertical-align:middle;white-space:nowrap}.fb_dialog_content .dialog_header table{-webkit-font-smoothing:subpixel-antialiased;height:43px;width:100\u0025}.fb_dialog_content .dialog_header td.header_left{font-size:13px;padding-left:5px;vertical-align:middle;width:60px}.fb_dialog_content .dialog_header td.header_right{font-size:13px;padding-right:5px;vertical-align:middle;width:60px}.fb_dialog_content .touchable_button{background:-webkit-gradient(linear, 0\u0025 0\u0025, 0\u0025 100\u0025, from(#4966A6), color-stop(.5, #355492), to(#2A4887));border:1px solid #29447e;-webkit-background-clip:padding-box;-webkit-border-radius:3px;-webkit-box-shadow:rgba(0, 0, 0, .117188) 0 1px 1px inset, rgba(255, 255, 255, .167969) 0 1px 0;display:inline-block;margin-top:3px;max-width:85px;line-height:18px;padding:4px 12px;position:relative}.fb_dialog_content .dialog_header .touchable_button input{border:none;background:none;color:#fff;font:12px Helvetica, sans-serif;font-weight:bold;margin:2px -12px;padding:2px 6px 3px 6px;text-shadow:rgba(0, 30, 84, .296875) 0 -1px 0}.fb_dialog_content .dialog_header .header_center{color:#fff;font-size:17px;font-weight:bold;line-height:18px;text-align:center;vertical-align:middle}.fb_dialog_content .dialog_content{background:url(http:\/\/static.ak.fbcdn.net\/rsrc.php\/v2\/y9\/r\/jKEcVPZFk-2.gif) no-repeat 50\u0025 50\u0025;border:1px solid #555;border-bottom:0;border-top:0;height:150px}.fb_dialog_content .dialog_footer{background:#f2f2f2;border:1px solid #555;border-top-color:#ccc;height:40px}#fb_dialog_loader_close{float:left}.fb_dialog.fb_dialog_mobile .fb_dialog_close_button{text-shadow:rgba(0, 30, 84, .296875) 0 -1px 0}.fb_dialog.fb_dialog_mobile .fb_dialog_close_icon{visibility:hidden}\n.fb_iframe_widget{display:inline-block;position:relative}.fb_iframe_widget span{display:inline-block;position:relative;text-align:justify}.fb_iframe_widget iframe{position:absolute}.fb_iframe_widget_lift{z-index:1}.fb_hide_iframes iframe{position:relative;left:-10000px}.fb_iframe_widget_loader{position:relative;display:inline-block}.fb_iframe_widget_fluid{display:inline}.fb_iframe_widget_fluid span{width:100\u0025}.fb_iframe_widget_loader iframe{min-height:32px;z-index:2;zoom:1}.fb_iframe_widget_loader .FB_Loader{background:url(http:\/\/static.ak.fbcdn.net\/rsrc.php\/v2\/y9\/r\/jKEcVPZFk-2.gif) no-repeat;height:32px;width:32px;margin-left:-16px;position:absolute;left:50\u0025;z-index:4}\n.fbpluginrecommendationsbarleft,.fbpluginrecommendationsbarright{position:fixed !important;bottom:0;z-index:999}.fbpluginrecommendationsbarleft{left:10px}.fbpluginrecommendationsbarright{right:10px}","components":["css:fb.css.base","css:fb.css.dialog","css:fb.css.iframewidget","css:fb.css.plugin.recommendationsbar"]});__d("ApiClientConfig",[],{"FlashRequest":{"swfUrl":"https:\/\/connect.facebook.net\/rsrc.php\/v1\/yW\/r\/PvklbuW2Ycn.swf"}});__d("JSSDKCanvasPrefetcherConfig",[],{"blacklist":[144959615576466],"sampleRate":500});__d("JSSDKPluginPipeConfig",[],{"threshold":0,"enabledApps":{"209753825810663":1,"187288694643718":1}});
+ __d("QueryString",[],function(a,b,c,d,e,f){function g(k){var l=[];ES(ES('Object','keys',false,k).sort(),'forEach',true,function(m){var n=k[m];if(typeof n==='undefined')return;if(n===null){l.push(m);return;}l.push(encodeURIComponent(m)+'='+encodeURIComponent(n));});return l.join('&');}function h(k,l){var m={};if(k==='')return m;var n=k.split('&');for(var o=0;oh);},ie64:function(){return x.ie()&&r;},firefox:function(){return w()||i;},opera:function(){return w()||j;},webkit:function(){return w()||k;},safari:function(){return x.webkit();},chrome:function(){return w()||l;},windows:function(){return w()||o;},osx:function(){return w()||n;},linux:function(){return w()||p;},iphone:function(){return w()||s;},mobile:function(){return w()||(s||t||q||v);},nativeApp:function(){return w()||u;},android:function(){return w()||q;},ipad:function(){return w()||t;}};e.exports=x;},null);
+ __d("hasNamePropertyBug",["guid","UserAgent_DEPRECATED"],function(a,b,c,d,e,f,g,h){var i=h.ie()?undefined:false;function j(){var l=document.createElement("form"),m=l.appendChild(document.createElement("input"));m.name=g();i=m!==l.elements[m.name];l=m=null;return i;}function k(){return typeof i==='undefined'?j():i;}e.exports=k;},null);
+ __d("wrapFunction",[],function(a,b,c,d,e,f){var g={};function h(i,j,k){j=j||'default';return function(){var l=j in g?g[j](i,k):i;return l.apply(this,arguments);};}h.setWrapper=function(i,j){j=j||'default';g[j]=i;};e.exports=h;},null);
+ __d("DOMEventListener",["wrapFunction"],function(a,b,c,d,e,f,g){var h,i;if(window.addEventListener){h=function(k,l,m){m.wrapper=g(m,'entry','DOMEventListener.add '+l);k.addEventListener(l,m.wrapper,false);};i=function(k,l,m){k.removeEventListener(l,m.wrapper,false);};}else if(window.attachEvent){h=function(k,l,m){m.wrapper=g(m,'entry','DOMEventListener.add '+l);k.attachEvent('on'+l,m.wrapper);};i=function(k,l,m){k.detachEvent('on'+l,m.wrapper);};}else i=h=function(){};var j={add:function(k,l,m){h(k,l,m);return {remove:function(){i(k,l,m);k=null;}};},remove:i};e.exports=j;},null);
+ __d("sdk.createIframe",["guid","hasNamePropertyBug","DOMEventListener"],function(a,b,c,d,e,f,g,h,i){function j(k){k=ES('Object','assign',false,{},k);var l,m=k.name||g(),n=k.root,o=k.style||{border:'none'},p=k.url,q=k.onload,r=k.onerror;if(h()){l=document.createElement('');}else{l=document.createElement("iframe");l.name=m;}delete k.style;delete k.name;delete k.url;delete k.root;delete k.onload;delete k.onerror;var s=ES('Object','assign',false,{frameBorder:0,allowTransparency:true,scrolling:'no'},k);if(s.width)l.width=s.width+'px';if(s.height)l.height=s.height+'px';delete s.height;delete s.width;for(var t in s)if(s.hasOwnProperty(t))l.setAttribute(t,s[t]);ES('Object','assign',false,l.style,o);l.src="javascript:false";n.appendChild(l);if(q)var u=i.add(l,'load',function(){u.remove();q();});if(r)var v=i.add(l,'error',function(){v.remove();r();});l.src=p;return l;}e.exports=j;},null);
+ __d("DOMWrapper",[],function(a,b,c,d,e,f){var g,h,i={setRoot:function(j){g=j;},getRoot:function(){return g||document.body;},setWindow:function(j){h=j;},getWindow:function(){return h||self;}};e.exports=i;},null);
+ __d("sdk.feature",["JSSDKConfig"],function(a,b,c,d,e,f,g){function h(i,j){if(g.features&&i in g.features){var k=g.features[i];if(typeof k==='object'&&typeof k.rate==='number'){if(k.rate&&Math.random()*100<=k.rate){return k.value||true;}else return k.value?null:false;}else return k;}return typeof j!=='undefined'?j:null;}e.exports=h;},null);
+ __d("sdk.getContextType",["UserAgent_DEPRECATED","sdk.Runtime"],function(a,b,c,d,e,f,g,h){function i(){if(g.nativeApp())return 3;if(g.mobile())return 2;if(h.isEnvironment(h.ENVIRONMENTS.CANVAS))return 5;return 1;}e.exports=i;},null);
+ __d("sdk.domReady",[],function(a,b,c,d,e,f){var g,h="readyState" in document?/loaded|complete/.test(document.readyState):!!document.body;function i(){if(!g)return;var l;while(l=g.shift())l();g=null;}function j(l){if(g){g.push(l);return;}else l();}if(!h){g=[];if(document.addEventListener){document.addEventListener('DOMContentLoaded',i,false);window.addEventListener('load',i,false);}else if(document.attachEvent){document.attachEvent('onreadystatechange',i);window.attachEvent('onload',i);}if(document.documentElement.doScroll&&window==window.top){var k=function(){try{document.documentElement.doScroll('left');}catch(l){setTimeout(k,0);return;}i();};k();}}e.exports=j;},3);
+ __d("Log",["sprintf"],function(a,b,c,d,e,f,g){var h={DEBUG:3,INFO:2,WARNING:1,ERROR:0};function i(k,l){var m=Array.prototype.slice.call(arguments,2),n=g.apply(null,m),o=window.console;if(o&&j.level>=l)o[k in o?k:'log'](n);}var j={level:-1,Level:h,debug:ES(i,'bind',true,null,'debug',h.DEBUG),info:ES(i,'bind',true,null,'info',h.INFO),warn:ES(i,'bind',true,null,'warn',h.WARNING),error:ES(i,'bind',true,null,'error',h.ERROR)};e.exports=j;},null);
+ __d("sdk.Content",["sdk.domReady","Log","UserAgent_DEPRECATED"],function(a,b,c,d,e,f,g,h,i){var j,k,l={append:function(m,n){if(!n)if(!j){j=n=document.getElementById('fb-root');if(!n){h.warn('The "fb-root" div has not been created, auto-creating');j=n=document.createElement('div');n.id='fb-root';if(i.ie()||!document.body){g(function(){document.body.appendChild(n);});}else document.body.appendChild(n);}n.className+=' fb_reset';}else n=j;if(typeof m=='string'){var o=document.createElement('div');n.appendChild(o).innerHTML=m;return o;}else return n.appendChild(m);},appendHidden:function(m){if(!n){var n=document.createElement('div'),o=n.style;o.position='absolute';o.top='-10000px';o.width=o.height=0;n=l.append(n);}return l.append(m,n);},submitToTarget:function(m,n){var o=document.createElement('form');o.action=m.url;o.target=m.target;o.method=(n)?'GET':'POST';l.appendHidden(o);for(var p in m.params)if(m.params.hasOwnProperty(p)){var q=m.params[p];if(q!==null&&q!==undefined){var r=document.createElement('input');r.name=p;r.value=q;o.appendChild(r);}}o.submit();o.parentNode.removeChild(o);}};e.exports=l;},null);
+ __d("dotAccess",[],function(a,b,c,d,e,f){function g(h,i,j){var k=i.split('.');do{var l=k.shift();h=h[l]||j&&(h[l]={});}while(k.length&&h);return h;}e.exports=g;},null);
+ __d("GlobalCallback",["DOMWrapper","dotAccess","guid","wrapFunction"],function(a,b,c,d,e,f,g,h,i,j){var k,l,m={setPrefix:function(n){k=h(g.getWindow(),n,true);l=n;},create:function(n,o){if(!k)this.setPrefix('__globalCallbacks');var p=i();k[p]=j(n,'entry',o||'GlobalCallback');return l+'.'+p;},remove:function(n){var o=n.substring(l.length+1);delete k[o];}};e.exports=m;},null);
+ __d("insertIframe",["guid","GlobalCallback"],function(a,b,c,d,e,f,g,h){function i(j){j.id=j.id||g();j.name=j.name||g();var k=false,l=false,m=function(){if(k&&!l){l=true;j.onload&&j.onload(j.root.firstChild);}},n=h.create(m);if(document.attachEvent){var o=('');j.root.innerHTML=('');k=true;setTimeout(function(){j.root.innerHTML=o;j.root.firstChild.src=j.url;j.onInsert&&j.onInsert(j.root.firstChild);},0);}else{var p=document.createElement('iframe');p.id=j.id;p.name=j.name;p.onload=m;p.scrolling='no';p.style.border='none';p.style.overflow='hidden';if(j.title)p.title=j.title;if(j.className)p.className=j.className;if(j.height!==undefined)p.style.height=j.height+'px';if(j.width!==undefined)if(j.width=='100%'){p.style.width=j.width;}else p.style.width=j.width+'px';j.root.appendChild(p);k=true;p.src=j.url;j.onInsert&&j.onInsert(p);}}e.exports=i;},null);
+ __d("Miny",[],function(a,b,c,d,e,f){var g='Miny1',h={encode:[],decode:{}},i='wxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_'.split('');function j(n){for(var o=h.encode.length;o2000)if(p.payload&&typeof p.payload==='string'){var t=j.encode(p.payload);if(t&&t.length>>18),g.charCodeAt((l>>>12)&63),g.charCodeAt((l>>>6)&63),g.charCodeAt(l&63));}var i='>___?456789:;<=_______'+'\0\1\2\3\4\5\6\7\b\t\n\13\f\r\16\17\20\21\22\23\24\25\26\27\30\31'+'______\32\33\34\35\36\37 !"#$%&\'()*+,-./0123';function j(l){l=(i.charCodeAt(l.charCodeAt(0)-43)<<18)|(i.charCodeAt(l.charCodeAt(1)-43)<<12)|(i.charCodeAt(l.charCodeAt(2)-43)<<6)|i.charCodeAt(l.charCodeAt(3)-43);return String.fromCharCode(l>>>16,(l>>>8)&255,l&255);}var k={encode:function(l){l=unescape(encodeURI(l));var m=(l.length+2)%3;l=(l+'\0\0'.slice(m)).replace(/[\s\S]{3}/g,h);return l.slice(0,l.length+m-2)+'=='.slice(m);},decode:function(l){l=l.replace(/[^A-Za-z0-9+\/]/g,'');var m=(l.length+3)&3;l=(l+'AAA'.slice(m)).replace(/..../g,j);l=l.slice(0,l.length+m-3);try{return decodeURIComponent(escape(l));}catch(n){throw new Error('Not valid UTF-8');}},encodeObject:function(l){return k.encode(ES('JSON','stringify',false,l));},decodeObject:function(l){return ES('JSON','parse',false,k.decode(l));},encodeNums:function(l){return String.fromCharCode.apply(String,ES(l,'map',true,function(m){return g.charCodeAt((m|-(m>63))&-(m>0)&63);}));}};e.exports=k;},null);
+ __d("sdk.SignedRequest",["Base64"],function(a,b,c,d,e,f,g){function h(j){if(!j)return null;var k=j.split('.',2)[1].replace(/\-/g,'+').replace(/\_/g,'/');return g.decodeObject(k);}var i={parse:h};e.exports=i;},null);
+ __d("URIRFC3986",[],function(a,b,c,d,e,f){var g=new RegExp('^'+'([^:/?#]+:)?'+'(//'+'([^\\\\/?#@]*@)?'+'('+'\\[[A-Fa-f0-9:.]+\\]|'+'[^\\/?#:]*'+')'+'(:[0-9]*)?'+')?'+'([^?#]*)'+'(\\?[^#]*)?'+'(#.*)?'),h={parse:function(i){if(ES(i,'trim',true)==='')return null;var j=i.match(g),k={};k.uri=j[0]?j[0]:null;k.scheme=j[1]?j[1].substr(0,j[1].length-1):null;k.authority=j[2]?j[2].substr(2):null;k.userinfo=j[3]?j[3].substr(0,j[3].length-1):null;k.host=j[2]?j[4]:null;k.port=j[5]?(j[5].substr(1)?parseInt(j[5].substr(1),10):null):null;k.path=j[6]?j[6]:null;k.query=j[7]?j[7].substr(1):null;k.fragment=j[8]?j[8].substr(1):null;k.isGenericURI=k.authority===null&&!!k.scheme;return k;}};e.exports=h;},null);
+ __d("createObjectFrom",[],function(a,b,c,d,e,f){function g(h,i){var j={},k=ES('Array','isArray',false,i);if(typeof i=='undefined')i=true;for(var l=h.length;l--;)j[h[l]]=k?i[l]:i;return j;}e.exports=g;},null);
+ __d("URISchemes",["createObjectFrom"],function(a,b,c,d,e,f,g){var h=g(['fb','fbcf','fbconnect','fb-messenger','fbrpc','file','ftp','http','https','mailto','ms-app','itms','itms-apps','itms-services','market','svn+ssh','fbstaging','tel','sms']),i={isAllowed:function(j){if(!j)return true;return h.hasOwnProperty(j.toLowerCase());}};e.exports=i;},null);
+ __d("copyProperties",[],function(a,b,c,d,e,f){function g(h,i,j,k,l,m,n){h=h||{};var o=[i,j,k,l,m],p=0,q;while(o[p]){q=o[p++];for(var r in q)h[r]=q[r];if(q.hasOwnProperty&&q.hasOwnProperty('toString')&&(typeof q.toString!='undefined')&&(h.toString!==q.toString))h.toString=q.toString;}return h;}e.exports=g;},null);
+ __d("eprintf",[],function(a,b,c,d,e,f){var g=function(h){var i=ES(Array.prototype.slice.call(arguments),'map',true,function(l){return String(l);}),j=h.split('%s').length-1;if(j!==i.length-1)return g('eprintf args number mismatch: %s',ES('JSON','stringify',false,i));var k=1;return h.replace(/%s/g,function(l){return String(i[k++]);});};e.exports=g;},null);
+ __d("ex",["eprintf"],function(a,b,c,d,e,f,g){var h=function(){var i=Array.prototype.slice.call(arguments,0);i=ES(i,'map',true,function(j){return String(j);});if(i[0].split('%s').length!==i.length)return h('ex args number mismatch: %s',ES('JSON','stringify',false,i));return h._prefix+ES('JSON','stringify',false,i)+h._suffix;};h._prefix='';e.exports=h;},null);
+ __d("invariant",[],function(a,b,c,d,e,f){"use strict";var g=function(h,i,j,k,l,m,n,o){if(!h){var p;if(i===undefined){p=new Error('Minified exception occurred; use the non-minified dev environment '+'for the full error message and additional helpful warnings.');}else{var q=[j,k,l,m,n,o],r=0;p=new Error('Invariant Violation: '+i.replace(/%s/g,function(){return q[r++];}));}p.framesToPop=1;throw p;}};e.exports=g;},null);
+ __d("URIBase",["URIRFC3986","URISchemes","copyProperties","ex","invariant"],function(a,b,c,d,e,f,g,h,i,j,k){var l=new RegExp('[\\x00-\\x2c\\x2f\\x3b-\\x40\\x5c\\x5e\\x60\\x7b-\\x7f'+'\\uFDD0-\\uFDEF\\uFFF0-\\uFFFF'+'\\u2047\\u2048\\uFE56\\uFE5F\\uFF03\\uFF0F\\uFF1F]'),m=new RegExp('^(?:[^/]*:|'+'[\\x00-\\x1f]*/[\\x00-\\x1f]*/)');function n(p,q,r,s){if(!q)return true;if(q instanceof o){p.setProtocol(q.getProtocol());p.setDomain(q.getDomain());p.setPort(q.getPort());p.setPath(q.getPath());p.setQueryData(s.deserialize(s.serialize(q.getQueryData())));p.setFragment(q.getFragment());p.setForceFragmentSeparator(q.getForceFragmentSeparator());return true;}q=ES(q.toString(),'trim',true);var t=g.parse(q)||{};if(!r&&!h.isAllowed(t.scheme))return false;p.setProtocol(t.scheme||'');if(!r&&l.test(t.host))return false;p.setDomain(t.host||'');p.setPort(t.port||'');p.setPath(t.path||'');if(r){p.setQueryData(s.deserialize(t.query)||{});}else try{p.setQueryData(s.deserialize(t.query)||{});}catch(u){return false;}p.setFragment(t.fragment||'');if(t.fragment==='')p.setForceFragmentSeparator(true);if(t.userinfo!==null)if(r){throw new Error(j('URI.parse: invalid URI (userinfo is not allowed in a URI): %s',p.toString()));}else return false;if(!p.getDomain()&&ES(p.getPath(),'indexOf',true,'\\')!==-1)if(r){throw new Error(j('URI.parse: invalid URI (no domain but multiple back-slashes): %s',p.toString()));}else return false;if(!p.getProtocol()&&m.test(q))if(r){throw new Error(j('URI.parse: invalid URI (unsafe protocol-relative URLs): %s',p.toString()));}else return false;return true;}function o(p,q){"use strict";k(q);this.$URIBase0=q;this.$URIBase1='';this.$URIBase2='';this.$URIBase3='';this.$URIBase4='';this.$URIBase5='';this.$URIBase6={};this.$URIBase7=false;n(this,p,true,q);}o.prototype.setProtocol=function(p){"use strict";k(h.isAllowed(p));this.$URIBase1=p;return this;};o.prototype.getProtocol=function(p){"use strict";return this.$URIBase1;};o.prototype.setSecure=function(p){"use strict";return this.setProtocol(p?'https':'http');};o.prototype.isSecure=function(){"use strict";return this.getProtocol()==='https';};o.prototype.setDomain=function(p){"use strict";if(l.test(p))throw new Error(j('URI.setDomain: unsafe domain specified: %s for url %s',p,this.toString()));this.$URIBase2=p;return this;};o.prototype.getDomain=function(){"use strict";return this.$URIBase2;};o.prototype.setPort=function(p){"use strict";this.$URIBase3=p;return this;};o.prototype.getPort=function(){"use strict";return this.$URIBase3;};o.prototype.setPath=function(p){"use strict";this.$URIBase4=p;return this;};o.prototype.getPath=function(){"use strict";return this.$URIBase4;};o.prototype.addQueryData=function(p,q){"use strict";if(Object.prototype.toString.call(p)==='[object Object]'){i(this.$URIBase6,p);}else this.$URIBase6[p]=q;return this;};o.prototype.setQueryData=function(p){"use strict";this.$URIBase6=p;return this;};o.prototype.getQueryData=function(){"use strict";return this.$URIBase6;};o.prototype.removeQueryData=function(p){"use strict";if(!ES('Array','isArray',false,p))p=[p];for(var q=0,r=p.length;q0||this.getFragment());};o.prototype.toString=function(){"use strict";var p='';if(this.$URIBase1)p+=this.$URIBase1+'://';if(this.$URIBase2)p+=this.$URIBase2;if(this.$URIBase3)p+=':'+this.$URIBase3;if(this.$URIBase4){p+=this.$URIBase4;}else if(p)p+='/';var q=this.$URIBase0.serialize(this.$URIBase6);if(q)p+='?'+q;if(this.$URIBase5){p+='#'+this.$URIBase5;}else if(this.$URIBase7)p+='#';return p;};o.prototype.getOrigin=function(){"use strict";return this.$URIBase1+'://'+this.$URIBase2+(this.$URIBase3?':'+this.$URIBase3:'');};o.isValidURI=function(p,q){return n(new o(null,q),p,false,q);};e.exports=o;},null);
+ __d("sdk.URI",["Assert","QueryString","URIBase"],function(a,b,c,d,e,f,g,h,i){var j=/\.facebook\.com$/,k={serialize:function(o){return o?h.encode(o):'';},deserialize:function(o){return o?h.decode(o):{};}};for(var l in i)if(i.hasOwnProperty(l))n[l]=i[l];var m=i===null?null:i.prototype;n.prototype=ES('Object','create',false,m);n.prototype.constructor=n;n.__superConstructor__=i;function n(o){"use strict";g.isString(o,'The passed argument was of invalid type.');if(!(this instanceof n))return new n(o);i.call(this,o,k);}n.prototype.isFacebookURI=function(){"use strict";return j.test(this.getDomain());};n.prototype.valueOf=function(){"use strict";return this.toString();};e.exports=n;},null);
+ __d("sdk.Event",[],function(a,b,c,d,e,f){var g={SUBSCRIBE:'event.subscribe',UNSUBSCRIBE:'event.unsubscribe',subscribers:function(){if(!this._subscribersMap)this._subscribersMap={};return this._subscribersMap;},subscribe:function(h,i){var j=this.subscribers();if(!j[h]){j[h]=[i];}else if(ES(j[h],'indexOf',true,i)==-1)j[h].push(i);if(h!=this.SUBSCRIBE&&h!=this.UNSUBSCRIBE)this.fire(this.SUBSCRIBE,h,j[h]);},unsubscribe:function(h,i){var j=this.subscribers()[h];if(j)ES(j,'forEach',true,function(k,l){if(k==i)j.splice(l,1);});if(h!=this.SUBSCRIBE&&h!=this.UNSUBSCRIBE)this.fire(this.UNSUBSCRIBE,h,j);},monitor:function(h,i){if(!i()){var j=this,k=function(){if(i.apply(i,arguments))j.unsubscribe(h,k);};this.subscribe(h,k);}},clear:function(h){delete this.subscribers()[h];},fire:function(h){var i=Array.prototype.slice.call(arguments,1),j=this.subscribers()[h];if(j)ES(j,'forEach',true,function(k){if(k)k.apply(this,i);});}};e.exports=g;},null);
+ __d("Queue",["copyProperties"],function(a,b,c,d,e,f,g){var h={};function i(j){"use strict";this._opts=g({interval:0,processor:null},j);this._queue=[];this._stopped=true;}i.prototype._dispatch=function(j){"use strict";if(this._stopped||this._queue.length===0)return;if(!this._opts.processor){this._stopped=true;throw new Error('No processor available');}if(this._opts.interval){this._opts.processor.call(this,this._queue.shift());this._timeout=setTimeout(ES(this._dispatch,'bind',true,this),this._opts.interval);}else while(this._queue.length)this._opts.processor.call(this,this._queue.shift());};i.prototype.enqueue=function(j){"use strict";if(this._opts.processor&&!this._stopped){this._opts.processor.call(this,j);}else this._queue.push(j);return this;};i.prototype.start=function(j){"use strict";if(j)this._opts.processor=j;this._stopped=false;this._dispatch();return this;};i.prototype.isStarted=function(){"use strict";return !this._stopped;};i.prototype.dispatch=function(){"use strict";this._dispatch(true);};i.prototype.stop=function(j){"use strict";this._stopped=true;if(j)clearTimeout(this._timeout);return this;};i.prototype.merge=function(j,k){"use strict";this._queue[k?'unshift':'push'].apply(this._queue,j._queue);j._queue=[];this._dispatch();return this;};i.prototype.getLength=function(){"use strict";return this._queue.length;};i.get=function(j,k){"use strict";var l;if(j in h){l=h[j];}else l=h[j]=new i(k);return l;};i.exists=function(j){"use strict";return j in h;};i.remove=function(j){"use strict";return delete h[j];};e.exports=i;},null);
+ __d("JSONRPC",["Log"],function(a,b,c,d,e,f,g){function h(i){"use strict";this.$JSONRPC0=0;this.$JSONRPC1={};this.remote=ES(function(j){this.$JSONRPC2=j;return this.remote;},'bind',true,this);this.local={};this.$JSONRPC3=i;}h.prototype.stub=function(i){"use strict";this.remote[i]=ES(function(){var j=Array.prototype.slice.call(arguments,0),k={jsonrpc:'2.0',method:i};if(typeof j[j.length-1]=='function'){k.id=++this.$JSONRPC0;this.$JSONRPC1[k.id]=j.pop();}k.params=j;this.$JSONRPC3(ES('JSON','stringify',false,k),this.$JSONRPC2||{method:i});},'bind',true,this);};h.prototype.read=function(i,j){"use strict";var k=ES('JSON','parse',false,i),l=k.id;if(!k.method){if(!this.$JSONRPC1[l]){g.warn('Could not find callback %s',l);return;}var m=this.$JSONRPC1[l];delete this.$JSONRPC1[l];delete k.id;delete k.jsonrpc;m(k);return;}var n=this,o=this.local[k.method],p;if(l){p=function(s,t){var u={jsonrpc:'2.0',id:l};u[s]=t;setTimeout(function(){n.$JSONRPC3(ES('JSON','stringify',false,u),j);},0);};}else p=function(){};if(!o){g.error('Method "%s" has not been defined',k.method);p('error',{code:-32601,message:'Method not found',data:k.method});return;}k.params.push(ES(p,'bind',true,null,'result'));k.params.push(ES(p,'bind',true,null,'error'));try{var r=o.apply(j||null,k.params);if(typeof r!=='undefined')p('result',r);}catch(q){g.error('Invokation of RPC method %s resulted in the error: %s',k.method,q.message);p('error',{code:-32603,message:'Internal error',data:q.message});}};e.exports=h;},null);
+ __d("sdk.RPC",["Assert","JSONRPC","Queue"],function(a,b,c,d,e,f,g,h,i){var j=new i(),k=new h(function(m){j.enqueue(m);}),l={local:k.local,remote:k.remote,stub:ES(k.stub,'bind',true,k),setInQueue:function(m){g.isInstanceOf(i,m);m.start(function(n){k.read(n);});},getOutQueue:function(){return j;}};e.exports=l;},null);
+ __d("sdk.Scribe",["QueryString","sdk.Runtime","UrlMap"],function(a,b,c,d,e,f,g,h,i){function j(l,m){if(typeof m.extra=='object')m.extra.revision=h.getRevision();(new Image()).src=g.appendToUrl(i.resolve('www',true)+'/common/scribe_endpoint.php',{c:l,m:ES('JSON','stringify',false,m)});}var k={log:j};e.exports=k;},null);
+ __d("emptyFunction",["copyProperties"],function(a,b,c,d,e,f,g){function h(j){return function(){return j;};}function i(){}g(i,{thatReturns:h,thatReturnsFalse:h(false),thatReturnsTrue:h(true),thatReturnsNull:h(null),thatReturnsThis:function(){return this;},thatReturnsArgument:function(j){return j;}});e.exports=i;},null);
+ __d("htmlSpecialChars",[],function(a,b,c,d,e,f){var g=/&/g,h=/