From 5e82385de1b2830bb35c24df4b5cdde516dfce3f Mon Sep 17 00:00:00 2001 From: jianglong0156 Date: Fri, 14 Nov 2014 10:12:36 +0800 Subject: [PATCH 0001/1345] Revert "issue #1108: add two method cleanScript and restart" This reverts commit 765e890ddcb3e4c4b1cac3185c025b7c47069fb8. --- CCBoot.js | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index 073cd58ea0..5484d8827f 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -1673,17 +1673,6 @@ cc._initSys = function (config, CONFIG_KEY) { // N/A in cocos2d-html5 }; - /** - * cleanScript the singal JS file - * @memberof cc.sys - * @name cleanScript - * @param {String} jsfile - * @function - */ - sys.cleanScript = function (jsfile) { - // N/A in cocos2d-html5 - }; - /** * Dump system informations * @memberof cc.sys @@ -2045,13 +2034,6 @@ cc.game = /** @lends cc.game# */{ self._paused = false; }, - /** - * Run game. - */ - restart: function () { - window.location.href = window.location.href; - }, - /** * Run game. */ From adc5958682c3b8cd43ab7863835f238948c162c1 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 10 Dec 2014 20:54:38 +0800 Subject: [PATCH 0002/1345] Fixed audio web audio error --- cocos2d/audio/CCAudio.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index a0bf2f8a71..8d07b6df1a 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -700,7 +700,7 @@ cc.Audio = cc.Class.extend({ audio = effectList[i]; audio.setVolume(this._effectVolume); audio.play(0, loop); - }else if(SWA && i > this._maxAudioInstance){ + }else if(!SWA && i > this._maxAudioInstance){ cc.log("Error: %s greater than %d", url, this._maxAudioInstance); }else{ var audio = loader.cache[url]; From cb3e06a1e020bbf56331793145532cec1f550b04 Mon Sep 17 00:00:00 2001 From: sxd1140 Date: Thu, 11 Dec 2014 01:48:42 +0800 Subject: [PATCH 0003/1345] add stopActionByName() --- extensions/cocostudio/action/CCActionManager.js | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/extensions/cocostudio/action/CCActionManager.js b/extensions/cocostudio/action/CCActionManager.js index b990197870..88d2bbe626 100644 --- a/extensions/cocostudio/action/CCActionManager.js +++ b/extensions/cocostudio/action/CCActionManager.js @@ -81,6 +81,17 @@ ccs.actionManager = /** @lends ccs.actionManager# */{ if (action) action.play(fun); }, + + /** + * Stop an Action with a name. + * @param {String} jsonName + * @param {String} actionName + */ + stopActionByName: function (jsonName, actionName) { + var action = this.getActionByName(jsonName, actionName); + if (action) + action.stop(); + }, /** * Release all actions. @@ -95,4 +106,4 @@ ccs.actionManager = /** @lends ccs.actionManager# */{ clear: function() { this._actionDic = {}; } -}; \ No newline at end of file +}; From 61c353e3c5331ceabcc4a52ef9ffa19f75639dba Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Thu, 11 Dec 2014 11:30:58 +0800 Subject: [PATCH 0004/1345] Update the authors for V3.2 rc0 --- AUTHORS.txt | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/AUTHORS.txt b/AUTHORS.txt index 208e7edf3e..537ad3deb9 100644 --- a/AUTHORS.txt +++ b/AUTHORS.txt @@ -169,12 +169,13 @@ Asano @LaercioAsano cc.Node bug fix Bruno Assarisse @bassarisse cc.LabelBMFont bug fix -musikov @musikov cc.ClippingNode bug fix +Mykyta Usikov @musikov cc.ClippingNode bug fix cc.fontLoader bug fix Inverted ClippingNode with DrawNode as stencil bug fix under canvas render mode JumpTo bug with wrong _delta position bug fix - cc.ProgressTimer bug fix - cc.Scale9Sprite bug fix + cc.ProgressTimer bugs fix + cc.Scale9Sprite bugs fix + cc.RenderTexture bug fix Han XiaoLong @kpkhxlgy0 cc.ParticleSytem bug fix @@ -216,6 +217,12 @@ nopakos @nopakos cc.Texture2D bug fix Robert Rouhani @Robmaister cc.TMXMapInfo bug fix cc.TMXLayer bug fix +Igor Mats @IgorMats cc.Scale9Sprite bug fix + +Tim @duhaibo0404 ccs.csLoader bug fix + +Hermanto @man2 cc.loader bug fix + Retired Core Developers: Shengxiang Chen (Nero Chan) Xingsen Ma From 52281b4852527f3bd221062a55fba10d7e823c0d Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 11 Dec 2014 11:51:53 +0800 Subject: [PATCH 0005/1345] Update the build.xml, and create inspection tools --- cocos2d/core/platform/CCConfig.js | 2 +- cocos2d/tilemap/CCTileMapAtlas.js | 308 ------------------------------ tools/XmlCheck.js | 130 +++++++++++++ tools/build.xml | 69 ++++++- 4 files changed, 193 insertions(+), 316 deletions(-) delete mode 100644 cocos2d/tilemap/CCTileMapAtlas.js create mode 100644 tools/XmlCheck.js diff --git a/cocos2d/core/platform/CCConfig.js b/cocos2d/core/platform/CCConfig.js index d9c4aefd81..a2847ca9a3 100644 --- a/cocos2d/core/platform/CCConfig.js +++ b/cocos2d/core/platform/CCConfig.js @@ -31,7 +31,7 @@ * @type {String} * @name cc.ENGINE_VERSION */ -window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.1"; +window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.2 RC0"; /** *

diff --git a/cocos2d/tilemap/CCTileMapAtlas.js b/cocos2d/tilemap/CCTileMapAtlas.js deleted file mode 100644 index 40d4f562e1..0000000000 --- a/cocos2d/tilemap/CCTileMapAtlas.js +++ /dev/null @@ -1,308 +0,0 @@ -/**************************************************************************** - Copyright (c) 2008-2010 Ricardo Quesada - Copyright (c) 2011-2012 cocos2d-x.org - Copyright (c) 2013-2014 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -/** - *

cc.TileMapAtlas is a subclass of cc.AtlasNode.

- * - *

It knows how to render a map based of tiles.
- * The tiles must be in a .PNG format while the map must be a .TGA file.

- * - *

For more information regarding the format, please see this post:
- * http://www.cocos2d-iphone.org/archives/27

- * - *

All features from cc.AtlasNode are valid in cc.TileMapAtlas

- * - *

IMPORTANT:
- * This class is deprecated. It is maintained for compatibility reasons only.
- * You SHOULD not use this class.
- * Instead, use the newer TMX file format: cc.TMXTiledMap

- * @class - * @extends cc.AtlasNode - * - * @property {cc.ImageTGA} tgaInfo - TGA Info - */ -cc.TileMapAtlas = cc.AtlasNode.extend(/** @lends cc.TileMapAtlas# */{ - tgaInfo:null, - - indices:null, - //numbers of tiles to render - _itemsToRender:0, - //x,y to altas dictionary - _posToAtlasIndex:null, - _className:"TileMapAtlas", - - /** - *

Creates a cc.TileMap with a tile file (atlas) with a map file and the width and height of each tile in points.
- * The tile file will be loaded using the TextureMgr.
- * Constructor of cc.TileMapAtlas - *

- * - * @param {String} tile - * @param {String} mapFile - * @param {Number} tileWidth - * @param {Number} tileHeight - * @example - * //example - * var tmpAtlas = new cc.TileMapAtlas("hello.png", "hello.tga", 16, 16); - */ - ctor:function(tile, mapFile, tileWidth, tileHeight){ - cc.AtlasNode.prototype.ctor.call(this); - if(tileHeight !== undefined) - this.initWithTileFile(tile, mapFile, tileWidth, tileHeight); - }, - - /** - * @return {cc.ImageTGA} - */ - getTGAInfo:function () { - return this.tgaInfo; - }, - - /** - * @param {cc.ImageTGA} Var - */ - setTGAInfo:function (Var) { - this.tgaInfo = Var; - }, - - /** - * Initializes a cc.TileMap with a tile file (atlas) with a map file and the width and height of each tile in points.
- * The file will be loaded using the TextureMgr. - * @param {String} tile - * @param {String} mapFile - * @param {Number} tileWidth - * @param {Number} tileHeight - * @return {Boolean} - * @example - * //example - * var tmpAtlas = new cc.TileMapAtlas(); - * tmpAtlas.initWithTileFile("hello.png", "hello.tga", 16, 16); - */ - initWithTileFile:function (tile, mapFile, tileWidth, tileHeight) { - this._calculateItemsToRender(); - if (cc.AtlasNode.prototype.initWithTileFile.call(this, tile, tileWidth, tileHeight, this._itemsToRender)) { - this._color = cc.color.WHITE; - this._posToAtlasIndex = {}; - this._updateAtlasValues(); - this.width = this.tgaInfo.width * this._itemWidth; - this.height = this.tgaInfo.height * this._itemHeight; - return true; - } - return false; - }, - - /** - *

Returns a tile from position x,y.
- * For the moment only channel R is used.

- * @param {cc.Point} position - * @return {cc.Color} - */ - getTileAt:function (position) { - if(!this.tgaInfo){ - cc.log("cc.TileMapAtlas.getTileAt(): tgaInfo must not be null"); - return null; - } - if(position.x >= this.tgaInfo.width || position.y >= this.tgaInfo.height) - throw "cc.TileMapAtlas.getTileAt(): Invalid position"; - - var colorPos = 0|(position.x * 3 + position.y * this.tgaInfo.width * 3); - var locTGAImageData = this.tgaInfo.imageData; - return cc.color(locTGAImageData[colorPos], locTGAImageData[colorPos + 1], locTGAImageData[colorPos + 2]); - }, - - /** - * Sets a tile at position x,y. - * For the moment only channel R is used - * @param {cc.Color} tile - * @param {cc.Point} position - */ - setTile:function (tile, position) { - if(!this.tgaInfo){ - cc.log("cc.TileMapAtlas.setTile(): tgaInfo must not be null"); - return; - } - if(!this._posToAtlasIndex){ - cc.log("cc.TileMapAtlas.setTile(): posToAtlasIndex must not be null"); - return; - } - if(position.x >= this.tgaInfo.width || position.y >= this.tgaInfo.height) - throw "cc.TileMapAtlas.setTile(): Invalid position"; - if(!tile || tile.r == 0) - throw "cc.TileMapAtlas.setTile(): tile should be non-null and tile.r should be non-nil"; - - var colorPos = 0 | (position.x * 3 + position.y * this.tgaInfo.width * 3); - if (this.tgaInfo.imageData[colorPos] == 0) - cc.log("cocos2d: Value.r must be non 0."); - else { - this.tgaInfo.imageData[colorPos] = tile.r; - this.tgaInfo.imageData[colorPos + 1] = tile.g; - this.tgaInfo.imageData[colorPos + 2] = tile.b; - - var num = this._posToAtlasIndex[position.x + "_" + position.y]; - this._updateAtlasValueAt(position, tile, num); - } - }, - - /** - * Dealloc the map from memory - */ - releaseMap:function () { - if (this.tgaInfo) { - cc.tgaDestroy(this.tgaInfo); - } - this.tgaInfo = null; - }, - - _calculateItemsToRender:function () { - if(!this.tgaInfo){ - cc.log("cc.TileMapAtlas._calculateItemsToRender(): tgaInfo must not be null"); - return; - } - - this._itemsToRender = 0; - var locWidth = this.tgaInfo.width, locHeight = this.tgaInfo.height, locImageData = this.tgaInfo.imageData; - for (var x = 0; x < locWidth; x++) { - for (var y = 0; y < locHeight; y++) { - if (locImageData[x * 3 + y * locWidth * 3]) - ++this._itemsToRender; - } - } - }, - - /** - * @param {cc.Point|cc.GridSize} pos - * @param {cc.Color} value - * @param {Number} index - * @private - */ - _updateAtlasValueAt:function (pos, value, index) { - var locTextureAtlas = this.textureAtlas; - if(index < 0 && index >= locTextureAtlas.getCapacity()) - throw "cc.TileMapAtlas._updateAtlasValueAt(): Invalid index"; - var quad = locTextureAtlas.quads[index]; - - var x = pos.x; - var y = pos.y; - var row = (value.r % this._itemsPerRow); - var col = (value.r / this._itemsPerRow); - - var tex = locTextureAtlas.texture, textureWide = tex.pixelsWidth, textureHigh = tex.pixelsHeight; - - var locItemWidth = this._itemWidth; - var locItemHeight = this._itemHeight; - var itemWidthInPixels = locItemWidth * cc.contentScaleFactor(); - var itemHeightInPixels = locItemHeight * cc.contentScaleFactor(); - - var left, right, top, bottom; - if (cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL) { - 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; - } - - quad.tl.texCoords.u = left; - quad.tl.texCoords.v = top; - quad.tr.texCoords.u = right; - quad.tr.texCoords.v = top; - quad.bl.texCoords.u = left; - quad.bl.texCoords.v = bottom; - quad.br.texCoords.u = right; - quad.br.texCoords.v = bottom; - - quad.bl.vertices.x = (x * locItemWidth); - quad.bl.vertices.y = (y * locItemHeight); - quad.bl.vertices.z = 0.0; - quad.br.vertices.x = (x * locItemWidth + locItemWidth); - quad.br.vertices.y = (y * locItemHeight); - quad.br.vertices.z = 0.0; - quad.tl.vertices.x = (x * locItemWidth); - quad.tl.vertices.y = (y * locItemHeight + locItemHeight); - quad.tl.vertices.z = 0.0; - quad.tr.vertices.x = (x * locItemWidth + locItemWidth); - quad.tr.vertices.y = (y * locItemHeight + locItemHeight); - quad.tr.vertices.z = 0.0; - - var locColor = this._displayedColor; - var color = {r: locColor.r, g: locColor.g, b: locColor.b, a: this._displayedOpacity}; - quad.tr.colors = color; - quad.tl.colors = color; - quad.br.colors = color; - quad.bl.colors = color; - - locTextureAtlas.dirty = true; - var totalQuads = locTextureAtlas.totalQuads; - if (index + 1 > totalQuads) - locTextureAtlas.increaseTotalQuadsWith(index + 1 - totalQuads); - }, - - _updateAtlasValues:function () { - if(!this.tgaInfo){ - cc.log("cc.TileMapAtlas._updateAtlasValues(): tgaInfo must not be null"); - return; - } - - var total = 0; - var locTGAInfo = this.tgaInfo; - var locTGAInfoWidth = locTGAInfo.width, locTGAInfoHeight = locTGAInfo.height, locItemsToRender = this._itemsToRender; - for (var x = 0; x < locTGAInfoWidth; x++) { - for (var y = 0; y < locTGAInfoHeight; y++) { - if (total < locItemsToRender) { - var colorPos = x * 3 + y * locTGAInfoWidth * 3; - var value = cc.color(locTGAInfo.imageData[colorPos], locTGAInfo.imageData[colorPos + 1], locTGAInfo.imageData[colorPos + 2]); - if (value.r != 0) { - this._updateAtlasValueAt(cc.p(x, y), value, total); - this._posToAtlasIndex[x + "_" + y] = total; - total++; - } - } - } - } - } -}); - -/** - *

Creates a cc.TileMap with a tile file (atlas) with a map file and the width and height of each tile in points.
- * The tile file will be loaded using the TextureMgr.

- * @deprecated since v3.0 please use new cc.TileMapAtlas(tile, mapFile, tileWidth, tileHeight) instead. - * @param {String} tile - * @param {String} mapFile - * @param {Number} tileWidth - * @param {Number} tileHeight - * @return {cc.TileMapAtlas} - * @example - * //example - * var tmpAtlas = new cc.TileMapAtlas(); - * tmpAtlas.initWithTileFile("hello.png", "hello.tga", 16, 16); - */ -cc.TileMapAtlas.create = function (tile, mapFile, tileWidth, tileHeight) { - return new cc.TileMapAtlas(tile, mapFile, tileWidth, tileHeight); -}; diff --git a/tools/XmlCheck.js b/tools/XmlCheck.js new file mode 100644 index 0000000000..62f383d0a5 --- /dev/null +++ b/tools/XmlCheck.js @@ -0,0 +1,130 @@ +const fs = require("fs"); +const path = require("path"); +const modules = JSON.parse(fs.readFileSync("../moduleConfig.json")); + +var contains = [ + "../cocos2d", + "../extensions", + "../external", + "../Base64Images.js", + "../CCBoot.js", + "../CCDebugger.js" +]; +(function(){ + var i = 0; + function read(name){ + if(fs.existsSync(name)){ + var stat = fs.statSync(name); + if(stat.isDirectory()){ + contains.splice(i--, 1); + var fileList = fs.readdirSync(name); + for(var n=0; n((.|\r\n|\r|\n)*?)\<\/sources/g, function(a, b){ + a.replace(/file name\=\"(.*)\"\/\>/g, function(c, d){ + arr[index] && arr[index].push("../" + d); + }); + index++; + }); +})(); +console.log(" The number of files in the XML file : %s", xmlFile.length); + +console.log("\x1B[0m\x1B[33m"); +console.log(" warn : moduleConfig missing..."); +contains.forEach(function(a){ + if(!moduleFile.some(function(b){return b==a})) + console.log(" " + a); +}); + + +console.log("\x1B[0m\x1B[92m"); +console.log(" warn : engine dir missing..."); +moduleFile.forEach(function(a){ + if(!contains.some(function(b){return b==a})) + console.log(" " + a); +}); + + +console.log("\x1B[0m\x1B[96m"); +console.log(" warn : xml(all) file missing..."); +contains.forEach(function(a){ + if(!xmlFile.some(function(b){return b==a})) + console.log(" " + a); +}); + + +console.log("\x1B[0m\x1B[91m"); +console.log(" warn : xml(all) redundant files..."); +xmlFile.forEach(function(a){ + if(!contains.some(function(b){return b==a})) + console.log(" " + a); +}); + + +console.log("\x1B[0m\x1B[94m"); +console.log(" warn : xml(core) maybe missing files..."); +xmlFile2.forEach(function(a){ + var basename = path.basename(a); + basename = basename.substr(0, basename.indexOf(".")); + contains.forEach(function(b){ + if(b.indexOf(basename) > -1 && a != b){ + if( + b.indexOf("extensions") == -1 && + !xmlFile2.some(function(c){return b == c;}) + ) + console.log(" " + b); + } + }); +}); + + +console.log("\x1B[0m\x1B[35m"); +console.log(" warn : xml(core) redundant files..."); +xmlFile2.forEach(function(a){ + if(!contains.some(function(b){return b==a})) + console.log(" " + a); +}); +console.log("\x1B[0m"); \ No newline at end of file diff --git a/tools/build.xml b/tools/build.xml index fd39a423f2..0b37149aa6 100644 --- a/tools/build.xml +++ b/tools/build.xml @@ -5,7 +5,7 @@ classpath="./compiler/compiler.jar"/> + debug="false" output="./../lib/cocos2d-js-v3.2-RC0-min.js"> @@ -43,8 +43,14 @@ + + + + + + @@ -52,17 +58,21 @@ - - + + + + + + @@ -72,6 +82,8 @@ + + @@ -90,12 +102,24 @@ + + + + + + + + + + + + @@ -110,6 +134,8 @@ + + @@ -121,8 +147,12 @@ + + + + @@ -132,13 +162,18 @@ + + + + + @@ -148,6 +183,8 @@ + + @@ -166,7 +203,11 @@ + + + + @@ -186,7 +227,6 @@ - @@ -203,11 +243,15 @@ + + + + @@ -221,7 +265,7 @@ - + @@ -245,17 +289,25 @@ + + + + + + + + + debug="false" output="./../lib/cocos2d-js-v3.2-RC0-core-min.js"> @@ -279,6 +331,7 @@ + @@ -288,10 +341,11 @@ - + + @@ -300,6 +354,7 @@ + @@ -307,7 +307,7 @@ + debug="false" output="./../lib/cocos2d-js-v3.2-core-min.js"> From 7be2e36eb01f117b89a200e1c8d8a00ee6afc18a Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 29 Dec 2014 17:08:51 +0800 Subject: [PATCH 0067/1345] new studio loader --- extensions/cocostudio/reader/loader/load.js | 127 +++ .../loader/parsers/timelineParser-1.x.js | 256 ++++++ .../loader/parsers/timelineParser-2.x.js | 278 ++++++ .../reader/loader/parsers/uiParser-1.x.js | 800 ++++++++++++++++++ moduleConfig.json | 9 +- 5 files changed, 1469 insertions(+), 1 deletion(-) create mode 100644 extensions/cocostudio/reader/loader/load.js create mode 100644 extensions/cocostudio/reader/loader/parsers/timelineParser-1.x.js create mode 100644 extensions/cocostudio/reader/loader/parsers/timelineParser-2.x.js create mode 100644 extensions/cocostudio/reader/loader/parsers/uiParser-1.x.js diff --git a/extensions/cocostudio/reader/loader/load.js b/extensions/cocostudio/reader/loader/load.js new file mode 100644 index 0000000000..fbfb126792 --- /dev/null +++ b/extensions/cocostudio/reader/loader/load.js @@ -0,0 +1,127 @@ +ccs.loadNode = (function(){ + + var load = function(file){ + + var json = cc.loader.getRes(file); + + if(!json) + return cc.log("%s is not exists", file); + var ext = extname(file).toLocaleLowerCase(); + if(ext !== "json" && ext !== "exportjson") + return cc.log("%s load error, must be json file", file); + + // Judging the parser (uiParse or timelineParse, Temporarily blank) + // The judgment condition is unknown + var parse; + if(json["widgetTree"]) + parse = parser["ccui"]; + else if(json["nodeTree"]) + parse = parser["timeline"]; + else if(json["Content"]) + parse = parser["timeline"]; + + if(!parse){ + cc.log("Can't find the parser : %s", file); + return new cc.Node(); + } + var version = json["version"] || json["Version"]; + 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) || new cc.Node(); + }; + + var parser = { + "ccui": {}, + "timeline": {} + }; + + 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){ + var resourcePath = this._dirname(file); + this.pretreatment(json, resourcePath); + var node = this.parseNode(this.getNodeJson(json), resourcePath); + 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, this.parseNode, resourcePath); + else + cc.log("Can't find the parser : %s", this.getClass(json)); + + return widget; + }, + + registerParser: function(widget, parse){ + this.parsers[widget] = parse; + } +}); diff --git a/extensions/cocostudio/reader/loader/parsers/timelineParser-1.x.js b/extensions/cocostudio/reader/loader/parsers/timelineParser-1.x.js new file mode 100644 index 0000000000..7da3666f2a --- /dev/null +++ b/extensions/cocostudio/reader/loader/parsers/timelineParser-1.x.js @@ -0,0 +1,256 @@ +(function(load, baseParser){ + + var Parser = baseParser.extend({ + + getNodeJson: function(json){ + return json["nodeTree"]; + }, + + addSpriteFrame: function(textures, plists, resourcePath){ + if(!textures) return; + for (var i = 0; i < textures.length; i++) { + cc.spriteFrameCache.addSpriteFrames( + resourcePath + textures[i], + resourcePath + plists[i] + ); + } + }, + + pretreatment: function(json, resourcePath, file){ + this.addSpriteFrame(json["textures"], json["texturesPng"], resourcePath); + ccs.actionTimelineCache.loadAnimationActionWithContent(file, json); + } + + }); + var parser = new Parser(); + + parser.generalAttributes = function(node, options){ + var width = options[ccui.CSLoaderStatic.WIDTH] !=null ? options[ccui.CSLoaderStatic.WIDTH] : 0; + var height = options[ccui.CSLoaderStatic.HEIGHT] !=null ? options[ccui.CSLoaderStatic.HEIGHT] : 0; + var x = options[ccui.CSLoaderStatic.X] !=null ? options[ccui.CSLoaderStatic.X] : 0; + var y = options[ccui.CSLoaderStatic.Y] !=null ? options[ccui.CSLoaderStatic.Y] : 0; + var scalex = options[ccui.CSLoaderStatic.SCALE_X] !=null ? options[ccui.CSLoaderStatic.SCALE_X] : 1; + var scaley = options[ccui.CSLoaderStatic.SCALE_Y] !=null ? options[ccui.CSLoaderStatic.SCALE_Y] : 1; + var rotation = options[ccui.CSLoaderStatic.ROTATION] !=null ? options[ccui.CSLoaderStatic.ROTATION] : 0; + var rotationSkewX = options[ccui.CSLoaderStatic.ROTATION_SKEW_X]!=null ? options[ccui.CSLoaderStatic.ROTATION_SKEW_X] : 0; + var rotationSkewY = options[ccui.CSLoaderStatic.ROTATION_SKEW_Y]!=null ? options[ccui.CSLoaderStatic.ROTATION_SKEW_Y] : 0; + var skewx = options[ccui.CSLoaderStatic.SKEW_X] !=null ? options[ccui.CSLoaderStatic.SKEW_X] : 0; + var skewy = options[ccui.CSLoaderStatic.SKEW_Y] !=null ? options[ccui.CSLoaderStatic.SKEW_Y] : 0; + var anchorx = options[ccui.CSLoaderStatic.ANCHOR_X] !=null ? options[ccui.CSLoaderStatic.ANCHOR_X] : 0.5; + var anchory = options[ccui.CSLoaderStatic.ANCHOR_Y] !=null ? options[ccui.CSLoaderStatic.ANCHOR_Y] : 0.5; + var alpha = options[ccui.CSLoaderStatic.ALPHA] !=null ? options[ccui.CSLoaderStatic.ALPHA] : 255; + var red = options[ccui.CSLoaderStatic.RED] !=null ? options[ccui.CSLoaderStatic.RED] : 255; + var green = options[ccui.CSLoaderStatic.GREEN] !=null ? options[ccui.CSLoaderStatic.GREEN] : 255; + var blue = options[ccui.CSLoaderStatic.BLUE] !=null ? options[ccui.CSLoaderStatic.BLUE] : 255; + var zorder = options[ccui.CSLoaderStatic.ZORDER] !=null ? options[ccui.CSLoaderStatic.ZORDER] : 0; + var tag = options[ccui.CSLoaderStatic.TAG] !=null ? options[ccui.CSLoaderStatic.TAG] : 0; + var actionTag = options[ccui.CSLoaderStatic.ACTION_TAG] !=null ? options[ccui.CSLoaderStatic.ACTION_TAG] : 0; + var visible = options[ccui.CSLoaderStatic.VISIBLE] !=null ? options[ccui.CSLoaderStatic.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)); + } + 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[ccui.CSLoaderStatic.TMX_FILE]; + var tmxString = options[ccui.CSLoaderStatic.TMX_STRING]; + //todo check path and resourcePath + var path = options[ccui.CSLoaderStatic.RESOURCE_PATH]; + + 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")["1.*"]; + parser.initWidget = function(options, resourcePath){ + var node = uiParser.parseNode.call(this, 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[ccui.CSLoaderStatic.ACTION_TAG]; + 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", "1.*", parser); + + +})(ccs.loadNode, ccs._parser); \ No newline at end of file diff --git a/extensions/cocostudio/reader/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/reader/loader/parsers/timelineParser-2.x.js new file mode 100644 index 0000000000..38e2e38126 --- /dev/null +++ b/extensions/cocostudio/reader/loader/parsers/timelineParser-2.x.js @@ -0,0 +1,278 @@ +(function(load, baseParser){ + + var Parser = baseParser.extend({ + + parse: function(file, json){ + var resourcePath = this._dirname(file); + this.pretreatment(json, resourcePath); + var node = this.parseNode(this.getNodeJson(json), resourcePath); + this.deferred(json, resourcePath, node, file); + return node; + }, + + getNodeJson: function(json){ + return json["Content"]["Content"]["ObjectData"]; + }, + + getClass: function(json){ + return json["ctype"]; + }, + + addSpriteFrame: function(textures, plists, resourcePath){ + if(!textures) return; + for (var i = 0; i < textures.length; i++) { + cc.spriteFrameCache.addSpriteFrames( + resourcePath + textures[i], + resourcePath + plists[i] + ); + } + }, + + pretreatment: function(json, resourcePath, file){ + this.addSpriteFrame(json["textures"], json["texturesPng"], resourcePath); + ccs.actionTimelineCache.loadAnimationActionWithContent(file, json); + } + + }); + var parser = new Parser(); + + + ////////// + // 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); + //rotationSkewX + var rotationSkewY = json["RotationSkewY"]; + if (json["RotationSkewY"] != null) + node.setRotationY(rotationSkewY); + //rotationSkewY + + //todo check it + var anchor = json["AnchorPoint"]; + if(anchor && (anchor["ScaleX"] || anchor["ScaleY"])) + node.setAnchorPoint(cc.p(anchor["ScaleX"]||0.5, anchor["ScaleY"]||0.5)); + + if (json["ZOrder"] != null) + node.setLocalZOrder(json["ZOrder"]); + + var visible = json["VisibleForFrame"]; + if (visible != null) + node.setVisible(visible == "True"); + + + var contentSize = json["Size"]; + if(contentSize != null && (contentSize["X"] != null || contentSize["Y"] != null)) + node.setContentSize(cc.size(contentSize["X"]||0, contentSize["Y"]||0)); + + if (json["Alpha"] != null) + node.setOpacity(json["Alpha"]); + var color = json["CColor"]; + if(color != null && (color["R"] != null || color["G"] != null || color["B"] != null)) + node.setColor(cc.color(color["R"]||255, color["G"]||255, color["B"]||255)); + + if (json["Tag"] != null) + node.setTag(json["Tag"]); + + if (json["ActionTag"] != null) + node.setUserObject(new ccs.ActionTimelineData(json["ActionTag"])); + + node.setCascadeColorEnabled(true); + node.setCascadeOpacityEnabled(true); + }; + + parser.parseChild = function(node, children, resourcePath){ + if(!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)); + } + var AnchorPointIn = node.getAnchorPointInPoints(); + child.setPosition(cc.p(child.getPositionX() + AnchorPointIn.x, child.getPositionY() + AnchorPointIn.y)); + } + node.addChild(child); + } + } + } + } + }; + + parser.initSingleNode = function(json){ + var node = new cc.Node(); + + this.generalAttributes(node, json); + + return node; + }; + + parser.initSprite = function(json){ + var node = new cc.Sprite(); + + this.generalAttributes(node, json); + + var fileData = json["FileData"]; + if(fileData){ + switch(fileData["Type"]){ + case 1: + var spriteFrame = cc.spriteFrameCache.getSpriteFrameByName(); + if(spriteFrame) + node.setSpriteFrame(spriteFrame); + break; + default: + if(fileData["Path"]) + node.setTexture(fileData["Path"]); + } + + } +// if (!fileExist) +// { +// auto label = Label::create(); +// label->setString(__String::createWithFormat("%s missed", errorFilePath.c_str())->getCString()); +// sprite->addChild(label); +// } + + if(json["FlipX"]) + node.setFlippedX(true); + if(json["FlipY"]) + node.setFlippedY(true); + + return node; + }; + + parser.initParticle = function(json){ + var fileData = json["FileData"]; + var node; + if(fileData){ + node = new cc.ParticleSystemQuad(); + this.generalAttributes(node, json); + } + return node; + }; + + + //////////// + // WIDGET // + //////////// + + parser.widgetAttributes = function(widget, json){ + var name = json["Name"]; + if(name) + widget.setName(name); + + var actionTag = json["ActionTag"]; + if(actionTag){ + widget.setActionTag(actionTag); + widget.setUserObject(new ccs.ActionTimelineData(actionTag)); + } + + var rotationSkewX = json["RotationSkewX"]; + if(rotationSkewX) + widget.setRotationX(rotationSkewX); + + var rotationSkewY = json["RotationSkewY"]; + if(rotationSkewY) + widget.setRotationX(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 = json["VisibleForFrame"]; + if(visible != null) + widget.setVisible(visible); + + var alpha = json["Alpha"]; + if(alpha != null) + widget.setOpacity(alpha); + + var tag = json["Tag"]; + if(tag != null) + widget.setTag(tag); + + var touchEnabled = json["TouchEnabled"]; + if(touchEnabled != null) + widget.setTouchEnabled(touchEnabled); + + // -- var frameEvent = json["FrameEvent"]; + + var callBackType = json["CallBackType"]; + if(callBackType != nul) + widget.setCallbackType(callBackType); + + var callBackName = json["CallBackName"]; + if(callBackName) + widget.setCallbackName(callBackName); + }; + + parser.initPanel = function(json){ + var widget = new ccui.Layout(); + + + + + return node; + }; + + var register = [ + {name: "SingleNodeObjectData", handle: parser.initSingleNode}, + {name: "SpriteObjectData", handle: parser.initSprite}, + {name: "ParticleObjectData", handle: parser.initParticle}, + {name: "PanelObjectData", handle: parser.initPanel} + ]; + + register.forEach(function(item){ + parser.registerParser(item.name, function(options, parse, resourcePath){ + var node = item.handle.call(this, options); + this.parseChild(node, options["Children"], resourcePath); + return node; + }); + }); + + + load.registerParser("timeline", "2.*", parser); + + +})(ccs.loadNode, ccs._parser); \ No newline at end of file diff --git a/extensions/cocostudio/reader/loader/parsers/uiParser-1.x.js b/extensions/cocostudio/reader/loader/parsers/uiParser-1.x.js new file mode 100644 index 0000000000..20628505c2 --- /dev/null +++ b/extensions/cocostudio/reader/loader/parsers/uiParser-1.x.js @@ -0,0 +1,800 @@ +(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); + + widget.setSizeType(options["sizeType"]); + 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(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) + 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); + } + } + } + } + }; + + /** + * 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){ + var imageFileName, + imageFileNameType = imageFileNameDic["resourceType"]; + switch (imageFileNameType) + { + case 0: + { + var tp_b = resourcePath; + imageFileName = imageFileNameDic["path"]; + var imageFileName_tp = (imageFileName && (imageFileName !== "")) ? + tp_b + imageFileName : + null; + widget.setBackGroundImage(imageFileName_tp); + break; + } + case 1: + { + imageFileName = imageFileNameDic["path"]; + widget.setBackGroundImage(imageFileName, 1/*ui.UI_TEX_TYPE_PLIST*/); + break; + } + default: + break; + } + } + + 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)); + } + widget.setLayoutType(options["layoutType"]); + }; + /** + * Button parser (UIButton) + */ + parser.ButtonAttributes = function(widget, options, resourcePath){ + var button = widget; + var scale9Enable = options["scale9Enable"]; + button.setScale9Enabled(scale9Enable); + + var normalFileName, + normalDic = options["normalData"], + normalType = normalDic["resourceType"]; + switch (normalType) { + case 0: + var tp_n = resourcePath; + normalFileName = normalDic["path"]; + var normalFileName_tp = (normalFileName && normalFileName !== "") ? + tp_n + normalFileName : null; + button.loadTextureNormal(normalFileName_tp); + break; + case 1: + normalFileName = normalDic["path"]; + button.loadTextureNormal(normalFileName, 1/*ui.UI_TEX_TYPE_PLIST*/); + break; + default: + break; + } + var pressedFileName, + pressedDic = options["pressedData"], + pressedType = pressedDic["resourceType"]; + switch (pressedType) { + case 0: + var tp_p = resourcePath; + pressedFileName = pressedDic["path"]; + var pressedFileName_tp = (pressedFileName && pressedFileName !== "") ? + tp_p + pressedFileName : null; + button.loadTexturePressed(pressedFileName_tp); + break; + case 1: + pressedFileName = pressedDic["path"]; + button.loadTexturePressed(pressedFileName, 1/*ui.UI_TEX_TYPE_PLIST*/); + break; + default: + break; + } + var disabledFileName, + disabledDic = options["disabledData"], + disabledType = disabledDic["resourceType"]; + switch (disabledType){ + case 0: + var tp_d = resourcePath; + disabledFileName = disabledDic["path"]; + var disabledFileName_tp = (disabledFileName && disabledFileName !== "") ? + tp_d + disabledFileName : null; + button.loadTextureDisabled(disabledFileName_tp); + break; + case 1: + disabledFileName = disabledDic["path"]; + button.loadTextureDisabled(disabledFileName, 1/*ui.UI_TEX_TYPE_PLIST*/); + break; + default: + break; + } + 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"]; + var backGroundType = backGroundDic["resourceType"]; + var backGroundTexturePath = resourcePath + backGroundDic["path"]; + widget.loadTextureBackGround(backGroundTexturePath, backGroundType); + + //load background selected image + var backGroundSelectedDic = options["backGroundBoxSelectedData"]; + var backGroundSelectedType = backGroundSelectedDic["resourceType"]; + var backGroundSelectedTexturePath = resourcePath + backGroundSelectedDic["path"]; + if(!backGroundSelectedTexturePath){ + backGroundSelectedType = backGroundType; + backGroundSelectedTexturePath = backGroundTexturePath; + } + widget.loadTextureBackGroundSelected(backGroundSelectedTexturePath, backGroundSelectedType); + + //load frontCross image + var frontCrossDic = options["frontCrossData"]; + var frontCrossType = frontCrossDic["resourceType"]; + var frontCrossFileName = resourcePath + frontCrossDic["path"]; + widget.loadTextureFrontCross(frontCrossFileName, frontCrossType); + + //load backGroundBoxDisabledData + var backGroundDisabledDic = options["backGroundBoxDisabledData"]; + var backGroundDisabledType = backGroundDisabledDic["resourceType"]; + var backGroundDisabledFileName = resourcePath + backGroundDisabledDic["path"]; + if(!backGroundDisabledFileName){ + backGroundDisabledType = frontCrossType; + backGroundDisabledFileName = frontCrossFileName; + } + widget.loadTextureBackGroundDisabled(backGroundDisabledFileName, backGroundDisabledType); + + ///load frontCrossDisabledData + var frontCrossDisabledDic = options["frontCrossDisabledData"]; + var frontCrossDisabledType = frontCrossDisabledDic["resourceType"]; + var frontCrossDisabledFileName = resourcePath + frontCrossDisabledDic["path"]; + widget.loadTextureFrontCrossDisabled(frontCrossDisabledFileName, frontCrossDisabledType); + + if (options["selectedState"]) + widget.setSelected(options["selectedState"]); + }; + /** + * ImageView parser (UIImageView) + */ + parser.ImageViewAttributes = function(widget, options, resourcePath){ + var imageFileName, + imageFileNameDic = options["fileNameData"], + imageFileNameType = imageFileNameDic["resourceType"]; + switch (imageFileNameType){ + case 0: + var tp_i = resourcePath; + imageFileName = imageFileNameDic["path"]; + var imageFileName_tp = null; + if (imageFileName && imageFileName !== "") { + imageFileName_tp = tp_i + imageFileName; + widget.loadTexture(imageFileName_tp); + } + break; + case 1: + imageFileName = imageFileNameDic["path"]; + widget.loadTexture(imageFileName, 1/*ui.UI_TEX_TYPE_PLIST*/); + break; + default: + break; + } + + 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) + */ + 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){ + widget.setFontName(options["fontName"]); + } + 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, resoutcePath){ + var imageFileName, + imageFileNameDic = options["textureData"], + imageFileNameType = imageFileNameDic["resourceType"]; + switch (imageFileNameType){ + case 0: + var tp_i = resoutcePath; + imageFileName = imageFileNameDic["path"]; + var imageFileName_tp = null; + if (imageFileName && (imageFileName !== "")){ + imageFileName_tp = tp_i + imageFileName; + widget.loadTexture(imageFileName_tp); + } + break; + case 1: + imageFileName = imageFileNameDic["path"]; + widget.loadTexture(imageFileName, 1/*ui.UI_TEX_TYPE_PLIST*/); + break; + default: + break; + } + + 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, resoutcePath){ + + var slider = widget; + var tp = resoutcePath; + + 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"]; + var imageFileName_tp; + + if(bt != null){ + if(barTextureScale9Enable){ + switch(imageFileType){ + case 0: + imageFileName_tp = imageFileName ? + ( tp + imageFileName ) : + null; + slider.loadBarTexture(imageFileName_tp); + break; + case 1: + slider.loadBarTexture(imageFileName, 1 /*ui.UI_TEX_TYPE_PLIST*/); + break; + default: + break; + } + slider.setSize(cc.size(barLength, slider.getContentSize().height)); + } + }else{ + switch(imageFileType){ + case 0: + imageFileName_tp = imageFileName ? + tp + imageFileName : + null; + slider.loadBarTexture(imageFileName_tp); + break; + case 1: + slider.loadBarTexture(imageFileName, 1 /*ui.UI_TEX_TYPE_PLIST*/); + break; + default: + break; + } + } + var normalDic = options["ballNormalData"]; + var normalType = normalDic["resourceType"]; + var normalFileName = normalDic["path"]; + switch(normalType){ + case 0: + var normalFileName_tp = normalFileName ? + tp + normalFileName : + null; + slider.loadSlidBallTextureNormal(normalFileName_tp); + break; + case 1: + slider.loadSlidBallTextureNormal(normalFileName, 1/*ui.UI_TEX_TYPE_PLIST*/); + break; + default: + break; + } + + var pressedDic = options["ballPressedData"]; + var pressedType = pressedDic["resourceType"]; + var pressedFileName = pressedDic["path"]; + if(pressedFileName === null){ + pressedType = normalType; + pressedFileName = normalFileName; + } + switch(pressedType){ + case 0: + var pressedFileName_tp = pressedFileName ? + tp + pressedFileName : + null; + slider.loadSlidBallTexturePressed(pressedFileName_tp); + break; + case 1: + slider.loadSlidBallTexturePressed(pressedFileName, 1/*ui.UI_TEX_TYPE_PLIST*/); + break; + default: + break; + } + var disabledDic = options["ballDisabledData"]; + var disabledType = disabledDic["resourceType"]; + var disabledFileName = disabledDic["path"]; + switch(disabledType){ + case 0: + var disabledFileName_tp = disabledFileName ? + tp + disabledFileName : + null; + slider.loadSlidBallTextureDisabled(disabledFileName_tp); + break; + case 1: + slider.loadSlidBallTextureDisabled(disabledFileName, 1/*ui.UI_TEX_TYPE_PLIST*/); + break; + default: + break; + } + var progressBarDic = options["progressBarData"]; + var progressBarType = progressBarDic["resourceType"]; + var imageProgressFileName = progressBarDic["path"]; + switch (progressBarType){ + case 0: + var imageProgressFileName_tp = imageProgressFileName ? + (tp + imageProgressFileName) : + null; + slider.loadProgressBarTexture(imageProgressFileName_tp); + break; + case 1: + slider.loadProgressBarTexture(imageProgressFileName, 1/*ui.UI_TEX_TYPE_PLIST*/); + break; + default: + break; + } + }; + /** + * TextField parser (UITextField) + */ + parser.TextFieldAttributes = function(widget, options, resoutcePath){ + 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) + widget.setFontName(fn); + 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, parse, 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, parse, widget, options, resourcePath); + return widget; + }); + }); + + load.registerParser("ccui", "1.*", parser); + + +})(ccs.loadNode, ccs._parser); \ No newline at end of file diff --git a/moduleConfig.json b/moduleConfig.json index b5da63757a..02530f0941 100644 --- a/moduleConfig.json +++ b/moduleConfig.json @@ -396,7 +396,14 @@ "extensions/cocostudio/reader/timeline/ActionTimelineCache.js", "extensions/cocostudio/reader/timeline/Frame.js", "extensions/cocostudio/reader/timeline/Timeline.js", - "extensions/cocostudio/reader/timeline/CSLoader.js" + "extensions/cocostudio/reader/timeline/CSLoader.js", + + "extensions/cocostudio/reader/loader/load.js", + "extensions/cocostudio/reader/loader/parsers/uiParser-1.x.js", + "extensions/cocostudio/reader/loader/parsers/timelineParser-1.x.js", + "extensions/cocostudio/reader/loader/parsers/timelineParser-2.x.js" + + ], "gui" : [ "core", "clipping-nodes", "render-texture", "actions", "progress-timer", From b0a81068e17f396ae0574345d167f27ef62aafbf Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Mon, 29 Dec 2014 18:28:26 +0800 Subject: [PATCH 0068/1345] Fixed a bug of cc.Sprite that its setColor doesn't work on IE11 --- cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js index 7f84a3c9ff..d12d6b23a0 100644 --- a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js @@ -380,7 +380,7 @@ ctx = buff.getContext("2d"); ctx.clearRect(0, 0, w, h); } - + ctx.save(); ctx.globalCompositeOperation = 'lighter'; // Make sure to keep the renderCanvas alpha in mind in case of overdraw var a = ctx.globalAlpha; @@ -400,6 +400,7 @@ ctx.globalAlpha = a; ctx.drawImage(tintedImgCache[3], rect.x, rect.y, w, h, 0, 0, w, h); } + ctx.restore(); return buff; }; From 8c50f991af9fff6f4766ae31d97c64f00bbd5bc5 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Tue, 30 Dec 2014 13:50:48 +0800 Subject: [PATCH 0069/1345] Fixed #2489: added a checking to addEventListener of Texture2D, Sprite etc, let them dispatch 'load' event in next frame when texture is loaded. --- cocos2d/core/event-manager/CCEventManager.js | 6 ++++++ cocos2d/core/sprites/CCSprite.js | 2 +- cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js | 2 +- cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js | 2 +- cocos2d/core/textures/CCTexture2D.js | 13 +++++-------- cocos2d/core/textures/TexturesWebGL.js | 11 +++++------ cocos2d/particle/CCParticleSystemCanvasRenderCmd.js | 2 +- .../armature/display/CCSkinWebGLRenderCmd.js | 2 +- 8 files changed, 21 insertions(+), 19 deletions(-) diff --git a/cocos2d/core/event-manager/CCEventManager.js b/cocos2d/core/event-manager/CCEventManager.js index f0bf33a625..6fd0512f68 100644 --- a/cocos2d/core/event-manager/CCEventManager.js +++ b/cocos2d/core/event-manager/CCEventManager.js @@ -942,6 +942,12 @@ cc.EventHelper.prototype = { }, addEventListener: function ( type, listener, target ) { + //check 'type' status, if the status is ready, dispatch event next frame + if(type === "load" && this._textureLoaded){ //only load event checked. + setTimeout(listener.call(target), 0); + return; + } + if ( this._listeners === undefined ) this._listeners = {}; diff --git a/cocos2d/core/sprites/CCSprite.js b/cocos2d/core/sprites/CCSprite.js index cfe5038633..3a5202fa12 100644 --- a/cocos2d/core/sprites/CCSprite.js +++ b/cocos2d/core/sprites/CCSprite.js @@ -932,7 +932,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ var size = texture.getContentSize(); _t.setTextureRect(cc.rect(0,0, size.width, size.height)); //If image isn't loaded. Listen for the load event. - if(!texture._isLoaded){ + if(!texture._textureLoaded){ texture.addEventListener("load", function(){ var size = texture.getContentSize(); _t.setTextureRect(cc.rect(0,0, size.width, size.height)); diff --git a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js index d12d6b23a0..7a8645a5d1 100644 --- a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js @@ -114,7 +114,7 @@ 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._isLoaded)) || alpha === 0) + || !node._texture._textureLoaded)) || alpha === 0) return; var wrapper = ctx || cc._renderContext, context = wrapper.getContext(); diff --git a/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js b/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js index 06311b611f..b590b6c74b 100644 --- a/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js @@ -419,7 +419,7 @@ //cc.assert(!_t._batchNode, "If cc.Sprite is being rendered by cc.SpriteBatchNode, cc.Sprite#draw SHOULD NOT be called"); if (locTexture) { - if (locTexture._isLoaded) { + if (locTexture._textureLoaded) { this._shaderProgram.use(); this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix); diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index dbdc03ee4d..82833cab4f 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -122,16 +122,14 @@ if (cc._renderType === cc._RENDER_TYPE_CANVAS) { */ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{ _contentSize: null, - _isLoaded: false, + _textureLoaded: false, _htmlElementObj: null, - url: null, - _pattern: null, ctor: function () { this._contentSize = cc.size(0, 0); - this._isLoaded = false; + this._textureLoaded = false; this._htmlElementObj = null; this._pattern = ""; }, @@ -199,7 +197,7 @@ if (cc._renderType === cc._RENDER_TYPE_CANVAS) { * @returns {boolean} */ isLoaded: function () { - return this._isLoaded; + return this._textureLoaded; }, /** @@ -207,14 +205,14 @@ if (cc._renderType === cc._RENDER_TYPE_CANVAS) { */ handleLoadedTexture: function () { var self = this; - if (self._isLoaded) return; + if (self._textureLoaded) return; if (!self._htmlElementObj) { var img = cc.loader.getRes(self.url); if (!img) return; self.initWithElement(img); } - self._isLoaded = true; + self._textureLoaded = true; var locElement = self._htmlElementObj; self._contentSize.width = locElement.width; self._contentSize.height = locElement.height; @@ -398,7 +396,6 @@ if (cc._renderType === cc._RENDER_TYPE_CANVAS) { /** * remove listener from listeners by target * @param {cc.Node} target - * @deprecated since 3.1, please use addEventListener instead */ removeLoadedEventListener: function (target) { this.removeEventListener("load", target); diff --git a/cocos2d/core/textures/TexturesWebGL.js b/cocos2d/core/textures/TexturesWebGL.js index 567efa7998..4e0f41c5d9 100644 --- a/cocos2d/core/textures/TexturesWebGL.js +++ b/cocos2d/core/textures/TexturesWebGL.js @@ -64,7 +64,7 @@ cc._tmp.WebGLTexture2D = function () { shaderProgram: null, - _isLoaded: false, + _textureLoaded: false, _htmlElementObj: null, _webTextureObj: null, @@ -308,7 +308,7 @@ cc._tmp.WebGLTexture2D = function () { self._hasMipmaps = false; self.shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURE); - self._isLoaded = true; + self._textureLoaded = true; return true; }, @@ -406,7 +406,7 @@ cc._tmp.WebGLTexture2D = function () { cc.log(cc._LogInfos.Texture2D_initWithImage_2, imageWidth, imageHeight, maxTextureSize, maxTextureSize); return false; } - this._isLoaded = true; + this._textureLoaded = true; // always load premultiplied images return this._initPremultipliedATextureWithImage(uiImage, imageWidth, imageHeight); @@ -436,7 +436,7 @@ cc._tmp.WebGLTexture2D = function () { * @return {Boolean} */ isLoaded: function () { - return this._isLoaded; + return this._textureLoaded; }, /** @@ -454,7 +454,7 @@ cc._tmp.WebGLTexture2D = function () { } if (!self._htmlElementObj.width || !self._htmlElementObj.height) return; - self._isLoaded = true; + self._textureLoaded = true; //upload image to buffer var gl = cc._renderContext; @@ -757,7 +757,6 @@ cc._tmp.WebGLTexture2D = function () { /** * remove listener from listeners by target * @param {cc.Node} target - * @deprecated since 3.1, please use addEventListener instead */ removeLoadedEventListener: function (target) { this.removeEventListener("load", target); diff --git a/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js b/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js index 6d71ac0ccc..7b316d3ed3 100644 --- a/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js +++ b/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js @@ -84,7 +84,7 @@ var particleCount = this._node.particleCount, particles = this._node._particles; if (node.drawMode == cc.ParticleSystem.TEXTURE_MODE) { // Delay drawing until the texture is fully loaded by the browser - if (!node._texture || !node._texture._isLoaded) { + if (!node._texture || !node._texture._textureLoaded) { wrapper.restore(); return; } diff --git a/extensions/cocostudio/armature/display/CCSkinWebGLRenderCmd.js b/extensions/cocostudio/armature/display/CCSkinWebGLRenderCmd.js index deb0370c31..f541aa1058 100644 --- a/extensions/cocostudio/armature/display/CCSkinWebGLRenderCmd.js +++ b/extensions/cocostudio/armature/display/CCSkinWebGLRenderCmd.js @@ -99,7 +99,7 @@ return; var gl = ctx || cc._renderContext, locTexture = node._texture; - if (locTexture && locTexture._isLoaded) { + if (locTexture && locTexture._textureLoaded) { this._shaderProgram.use(); this._shaderProgram.setUniformForModelViewAndProjectionMatrixWithMat4(); From 1fd60f39f5838145a97f2d92319715c250dcd243 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 30 Dec 2014 18:31:20 +0800 Subject: [PATCH 0070/1345] update timelineParser-2.x.js --- extensions/cocostudio/reader/loader/load.js | 11 +- .../loader/parsers/timelineParser-2.x.js | 605 +++++++++++++++++- 2 files changed, 588 insertions(+), 28 deletions(-) diff --git a/extensions/cocostudio/reader/loader/load.js b/extensions/cocostudio/reader/loader/load.js index fbfb126792..9bcca3bea0 100644 --- a/extensions/cocostudio/reader/loader/load.js +++ b/extensions/cocostudio/reader/loader/load.js @@ -1,6 +1,12 @@ ccs.loadNode = (function(){ - var load = function(file){ + /** + * load file + * @param file + * @param type - ui|timeline|action + * @returns {*} + */ + var load = function(file, type){ var json = cc.loader.getRes(file); @@ -36,7 +42,8 @@ ccs.loadNode = (function(){ var parser = { "ccui": {}, - "timeline": {} + "timeline": {}, + "action": {} }; load.registerParser = function(name, version, target){ diff --git a/extensions/cocostudio/reader/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/reader/loader/parsers/timelineParser-2.x.js index 38e2e38126..e82139cd07 100644 --- a/extensions/cocostudio/reader/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/reader/loader/parsers/timelineParser-2.x.js @@ -1,5 +1,7 @@ (function(load, baseParser){ + var DEBUG = true; + var Parser = baseParser.extend({ parse: function(file, json){ @@ -128,6 +130,11 @@ } }; + /** + * SingleNode + * @param json + * @returns {cc.Node} + */ parser.initSingleNode = function(json){ var node = new cc.Node(); @@ -136,31 +143,19 @@ return node; }; - parser.initSprite = function(json){ + /** + * Sprite + * @param json + * @returns {cc.Sprite} + */ + parser.initSprite = function(json, resourcePath){ var node = new cc.Sprite(); this.generalAttributes(node, json); - var fileData = json["FileData"]; - if(fileData){ - switch(fileData["Type"]){ - case 1: - var spriteFrame = cc.spriteFrameCache.getSpriteFrameByName(); - if(spriteFrame) - node.setSpriteFrame(spriteFrame); - break; - default: - if(fileData["Path"]) - node.setTexture(fileData["Path"]); - } - - } -// if (!fileExist) -// { -// auto label = Label::create(); -// label->setString(__String::createWithFormat("%s missed", errorFilePath.c_str())->getCString()); -// sprite->addChild(label); -// } + loadTexture(json["FileData"], resourcePath, function(path, type){ + node.setTexture(path); + }); if(json["FlipX"]) node.setFlippedX(true); @@ -170,6 +165,11 @@ return node; }; + /** + * Particle + * @param json + * @returns {*} + */ parser.initParticle = function(json){ var fileData = json["FileData"]; var node; @@ -239,34 +239,587 @@ // -- var frameEvent = json["FrameEvent"]; var callBackType = json["CallBackType"]; - if(callBackType != nul) + 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){ + widget.setScaleX(scale["ScaleX"] || 1); + widget.setScaleY(scale["ScaleY"] || 1); + } + + var anchorPoint = json["AnchorPoint"]; + if(anchorPoint != null) + widget.setAnchorPoint(anchorPoint["ScaleX"] || 0.5, anchorPoint["ScaleY"] || 0.5); + + var color = json["CColor"]; + if(color != null && color["R"] != null &&color["G"] != null &&color["B"] != null) + widget.setColor(color["R"], color["G"], color["B"]); +// +// var size = json["Size"]; +// if(size != null) +// widget.setContentSize(size["X"]||0, size["Y"]||0); + + if(widget instanceof ccui.Layout){ + //todo update UILayoutComponent.bindLayoutComponent + var positionXPercentEnabled = json["PositionPercentXEnable"]; + var positionYPercentEnabled = json["PositionPercentYEnable"]; + var sizeXPercentEnable = json["PercentWidthEnable"]; + var sizeYPercentEnable = json["PercentHeightEnable"]; + var stretchHorizontalEnabled = json["StretchWidthEnable"]; + var stretchVerticalEnabled = json["StretchHeightEnable"]; + var horizontalEdge = json["HorizontalEdge"]; + var verticalEdge = json["VerticalEdge"]; + var leftMargin = json["LeftMargin"]; + var rightMargin = json["RightMargin"]; + var topMargin = json["TopMargin"]; + var bottomMargin = json["BottomMargin"]; + //var prePosition = json["PrePosition"]; + //if(prePosition) + // prePosition["X"], prePosition["Y"] + + //var preSize = json["PreSize"]; + //if(preSize) + // preSize["X"], preSize["Y"] + } + }; - parser.initPanel = function(json){ + /** + * 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["ClipAple"]; + if(clipEnabled != null) + widget.setClippingEnabled(clipEnabled); + + var colorType = json["ComboBoxIndex"]; + if(colorType != null) + widget.setBackGroundColorType(colorType); + + var bgColorOpacity = json["BackColorAlpha"]; + if(bgColorOpacity != null) + widget.setBackGroundColorOpacity(bgColorOpacity); + + var backGroundScale9Enabled = json["Scale9Enable"]; + if(backGroundScale9Enabled != null) + widget.setBackGroundImageScale9Enabled(backGroundScale9Enabled); + + var scale9OriginX = json["Scale9OriginX"]; + var scale9OriginY = json["Scale9OriginY"]; + + var scale9Width = json["Scale9Width"]; + var scale9Height = json["Scale9Height"]; + + var bgStartColor = json["FirstColor"]; + var bgEndColor = json["EndColor"]; + if(bgStartColor != null && bgEndColor != null){ + bgStartColor["R"] == undefined && (bgStartColor["R"] = 255); + bgStartColor["G"] == undefined && (bgStartColor["G"] = 255); + bgStartColor["B"] == undefined && (bgStartColor["B"] = 255); + bgEndColor["R"] == undefined && (bgEndColor["R"] = 255); + bgEndColor["G"] == undefined && (bgEndColor["G"] = 255); + bgEndColor["B"] == undefined && (bgEndColor["B"] = 255); + widget.setBackGroundColor( + cc.color(bgStartColor["R"], bgStartColor["G"], bgStartColor["B"]), + cc.color(bgEndColor["R"], bgEndColor["G"], bgEndColor["B"]) + ); + } - return node; + var colorVector = json["ColorVector"]; + if(colorVector != null) + colorVector["ScaleX"]; + + loadTexture(json["FileData"], resourcePath, function(path, type){ + widget.setBackGroundImage(path, type); + }); + + return widget; + }; + + /** + * Text + * @param json + * @param resourcePath + */ + parser.initText = function(json, resourcePath){ + + var widget = new ccui.Text(); + + this.widgetAttributes(widget, json); + + 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"]; + 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"]; + 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); + + //todo check it + var isCustomSize = json["IsCustomSize"]; + widget.ignoreContentAdaptWithSize(!isCustomSize); + + var path, resoutceType, plistFile; + var fontResource = json["FontResource"]; + if(fontResource != null){ + path = fontResource["Path"]; + resoutceType = fontResource["Type"]; + plistFile = fontResource["Plist"]; + } + + widget.setUnifySizeEnabled(false); + + if(widget.isIgnoreContentAdaptWithSize()){ + var size = json["Size"]; + if(size != null) + widget.setContentSize(cc.size(size["X"]||0, size["Y"]||0)); + } + + return widget; + + }; + + /** + * Button + * @param json + * @param resourcePath + */ + parser.initButton = function(json, resourcePath){ + + var widget = new ccui.Button(); + + this.widgetAttributes(widget, json); + + var scale9Enabled = json["Scale9Enable"]; + if(scale9Enabled){ + widget.setScale9Enabled(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); + + } + + var size = json["Size"]; + if(size != null){ + widget.setContentSize(size["X"] || 0, size["Y"] || 0); + } + + 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 displaystate = json["DisplayState"]; + if(displaystate != null){ + widget.setBright(displaystate); + widget.setEnabled(displaystate); + } + + var textColor = json["TextColor"]; + if(textColor != null){ + textColor["R"] = textColor["R"] != null ? textColor["R"] : 255; + textColor["G"] = textColor["G"] != null ? textColor["G"] : 255; + textColor["B"] = textColor["B"] != null ? textColor["B"] : 255; + widget.setTitleColor(cc.color(textColor["R"], textColor["G"], textColor["B"])); + } + + var dataList = [ + {json: json["DisabledFileData"], handle: function(path, type){ + widget.loadTextureDisabled(path, type); + }}, + {json: json["PressedFileData"], handle: function(path, type){ + widget.loadTexturePressed(path, type); + }}, + {json: json["NormalFileData"], handle: function(path, type){ + widget.loadTextureNormal(path, type); + }} + ]; + + dataList.forEach(function(item){ + loadTexture(item.json, resourcePath, item.handle); + }); + + //var fontResourcePath, fontResourceResourceType, fontResourcePlistFile; + //var fontResource = json["FontResource"]; + //if(fontResource != null){ + // fontResourcePath = fontResource["Path"]; + // fontResourceResourceType = fontResource["Type"] == "Default" ? 0 : 1; + // fontResourcePlistFile = fontResource["Plist"]; + //} + + return widget; + + }; + + /** + * CheckBox + * @param json + * @param resourcePath + */ + parser.initCheckBox = function(json, resourcePath){ + + var widget = new ccui.CheckBox(); + + this.widgetAttributes(widget, json); + + var selectedState = json["CheckedState"]; + if(selectedState) + widget.setSelected(true); + + var displaystate = json["DisplayState"]; + if(displaystate){ + widget.setBright(displaystate); + widget.setEnabled(displaystate); + } + + var dataList = [ + {json: json["NormalBackFileData"], handle: function(path, type){ + widget.loadTextureBackGround(path, type); + }}, + {json: json["PressedBackFileData"], handle: function(path, type){ + widget.loadTextureBackGroundSelected(path, type); + }}, + {json: json["NodeNormalFileData"], handle: function(path, type){ + widget.loadTextureFrontCross(path, type); + }}, + {json: json["DisableBackFileData"], handle: function(path, type){ + widget.loadTextureBackGroundDisabled(path, type); + }}, + {json: json["NodeDisableFileData"], handle: function(path, type){ + widget.loadTextureFrontCrossDisabled(path, type); + }} + ]; + + dataList.forEach(function(item){ + loadTexture(item.json, resourcePath, item.handle); + }); + + return widget; + }; + + /** + * ScrollView + * @param json + * @param resourcePath + */ + parser.initScrollView = function(json, resourcePath){ + var widget = new ccui.ScrollView(); + + this.widgetAttributes(widget, json); + + var clipEnabled = json["ClipAble"]; + if(clipEnabled) + widget.setClippingEnabled(true); + + var colorType = json["ComboBoxIndex"]; + if(colorType != null) + widget.setBackGroundColorType(colorType); + + var bgColorOpacity = json["BackColorAlpha"]; + if(bgColorOpacity) + widget.setBackGroundColorOpacity(bgColorOpacity); + + var backGroundScale9Enabled = json["Scale9Enable"]; + if(backGroundScale9Enabled){ + widget.setBackGroundImageScale9Enabled(true); + } + + var scale9OriginX = json["Scale9OriginX"]; + var scale9OriginY = json["Scale9OriginY"]; + + var scale9Width = json["Scale9Width"]; + var scale9Height = json["Scale9Height"]; + + var scale9Size = json["Size"]; + if(scale9Size){ + scale9Size = cc.size(scale9Size["X"] || 0, scale9Size["Y"] || 0); + } + + + if(json["FirstColor"] && json["EndColor"]){ + var bgStartColor, bgEndColor; + bgStartColor = setColor(json["FirstColor"]); + bgEndColor = setColor(json["EndColor"]); + widget.setBackGroundColor(bgStartColor, bgEndColor); + }else{ + widget.setBackGroundColor(setColor(json["SingleColor"])); + } + + + var colorVector = json["ColorVector"]; + if(colorVector){ + widget.setBackGroundColorVector(cc.p(colorVector["ScaleX"] || 1, colorVector["ScaleY"] || 1)); + } + + loadTexture(json["FileData"], resourcePath, function(path, type){ + widget.setBackGroundImage(path, type); + }); + + 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 = json["IsBounceEnabled"]; + if(bounceEnabled) + widget.setBounceEnabled(bounceEnabled); + + return widget; + }; + + /** + * ImageView + * @param json + * @param resourcePath + */ + parser.initImageView = function(json, resourcePath){ + + var widget = new ccui.ImageView(); + + this.widgetAttributes(widget, json); + + var scale9Enabled = json["Scale9Enable"]; + if(scale9Enabled){ + widget.setScale9Enabled(true); + widget.setUnifySizeEnabled(false); + widget.ignoreContentAdaptWithSize(false); + + var scale9OriginX = json["Scale9OriginX"]; + var scale9OriginY = json["Scale9OriginY"]; + var scale9Width = json["Scale9Width"]; + var scale9Height = json["Scale9Height"]; + widget.setCapInsets(cc.rect( + scale9OriginX || 0, + scale9OriginY || 0, + scale9Width || 0, + scale9Height || 0 + )); + } + + + var scale9Size = json["Size"]; + if(scale9Size) + widget.setContentSize(cc.size(scale9Size["X"] || 0, scale9Size["Y"] || 0)); + + loadTexture(json["FileData"], resourcePath, function(path, type){ + widget.loadTexture(path, type); + }); + + return widget; + }; + + /** + * + * @param json + * @param resourcePath + * @returns {ccui.LoadingBar} + */ + parser.initLoadingBar = function(json, resourcePath){ + + var widget = new ccui.LoadingBar(); + + this.widgetAttributes(widget, json); + + var direction = json["ProgressType"] == "Left_To_Right" ? 0 : 1; + widget.setDirection(direction); + + var percent = json["ProgressInfo"] != null ? json["ProgressInfo"] : 0; + widget.setPercent(percent); + + loadTexture(json["ImageFileData"], resourcePath, function(path, type){ + widget.loadTexture(path, type); + }); + + return widget; + }; + /** + * + * @param json + * @param resourcePath + */ + parser.initSlider = function(json, resourcePath){ + + var widget = new ccui.Slider(); + + this.widgetAttributes(widget, json); + + var percent = json["PercentInfo"]; + if(percent != null) + widget.setPercent(percent); + + var displaystate = json["DisplayState"]; + if(displaystate != null){ + widget.setBright(displaystate); + widget.setEnabled(displaystate); + } + + loadTexture(json["BackGroundData"], resourcePath, function(path, type){ + widget.loadBarTexture(path, type); + }); + loadTexture(json["BallNormalData"], resourcePath, function(path, type){ + widget.loadSlidBallTextureNormal(path, type); + }); + loadTexture(json["BallPressedData"], resourcePath, function(path, type){ + widget.loadSlidBallTexturePressed(path, type); + }); + loadTexture(json["BallDisabledData"], resourcePath, function(path, type){ + widget.loadSlidBallTextureDisabled(path, type); + }); + loadTexture(json["ProgressBarData"], resourcePath, function(path, type){ + widget.loadProgressBarTexture(path, type); + }); + + + return widget; + }; + + /** + * + * @param json + * @param resourcePath + */ + parser.initPageView = function(json, resourcePath){ + + var widget = ccui.PageView(); + + this.widgetAttributes(widget, json); + + var percent = json["PercentInfo"]; + + var displaystate = json["DisplayState"]; + + return widget; + + }; + + 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) + cc.spriteFrameCache.addSpriteFrames(resourcePath + plist); + if(type !== 0) + cb(path, type); + else + cb(resourcePath + path, type); + } + }; + + var setColor = 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; + return cc.size(r, g, b); + }; + + + var register = [ {name: "SingleNodeObjectData", handle: parser.initSingleNode}, {name: "SpriteObjectData", handle: parser.initSprite}, {name: "ParticleObjectData", handle: parser.initParticle}, - {name: "PanelObjectData", handle: parser.initPanel} + {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} ]; register.forEach(function(item){ parser.registerParser(item.name, function(options, parse, resourcePath){ - var node = item.handle.call(this, options); + var node = item.handle.call(this, options, resourcePath); this.parseChild(node, options["Children"], resourcePath); + DEBUG && (node.__parserName = item.name); return node; }); }); From 795cd35eb476df5990638f893fdb2d9b822af9a0 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Wed, 31 Dec 2014 10:11:03 +0800 Subject: [PATCH 0071/1345] Fixed #2560: fixed a bug of Armature that its position doesn't update in visit on WebGL mode --- .../armature/CCArmatureWebGLRenderCmd.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js b/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js index bf2df6893f..f405d461e4 100644 --- a/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js +++ b/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js @@ -117,6 +117,23 @@ 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. From 3795b23accdad2212300187458cc71eb8a8cd8b8 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 31 Dec 2014 11:43:21 +0800 Subject: [PATCH 0072/1345] Issue #2563: add ListView and PageView --- .../loader/parsers/timelineParser-2.x.js | 150 ++++++++++++++++-- 1 file changed, 140 insertions(+), 10 deletions(-) diff --git a/extensions/cocostudio/reader/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/reader/loader/parsers/timelineParser-2.x.js index e82139cd07..da557de0b0 100644 --- a/extensions/cocostudio/reader/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/reader/loader/parsers/timelineParser-2.x.js @@ -174,7 +174,7 @@ var fileData = json["FileData"]; var node; if(fileData){ - node = new cc.ParticleSystemQuad(); + node = new cc.ParticleSystem(); this.generalAttributes(node, json); } return node; @@ -608,11 +608,11 @@ if(json["FirstColor"] && json["EndColor"]){ var bgStartColor, bgEndColor; - bgStartColor = setColor(json["FirstColor"]); - bgEndColor = setColor(json["EndColor"]); + bgStartColor = getColor(json["FirstColor"]); + bgEndColor = getColor(json["EndColor"]); widget.setBackGroundColor(bgStartColor, bgEndColor); }else{ - widget.setBackGroundColor(setColor(json["SingleColor"])); + widget.setBackGroundColor(getColor(json["SingleColor"])); } @@ -674,7 +674,6 @@ )); } - var scale9Size = json["Size"]; if(scale9Size) widget.setContentSize(cc.size(scale9Size["X"] || 0, scale9Size["Y"] || 0)); @@ -760,18 +759,148 @@ */ parser.initPageView = function(json, resourcePath){ - var widget = ccui.PageView(); + var widget = new ccui.PageView(); this.widgetAttributes(widget, json); - var percent = json["PercentInfo"]; + var clipEnabled = json["ClipAble"]; + if(clipEnabled) + widget.setClippingEnabled(true); - var displaystate = json["DisplayState"]; + var backGroundScale9Enabled = json["Scale9Enable"]; + if(backGroundScale9Enabled){ + widget.setBackGroundImageScale9Enabled(true); + + var scale9OriginX = json["Scale9OriginX"]; + var scale9OriginY = json["Scale9OriginY"]; + var scale9Width = json["Scale9Width"]; + var scale9Height = json["Scale9Height"]; + widget.setBackGroundImageCapInsets(cc.rect( + scale9OriginX || 0, + scale9OriginY || 0, + scale9Width || 0, + scale9Height || 0 + )); + } + + var colorType = json["ComboBoxIndex"]; + if(colorType != null) + widget.setBackGroundColorType(colorType); + + var bgColorOpacity = json["BackColorAlpha"]; + var bgColor = getColor(json["SingleColor"]); + var bgEndColor = getColor(json["EndColor"]); + var bgStartColor = getColor(json["FirstColor"]); + if(bgEndColor && bgStartColor) + widget.setBackGroundColor(bgStartColor, bgEndColor); + else + widget.setBackGroundColor(bgColor); + + var colorVector = json["ColorVector"]; + if(colorVector != null && colorVector["ScaleX"] != null && colorVector["ScaleY"] != null) + widget.setBackGroundColorVector(colorVector["ScaleX"], colorVector["ScaleY"]); + widget.setBackGroundColorOpacity(bgColorOpacity); + + loadTexture(json["FileData"], resourcePath, function(path, type){ + widget.setBackGroundImage(path, type); + }); + + var size = json["Size"]; + if(size != null) + widget.setContentSize(size["X"], size["Y"]); return widget; }; + parser.initListView = function(json, resourcePath){ + + var widget = new ccui.ListView(); + + var clipEnabled = json["ClipAble"]; + if(clipEnabled) + widget.setClippingEnabled(true); + + var colorType = json["ComboBoxIndex"]; + if(colorType != null) + widget.setBackGroundColorType(colorType); + + var bgColorOpacity = json["BackColorAlpha"]; + var backGroundScale9Enabled = json["Scale9Enable"]; + if(backGroundScale9Enabled){ + widget.setBackGroundImageScale9Enabled(true); + + var scale9OriginX = json["Scale9OriginX"]; + var scale9OriginY = json["Scale9OriginY"]; + var scale9Width = json["Scale9Width"]; + var scale9Height = json["Scale9Height"]; + widget.setBackGroundImageCapInsets(cc.rect( + scale9OriginX || 0, + scale9OriginY || 0, + scale9Width || 0, + scale9Height || 0 + )); + } + + var directionType = json["DirectionType"]; + var verticalType = json["VerticalType"]; + var horizontalType = json["HorizontalType"]; + if(!directionType){ + widget.setDirection(ccui.ListView.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.ListView.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_VERTICAL); + } + + + var bounceEnabled = json["IsBounceEnabled"]; + if(bounceEnabled) + widget.setBounceEnabled(true); + var itemMargin = json["ItemMargin"]; + if(itemMargin != null){ + widget.setItemsMargin(itemMargin); + } + + var innerSize = json["InnerNodeSize"]; + //Width + if(innerSize != null) + widget.setInnerContainerSize(cc.size(innerSize["Widget"]||0, innerSize["Height"]||0)); + + var bgColor = getColor(json["SingleColor"]); + var bgEndColor = getColor(json["EndColor"]); + var bgStartColor = getColor(json["FirstColor"]); + if(bgEndColor && bgStartColor) + widget.setBackGroundColor(bgStartColor, bgEndColor); + else + widget.setBackGroundColor(bgColor); + var colorVector = json["ColorVector"]; + if(colorVector != null && colorVector["ScaleX"] != null && colorVector["ScaleY"] != null) + widget.setBackGroundColorVector(colorVector["ScaleX"], colorVector["ScaleY"]); + widget.setBackGroundColorOpacity(bgColorOpacity); + + + loadTexture(json["FileData"], resourcePath, function(path, type){ + widget.setBackGroundImage(path, type); + }); + + var size = json["Size"]; + if(size != null) + widget.setContentSize(size["X"]||0, size["Y"]||0); + + return widget; + }; + var loadTexture = function(json, resourcePath, cb){ if(json != null){ var path = json["Path"]; @@ -790,7 +919,7 @@ } }; - var setColor = function(json){ + var getColor = function(json){ if(!json) return; var r = json["R"] != null ? json["R"] : 255; var g = json["G"] != null ? json["G"] : 255; @@ -812,7 +941,8 @@ {name: "ImageViewObjectData", handle: parser.initImageView}, {name: "LoadingBarObjectData", handle: parser.initLoadingBar}, {name: "SliderObjectData", handle: parser.initSlider}, - {name: "PageViewObjectData", handle: parser.initPageView} + {name: "PageViewObjectData", handle: parser.initPageView}, + {name: "ListViewObjectData", handle: parser.initListView} ]; register.forEach(function(item){ From c699dce722cf3e850645e17c0584cd30815bef64 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Wed, 31 Dec 2014 15:06:14 +0800 Subject: [PATCH 0073/1345] Fixed #1545: fixed a bug of cc.Sprite that its setTextureRect doesn't work when called setColor --- cocos2d/core/sprites/CCSprite.js | 2 +- .../core/sprites/CCSpriteCanvasRenderCmd.js | 94 +++++++++++-------- 2 files changed, 55 insertions(+), 41 deletions(-) diff --git a/cocos2d/core/sprites/CCSprite.js b/cocos2d/core/sprites/CCSprite.js index 3a5202fa12..8c7f1abf23 100644 --- a/cocos2d/core/sprites/CCSprite.js +++ b/cocos2d/core/sprites/CCSprite.js @@ -825,7 +825,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ cc.assert(newFrame, cc._LogInfos.Sprite_setSpriteFrame) } - this.setNodeDirty(true) + this.setNodeDirty(true); var frameOffset = newFrame.getOffset(); _t._unflippedOffsetPositionFromCenter.x = frameOffset.x; diff --git a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js index 7a8645a5d1..ec0ecd09b8 100644 --- a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js @@ -100,12 +100,10 @@ proto._checkTextureBoundary = function (texture, rect, rotated) { if (texture && texture.url) { var _x = rect.x + rect.width, _y = rect.y + rect.height; - if (_x > texture.width) { + if (_x > texture.width) cc.error(cc._LogInfos.RectWidth, texture.url); - } - if (_y > texture.height) { + if (_y > texture.height) cc.error(cc._LogInfos.RectHeight, texture.url); - } } this._node._originalTexture = texture; }; @@ -165,28 +163,24 @@ cc.g_NumberOfDraws++; }; - proto._updateColor = function () { - //TODO need refactor - var node = this._node; - var displayedColor = this._displayedColor; + if(!cc.sys._supportCanvasNewBlendModes){ + proto._updateColor = function () { + var node = this._node, displayedColor = this._displayedColor; - if(this._colorized){ - if(displayedColor.r === 255 && displayedColor.g === 255 && displayedColor.b === 255){ - this._colorized = false; - node.texture = this._originalTexture; + if (displayedColor.r === 255 && displayedColor.g === 255 && displayedColor.b === 255){ + if(this._colorized){ + this._colorized = false; + node.texture = this._originalTexture; + } return; } - }else - if(displayedColor.r === 255 && displayedColor.g === 255 && displayedColor.b === 255) - return; - var locElement, locTexture = node._texture, locRect = this._textureCoord; - if (locTexture && locRect.validRect && this._originalTexture) { - locElement = locTexture.getHtmlElementObj(); - if (!locElement) - return; + var locElement, locTexture = node._texture, locRect = this._textureCoord; + if (locTexture && locRect.validRect && this._originalTexture) { + locElement = locTexture.getHtmlElementObj(); + if (!locElement) + return; - if (!cc.sys._supportCanvasNewBlendModes) { var cacheTextureForColor = cc.textureCache.getTextureColors(this._originalTexture.getHtmlElementObj()); if (cacheTextureForColor) { this._colorized = true; @@ -201,7 +195,25 @@ node.texture = locTexture; } } - } else { + } + }; + } else { + proto._updateColor = function () { + var node = this._node, displayedColor = this._displayedColor; + if (displayedColor.r === 255 && displayedColor.g === 255 && displayedColor.b === 255) { + if (this._colorized) { + this._colorized = false; + node.texture = this._originalTexture; + } + return; + } + + var locElement, locTexture = node._texture, locRect = this._textureCoord; + if (locTexture && locRect.validRect && this._originalTexture) { + locElement = locTexture.getHtmlElementObj(); + if (!locElement) + return; + this._colorized = true; if (locElement instanceof HTMLCanvasElement && !this._rectRotated && !this._newTextureWhenChangeColor && this._originalTexture._htmlElementObj != locElement) @@ -214,8 +226,8 @@ node.texture = locTexture; } } - } - }; + }; + } proto.getQuad = function () { //throw an error. it doesn't support this function. @@ -270,24 +282,20 @@ }; proto._spriteFrameLoadedCallback = function (spriteFrame) { - var _t = this; - _t.setTextureRect(spriteFrame.getRect(), spriteFrame.isRotated(), spriteFrame.getOriginalSize()); - - //TODO change - var curColor = _t.getColor(); - if (curColor.r !== 255 || curColor.g !== 255 || curColor.b !== 255) - _t._updateColor(); + var node = this; + node.setTextureRect(spriteFrame.getRect(), spriteFrame.isRotated(), spriteFrame.getOriginalSize()); - _t.dispatchEvent("load"); + node._renderCmd._updateColor(); + node.dispatchEvent("load"); }; proto._textureLoadedCallback = function (sender) { - var _t = this; - if (_t._textureLoaded) + var node = this; + if (node._textureLoaded) return; - _t._textureLoaded = true; - var locRect = _t._rect, locRenderCmd = this._renderCmd; + node._textureLoaded = true; + var locRect = node._rect, locRenderCmd = this._renderCmd; if (!locRect) { locRect = cc.rect(0, 0, sender.width, sender.height); } else if (cc._rectEqualToZero(locRect)) { @@ -296,8 +304,8 @@ } locRenderCmd._originalTexture = sender; - _t.texture = sender; - _t.setTextureRect(locRect, _t._rectRotated); + node.texture = sender; + node.setTextureRect(locRect, node._rectRotated); //set the texture's color after the it loaded var locColor = locRenderCmd._displayedColor; @@ -306,8 +314,8 @@ // by default use "Self Render". // if the sprite is added to a batchnode, then it will automatically switch to "batchnode Render" - _t.setBatchNode(_t._batchNode); - _t.dispatchEvent("load"); + node.setBatchNode(node._batchNode); + node.dispatchEvent("load"); }; proto._setTextureCoords = function (rect, needConvert) { @@ -320,6 +328,12 @@ locTextureRect.width = 0 | (rect.width * scaleFactor); locTextureRect.height = 0 | (rect.height * scaleFactor); locTextureRect.validRect = !(locTextureRect.width === 0 || locTextureRect.height === 0 || locTextureRect.x < 0 || locTextureRect.y < 0); + + if(this._colorized){ + this._node._texture = this._originalTexture; + this._colorized = false; + this._updateColor(); + } }; //TODO need refactor these functions From 7449900bb735a55710587159f2c3a9d3c9e2c987 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Sun, 4 Jan 2015 10:09:07 +0800 Subject: [PATCH 0074/1345] Issue #2563: add action parser --- extensions/cocostudio/reader/loader/load.js | 18 +++++++----- .../reader/loader/parsers/action-2.x.js | 29 +++++++++++++++++++ moduleConfig.json | 1 + 3 files changed, 41 insertions(+), 7 deletions(-) create mode 100644 extensions/cocostudio/reader/loader/parsers/action-2.x.js diff --git a/extensions/cocostudio/reader/loader/load.js b/extensions/cocostudio/reader/loader/load.js index 9bcca3bea0..47be300a21 100644 --- a/extensions/cocostudio/reader/loader/load.js +++ b/extensions/cocostudio/reader/loader/load.js @@ -3,7 +3,7 @@ ccs.loadNode = (function(){ /** * load file * @param file - * @param type - ui|timeline|action + * @param type - ccui|node|action * @returns {*} */ var load = function(file, type){ @@ -19,12 +19,16 @@ ccs.loadNode = (function(){ // Judging the parser (uiParse or timelineParse, Temporarily blank) // The judgment condition is unknown var parse; - if(json["widgetTree"]) - parse = parser["ccui"]; - else if(json["nodeTree"]) - parse = parser["timeline"]; - else if(json["Content"]) - parse = parser["timeline"]; + if(!type){ + if(json["widgetTree"]) + parse = parser["ccui"]; + else if(json["nodeTree"]) + parse = parser["timeline"]; + else if(json["Content"]) + parse = parser["timeline"]; + }else{ + parse = parser[type]; + } if(!parse){ cc.log("Can't find the parser : %s", file); diff --git a/extensions/cocostudio/reader/loader/parsers/action-2.x.js b/extensions/cocostudio/reader/loader/parsers/action-2.x.js new file mode 100644 index 0000000000..b9a77f41c8 --- /dev/null +++ b/extensions/cocostudio/reader/loader/parsers/action-2.x.js @@ -0,0 +1,29 @@ +(function(load, baseParser){ + + var Parser = baseParser.extend({ + + getNodeJson: function(json){ + return json["Content"]["Content"]["Animation"]; + }, + + parseNode: function(json, resourcePath, file){ + var self = this; + //The process of analysis + var timelines = json["Timelines"]; + timelines.forEach(function(timeline){ + var parser = self.parsers[timeline["FrameType"]]; + parser.call(self, timeline, resourcePath); + }); + return new cc.Action(); + } + + }); + var parser = new Parser(); + + parser.registerParser("RotationSkewFrame", function(options, resourcePath){ + + }); + + load.registerParser("action", "2.*", parser); + +})(ccs.loadNode, ccs._parser); \ No newline at end of file diff --git a/moduleConfig.json b/moduleConfig.json index 02530f0941..cca3b2c9e9 100644 --- a/moduleConfig.json +++ b/moduleConfig.json @@ -400,6 +400,7 @@ "extensions/cocostudio/reader/loader/load.js", "extensions/cocostudio/reader/loader/parsers/uiParser-1.x.js", + "extensions/cocostudio/reader/loader/parsers/action-2.x.js", "extensions/cocostudio/reader/loader/parsers/timelineParser-1.x.js", "extensions/cocostudio/reader/loader/parsers/timelineParser-2.x.js" From b1e42e1218d2b87b7e093bb48c8a340580beeeb3 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Sun, 4 Jan 2015 17:52:52 +0800 Subject: [PATCH 0075/1345] Fixed #2517: fixed a bug of cc.PhysicsSprite that its position is incorrect --- cocos2d/physics/CCPhysicsSprite.js | 2 +- cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js | 15 ++++++--------- cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js | 1 - external/chipmunk/chipmunk.js | 1 + 4 files changed, 8 insertions(+), 11 deletions(-) diff --git a/cocos2d/physics/CCPhysicsSprite.js b/cocos2d/physics/CCPhysicsSprite.js index d415a281c5..913b8726e6 100644 --- a/cocos2d/physics/CCPhysicsSprite.js +++ b/cocos2d/physics/CCPhysicsSprite.js @@ -59,7 +59,7 @@ * 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 + * 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); diff --git a/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js b/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js index f8a589c455..cb67531c89 100644 --- a/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js +++ b/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js @@ -38,20 +38,17 @@ // This is a special class // Sprite can not obtain sign // So here must to calculate of each frame - if (this._node.transform) - this._node.transform(); + 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; - if(node._usingNormalizedPosition && node._parent){ //TODO need refactor - var conSize = node._parent._contentSize; - node._position.x = node._normalizedPosition.x * conSize.width; - node._position.y = node._normalizedPosition.y * conSize.height; - node._normalizedPositionDirty = false; - } - var t = this._transform;// quick reference // base position diff --git a/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js b/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js index 44847d998b..893c272953 100644 --- a/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js +++ b/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js @@ -38,7 +38,6 @@ // 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) diff --git a/external/chipmunk/chipmunk.js b/external/chipmunk/chipmunk.js index 6f2fc2b459..0fb3aeaa68 100644 --- a/external/chipmunk/chipmunk.js +++ b/external/chipmunk/chipmunk.js @@ -1575,6 +1575,7 @@ var createStaticBody = function() 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); }; From dae1062ee80c2f51a86d840b618e2f42470f2199 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 5 Jan 2015 14:44:33 +0800 Subject: [PATCH 0076/1345] Issue #2563: Fix reader bug and moving file --- .../cocostudio/{reader => }/loader/load.js | 16 +- .../{reader => }/loader/parsers/action-2.x.js | 2 +- .../loader/parsers/timelineParser-1.x.js | 2 +- .../loader/parsers/timelineParser-2.x.js | 296 +++++++++++++----- .../loader/parsers/uiParser-1.x.js | 2 +- moduleConfig.json | 10 +- 6 files changed, 230 insertions(+), 98 deletions(-) rename extensions/cocostudio/{reader => }/loader/load.js (89%) rename extensions/cocostudio/{reader => }/loader/parsers/action-2.x.js (96%) rename extensions/cocostudio/{reader => }/loader/parsers/timelineParser-1.x.js (99%) rename extensions/cocostudio/{reader => }/loader/parsers/timelineParser-2.x.js (79%) rename extensions/cocostudio/{reader => }/loader/parsers/uiParser-1.x.js (99%) diff --git a/extensions/cocostudio/reader/loader/load.js b/extensions/cocostudio/loader/load.js similarity index 89% rename from extensions/cocostudio/reader/loader/load.js rename to extensions/cocostudio/loader/load.js index 47be300a21..dbda4dffe7 100644 --- a/extensions/cocostudio/reader/loader/load.js +++ b/extensions/cocostudio/loader/load.js @@ -1,4 +1,4 @@ -ccs.loadNode = (function(){ +ccs._load = (function(){ /** * load file @@ -24,7 +24,7 @@ ccs.loadNode = (function(){ parse = parser["ccui"]; else if(json["nodeTree"]) parse = parser["timeline"]; - else if(json["Content"]) + else if(json["Content"] && json["Content"]["Content"]) parse = parser["timeline"]; }else{ parse = parser[type]; @@ -41,7 +41,7 @@ ccs.loadNode = (function(){ return new cc.Node(); } - return currentParser.parse(file, json) || new cc.Node(); + return currentParser.parse(file, json) || null; }; var parser = { @@ -88,6 +88,16 @@ ccs.loadNode = (function(){ })(); +//cc.loader.register(["json", "ExportJson"], { +// load: function(realUrl, url, res, cb){ +// var cloader = cc.loader; +// if(cloader.cache[url]){ +// console.log(url) +// }else{ +// return cc.loader.loadJson(realUrl, cb); +// } +// } +//}); ccs._parser = cc.Class.extend({ diff --git a/extensions/cocostudio/reader/loader/parsers/action-2.x.js b/extensions/cocostudio/loader/parsers/action-2.x.js similarity index 96% rename from extensions/cocostudio/reader/loader/parsers/action-2.x.js rename to extensions/cocostudio/loader/parsers/action-2.x.js index b9a77f41c8..765cdfe171 100644 --- a/extensions/cocostudio/reader/loader/parsers/action-2.x.js +++ b/extensions/cocostudio/loader/parsers/action-2.x.js @@ -26,4 +26,4 @@ load.registerParser("action", "2.*", parser); -})(ccs.loadNode, ccs._parser); \ No newline at end of file +})(ccs._load, ccs._parser); \ No newline at end of file diff --git a/extensions/cocostudio/reader/loader/parsers/timelineParser-1.x.js b/extensions/cocostudio/loader/parsers/timelineParser-1.x.js similarity index 99% rename from extensions/cocostudio/reader/loader/parsers/timelineParser-1.x.js rename to extensions/cocostudio/loader/parsers/timelineParser-1.x.js index 7da3666f2a..8cf3976b37 100644 --- a/extensions/cocostudio/reader/loader/parsers/timelineParser-1.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-1.x.js @@ -253,4 +253,4 @@ load.registerParser("timeline", "1.*", parser); -})(ccs.loadNode, ccs._parser); \ No newline at end of file +})(ccs._load, ccs._parser); \ No newline at end of file diff --git a/extensions/cocostudio/reader/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js similarity index 79% rename from extensions/cocostudio/reader/loader/parsers/timelineParser-2.x.js rename to extensions/cocostudio/loader/parsers/timelineParser-2.x.js index da557de0b0..9043c69c4b 100644 --- a/extensions/cocostudio/reader/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -6,7 +6,7 @@ parse: function(file, json){ var resourcePath = this._dirname(file); - this.pretreatment(json, resourcePath); + this.pretreatment(json, resourcePath, file); var node = this.parseNode(this.getNodeJson(json), resourcePath); this.deferred(json, resourcePath, node, file); return node; @@ -32,7 +32,7 @@ pretreatment: function(json, resourcePath, file){ this.addSpriteFrame(json["textures"], json["texturesPng"], resourcePath); - ccs.actionTimelineCache.loadAnimationActionWithContent(file, json); +// ccs.actionTimelineCache.loadAnimationActionWithContent(file, json); } }); @@ -62,16 +62,21 @@ var rotationSkewX = json["RotationSkewX"]; if (rotationSkewX != null) node.setRotationX(rotationSkewX); - //rotationSkewX + var rotationSkewY = json["RotationSkewY"]; if (json["RotationSkewY"] != null) node.setRotationY(rotationSkewY); - //rotationSkewY - //todo check it + var anchor = json["AnchorPoint"]; - if(anchor && (anchor["ScaleX"] || anchor["ScaleY"])) - node.setAnchorPoint(cc.p(anchor["ScaleX"]||0.5, anchor["ScaleY"]||0.5)); + 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"]); @@ -87,9 +92,6 @@ if (json["Alpha"] != null) node.setOpacity(json["Alpha"]); - var color = json["CColor"]; - if(color != null && (color["R"] != null || color["G"] != null || color["B"] != null)) - node.setColor(cc.color(color["R"]||255, color["G"]||255, color["B"]||255)); if (json["Tag"] != null) node.setTag(json["Tag"]); @@ -151,10 +153,14 @@ parser.initSprite = function(json, resourcePath){ var node = new cc.Sprite(); - this.generalAttributes(node, json); - loadTexture(json["FileData"], resourcePath, function(path, type){ - node.setTexture(path); + if(type == 0) + node.setTexture(path); + else if(type == 1){ + var spriteFrame = cc.spriteFrameCache.getSpriteFrame(path); + node.setSpriteFrame(spriteFrame); + } + }); if(json["FlipX"]) @@ -162,21 +168,29 @@ 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){ - var fileData = json["FileData"]; - var node; - if(fileData){ - node = new cc.ParticleSystem(); - this.generalAttributes(node, json); - } + 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 pre load", path); + node = new cc.ParticleSystem(path); + self.generalAttributes(node, json); + }); return node; }; @@ -202,7 +216,7 @@ var rotationSkewY = json["RotationSkewY"]; if(rotationSkewY) - widget.setRotationX(rotationSkewY); + widget.setRotationY(rotationSkewY); //var rotation = json["Rotation"]; @@ -232,9 +246,9 @@ if(tag != null) widget.setTag(tag); - var touchEnabled = json["TouchEnabled"]; - if(touchEnabled != null) - widget.setTouchEnabled(touchEnabled); + var touchEnabled = json["TouchEnable"]; + if(touchEnabled) + widget.setTouchEnabled(true); // -- var frameEvent = json["FrameEvent"]; @@ -261,12 +275,12 @@ widget.setAnchorPoint(anchorPoint["ScaleX"] || 0.5, anchorPoint["ScaleY"] || 0.5); var color = json["CColor"]; - if(color != null && color["R"] != null &&color["G"] != null &&color["B"] != null) - widget.setColor(color["R"], color["G"], color["B"]); -// -// var size = json["Size"]; -// if(size != null) -// widget.setContentSize(size["X"]||0, size["Y"]||0); + if(color != null) + widget.setColor(getColor(color)); + + var size = json["Size"]; + if(size != null) + widget.setContentSize(size["X"]||0, size["Y"]||0); if(widget instanceof ccui.Layout){ //todo update UILayoutComponent.bindLayoutComponent @@ -329,20 +343,12 @@ var bgStartColor = json["FirstColor"]; var bgEndColor = json["EndColor"]; if(bgStartColor != null && bgEndColor != null){ - bgStartColor["R"] == undefined && (bgStartColor["R"] = 255); - bgStartColor["G"] == undefined && (bgStartColor["G"] = 255); - bgStartColor["B"] == undefined && (bgStartColor["B"] = 255); - bgEndColor["R"] == undefined && (bgEndColor["R"] = 255); - bgEndColor["G"] == undefined && (bgEndColor["G"] = 255); - bgEndColor["B"] == undefined && (bgEndColor["B"] = 255); widget.setBackGroundColor( - cc.color(bgStartColor["R"], bgStartColor["G"], bgStartColor["B"]), - cc.color(bgEndColor["R"], bgEndColor["G"], bgEndColor["B"]) + getColor(bgStartColor), + getColor(bgEndColor) ); } - - var colorVector = json["ColorVector"]; if(colorVector != null) colorVector["ScaleX"]; @@ -412,14 +418,19 @@ //todo check it var isCustomSize = json["IsCustomSize"]; - widget.ignoreContentAdaptWithSize(!isCustomSize); + if(isCustomSize != null) + widget.ignoreContentAdaptWithSize(!isCustomSize); - var path, resoutceType, plistFile; + //todo check it var fontResource = json["FontResource"]; if(fontResource != null){ - path = fontResource["Path"]; - resoutceType = fontResource["Type"]; - plistFile = fontResource["Plist"]; + var path = fontResource["Path"]; + //resoutceType = fontResource["Type"]; + if(path != null){ + fontName = path.match(/([^\/]+)\.ttf/); + fontName = fontName ? fontName[1] : ""; + widget.setFontName(fontName); + } } widget.setUnifySizeEnabled(false); @@ -486,27 +497,18 @@ } var textColor = json["TextColor"]; - if(textColor != null){ - textColor["R"] = textColor["R"] != null ? textColor["R"] : 255; - textColor["G"] = textColor["G"] != null ? textColor["G"] : 255; - textColor["B"] = textColor["B"] != null ? textColor["B"] : 255; - widget.setTitleColor(cc.color(textColor["R"], textColor["G"], textColor["B"])); - } + if(textColor != null) + widget.setTitleColor(getColor(textColor)); - var dataList = [ - {json: json["DisabledFileData"], handle: function(path, type){ - widget.loadTextureDisabled(path, type); - }}, - {json: json["PressedFileData"], handle: function(path, type){ - widget.loadTexturePressed(path, type); - }}, - {json: json["NormalFileData"], handle: function(path, type){ - widget.loadTextureNormal(path, type); - }} - ]; - dataList.forEach(function(item){ - loadTexture(item.json, resourcePath, item.handle); + 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 fontResourcePath, fontResourceResourceType, fontResourcePlistFile; @@ -681,6 +683,9 @@ loadTexture(json["FileData"], resourcePath, function(path, type){ widget.loadTexture(path, type); }); + loadTexture(json["ImageFileData"], resourcePath, function(path, type){ + widget.loadTexture(path, type); + }); return widget; }; @@ -697,16 +702,17 @@ this.widgetAttributes(widget, json); - var direction = json["ProgressType"] == "Left_To_Right" ? 0 : 1; - widget.setDirection(direction); - - var percent = json["ProgressInfo"] != null ? json["ProgressInfo"] : 0; - widget.setPercent(percent); - loadTexture(json["ImageFileData"], resourcePath, function(path, type){ widget.loadTexture(path, type); }); + var direction = json["ProgressType"]; + widget.setDirection((direction != "Left_To_Right") | 0); + + var percent = json["ProgressInfo"]; + if(percent != null) + widget.setPercent(percent); + return widget; }; @@ -719,35 +725,46 @@ parser.initSlider = function(json, resourcePath){ var widget = new ccui.Slider(); + var loader = cc.loader, + cache = cc.spriteFrameCache; this.widgetAttributes(widget, json); - var percent = json["PercentInfo"]; - if(percent != null) - widget.setPercent(percent); - - var displaystate = json["DisplayState"]; - if(displaystate != null){ - widget.setBright(displaystate); - widget.setEnabled(displaystate); - } - loadTexture(json["BackGroundData"], resourcePath, function(path, type){ + if(type == 0 && !loader.getRes(path)) + cc.log("%s need to pre load", path); widget.loadBarTexture(path, type); }); loadTexture(json["BallNormalData"], resourcePath, function(path, type){ + if(type == 0 && !loader.getRes(path)) + cc.log("%s need to pre load", path); widget.loadSlidBallTextureNormal(path, type); }); loadTexture(json["BallPressedData"], resourcePath, function(path, type){ + if(type == 0 && !loader.getRes(path)) + cc.log("%s need to pre load", path); widget.loadSlidBallTexturePressed(path, type); }); loadTexture(json["BallDisabledData"], resourcePath, function(path, type){ + if(type == 0 && !loader.getRes(path)) + cc.log("%s need to pre load", path); widget.loadSlidBallTextureDisabled(path, type); }); loadTexture(json["ProgressBarData"], resourcePath, function(path, type){ + if(type == 0 && !loader.getRes(path)) + cc.log("%s need to pre load", path); widget.loadProgressBarTexture(path, type); }); + var percent = json["PercentInfo"]; + if(percent != null) + widget.setPercent(percent); + + var displaystate = json["DisplayState"]; + if(displaystate != null){ + widget.setBright(displaystate); + widget.setEnabled(displaystate); + } return widget; }; @@ -901,6 +918,103 @@ return widget; }; + 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 pre load", path); + if(type == 0){ + widget.setProperty(stringValue, path, itemWidth, itemHeight, startCharMap); + } + }); + this.widgetAttributes(widget, json); + + return widget; + }; + + 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){ + widget.setFntFile(path); + }); + return widget; + }; + + parser.initTextField = function(json, resourcePath){ + var widget = new ccui.TextField(); + + var passwordEnabled = json["PasswordEnable"]; + if(passwordEnabled){ + widget.setPasswordEnabled(true); + var passwordStyleText = json["PasswordStyleText"]; + if(passwordStyleText != null) + 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"]; + if(maxLength != null) + widget.setMaxLength(maxLength); + } + + //var isCustomSize = json["IsCustomSize"]; + this.widgetAttributes(widget, json); + + var text = json["LabelText"]; + if(text != null) + widget.setString(text); + + loadTexture(json["FontResource"], resourcePath, function(path, type){ + widget.setFontName(path); + }); + + widget.setUnifySizeEnabled(false); + widget.ignoreContentAdaptWithSize(false); + + var color = json["CColor"]; + if(color != null) + widget.setTextColor(getColor(color)); + + if (!widget.isIgnoreContentAdaptWithSize()) + { + //widget.getVirtualRenderer().setLineBreakWithoutSpace(true); + var size = json["Size"]; + if(size) + widget.setContentSize(cc.size(size["X"] || 0, size["Y"] || 0)); + } + return widget; + + }; + + var loadedPlist = {}; var loadTexture = function(json, resourcePath, cb){ if(json != null){ var path = json["Path"]; @@ -910,8 +1024,15 @@ else type = 1; var plist = json["Plist"]; - if(plist) - cc.spriteFrameCache.addSpriteFrames(resourcePath + plist); + 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 pre load", resourcePath + plist); + } + } if(type !== 0) cb(path, type); else @@ -924,11 +1045,9 @@ var r = json["R"] != null ? json["R"] : 255; var g = json["G"] != null ? json["G"] : 255; var b = json["B"] != null ? json["B"] : 255; - return cc.size(r, g, b); + return cc.color(r, g, b); }; - - var register = [ {name: "SingleNodeObjectData", handle: parser.initSingleNode}, {name: "SpriteObjectData", handle: parser.initSprite}, @@ -942,7 +1061,10 @@ {name: "LoadingBarObjectData", handle: parser.initLoadingBar}, {name: "SliderObjectData", handle: parser.initSlider}, {name: "PageViewObjectData", handle: parser.initPageView}, - {name: "ListViewObjectData", handle: parser.initListView} + {name: "ListViewObjectData", handle: parser.initListView}, + {name: "TextAtlasObjectData", handle: parser.initTextAtlas}, + {name: "TextBMFontObjectData", handle: parser.initTextBMFont}, + {name: "TextFieldObjectData", handle: parser.initTextField} ]; register.forEach(function(item){ @@ -958,4 +1080,4 @@ load.registerParser("timeline", "2.*", parser); -})(ccs.loadNode, ccs._parser); \ No newline at end of file +})(ccs._load, ccs._parser); \ No newline at end of file diff --git a/extensions/cocostudio/reader/loader/parsers/uiParser-1.x.js b/extensions/cocostudio/loader/parsers/uiParser-1.x.js similarity index 99% rename from extensions/cocostudio/reader/loader/parsers/uiParser-1.x.js rename to extensions/cocostudio/loader/parsers/uiParser-1.x.js index 20628505c2..ef3a5b1e03 100644 --- a/extensions/cocostudio/reader/loader/parsers/uiParser-1.x.js +++ b/extensions/cocostudio/loader/parsers/uiParser-1.x.js @@ -797,4 +797,4 @@ load.registerParser("ccui", "1.*", parser); -})(ccs.loadNode, ccs._parser); \ No newline at end of file +})(ccs._load, ccs._parser); \ No newline at end of file diff --git a/moduleConfig.json b/moduleConfig.json index cca3b2c9e9..2f3df9fca6 100644 --- a/moduleConfig.json +++ b/moduleConfig.json @@ -398,11 +398,11 @@ "extensions/cocostudio/reader/timeline/Timeline.js", "extensions/cocostudio/reader/timeline/CSLoader.js", - "extensions/cocostudio/reader/loader/load.js", - "extensions/cocostudio/reader/loader/parsers/uiParser-1.x.js", - "extensions/cocostudio/reader/loader/parsers/action-2.x.js", - "extensions/cocostudio/reader/loader/parsers/timelineParser-1.x.js", - "extensions/cocostudio/reader/loader/parsers/timelineParser-2.x.js" + "extensions/cocostudio/loader/load.js", + "extensions/cocostudio/loader/parsers/uiParser-1.x.js", + "extensions/cocostudio/loader/parsers/action-2.x.js", + "extensions/cocostudio/loader/parsers/timelineParser-1.x.js", + "extensions/cocostudio/loader/parsers/timelineParser-2.x.js" ], From ec65e22b8eb6cab2d0a7ee51903b9bdbce2efd00 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 5 Jan 2015 15:08:42 +0800 Subject: [PATCH 0077/1345] this._shaderProgram is not initialized --- cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js b/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js index 4e6a863ac6..1d358bc78c 100644 --- a/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js +++ b/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js @@ -52,7 +52,8 @@ proto.rendering = function (ctx) { var context = ctx || cc._renderContext, node = this._node; - + if(!this._shaderProgram) + return; this._shaderProgram.use(); this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix); From e3570f752382031a3348c77ac6a6b137a05f8fc3 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 5 Jan 2015 15:59:16 +0800 Subject: [PATCH 0078/1345] Issue #2563: add audio | project | armature --- .../loader/parsers/timelineParser-2.x.js | 58 ++++++++++++++++++- 1 file changed, 55 insertions(+), 3 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 9043c69c4b..837e6b7dd1 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -104,7 +104,7 @@ }; parser.parseChild = function(node, children, resourcePath){ - if(!children) return; + if(!node || !children) return; for (var i = 0; i < children.length; i++) { var child = this.parseNode(children[i], resourcePath); if(child){ @@ -1014,6 +1014,54 @@ }; + parser.initSimpleAudio = function(json, resourcePath){ + + var loop = json["Loop"]; + var volume = json["Volume"]; + if(volume != null) + cc.audioEngine.setMusicVolume(volume); + //var name = json["Name"]; + var resPath = (cc.loader.resPath + "/").replace(/\/\/$/, "/"); + loadTexture(json["FileData"], resourcePath, function(path, type){ + cc.loader.load(path, function(){ + cc.audioEngine.playMusic(resPath + path, loop); + }); + }); + + }; + + parser.initGameMap = function(json, resourcePath){ + + var node = null; + + loadTexture(json["FileData"], resourcePath, function(path, type){ + if(type == 0) + node = new cc.TMXTiledMap(path); + }); + + return node; + }; + + parser.initProjectNode = function(json, resourcePath){ + return ccs._load(json); + }; + + 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){ + ccs.ArmatureDataManager.addArmatureFileInfo(path); + }); + node.init(); + }; + var loadedPlist = {}; var loadTexture = function(json, resourcePath, cb){ if(json != null){ @@ -1064,14 +1112,18 @@ {name: "ListViewObjectData", handle: parser.initListView}, {name: "TextAtlasObjectData", handle: parser.initTextAtlas}, {name: "TextBMFontObjectData", handle: parser.initTextBMFont}, - {name: "TextFieldObjectData", handle: parser.initTextField} + {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} ]; register.forEach(function(item){ parser.registerParser(item.name, function(options, parse, resourcePath){ var node = item.handle.call(this, options, resourcePath); this.parseChild(node, options["Children"], resourcePath); - DEBUG && (node.__parserName = item.name); + DEBUG && node && (node.__parserName = item.name); return node; }); }); From 289944ba93e087d281a8958a7af5680bc0dc18cb Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Mon, 5 Jan 2015 16:23:04 +0800 Subject: [PATCH 0079/1345] Issue #1267: refactor ccui's visit --- cocos2d/core/layers/CCLayerCanvasRenderCmd.js | 5 +- .../ccui/base-classes/CCProtectedNode.js | 10 --- .../CCProtectedNodeCanvasRenderCmd.js | 53 +++++++--------- .../CCProtectedNodeWebGLRenderCmd.js | 29 --------- extensions/ccui/base-classes/UIWidget.js | 59 +++++++----------- .../ccui/base-classes/UIWidgetRenderCmd.js | 62 +++++++++++++++++++ extensions/ccui/layouts/UILayout.js | 10 +-- .../ccui/layouts/UILayoutCanvasRenderCmd.js | 24 ++++++- .../ccui/layouts/UILayoutWebGLRenderCmd.js | 22 +++++++ extensions/ccui/uiwidgets/UIRichText.js | 12 +--- moduleConfig.json | 1 + tools/build.xml | 1 + 12 files changed, 162 insertions(+), 126 deletions(-) create mode 100644 extensions/ccui/base-classes/UIWidgetRenderCmd.js diff --git a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js index 418d308abf..a7f3c6a24b 100644 --- a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js +++ b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js @@ -125,14 +125,13 @@ return; } - var _t = this, node = this._node; - var children = node._children; + var node = this._node, children = node._children; var len = children.length; // quick return if not visible if (!node._visible || len === 0) return; - _t._syncStatus(parentCmd); + this._syncStatus(parentCmd); cc.renderer.pushRenderCommand(this); //the bakeSprite is drawing diff --git a/extensions/ccui/base-classes/CCProtectedNode.js b/extensions/ccui/base-classes/CCProtectedNode.js index 891c66c7d6..c9f8d9f812 100644 --- a/extensions/ccui/base-classes/CCProtectedNode.js +++ b/extensions/ccui/base-classes/CCProtectedNode.js @@ -224,16 +224,6 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{ } }, - /** - * transforms and draws itself, and visit its children and protected children. - * @override - * @function - * @param {CanvasRenderingContext2D|WebGLRenderingContext} ctx context of renderer - */ - visit: function(parentCmd){ - this._renderCmd._visit(parentCmd); - }, - _changePosition: function(){}, /** diff --git a/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js b/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js index 4f2d0725f8..1a1a34f113 100644 --- a/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js +++ b/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js @@ -113,6 +113,28 @@ } } 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(); } }; @@ -127,10 +149,6 @@ proto.constructor = cc.ProtectedNode.CanvasRenderCmd; proto.visit = function(parentCmd){ - this._node.visit(parentCmd); - }; - - proto._visit = function(parentCmd){ var node = this._node; // quick return if not visible if (!node._visible) @@ -147,7 +165,6 @@ node.sortAllChildren(); node.sortAllProtectedChildren(); - var pChild; // draw children zOrder < 0 for (i = 0; i < childLen; i++) { @@ -182,28 +199,6 @@ this._cacheDirty = false; }; - proto._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(); - }; - proto.transform = function(parentCmd, recursive){ var node = this._node; @@ -224,8 +219,8 @@ worldT.tx = (t.tx * pt.a + t.ty * pt.c + pt.tx + xOffset); //tx worldT.ty = (t.tx * pt.b + t.ty * pt.d + pt.ty + yOffset); //ty }else{ - worldT.tx = (t.tx * pt.a + t.ty * pt.c + pt.tx); //tx - worldT.ty = (t.tx * pt.b + t.ty * pt.d + pt.ty); //ty + worldT.tx = (t.tx * pt.a + t.ty * pt.c + pt.tx); //tx + worldT.ty = (t.tx * pt.b + t.ty * pt.d + pt.ty); //ty } } else { worldT.a = t.a; diff --git a/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js b/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js index 559f788cf5..b4581dbaaf 100644 --- a/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js +++ b/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js @@ -25,8 +25,6 @@ (function(){ cc.ProtectedNode.WebGLRenderCmd = function (renderable) { cc.Node.WebGLRenderCmd.call(this, renderable); - this._cachedParent = null; - this._cacheDirty = false; }; var proto = cc.ProtectedNode.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype); @@ -34,10 +32,6 @@ proto.constructor = cc.ProtectedNode.WebGLRenderCmd; proto.visit = function(parentCmd){ - this._node.visit(parentCmd); //todo refactor late - }; - - proto._visit = function(parentCmd){ var node = this._node; // quick return if not visible if (!node._visible) @@ -60,7 +54,6 @@ node.sortAllChildren(); node.sortAllProtectedChildren(); - var pChild; // draw children zOrder < 0 for (i = 0; i < childLen; i++) { @@ -99,28 +92,6 @@ currentStack.top = currentStack.stack.pop(); }; - proto._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(); - }; - proto.transform = function(parentCmd, recursive){ var node = this._node; var t4x4 = this._transform4x4, stackMatrix = this._stackMatrix, diff --git a/extensions/ccui/base-classes/UIWidget.js b/extensions/ccui/base-classes/UIWidget.js index d078172802..67dc978fbb 100644 --- a/extensions/ccui/base-classes/UIWidget.js +++ b/extensions/ccui/base-classes/UIWidget.js @@ -156,25 +156,12 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ getOrCreateLayoutComponent: function(){ var layoutComponent = this.getComponent(ccui.__LAYOUT_COMPONENT_NAME); if (null == layoutComponent){ - var component = new ccui.LayoutComponent(); + layoutComponent = new ccui.LayoutComponent(); this.addComponent(component); - layoutComponent = component; } return layoutComponent; }, - /** - * Calls _adaptRenderers(its subClass will override it) before calls its parent's visit. - * @param {CanvasRenderingContext2D|WebGLRenderingContext} ctx - * @override - */ - visit: function (ctx) { - if (this._visible) { - this._adaptRenderers(); - cc.ProtectedNode.prototype.visit.call(this, ctx); - } - }, - /** * The direct parent when it's a widget also, otherwise equals null * @returns {ccui.Widget|null} @@ -273,8 +260,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ /** * initializes renderer of widget. */ - _initRenderer: function () { - }, + _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. @@ -690,8 +676,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @note it doesn't implemented on Web * @param {Boolean} enable set true to enable dpad focus navigation, otherwise disable dpad focus navigation */ - enableDpadNavigation: function(enable){ - }, + enableDpadNavigation: function(enable){}, /** *

@@ -785,14 +770,11 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ } }, - _onPressStateChangedToNormal: function () { - }, + _onPressStateChangedToNormal: function () {}, - _onPressStateChangedToPressed: function () { - }, + _onPressStateChangedToPressed: function () {}, - _onPressStateChangedToDisabled: function () { - }, + _onPressStateChangedToDisabled: function () {}, _updateChildrenDisplayedRGBA: function(){ this.setColor(this.getColor()); @@ -802,8 +784,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ /** * A call back function when widget lost of focus. */ - didNotSelectSelf: function () { - }, + didNotSelectSelf: function () {}, /** *

@@ -848,8 +829,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ propagateTouchEvent: function(event, sender, touch){ var widgetParent = this.getWidgetParent(); - if (widgetParent) - { + if (widgetParent){ widgetParent.interceptTouchEvent(event, sender, touch); } }, @@ -1192,14 +1172,11 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ return this._flippedY; }, - _updateFlippedX: function () { - }, + _updateFlippedX: function () {}, - _updateFlippedY: function () { - }, + _updateFlippedY: function () {}, - _adaptRenderers: function(){ - }, + _adaptRenderers: function(){}, /** * Determines if the widget is bright @@ -1334,8 +1311,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ } }, - _copySpecialProperties: function (model) { - }, + _copySpecialProperties: function (model) {}, _copyProperties: function (widget) { this.setEnabled(widget.isEnabled()); @@ -1558,11 +1534,11 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @param {Boolean} [cleanup] */ removeNodeByTag: function (tag, cleanup) { - var node = this.getNodeByTag(tag); + var node = this.getChildByTag(tag); if (!node) cc.log("cocos2d: removeNodeByTag(tag = %d): child not found!", tag); else - this.removeNode(node); + this.removeChild(node, cleanup); }, /** @@ -1595,6 +1571,13 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ setUnifySizeEnabled: function(enable){ this._unifySize = enable; + }, + + _createRenderCmd: function(){ + if(cc._renderType === cc._RENDER_TYPE_WEBGL) + return new ccui.Widget.WebGLRenderCmd(this); + else + return new ccui.Widget.CanvasRenderCmd(this); } }); diff --git a/extensions/ccui/base-classes/UIWidgetRenderCmd.js b/extensions/ccui/base-classes/UIWidgetRenderCmd.js new file mode 100644 index 0000000000..b042a4c8b8 --- /dev/null +++ b/extensions/ccui/base-classes/UIWidgetRenderCmd.js @@ -0,0 +1,62 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +if (cc._renderType === cc._RENDER_TYPE_CANVAS) { + (function () { + 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); + } + }; + })(); +} else { + (function () { + 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); + } + }; + })(); +} + diff --git a/extensions/ccui/layouts/UILayout.js b/extensions/ccui/layouts/UILayout.js index 86f35681fc..7bd7f771a0 100644 --- a/extensions/ccui/layouts/UILayout.js +++ b/extensions/ccui/layouts/UILayout.js @@ -312,9 +312,9 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * If clippingEnabled is true, it will clip/scissor area. *

* @override - * @param {CanvasRenderingContext2D|WebGLRenderingContext} ctx + * @param {cc.Node.RenderCmd} [parentCmd] */ - visit: function (ctx) { + visit: function (parentCmd) { if (!this._visible) return; this._adaptRenderers(); @@ -323,16 +323,16 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ if (this._clippingEnabled) { switch (this._clippingType) { case ccui.Layout.CLIPPING_STENCIL: - this._renderCmd.stencilClippingVisit(ctx); + this._renderCmd.stencilClippingVisit(parentCmd); break; case ccui.Layout.CLIPPING_SCISSOR: - this._renderCmd.scissorClippingVisit(ctx); + this._renderCmd.scissorClippingVisit(parentCmd); break; default: break; } } else - ccui.Widget.prototype.visit.call(this, ctx); + ccui.Widget.prototype.visit.call(this, parentCmd); }, /** diff --git a/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js b/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js index bdacc19a75..d3861d2573 100644 --- a/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js +++ b/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js @@ -39,6 +39,28 @@ 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) { @@ -60,8 +82,6 @@ //var node = this._node; if (this._clipElemType) { wrapper.setCompositeOperation("destination-in"); - //var parentCmd = node._parent ? node._parent._renderCmd : null; - //this.transform(parentCmd); //todo: why? } }; diff --git a/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js b/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js index f2de94d980..4ec484d55e 100644 --- a/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js +++ b/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js @@ -50,6 +50,28 @@ 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; diff --git a/extensions/ccui/uiwidgets/UIRichText.js b/extensions/ccui/uiwidgets/UIRichText.js index 9e7069151b..6b44784902 100644 --- a/extensions/ccui/uiwidgets/UIRichText.js +++ b/extensions/ccui/uiwidgets/UIRichText.js @@ -463,16 +463,8 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ this._elementRenders[this._elementRenders.length - 1].push(renderer); }, - /** - * Calls formatText before calls parent class' visit. - * @override - * @param parentCmd - */ - visit: function (parentCmd) { - if (this._enabled) { - this.formatText(); - ccui.Widget.prototype.visit.call(this, parentCmd); - } + _adaptRenderers: function(){ + this.formatText(); }, /** diff --git a/moduleConfig.json b/moduleConfig.json index b5da63757a..8d8cb65595 100644 --- a/moduleConfig.json +++ b/moduleConfig.json @@ -300,6 +300,7 @@ "extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js", "extensions/ccui/system/CocosGUI.js", "extensions/ccui/base-classes/UIWidget.js", + "extensions/ccui/base-classes/UIWidgetRenderCmd.js", "extensions/ccui/base-classes/UIScale9Sprite.js", "extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js", "extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js", diff --git a/tools/build.xml b/tools/build.xml index b89f21f929..0881ff6395 100644 --- a/tools/build.xml +++ b/tools/build.xml @@ -202,6 +202,7 @@ + From 9cd641f72ebaf7bc88257c4a3b12a7dfc53a98ad Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 5 Jan 2015 16:31:01 +0800 Subject: [PATCH 0080/1345] Fix webgl cc.Director is undefined (Compression mode) --- tools/build.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/build.xml b/tools/build.xml index b89f21f929..e602c3e0e0 100644 --- a/tools/build.xml +++ b/tools/build.xml @@ -74,8 +74,8 @@ - + From 887bdb07f42ab1aebc60bbb822ad06e625f0292e Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 5 Jan 2015 17:31:56 +0800 Subject: [PATCH 0081/1345] Issue #2563: Finishing the code --- .../loader/parsers/timelineParser-2.x.js | 214 +++++++++--------- 1 file changed, 107 insertions(+), 107 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 837e6b7dd1..507de25e2d 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -1,6 +1,6 @@ (function(load, baseParser){ - var DEBUG = true; + var DEBUG = false; var Parser = baseParser.extend({ @@ -18,21 +18,6 @@ getClass: function(json){ return json["ctype"]; - }, - - addSpriteFrame: function(textures, plists, resourcePath){ - if(!textures) return; - for (var i = 0; i < textures.length; i++) { - cc.spriteFrameCache.addSpriteFrames( - resourcePath + textures[i], - resourcePath + plists[i] - ); - } - }, - - pretreatment: function(json, resourcePath, file){ - this.addSpriteFrame(json["textures"], json["texturesPng"], resourcePath); -// ccs.actionTimelineCache.loadAnimationActionWithContent(file, json); } }); @@ -85,10 +70,7 @@ if (visible != null) node.setVisible(visible == "True"); - - var contentSize = json["Size"]; - if(contentSize != null && (contentSize["X"] != null || contentSize["Y"] != null)) - node.setContentSize(cc.size(contentSize["X"]||0, contentSize["Y"]||0)); + setContentSize(node, json["Size"]); if (json["Alpha"] != null) node.setOpacity(json["Alpha"]); @@ -148,6 +130,7 @@ /** * Sprite * @param json + * @param resourcePath * @returns {cc.Sprite} */ parser.initSprite = function(json, resourcePath){ @@ -278,9 +261,7 @@ if(color != null) widget.setColor(getColor(color)); - var size = json["Size"]; - if(size != null) - widget.setContentSize(size["X"]||0, size["Y"]||0); + setContentSize(widget, json["Size"]); if(widget instanceof ccui.Layout){ //todo update UILayoutComponent.bindLayoutComponent @@ -342,12 +323,8 @@ var bgStartColor = json["FirstColor"]; var bgEndColor = json["EndColor"]; - if(bgStartColor != null && bgEndColor != null){ - widget.setBackGroundColor( - getColor(bgStartColor), - getColor(bgEndColor) - ); - } + if(bgStartColor != null && bgEndColor != null) + widget.setBackGroundColor( getColor(bgStartColor), getColor(bgEndColor) ); var colorVector = json["ColorVector"]; if(colorVector != null) @@ -435,11 +412,8 @@ widget.setUnifySizeEnabled(false); - if(widget.isIgnoreContentAdaptWithSize()){ - var size = json["Size"]; - if(size != null) - widget.setContentSize(cc.size(size["X"]||0, size["Y"]||0)); - } + if(widget.isIgnoreContentAdaptWithSize()) + setContentSize(widget, json["Size"]); return widget; @@ -473,10 +447,7 @@ } - var size = json["Size"]; - if(size != null){ - widget.setContentSize(size["X"] || 0, size["Y"] || 0); - } + setContentSize(widget, json["Size"]); var text = json["ButtonText"]; if(text != null) @@ -511,13 +482,14 @@ widget.loadTextureDisabled(path, type); }); - //var fontResourcePath, fontResourceResourceType, fontResourcePlistFile; - //var fontResource = json["FontResource"]; - //if(fontResource != null){ + var fontResourcePath, fontResourceResourceType, fontResourcePlistFile; + var fontResource = json["FontResource"]; + if(fontResource != null){ + console.log(fontResource["Path"]) // fontResourcePath = fontResource["Path"]; // fontResourceResourceType = fontResource["Type"] == "Default" ? 0 : 1; // fontResourcePlistFile = fontResource["Plist"]; - //} + } return widget; @@ -545,25 +517,17 @@ } var dataList = [ - {json: json["NormalBackFileData"], handle: function(path, type){ - widget.loadTextureBackGround(path, type); - }}, - {json: json["PressedBackFileData"], handle: function(path, type){ - widget.loadTextureBackGroundSelected(path, type); - }}, - {json: json["NodeNormalFileData"], handle: function(path, type){ - widget.loadTextureFrontCross(path, type); - }}, - {json: json["DisableBackFileData"], handle: function(path, type){ - widget.loadTextureBackGroundDisabled(path, type); - }}, - {json: json["NodeDisableFileData"], handle: function(path, type){ - widget.loadTextureFrontCrossDisabled(path, type); - }} + {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(item.json, resourcePath, item.handle); + loadTexture(json[item.name], resourcePath, function(path, type){ + item.handle.call(widget, path, type); + }); }); return widget; @@ -602,11 +566,8 @@ var scale9Width = json["Scale9Width"]; var scale9Height = json["Scale9Height"]; - var scale9Size = json["Size"]; - if(scale9Size){ - scale9Size = cc.size(scale9Size["X"] || 0, scale9Size["Y"] || 0); - } - + //todo please check it + setContentSize(widget, json["Size"]); if(json["FirstColor"] && json["EndColor"]){ var bgStartColor, bgEndColor; @@ -676,9 +637,7 @@ )); } - var scale9Size = json["Size"]; - if(scale9Size) - widget.setContentSize(cc.size(scale9Size["X"] || 0, scale9Size["Y"] || 0)); + setContentSize(widget, json["Size"]); loadTexture(json["FileData"], resourcePath, function(path, type){ widget.loadTexture(path, type); @@ -691,7 +650,7 @@ }; /** - * + * LoadingBar * @param json * @param resourcePath * @returns {ccui.LoadingBar} @@ -718,42 +677,30 @@ }; /** - * + * Slider * @param json * @param resourcePath */ parser.initSlider = function(json, resourcePath){ var widget = new ccui.Slider(); - var loader = cc.loader, - cache = cc.spriteFrameCache; + var loader = cc.loader; this.widgetAttributes(widget, json); - loadTexture(json["BackGroundData"], resourcePath, function(path, type){ - if(type == 0 && !loader.getRes(path)) - cc.log("%s need to pre load", path); - widget.loadBarTexture(path, type); - }); - loadTexture(json["BallNormalData"], resourcePath, function(path, type){ - if(type == 0 && !loader.getRes(path)) - cc.log("%s need to pre load", path); - widget.loadSlidBallTextureNormal(path, type); - }); - loadTexture(json["BallPressedData"], resourcePath, function(path, type){ - if(type == 0 && !loader.getRes(path)) - cc.log("%s need to pre load", path); - widget.loadSlidBallTexturePressed(path, type); - }); - loadTexture(json["BallDisabledData"], resourcePath, function(path, type){ - if(type == 0 && !loader.getRes(path)) - cc.log("%s need to pre load", path); - widget.loadSlidBallTextureDisabled(path, type); - }); - loadTexture(json["ProgressBarData"], resourcePath, function(path, type){ - if(type == 0 && !loader.getRes(path)) - cc.log("%s need to pre load", path); - widget.loadProgressBarTexture(path, type); + 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 pre load", path); + item.handle.call(widget, path, type); + }); }); var percent = json["PercentInfo"]; @@ -770,7 +717,7 @@ }; /** - * + * PageView * @param json * @param resourcePath */ @@ -822,14 +769,18 @@ widget.setBackGroundImage(path, type); }); - var size = json["Size"]; - if(size != null) - widget.setContentSize(size["X"], size["Y"]); + setContentSize(widget, json["Size"]); return widget; }; + /** + * ListView + * @param json + * @param resourcePath + * @returns {ccui.ListView} + */ parser.initListView = function(json, resourcePath){ var widget = new ccui.ListView(); @@ -911,13 +862,17 @@ widget.setBackGroundImage(path, type); }); - var size = json["Size"]; - if(size != null) - widget.setContentSize(size["X"]||0, size["Y"]||0); + setContentSize(widget, json["Size"]); return widget; }; + /** + * TextAtlas + * @param json + * @param resourcePath + * @returns {ccui.TextAtlas} + */ parser.initTextAtlas = function(json, resourcePath){ var widget = new ccui.TextAtlas(); @@ -940,6 +895,12 @@ return widget; }; + /** + * TextBMFont + * @param json + * @param resourcePath + * @returns {ccui.TextBMFont} + */ parser.initTextBMFont = function(json, resourcePath){ var widget = new ccui.TextBMFont(); @@ -954,6 +915,12 @@ return widget; }; + /** + * TextField + * @param json + * @param resourcePath + * @returns {ccui.TextField} + */ parser.initTextField = function(json, resourcePath){ var widget = new ccui.TextField(); @@ -1004,16 +971,18 @@ widget.setTextColor(getColor(color)); if (!widget.isIgnoreContentAdaptWithSize()) - { + setContentSize(widget, json["Size"]); //widget.getVirtualRenderer().setLineBreakWithoutSpace(true); - var size = json["Size"]; - if(size) - widget.setContentSize(cc.size(size["X"] || 0, size["Y"] || 0)); - } + return widget; }; + /** + * SimpleAudio + * @param json + * @param resourcePath + */ parser.initSimpleAudio = function(json, resourcePath){ var loop = json["Loop"]; @@ -1030,6 +999,12 @@ }; + /** + * GameMap + * @param json + * @param resourcePath + * @returns {*} + */ parser.initGameMap = function(json, resourcePath){ var node = null; @@ -1042,10 +1017,28 @@ return node; }; + /** + * ProjectNode + * @param json + * @param resourcePath + * @returns {*} + */ parser.initProjectNode = function(json, resourcePath){ - return ccs._load(json); + var projectFile = json["FileData"]; + if(projectFile != null && projectFile["Path"]){ + var file = resourcePath + projectFile["Path"]; + if(cc.loader.getRes(file)) + return ccs._load(file); + else + cc.log("%s need to pre load", file); + } }; + /** + * Armature + * @param json + * @param resourcePath + */ parser.initArmature = function(json, resourcePath){ var node = new ccs.Armature(); @@ -1096,6 +1089,13 @@ return cc.color(r, g, b); }; + 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: "SpriteObjectData", handle: parser.initSprite}, From 7ecdcf4ae6f7fdab2f1fc3de7d7aa32206925e9a Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Tue, 6 Jan 2015 10:45:59 +0800 Subject: [PATCH 0082/1345] Issue #1267: Migrating ccui.Scale9Sprite --- .../ccui/base-classes/UIScale9Sprite.js | 137 ++++++++++++++++-- 1 file changed, 127 insertions(+), 10 deletions(-) diff --git a/extensions/ccui/base-classes/UIScale9Sprite.js b/extensions/ccui/base-classes/UIScale9Sprite.js index 153df2fc14..027bdd9f83 100644 --- a/extensions/ccui/base-classes/UIScale9Sprite.js +++ b/extensions/ccui/base-classes/UIScale9Sprite.js @@ -68,10 +68,6 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ _bottomRight: null, //cache in canvas on Canvas mode - _cacheSprite: null, - _cacheCanvas: null, - _cacheContext: null, - _cacheTexture: null, _scale9Dirty: true, _opacityModifyRGB: false, @@ -91,6 +87,21 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ _textureLoaded:false, _className:"Scale9Sprite", + //v3.3 + _scale9Enabled: false, + _topLeftSize: null, + _centerSize: null, + _bottomRightSize: null, + _centerOffset: null, + + _offset: null, + + _protectedChildren: null, + _reorderProtectedChildDirty: false, + + _flippedX: false, + _flippedY: false, + /** * return texture is loaded * @returns {boolean} @@ -521,8 +532,8 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ * to resize the sprite will all it's 9-slice goodness interact. * It respects the anchorPoint too. * - * @param spriteFrameName The sprite frame name. - * @param capInsets The values to use for the cap insets. + * @param {String} spriteFrameName The sprite frame name. + * @param {cc.Rect} capInsets The values to use for the cap insets. */ initWithSpriteFrameName: function (spriteFrameName, capInsets) { if(!spriteFrameName) @@ -539,11 +550,12 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ }, /** - * 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 + *

+ * 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 {cc.Rect} capInsets The values to use for the cap insets. */ resizableSpriteWithCapInsets: function (capInsets) { @@ -918,6 +930,111 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ this._insetBottom = 0; }, + //todo: v3.3 + updateWithSprite: function(sprite, rect, rotated, offset, orginalSize, capInsets){ + //virtual bool updateWithSprite(Sprite* sprite, const Rect& rect, bool rotated, const Rect& capInsets); + //virtual bool updateWithSprite(Sprite* sprite, const Rect& rect, bool rotated, const Vec2 &offset, const Size &originalSize, const Rect& capInsets); + }, + + //virtual void setAnchorPoint(const Vec2& anchorPoint) override; + + /** + * set the state of ccui.Scale9Sprite + * @param {Number} state + */ + setState: function(state){ + + }, + + cleanup: function(){}, + + onEnter: function(){}, + + onEnterTransitionDidFinish: function(){}, + + onExit: function(){}, + + onExitTransitionDidStart: function(){}, + + /** + * Sets whether the widget should be flipped horizontally or not. + * @param {Boolean} flippedX true if the widget should be flipped horizontally, false otherwise. + */ + setFlippedX: function(flippedX){}, + + /** + *

+ * 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(){}, + + /** + * Sets whether the widget should be flipped vertically or not. + * @param {Boolean} flippedY true if the widget should be flipped vertically, false otherwise. + */ + setFlippedY: function(flippedY){}, + + /** + *

+ * 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(){}, + + setScaleX: function(scaleX){}, + + setScaleY: function(scaleY){}, + + setScale: function(scaleX, scaleY){}, + + getScaleX: function(){}, + + getScaleY: function(){}, + + getScale: function(){}, + + _createSlicedSprites: function(){}, + + _cleanupSlicedSprites: function(){ + if (this._topLeft && this._topLeft.isRunning()) + this._topLeft.onExit(); + if (this._top && this._top.isRunning()) + this._top.onExit(); + if (this._topRight && this._topRight.isRunning()) + this._topRight.onExit(); + if (this._left && this._left.isRunning()) + this._left.onExit(); + if (this._centre && this._centre.isRunning()) + this._centre.onExit(); + if (this._right && this._right.isRunning()) + this._right.onExit(); + if (this._bottomLeft && this._bottomLeft.isRunning()) + this._bottomLeft.onExit(); + if (this._bottomRight && this._bottomRight.isRunning()) + this._bottomRight.onExit(); + if (this._bottom && this._bottom.isRunning()) + this._bottom.onExit(); + }, + + _adjustScale9ImagePosition: function(){}, + + _sortAllProtectedChildren: function(){}, + + _addProtectedChild: function(){}, + _createRenderCmd: function(){ if(cc._renderType === cc._RENDER_TYPE_CANVAS) return new ccui.Scale9Sprite.CanvasRenderCmd(this); From 2ba32e5c94e97de2cfcc11b31b0f8c1303268fd7 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 6 Jan 2015 14:21:18 +0800 Subject: [PATCH 0083/1345] Issue #2563: support timeline(action) 1.0.0.0 --- .../cocostudio/loader/parsers/action-1.x.js | 212 ++++++++++++++++++ 1 file changed, 212 insertions(+) create mode 100644 extensions/cocostudio/loader/parsers/action-1.x.js diff --git a/extensions/cocostudio/loader/parsers/action-1.x.js b/extensions/cocostudio/loader/parsers/action-1.x.js new file mode 100644 index 0000000000..135e83f4a5 --- /dev/null +++ b/extensions/cocostudio/loader/parsers/action-1.x.js @@ -0,0 +1,212 @@ +(function(load, baseParser){ + + var cache = {}; + + var Parser = baseParser.extend({ + + getNodeJson: function(json){ + return json["action"]; + }, + + parseNode: function(json, resourcePath, file){ + if(cache[file]) + return cache[file].clone(); + + var self = this, + action = new ccs.ActionTimeline(); + + action.setDuration(json["duration"]); + action.setTimeSpeed(json["speed"] || 1); + //The process of analysis + var timelines = json["timelines"]; + timelines.forEach(function(timeline){ + var parser = self.parsers[timeline["frameType"]]; + var frame; + if(parser) + frame = parser.call(self, timeline, resourcePath); + else + cc.log("parser is not exists : %s", timeline["frameType"]); + if(frame) + action.addTimeline(frame); + + if(timeline["frameType"] == "ColorFrame"){ + action.addTimeline( + self.parsers["AlphaFrame"].call(self, timeline, resourcePath) + ); + } + }); + + cache[file] = action; + + return action.clone(); + } + + }); + + var parser = new Parser(); + + var frameList = [ + { + name: "PositionFrame", + handle: function(options){ + var frame = new ccs.PositionFrame(); + var x = options["x"]; + var y = options["y"]; + frame.setPosition(cc.p(x,y)); + return frame; + } + }, + { + name: "VisibleFrame", + handle: function(options){ + var frame = new ccs.VisibleFrame(); + var visible = options["value"]; + frame.setVisible(visible); + return frame; + } + }, + { + name: "ScaleFrame", + handle: function(options){ + var frame = new ccs.ScaleFrame(); + var scalex = options["x"]; + var scaley = options["y"]; + frame.setScaleX(scalex); + frame.setScaleY(scaley); + return frame; + } + }, + { + name: "RotationFrame", + handle: function(options){ + var frame = new ccs.RotationFrame(); + var rotation = options["rotation"]; + frame.setRotation(rotation); + return frame; + } + }, + { + name: "SkewFrame", + handle: function(options){ + var frame = new ccs.SkewFrame(); + var skewx = options["x"]; + var skewy = options["y"]; + frame.setSkewX(skewx); + frame.setSkewY(skewy); + return frame; + } + }, + { + name: "RotationSkewFrame", + handle: function(options){ + var frame = new ccs.RotationSkewFrame(); + var skewx = options["x"]; + var skewy = options["y"]; + frame.setSkewX(skewx); + frame.setSkewY(skewy); + return frame; + } + }, + { + name: "AnchorFrame", + handle: function(options){ + var frame = new ccs.AnchorPointFrame(); + var anchorx = options["x"]; + var anchory = options["y"]; + frame.setAnchorPoint(cc.p(anchorx, anchory)); + return frame; + } + }, + { + name: "InnerActionFrame", + handle: function(options){ + var frame = new ccs.InnerActionFrame(); + var type = options["innerActionType"]; + var startFrame = options["startFrame"]; + frame.setInnerActionType(type); + frame.setStartFrameIndex(startFrame); + return frame; + } + }, + { + name: "ColorFrame", + handle: function(options){ + var frame = new ccs.ColorFrame(); + var red = options["red"]; + var green = options["green"]; + var blue = options["blue"]; + frame.setColor(cc.color(red, green, blue)); + var alphaFrame = new ccs.AlphaFrame(); + var alpha = options["alpha"]; + alphaFrame.setAlpha(alpha); + return frame; + } + }, + { + name: "AlphaFrame", + handle: function(options){ + var frame = new ccs.AlphaFrame(); + var alpha = options["alpha"]; + frame.setAlpha(alpha); + return frame; + } + }, + { + name: "TextureFrame", + handle: function(options){ + var frame = new ccs.TextureFrame(); + var texture = options["value"]; + if(texture != null) { + var path = texture; + var spriteFrame = cc.spriteFrameCache.getSpriteFrame(path); + if(spriteFrame == null){ + var jsonPath = ccs.csLoader.getJsonPath(); + path = jsonPath + texture; + } + frame.setTextureName(path); + } + return frame; + } + }, + { + name: "EventFrame", + handle: function(options){ + var frame = new ccs.EventFrame(); + var evnt = options["value"]; + if(evnt != null) + frame.setEvent(evnt); + return frame; + } + }, + { + name: "ZOrderFrame", + handle: function(options){ + var frame = new ccs.ZOrderFrame(); + var zorder = options["value"]; + frame.setZOrder(zorder); + return frame; + } + } + ]; + + frameList.forEach(function(item){ + parser.registerParser(item.name, function(options, resourcePath){ + var timeline = new ccs.Timeline(); + timeline.setActionTag(options["actionTag"]); + + var frames = options["frames"]; + if(frames && frames.length){ + frames.forEach(function(frameData){ + var frame = item.handle(frameData); + frame.setFrameIndex(frameData["frameIndex"]); + frame.setTween(frameData["tween"]); + timeline.addFrame(frame); + }); + } + return timeline; + }); + }); + + load.registerParser("action", "1.*", parser); + +})(ccs._load, ccs._parser); \ No newline at end of file From de3f38ae0aca3edd9ddc0a00802c4e84e19078d8 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 6 Jan 2015 14:21:50 +0800 Subject: [PATCH 0084/1345] Issue #2563: Add ccs.AlphaFrame --- .../cocostudio/reader/timeline/Frame.js | 85 ++++++++++++------- 1 file changed, 56 insertions(+), 29 deletions(-) diff --git a/extensions/cocostudio/reader/timeline/Frame.js b/extensions/cocostudio/reader/timeline/Frame.js index 8fffc07af4..8b39c62ca6 100644 --- a/extensions/cocostudio/reader/timeline/Frame.js +++ b/extensions/cocostudio/reader/timeline/Frame.js @@ -239,8 +239,7 @@ ccs.TextureFrame = ccs.Frame.extend({ */ onEnter: function(nextFrame){ if(this._sprite){ - var spriteFrame = cc.spriteFrameCache.getSpriteFrame(this._textureName); - + var spriteFrame = cc.spriteFrameCache._spriteFrames[this._textureName]; if(spriteFrame != null) this._sprite.setSpriteFrame(spriteFrame); else @@ -952,22 +951,16 @@ ccs.ColorFrame = ccs.Frame.extend({ ctor: function(){ ccs.Frame.prototype.ctor.call(this); - - this._alpha = 255; - this.color = cc.color(255, 255, 255); + this._color = cc.color(255, 255, 255); }, /** * the execution of the callback - * @param {ccs.Frame} nextFrame + * @param {ccs.ColorFrame} nextFrame */ onEnter: function(nextFrame){ - this._node.setOpacity(this._alpha); this._node.setColor(this._color); - if(this._tween){ - this._betweenAlpha = nextFrame._alpha - this._alpha; - var color = nextFrame._color; this._betweenRed = color.r - this._color.r; this._betweenGreen = color.g - this._color.g; @@ -1001,30 +994,11 @@ ccs.ColorFrame = ccs.Frame.extend({ */ clone: function(){ var frame = new ccs.ColorFrame(); - frame.setAlpha(this._alpha); frame.setColor(this._color); - frame._cloneProperty(this); - return frame; }, - /** - * Set the alpha - * @param {Number} alpha - */ - setAlpha: function(alpha){ - this._alpha = alpha; - }, - - /** - * Gets the alpha - * @returns {Number} - */ - getAlpha: function(){ - return this._alpha; - }, - /** * Set the color * @param {cc.color} color @@ -1053,6 +1027,59 @@ ccs.ColorFrame.create = function(){ return new ccs.ColorFrame(); }; +/** + * Alpha frame + * @class + * @extend ccs.Frame + */ +ccs.AlphaFrame = ccs.Frame.extend({ + + _alpha: null, + _betweenAlpha: null, + + ctor: function(){ + ccs.Frame.prototype.ctor.call(this); + this._alpha = 255; + }, + + onEnter: function(nextFrame){ + this._node.setOpacity(this._alpha); + if(this._tween){ + this._betweenAlpha = nextFrame._alpha - this._alpha; + } + }, + + apply: function(percent){ + if (this._tween){ + var alpha = this._alpha + this._betweenAlpha * percent; + this._node.setOpacity(alpha); + } + }, + + /** + * Set the alpha + * @param {Number} alpha + */ + setAlpha: function(alpha){ + this._alpha = alpha; + }, + + /** + * Gets the alpha + * @returns {Number} + */ + getAlpha: function(){ + return this._alpha; + }, + + clone: function(){ + var frame = new ccs.AlphaFrame(); + frame.setAlpha(this._alpha); + frame._cloneProperty(this); + return frame; + } +}); + /** * Event frame * @class From 3e7f8197ffc487c89abf33a1a0f0f0f19b4c83ed Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 6 Jan 2015 14:23:12 +0800 Subject: [PATCH 0085/1345] Issue #2563: Add ccs.load function --- extensions/cocostudio/loader/load.js | 35 +++++++++++-------- .../reader/timeline/ActionTimelineCache.js | 2 +- moduleConfig.json | 1 + 3 files changed, 23 insertions(+), 15 deletions(-) diff --git a/extensions/cocostudio/loader/load.js b/extensions/cocostudio/loader/load.js index dbda4dffe7..876772e69d 100644 --- a/extensions/cocostudio/loader/load.js +++ b/extensions/cocostudio/loader/load.js @@ -16,8 +16,6 @@ ccs._load = (function(){ if(ext !== "json" && ext !== "exportjson") return cc.log("%s load error, must be json file", file); - // Judging the parser (uiParse or timelineParse, Temporarily blank) - // The judgment condition is unknown var parse; if(!type){ if(json["widgetTree"]) @@ -88,17 +86,6 @@ ccs._load = (function(){ })(); -//cc.loader.register(["json", "ExportJson"], { -// load: function(realUrl, url, res, cb){ -// var cloader = cc.loader; -// if(cloader.cache[url]){ -// console.log(url) -// }else{ -// return cc.loader.loadJson(realUrl, cb); -// } -// } -//}); - ccs._parser = cc.Class.extend({ ctor: function(){ @@ -135,7 +122,7 @@ ccs._parser = cc.Class.extend({ var parser = this.parsers[this.getClass(json)]; var widget = null; if(parser) - widget = parser.call(this, json, this.parseNode, resourcePath); + widget = parser.call(this, json, resourcePath); else cc.log("Can't find the parser : %s", this.getClass(json)); @@ -146,3 +133,23 @@ ccs._parser = cc.Class.extend({ 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.* + * @param {String} file + * @returns {{node: cc.Node, action: cc.Action}} + */ +ccs.load = function(file){ + var object = { + node: null, + action: null + }; + object.node = ccs._load(file); + object.action = ccs._load(file, "action"); + return object; +}; \ No newline at end of file diff --git a/extensions/cocostudio/reader/timeline/ActionTimelineCache.js b/extensions/cocostudio/reader/timeline/ActionTimelineCache.js index 95c4a5d07f..76b5fa0ee0 100644 --- a/extensions/cocostudio/reader/timeline/ActionTimelineCache.js +++ b/extensions/cocostudio/reader/timeline/ActionTimelineCache.js @@ -291,7 +291,7 @@ ccs.actionTimelineCache = { var anchorx = json[ccui.actionTimelineCacheStatic.X]; var anchory = json[ccui.actionTimelineCacheStatic.Y]; - frame.setAnchorPoint(Point(anchorx, anchory)); + frame.setAnchorPoint(cc.p(anchorx, anchory)); return frame; }, diff --git a/moduleConfig.json b/moduleConfig.json index 2f3df9fca6..af0f419530 100644 --- a/moduleConfig.json +++ b/moduleConfig.json @@ -400,6 +400,7 @@ "extensions/cocostudio/loader/load.js", "extensions/cocostudio/loader/parsers/uiParser-1.x.js", + "extensions/cocostudio/loader/parsers/action-1.x.js", "extensions/cocostudio/loader/parsers/action-2.x.js", "extensions/cocostudio/loader/parsers/timelineParser-1.x.js", "extensions/cocostudio/loader/parsers/timelineParser-2.x.js" From f69ff3151ed15a504c38e4eaafd3a473e171895d Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 6 Jan 2015 14:23:33 +0800 Subject: [PATCH 0086/1345] Issue #2563: support timeline(action) 2.0.0.0 --- .../cocostudio/loader/parsers/action-2.x.js | 184 +++++++++++++++++- 1 file changed, 179 insertions(+), 5 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/action-2.x.js b/extensions/cocostudio/loader/parsers/action-2.x.js index 765cdfe171..8c15026208 100644 --- a/extensions/cocostudio/loader/parsers/action-2.x.js +++ b/extensions/cocostudio/loader/parsers/action-2.x.js @@ -1,5 +1,7 @@ (function(load, baseParser){ + var cache = {}; + var Parser = baseParser.extend({ getNodeJson: function(json){ @@ -7,21 +9,193 @@ }, parseNode: function(json, resourcePath, file){ - var self = this; + if(cache[file]) + return cache[file].clone(); + + var self = this, + action = new ccs.ActionTimeline(); + + action.setDuration(json["Duration"]); + action.setTimeSpeed(json["Speed"] || 1); //The process of analysis var timelines = json["Timelines"]; timelines.forEach(function(timeline){ - var parser = self.parsers[timeline["FrameType"]]; - parser.call(self, timeline, resourcePath); + var parser = self.parsers[timeline["Property"]]; + var frame; + if(parser) + frame = parser.call(self, timeline, resourcePath); + else + cc.log("parser is not exists : %s", timeline["Property"]); + if(frame) + action.addTimeline(frame); }); - return new cc.Action(); + + cache[file] = action; + + return action.clone(); } }); var parser = new Parser(); - parser.registerParser("RotationSkewFrame", function(options, resourcePath){ + var frameList = [ + { + name: "Position", + handle: function(options){ + var frame = new ccs.PositionFrame(); + var x = options["X"]; + var y = options["Y"]; + frame.setPosition(cc.p(x,y)); + return frame; + } + }, + { + name: "VisibleForFrame", + handle: function(options){ + var frame = new ccs.VisibleFrame(); + var visible = options["Value"]; + frame.setVisible(visible); + return frame; + } + }, + { + name: "Scale", + handle: function(options){ + var frame = new ccs.ScaleFrame(); + var scalex = options["X"]; + var scaley = options["Y"]; + frame.setScaleX(scalex); + frame.setScaleY(scaley); + return frame; + } + }, + { + name: "Rotation", + handle: function(options){ + var frame = new ccs.RotationFrame(); + var rotation = options["Rotation"]; + frame.setRotation(rotation); + return frame; + } + }, + { + name: "Skew", + handle: function(options){ + var frame = new ccs.SkewFrame(); + var skewx = options["X"]; + var skewy = options["Y"]; + frame.setSkewX(skewx); + frame.setSkewY(skewy); + return frame; + } + }, + { + name: "RotationSkew", + handle: function(options){ + var frame = new ccs.RotationSkewFrame(); + var skewx = options["X"]; + var skewy = options["Y"]; + frame.setSkewX(skewx); + frame.setSkewY(skewy); + return frame; + } + }, + { + name: "Anchor", + handle: function(options){ + var frame = new ccs.AnchorPointFrame(); + var anchorx = options["X"]; + var anchory = options["Y"]; + frame.setAnchorPoint(cc.p(anchorx, anchory)); + return frame; + } + }, + { + name: "InnerAction", + handle: function(options){ + var frame = new ccs.InnerActionFrame(); + var type = options["InnerActionType"]; + var startFrame = options["StartFrame"]; + frame.setInnerActionType(type); + frame.setStartFrameIndex(startFrame); + return frame; + } + }, + { + name: "CColor", + handle: function(options){ + var frame = new ccs.ColorFrame(); + var color = options["Color"]; + if(!color) color = {}; + color["R"] = color["R"] || 255; + color["G"] = color["G"] || 255; + color["B"] = color["B"] || 255; + frame.setColor(cc.color(color["R"], color["G"], color["B"])); + return frame; + } + }, + { + name: "Alpha", + handle: function(options){ + var frame = new ccs.AlphaFrame(); + var alpha = options["Value"]; + frame.setAlpha(alpha); + return frame; + } + }, + { + name: "FileData", + handle: function(options, resourcePath){ + var frame = new ccs.TextureFrame(); + var texture = options["TextureFile"]; + if(texture != null) { + var path = texture["Path"]; + var spriteFrame = cc.spriteFrameCache._spriteFrames[path]; + if(spriteFrame == null){ + path = resourcePath + path; + } + frame.setTextureName(path); + } + return frame; + } + }, + { + name: "FrameEvent", + handle: function(options){ + var frame = new ccs.EventFrame(); + var evnt = options["Value"]; + if(evnt != null) + frame.setEvent(evnt); + return frame; + } + }, + { + name: "ZOrder", + handle: function(options){ + var frame = new ccs.ZOrderFrame(); + var zorder = options["Value"]; + frame.setZOrder(zorder); + return frame; + } + } + ]; + + frameList.forEach(function(item){ + parser.registerParser(item.name, function(options, resourcePath){ + var timeline = new ccs.Timeline(); + timeline.setActionTag(options["ActionTag"]); + var frames = options["Frames"]; + if(frames && frames.length){ + frames.forEach(function(frameData){ + var frame = item.handle(frameData, resourcePath); + frame.setFrameIndex(frameData["FrameIndex"]); + frame.setTween(frameData["Tween"]); + timeline.addFrame(frame); + }); + } + return timeline; + }); }); load.registerParser("action", "2.*", parser); From 5bb079f264c6ec3fd1397e380f4b233c25c37a0d Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 6 Jan 2015 14:24:49 +0800 Subject: [PATCH 0087/1345] Issue #2563: repair some of the problem that is parser error --- .../loader/parsers/timelineParser-1.x.js | 29 +++++++++++++------ .../loader/parsers/timelineParser-2.x.js | 2 +- .../cocostudio/loader/parsers/uiParser-1.x.js | 2 +- 3 files changed, 22 insertions(+), 11 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-1.x.js b/extensions/cocostudio/loader/parsers/timelineParser-1.x.js index 8cf3976b37..6c5de0792c 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-1.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-1.x.js @@ -1,24 +1,31 @@ (function(load, baseParser){ + var loadedPlist = {}; + var Parser = baseParser.extend({ getNodeJson: function(json){ return json["nodeTree"]; }, - addSpriteFrame: function(textures, plists, resourcePath){ - if(!textures) return; - for (var i = 0; i < textures.length; i++) { + 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 pre load", plist); + else + loadedPlist[plist] = true; cc.spriteFrameCache.addSpriteFrames( - resourcePath + textures[i], - resourcePath + plists[i] + plist, + resourcePath + pngs[i] ); } }, pretreatment: function(json, resourcePath, file){ this.addSpriteFrame(json["textures"], json["texturesPng"], resourcePath); - ccs.actionTimelineCache.loadAnimationActionWithContent(file, json); } }); @@ -196,7 +203,13 @@ }; var uiParser = load.getParser("ccui")["1.*"]; parser.initWidget = function(options, resourcePath){ - var node = uiParser.parseNode.call(this, 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"]; @@ -249,8 +262,6 @@ }); }); - load.registerParser("timeline", "1.*", parser); - })(ccs._load, ccs._parser); \ No newline at end of file diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 507de25e2d..323e1ecd2a 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -485,7 +485,7 @@ var fontResourcePath, fontResourceResourceType, fontResourcePlistFile; var fontResource = json["FontResource"]; if(fontResource != null){ - console.log(fontResource["Path"]) + //console.log(fontResource["Path"]); // fontResourcePath = fontResource["Path"]; // fontResourceResourceType = fontResource["Type"] == "Default" ? 0 : 1; // fontResourcePlistFile = fontResource["Plist"]; diff --git a/extensions/cocostudio/loader/parsers/uiParser-1.x.js b/extensions/cocostudio/loader/parsers/uiParser-1.x.js index ef3a5b1e03..1e85e82354 100644 --- a/extensions/cocostudio/loader/parsers/uiParser-1.x.js +++ b/extensions/cocostudio/loader/parsers/uiParser-1.x.js @@ -782,7 +782,7 @@ ]; register.forEach(function(item){ - parser.registerParser(item.name, function(options, parse, resourcePath){ + parser.registerParser(item.name, function(options, resourcePath){ var widget = new item.object; var uiOptions = options["options"]; parser.generalAttributes(widget, uiOptions); From 5355540289719b5c6f860783ea9aaf5424fca6eb Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 6 Jan 2015 16:31:58 +0800 Subject: [PATCH 0088/1345] Need to set the design resolution --- extensions/cocostudio/reader/GUIReader.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/extensions/cocostudio/reader/GUIReader.js b/extensions/cocostudio/reader/GUIReader.js index a5ecb04772..ed96f8959b 100644 --- a/extensions/cocostudio/reader/GUIReader.js +++ b/extensions/cocostudio/reader/GUIReader.js @@ -1030,8 +1030,7 @@ ccs.WidgetPropertiesReader0300 = ccs.WidgetPropertiesReader.extend(/** @lends cc var widget = this.widgetFromJsonDictionary(widgetTree); var size = widget.getContentSize(); - if (size.width == 0 && size.height == 0) - widget.setSize(cc.size(fileDesignWidth, fileDesignHeight)); + widget.setSize(cc.size(fileDesignWidth, fileDesignHeight)); var actions = jsonDict["animation"]; ccs.actionManager.initWithDictionary(fileName, actions, widget); From 205ec78006dd9c13aa94c56a455a44785a6e8364 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 6 Jan 2015 16:35:50 +0800 Subject: [PATCH 0089/1345] Issue #2563: prevent accidental interruption --- extensions/cocostudio/loader/load.js | 10 +- .../cocostudio/loader/parsers/action-1.x.js | 2 + .../cocostudio/loader/parsers/action-2.x.js | 2 + .../loader/parsers/timelineParser-2.x.js | 2 +- .../cocostudio/loader/parsers/uiParser-1.x.js | 299 +++++------------- 5 files changed, 93 insertions(+), 222 deletions(-) diff --git a/extensions/cocostudio/loader/load.js b/extensions/cocostudio/loader/load.js index 876772e69d..359f9b568b 100644 --- a/extensions/cocostudio/loader/load.js +++ b/extensions/cocostudio/loader/load.js @@ -110,7 +110,7 @@ ccs._parser = cc.Class.extend({ var resourcePath = this._dirname(file); this.pretreatment(json, resourcePath); var node = this.parseNode(this.getNodeJson(json), resourcePath); - this.deferred(json, resourcePath, node, file); + node && this.deferred(json, resourcePath, node, file); return node; }, @@ -149,7 +149,11 @@ ccs.load = function(file){ node: null, action: null }; - object.node = ccs._load(file); - object.action = ccs._load(file, "action"); + try{ + object.node = ccs._load(file); + object.action = ccs._load(file, "action"); + }catch(error){ + cc.log("ccs.load has encountered some problems"); + } return object; }; \ No newline at end of file diff --git a/extensions/cocostudio/loader/parsers/action-1.x.js b/extensions/cocostudio/loader/parsers/action-1.x.js index 135e83f4a5..8f05c137fd 100644 --- a/extensions/cocostudio/loader/parsers/action-1.x.js +++ b/extensions/cocostudio/loader/parsers/action-1.x.js @@ -9,6 +9,8 @@ }, parseNode: function(json, resourcePath, file){ + if(!json) + return null; if(cache[file]) return cache[file].clone(); diff --git a/extensions/cocostudio/loader/parsers/action-2.x.js b/extensions/cocostudio/loader/parsers/action-2.x.js index 8c15026208..25d2f10d88 100644 --- a/extensions/cocostudio/loader/parsers/action-2.x.js +++ b/extensions/cocostudio/loader/parsers/action-2.x.js @@ -9,6 +9,8 @@ }, parseNode: function(json, resourcePath, file){ + if(!json) + return null; if(cache[file]) return cache[file].clone(); diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 323e1ecd2a..60b9e16103 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -1120,7 +1120,7 @@ ]; register.forEach(function(item){ - parser.registerParser(item.name, function(options, parse, resourcePath){ + 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); diff --git a/extensions/cocostudio/loader/parsers/uiParser-1.x.js b/extensions/cocostudio/loader/parsers/uiParser-1.x.js index 1e85e82354..83de06d419 100644 --- a/extensions/cocostudio/loader/parsers/uiParser-1.x.js +++ b/extensions/cocostudio/loader/parsers/uiParser-1.x.js @@ -143,7 +143,7 @@ widget.setAnchorPoint(cc.p(anchorPointXInFile, anchorPointYInFile)); }; - parser.parseChild = function(parse, widget, options, resourcePath){ + 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); @@ -170,6 +170,15 @@ } }; + var getPath = function(res, type, path, cb){ + if(path){ + if(type == 0) + cb(res + path, type); + else + cb(path, type); + } + }; + /** * Panel parser (UILayout) */ @@ -217,33 +226,12 @@ var imageFileNameDic = options["backGroundImageData"]; if(imageFileNameDic){ - var imageFileName, - imageFileNameType = imageFileNameDic["resourceType"]; - switch (imageFileNameType) - { - case 0: - { - var tp_b = resourcePath; - imageFileName = imageFileNameDic["path"]; - var imageFileName_tp = (imageFileName && (imageFileName !== "")) ? - tp_b + imageFileName : - null; - widget.setBackGroundImage(imageFileName_tp); - break; - } - case 1: - { - imageFileName = imageFileNameDic["path"]; - widget.setBackGroundImage(imageFileName, 1/*ui.UI_TEX_TYPE_PLIST*/); - break; - } - default: - break; - } + getPath(resourcePath, imageFileNameDic["resourceType"], imageFileNameDic["path"], function(path, type){ + widget.setBackGroundImage(path, type); + }); } - if (backGroundScale9Enable) - { + if (backGroundScale9Enable){ var cx = options["capInsetsX"]; var cy = options["capInsetsY"]; var cw = options["capInsetsWidth"]; @@ -260,60 +248,18 @@ var scale9Enable = options["scale9Enable"]; button.setScale9Enabled(scale9Enable); - var normalFileName, - normalDic = options["normalData"], - normalType = normalDic["resourceType"]; - switch (normalType) { - case 0: - var tp_n = resourcePath; - normalFileName = normalDic["path"]; - var normalFileName_tp = (normalFileName && normalFileName !== "") ? - tp_n + normalFileName : null; - button.loadTextureNormal(normalFileName_tp); - break; - case 1: - normalFileName = normalDic["path"]; - button.loadTextureNormal(normalFileName, 1/*ui.UI_TEX_TYPE_PLIST*/); - break; - default: - break; - } - var pressedFileName, - pressedDic = options["pressedData"], - pressedType = pressedDic["resourceType"]; - switch (pressedType) { - case 0: - var tp_p = resourcePath; - pressedFileName = pressedDic["path"]; - var pressedFileName_tp = (pressedFileName && pressedFileName !== "") ? - tp_p + pressedFileName : null; - button.loadTexturePressed(pressedFileName_tp); - break; - case 1: - pressedFileName = pressedDic["path"]; - button.loadTexturePressed(pressedFileName, 1/*ui.UI_TEX_TYPE_PLIST*/); - break; - default: - break; - } - var disabledFileName, - disabledDic = options["disabledData"], - disabledType = disabledDic["resourceType"]; - switch (disabledType){ - case 0: - var tp_d = resourcePath; - disabledFileName = disabledDic["path"]; - var disabledFileName_tp = (disabledFileName && disabledFileName !== "") ? - tp_d + disabledFileName : null; - button.loadTextureDisabled(disabledFileName_tp); - break; - case 1: - disabledFileName = disabledDic["path"]; - button.loadTextureDisabled(disabledFileName, 1/*ui.UI_TEX_TYPE_PLIST*/); - break; - default: - break; - } + 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"]; @@ -351,41 +297,41 @@ parser.CheckBoxAttributes = function(widget, options, resourcePath){ //load background image var backGroundDic = options["backGroundBoxData"]; - var backGroundType = backGroundDic["resourceType"]; - var backGroundTexturePath = resourcePath + backGroundDic["path"]; - widget.loadTextureBackGround(backGroundTexturePath, backGroundType); + getPath(resourcePath, backGroundDic["resourceType"], backGroundDic["path"], function(path, type){ + widget.loadTextureBackGround(path, type); + }); //load background selected image var backGroundSelectedDic = options["backGroundBoxSelectedData"]; - var backGroundSelectedType = backGroundSelectedDic["resourceType"]; - var backGroundSelectedTexturePath = resourcePath + backGroundSelectedDic["path"]; - if(!backGroundSelectedTexturePath){ - backGroundSelectedType = backGroundType; - backGroundSelectedTexturePath = backGroundTexturePath; - } - widget.loadTextureBackGroundSelected(backGroundSelectedTexturePath, backGroundSelectedType); + getPath( + resourcePath, + backGroundSelectedDic["resourceType"] || backGroundDic["resourceType"], + backGroundSelectedDic["path"] || backGroundDic["path"], + function(path, type){ + widget.loadTextureBackGroundSelected(path, type); + }); //load frontCross image var frontCrossDic = options["frontCrossData"]; - var frontCrossType = frontCrossDic["resourceType"]; - var frontCrossFileName = resourcePath + frontCrossDic["path"]; - widget.loadTextureFrontCross(frontCrossFileName, frontCrossType); + getPath(resourcePath, frontCrossDic["resourceType"], frontCrossDic["path"], function(path, type){ + widget.loadTextureFrontCross(path, type); + }); //load backGroundBoxDisabledData var backGroundDisabledDic = options["backGroundBoxDisabledData"]; - var backGroundDisabledType = backGroundDisabledDic["resourceType"]; - var backGroundDisabledFileName = resourcePath + backGroundDisabledDic["path"]; - if(!backGroundDisabledFileName){ - backGroundDisabledType = frontCrossType; - backGroundDisabledFileName = frontCrossFileName; - } - widget.loadTextureBackGroundDisabled(backGroundDisabledFileName, backGroundDisabledType); + getPath( + resourcePath, + backGroundDisabledDic["resourceType"] || frontCrossDic["resourceType"], + backGroundDisabledDic["path"] || frontCrossDic["path"], + function(path, type){ + widget.loadTextureBackGroundDisabled(path, type); + }); ///load frontCrossDisabledData var frontCrossDisabledDic = options["frontCrossDisabledData"]; - var frontCrossDisabledType = frontCrossDisabledDic["resourceType"]; - var frontCrossDisabledFileName = resourcePath + frontCrossDisabledDic["path"]; - widget.loadTextureFrontCrossDisabled(frontCrossDisabledFileName, frontCrossDisabledType); + getPath(resourcePath, frontCrossDisabledDic["resourceType"], frontCrossDisabledDic["path"], function(path, type){ + widget.loadTextureFrontCrossDisabled(path, type); + }); if (options["selectedState"]) widget.setSelected(options["selectedState"]); @@ -537,27 +483,11 @@ /** * LoadingBar parser (UILoadingBar) */ - parser.LoadingBarAttributes = function(widget, options, resoutcePath){ - var imageFileName, - imageFileNameDic = options["textureData"], - imageFileNameType = imageFileNameDic["resourceType"]; - switch (imageFileNameType){ - case 0: - var tp_i = resoutcePath; - imageFileName = imageFileNameDic["path"]; - var imageFileName_tp = null; - if (imageFileName && (imageFileName !== "")){ - imageFileName_tp = tp_i + imageFileName; - widget.loadTexture(imageFileName_tp); - } - break; - case 1: - imageFileName = imageFileNameDic["path"]; - widget.loadTexture(imageFileName, 1/*ui.UI_TEX_TYPE_PLIST*/); - break; - default: - break; - } + 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); @@ -598,10 +528,9 @@ /** * Slider parser (UISlider) */ - parser.SliderAttributes = function(widget, options, resoutcePath){ + parser.SliderAttributes = function(widget, options, resourcePath){ var slider = widget; - var tp = resoutcePath; var barTextureScale9Enable = options["scale9Enable"]; slider.setScale9Enabled(barTextureScale9Enable); @@ -611,109 +540,43 @@ var imageFileNameDic = options["barFileNameData"]; var imageFileType = imageFileNameDic["resourceType"]; var imageFileName = imageFileNameDic["path"]; - var imageFileName_tp; if(bt != null){ if(barTextureScale9Enable){ - switch(imageFileType){ - case 0: - imageFileName_tp = imageFileName ? - ( tp + imageFileName ) : - null; - slider.loadBarTexture(imageFileName_tp); - break; - case 1: - slider.loadBarTexture(imageFileName, 1 /*ui.UI_TEX_TYPE_PLIST*/); - break; - default: - break; - } + getPath(resourcePath, imageFileType, imageFileName, function(path, type){ + slider.loadBarTexture(path, type); + }); slider.setSize(cc.size(barLength, slider.getContentSize().height)); } }else{ - switch(imageFileType){ - case 0: - imageFileName_tp = imageFileName ? - tp + imageFileName : - null; - slider.loadBarTexture(imageFileName_tp); - break; - case 1: - slider.loadBarTexture(imageFileName, 1 /*ui.UI_TEX_TYPE_PLIST*/); - break; - default: - break; - } + getPath(resourcePath, imageFileType, imageFileName, function(path, type){ + slider.loadBarTexture(path, type); + }); } + var normalDic = options["ballNormalData"]; - var normalType = normalDic["resourceType"]; - var normalFileName = normalDic["path"]; - switch(normalType){ - case 0: - var normalFileName_tp = normalFileName ? - tp + normalFileName : - null; - slider.loadSlidBallTextureNormal(normalFileName_tp); - break; - case 1: - slider.loadSlidBallTextureNormal(normalFileName, 1/*ui.UI_TEX_TYPE_PLIST*/); - break; - default: - break; - } + getPath(resourcePath, normalDic["resourceType"], normalDic["path"], function(path, type){ + slider.loadSlidBallTextureNormal(path, type); + }); var pressedDic = options["ballPressedData"]; - var pressedType = pressedDic["resourceType"]; - var pressedFileName = pressedDic["path"]; - if(pressedFileName === null){ - pressedType = normalType; - pressedFileName = normalFileName; - } - switch(pressedType){ - case 0: - var pressedFileName_tp = pressedFileName ? - tp + pressedFileName : - null; - slider.loadSlidBallTexturePressed(pressedFileName_tp); - break; - case 1: - slider.loadSlidBallTexturePressed(pressedFileName, 1/*ui.UI_TEX_TYPE_PLIST*/); - break; - default: - break; - } + getPath( + resourcePath, + pressedDic["resourceType"] || normalDic["resourceType"], + pressedDic["path"] || normalDic["path"], + function(path, type){ + slider.loadSlidBallTexturePressed(path, type); + }); + var disabledDic = options["ballDisabledData"]; - var disabledType = disabledDic["resourceType"]; - var disabledFileName = disabledDic["path"]; - switch(disabledType){ - case 0: - var disabledFileName_tp = disabledFileName ? - tp + disabledFileName : - null; - slider.loadSlidBallTextureDisabled(disabledFileName_tp); - break; - case 1: - slider.loadSlidBallTextureDisabled(disabledFileName, 1/*ui.UI_TEX_TYPE_PLIST*/); - break; - default: - break; - } + getPath(resourcePath, disabledDic["resourceType"], disabledDic["path"], function(path, type){ + slider.loadSlidBallTextureDisabled(path, type); + }); + var progressBarDic = options["progressBarData"]; - var progressBarType = progressBarDic["resourceType"]; - var imageProgressFileName = progressBarDic["path"]; - switch (progressBarType){ - case 0: - var imageProgressFileName_tp = imageProgressFileName ? - (tp + imageProgressFileName) : - null; - slider.loadProgressBarTexture(imageProgressFileName_tp); - break; - case 1: - slider.loadProgressBarTexture(imageProgressFileName, 1/*ui.UI_TEX_TYPE_PLIST*/); - break; - default: - break; - } + getPath(resourcePath, progressBarDic["resourceType"], progressBarDic["path"], function(path, type){ + slider.loadProgressBarTexture(path, type); + }); }; /** * TextField parser (UITextField) @@ -789,7 +652,7 @@ item.handle(widget, uiOptions, resourcePath); parser.colorAttributes(widget, uiOptions); parser.anchorPointAttributes(widget, uiOptions); - parser.parseChild.call(this, parse, widget, options, resourcePath); + parser.parseChild.call(this, widget, options, resourcePath); return widget; }); }); From 27644f938ee3704aa2d39ee3f6e017cc155ac256 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 7 Jan 2015 14:16:29 +0800 Subject: [PATCH 0090/1345] Issue #2563: Timeline does not belong to reader --- extensions/cocostudio/{reader => }/timeline/ActionTimeline.js | 0 extensions/cocostudio/{reader => }/timeline/Frame.js | 0 extensions/cocostudio/{reader => }/timeline/Timeline.js | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename extensions/cocostudio/{reader => }/timeline/ActionTimeline.js (100%) rename extensions/cocostudio/{reader => }/timeline/Frame.js (100%) rename extensions/cocostudio/{reader => }/timeline/Timeline.js (100%) diff --git a/extensions/cocostudio/reader/timeline/ActionTimeline.js b/extensions/cocostudio/timeline/ActionTimeline.js similarity index 100% rename from extensions/cocostudio/reader/timeline/ActionTimeline.js rename to extensions/cocostudio/timeline/ActionTimeline.js diff --git a/extensions/cocostudio/reader/timeline/Frame.js b/extensions/cocostudio/timeline/Frame.js similarity index 100% rename from extensions/cocostudio/reader/timeline/Frame.js rename to extensions/cocostudio/timeline/Frame.js diff --git a/extensions/cocostudio/reader/timeline/Timeline.js b/extensions/cocostudio/timeline/Timeline.js similarity index 100% rename from extensions/cocostudio/reader/timeline/Timeline.js rename to extensions/cocostudio/timeline/Timeline.js From b44eefb1c63dd496b93adcbebc59fcfaab057099 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 7 Jan 2015 14:18:14 +0800 Subject: [PATCH 0091/1345] Issue #2563: Add a scene analysis --- extensions/cocostudio/loader/load.js | 58 +++- .../cocostudio/loader/parsers/compatible.js | 243 +++++++++++++++++ .../cocostudio/loader/parsers/scene-1.x.js | 256 ++++++++++++++++++ 3 files changed, 556 insertions(+), 1 deletion(-) create mode 100644 extensions/cocostudio/loader/parsers/compatible.js create mode 100644 extensions/cocostudio/loader/parsers/scene-1.x.js diff --git a/extensions/cocostudio/loader/load.js b/extensions/cocostudio/loader/load.js index 359f9b568b..d1a09cbcb2 100644 --- a/extensions/cocostudio/loader/load.js +++ b/extensions/cocostudio/loader/load.js @@ -1,3 +1,27 @@ +/**************************************************************************** + 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(){ /** @@ -24,6 +48,8 @@ ccs._load = (function(){ parse = parser["timeline"]; else if(json["Content"] && json["Content"]["Content"]) parse = parser["timeline"]; + else if(json["gameobjects"] && json["Triggers"]) + parse = parser["scene"]; }else{ parse = parser[type]; } @@ -45,7 +71,8 @@ ccs._load = (function(){ var parser = { "ccui": {}, "timeline": {}, - "action": {} + "action": {}, + "scene": {} }; load.registerParser = function(name, version, target){ @@ -156,4 +183,33 @@ ccs.load = function(file){ cc.log("ccs.load has encountered some problems"); } 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); + } }; \ No newline at end of file diff --git a/extensions/cocostudio/loader/parsers/compatible.js b/extensions/cocostudio/loader/parsers/compatible.js new file mode 100644 index 0000000000..4a91c56ab0 --- /dev/null +++ b/extensions/cocostudio/loader/parsers/compatible.js @@ -0,0 +1,243 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + + +/* + This file is for compatibility compatibility with older versions of GUIReader and SceneReader + */ + +(function(){ + + ccs.uiReader = { + + _fileDesignSizes: {}, + + //@deprecated This function will be deprecated sooner or later please use ccs.load + /** + * Create CCUI Node + * @param file + * @returns {*} + */ + widgetFromJsonFile: function(file){ + var json = cc.loader.getRes(file); + if(json) + this._fileDesignSizes[file] = cc.size(json["designWidth"]||0, json["designHeight"]||0); + 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..8e01342094 --- /dev/null +++ b/extensions/cocostudio/loader/parsers/scene-1.x.js @@ -0,0 +1,256 @@ +/**************************************************************************** + 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; + }, + + setPropertyFromJsonDict: function(node, json){ + var x = (cc.isUndefined(json["x"]))?0:json["x"]; + var y = (cc.isUndefined(json["y"]))?0:json["y"]; + node.setPosition(x, y); + + var bVisible = Boolean((cc.isUndefined(json["visible"]))?1:json["visible"]); + node.setVisible(bVisible); + + var nTag = (cc.isUndefined(json["objecttag"]))?-1:json["objecttag"]; + node.setTag(nTag); + + var nZorder = (cc.isUndefined(json["zorder"]))?0:json["zorder"]; + node.setLocalZOrder(nZorder); + + var fScaleX = (cc.isUndefined(json["scalex"]))?1:json["scalex"]; + var fScaleY = (cc.isUndefined(json["scaley"]))?1:json["scaley"]; + node.setScaleX(fScaleX); + node.setScaleY(fScaleY); + + var fRotationZ = (cc.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 pre load", 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); \ No newline at end of file From 4a348c05f6565e02386b718f9736fd6c465dc003 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 7 Jan 2015 14:19:04 +0800 Subject: [PATCH 0092/1345] Issue #2563: Check the file dependence, remove excess file --- .../cocostudio/loader/parsers/action-1.x.js | 26 ++++++- .../cocostudio/loader/parsers/action-2.x.js | 24 ++++++ .../loader/parsers/timelineParser-1.x.js | 76 ++++++++++++------- .../loader/parsers/timelineParser-2.x.js | 24 ++++++ .../cocostudio/loader/parsers/uiParser-1.x.js | 51 +++++++------ moduleConfig.json | 32 ++------ 6 files changed, 158 insertions(+), 75 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/action-1.x.js b/extensions/cocostudio/loader/parsers/action-1.x.js index 8f05c137fd..1b02ce6b2e 100644 --- a/extensions/cocostudio/loader/parsers/action-1.x.js +++ b/extensions/cocostudio/loader/parsers/action-1.x.js @@ -1,3 +1,27 @@ +/**************************************************************************** + 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 cache = {}; @@ -209,6 +233,6 @@ }); }); - load.registerParser("action", "1.*", parser); + load.registerParser("action", "*", parser); })(ccs._load, ccs._parser); \ No newline at end of file diff --git a/extensions/cocostudio/loader/parsers/action-2.x.js b/extensions/cocostudio/loader/parsers/action-2.x.js index 25d2f10d88..41b52895b5 100644 --- a/extensions/cocostudio/loader/parsers/action-2.x.js +++ b/extensions/cocostudio/loader/parsers/action-2.x.js @@ -1,3 +1,27 @@ +/**************************************************************************** + 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 cache = {}; diff --git a/extensions/cocostudio/loader/parsers/timelineParser-1.x.js b/extensions/cocostudio/loader/parsers/timelineParser-1.x.js index 6c5de0792c..aadd9323e9 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-1.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-1.x.js @@ -1,3 +1,27 @@ +/**************************************************************************** + 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 = {}; @@ -32,27 +56,27 @@ var parser = new Parser(); parser.generalAttributes = function(node, options){ - var width = options[ccui.CSLoaderStatic.WIDTH] !=null ? options[ccui.CSLoaderStatic.WIDTH] : 0; - var height = options[ccui.CSLoaderStatic.HEIGHT] !=null ? options[ccui.CSLoaderStatic.HEIGHT] : 0; - var x = options[ccui.CSLoaderStatic.X] !=null ? options[ccui.CSLoaderStatic.X] : 0; - var y = options[ccui.CSLoaderStatic.Y] !=null ? options[ccui.CSLoaderStatic.Y] : 0; - var scalex = options[ccui.CSLoaderStatic.SCALE_X] !=null ? options[ccui.CSLoaderStatic.SCALE_X] : 1; - var scaley = options[ccui.CSLoaderStatic.SCALE_Y] !=null ? options[ccui.CSLoaderStatic.SCALE_Y] : 1; - var rotation = options[ccui.CSLoaderStatic.ROTATION] !=null ? options[ccui.CSLoaderStatic.ROTATION] : 0; - var rotationSkewX = options[ccui.CSLoaderStatic.ROTATION_SKEW_X]!=null ? options[ccui.CSLoaderStatic.ROTATION_SKEW_X] : 0; - var rotationSkewY = options[ccui.CSLoaderStatic.ROTATION_SKEW_Y]!=null ? options[ccui.CSLoaderStatic.ROTATION_SKEW_Y] : 0; - var skewx = options[ccui.CSLoaderStatic.SKEW_X] !=null ? options[ccui.CSLoaderStatic.SKEW_X] : 0; - var skewy = options[ccui.CSLoaderStatic.SKEW_Y] !=null ? options[ccui.CSLoaderStatic.SKEW_Y] : 0; - var anchorx = options[ccui.CSLoaderStatic.ANCHOR_X] !=null ? options[ccui.CSLoaderStatic.ANCHOR_X] : 0.5; - var anchory = options[ccui.CSLoaderStatic.ANCHOR_Y] !=null ? options[ccui.CSLoaderStatic.ANCHOR_Y] : 0.5; - var alpha = options[ccui.CSLoaderStatic.ALPHA] !=null ? options[ccui.CSLoaderStatic.ALPHA] : 255; - var red = options[ccui.CSLoaderStatic.RED] !=null ? options[ccui.CSLoaderStatic.RED] : 255; - var green = options[ccui.CSLoaderStatic.GREEN] !=null ? options[ccui.CSLoaderStatic.GREEN] : 255; - var blue = options[ccui.CSLoaderStatic.BLUE] !=null ? options[ccui.CSLoaderStatic.BLUE] : 255; - var zorder = options[ccui.CSLoaderStatic.ZORDER] !=null ? options[ccui.CSLoaderStatic.ZORDER] : 0; - var tag = options[ccui.CSLoaderStatic.TAG] !=null ? options[ccui.CSLoaderStatic.TAG] : 0; - var actionTag = options[ccui.CSLoaderStatic.ACTION_TAG] !=null ? options[ccui.CSLoaderStatic.ACTION_TAG] : 0; - var visible = options[ccui.CSLoaderStatic.VISIBLE] !=null ? options[ccui.CSLoaderStatic.VISIBLE] : true; + 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)); @@ -188,10 +212,10 @@ return particle; }; parser.initTMXTiledMap = function(options, resourcePath){ - var tmxFile = options[ccui.CSLoaderStatic.TMX_FILE]; - var tmxString = options[ccui.CSLoaderStatic.TMX_STRING]; + var tmxFile = options["tmxFile"]; + var tmxString = options["tmxString"]; //todo check path and resourcePath - var path = options[ccui.CSLoaderStatic.RESOURCE_PATH]; + var path = options["resourcePath"]; var tmx = null; if (tmxFile && "" != tmxFile){ @@ -224,7 +248,7 @@ if(skewy != 0) node.setSkewY(skewy); - var actionTag = options[ccui.CSLoaderStatic.ACTION_TAG]; + var actionTag = options["actionTag"]; node.setUserObject(new ccs.ActionTimelineData(actionTag)); } return node; @@ -262,6 +286,6 @@ }); }); - load.registerParser("timeline", "1.*", parser); + load.registerParser("timeline", "*", parser); })(ccs._load, ccs._parser); \ No newline at end of file diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 60b9e16103..d98a52a06b 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -1,3 +1,27 @@ +/**************************************************************************** + 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; diff --git a/extensions/cocostudio/loader/parsers/uiParser-1.x.js b/extensions/cocostudio/loader/parsers/uiParser-1.x.js index 83de06d419..a89b01cddc 100644 --- a/extensions/cocostudio/loader/parsers/uiParser-1.x.js +++ b/extensions/cocostudio/loader/parsers/uiParser-1.x.js @@ -1,3 +1,27 @@ +/**************************************************************************** + 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({ @@ -340,26 +364,10 @@ * ImageView parser (UIImageView) */ parser.ImageViewAttributes = function(widget, options, resourcePath){ - var imageFileName, - imageFileNameDic = options["fileNameData"], - imageFileNameType = imageFileNameDic["resourceType"]; - switch (imageFileNameType){ - case 0: - var tp_i = resourcePath; - imageFileName = imageFileNameDic["path"]; - var imageFileName_tp = null; - if (imageFileName && imageFileName !== "") { - imageFileName_tp = tp_i + imageFileName; - widget.loadTexture(imageFileName_tp); - } - break; - case 1: - imageFileName = imageFileNameDic["path"]; - widget.loadTexture(imageFileName, 1/*ui.UI_TEX_TYPE_PLIST*/); - break; - default: - break; - } + var imageFileNameDic = options["fileNameData"] + getPath(resourcePath, imageFileNameDic["resourceType"], imageFileNameDic["path"], function(path, type){ + widget.loadTexture(path, type); + }); var scale9EnableExist = options["scale9Enable"]; var scale9Enable = false; @@ -657,7 +665,6 @@ }); }); - load.registerParser("ccui", "1.*", parser); - + load.registerParser("ccui", "*", parser); })(ccs._load, ccs._parser); \ No newline at end of file diff --git a/moduleConfig.json b/moduleConfig.json index af0f419530..fa4cbaa52e 100644 --- a/moduleConfig.json +++ b/moduleConfig.json @@ -372,38 +372,18 @@ "extensions/cocostudio/trigger/TriggerMng.js", "extensions/cocostudio/trigger/TriggerObj.js", - - "extensions/cocostudio/reader/widgetreader/ButtonReader/ButtonReader.js", - "extensions/cocostudio/reader/widgetreader/CheckBoxReader/CheckBoxReader.js", - "extensions/cocostudio/reader/widgetreader/ImageViewReader/ImageViewReader.js", - "extensions/cocostudio/reader/widgetreader/LabelAtlasReader/LabelAtlasReader.js", - "extensions/cocostudio/reader/widgetreader/LabelBMFontReader/LabelBMFontReader.js", - "extensions/cocostudio/reader/widgetreader/LabelReader/LabelReader.js", - "extensions/cocostudio/reader/widgetreader/LayoutReader/LayoutReader.js", - "extensions/cocostudio/reader/widgetreader/ScrollViewReader/ScrollViewReader.js", - "extensions/cocostudio/reader/widgetreader/ListViewReader/ListViewReader.js", - "extensions/cocostudio/reader/widgetreader/LoadingBarReader/LoadingBarReader.js", - "extensions/cocostudio/reader/widgetreader/PageViewReader/PageViewReader.js", - "extensions/cocostudio/reader/widgetreader/SliderReader/SliderReader.js", - "extensions/cocostudio/reader/widgetreader/TextFieldReader/TextFieldReader.js", - "extensions/cocostudio/reader/widgetreader/WidgetReaderProtocol.js", - "extensions/cocostudio/reader/widgetreader/WidgetReader.js", - - "extensions/cocostudio/reader/GUIReader.js", - "extensions/cocostudio/reader/SceneReader.js", - - "extensions/cocostudio/reader/timeline/ActionTimeline.js", - "extensions/cocostudio/reader/timeline/ActionTimelineCache.js", - "extensions/cocostudio/reader/timeline/Frame.js", - "extensions/cocostudio/reader/timeline/Timeline.js", - "extensions/cocostudio/reader/timeline/CSLoader.js", + "extensions/cocostudio/timeline/ActionTimeline.js", + "extensions/cocostudio/timeline/Frame.js", + "extensions/cocostudio/timeline/Timeline.js", "extensions/cocostudio/loader/load.js", + "extensions/cocostudio/loader/parsers/scene-1.x.js", "extensions/cocostudio/loader/parsers/uiParser-1.x.js", "extensions/cocostudio/loader/parsers/action-1.x.js", "extensions/cocostudio/loader/parsers/action-2.x.js", "extensions/cocostudio/loader/parsers/timelineParser-1.x.js", - "extensions/cocostudio/loader/parsers/timelineParser-2.x.js" + "extensions/cocostudio/loader/parsers/timelineParser-2.x.js", + "extensions/cocostudio/loader/parsers/compatible.js" ], From dd1b0c0bc91e63bf28d8e4db8c2eb17c8f3dd421 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 7 Jan 2015 14:22:43 +0800 Subject: [PATCH 0093/1345] Issue #2563: remove excess file(Is compatible with the old interface - compatible.js) --- extensions/cocostudio/reader/GUIReader.js | 2096 ----------------- extensions/cocostudio/reader/SceneReader.js | 366 --- .../reader/timeline/ActionTimelineCache.js | 909 ------- .../cocostudio/reader/timeline/CSLoader.js | 729 ------ .../widgetreader/ButtonReader/ButtonReader.js | 128 - .../CheckBoxReader/CheckBoxReader.js | 96 - .../ImageViewReader/ImageViewReader.js | 93 - .../LabelAtlasReader/LabelAtlasReader.js | 69 - .../LabelBMFontReader/LabelBMFontReader.js | 65 - .../widgetreader/LabelReader/LabelReader.js | 75 - .../widgetreader/LayoutReader/LayoutReader.js | 122 - .../ListViewReader/ListViewReader.js | 52 - .../LoadingBarReader/LoadingBarReader.js | 87 - .../PageViewReader/PageViewReader.js | 42 - .../ScrollViewReader/ScrollViewReader.js | 52 - .../widgetreader/SliderReader/SliderReader.js | 160 -- .../TextFieldReader/TextFieldReader.js | 89 - .../reader/widgetreader/WidgetReader.js | 226 -- .../widgetreader/WidgetReaderProtocol.js | 30 - 19 files changed, 5486 deletions(-) delete mode 100644 extensions/cocostudio/reader/GUIReader.js delete mode 100644 extensions/cocostudio/reader/SceneReader.js delete mode 100644 extensions/cocostudio/reader/timeline/ActionTimelineCache.js delete mode 100644 extensions/cocostudio/reader/timeline/CSLoader.js delete mode 100644 extensions/cocostudio/reader/widgetreader/ButtonReader/ButtonReader.js delete mode 100644 extensions/cocostudio/reader/widgetreader/CheckBoxReader/CheckBoxReader.js delete mode 100644 extensions/cocostudio/reader/widgetreader/ImageViewReader/ImageViewReader.js delete mode 100644 extensions/cocostudio/reader/widgetreader/LabelAtlasReader/LabelAtlasReader.js delete mode 100644 extensions/cocostudio/reader/widgetreader/LabelBMFontReader/LabelBMFontReader.js delete mode 100644 extensions/cocostudio/reader/widgetreader/LabelReader/LabelReader.js delete mode 100644 extensions/cocostudio/reader/widgetreader/LayoutReader/LayoutReader.js delete mode 100644 extensions/cocostudio/reader/widgetreader/ListViewReader/ListViewReader.js delete mode 100644 extensions/cocostudio/reader/widgetreader/LoadingBarReader/LoadingBarReader.js delete mode 100644 extensions/cocostudio/reader/widgetreader/PageViewReader/PageViewReader.js delete mode 100644 extensions/cocostudio/reader/widgetreader/ScrollViewReader/ScrollViewReader.js delete mode 100644 extensions/cocostudio/reader/widgetreader/SliderReader/SliderReader.js delete mode 100644 extensions/cocostudio/reader/widgetreader/TextFieldReader/TextFieldReader.js delete mode 100644 extensions/cocostudio/reader/widgetreader/WidgetReader.js delete mode 100644 extensions/cocostudio/reader/widgetreader/WidgetReaderProtocol.js diff --git a/extensions/cocostudio/reader/GUIReader.js b/extensions/cocostudio/reader/GUIReader.js deleted file mode 100644 index ed96f8959b..0000000000 --- a/extensions/cocostudio/reader/GUIReader.js +++ /dev/null @@ -1,2096 +0,0 @@ -/**************************************************************************** - 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(){ - var factoryCreate = ccs.objectFactory; - - factoryCreate.registerType({_className:"ButtonReader", _fun: ccs.buttonReader}); - factoryCreate.registerType({_className: "CheckBoxReader", _fun: ccs.checkBoxReader}); - factoryCreate.registerType({_className: "SliderReader", _fun: ccs.sliderReader}); - factoryCreate.registerType({_className: "ImageViewReader", _fun: ccs.imageViewReader}); - factoryCreate.registerType({_className: "LoadingBarReader", _fun: ccs.loadingBarReader}); - factoryCreate.registerType({_className: "TextAtlasReader", _fun: ccs.labelAtlasReader}); - factoryCreate.registerType({_className: "TextReader", _fun: ccs.labelReader}); - factoryCreate.registerType({_className: "TextBMFontReader", _fun: ccs.labelBMFontReader}); - factoryCreate.registerType({_className: "TextFieldReader", _fun: ccs.textFieldReader}); - factoryCreate.registerType({_className: "LayoutReader", _fun: ccs.layoutReader}); - factoryCreate.registerType({_className: "PageViewReader", _fun: ccs.pageViewReader}); - factoryCreate.registerType({_className: "ScrollViewReader", _fun: ccs.scrollViewReader}); - factoryCreate.registerType({_className: "ListViewReader", _fun: ccs.listViewReader}); - factoryCreate.registerType({_className: "WidgetReader", _fun: ccs.widgetReader}); - - factoryCreate.registerType({_className: "Button", _fun: ccui.Button}); - factoryCreate.registerType({_className: "CheckBox", _fun: ccui.CheckBox}); - factoryCreate.registerType({_className: "ImageView", _fun: ccui.ImageView}); - factoryCreate.registerType({_className: "Text", _fun: ccui.Text}); - factoryCreate.registerType({_className: "TextAtlas", _fun: ccui.TextAtlas}); - factoryCreate.registerType({_className: "TextBMFont", _fun: ccui.TextBMFont}); - factoryCreate.registerType({_className: "LoadingBar", _fun: ccui.LoadingBar}); - factoryCreate.registerType({_className: "Slider", _fun: ccui.Slider}); - factoryCreate.registerType({_className: "TextField", _fun: ccui.TextField}); - factoryCreate.registerType({_className: "Layout", _fun: ccui.Layout}); - factoryCreate.registerType({_className: "ListView", _fun: ccui.ListView}); - factoryCreate.registerType({_className: "PageView", _fun: ccui.PageView}); - factoryCreate.registerType({_className: "ScrollView", _fun: ccui.ScrollView}); - -})(); - -/** - * ccs.uiReader is a singleton object which is the reader for Cocos Studio ui. - * @class - * @name ccs.uiReader - */ -ccs.uiReader = /** @lends ccs.uiReader# */{ - _filePath: "", - _olderVersion: false, - _fileDesignSizes: {}, - _mapObject: {}, - _mapParseSelector: {}, - - /** - * Gets the version number by version string. - * @param {String} str version string. - * @returns {Number} - */ - getVersionInteger: function (str) { - if(!str) - return 0; - var strVersion = str; - var versionLength = strVersion.length; - if (versionLength < 7) { - return 0; - } - var pos = strVersion.indexOf("."); - var t = strVersion.substr(0, pos); - strVersion = strVersion.substr(pos + 1, versionLength - 1); - - pos = strVersion.indexOf("."); - var h = strVersion.substr(0, pos); - strVersion = strVersion.substr(pos + 1, versionLength - 1); - - pos = strVersion.indexOf("."); - var te = strVersion.substr(0, pos); - strVersion = strVersion.substr(pos + 1, versionLength - 1); - - pos = strVersion.indexOf("."); - var s = (pos == -1) ? strVersion : strVersion.substr(0, pos); - - var it = parseInt(t); - var ih = parseInt(h); - var ite = parseInt(te); - var is = parseInt(s); - - return (it * 1000 + ih * 100 + ite * 10 + is); - }, - - /** - * stores the designSize of UI file. - * @param {String} fileName - * @param {cc.Size} size - */ - storeFileDesignSize: function (fileName, size) { - this._fileDesignSizes[fileName] = size; - }, - - /** - * Gets the design size by filename. - * @param {String} fileName - * @returns {cc.Size} - */ - getFileDesignSize: function (fileName) { - return this._fileDesignSizes[fileName]; - }, - - /** - * Creates uiWidget from a json file that exported by cocostudio UI editor - * @param {String} fileName - * @returns {ccui.Widget} - */ - widgetFromJsonFile: function (fileName) { - var jsonDict = cc.loader.getRes(fileName); - if(!jsonDict) throw "Please load the resource first : " + fileName; - - var tempFilePath = cc.path.dirname(fileName); - this._filePath = tempFilePath == "" ? tempFilePath : tempFilePath + "/"; - - var fileVersion = jsonDict["version"]; - var pReader, widget; - var versionInteger = this.getVersionInteger(fileVersion); - if (fileVersion) { - if (versionInteger < 250) { - pReader = new ccs.WidgetPropertiesReader0250(); - widget = pReader.createWidget(jsonDict, this._filePath, fileName); - } else { - pReader = new ccs.WidgetPropertiesReader0300(); - widget = pReader.createWidget(jsonDict, this._filePath, fileName); - } - } else { - pReader = new ccs.WidgetPropertiesReader0250(); - widget = pReader.createWidget(jsonDict, this._filePath, fileName); - } - - if (!fileVersion || versionInteger < 250) { - this._olderVersion = true; - } - jsonDict = null; - return widget; - }, - - /** - * Resets the states and clear the file design sizes. - */ - clear: function () { - this._filePath = ""; - this._olderVersion = false; - this._fileDesignSizes = {}; - }, - - /** - * Registers class type and callback. - * @param {String} classType - * @param {ccs.objectFactory} ins - * @param {Object} object - * @param {function} callback - */ - registerTypeAndCallBack: function(classType, ins, object, callback){ - var factoryCreate = ccs.objectFactory; - var t = new ccs.TInfo(classType, ins); - factoryCreate.registerType(t); - - if(object) - this._mapObject[classType] = object; - if(callback) - this._mapParseSelector[classType] = callback; - }, - - /** - * Returns the file path - * @returns {string} - */ - getFilePath: function(){ - return this._filePath; - }, - - setFilePath: function(path){ - this._filePath = path; - }, - - /** - * Returns the parsed object map. - * @returns {Object} - */ - getParseObjectMap: function(){ - return this._mapObject; - }, - - /** - * Returns the parsed callback map. - * @returns {*} - */ - getParseCallBackMap: function(){ - return this._mapParseSelector; - } -}; - -/** - * The base class of widget properties reader. It parse the foundation properties of widget. - * @class - * @extends ccs.Class - */ -ccs.WidgetPropertiesReader = ccs.Class.extend(/** @lends ccs.WidgetPropertiesReader# */{ - _filePath: "", - - /** - * Create a widget object by json object. - * @param {Object} jsonDict - * @param {String} fullPath - * @param {String} fileName - */ - createWidget: function (jsonDict, fullPath, fileName) { - }, - - /** - * Parses the widget properties. - * @param {Object} data - */ - widgetFromJsonDictionary: function (data) { - }, - - _createGUI: function(className){ - var name = this._getGUIClassName(className); - return ccs.objectFactory.createObject(name); - }, - - _getGUIClassName: function(name){ - var convertedClassName = name; - if (name == "Panel") - convertedClassName = "Layout"; - else if (name == "TextArea") - convertedClassName = "Text"; - else if (name == "TextButton") - convertedClassName = "Button"; - else if (name == "Label") - convertedClassName = "Text"; - else if (name == "LabelAtlas") - convertedClassName = "TextAtlas"; - else if (name == "LabelBMFont") - convertedClassName = "TextBMFont"; - else if (name == "Node") - convertedClassName = "Layout"; - return convertedClassName; - }, - - _getWidgetReaderClassName: function(className){ - // create widget reader to parse properties of widget - var readerName = className; - if (readerName == "Panel") - readerName = "Layout"; - else if (readerName == "TextArea") - readerName = "Text"; - else if (readerName == "TextButton") - readerName = "Button"; - else if (readerName == "Label") - readerName = "Text"; - else if (readerName == "LabelAtlas") - readerName = "TextAtlas"; - else if (readerName == "LabelBMFont") - readerName = "TextBMFont"; - readerName += "Reader"; - return readerName; - }, - - _getWidgetReaderClassNameFromWidget: function(widget){ - var readerName = ""; - // 1st., custom widget parse properties of parent widget with parent widget reader - if (widget instanceof ccui.Button) - readerName = "ButtonReader"; - else if (widget instanceof ccui.CheckBox) - readerName = "CheckBoxReader"; - else if (widget instanceof ccui.ImageView) - readerName = "ImageViewReader"; - else if (widget instanceof ccui.TextAtlas) - readerName = "TextAtlasReader"; - else if (widget instanceof ccui.TextBMFont) - readerName = "TextBMFontReader"; - else if (widget instanceof ccui.Text) - readerName = "TextReader"; - else if (widget instanceof ccui.LoadingBar) - readerName = "LoadingBarReader"; - else if (widget instanceof ccui.Slider) - readerName = "SliderReader"; - else if (widget instanceof ccui.TextField) - readerName = "TextFieldReader"; - else if (widget instanceof ccui.ListView) - readerName = "ListViewReader"; - else if (widget instanceof ccui.PageView) - readerName = "PageViewReader"; - else if (widget instanceof ccui.ScrollView) - readerName = "ScrollViewReader"; - else if (widget instanceof ccui.Layout) - readerName = "LayoutReader"; - else if (widget instanceof ccui.Widget) - readerName = "WidgetReader"; - - return readerName; - }, - - _createWidgetReaderProtocol: function(className){ - return ccs.objectFactory.createObject(className); - } -}); - -/** - * The widget properties reader to parse Cocostudio exported file v0.3 -- v1.0 - * @class - * @extends ccs.WidgetPropertiesReader - */ -ccs.WidgetPropertiesReader0250 = ccs.WidgetPropertiesReader.extend(/** @lends ccs.WidgetPropertiesReader0250# */{ - /** - * Creates a widget by json object. - * @param {Object} jsonDict - * @param {string} fullPath - * @param {string} fileName - * @returns {*} - */ - createWidget: function (jsonDict, fullPath, fileName) { - this._filePath = fullPath == "" ? fullPath : cc.path.join(fullPath, "/"); - var textures = jsonDict["textures"]; - for (var i = 0; i < textures.length; i++) { - var file = textures[i]; - var tp = fullPath; - tp += file; - cc.spriteFrameCache.addSpriteFrames(tp); - } - var fileDesignWidth = jsonDict["designWidth"]; - var fileDesignHeight = jsonDict["designHeight"]; - if (fileDesignWidth <= 0 || fileDesignHeight <= 0) { - cc.log("Read design size error!"); - var winSize = cc.director.getWinSize(); - ccs.uiReader.storeFileDesignSize(fileName, winSize); - } else - ccs.uiReader.storeFileDesignSize(fileName, cc.size(fileDesignWidth, fileDesignHeight)); - var widgetTree = jsonDict["widgetTree"]; - var widget = this.widgetFromJsonDictionary(widgetTree); - - var size = widget.getContentSize(); - if (size.width == 0 && size.height == 0) - widget.setSize(cc.size(fileDesignWidth, fileDesignHeight)); - - var actions = jsonDict["animation"]; - ccs.actionManager.initWithDictionary(fileName, actions, widget); - widgetTree = null; - actions = null; - return widget; - }, - - /** - * Creates a widget by json dictionary. - * @param {Object} data - * @returns {ccui.Widget} - */ - widgetFromJsonDictionary: function (data) { - var widget = null; - var classname = data["classname"]; - var uiOptions = data["options"]; - if (classname == "Button") { - widget = new ccui.Button(); - this.setPropsForButtonFromJsonDictionary(widget, uiOptions); - } else if (classname == "CheckBox") { - widget = new ccui.CheckBox(); - this.setPropsForCheckBoxFromJsonDictionary(widget, uiOptions); - } else if (classname == "Label") { - widget = new ccui.Text(); - this.setPropsForLabelFromJsonDictionary(widget, uiOptions); - } else if (classname == "LabelAtlas") { - widget = new ccui.TextAtlas(); - this.setPropsForLabelAtlasFromJsonDictionary(widget, uiOptions); - } else if (classname == "LoadingBar") { - widget = new ccui.LoadingBar(); - this.setPropsForLoadingBarFromJsonDictionary(widget, uiOptions); - } else if (classname == "ScrollView") { - widget = new ccui.ScrollView(); - this.setPropsForScrollViewFromJsonDictionary(widget, uiOptions); - } else if (classname == "TextArea") { - widget = new ccui.Text(); - this.setPropsForLabelFromJsonDictionary(widget, uiOptions); - } else if (classname == "TextButton") { - widget = new ccui.Button(); - this.setPropsForButtonFromJsonDictionary(widget, uiOptions); - } else if (classname == "TextField") { - widget = new ccui.TextField(); - this.setPropsForTextFieldFromJsonDictionary(widget, uiOptions); - } else if (classname == "ImageView") { - widget = new ccui.ImageView(); - this.setPropsForImageViewFromJsonDictionary(widget, uiOptions); - } else if (classname == "Panel") { - widget = new ccui.Layout(); - this.setPropsForLayoutFromJsonDictionary(widget, uiOptions); - } else if (classname == "Slider") { - widget = new ccui.Slider(); - this.setPropsForSliderFromJsonDictionary(widget, uiOptions); - } else if (classname == "LabelBMFont") { - widget = new ccui.TextBMFont(); - this.setPropsForLabelBMFontFromJsonDictionary(widget, uiOptions); - } else if (classname == "DragPanel") { - widget = new ccui.ScrollView(); - this.setPropsForScrollViewFromJsonDictionary(widget, uiOptions); - } - var children = data["children"]; - for (var i = 0; i < children.length; i++) { - var subData = children[i]; - var child = this.widgetFromJsonDictionary(subData); - if (child) - widget.addChild(child); - subData = null; - } - uiOptions = null; - return widget; - }, - - /** - * Sets widget's properties from json dictionary. - * @param {ccui.Widget} widget - * @param {Object} options the json dictionary. - */ - setPropsForWidgetFromJsonDictionary: function (widget, options) { - if (options["ignoreSize"] !== undefined) - widget.ignoreContentAdaptWithSize(options["ignoreSize"]); - - var w = options["width"]; - var h = options["height"]; - widget.setSize(cc.size(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(cc.p(x, y)); - if (options["scaleX"] !== undefined) { - widget.setScaleX(options["scaleX"]); - } - if (options["scaleY"] !== undefined) { - widget.setScaleY(options["scaleY"]); - } - if (options["rotation"] !== undefined) { - widget.setRotation(options["rotation"]); - } - if (options["visible"] !== undefined) { - widget.setVisible(options["visible"]); - } - - var z = options["ZOrder"]; - widget.setLocalZOrder(z); - }, - - /** - * Sets all widgets' properties from json dictionary. - */ - setPropsForAllWidgetFromJsonDictionary: function(){}, - - /** - * Sets all custom widget's properties from json dictionary. - */ - setPropsForAllCustomWidgetFromJsonDictionary: function(){}, - - /** - * Sets widget's color, anchor point, flipped properties from json object. - * @param {ccui.Widget} widget - * @param {Object} options json object. - */ - setColorPropsForWidgetFromJsonDictionary: function (widget, options) { - if (options["opacity"] !== undefined) { - widget.setOpacity(options["opacity"]); - } - var colorR = options["colorR"] !== undefined ? options["colorR"] : 255; - var colorG = options["colorG"] !== undefined ? options["colorG"] : 255; - var colorB = options["colorB"] !== undefined ? options["colorB"] : 255; - widget.setColor(cc.color(colorR, colorG, colorB)); - var apx = options["anchorPointX"] !== undefined ? options["anchorPointX"] : ((widget.getWidgetType() == ccui.Widget.TYPE_WIDGET) ? 0.5 : 0); - var apy = options["anchorPointY"] !== undefined ? options["anchorPointY"] : ((widget.getWidgetType() == ccui.Widget.TYPE_WIDGET) ? 0.5 : 0); - widget.setAnchorPoint(apx, apy); - var flipX = options["flipX"]; - var flipY = options["flipY"]; - widget.setFlippedX(flipX); - widget.setFlippedY(flipY); - }, - - /** - * Sets ccui.Button's properties from json object. - * @param {ccui.Button} widget - * @param {Object} options - */ - setPropsForButtonFromJsonDictionary: function (widget, options) { - this.setPropsForWidgetFromJsonDictionary(widget, options); - var button = widget; - var scale9Enable = options["scale9Enable"]; - button.setScale9Enabled(scale9Enable); - - var normalFileName = options["normal"]; - var pressedFileName = options["pressed"]; - var disabledFileName = options["disabled"]; - - var normalFileName_tp = normalFileName ? this._filePath + normalFileName : null; - var pressedFileName_tp = pressedFileName ? this._filePath + pressedFileName : null; - var disabledFileName_tp = disabledFileName ? this._filePath + disabledFileName : null; - var useMergedTexture = options["useMergedTexture"]; - if (scale9Enable) { - var cx = options["capInsetsX"]; - var cy = options["capInsetsY"]; - var cw = options["capInsetsWidth"]; - var ch = options["capInsetsHeight"]; - - if (useMergedTexture) - button.loadTextures(normalFileName, pressedFileName, disabledFileName, ccui.Widget.PLIST_TEXTURE); - else - button.loadTextures(normalFileName_tp, pressedFileName_tp, disabledFileName_tp); - //button.setCapInsets(cc.rect(cx, cy, cw, ch)); - if (options["scale9Width"] !== undefined && options["scale9Height"] !== undefined) { - var swf = options["scale9Width"]; - var shf = options["scale9Height"]; - button.setSize(cc.size(swf, shf)); - } - } else { - if (useMergedTexture) - button.loadTextures(normalFileName, pressedFileName, disabledFileName, ccui.Widget.PLIST_TEXTURE); - else - button.loadTextures(normalFileName_tp, pressedFileName_tp, disabledFileName_tp); - } - if (options["text"] !== undefined) { - var text = options["text"] || ""; - if (text) - button.setTitleText(text); - } - if (options["fontSize"] !== undefined) { - button.setTitleFontSize(options["fontSize"]); - } - if (options["fontName"] !== undefined) { - button.setTitleFontName(options["fontName"]); - } - var cr = options["textColorR"] !== undefined ? options["textColorR"] : 255; - var cg = options["textColorG"] !== undefined ? options["textColorG"] : 255; - var cb = options["textColorB"] !== undefined ? options["textColorB"] : 255; - var tc = cc.color(cr, cg, cb); - button.setTitleColor(tc); - this.setColorPropsForWidgetFromJsonDictionary(widget, options); - }, - - /** - * Sets ccui.CheckBox's properties from json object. - * @param {ccui.CheckBox} widget - * @param {Object} options - */ - setPropsForCheckBoxFromJsonDictionary: function (widget, options) { - this.setPropsForWidgetFromJsonDictionary(widget, options); - var checkBox = widget; - var backGroundFileName = options["backGroundBox"]; - var backGroundSelectedFileName = options["backGroundBoxSelected"]; - var frontCrossFileName = options["frontCross"]; - var backGroundDisabledFileName = options["backGroundBoxDisabled"]; - var frontCrossDisabledFileName = options["frontCrossDisabled"]; - - var locFilePath = this._filePath; - - var backGroundFileName_tp = backGroundFileName ? locFilePath + backGroundFileName : null; - var backGroundSelectedFileName_tp = backGroundSelectedFileName ? locFilePath + backGroundSelectedFileName : null; - var frontCrossFileName_tp = frontCrossFileName ? locFilePath + frontCrossFileName : null; - var backGroundDisabledFileName_tp = backGroundDisabledFileName ? locFilePath + backGroundDisabledFileName : null; - var frontCrossDisabledFileName_tp = frontCrossDisabledFileName ? locFilePath + frontCrossDisabledFileName : null; - var useMergedTexture = options["useMergedTexture"]; - - if (useMergedTexture) { - checkBox.loadTextures(backGroundFileName, backGroundSelectedFileName, frontCrossFileName, backGroundDisabledFileName, frontCrossDisabledFileName, ccui.Widget.PLIST_TEXTURE); - } - else { - checkBox.loadTextures(backGroundFileName_tp, backGroundSelectedFileName_tp, frontCrossFileName_tp, backGroundDisabledFileName_tp, frontCrossDisabledFileName_tp); - } - - checkBox.setSelected(options["selectedState"] || false); - this.setColorPropsForWidgetFromJsonDictionary(widget, options); - }, - - /** - * Sets ccui.ImageView's properties from json object. - * @param {ccui.ImageView} widget - * @param {Object} options - */ - setPropsForImageViewFromJsonDictionary: function (widget, options) { - this.setPropsForWidgetFromJsonDictionary(widget, options); - - var imageView = widget; - var imageFileName = options["fileName"]; - var scale9Enable = options["scale9Enable"] || false; - imageView.setScale9Enabled(scale9Enable); - - var tp_i = this._filePath; - var imageFileName_tp = null; - if (imageFileName) - imageFileName_tp = tp_i + imageFileName; - - var useMergedTexture = options["useMergedTexture"]; - if (scale9Enable) { - if (useMergedTexture) { - imageView.loadTexture(imageFileName, ccui.Widget.PLIST_TEXTURE); - } - else { - imageView.loadTexture(imageFileName_tp); - } - - if (options["scale9Width"] !== undefined && options["scale9Height"] !== undefined) { - var swf = options["scale9Width"]; - var shf = options["scale9Height"]; - imageView.setSize(cc.size(swf, shf)); - } - - var cx = options["capInsetsX"]; - var cy = options["capInsetsY"]; - var cw = options["capInsetsWidth"]; - var ch = options["capInsetsHeight"]; - imageView.setCapInsets(cc.rect(cx, cy, cw, ch)); - - } - else { - if (useMergedTexture) { - imageView.loadTexture(imageFileName, ccui.Widget.PLIST_TEXTURE); - } - else { - imageView.loadTexture(imageFileName_tp); - } - } - this.setColorPropsForWidgetFromJsonDictionary(widget, options); - }, - - /** - * Sets ccui.Text's properties from json object. - * @param {ccui.Text} widget - * @param {Object} options json dictionary - */ - setPropsForLabelFromJsonDictionary: function (widget, options) { - this.setPropsForWidgetFromJsonDictionary(widget, options); - var label = widget; - var touchScaleChangeAble = options["touchScaleEnable"]; - label.setTouchScaleChangeEnabled(touchScaleChangeAble); - var text = options["text"]; - label.setString(text); - if (options["fontSize"] !== undefined) { - label.setFontSize(options["fontSize"]); - } - if (options["fontName"] !== undefined) { - label.setFontName(options["fontName"]); - } - if (options["areaWidth"] !== undefined && options["areaHeight"] !== undefined) { - var size = cc.size(options["areaWidth"], options["areaHeight"]); - label.setTextAreaSize(size); - } - if (options["hAlignment"]) { - label.setTextHorizontalAlignment(options["hAlignment"]); - } - if (options["vAlignment"]) { - label.setTextVerticalAlignment(options["vAlignment"]); - } - this.setColorPropsForWidgetFromJsonDictionary(widget, options); - }, - - /** - * Sets ccui.TextAtlas' properties from json object. - * @param {ccui.TextAtlas} widget - * @param {Object} options - */ - setPropsForLabelAtlasFromJsonDictionary: function (widget, options) { - this.setPropsForWidgetFromJsonDictionary(widget, options); - var labelAtlas = widget; - - var cmft = options["charMapFileData"], svValue = options["stringValue"], iwValue = options["itemWidth"]; - var ihValue = options["itemHeight"], scmValue = options["startCharMap"]; - var sv = (svValue !== undefined); - var cmf = (cmft !== undefined); - var iw = (iwValue !== undefined); - var ih = (ihValue !== undefined); - var scm = (scmValue !== undefined); - if (sv && cmf && iw && ih && scm && cmft) { - var cmf_tp = this._filePath + cmft; - labelAtlas.setProperty(svValue, cmf_tp, iwValue, ihValue, scmValue); - } - this.setColorPropsForWidgetFromJsonDictionary(widget, options); - }, - - /** - * Sets ccui.Layout's properties from json object. - * @param {ccui.Layout} widget - * @param {Object} options - */ - setPropsForLayoutFromJsonDictionary: function (widget, options) { - this.setPropsForWidgetFromJsonDictionary(widget, options); - var containerWidget = widget; - if (!(containerWidget instanceof ccui.ScrollView) && !(containerWidget instanceof ccui.ListView)) { - containerWidget.setClippingEnabled(options["clipAble"]); - } - var panel = widget; - var backGroundScale9Enable = options["backGroundScale9Enable"]; - panel.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"]; - panel.setBackGroundColorVector(cc.p(bgcv1, bgcv2)); - - var co = options["bgColorOpacity"]; - - var colorType = options["colorType"]; - panel.setBackGroundColorType(colorType); - panel.setBackGroundColor(cc.color(scr, scg, scb), cc.color(ecr, ecg, ecb)); - panel.setBackGroundColor(cc.color(cr, cg, cb)); - panel.setBackGroundColorOpacity(co); - - var imageFileName = options["backGroundImage"]; - var imageFileName_tp = imageFileName ? this._filePath + imageFileName : null; - var useMergedTexture = options["useMergedTexture"]; - if (useMergedTexture) { - panel.setBackGroundImage(imageFileName, ccui.Widget.PLIST_TEXTURE); - } - else { - panel.setBackGroundImage(imageFileName_tp); - } - if (backGroundScale9Enable) { - var cx = options["capInsetsX"]; - var cy = options["capInsetsY"]; - var cw = options["capInsetsWidth"]; - var ch = options["capInsetsHeight"]; - panel.setBackGroundImageCapInsets(cc.rect(cx, cy, cw, ch)); - } - this.setColorPropsForWidgetFromJsonDictionary(widget, options); - }, - - /** - * Sets ccui.ScrollView's properties from json dictionary. - * @param {ccui.ScrollView} widget - * @param {Object} options json dictionary. - */ - setPropsForScrollViewFromJsonDictionary: function (widget, options) { - this.setPropsForLayoutFromJsonDictionary(widget, options); - var scrollView = widget; - var innerWidth = options["innerWidth"]; - var innerHeight = options["innerHeight"]; - scrollView.setInnerContainerSize(cc.size(innerWidth, innerHeight)); - var direction = options["direction"]; - scrollView.setDirection(direction); - scrollView.setBounceEnabled(options["bounceEnable"]); - this.setColorPropsForWidgetFromJsonDictionary(widget, options); - }, - - /** - * Sets the container's properties from json dictionary. - * @param {ccui.Widget} widget - * @param {Object} options json dictionary. - */ - setPropsForContainerWidgetFromJsonDictionary: function (widget, options) { - this.setPropsForWidgetFromJsonDictionary(widget, options); - var containerWidget = widget; - if (containerWidget instanceof ccui.ScrollView || - containerWidget instanceof ccui.ListView) { - containerWidget.setClippingEnabled(options["clipAble"]); - } - this.setColorPropsForWidgetFromJsonDictionary(widget, options); - }, - - /** - * Sets ccui.Slider's properties from json dictionary. - * @param {ccui.Slider} widget - * @param {Object} options json dictionary. - */ - setPropsForSliderFromJsonDictionary: function (widget, options) { - this.setPropsForWidgetFromJsonDictionary(widget, options); - var slider = widget; - - var barTextureScale9Enable = options["barTextureScale9Enable"] || false; - slider.setScale9Enabled(barTextureScale9Enable); - var barLength = options["length"]; - var useMergedTexture = options["useMergedTexture"]; - var bt = (options["barFileName"] !== undefined); - if (bt) { - if (barTextureScale9Enable) { - var imageFileName = options["barFileName"]; - var imageFileName_tp = imageFileName ? this._filePath + imageFileName : null; - if (useMergedTexture) { - slider.loadBarTexture(imageFileName, ccui.Widget.PLIST_TEXTURE); - } else { - slider.loadBarTexture(imageFileName_tp); - } - slider.setSize(cc.size(barLength, slider.getContentSize().height)); - } else { - var imageFileName = options["barFileName"]; - var imageFileName_tp = imageFileName ? this._filePath + imageFileName : null; - if (useMergedTexture) { - slider.loadBarTexture(imageFileName, ccui.Widget.PLIST_TEXTURE); - } else { - slider.loadBarTexture(imageFileName_tp); - } - } - } - - var normalFileName = options["ballNormal"]; - var pressedFileName = options["ballPressed"]; - var disabledFileName = options["ballDisabled"]; - - var normalFileName_tp = normalFileName ? this._filePath + normalFileName : null; - var pressedFileName_tp = pressedFileName ? this._filePath + pressedFileName : null; - var disabledFileName_tp = disabledFileName ? this._filePath + disabledFileName : null; - if (useMergedTexture) { - slider.loadSlidBallTextures(normalFileName, pressedFileName, disabledFileName, ccui.Widget.PLIST_TEXTURE); - } else { - slider.loadSlidBallTextures(normalFileName_tp, pressedFileName_tp, disabledFileName_tp); - } - slider.setPercent(options["percent"]); - - var imageFileName = options["progressBarFileName"]; - var imageFileName_tp = imageFileName ? this._filePath + imageFileName : null; - if (useMergedTexture) { - slider.loadProgressBarTexture(imageFileName, ccui.Widget.PLIST_TEXTURE); - } else { - slider.loadProgressBarTexture(imageFileName_tp); - } - this.setColorPropsForWidgetFromJsonDictionary(widget, options); - }, - - /** - * Sets ccui.TextField's properties from json object. - * @param {ccui.TextField} widget - * @param {Object} options - */ - setPropsForTextAreaFromJsonDictionary: function (widget, options) { - this.setPropsForWidgetFromJsonDictionary(widget, options); - var textArea = widget; - textArea.setString(options["text"]); - if (options["fontSize"] !== undefined) { - textArea.setFontSize(options["fontSize"]); - } - var cr = options["colorR"]; - var cg = options["colorG"]; - var cb = options["colorB"]; - textArea.setColor(cc.color((cr == null) ? 255 : cr, (cg == null) ? 255 : cg, (cb == null) ? 255 : cb)); - textArea.setFontName(options["fontName"]); - if (options["areaWidth"] !== undefined && options["areaHeight"] !== undefined) { - var size = cc.size(options["areaWidth"], options["areaHeight"]); - textArea.setTextAreaSize(size); - } - if (options["hAlignment"]) { - textArea.setTextHorizontalAlignment(options["hAlignment"]); - } - if (options["vAlignment"]) { - textArea.setTextVerticalAlignment(options["vAlignment"]); - } - this.setColorPropsForWidgetFromJsonDictionary(widget, options); - }, - - /** - * Sets ccui.Button's text properties from json dictionary. - * @param {ccui.Button} widget - * @param {Object} options - */ - setPropsForTextButtonFromJsonDictionary: function (widget, options) { - this.setPropsForButtonFromJsonDictionary(widget, options); - - var textButton = widget; - textButton.setTitleText(options["text"] || ""); - var cri = options["textColorR"] !== undefined ? options["textColorR"] : 255; - var cgi = options["textColorG"] !== undefined ? options["textColorG"] : 255; - var cbi = options["textColorB"] !== undefined ? options["textColorB"] : 255; - textButton.setTitleColor(cc.color(cri, cgi, cbi)); - if (options["fontSize"] !== undefined) - textButton.setTitleFontSize(options["fontSize"]); - if (options["fontName"] !== undefined) - textButton.setTitleFontName(options["fontName"]); - this.setColorPropsForWidgetFromJsonDictionary(widget, options); - }, - - /** - * Sets ccui.TextField's properties from json dictionary. - * @param {ccui.TextField} widget - * @param {Object} options json dictionary - */ - setPropsForTextFieldFromJsonDictionary: function (widget, options) { - this.setPropsForWidgetFromJsonDictionary(widget, options); - var textField = widget; - if (options["placeHolder"] !== undefined) { - textField.setPlaceHolder(options["placeHolder"]); - } - textField.setString(options["text"]); - if (options["fontSize"] !== undefined) { - textField.setFontSize(options["fontSize"]); - } - if (options["fontName"] !== undefined) { - textField.setFontName(options["fontName"]); - } - if (options["touchSizeWidth"] !== undefined && options["touchSizeHeight"] !== undefined) { - textField.setTouchSize(cc.size(options["touchSizeWidth"], options["touchSizeHeight"])); - } - - var dw = options["width"]; - var dh = options["height"]; - if (dw > 0.0 || dh > 0.0) { - //textField.setSize(CCSizeMake(dw, dh)); - } - var maxLengthEnable = options["maxLengthEnable"]; - textField.setMaxLengthEnabled(maxLengthEnable); - - if (maxLengthEnable) { - var maxLength = options["maxLength"]; - textField.setMaxLength(maxLength); - } - var passwordEnable = options["passwordEnable"]; - textField.setPasswordEnabled(passwordEnable); - if (passwordEnable) { - textField.setPasswordStyleText(options["passwordStyleText"]); - } - this.setColorPropsForWidgetFromJsonDictionary(widget, options); - }, - - /** - * Sets ccui.LoadingBar's properties from json dictionary. - * @param {ccui.LoadingBar} widget - * @param {Object} options json dictionary - */ - setPropsForLoadingBarFromJsonDictionary: function (widget, options) { - this.setPropsForWidgetFromJsonDictionary(widget, options); - var loadingBar = widget; - var useMergedTexture = options["useMergedTexture"]; - var imageFileName = options["texture"]; - var imageFileName_tp = imageFileName ? this._filePath + imageFileName : null; - if (useMergedTexture) { - loadingBar.loadTexture(imageFileName, ccui.Widget.PLIST_TEXTURE); - } else { - loadingBar.loadTexture(imageFileName_tp); - } - loadingBar.setDirection(options["direction"]); - loadingBar.setPercent(options["percent"]); - this.setColorPropsForWidgetFromJsonDictionary(widget, options); - }, - - /** - * Sets ccui.ListView's properties from json dictionary. - * @param {ccui.ListView} widget - * @param {Object} options json dictionary - */ - setPropsForListViewFromJsonDictionary: function (widget, options) { - this.setPropsForLayoutFromJsonDictionary(widget, options); - }, - - /** - * Sets ccui.PageView's properties from json dictionary. - * @param {ccui.PageView} widget - * @param {Object} options json dictionary - */ - setPropsForPageViewFromJsonDictionary: function (widget, options) { - this.setPropsForLayoutFromJsonDictionary(widget, options); - }, - - /** - * Sets ccui.TextBMFont's properties from json dictionary. - * @param {ccui.TextBMFont} widget - * @param {Object} options json dictionary - */ - setPropsForLabelBMFontFromJsonDictionary: function (widget, options) { - this.setPropsForWidgetFromJsonDictionary(widget, options); - var labelBMFont = widget; - var cmft = options["fileName"]; - var cmf_tp = this._filePath + cmft; - labelBMFont.setFntFile(cmf_tp); - var text = options["text"]; - labelBMFont.setString(text); - this.setColorPropsForWidgetFromJsonDictionary(widget, options); - } -}); - -/** - * The widget properties reader to parse Cocostudio exported file v1.0 higher. - * @class - * @extends ccs.WidgetPropertiesReader - */ -ccs.WidgetPropertiesReader0300 = ccs.WidgetPropertiesReader.extend(/** @lends ccs.WidgetPropertiesReader0300# */{ - /** - * Creates widget by json object. - * @param {Object} jsonDict json dictionary - * @param {String} fullPath - * @param {String} fileName - * @returns {ccui.Widget} - */ - createWidget: function (jsonDict, fullPath, fileName) { - this._filePath = fullPath == "" ? fullPath : cc.path.join(fullPath, "/"); - var textures = jsonDict["textures"]; - for (var i = 0; i < textures.length; i++) { - var file = textures[i]; - var tp = fullPath; - tp += file; - cc.spriteFrameCache.addSpriteFrames(tp); - } - var fileDesignWidth = jsonDict["designWidth"]; - var fileDesignHeight = jsonDict["designHeight"]; - if (fileDesignWidth <= 0 || fileDesignHeight <= 0) { - cc.log("Read design size error!"); - var winSize = cc.director.getWinSize(); - ccs.uiReader.storeFileDesignSize(fileName, winSize); - } else - ccs.uiReader.storeFileDesignSize(fileName, cc.size(fileDesignWidth, fileDesignHeight)); - var widgetTree = jsonDict["widgetTree"]; - var widget = this.widgetFromJsonDictionary(widgetTree); - - var size = widget.getContentSize(); - widget.setSize(cc.size(fileDesignWidth, fileDesignHeight)); - - var actions = jsonDict["animation"]; - ccs.actionManager.initWithDictionary(fileName, actions, widget); - - widgetTree = null; - actions = null; - return widget; - }, - - /** - * Sets widget's foundation properties from json dictionary. - * @param {Object} reader widget reader - * @param {ccui.Widget} widget - * @param {Object} options json dictionary - */ - setPropsForAllWidgetFromJsonDictionary: function(reader, widget, options){ - if(reader && reader.setPropsFromJsonDictionary) - reader.setPropsFromJsonDictionary(widget, options); - }, - - /** - * Sets widget's custom properties from json dictionary - * @param {String} classType class type - * @param {ccui.Widget} widget - * @param {Object} customOptions - */ - setPropsForAllCustomWidgetFromJsonDictionary: function(classType, widget, customOptions){ - var guiReader = ccs.uiReader; - var object_map = guiReader.getParseObjectMap(); - var object = object_map[classType]; - - var selector_map = guiReader.getParseCallBackMap(); - var selector = selector_map[classType]; - - if (object && selector) - selector.call(object, classType, widget, customOptions); - }, - - /** - * Creates a widget from json dictionary. - * @param {Object} data json data - * @returns {ccui.Widget} - */ - widgetFromJsonDictionary: function (data) { - var classname = data["classname"]; - var uiOptions = data["options"]; - var widget = this._createGUI(classname); - - var readerName = this._getWidgetReaderClassName(classname); - var reader = this._createWidgetReaderProtocol(readerName); - - if (reader){ - // widget parse with widget reader - this.setPropsForAllWidgetFromJsonDictionary(reader, widget, uiOptions); - } else { - readerName = this._getWidgetReaderClassNameFromWidget(widget); - - reader = ccs.objectFactory.createObject(readerName); - - if (reader && widget) { - this.setPropsForAllWidgetFromJsonDictionary(reader, widget, uiOptions); - - // 2nd., custom widget parse with custom reader - var customProperty = uiOptions["customProperty"]; - var customJsonDict = JSON.parse(customProperty); - this.setPropsForAllCustomWidgetFromJsonDictionary(classname, widget, customJsonDict); - }else{ - cc.log("Widget or WidgetReader doesn't exists!!! Please check your json file."); - } - - } - - var childrenItem = data["children"]; - for(var i=0; i 0.0 || dh > 0.0) { - //textField.setSize(CCSizeMake(dw, dh)); - } - var maxLengthEnable = options["maxLengthEnable"]; - textField.setMaxLengthEnabled(maxLengthEnable); - - if (maxLengthEnable) { - var maxLength = options["maxLength"]; - textField.setMaxLength(maxLength); - } - var passwordEnable = options["passwordEnable"]; - textField.setPasswordEnabled(passwordEnable); - if (passwordEnable) { - textField.setPasswordStyleText(options["passwordStyleText"]); - } - this.setColorPropsForWidgetFromJsonDictionary(widget, options); - }, - - /** - * Sets ccui.LoadingBar's properties from json dictionary. - * @param {ccui.LoadingBar} widget - * @param {Object} options json dictionary - */ - setPropsForLoadingBarFromJsonDictionary: function (widget, options) { - this.setPropsForWidgetFromJsonDictionary(widget, options); - var loadingBar = widget; - - var imageFileNameDic = options["textureData"]; - var imageFileNameType = imageFileNameDic["resourceType"]; - switch (imageFileNameType) { - case 0: - var tp_i = this._filePath; - var imageFileName = imageFileNameDic["path"]; - var imageFileName_tp = null; - if (imageFileName) { - imageFileName_tp = tp_i + imageFileName; - loadingBar.loadTexture(imageFileName_tp); - } - break; - case 1: - var imageFileName = imageFileNameDic["path"]; - loadingBar.loadTexture(imageFileName, ccui.Widget.PLIST_TEXTURE); - break; - default: - break; - } - imageFileNameDic = null; - - var scale9Enable = options["scale9Enable"]; - loadingBar.setScale9Enabled(scale9Enable); - - if (scale9Enable) { - var cx = options["capInsetsX"]; - var cy = options["capInsetsY"]; - var cw = options["capInsetsWidth"]; - var ch = options["capInsetsHeight"]; - - loadingBar.setCapInsets(cc.rect(cx, cy, cw, ch)); - - var width = options["width"]; - var height = options["height"]; - loadingBar.setSize(cc.size(width, height)); - } - - loadingBar.setDirection(options["direction"]); - loadingBar.setPercent(options["percent"]); - this.setColorPropsForWidgetFromJsonDictionary(widget, options); - - }, - - /** - * Sets ccui.ListView's properties from json dictionary. - * @param {ccui.ListView} widget - * @param {Object} options json dictionary - */ - setPropsForListViewFromJsonDictionary: function (widget, options) { - this.setPropsForLayoutFromJsonDictionary(widget, options); - var innerWidth = options["innerWidth"] || 0; - var innerHeight = options["innerHeight"] || 0; - widget.setInnerContainerSize(cc.size(innerWidth, innerHeight)); - widget.setDirection(options["direction"] || 0); - widget.setGravity(options["gravity"] || 0); - widget.setItemsMargin(options["itemMargin"] || 0); - }, - - /** - * Sets ccui.PageView's properties from json dictionary. - * @param {ccui.PageView} widget - * @param {Object} options json dictionary - */ - setPropsForPageViewFromJsonDictionary: function (widget, options) { - this.setPropsForLayoutFromJsonDictionary(widget, options); - }, - - /** - * Sets ccui.TextBMFont's properties from json dictionary. - * @param {ccui.TextBMFont} widget - * @param {Object} options json dictionary - */ - setPropsForLabelBMFontFromJsonDictionary: function (widget, options) { - this.setPropsForWidgetFromJsonDictionary(widget, options); - - var labelBMFont = widget; - - var cmftDic = options["fileNameData"]; - var cmfType = cmftDic["resourceType"]; - switch (cmfType) { - case 0: - var cmfPath = cmftDic["path"]; - var cmf_tp = this._filePath + cmfPath; - labelBMFont.setFntFile(cmf_tp); - break; - case 1: - cc.log("Wrong res type of LabelAtlas!"); - break; - default: - break; - } - cmftDic = null; - - var text = options["text"]; - labelBMFont.setString(text); - - this.setColorPropsForWidgetFromJsonDictionary(widget, options); - }, - - widgetFromXML: function(objectData, classType){ - var classname = classType.substr(0, classType.find("ObjectData")); - //cc.log("classname = %s", classname); - - var widget = this.createGUI(classname); - var readerName = this.getWidgetReaderClassName(classname); - - var reader = this.createWidgetReaderProtocol(readerName); - - if (reader) - { - // widget parse with widget reader - this.setPropsForAllWidgetFromXML(reader, widget, objectData); - } - else - { - // - // 1st., custom widget parse properties of parent widget with parent widget reader - readerName = this.getWidgetReaderClassName(widget); - reader = this.createWidgetReaderProtocol(readerName); - if (reader && widget) - { - this.setPropsForAllWidgetFromXML(reader, widget, objectData); - - // 2nd., custom widget parse with custom reader - // const protocolbuffers::WidgetOptions& widgetOptions = nodetree.widgetoptions(); - // const char* customProperty = widgetOptions.customproperty().c_str(); - var customProperty = ""; - var customJsonDict; - customJsonDict.Parse(customProperty); - if (customJsonDict.HasParseError()) - { - cc.log("GetParseError %s\n", customJsonDict.GetParseError()); - } - this.setPropsForAllCustomWidgetFromJsonDictionary(classname, widget, customJsonDict); - } - else - { - cc.log("Widget or WidgetReader doesn't exists!!! Please check your json file."); - } - // - } - - - - - - // children - var containChildrenElement = false; - objectData = objectData.FirstChildElement(); - - while (objectData) - { - //cc.log("objectData name = %s", objectData.Name()); - - if ("Children" !== objectData.Name()) - { - containChildrenElement = true; - break; - } - - objectData = objectData.NextSiblingElement(); - } - - if (containChildrenElement) - { - objectData = objectData.FirstChildElement(); - //cc.log("objectData name = %s", objectData.Name()); - - while (objectData) - { - var attribute = objectData.FirstAttribute(); - while (attribute) - { - var name = attribute.Name(); - var value = attribute.Value(); - - if (name == "ctype") - { - var child = this.widgetFromXML(objectData, value); - //cc.log("child = %p", child); - if (child) - { - var pageView = widget; - var listView = widget; - if (pageView instanceof ccui.PageView) - { - var layout = child; - if (layout instanceof ccui.Layout) - { - pageView.addPage(layout); - } - } - else if (listView) - { - var widgetChild = child; - if (widgetChild instanceof ccui.Widget) - { - listView.pushBackCustomItem(widgetChild); - } - } - else - { - widget.addChild(child); - } - } - - break; - } - - attribute = attribute.Next(); - } - - // Node* child = nodeFromXML(objectData, value); - // CCLOG("child = %p", child); - // if (child) - // { - // PageView* pageView = dynamic_cast(node); - // ListView* listView = dynamic_cast(node); - // if (pageView) - // { - // Layout* layout = dynamic_cast(child); - // if (layout) - // { - // pageView.addPage(layout); - // } - // } - // else if (listView) - // { - // Widget* widget = dynamic_cast(child); - // if (widget) - // { - // listView.pushBackCustomItem(widget); - // } - // } - // else - // { - // node.addChild(child); - // } - // } - - objectData = objectData.NextSiblingElement(); - } - } - // - - //cc.log("widget = %p", widget); - - return widget; - }, - - setPropsForAllWidgetFromXML: function(reader, widget, objectData){ - reader.setPropsFromXML(widget, objectData); - } - -}); diff --git a/extensions/cocostudio/reader/SceneReader.js b/extensions/cocostudio/reader/SceneReader.js deleted file mode 100644 index f085421994..0000000000 --- a/extensions/cocostudio/reader/SceneReader.js +++ /dev/null @@ -1,366 +0,0 @@ -/**************************************************************************** - 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.sceneReader is the reader for Cocos Studio scene editor. - * @class - * @name ccs.sceneReader - */ -ccs.sceneReader = /** @lends ccs.sceneReader# */{ - _baseBath:"", - _listener:null, - _selector:null, - _node: null, - - /** - * Creates a node with json file that exported by CocoStudio scene editor - * @param pszFileName - * @returns {cc.Node} - */ - createNodeWithSceneFile: function (pszFileName) { - this._node = null; - do{ - this._baseBath = cc.path.dirname(pszFileName); - var jsonDict = cc.loader.getRes(pszFileName); - if (!jsonDict) - throw "Please load the resource first : " + pszFileName; - this._node = this.createObject(jsonDict, null); - ccs.triggerManager.parse(jsonDict["Triggers"]||[]); - }while(0); - return this._node; - }, - - /** - * create UI object from data - * @param {Object} inputFiles - * @param {cc.Node} parenet - * @returns {cc.Node} - */ - createObject: function (inputFiles, parenet) { - var className = inputFiles["classname"]; - if (className == "CCNode") { - var gb = null; - if (!parenet) { - gb = new cc.Node(); - } - else { - gb = new cc.Node(); - parenet.addChild(gb); - } - - this.setPropertyFromJsonDict(gb, inputFiles); - - var components = inputFiles["components"]; - for (var i = 0; i < components.length; i++) { - var subDict = components[i]; - if (!subDict) { - break; - } - className = subDict["classname"]; - var comName = subDict["name"]; - - var fileData = subDict["fileData"]; - var path = "", plistFile = ""; - var resType = 0; - if (fileData != null) { - if(fileData["resourceType"] !== undefined){ - resType = fileData["resourceType"] - }else{ - resType =-1; - } - - path = cc.path.join(this._baseBath, fileData["path"]); - plistFile = fileData["plistFile"]; - } - - var pathExtname = cc.path.extname(path); - - if (className == "CCSprite") { - var sprite = null; - - if (resType == 0) { - if (pathExtname != ".png") continue; - sprite = new cc.Sprite(path); - } - else if (resType == 1) { - if (pathExtname != ".plist") continue; - - plistFile = cc.path.join(this._baseBath, plistFile); - var pngFile = cc.path.changeExtname(plistFile, ".png"); - cc.spriteFrameCache.addSpriteFrames(plistFile, pngFile); - sprite = new cc.Sprite("#" + fileData["path"]); - } - else { - continue; - } - - var render = new ccs.ComRender(sprite, "CCSprite"); - if (comName != null) { - render.setName(comName); - } - - gb.addComponent(render); - this._callSelector(sprite, subDict); - } - else if (className == "CCTMXTiledMap") { - var tmx = null; - if (resType == 0) { - if (pathExtname != ".tmx") continue; - tmx = new cc.TMXTiledMap(path); - } - else { - continue; - } - - var render = new ccs.ComRender(tmx, "CCTMXTiledMap"); - if (comName != null) { - render.setName(comName); - } - gb.addComponent(render); - this._callSelector(tmx, subDict); - } - else if (className == "CCParticleSystemQuad") { - if (pathExtname != ".plist") continue; - - var particle = null; - if (resType == 0) { - particle = new cc.ParticleSystem(path); - } - else { - cc.log("unknown resourcetype on CCParticleSystemQuad!"); - continue; - } - - particle.setPosition(0, 0); - var render = new ccs.ComRender(particle, "CCParticleSystemQuad"); - if (comName != null) { - render.setName(comName); - } - gb.addComponent(render); - this._callSelector(particle, subDict); - } - else if (className == "CCArmature") { - if (resType != 0) { - continue; - } - 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); - - var armature = new ccs.Armature(name); - - var render = new ccs.ComRender(armature, "CCArmature"); - if (comName != null) { - render.setName(comName); - } - gb.addComponent(render); - - var actionName = subDict["selectedactionname"]; - if (actionName && armature.getAnimation()) { - armature.getAnimation().play(actionName); - } - jsonDict = null; - subData = null; - this._callSelector(armature, subDict); - } - else if (className == "CCComAudio") { - var audio = null; - if (resType == 0) { - audio = new ccs.ComAudio(); - } - else { - continue; - } - audio.preloadEffect(path); - if (comName) { - audio.setName(comName); - } - gb.addComponent(audio); - this._callSelector(audio, subDict); - } - else if (className == "CCComAttribute") { - var attribute = null; - if (resType == 0) { - attribute = new ccs.ComAttribute(); - if (path != "") attribute.parse(path); - } - else { - cc.log("unknown resourcetype on CCComAttribute!"); - continue; - } - if (comName) { - attribute.setName(comName); - } - gb.addComponent(attribute); - this._callSelector(attribute, subDict); - } - else if (className == "CCBackgroundAudio") { - if(!pathExtname) continue; - if(resType!=0) continue; - - var audio = new ccs.ComAudio(); - audio.preloadBackgroundMusic(path); - audio.setFile(path); - var bLoop = Boolean(subDict["loop"] || 0); - audio.setLoop(bLoop); - if (comName) { - audio.setName(comName); - } - gb.addComponent(audio); - audio.playBackgroundMusic(path, bLoop); - this._callSelector(audio, subDict); - } - else if (className == "GUIComponent") { - var widget = ccs.uiReader.widgetFromJsonFile(path); - var render = new ccs.ComRender(widget, "GUIComponent"); - if (comName != null) { - render.setName(comName); - } - gb.addComponent(render); - this._callSelector(audio, subDict); - } - subDict = null; - } - var gameobjects = inputFiles["gameobjects"]; - for (var i = 0; i < gameobjects.length; i++) { - var subDict = gameobjects[i]; - if (!subDict) - break; - this.createObject(subDict, gb); - subDict = null; - } - - var canvasSizeDict = inputFiles["CanvasSize"]; - if (canvasSizeDict) - { - var width = canvasSizeDict["_width"]; - var height = canvasSizeDict["_height"]; - gb.setContentSize(cc.size(width, height)); - } - - return gb; - } - - return null; - }, - - _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; - }, - - /** - * 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); - }, - - /** - * Sets properties from json dictionary. - * @param {cc.Node} node - * @param {Object} dict - */ - setPropertyFromJsonDict: function (node, dict) { - var x = (cc.isUndefined(dict["x"]))?0:dict["x"]; - var y = (cc.isUndefined(dict["y"]))?0:dict["y"]; - node.setPosition(x, y); - - var bVisible = Boolean((cc.isUndefined(dict["visible"]))?1:dict["visible"]); - node.setVisible(bVisible); - - var nTag = (cc.isUndefined(dict["objecttag"]))?-1:dict["objecttag"]; - node.setTag(nTag); - - var nZorder = (cc.isUndefined(dict["zorder"]))?0:dict["zorder"]; - node.setLocalZOrder(nZorder); - - var fScaleX = (cc.isUndefined(dict["scalex"]))?1:dict["scalex"]; - var fScaleY = (cc.isUndefined(dict["scaley"]))?1:dict["scaley"]; - node.setScaleX(fScaleX); - node.setScaleY(fScaleY); - - var fRotationZ = (cc.isUndefined(dict["rotation"]))?0:dict["rotation"]; - node.setRotation(fRotationZ); - - var sName = dict["name"] || ""; - node.setName(sName); - }, - - /** - * Sets the listener to reader. - * @param {function} selector - * @param {Object} listener the target object. - */ - setTarget : function(selector,listener){ - this._listener = listener; - this._selector = selector; - }, - - _callSelector:function(obj,subDict){ - if(this._selector) - this._selector.call(this._listener,obj,subDict); - }, - - /** - * Returns the version of ccs.SceneReader. - * @returns {string} - */ - version: function () { - return "1.2.0.0"; - }, - - /** - * 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/reader/timeline/ActionTimelineCache.js b/extensions/cocostudio/reader/timeline/ActionTimelineCache.js deleted file mode 100644 index 76b5fa0ee0..0000000000 --- a/extensions/cocostudio/reader/timeline/ActionTimelineCache.js +++ /dev/null @@ -1,909 +0,0 @@ -/**************************************************************************** - 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.actionTimelineCacheStatic = { - FrameType_VisibleFrame : "VisibleFrame", - FrameType_PositionFrame : "PositionFrame", - FrameType_ScaleFrame : "ScaleFrame", - FrameType_RotationFrame : "RotationFrame", - FrameType_SkewFrame : "SkewFrame", - FrameType_RotationSkewFrame : "RotationSkewFrame", - FrameType_AnchorFrame : "AnchorPointFrame", - FrameType_InnerActionFrame : "InnerActionFrame", - FrameType_ColorFrame : "ColorFrame", - FrameType_TextureFrame : "TextureFrame", - FrameType_EventFrame : "EventFrame", - FrameType_ZOrderFrame : "ZOrderFrame", - - ACTION : "action", - DURATION : "duration", - TIMELINES : "timelines", - FRAME_TYPE : "frameType", - FRAMES : "frames", - FRAME_INDEX : "frameIndex", - TWEEN : "tween", - TIME_SPEED : "speed", - ACTION_TAG : "actionTag", - INNER_ACTION : "innerActionType", - START_FRAME : "startFrame", - - X : "x", - Y : "y", - ROTATION : "rotation", - ALPHA : "alpha", - RED : "red", - GREEN : "green", - BLUE : "blue", - Value : "value" -}; - -/** - * action timeline cache - * @name ccs.ActionTimelineCache - * @namespace - */ -ccs.actionTimelineCache = { - - _FrameCreateFunc: null, - _Pair: null, - _funcs: null, - _animationActions: null, - - /** - * The initialization part object - */ - init: function(){ - - this._animationActions = {}; - this._funcs = {}; - this._funcs["VisibleFrame"] = this._loadVisibleFrame; - this._funcs["PositionFrame"] = this._loadPositionFrame; - this._funcs["ScaleFrame"] = this._loadScaleFrame; - this._funcs["RotationFrame"] = this._loadRotationFrame; - this._funcs["SkewFrame"] = this._loadSkewFrame; - this._funcs["RotationSkewFrame"] = this._loadRotationSkewFrame; - this._funcs["AnchorFrame"] = this._loadAnchorPointFrame; - this._funcs["InnerActionFrame"] = this._loadInnerActionFrame; - this._funcs["ColorFrame"] = this._loadColorFrame; - this._funcs["TextureFrame"] = this._loadTextureFrame; - this._funcs["EventFrame"] = this._loadEventFrame; - this._funcs["ZOrderFrame"] = this._loadZOrderFrame; - }, - - /** - * remove Action - * @param {string} fileName - */ - removeAction: function(fileName){ - if (this._animationActions[fileName]) { - delete this._animationActions[fileName]; - } - }, - - /** - * Create new action - * @param {string} filename - * @returns {*} - */ - createAction: function(filename){ - - var path = filename; - var pos = path.lastIndexOf('.'); - var suffix = path.substr(pos + 1, path.length); - //cc.log("suffix = %s", suffix); - - var cache = ccs.actionTimelineCache; - if (suffix == "csb"){ - throw "Does not support protobuf"; - }else if (suffix == "json" || suffix == "ExportJson"){ - return cache.createActionFromJson(filename); - }else if(suffix == "xml") { - cc.log("Does not support"); - } - return null; - }, - - /** - * Create new action - * @param {string} fileName - * @returns {*} - */ - createActionFromJson: function(fileName){ - - var action = this._animationActions[fileName]; - if (action == null) { - action = this.loadAnimationActionWithFile(fileName); - } - return action.clone(); - }, - - /** - * load Animation Action With File - * @param {string} fileName - * @returns {*} - */ - loadAnimationActionWithFile: function(fileName){ - // Read content from file - //TODO Whether you need a complete path splicing? - var contentStr = cc.loader.getRes(fileName); - return this.loadAnimationActionWithContent(fileName, contentStr); - - }, - - /** - * Load animation action with content. - * @param {string} fileName - * @param {Object} content - * @returns {*} - */ - loadAnimationActionWithContent: function(fileName, content){ - // if already exists an action with filename, then return this action - var action = this._animationActions[fileName]; - if(action) - return action; - - var json = content[ccui.actionTimelineCacheStatic.ACTION]; - - action = new ccs.ActionTimeline(); - - action.setDuration(json[ccui.actionTimelineCacheStatic.DURATION]); - action.setTimeSpeed(json[ccui.actionTimelineCacheStatic.TIME_SPEED] || 1); - - var timelineLength = json[ccui.actionTimelineCacheStatic.TIMELINES].length; - for (var i = 0; i 0 || dh > 0){ - //textField.setSize(cc.size(dw, dh)); - } - var maxLengthEnable = options["maxLengthEnable"]; - textField.setMaxLengthEnabled(maxLengthEnable); - - if(maxLengthEnable){ - var maxLength = options["maxLength"]; - textField.setMaxLength(maxLength); - } - var passwordEnable = options["passwordEnable"]; - textField.setPasswordEnabled(passwordEnable); - if(passwordEnable) - textField.setPasswordStyleText(options["passwordStyleText"]); - - var aw = options["areaWidth"]; - var ah = options["areaHeight"]; - if(aw && ah){ - var size = cc.size(aw, ah); - textField.setTextAreaSize(size); - } - var ha = options["hAlignment"]; - if(ha) - textField.setTextHorizontalAlignment(ha); - var va = options["vAlignment"]; - if(va) - textField.setTextVerticalAlignment(va); - - ccs.widgetReader.setColorPropsFromJsonDictionary.call(this, widget, options); - } -}; \ No newline at end of file diff --git a/extensions/cocostudio/reader/widgetreader/WidgetReader.js b/extensions/cocostudio/reader/widgetreader/WidgetReader.js deleted file mode 100644 index dfe3eae17f..0000000000 --- a/extensions/cocostudio/reader/widgetreader/WidgetReader.js +++ /dev/null @@ -1,226 +0,0 @@ -/**************************************************************************** - 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 ccui.Widget's properties reader for GUIReader. - * @class - * @name ccs.widgetReader - **/ -ccs.widgetReader = /** @lends ccs.widgetReader# */{ - - /** - * Sets widget's properties from json dictionary - * @param {ccui.Widget} widget - * @param {object} options - */ - setPropsFromJsonDictionary: function(widget, options){ - var ignoreSizeExsit = options["ignoreSize"]; - if(ignoreSizeExsit != null) - widget.ignoreContentAdaptWithSize(ignoreSizeExsit); - - widget.setSizeType(options["sizeType"]); - 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); - } - } - }, - - /** - * Sets widget's color, anchor point and flipped properties from json dictionary - * @param {ccui.Widget} widget - * @param {object} options - */ - setColorPropsFromJsonDictionary: 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)); - - ccs.widgetReader._setAnchorPointForWidget(widget, options); - widget.setFlippedX(options["flipX"]); - widget.setFlippedY(options["flipY"]); - }, - - _setAnchorPointForWidget: 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)); - }, - - _getResourcePath: function(dict, key, texType){ - var imageFileName = dict[key]; - var imageFileName_tp; - if (null != imageFileName) { - if (texType == 0) - imageFileName_tp = ccs.uiReader.getFilePath() + imageFileName; - else if(texType == 1) - imageFileName_tp = imageFileName; - else - cc.assert(0, "invalid TextureResType!!!"); - } - return imageFileName_tp; - }, - - setAnchorPointForWidget: function(widget, nodeTree){ - var options = nodeTree["widgetOptions"]; - - var isAnchorPointXExists = options["anchorPointX"]; - var anchorPointXInFile; - if (isAnchorPointXExists) - { - anchorPointXInFile = options["anchorPointX"]; - } - else - { - anchorPointXInFile = widget.getAnchorPoint().x; - } - - var isAnchorPointYExists = options["anchorPointY"]; - var anchorPointYInFile; - if (isAnchorPointYExists) - { - anchorPointYInFile = options["anchorPointY"]; - } - else - { - anchorPointYInFile = widget.getAnchorPoint().y; - } - - if (isAnchorPointXExists || isAnchorPointYExists) - { - widget.setAnchorPoint(cc.p(anchorPointXInFile, anchorPointYInFile)); - } - }, - - getResourcePath: function(path, texType){ - var filePath = ccs.uiReader.getFilePath(); - var imageFileName = path; - var imageFileName_tp; - if (null != imageFileName && 0 != "" != imageFileName) - { - if (texType == ccui.Widget.LOCAL_TEXTURE) { - imageFileName_tp = filePath + imageFileName; - } - else if(texType == ccui.Widget.PLIST_TEXTURE){ - imageFileName_tp = imageFileName; - } - else{ - cc.assert(0, "invalid TextureResType!!!"); - } - } - return imageFileName_tp; - } -}; \ No newline at end of file diff --git a/extensions/cocostudio/reader/widgetreader/WidgetReaderProtocol.js b/extensions/cocostudio/reader/widgetreader/WidgetReaderProtocol.js deleted file mode 100644 index 5c26a77bc6..0000000000 --- a/extensions/cocostudio/reader/widgetreader/WidgetReaderProtocol.js +++ /dev/null @@ -1,30 +0,0 @@ -/**************************************************************************** - 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.WidgetReaderProtocol = ccs.Class.extend({ - setPropsFromJsonDictionary: function(widget, options){ - - } -}); \ No newline at end of file From 7d476c5f74b4d817f04f25787dc441f2162817ea Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Wed, 7 Jan 2015 14:38:54 +0800 Subject: [PATCH 0094/1345] Issue #1267: Migrating ccui.Scale9Sprite --- .../ccui/base-classes/UIScale9Sprite.js | 427 ++++++++++++++++-- 1 file changed, 390 insertions(+), 37 deletions(-) diff --git a/extensions/ccui/base-classes/UIScale9Sprite.js b/extensions/ccui/base-classes/UIScale9Sprite.js index 027bdd9f83..c128b670c5 100644 --- a/extensions/ccui/base-classes/UIScale9Sprite.js +++ b/extensions/ccui/base-classes/UIScale9Sprite.js @@ -102,6 +102,46 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ _flippedX: false, _flippedY: false, + /** + * Constructor function. override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. + * @function + * @param {string|cc.SpriteFrame} file file name of texture or a SpriteFrame + * @param {cc.Rect} rect + * @param {cc.Rect} capInsets + * @returns {Scale9Sprite} + */ + ctor: function (file, rect, capInsets) { + cc.Node.prototype.ctor.call(this); + this._spriteRect = cc.rect(0, 0, 0, 0); + this._capInsetsInternal = cc.rect(0, 0, 0, 0); + + this._originalSize = cc.size(0, 0); + this._preferredSize = cc.size(0, 0); + this._capInsets = cc.rect(0, 0, 0, 0); + + this._topLeftSize = new cc.Size(0,0); + this._centerSize = new cc.Size(0,0); + this._bottomRightSize = new cc.Size(0,0); + this._centerOffset = new cc.Point(0,0); + + this._offset = new cc.Point(0,0); + this._protectedChildren = []; + + if(file != undefined){ + if(file instanceof cc.SpriteFrame) + this.initWithSpriteFrame(file, rect); + else{ + var frame = cc.spriteFrameCache.getSpriteFrame(file); + if(frame != null) + this.initWithSpriteFrame(frame, rect); + else + this.initWithFile(file, rect, capInsets); + } + }else{ + this.init(); + } + }, + /** * return texture is loaded * @returns {boolean} @@ -211,38 +251,6 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ locCenter.setPosition(leftWidth, bottomHeight); }, - /** - * Constructor function. override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. - * @function - * @param {string|cc.SpriteFrame} file file name of texture or a SpriteFrame - * @param {cc.Rect} rect - * @param {cc.Rect} capInsets - * @returns {Scale9Sprite} - */ - ctor: function (file, rect, capInsets) { - cc.Node.prototype.ctor.call(this); - this._spriteRect = cc.rect(0, 0, 0, 0); - this._capInsetsInternal = cc.rect(0, 0, 0, 0); - - this._originalSize = cc.size(0, 0); - this._preferredSize = cc.size(0, 0); - this._capInsets = cc.rect(0, 0, 0, 0); - - if(file != undefined){ - if(file instanceof cc.SpriteFrame) - this.initWithSpriteFrame(file, rect); - else{ - var frame = cc.spriteFrameCache.getSpriteFrame(file); - if(frame != null) - this.initWithSpriteFrame(frame, rect); - else - this.initWithFile(file, rect, capInsets); - } - }else{ - this.init(); - } - }, - getSprite: function () { return this._scale9Image; }, @@ -418,7 +426,7 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ * @returns {boolean} */ init: function () { - return this.initWithBatchNode(null, cc.rect(0, 0, 0, 0), false, cc.rect(0, 0, 0, 0)); + return this.initWithBatchNode(null, cc.rect(0, 0, 0, 0), false, cc.rect(0, 0, 0, 0)); //TODO }, /** @@ -429,7 +437,7 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ * @param {cc.Rect} [capInsets] * @returns {boolean} */ - initWithBatchNode: function (batchNode, rect, rotated, capInsets) { + initWithBatchNode: function (batchNode, rect, rotated, capInsets) { //TODO if (capInsets === undefined) { capInsets = rotated; rotated = false; @@ -642,7 +650,7 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ } // Set the given rect's size as original size - this._spriteRect = rect; + //this._spriteRect = rect; var locSpriteRect = this._spriteRect; locSpriteRect.x = rect.x; locSpriteRect.y = rect.y; @@ -931,9 +939,98 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ }, //todo: v3.3 - updateWithSprite: function(sprite, rect, rotated, offset, orginalSize, capInsets){ + updateWithSprite: function(sprite, rect, rotated, offset, originalSize, capInsets){ //virtual bool updateWithSprite(Sprite* sprite, const Rect& rect, bool rotated, const Rect& capInsets); //virtual bool updateWithSprite(Sprite* sprite, const Rect& rect, bool rotated, const Vec2 &offset, const Size &originalSize, const Rect& capInsets); + if(originalSize === undefined){ + capInsets = offset; + offset = new cc.Point(0,0); + originalSize = new cc.Size(rect.width, rect.height); + } + + var opacity = this.getOpacity(); + var color = this.getColor(); + + // Release old sprites + this._cleanupSlicedSprites(); + this._protectedChildren.length = 0; + + if(this._scale9Image != sprite) + this._scale9Image = sprite; + if (!this._scale9Image) + return false; + +/* var tmpTexture = batchNode.getTexture(); + var locLoaded = tmpTexture.isLoaded(); + this._textureLoaded = locLoaded; + if(!locLoaded){ + tmpTexture.addEventListener("load", function(sender){ + this._positionsAreDirty = true; + this.dispatchEvent("load"); + },this); + return true; + }*/ + + var locScale9Image = this._scale9Image; + var spriteFrame = locScale9Image.getSpriteFrame(); + if (!spriteFrame) + return false; + + var locCapInsets = this._capInsets; + if(capInsets) { + locCapInsets.x = capInsets.x; + locCapInsets.y = capInsets.y; + locCapInsets.width = capInsets.width; + locCapInsets.height = capInsets.height; + } + this._spriteFrameRotated = rotated; + + // If there is no given rect + if (cc._rectEqualToZero(rect)) { + // Get the texture size as original + var textureSize = locScale9Image.getTexture().getContentSize(); + rect = cc.rect(0, 0, textureSize.width, textureSize.height); + } + if(originalSize.width === 0 && originalSize.height === 0){ + originalSize.width = rect.width; + originalSize.height = rect.height; + } + + // Set the given rect's size as original size + var locSpriteRect = this._spriteRect; + locSpriteRect.x = rect.x; + locSpriteRect.y = rect.y; + locSpriteRect.width = rect.width; + locSpriteRect.height = rect.height; + + this._offset.x = offset.x; + this._offset.y = offset.y; + + this._originalSize.width = originalSize.width; + this._originalSize.height = originalSize.height; + + this._preferredSize.width = originalSize.width; + this._preferredSize.height = originalSize.height; + + var locCapInsetsInternal = this._capInsetsInternal; + if(capInsets){ + locCapInsetsInternal.x = capInsets.x; + locCapInsetsInternal.y = capInsets.y; + locCapInsetsInternal.width = capInsets.width; + locCapInsetsInternal.height = capInsets.height; + } + + if (this._scale9Enabled) + this._createSlicedSprites(); + this.setContentSize(originalSize); + + if (this._spritesGenerated){ + // Restore color and opacity + this.setOpacity(opacity); + this.setColor(color); + } + this._spritesGenerated = true; + return true; }, //virtual void setAnchorPoint(const Vec2& anchorPoint) override; @@ -1006,7 +1103,263 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ getScale: function(){}, - _createSlicedSprites: function(){}, + _intersectRect:function(first, second){ + var ret = cc.rect(Math.max(first.x,second.x), Math.max(first.y,second.y), 0,0); + var rightRealPoint = Math.min(first.x + first.width, second.x + second.width); + var bottomRealPoint = Math.min(first.y + first.height, second.y + second.height); + ret.width = Math.max(rightRealPoint - ret.x, 0.0); + ret.height = Math.max(bottomRealPoint - ret.y, 0.0); + return ret; + }, + + _createSlicedSprites: function(){ + var w = this._originalSize.width; + var h = this._originalSize.height; + + var offsetPosition = new cc.Point( + Math.ceil(this._offset.x + (this._originalSize.width - this._spriteRect.size.width) / 2), + Math.ceil(this._offset.y + (this._originalSize.height - this._spriteRect.size.height) / 2)); + + var locCapInsetsInternal = this._capInsetsInternal; + // If there is no specified center region + if ( cc._rectEqualToZero(locCapInsetsInternal)){ + // cc.log("... cap insets not specified : using default cap insets ..."); + locCapInsetsInternal.x = w / 3; + locCapInsetsInternal.y = h / 3; + locCapInsetsInternal.width = w / 3; + locCapInsetsInternal.height = h / 3; + } + + var originalRect; + if(this._spriteFrameRotated) + originalRect = cc.rect(this._spriteRect.x - offsetPosition.y, this._spriteRect.y - offsetPosition.x, this._originalSize.width, this._originalSize.height); + else + originalRect = cc.rect(this._spriteRect.x - offsetPosition.x, this._spriteRect.y - offsetPosition.y, this._originalSize.width, this._originalSize.height); + + var left_w = locCapInsetsInternal.x; + var center_w = locCapInsetsInternal.width; + var right_w = locCapInsetsInternal.width - (left_w + center_w); + + var top_h = locCapInsetsInternal.y; + var center_h = locCapInsetsInternal.height; + var bottom_h = originalRect.height - (top_h + center_h); + + // calculate rects + // ... top row + var x = 0.0; + var y = 0.0; + + var pixelRect = cc.rect(offsetPosition.x, offsetPosition.y, this._spriteRect.width, this._spriteRect.height); + + // top left + var lefttopboundsorig = cc.rect(x + 0.5 | 0, y + 0.5 | 0, left_w + 0.5 | 0, top_h + 0.5 | 0); + var lefttopbounds = lefttopboundsorig; + + // top center + x += left_w; + var centertopbounds = cc.rect(x + 0.5 | 0, y + 0.5 | 0, center_w + 0.5 | 0, top_h + 0.5 | 0); + + // top right + x += center_w; + var righttopbounds = cc.rect(x + 0.5 | 0, y + 0.5 | 0, right_w + 0.5 | 0, top_h + 0.5 | 0); + + // ... center row + x = 0.0; + y = 0.0; + y += top_h; + + // center left + var leftcenterbounds = cc.rect(x + 0.5 | 0, y + 0.5 | 0, left_w + 0.5 | 0, center_h + 0.5 | 0); + + // center center + x += left_w; + var centerboundsorig = cc.rect(x + 0.5 | 0, y + 0.5 | 0, center_w + 0.5 | 0, center_h + 0.5 | 0); + var centerbounds = centerboundsorig; + + // center right + x += center_w; + var rightcenterbounds = cc.rect(x + 0.5 | 0, y + 0.5 | 0, right_w + 0.5 | 0, center_h + 0.5 | 0); + + // ... bottom row + x = 0.0; + y = 0.0; + y += top_h; + y += center_h; + + // bottom left + var leftbottombounds = cc.rect(x + 0.5 | 0, y + 0.5 | 0, left_w + 0.5 | 0, bottom_h + 0.5 | 0); + + // bottom center + x += left_w; + var centerbottombounds = cc.rect(x + 0.5 | 0, y + 0.5 | 0, center_w + 0.5 | 0, bottom_h + 0.5 | 0); + + // bottom right + x += center_w; + var rightbottomboundsorig = cc.rect(x + 0.5 | 0, y + 0.5 | 0, right_w + 0.5 | 0, bottom_h + 0.5 | 0); + var rightbottombounds = rightbottomboundsorig; + + if((locCapInsetsInternal.x + locCapInsetsInternal.width) <= this._originalSize.width + || (locCapInsetsInternal.y + locCapInsetsInternal.height) <= this._originalSize.height) { + //in general case it is error but for legacy support we will check it + lefttopbounds = this._intersectRect(lefttopbounds, pixelRect); + centertopbounds = this._intersectRect(centertopbounds, pixelRect); + righttopbounds = this._intersectRect(righttopbounds, pixelRect); + leftcenterbounds = this._intersectRect(leftcenterbounds, pixelRect); + centerbounds = this._intersectRect(centerbounds, pixelRect); + rightcenterbounds = this._intersectRect(rightcenterbounds, pixelRect); + leftbottombounds = this._intersectRect(leftbottombounds, pixelRect); + centerbottombounds = this._intersectRect(centerbottombounds, pixelRect); + rightbottombounds = this._intersectRect(rightbottombounds, pixelRect); + } else + cc.log("Scale9Sprite capInsetsInternal > originalSize"); //it is error but for legacy turn off clip system + + var rotatedlefttopboundsorig = lefttopboundsorig; + var rotatedcenterboundsorig = centerboundsorig; + var rotatedrightbottomboundsorig = rightbottomboundsorig; + + var rotatedcenterbounds = centerbounds; + var rotatedrightbottombounds = rightbottombounds; + var rotatedleftbottombounds = leftbottombounds; + var rotatedrighttopbounds = righttopbounds; + var rotatedlefttopbounds = lefttopbounds; + var rotatedrightcenterbounds = rightcenterbounds; + var rotatedleftcenterbounds = leftcenterbounds; + var rotatedcenterbottombounds = centerbottombounds; + var rotatedcentertopbounds = centertopbounds; + + var t = cc.affineTransformMakeIdentity(); + if (!this._spriteFrameRotated) { + //TODO + t = cc.affineTransformTranslate(t, originalRect.x, originalRect.y); + + rotatedlefttopboundsorig = RectApplyAffineTransform(rotatedlefttopboundsorig, t); + rotatedcenterboundsorig = RectApplyAffineTransform(rotatedcenterboundsorig, t); + rotatedrightbottomboundsorig = RectApplyAffineTransform(rotatedrightbottomboundsorig, t); + + rotatedcenterbounds = RectApplyAffineTransform(rotatedcenterbounds, t); + rotatedrightbottombounds = RectApplyAffineTransform(rotatedrightbottombounds, t); + rotatedleftbottombounds = RectApplyAffineTransform(rotatedleftbottombounds, t); + rotatedrighttopbounds = RectApplyAffineTransform(rotatedrighttopbounds, t); + rotatedlefttopbounds = RectApplyAffineTransform(rotatedlefttopbounds, t); + rotatedrightcenterbounds = RectApplyAffineTransform(rotatedrightcenterbounds, t); + rotatedleftcenterbounds = RectApplyAffineTransform(rotatedleftcenterbounds, t); + rotatedcenterbottombounds = RectApplyAffineTransform(rotatedcenterbottombounds, t); + rotatedcentertopbounds = RectApplyAffineTransform(rotatedcentertopbounds, t); + } else { + // set up transformation of coordinates + // to handle the case where the sprite is stored rotated + // in the spritesheet + // log("rotated"); + t = cc.affineTransformTranslate(t, originalRect.height+originalRect.x, originalRect.y); + t = cc.affineTransformRotate(t, 1.57079633); + + lefttopboundsorig = RectApplyAffineTransform(lefttopboundsorig, t); + centerboundsorig = RectApplyAffineTransform(centerboundsorig, t); + rightbottomboundsorig = RectApplyAffineTransform(rightbottomboundsorig, t); + + centerbounds = RectApplyAffineTransform(centerbounds, t); + rightbottombounds = RectApplyAffineTransform(rightbottombounds, t); + leftbottombounds = RectApplyAffineTransform(leftbottombounds, t); + righttopbounds = RectApplyAffineTransform(righttopbounds, t); + lefttopbounds = RectApplyAffineTransform(lefttopbounds, t); + rightcenterbounds = RectApplyAffineTransform(rightcenterbounds, t); + leftcenterbounds = RectApplyAffineTransform(leftcenterbounds, t); + centerbottombounds = RectApplyAffineTransform(centerbottombounds, t); + centertopbounds = RectApplyAffineTransform(centertopbounds, t); + + rotatedlefttopboundsorig.origin = lefttopboundsorig.origin; + rotatedcenterboundsorig.origin = centerboundsorig.origin; + rotatedrightbottomboundsorig.origin = rightbottomboundsorig.origin; + + rotatedcenterbounds.origin = centerbounds.origin; + rotatedrightbottombounds.origin = rightbottombounds.origin; + rotatedleftbottombounds.origin = leftbottombounds.origin; + rotatedrighttopbounds.origin = righttopbounds.origin; + rotatedlefttopbounds.origin = lefttopbounds.origin; + rotatedrightcenterbounds.origin = rightcenterbounds.origin; + rotatedleftcenterbounds.origin = leftcenterbounds.origin; + rotatedcenterbottombounds.origin = centerbottombounds.origin; + rotatedcentertopbounds.origin = centertopbounds.origin; + } + + this._topLeftSize.width = rotatedlefttopboundsorig.width; + this._topLeftSize.height = rotatedlefttopboundsorig.height; + this._centerSize.width = rotatedcenterboundsorig.width; + this._centerSize.height = rotatedcenterboundsorig.height; + this._bottomRightSize.width = rotatedrightbottomboundsorig.width; + this._bottomRightSize.height = rotatedrightbottomboundsorig.height; + + if(this._spriteFrameRotated){ + this._centerOffset.x = -(rotatedcenterboundsorig.y + rotatedcenterboundsorig.width/2)- (rotatedcenterbounds.y + rotatedcenterbounds.width/2); + this._centerOffset.y = (rotatedcenterbounds.x + rotatedcenterbounds.height/2) - (rotatedcenterboundsorig.x + rotatedcenterboundsorig.height/2); + } else { + this._centerOffset.x = (rotatedcenterbounds.x + rotatedcenterbounds.width/2) - (rotatedcenterboundsorig.x + rotatedcenterboundsorig.width/2); + this._centerOffset.y = (rotatedcenterboundsorig.y + rotatedcenterboundsorig.height/2)- (rotatedcenterbounds.y + rotatedcenterbounds.height/2); + } + + // Centre + if(rotatedcenterbounds.width > 0 && rotatedcenterbounds.height > 0 ) { + this._centre = new cc.Sprite(); + this._centre.initWithTexture(this._scale9Image.getTexture(), rotatedcenterbounds, this._spriteFrameRotated); + this.addProtectedChild(this._centre); + } + + // Top + if(rotatedcentertopbounds.width > 0 && rotatedcentertopbounds.height > 0 ) { + this._top = new cc.Sprite(); + this._top.initWithTexture(this._scale9Image.getTexture(), rotatedcentertopbounds, this._spriteFrameRotated); + this.addProtectedChild(this._top); + } + + // Bottom + if(rotatedcenterbottombounds.width > 0 && rotatedcenterbottombounds.height > 0 ) { + this._bottom = new cc.Sprite(); + this._bottom.initWithTexture(this._scale9Image.getTexture(), rotatedcenterbottombounds, this._spriteFrameRotated); + this.addProtectedChild(this._bottom); + } + + // Left + if(rotatedleftcenterbounds.width > 0 && rotatedleftcenterbounds.height > 0 ) { + this._left = new cc.Sprite(); + this._left.initWithTexture(this._scale9Image.getTexture(), rotatedleftcenterbounds, this._spriteFrameRotated); + this.addProtectedChild(this._left); + } + + // Right + if(rotatedrightcenterbounds.width > 0 && rotatedrightcenterbounds.height > 0 ) { + this._right = new cc.Sprite(); + this._right.initWithTexture(this._scale9Image.getTexture(), rotatedrightcenterbounds, this._spriteFrameRotated); + this.addProtectedChild(this._right); + } + + // Top left + if(rotatedlefttopbounds.width > 0 && rotatedlefttopbounds.height > 0 ) { + this._topLeft = new cc.Sprite(); + this._topLeft.initWithTexture(this._scale9Image.getTexture(), rotatedlefttopbounds, this._spriteFrameRotated); + this.addProtectedChild(this._topLeft); + } + + // Top right + if(rotatedrighttopbounds.width > 0 && rotatedrighttopbounds.height > 0 ) { + this._topRight = new cc.Sprite(); + this._topRight.initWithTexture(this._scale9Image.getTexture(), rotatedrighttopbounds, this._spriteFrameRotated); + this.addProtectedChild(this._topRight); + } + + // Bottom left + if(rotatedleftbottombounds.width > 0 && rotatedleftbottombounds.height > 0 ) { + this._bottomLeft = new cc.Sprite(); + this._bottomLeft.initWithTexture(this._scale9Image.getTexture(), rotatedleftbottombounds, this._spriteFrameRotated); + this.addProtectedChild(this._bottomLeft); + } + + // Bottom right + if(rotatedrightbottombounds.width > 0 && rotatedrightbottombounds.height > 0 ) { + this._bottomRight = new cc.Sprite(); + this._bottomRight.initWithTexture(this._scale9Image.getTexture(), rotatedrightbottombounds, this._spriteFrameRotated); + this.addProtectedChild(this._bottomRight); + } + }, _cleanupSlicedSprites: function(){ if (this._topLeft && this._topLeft.isRunning()) From 36bf522152f8c099943fa09084c6f1da088f45a9 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 7 Jan 2015 15:30:04 +0800 Subject: [PATCH 0095/1345] Issue #2563: add deprecated --- extensions/cocostudio/loader/parsers/compatible.js | 1 + 1 file changed, 1 insertion(+) diff --git a/extensions/cocostudio/loader/parsers/compatible.js b/extensions/cocostudio/loader/parsers/compatible.js index 4a91c56ab0..02a6ea00fe 100644 --- a/extensions/cocostudio/loader/parsers/compatible.js +++ b/extensions/cocostudio/loader/parsers/compatible.js @@ -25,6 +25,7 @@ /* This file is for compatibility compatibility with older versions of GUIReader and SceneReader + todo: deprecated all */ (function(){ From f0c69dcade6a40bde6b993e5805697ae8b2f64f0 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Wed, 7 Jan 2015 15:50:55 +0800 Subject: [PATCH 0096/1345] Fixed #1281: fixed a bug of ccs.Armature that ccs.Bone's setOpacity and setColor doesn't work. --- .../armature/CCArmatureCanvasRenderCmd.js | 16 ++++++++-- .../armature/CCArmatureWebGLRenderCmd.js | 17 +++++++++-- extensions/cocostudio/armature/CCBone.js | 30 ++++--------------- 3 files changed, 32 insertions(+), 31 deletions(-) diff --git a/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js b/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js index 0c6b363092..ce1dd9b250 100644 --- a/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js +++ b/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js @@ -70,14 +70,24 @@ ccs.Node.CanvasRenderCmd.prototype.transform.call(this, parentCmd, recursive); var locChildren = this._node._children; - window.allBones = locChildren; 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){ - selNode._renderCmd.transform(null); //must be null, use transform in armature mode + 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 flags = cc.Node._dirtyFlags, locFlag = cmd._dirtyFlag; + var colorDirty = locFlag & flags.colorDirty, + opacityDirty = locFlag & flags.opacityDirty; + if(colorDirty) + cmd._updateDisplayColor(); + if(opacityDirty) + cmd._updateDisplayOpacity(); + if(colorDirty || opacityDirty) + cmd._updateColor(); } } } diff --git a/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js b/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js index f405d461e4..d6991691cb 100644 --- a/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js +++ b/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js @@ -50,15 +50,13 @@ 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); //because skin didn't call visit() selNode.updateTransform(); var func = selBone.getBlendFunc(); @@ -100,6 +98,19 @@ this._shaderProgram = shaderProgram; }; + proto._updateColorAndOpacity = function(skinRenderCmd){ + //update displayNode's color and opacity + var flags = cc.Node._dirtyFlags, locFlag = skinRenderCmd._dirtyFlag; + var colorDirty = locFlag & flags.colorDirty, + opacityDirty = locFlag & flags.opacityDirty; + if(colorDirty) + skinRenderCmd._updateDisplayColor(); + if(opacityDirty) + skinRenderCmd._updateDisplayOpacity(); + if(colorDirty || opacityDirty) + skinRenderCmd._updateColor(); + }; + proto.updateChildPosition = function(ctx, dis, selBone, alphaPremultiplied, alphaNonPremultipled){ var node = this._node; dis.updateTransform(); diff --git a/extensions/cocostudio/armature/CCBone.js b/extensions/cocostudio/armature/CCBone.js index 84f5f78805..eb4bdff222 100644 --- a/extensions/cocostudio/armature/CCBone.js +++ b/extensions/cocostudio/armature/CCBone.js @@ -237,39 +237,19 @@ ccs.Bone = ccs.Node.extend(/** @lends ccs.Bone# */{ } }, - /** - * Updates display color - * @override - * @param {cc.Color} color - */ - updateDisplayedColor: function (color) { - this._realColor = cc.color(255, 255, 255); - cc.Node.prototype.updateDisplayedColor.call(this, color); - this.updateColor(); - }, - - /** - * Updates display opacity - * @param {Number} opacity - */ - updateDisplayedOpacity: function (opacity) { - this._realOpacity = 255; - cc.Node.prototype.updateDisplayedOpacity.call(this, opacity); - this.updateColor(); - }, - /** * Updates display color */ updateColor: function () { var display = this._displayManager.getDisplayRenderNode(); if (display != null) { + var cmd = this._renderCmd; display.setColor( cc.color( - this._displayedColor.r * this._tweenData.r / 255, - this._displayedColor.g * this._tweenData.g / 255, - this._displayedColor.b * this._tweenData.b / 255)); - display.setOpacity(this._displayedOpacity * this._tweenData.a / 255); + cmd._displayedColor.r * this._tweenData.r / 255, + cmd._displayedColor.g * this._tweenData.g / 255, + cmd._displayedColor.b * this._tweenData.b / 255)); + display.setOpacity(cmd._displayedOpacity * this._tweenData.a / 255); } }, From fc7a104bb175d31ba794f6c802c71ad7d032bb4a Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Wed, 7 Jan 2015 16:29:38 +0800 Subject: [PATCH 0097/1345] Fixed #1281: fixed a bug of ccs.Armature that ccs.Bone's setOpacity and setColor doesn't work --- .../cocostudio/armature/CCArmatureCanvasRenderCmd.js | 7 +++---- .../cocostudio/armature/CCArmatureWebGLRenderCmd.js | 9 +++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js b/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js index ce1dd9b250..ac491c13ba 100644 --- a/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js +++ b/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js @@ -79,15 +79,14 @@ 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(); + cmd._updateDisplayColor(parentColor); if(opacityDirty) - cmd._updateDisplayOpacity(); - if(colorDirty || opacityDirty) - cmd._updateColor(); + cmd._updateDisplayOpacity(parentOpacity); } } } diff --git a/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js b/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js index d6991691cb..42985ca1e0 100644 --- a/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js +++ b/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js @@ -56,7 +56,7 @@ switch (selBone.getDisplayRenderNodeType()) { case ccs.DISPLAY_TYPE_SPRITE: if (selNode instanceof ccs.Skin) { - this._updateColorAndOpacity(selNode._renderCmd); //because skin didn't call visit() + this._updateColorAndOpacity(selNode._renderCmd, selBone); //because skin didn't call visit() selNode.updateTransform(); var func = selBone.getBlendFunc(); @@ -98,15 +98,16 @@ this._shaderProgram = shaderProgram; }; - proto._updateColorAndOpacity = function(skinRenderCmd){ + 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(); + skinRenderCmd._updateDisplayColor(parentColor); if(opacityDirty) - skinRenderCmd._updateDisplayOpacity(); + skinRenderCmd._updateDisplayOpacity(parentOpacity); if(colorDirty || opacityDirty) skinRenderCmd._updateColor(); }; From a613e346f86b0a111aebe994a922785cd9b7aa51 Mon Sep 17 00:00:00 2001 From: jianglong0156 Date: Wed, 7 Jan 2015 16:43:05 +0800 Subject: [PATCH 0098/1345] issue #1272: fix the bug , test case need to improve. --- cocos2d/labels/CCLabelBMFont.js | 232 +++++++++++++++----------------- 1 file changed, 112 insertions(+), 120 deletions(-) diff --git a/cocos2d/labels/CCLabelBMFont.js b/cocos2d/labels/CCLabelBMFont.js index 2d7335122e..03376e3605 100644 --- a/cocos2d/labels/CCLabelBMFont.js +++ b/cocos2d/labels/CCLabelBMFont.js @@ -432,143 +432,135 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ this.setString(label, true); }, - /** - * Update Label.
- * Update this Label display string and more... - */ - updateLabel: function () { + // 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; - self.string = self._initialString; + var text = strArr[i]; + var curLength = 0; + for (var strArrIndex = 0; strArrIndex < i; strArrIndex++) + { + curLength += strArr[strArrIndex].length; + } - // Step 1: Make multiline - if (self._width > 0) { - var stringLength = self._string.length; - var multiline_string = []; - var last_word = []; + curLength = curLength + i - initStringWrapNum; // add the wrap line num - var line = 1, i = 0, start_line = false, start_word = false, startOfLine = -1, startOfWord = -1, skip = 0; + var allWidth = self._getCharsWidth(curLength, strArr[i].length - 1); - var characterSprite; - for (var j = 0, lj = self._children.length; j < lj; j++) { - var justSkipped = 0; - while (!(characterSprite = self.getChildByTag(j + skip + justSkipped))) - justSkipped++; - skip += justSkipped; + 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; - if (i >= stringLength) - break; + //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); + } - var character = self._string[i]; - if (!start_word) { - startOfWord = self._getLetterPosXLeft(characterSprite); - start_word = true; + 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 (!start_line) { - startOfLine = startOfWord; - start_line = true; + if (self._lineBreakWithoutSpaces) { + pushNum = 0; } + fuzzyLen = fuzzyLen + pushNum; + tmpText = text.substr(fuzzyLen); + width = allWidth - this._getCharsWidth(curLength + fuzzyLen, tmpText.length - 1); + } - // Newline. - if (character.charCodeAt(0) == 10) { - last_word.push('\n'); - multiline_string = multiline_string.concat(last_word); - last_word.length = 0; - start_word = false; - start_line = false; - startOfWord = -1; - startOfLine = -1; - //i+= justSkipped; - j--; - skip -= justSkipped; - line++; - - if (i >= stringLength) - break; - - character = self._string[i]; - if (!startOfWord) { - startOfWord = self._getLetterPosXLeft(characterSprite); - start_word = true; - } - if (!startOfLine) { - startOfLine = startOfWord; - start_line = true; + 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; } - i++; - continue; - } + fuzzyLen -= pushNum; - // Whitespace. - if (this._isspace_unicode(character)) { - last_word.push(character); - multiline_string = multiline_string.concat(last_word); - last_word.length = 0; - start_word = false; - startOfWord = -1; - i++; - continue; + sLine = text.substr(fuzzyLen); + sText = text.substr(0, fuzzyLen); } + } - // Out of bounds. - if (self._getLetterPosXRight(characterSprite) - startOfLine > self._width) { - if (!self._lineBreakWithoutSpaces) { - last_word.push(character); - - var found = multiline_string.lastIndexOf(" "); - if (found != -1) - this._utf8_trim_ws(multiline_string); - else - multiline_string = []; - - if (multiline_string.length > 0) - multiline_string.push('\n'); - - line++; - start_line = false; - startOfLine = -1; - i++; - } else { - this._utf8_trim_ws(last_word); - - last_word.push('\n'); - multiline_string = multiline_string.concat(last_word); - last_word.length = 0; - start_word = false; - start_line = false; - startOfWord = -1; - startOfLine = -1; - line++; - - if (i >= stringLength) - break; - - if (!startOfWord) { - startOfWord = self._getLetterPosXLeft(characterSprite); - start_word = true; - } - if (!startOfLine) { - startOfLine = startOfWord; - start_line = true; - } - j--; + //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; } - } else { - // Character is normal. - last_word.push(character); - i++; + fuzzyLen -= pushNum; + sLine = text.substr(fuzzyLen); + sText = text.substr(0, fuzzyLen); } } + strArr[i] = sLine || tmpText; + strArr.splice(i, 0, sText); + } + }, - multiline_string = multiline_string.concat(last_word); - var len = multiline_string.length; - var str_new = ""; - - for (i = 0; i < len; ++i) - str_new += multiline_string[i]; - - str_new = str_new + String.fromCharCode(0); - //this.updateString(true); - self._setString(str_new, false) + /** + * Update Label.
+ * Update this Label display string and more... + */ + updateLabel: function () { + var self = this; + self.string = self._initialString; + // 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, 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 From b1e52f911e0715637fea9a24be09f50745419fa2 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 7 Jan 2015 16:48:54 +0800 Subject: [PATCH 0099/1345] Issue #2563: modify condition to judgment the scene file --- extensions/cocostudio/loader/load.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/cocostudio/loader/load.js b/extensions/cocostudio/loader/load.js index d1a09cbcb2..bf2bee9544 100644 --- a/extensions/cocostudio/loader/load.js +++ b/extensions/cocostudio/loader/load.js @@ -48,7 +48,7 @@ ccs._load = (function(){ parse = parser["timeline"]; else if(json["Content"] && json["Content"]["Content"]) parse = parser["timeline"]; - else if(json["gameobjects"] && json["Triggers"]) + else if(json["gameobjects"]) parse = parser["scene"]; }else{ parse = parser[type]; From f77c5c83b68cb0ea1707a12c725284bbc67161e6 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 7 Jan 2015 17:30:52 +0800 Subject: [PATCH 0100/1345] Fix atlas _shaderProgram is not init --- cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js b/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js index 1d358bc78c..d398f20eef 100644 --- a/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js +++ b/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js @@ -33,6 +33,10 @@ this._colorUnmodified = cc.color.WHITE; this._colorF32Array = null; this._uniformColor = null; + + //shader stuff + this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURE_UCOLOR); + this._uniformColor = cc._renderContext.getUniformLocation(this._shaderProgram.getProgram(), "u_color"); }; var proto = cc.AtlasNode.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype); @@ -52,8 +56,7 @@ proto.rendering = function (ctx) { var context = ctx || cc._renderContext, node = this._node; - if(!this._shaderProgram) - return; + this._shaderProgram.use(); this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix); @@ -89,9 +92,6 @@ this._calculateMaxItems(); node.quadsToDraw = itemsToRender; - //shader stuff - this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURE_UCOLOR); - this._uniformColor = cc._renderContext.getUniformLocation(node.shaderProgram.getProgram(), "u_color"); return true; }; From 667819abcc12bfc498bea2b9ac1dc5e202cb3012 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 7 Jan 2015 17:37:08 +0800 Subject: [PATCH 0101/1345] Issue #2563: Modify access version number --- extensions/cocostudio/loader/parsers/timelineParser-1.x.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-1.x.js b/extensions/cocostudio/loader/parsers/timelineParser-1.x.js index aadd9323e9..f4cbe3d9c3 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-1.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-1.x.js @@ -225,7 +225,7 @@ } return tmx; }; - var uiParser = load.getParser("ccui")["1.*"]; + var uiParser = load.getParser("ccui")["*"]; parser.initWidget = function(options, resourcePath){ var type = options["classname"]; From e5e3d69d3564a3349be26ca54ae50e464343a024 Mon Sep 17 00:00:00 2001 From: jianglong0156 Date: Wed, 7 Jan 2015 18:16:17 +0800 Subject: [PATCH 0102/1345] issue #1272: fix a render bug in canvas mode --- cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js b/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js index 4920171d6a..211932df4e 100644 --- a/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js +++ b/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js @@ -70,7 +70,7 @@ proto.setTexture = function (texture) { var node = this._node; var locChildren = node._children; - var locDisplayedColor = node._displayedColor; + var locDisplayedColor = this._displayedColor; for (var i = 0; i < locChildren.length; i++) { var selChild = locChildren[i]; var cm = selChild._renderCmd; From a3be2b52d9f4d0385067b1ccf805179235c028f9 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 8 Jan 2015 11:51:14 +0800 Subject: [PATCH 0103/1345] Issue #2563: fix parse armature error --- extensions/cocostudio/loader/load.js | 1 + .../loader/parsers/timelineParser-2.x.js | 31 +++++++++++++++++-- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/extensions/cocostudio/loader/load.js b/extensions/cocostudio/loader/load.js index bf2bee9544..4d4dd8ca29 100644 --- a/extensions/cocostudio/loader/load.js +++ b/extensions/cocostudio/loader/load.js @@ -181,6 +181,7 @@ ccs.load = function(file){ object.action = ccs._load(file, "action"); }catch(error){ cc.log("ccs.load has encountered some problems"); + cc.log(error); } return object; }; diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index d98a52a06b..62d87ff1a1 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -1058,6 +1058,15 @@ } }; + var getFileName = function(name){ + if(!name) return ""; + var arr = name.match(/([^\/]+)\.[^\/]+$/); + if(arr && arr[1]) + return arr[1]; + else + return ""; + }; + /** * Armature * @param json @@ -1067,16 +1076,32 @@ var node = new ccs.Armature(); - var isLoop = json["isLoop"]; + var isLoop = json["IsLoop"]; var isAutoPlay = json["IsAutoPlay"]; var currentAnimationName = json["CurrentAnimationName"]; loadTexture(json["FileData"], resourcePath, function(path, type){ - ccs.ArmatureDataManager.addArmatureFileInfo(path); + var plists, pngs; + var armJson = cc.loader.getRes(path); + if(!armJson) + cc.log("%s need to pre load", path); + else{ + plists = armJson["config_file_path"]; + pngs = armJson["config_png_path"]; + plists.forEach(function(plist, index){ + if(pngs[index]) + cc.spriteFrameCache.addSpriteFrame(plist, pngs[index]); + }); + } + ccs.armatureDataManager.addArmatureFileInfo(path); + node.init(getFileName(path)); + if(isAutoPlay) + node.getAnimation().play(currentAnimationName, -1, isLoop); + }); - node.init(); + return node; }; var loadedPlist = {}; From 3e5142f818b860c9a319a52191d92e78af55431f Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 8 Jan 2015 14:21:24 +0800 Subject: [PATCH 0104/1345] Event callback error and Remove try/catch for ccs.load --- cocos2d/core/event-manager/CCEventManager.js | 4 +++- cocos2d/core/sprites/CCSprite.js | 2 -- extensions/cocostudio/loader/load.js | 11 ++++------- 3 files changed, 7 insertions(+), 10 deletions(-) diff --git a/cocos2d/core/event-manager/CCEventManager.js b/cocos2d/core/event-manager/CCEventManager.js index 6fd0512f68..f827944f7c 100644 --- a/cocos2d/core/event-manager/CCEventManager.js +++ b/cocos2d/core/event-manager/CCEventManager.js @@ -944,7 +944,9 @@ cc.EventHelper.prototype = { addEventListener: function ( type, listener, target ) { //check 'type' status, if the status is ready, dispatch event next frame if(type === "load" && this._textureLoaded){ //only load event checked. - setTimeout(listener.call(target), 0); + setTimeout(function(){ + listener.call(target); + }, 0); return; } diff --git a/cocos2d/core/sprites/CCSprite.js b/cocos2d/core/sprites/CCSprite.js index 8c7f1abf23..5237ab85bf 100644 --- a/cocos2d/core/sprites/CCSprite.js +++ b/cocos2d/core/sprites/CCSprite.js @@ -129,7 +129,6 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ self._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST}; self._rect = cc.rect(0, 0, 0, 0); - self._textureLoaded = true; self._softInit(fileName, rect, rotated); }, @@ -625,7 +624,6 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ _t._blendFunc.dst = cc.BLEND_DST; _t.texture = null; - _t._textureLoaded = true; _t._flippedX = _t._flippedY = false; // default transform anchor: center diff --git a/extensions/cocostudio/loader/load.js b/extensions/cocostudio/loader/load.js index 4d4dd8ca29..a8dfc5c5fa 100644 --- a/extensions/cocostudio/loader/load.js +++ b/extensions/cocostudio/loader/load.js @@ -168,6 +168,7 @@ ccs._parser = cc.Class.extend({ * ui 1.* * node 1.* - 2.* * action 1.* - 2.* + * scene 0.* - 1.* * @param {String} file * @returns {{node: cc.Node, action: cc.Action}} */ @@ -176,13 +177,9 @@ ccs.load = function(file){ node: null, action: null }; - try{ - object.node = ccs._load(file); - object.action = ccs._load(file, "action"); - }catch(error){ - cc.log("ccs.load has encountered some problems"); - cc.log(error); - } + + object.node = ccs._load(file); + object.action = ccs._load(file, "action"); return object; }; From 912ed01752ece4a6bebda33fee595789af544bcc Mon Sep 17 00:00:00 2001 From: jianglong0156 Date: Thu, 8 Jan 2015 14:50:55 +0800 Subject: [PATCH 0105/1345] fixed #1284: It's need to add scale parm when calc word wrap --- cocos2d/labels/CCLabelBMFont.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/labels/CCLabelBMFont.js b/cocos2d/labels/CCLabelBMFont.js index 03376e3605..0b5169d090 100644 --- a/cocos2d/labels/CCLabelBMFont.js +++ b/cocos2d/labels/CCLabelBMFont.js @@ -548,7 +548,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ var oldArrLength = 0; for (i = 0; i < stringArr.length; i++) { oldArrLength = stringArr.length; - this._checkWarp(stringArr, i, self._width, newWrapNum); + this._checkWarp(stringArr, i, self._width * this._scaleX, newWrapNum); if (oldArrLength < stringArr.length) { newWrapNum++; From 8cdfe00a2580de43433e7e30dccc7ae0c2494fa9 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 8 Jan 2015 14:56:58 +0800 Subject: [PATCH 0106/1345] LabelTTF add _textureLoaded = true --- cocos2d/core/labelttf/CCLabelTTF.js | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos2d/core/labelttf/CCLabelTTF.js b/cocos2d/core/labelttf/CCLabelTTF.js index 39874b8be6..e9847c0fe7 100644 --- a/cocos2d/core/labelttf/CCLabelTTF.js +++ b/cocos2d/core/labelttf/CCLabelTTF.js @@ -164,6 +164,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ this._lineWidths = []; this._renderCmd._setColorsString(); + this._textureLoaded = true; if (fontName && fontName instanceof cc.FontDefinition) { this.initWithStringAndTextDefinition(text, fontName); From 56cebd8cd123ad198097825398618ec24e922ee4 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Thu, 8 Jan 2015 15:49:59 +0800 Subject: [PATCH 0107/1345] Issue #1267: revert ccui.Scale9Sprite, because WebGL renderer doesn't support auto-batch --- cocos2d/core/support/CCPointExtension.js | 3 +- .../ccui/base-classes/UIScale9Sprite.js | 562 ++---------------- 2 files changed, 48 insertions(+), 517 deletions(-) diff --git a/cocos2d/core/support/CCPointExtension.js b/cocos2d/core/support/CCPointExtension.js index 3ec17e3d2e..db74da1001 100644 --- a/cocos2d/core/support/CCPointExtension.js +++ b/cocos2d/core/support/CCPointExtension.js @@ -204,7 +204,8 @@ cc.pDistance = function (v1, v2) { * @return {cc.Point} */ cc.pNormalize = function (v) { - return cc.pMult(v, 1.0 / cc.pLength(v)); + var n = cc.pLength(v); + return n === 0 ? cc.p(v) : cc.pMult(v, 1.0 / n); }; /** diff --git a/extensions/ccui/base-classes/UIScale9Sprite.js b/extensions/ccui/base-classes/UIScale9Sprite.js index c128b670c5..c49a2affcc 100644 --- a/extensions/ccui/base-classes/UIScale9Sprite.js +++ b/extensions/ccui/base-classes/UIScale9Sprite.js @@ -68,6 +68,10 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ _bottomRight: null, //cache in canvas on Canvas mode + _cacheSprite: null, + _cacheCanvas: null, + _cacheContext: null, + _cacheTexture: null, _scale9Dirty: true, _opacityModifyRGB: false, @@ -87,61 +91,6 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ _textureLoaded:false, _className:"Scale9Sprite", - //v3.3 - _scale9Enabled: false, - _topLeftSize: null, - _centerSize: null, - _bottomRightSize: null, - _centerOffset: null, - - _offset: null, - - _protectedChildren: null, - _reorderProtectedChildDirty: false, - - _flippedX: false, - _flippedY: false, - - /** - * Constructor function. override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. - * @function - * @param {string|cc.SpriteFrame} file file name of texture or a SpriteFrame - * @param {cc.Rect} rect - * @param {cc.Rect} capInsets - * @returns {Scale9Sprite} - */ - ctor: function (file, rect, capInsets) { - cc.Node.prototype.ctor.call(this); - this._spriteRect = cc.rect(0, 0, 0, 0); - this._capInsetsInternal = cc.rect(0, 0, 0, 0); - - this._originalSize = cc.size(0, 0); - this._preferredSize = cc.size(0, 0); - this._capInsets = cc.rect(0, 0, 0, 0); - - this._topLeftSize = new cc.Size(0,0); - this._centerSize = new cc.Size(0,0); - this._bottomRightSize = new cc.Size(0,0); - this._centerOffset = new cc.Point(0,0); - - this._offset = new cc.Point(0,0); - this._protectedChildren = []; - - if(file != undefined){ - if(file instanceof cc.SpriteFrame) - this.initWithSpriteFrame(file, rect); - else{ - var frame = cc.spriteFrameCache.getSpriteFrame(file); - if(frame != null) - this.initWithSpriteFrame(frame, rect); - else - this.initWithFile(file, rect, capInsets); - } - }else{ - this.init(); - } - }, - /** * return texture is loaded * @returns {boolean} @@ -251,6 +200,38 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ locCenter.setPosition(leftWidth, bottomHeight); }, + /** + * Constructor function. override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. + * @function + * @param {string|cc.SpriteFrame} file file name of texture or a SpriteFrame + * @param {cc.Rect} rect + * @param {cc.Rect} capInsets + * @returns {Scale9Sprite} + */ + ctor: function (file, rect, capInsets) { + cc.Node.prototype.ctor.call(this); + this._spriteRect = cc.rect(0, 0, 0, 0); + this._capInsetsInternal = cc.rect(0, 0, 0, 0); + + this._originalSize = cc.size(0, 0); + this._preferredSize = cc.size(0, 0); + this._capInsets = cc.rect(0, 0, 0, 0); + + if(file != undefined){ + if(file instanceof cc.SpriteFrame) + this.initWithSpriteFrame(file, rect); + else{ + var frame = cc.spriteFrameCache.getSpriteFrame(file); + if(frame != null) + this.initWithSpriteFrame(frame, rect); + else + this.initWithFile(file, rect, capInsets); + } + }else{ + this.init(); + } + }, + getSprite: function () { return this._scale9Image; }, @@ -426,7 +407,7 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ * @returns {boolean} */ init: function () { - return this.initWithBatchNode(null, cc.rect(0, 0, 0, 0), false, cc.rect(0, 0, 0, 0)); //TODO + return this.initWithBatchNode(null, cc.rect(0, 0, 0, 0), false, cc.rect(0, 0, 0, 0)); }, /** @@ -437,7 +418,7 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ * @param {cc.Rect} [capInsets] * @returns {boolean} */ - initWithBatchNode: function (batchNode, rect, rotated, capInsets) { //TODO + initWithBatchNode: function (batchNode, rect, rotated, capInsets) { if (capInsets === undefined) { capInsets = rotated; rotated = false; @@ -540,8 +521,8 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ * to resize the sprite will all it's 9-slice goodness interact. * It respects the anchorPoint too. * - * @param {String} spriteFrameName The sprite frame name. - * @param {cc.Rect} capInsets The values to use for the cap insets. + * @param spriteFrameName The sprite frame name. + * @param capInsets The values to use for the cap insets. */ initWithSpriteFrameName: function (spriteFrameName, capInsets) { if(!spriteFrameName) @@ -558,12 +539,11 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ }, /** - *

- * 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
+ * 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 {cc.Rect} capInsets The values to use for the cap insets. */ resizableSpriteWithCapInsets: function (capInsets) { @@ -650,7 +630,7 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ } // Set the given rect's size as original size - //this._spriteRect = rect; + this._spriteRect = rect; var locSpriteRect = this._spriteRect; locSpriteRect.x = rect.x; locSpriteRect.y = rect.y; @@ -938,456 +918,6 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ this._insetBottom = 0; }, - //todo: v3.3 - updateWithSprite: function(sprite, rect, rotated, offset, originalSize, capInsets){ - //virtual bool updateWithSprite(Sprite* sprite, const Rect& rect, bool rotated, const Rect& capInsets); - //virtual bool updateWithSprite(Sprite* sprite, const Rect& rect, bool rotated, const Vec2 &offset, const Size &originalSize, const Rect& capInsets); - if(originalSize === undefined){ - capInsets = offset; - offset = new cc.Point(0,0); - originalSize = new cc.Size(rect.width, rect.height); - } - - var opacity = this.getOpacity(); - var color = this.getColor(); - - // Release old sprites - this._cleanupSlicedSprites(); - this._protectedChildren.length = 0; - - if(this._scale9Image != sprite) - this._scale9Image = sprite; - if (!this._scale9Image) - return false; - -/* var tmpTexture = batchNode.getTexture(); - var locLoaded = tmpTexture.isLoaded(); - this._textureLoaded = locLoaded; - if(!locLoaded){ - tmpTexture.addEventListener("load", function(sender){ - this._positionsAreDirty = true; - this.dispatchEvent("load"); - },this); - return true; - }*/ - - var locScale9Image = this._scale9Image; - var spriteFrame = locScale9Image.getSpriteFrame(); - if (!spriteFrame) - return false; - - var locCapInsets = this._capInsets; - if(capInsets) { - locCapInsets.x = capInsets.x; - locCapInsets.y = capInsets.y; - locCapInsets.width = capInsets.width; - locCapInsets.height = capInsets.height; - } - this._spriteFrameRotated = rotated; - - // If there is no given rect - if (cc._rectEqualToZero(rect)) { - // Get the texture size as original - var textureSize = locScale9Image.getTexture().getContentSize(); - rect = cc.rect(0, 0, textureSize.width, textureSize.height); - } - if(originalSize.width === 0 && originalSize.height === 0){ - originalSize.width = rect.width; - originalSize.height = rect.height; - } - - // Set the given rect's size as original size - var locSpriteRect = this._spriteRect; - locSpriteRect.x = rect.x; - locSpriteRect.y = rect.y; - locSpriteRect.width = rect.width; - locSpriteRect.height = rect.height; - - this._offset.x = offset.x; - this._offset.y = offset.y; - - this._originalSize.width = originalSize.width; - this._originalSize.height = originalSize.height; - - this._preferredSize.width = originalSize.width; - this._preferredSize.height = originalSize.height; - - var locCapInsetsInternal = this._capInsetsInternal; - if(capInsets){ - locCapInsetsInternal.x = capInsets.x; - locCapInsetsInternal.y = capInsets.y; - locCapInsetsInternal.width = capInsets.width; - locCapInsetsInternal.height = capInsets.height; - } - - if (this._scale9Enabled) - this._createSlicedSprites(); - this.setContentSize(originalSize); - - if (this._spritesGenerated){ - // Restore color and opacity - this.setOpacity(opacity); - this.setColor(color); - } - this._spritesGenerated = true; - return true; - }, - - //virtual void setAnchorPoint(const Vec2& anchorPoint) override; - - /** - * set the state of ccui.Scale9Sprite - * @param {Number} state - */ - setState: function(state){ - - }, - - cleanup: function(){}, - - onEnter: function(){}, - - onEnterTransitionDidFinish: function(){}, - - onExit: function(){}, - - onExitTransitionDidStart: function(){}, - - /** - * Sets whether the widget should be flipped horizontally or not. - * @param {Boolean} flippedX true if the widget should be flipped horizontally, false otherwise. - */ - setFlippedX: function(flippedX){}, - - /** - *

- * 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(){}, - - /** - * Sets whether the widget should be flipped vertically or not. - * @param {Boolean} flippedY true if the widget should be flipped vertically, false otherwise. - */ - setFlippedY: function(flippedY){}, - - /** - *

- * 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(){}, - - setScaleX: function(scaleX){}, - - setScaleY: function(scaleY){}, - - setScale: function(scaleX, scaleY){}, - - getScaleX: function(){}, - - getScaleY: function(){}, - - getScale: function(){}, - - _intersectRect:function(first, second){ - var ret = cc.rect(Math.max(first.x,second.x), Math.max(first.y,second.y), 0,0); - var rightRealPoint = Math.min(first.x + first.width, second.x + second.width); - var bottomRealPoint = Math.min(first.y + first.height, second.y + second.height); - ret.width = Math.max(rightRealPoint - ret.x, 0.0); - ret.height = Math.max(bottomRealPoint - ret.y, 0.0); - return ret; - }, - - _createSlicedSprites: function(){ - var w = this._originalSize.width; - var h = this._originalSize.height; - - var offsetPosition = new cc.Point( - Math.ceil(this._offset.x + (this._originalSize.width - this._spriteRect.size.width) / 2), - Math.ceil(this._offset.y + (this._originalSize.height - this._spriteRect.size.height) / 2)); - - var locCapInsetsInternal = this._capInsetsInternal; - // If there is no specified center region - if ( cc._rectEqualToZero(locCapInsetsInternal)){ - // cc.log("... cap insets not specified : using default cap insets ..."); - locCapInsetsInternal.x = w / 3; - locCapInsetsInternal.y = h / 3; - locCapInsetsInternal.width = w / 3; - locCapInsetsInternal.height = h / 3; - } - - var originalRect; - if(this._spriteFrameRotated) - originalRect = cc.rect(this._spriteRect.x - offsetPosition.y, this._spriteRect.y - offsetPosition.x, this._originalSize.width, this._originalSize.height); - else - originalRect = cc.rect(this._spriteRect.x - offsetPosition.x, this._spriteRect.y - offsetPosition.y, this._originalSize.width, this._originalSize.height); - - var left_w = locCapInsetsInternal.x; - var center_w = locCapInsetsInternal.width; - var right_w = locCapInsetsInternal.width - (left_w + center_w); - - var top_h = locCapInsetsInternal.y; - var center_h = locCapInsetsInternal.height; - var bottom_h = originalRect.height - (top_h + center_h); - - // calculate rects - // ... top row - var x = 0.0; - var y = 0.0; - - var pixelRect = cc.rect(offsetPosition.x, offsetPosition.y, this._spriteRect.width, this._spriteRect.height); - - // top left - var lefttopboundsorig = cc.rect(x + 0.5 | 0, y + 0.5 | 0, left_w + 0.5 | 0, top_h + 0.5 | 0); - var lefttopbounds = lefttopboundsorig; - - // top center - x += left_w; - var centertopbounds = cc.rect(x + 0.5 | 0, y + 0.5 | 0, center_w + 0.5 | 0, top_h + 0.5 | 0); - - // top right - x += center_w; - var righttopbounds = cc.rect(x + 0.5 | 0, y + 0.5 | 0, right_w + 0.5 | 0, top_h + 0.5 | 0); - - // ... center row - x = 0.0; - y = 0.0; - y += top_h; - - // center left - var leftcenterbounds = cc.rect(x + 0.5 | 0, y + 0.5 | 0, left_w + 0.5 | 0, center_h + 0.5 | 0); - - // center center - x += left_w; - var centerboundsorig = cc.rect(x + 0.5 | 0, y + 0.5 | 0, center_w + 0.5 | 0, center_h + 0.5 | 0); - var centerbounds = centerboundsorig; - - // center right - x += center_w; - var rightcenterbounds = cc.rect(x + 0.5 | 0, y + 0.5 | 0, right_w + 0.5 | 0, center_h + 0.5 | 0); - - // ... bottom row - x = 0.0; - y = 0.0; - y += top_h; - y += center_h; - - // bottom left - var leftbottombounds = cc.rect(x + 0.5 | 0, y + 0.5 | 0, left_w + 0.5 | 0, bottom_h + 0.5 | 0); - - // bottom center - x += left_w; - var centerbottombounds = cc.rect(x + 0.5 | 0, y + 0.5 | 0, center_w + 0.5 | 0, bottom_h + 0.5 | 0); - - // bottom right - x += center_w; - var rightbottomboundsorig = cc.rect(x + 0.5 | 0, y + 0.5 | 0, right_w + 0.5 | 0, bottom_h + 0.5 | 0); - var rightbottombounds = rightbottomboundsorig; - - if((locCapInsetsInternal.x + locCapInsetsInternal.width) <= this._originalSize.width - || (locCapInsetsInternal.y + locCapInsetsInternal.height) <= this._originalSize.height) { - //in general case it is error but for legacy support we will check it - lefttopbounds = this._intersectRect(lefttopbounds, pixelRect); - centertopbounds = this._intersectRect(centertopbounds, pixelRect); - righttopbounds = this._intersectRect(righttopbounds, pixelRect); - leftcenterbounds = this._intersectRect(leftcenterbounds, pixelRect); - centerbounds = this._intersectRect(centerbounds, pixelRect); - rightcenterbounds = this._intersectRect(rightcenterbounds, pixelRect); - leftbottombounds = this._intersectRect(leftbottombounds, pixelRect); - centerbottombounds = this._intersectRect(centerbottombounds, pixelRect); - rightbottombounds = this._intersectRect(rightbottombounds, pixelRect); - } else - cc.log("Scale9Sprite capInsetsInternal > originalSize"); //it is error but for legacy turn off clip system - - var rotatedlefttopboundsorig = lefttopboundsorig; - var rotatedcenterboundsorig = centerboundsorig; - var rotatedrightbottomboundsorig = rightbottomboundsorig; - - var rotatedcenterbounds = centerbounds; - var rotatedrightbottombounds = rightbottombounds; - var rotatedleftbottombounds = leftbottombounds; - var rotatedrighttopbounds = righttopbounds; - var rotatedlefttopbounds = lefttopbounds; - var rotatedrightcenterbounds = rightcenterbounds; - var rotatedleftcenterbounds = leftcenterbounds; - var rotatedcenterbottombounds = centerbottombounds; - var rotatedcentertopbounds = centertopbounds; - - var t = cc.affineTransformMakeIdentity(); - if (!this._spriteFrameRotated) { - //TODO - t = cc.affineTransformTranslate(t, originalRect.x, originalRect.y); - - rotatedlefttopboundsorig = RectApplyAffineTransform(rotatedlefttopboundsorig, t); - rotatedcenterboundsorig = RectApplyAffineTransform(rotatedcenterboundsorig, t); - rotatedrightbottomboundsorig = RectApplyAffineTransform(rotatedrightbottomboundsorig, t); - - rotatedcenterbounds = RectApplyAffineTransform(rotatedcenterbounds, t); - rotatedrightbottombounds = RectApplyAffineTransform(rotatedrightbottombounds, t); - rotatedleftbottombounds = RectApplyAffineTransform(rotatedleftbottombounds, t); - rotatedrighttopbounds = RectApplyAffineTransform(rotatedrighttopbounds, t); - rotatedlefttopbounds = RectApplyAffineTransform(rotatedlefttopbounds, t); - rotatedrightcenterbounds = RectApplyAffineTransform(rotatedrightcenterbounds, t); - rotatedleftcenterbounds = RectApplyAffineTransform(rotatedleftcenterbounds, t); - rotatedcenterbottombounds = RectApplyAffineTransform(rotatedcenterbottombounds, t); - rotatedcentertopbounds = RectApplyAffineTransform(rotatedcentertopbounds, t); - } else { - // set up transformation of coordinates - // to handle the case where the sprite is stored rotated - // in the spritesheet - // log("rotated"); - t = cc.affineTransformTranslate(t, originalRect.height+originalRect.x, originalRect.y); - t = cc.affineTransformRotate(t, 1.57079633); - - lefttopboundsorig = RectApplyAffineTransform(lefttopboundsorig, t); - centerboundsorig = RectApplyAffineTransform(centerboundsorig, t); - rightbottomboundsorig = RectApplyAffineTransform(rightbottomboundsorig, t); - - centerbounds = RectApplyAffineTransform(centerbounds, t); - rightbottombounds = RectApplyAffineTransform(rightbottombounds, t); - leftbottombounds = RectApplyAffineTransform(leftbottombounds, t); - righttopbounds = RectApplyAffineTransform(righttopbounds, t); - lefttopbounds = RectApplyAffineTransform(lefttopbounds, t); - rightcenterbounds = RectApplyAffineTransform(rightcenterbounds, t); - leftcenterbounds = RectApplyAffineTransform(leftcenterbounds, t); - centerbottombounds = RectApplyAffineTransform(centerbottombounds, t); - centertopbounds = RectApplyAffineTransform(centertopbounds, t); - - rotatedlefttopboundsorig.origin = lefttopboundsorig.origin; - rotatedcenterboundsorig.origin = centerboundsorig.origin; - rotatedrightbottomboundsorig.origin = rightbottomboundsorig.origin; - - rotatedcenterbounds.origin = centerbounds.origin; - rotatedrightbottombounds.origin = rightbottombounds.origin; - rotatedleftbottombounds.origin = leftbottombounds.origin; - rotatedrighttopbounds.origin = righttopbounds.origin; - rotatedlefttopbounds.origin = lefttopbounds.origin; - rotatedrightcenterbounds.origin = rightcenterbounds.origin; - rotatedleftcenterbounds.origin = leftcenterbounds.origin; - rotatedcenterbottombounds.origin = centerbottombounds.origin; - rotatedcentertopbounds.origin = centertopbounds.origin; - } - - this._topLeftSize.width = rotatedlefttopboundsorig.width; - this._topLeftSize.height = rotatedlefttopboundsorig.height; - this._centerSize.width = rotatedcenterboundsorig.width; - this._centerSize.height = rotatedcenterboundsorig.height; - this._bottomRightSize.width = rotatedrightbottomboundsorig.width; - this._bottomRightSize.height = rotatedrightbottomboundsorig.height; - - if(this._spriteFrameRotated){ - this._centerOffset.x = -(rotatedcenterboundsorig.y + rotatedcenterboundsorig.width/2)- (rotatedcenterbounds.y + rotatedcenterbounds.width/2); - this._centerOffset.y = (rotatedcenterbounds.x + rotatedcenterbounds.height/2) - (rotatedcenterboundsorig.x + rotatedcenterboundsorig.height/2); - } else { - this._centerOffset.x = (rotatedcenterbounds.x + rotatedcenterbounds.width/2) - (rotatedcenterboundsorig.x + rotatedcenterboundsorig.width/2); - this._centerOffset.y = (rotatedcenterboundsorig.y + rotatedcenterboundsorig.height/2)- (rotatedcenterbounds.y + rotatedcenterbounds.height/2); - } - - // Centre - if(rotatedcenterbounds.width > 0 && rotatedcenterbounds.height > 0 ) { - this._centre = new cc.Sprite(); - this._centre.initWithTexture(this._scale9Image.getTexture(), rotatedcenterbounds, this._spriteFrameRotated); - this.addProtectedChild(this._centre); - } - - // Top - if(rotatedcentertopbounds.width > 0 && rotatedcentertopbounds.height > 0 ) { - this._top = new cc.Sprite(); - this._top.initWithTexture(this._scale9Image.getTexture(), rotatedcentertopbounds, this._spriteFrameRotated); - this.addProtectedChild(this._top); - } - - // Bottom - if(rotatedcenterbottombounds.width > 0 && rotatedcenterbottombounds.height > 0 ) { - this._bottom = new cc.Sprite(); - this._bottom.initWithTexture(this._scale9Image.getTexture(), rotatedcenterbottombounds, this._spriteFrameRotated); - this.addProtectedChild(this._bottom); - } - - // Left - if(rotatedleftcenterbounds.width > 0 && rotatedleftcenterbounds.height > 0 ) { - this._left = new cc.Sprite(); - this._left.initWithTexture(this._scale9Image.getTexture(), rotatedleftcenterbounds, this._spriteFrameRotated); - this.addProtectedChild(this._left); - } - - // Right - if(rotatedrightcenterbounds.width > 0 && rotatedrightcenterbounds.height > 0 ) { - this._right = new cc.Sprite(); - this._right.initWithTexture(this._scale9Image.getTexture(), rotatedrightcenterbounds, this._spriteFrameRotated); - this.addProtectedChild(this._right); - } - - // Top left - if(rotatedlefttopbounds.width > 0 && rotatedlefttopbounds.height > 0 ) { - this._topLeft = new cc.Sprite(); - this._topLeft.initWithTexture(this._scale9Image.getTexture(), rotatedlefttopbounds, this._spriteFrameRotated); - this.addProtectedChild(this._topLeft); - } - - // Top right - if(rotatedrighttopbounds.width > 0 && rotatedrighttopbounds.height > 0 ) { - this._topRight = new cc.Sprite(); - this._topRight.initWithTexture(this._scale9Image.getTexture(), rotatedrighttopbounds, this._spriteFrameRotated); - this.addProtectedChild(this._topRight); - } - - // Bottom left - if(rotatedleftbottombounds.width > 0 && rotatedleftbottombounds.height > 0 ) { - this._bottomLeft = new cc.Sprite(); - this._bottomLeft.initWithTexture(this._scale9Image.getTexture(), rotatedleftbottombounds, this._spriteFrameRotated); - this.addProtectedChild(this._bottomLeft); - } - - // Bottom right - if(rotatedrightbottombounds.width > 0 && rotatedrightbottombounds.height > 0 ) { - this._bottomRight = new cc.Sprite(); - this._bottomRight.initWithTexture(this._scale9Image.getTexture(), rotatedrightbottombounds, this._spriteFrameRotated); - this.addProtectedChild(this._bottomRight); - } - }, - - _cleanupSlicedSprites: function(){ - if (this._topLeft && this._topLeft.isRunning()) - this._topLeft.onExit(); - if (this._top && this._top.isRunning()) - this._top.onExit(); - if (this._topRight && this._topRight.isRunning()) - this._topRight.onExit(); - if (this._left && this._left.isRunning()) - this._left.onExit(); - if (this._centre && this._centre.isRunning()) - this._centre.onExit(); - if (this._right && this._right.isRunning()) - this._right.onExit(); - if (this._bottomLeft && this._bottomLeft.isRunning()) - this._bottomLeft.onExit(); - if (this._bottomRight && this._bottomRight.isRunning()) - this._bottomRight.onExit(); - if (this._bottom && this._bottom.isRunning()) - this._bottom.onExit(); - }, - - _adjustScale9ImagePosition: function(){}, - - _sortAllProtectedChildren: function(){}, - - _addProtectedChild: function(){}, - _createRenderCmd: function(){ if(cc._renderType === cc._RENDER_TYPE_CANVAS) return new ccui.Scale9Sprite.CanvasRenderCmd(this); @@ -1466,4 +996,4 @@ 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.POSITIONS_BOTTOMRIGHT = 7; \ No newline at end of file From b51e4d6eabf10fa76677cd6f7053694ba2e1e6e7 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 8 Jan 2015 17:33:21 +0800 Subject: [PATCH 0108/1345] _textureLoaded errore when call setTexture --- cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js | 1 + cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js | 1 + cocos2d/core/textures/CCTexture2D.js | 2 +- cocos2d/core/textures/TexturesWebGL.js | 3 ++- 4 files changed, 5 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js index ec0ecd09b8..45224e6adb 100644 --- a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js @@ -61,6 +61,7 @@ if (texture && texture.getHtmlElementObj() instanceof HTMLImageElement) { this._originalTexture = texture; } + node._textureLoaded = texture._textureLoaded; node._texture = texture; } }; diff --git a/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js b/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js index b590b6c74b..376d227e62 100644 --- a/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js @@ -297,6 +297,7 @@ this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_COLOR); if (!node._batchNode && node._texture != texture) { + node._textureLoaded = texture._textureLoaded; node._texture = texture; this._updateBlendFunc(); } diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index 82833cab4f..074a6efc77 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -182,6 +182,7 @@ if (cc._renderType === cc._RENDER_TYPE_CANVAS) { if (!element) return; this._htmlElementObj = element; + this._textureLoaded = true; }, /** @@ -212,7 +213,6 @@ if (cc._renderType === cc._RENDER_TYPE_CANVAS) { self.initWithElement(img); } - self._textureLoaded = true; var locElement = self._htmlElementObj; self._contentSize.width = locElement.width; self._contentSize.height = locElement.height; diff --git a/cocos2d/core/textures/TexturesWebGL.js b/cocos2d/core/textures/TexturesWebGL.js index 4e0f41c5d9..d26cbe5a57 100644 --- a/cocos2d/core/textures/TexturesWebGL.js +++ b/cocos2d/core/textures/TexturesWebGL.js @@ -421,6 +421,7 @@ cc._tmp.WebGLTexture2D = function () { return; this._webTextureObj = cc._renderContext.createTexture(); this._htmlElementObj = element; + this._textureLoaded = true; }, /** @@ -454,7 +455,7 @@ cc._tmp.WebGLTexture2D = function () { } if (!self._htmlElementObj.width || !self._htmlElementObj.height) return; - self._textureLoaded = true; + //upload image to buffer var gl = cc._renderContext; From 2b0e00f64061cc285c191ad8a389a69b2f8789a1 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 8 Jan 2015 17:55:00 +0800 Subject: [PATCH 0109/1345] Create a sprite from the frame and not pre loaded, color cannot be modified --- cocos2d/core/sprites/CCSprite.js | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/cocos2d/core/sprites/CCSprite.js b/cocos2d/core/sprites/CCSprite.js index 5237ab85bf..2fcce96352 100644 --- a/cocos2d/core/sprites/CCSprite.js +++ b/cocos2d/core/sprites/CCSprite.js @@ -843,13 +843,15 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ _t.texture = locNewTexture; _t.setTextureRect(sender.getRect(), sender.isRotated(), sender.getOriginalSize()); _t.dispatchEvent("load"); + _t.setColor(_t.color); }, _t); - } - // update texture before updating texture rect - if (pNewTexture != _t._texture) - _t.texture = pNewTexture; + }else{ + // update texture before updating texture rect + if (pNewTexture != _t._texture) + _t.texture = pNewTexture; - _t.setTextureRect(newFrame.getRect(), _t._rectRotated, newFrame.getOriginalSize()); + _t.setTextureRect(newFrame.getRect(), _t._rectRotated, newFrame.getOriginalSize()); + } this._renderCmd._updateForSetSpriteFrame(pNewTexture); }, From 71efef0ab5abbd53bc5fd0f8e208c1858ccada19 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Thu, 8 Jan 2015 18:29:54 +0800 Subject: [PATCH 0110/1345] Issue #1267: added flippedX/flippedY to ccui.Scale9Sprite --- .../core/sprites/CCSpriteCanvasRenderCmd.js | 2 +- .../ccui/base-classes/UIScale9Sprite.js | 103 ++++++++++++++++++ 2 files changed, 104 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js index ec0ecd09b8..f3b9178fef 100644 --- a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js @@ -278,7 +278,7 @@ proto._updateDisplayColor = function (parentColor) { cc.Node.CanvasRenderCmd.prototype._updateDisplayColor.call(this, parentColor); - this._updateColor(); + //this._updateColor(); }; proto._spriteFrameLoadedCallback = function (spriteFrame) { diff --git a/extensions/ccui/base-classes/UIScale9Sprite.js b/extensions/ccui/base-classes/UIScale9Sprite.js index c49a2affcc..a3b8191a60 100644 --- a/extensions/ccui/base-classes/UIScale9Sprite.js +++ b/extensions/ccui/base-classes/UIScale9Sprite.js @@ -91,6 +91,10 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ _textureLoaded:false, _className:"Scale9Sprite", + //v3.3 + _flippedX: false, + _flippedY: false, + /** * return texture is loaded * @returns {boolean} @@ -918,6 +922,105 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ this._insetBottom = 0; }, + //v3.3 + setState: function(state){ + // + }, + + //setScale9Enabled implement late + + /** + * Sets whether the widget should be flipped horizontally or not. + * @since v3.3 + * @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);
+ *

+ * @since v3.3 + * @return {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. + * @since v3.3 + * @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);
+ *

+ * @since v3.3 + * @return {Boolean} true if the widget is flipped vertically, false otherwise. + */ + isFlippedY:function(){ + return this._flippedY; + }, + + 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 () { + cc.log(this.getScaleX() == this.getScaleY(), "Scale9Sprite#scale. ScaleX != ScaleY. Don't know which one to return"); + return this.getScaleX(); + }, + _createRenderCmd: function(){ if(cc._renderType === cc._RENDER_TYPE_CANVAS) return new ccui.Scale9Sprite.CanvasRenderCmd(this); From 780bb615f23a691d4a7e0263f9e2af2f0116b929 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 9 Jan 2015 10:46:22 +0800 Subject: [PATCH 0111/1345] Issue #2563: Fixed particle texture size error --- cocos2d/core/textures/CCTexture2D.js | 2 ++ extensions/cocostudio/loader/parsers/timelineParser-2.x.js | 1 + 2 files changed, 3 insertions(+) diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index 074a6efc77..1eee6d2f0c 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -182,6 +182,8 @@ if (cc._renderType === cc._RENDER_TYPE_CANVAS) { if (!element) return; this._htmlElementObj = element; + this._contentSize.width = element.width; + this._contentSize.height = element.height; this._textureLoaded = true; }, diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 62d87ff1a1..746e6da38b 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -197,6 +197,7 @@ cc.log("%s need to pre load", path); node = new cc.ParticleSystem(path); self.generalAttributes(node, json); + node.setDrawMode(cc.ParticleSystem.TEXTURE_MODE); }); return node; }; From ea145250933c08162126667648b057cf194fb0ec Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 9 Jan 2015 10:50:20 +0800 Subject: [PATCH 0112/1345] Issue #2563: Fixed layoutType is undefined --- extensions/cocostudio/loader/parsers/uiParser-1.x.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/extensions/cocostudio/loader/parsers/uiParser-1.x.js b/extensions/cocostudio/loader/parsers/uiParser-1.x.js index a89b01cddc..6dfef4c8b6 100644 --- a/extensions/cocostudio/loader/parsers/uiParser-1.x.js +++ b/extensions/cocostudio/loader/parsers/uiParser-1.x.js @@ -262,7 +262,9 @@ var ch = options["capInsetsHeight"]; widget.setBackGroundImageCapInsets(cc.rect(cx, cy, cw, ch)); } - widget.setLayoutType(options["layoutType"]); + var layoutType = options["layoutType"]; + if(layoutType != null) + widget.setLayoutType(layoutType); }; /** * Button parser (UIButton) From 7874ec7df7f5e6ef6ccb849743fe3d83e63f3f1d Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 9 Jan 2015 11:49:44 +0800 Subject: [PATCH 0113/1345] Fixed ActionManager currTarget.actions is null error --- cocos2d/core/CCActionManager.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/CCActionManager.js b/cocos2d/core/CCActionManager.js index 06006dc795..18c2e3900d 100644 --- a/cocos2d/core/CCActionManager.js +++ b/cocos2d/core/CCActionManager.js @@ -339,7 +339,8 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{ //this._currentTargetSalvaged = false; if (!locCurrTarget.paused) { // The 'actions' CCMutableArray may change while inside this loop. - for (locCurrTarget.actionIndex = 0; locCurrTarget.actionIndex < locCurrTarget.actions.length; + for (locCurrTarget.actionIndex = 0; + locCurrTarget.actionIndex < (locCurrTarget.actions ? locCurrTarget.actions.length : 0); locCurrTarget.actionIndex++) { locCurrTarget.currentAction = locCurrTarget.actions[locCurrTarget.actionIndex]; if (!locCurrTarget.currentAction) From b5e7b13736ed336dec107a11b1a33e67c4bf96b3 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 9 Jan 2015 15:05:44 +0800 Subject: [PATCH 0114/1345] Fixed atlas setColor error when texture is not pre loaded --- cocos2d/labels/CCLabelAtlas.js | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos2d/labels/CCLabelAtlas.js b/cocos2d/labels/CCLabelAtlas.js index 9864ace3a7..4e649f6881 100644 --- a/cocos2d/labels/CCLabelAtlas.js +++ b/cocos2d/labels/CCLabelAtlas.js @@ -146,6 +146,7 @@ cc.LabelAtlas = cc.AtlasNode.extend(/** @lends cc.LabelAtlas# */{ texture.addEventListener("load", function (sender) { this.initWithTexture(texture, width, height, label.length); this.string = label; + this.setColor(this._renderCmd._displayedColor); this.dispatchEvent("load"); }, this); } From 4950effafee9c3892c66637d7f42a794b5f9f38c Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 9 Jan 2015 15:21:26 +0800 Subject: [PATCH 0115/1345] Fixed Sprite setTexture set _textureLoaded error --- cocos2d/core/sprites/CCSprite.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/cocos2d/core/sprites/CCSprite.js b/cocos2d/core/sprites/CCSprite.js index 2fcce96352..ac0733d9c7 100644 --- a/cocos2d/core/sprites/CCSprite.js +++ b/cocos2d/core/sprites/CCSprite.js @@ -936,7 +936,10 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ texture.addEventListener("load", function(){ var size = texture.getContentSize(); _t.setTextureRect(cc.rect(0,0, size.width, size.height)); + _t._textureLoaded = true; }, this); + }else{ + _t._textureLoaded = true; } return; } From 7931299a778e6bbd427d294a42e8b6b4577fdbd8 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Fri, 9 Jan 2015 16:17:07 +0800 Subject: [PATCH 0116/1345] Issue #1267: implemented ccui.Scale9Sprite's setState --- cocos2d/core/textures/CCTexture2D.js | 38 ++++++++++++++++++ .../ccui/base-classes/UIScale9Sprite.js | 16 ++++---- .../UIScale9SpriteCanvasRenderCmd.js | 13 ++++++ .../UIScale9SpriteWebGLRenderCmd.js | 40 +++++++++++++++++-- 4 files changed, 97 insertions(+), 10 deletions(-) diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index 82833cab4f..b6f919555b 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -399,9 +399,47 @@ if (cc._renderType === cc._RENDER_TYPE_CANVAS) { */ removeLoadedEventListener: function (target) { this.removeEventListener("load", target); + }, + + //hack for gray effect + _grayElementObj: null, + _backupElement: null, + _isGray: false, + _switchToGray: function(toGray){ + if(!this._textureLoaded || this._isGray == toGray) + return; + this._isGray = toGray; + if(this._isGray){ + this._backupElement = this._htmlElementObj; + if(!this._grayElementObj) + this._grayElementObj = cc.Texture2D._generateGrayTexture(this._htmlElementObj); + this._htmlElementObj = this._grayElementObj; + } else { + if(this._backupElement != null) + this._htmlElementObj = this._backupElement; + } } }); + cc.Texture2D._generateGrayTexture = function(texture, rect, renderCanvas){ + if (texture === null) + return null; + renderCanvas = renderCanvas || cc.newElement("canvas"); + rect = rect || cc.rect(0, 0, texture.width, texture.height); + renderCanvas.width = rect.width; + renderCanvas.height = rect.height; + + var context = renderCanvas.getContext("2d"); + context.drawImage(texture, rect.x, rect.y, rect.width, rect.height, 0, 0, rect.width, rect.height); + var imgData = context.getImageData(0, 0, rect.width, rect.height); + var data = imgData.data; + for (var i = 0, len = data.length; i < len; i += 4) { + data[i] = data[i + 1] = data[i + 2] = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2]; + } + context.putImageData(imgData, 0, 0); + return renderCanvas; + }; + } else { cc.assert(cc.isFunction(cc._tmp.WebGLTexture2D), cc._LogInfos.MissingFile, "TexturesWebGL.js"); cc._tmp.WebGLTexture2D(); diff --git a/extensions/ccui/base-classes/UIScale9Sprite.js b/extensions/ccui/base-classes/UIScale9Sprite.js index a3b8191a60..a828908e64 100644 --- a/extensions/ccui/base-classes/UIScale9Sprite.js +++ b/extensions/ccui/base-classes/UIScale9Sprite.js @@ -67,11 +67,6 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ _bottom: null, _bottomRight: null, - //cache in canvas on Canvas mode - _cacheSprite: null, - _cacheCanvas: null, - _cacheContext: null, - _cacheTexture: null, _scale9Dirty: true, _opacityModifyRGB: false, @@ -923,8 +918,13 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ }, //v3.3 + /** + * Sets ccui.Scale9Sprite's state + * @since v3.3 + * @param {Number} state + */ setState: function(state){ - // + this._renderCmd.setState(state); }, //setScale9Enabled implement late @@ -1099,4 +1099,6 @@ 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; \ No newline at end of file +ccui.Scale9Sprite.POSITIONS_BOTTOMRIGHT = 7; + +ccui.Scale9Sprite.state = {NORMAL: 0, GRAY: 1}; diff --git a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js index 31b21de117..a324dab733 100644 --- a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js +++ b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js @@ -120,4 +120,17 @@ if(!this._cacheSprite.getParent()) node.addChild(this._cacheSprite, -1); }; + + proto.setState = function(state){ + var locScale9Image = this._node._scale9Image; + if(!locScale9Image) + return; + var selTexture = locScale9Image.getTexture(); + if(state === ccui.Scale9Sprite.state.NORMAL){ + selTexture._switchToGray(false); + } else if( state === ccui.Scale9Sprite.state.GRAY){ + selTexture._switchToGray(true); + } + this._cacheScale9Sprite(); + }; })(); \ No newline at end of file diff --git a/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js b/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js index d26f118bd2..158eca0a47 100644 --- a/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js +++ b/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js @@ -34,9 +34,8 @@ proto.visit = function(parentCmd){ var node = this._node; - if(!node._visible){ + if(!node._visible) return; - } if (node._positionsAreDirty) { node._updatePositions(); @@ -60,7 +59,6 @@ } } } - }; proto._updateDisplayOpacity = function(parentColor){ @@ -77,7 +75,43 @@ } } } + }; + + proto.setState = function (state) { + var scale9Image = this._node._scale9Image; + 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()); + } + }; + + 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 From bbc07f03763704136c8fb7a18d66707e9733c6a4 Mon Sep 17 00:00:00 2001 From: jianglong0156 Date: Sat, 10 Jan 2015 17:10:20 +0800 Subject: [PATCH 0117/1345] issue #2563: protect the data --- extensions/cocostudio/loader/load.js | 2 +- .../cocostudio/loader/parsers/uiParser-1.x.js | 16 +++++++++++++--- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/extensions/cocostudio/loader/load.js b/extensions/cocostudio/loader/load.js index a8dfc5c5fa..e031a7dbff 100644 --- a/extensions/cocostudio/loader/load.js +++ b/extensions/cocostudio/loader/load.js @@ -136,7 +136,7 @@ ccs._parser = cc.Class.extend({ parse: function(file, json){ var resourcePath = this._dirname(file); this.pretreatment(json, resourcePath); - var node = this.parseNode(this.getNodeJson(json), resourcePath); + var node = this.parseNode(this.getNodeJson(json), resourcePath, file); node && this.deferred(json, resourcePath, node, file); return node; }, diff --git a/extensions/cocostudio/loader/parsers/uiParser-1.x.js b/extensions/cocostudio/loader/parsers/uiParser-1.x.js index a89b01cddc..41500f531f 100644 --- a/extensions/cocostudio/loader/parsers/uiParser-1.x.js +++ b/extensions/cocostudio/loader/parsers/uiParser-1.x.js @@ -53,8 +53,15 @@ if(ignoreSizeExsit != null) widget.ignoreContentAdaptWithSize(ignoreSizeExsit); - widget.setSizeType(options["sizeType"]); - widget.setPositionType(options["positionType"]); + 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"])); @@ -262,7 +269,10 @@ var ch = options["capInsetsHeight"]; widget.setBackGroundImageCapInsets(cc.rect(cx, cy, cw, ch)); } - widget.setLayoutType(options["layoutType"]); + if (options["layoutType"]) + { + widget.setLayoutType(options["layoutType"]); + } }; /** * Button parser (UIButton) From 064784be159294096a1e445fa90b7c3b8784f4bf Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Mon, 12 Jan 2015 10:16:08 +0800 Subject: [PATCH 0118/1345] Issue #1267: migrating UIWidget.js --- extensions/ccui/base-classes/UIWidget.js | 40 ++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/extensions/ccui/base-classes/UIWidget.js b/extensions/ccui/base-classes/UIWidget.js index 67dc978fbb..bc32a1cd34 100644 --- a/extensions/ccui/base-classes/UIWidget.js +++ b/extensions/ccui/base-classes/UIWidget.js @@ -89,6 +89,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ _highlight: false, _touchEventCallback: null, + _clickEventListener: null, _propagateTouchEvents: true, _unifySize: false, @@ -187,14 +188,29 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ 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) { @@ -202,6 +218,11 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ } }, + /** + * Return whether the widget is swallowing touch or not + * @since v3.2 + * @returns {boolean} + */ isSwallowTouches: function(){ if (this._touchListener){ //todo @@ -1573,6 +1594,25 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ this._unifySize = enable; }, + //v3.3 + /** + * Set a event handler to the widget in order to use cocostudio editor and framework + * @since v3.3 + * @param {function} callback + */ + addCCSEventListener: function(callback){}, + + //override the scale functions. + setScaleX: function(scaleX){}, + setScaleY: function(scaleY){}, + setScale: function(scaleX, scaleY){}, + + getScaleX: function(){}, + getScaleY: function(){}, + getScale: function(){}, + + + _createRenderCmd: function(){ if(cc._renderType === cc._RENDER_TYPE_WEBGL) return new ccui.Widget.WebGLRenderCmd(this); From c09f6eb2ff5ccd324890a9a6d466f4dcf75986d6 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Mon, 12 Jan 2015 10:25:38 +0800 Subject: [PATCH 0119/1345] Fixed Cocos2d-js/#1292: Gets the wrong OS type to sys.os when OS is Linux --- CCBoot.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CCBoot.js b/CCBoot.js index d2b733287d..f777148fc1 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -1561,7 +1561,7 @@ cc._initSys = function (config, CONFIG_KEY) { if (nav.appVersion.indexOf("Win") != -1) osName = sys.OS_WINDOWS; else if (iOS) osName = sys.OS_IOS; else if (nav.appVersion.indexOf("Mac") != -1) osName = sys.OS_OSX; - else if (nav.appVersion.indexOf("X11") != -1) osName = sys.OS_UNIX; + else if (nav.appVersion.indexOf("X11") != -1 && nav.appVersion.indexOf("Linux") == -1) osName = sys.OS_UNIX; else if (isAndroid) osName = sys.OS_ANDROID; else if (nav.appVersion.indexOf("Linux") != -1) osName = sys.OS_LINUX; From b140c2663a0e652e95677d7c5a956a0ce514641c Mon Sep 17 00:00:00 2001 From: jianglong0156 Date: Mon, 12 Jan 2015 11:18:55 +0800 Subject: [PATCH 0120/1345] issue #2563: keey the code same with the jsb code. --- extensions/cocostudio/loader/parsers/action-1.x.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/cocostudio/loader/parsers/action-1.x.js b/extensions/cocostudio/loader/parsers/action-1.x.js index 1b02ce6b2e..c5c20446c4 100644 --- a/extensions/cocostudio/loader/parsers/action-1.x.js +++ b/extensions/cocostudio/loader/parsers/action-1.x.js @@ -63,7 +63,7 @@ }); cache[file] = action; - + cache[file].retain(); return action.clone(); } From 1ee6e7ad510b48154cbe81568dfe05b51cb7a3e2 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Mon, 12 Jan 2015 13:51:00 +0800 Subject: [PATCH 0121/1345] Issue #1267: migrated ccui.Widget --- extensions/ccui/base-classes/UIWidget.js | 265 +++++++++++++++++++---- 1 file changed, 218 insertions(+), 47 deletions(-) diff --git a/extensions/ccui/base-classes/UIWidget.js b/extensions/ccui/base-classes/UIWidget.js index bc32a1cd34..d7dc060958 100644 --- a/extensions/ccui/base-classes/UIWidget.js +++ b/extensions/ccui/base-classes/UIWidget.js @@ -94,6 +94,10 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ _propagateTouchEvents: true, _unifySize: false, + _callbackName: null, + _callbackType: null, + _usingLayoutComponent: false, + /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. * @function @@ -141,7 +145,8 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @override */ onEnter: function () { - this.updateSizeAndPosition(); + if(!this._usingLayoutComponent) + this.updateSizeAndPosition(); cc.ProtectedNode.prototype.onEnter.call(this); }, @@ -154,11 +159,11 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ cc.ProtectedNode.prototype.onExit.call(this); }, - getOrCreateLayoutComponent: function(){ + _getOrCreateLayoutComponent: function(){ var layoutComponent = this.getComponent(ccui.__LAYOUT_COMPONENT_NAME); if (null == layoutComponent){ layoutComponent = new ccui.LayoutComponent(); - this.addComponent(component); + this.addComponent(layoutComponent); } return layoutComponent; }, @@ -175,6 +180,10 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ }, _updateContentSizeWithTextureSize: function(size){ + if(this._unifySize){ + this.setContentSize(size); + return; + } this.setContentSize(this._ignoreSize ? size : this._customSize); }, @@ -213,9 +222,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ */ setSwallowTouches: function(swallow){ if (this._touchListener) - { this._touchListener.setSwallowTouches(swallow); - } }, /** @@ -225,9 +232,8 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ */ isSwallowTouches: function(){ if (this._touchListener){ - //todo - return true; - //return this._touchListener.isSwallowTouches(); + //return true; //todo need test + return this._touchListener.isSwallowTouches(); } return false; }, @@ -297,10 +303,12 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ this._customSize.width = locWidth; this._customSize.height = locHeight; - if (this._ignoreSize){ + if(this._unifySize){ + //unify size logic + } else if (this._ignoreSize){ this._contentSize = this.getVirtualRendererSize(); } - if (this._running) { + 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; @@ -312,10 +320,13 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ _setWidth: function (w) { cc.Node.prototype._setWidth.call(this, w); this._customSize.width = w; - if(this._ignoreSize) + if(this._unifySize){ + //unify size logic + } else if (this._ignoreSize){ this._contentSize = this.getVirtualRendererSize(); + } - if (this._running) { + 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; @@ -325,10 +336,13 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ _setHeight: function (h) { cc.Node.prototype._setHeight.call(this, h); this._customSize.height = h; - if(this._ignoreSize) + if(this._unifySize){ + //unify size logic + } else if (this._ignoreSize){ this._contentSize = this.getVirtualRendererSize(); + } - if (this._running) { + 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; @@ -341,6 +355,13 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @param {cc.Point} 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; @@ -456,6 +477,10 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ */ setSizeType: function (type) { this._sizeType = type; + if (this._usingLayoutComponent) { + var component = this._getOrCreateLayoutComponent(); + component.setUsingPercentContentSize(this._sizeType == ccui.SIZE_PERCENT); + } }, /** @@ -471,12 +496,17 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @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(); + //this._onSizeChanged(); }, /** @@ -508,8 +538,11 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @returns {cc.Point} */ getSizePercent: function () { - var component = this.getOrCreateLayoutComponent(); - return component.getPercentContentSize(); + if(this._usingLayoutComponent){ + var component = this._getOrCreateLayoutComponent(); + this._sizePercent = component.getPercentContentSize(); + } + return this._sizePercent; }, _getWidthPercent: function () { return this._sizePercent.x; @@ -545,11 +578,13 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * call back function called when size changed. */ _onSizeChanged: function () { - 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(); + 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(); + } } }, @@ -839,8 +874,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ /* * Propagate touch events to its parents */ - if (this._propagateTouchEvents) - { + if (this._propagateTouchEvents) { this.propagateTouchEvent(ccui.Widget.TOUCH_BEGAN, this, touch); } @@ -868,9 +902,11 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ this._touchMovePosition.x = touchPoint.x; this._touchMovePosition.y = touchPoint.y; this.setHighlighted(this.hitTest(touchPoint)); - var widgetParent = this.getWidgetParent(); - if (widgetParent) - widgetParent.interceptTouchEvent(ccui.Widget.TOUCH_MOVED, this, touch); + /* + * Propagate touch events to its parents + */ + if (this._propagateTouchEvents) + this.propagateTouchEvent(ccui.Widget.TOUCH_MOVED, this, touch); this._moveEvent(); }, @@ -888,9 +924,12 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ var touchPoint = touch.getLocation(); this._touchEndPosition.x = touchPoint.x; this._touchEndPosition.y = touchPoint.y; - var widgetParent = this.getWidgetParent(); - if (widgetParent) - widgetParent.interceptTouchEvent(ccui.Widget.TOUCH_ENDED, this, touch); + /* + * Propagate touch events to its parents + */ + if (this._propagateTouchEvents) + this.propagateTouchEvent(ccui.Widget.TOUCH_ENDED, this, touch); + var highlight = this._highlight; this.setHighlighted(false); if (highlight) @@ -936,10 +975,8 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ 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) { + if (this._clickEventListener) this._clickEventListener(this); - } }, _cancelUpEvent: function () { @@ -1032,7 +1069,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @param {Number} [posY] */ setPosition: function (pos, posY) { - if (this._running) { + if (!this._usingLayoutComponent && this._running) { var widgetParent = this.getWidgetParent(); if (widgetParent) { var pSize = widgetParent.getContentSize(); @@ -1089,6 +1126,14 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @param {cc.Point} percent */ setPositionPercent: function (percent) { + if (this._usingLayoutComponent) + { + var component = this._getOrCreateLayoutComponent(); + component.setPositionPercentX(percent.x); + component.setPositionPercentY(percent.y); + component.refreshLayout(); + return; + } this._positionPercent = percent; if (this._running) { var widgetParent = this.getWidgetParent(); @@ -1099,6 +1144,13 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ } }, _setXPercent: function (percent) { + if (this._usingLayoutComponent) + { + var component = this._getOrCreateLayoutComponent(); + component.setPositionPercentX(percent.x); + component.refreshLayout(); + return; + } this._positionPercent.x = percent; if (this._running) { var widgetParent = this.getWidgetParent(); @@ -1107,6 +1159,13 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ } }, _setYPercent: function (percent) { + if (this._usingLayoutComponent) + { + var component = this._getOrCreateLayoutComponent(); + component.setPositionPercentY(percent.x); + component.refreshLayout(); + return; + } this._positionPercent.y = percent; if (this._running) { var widgetParent = this.getWidgetParent(); @@ -1120,13 +1179,28 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @returns {cc.Point} 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.getNormalizedPosition()); }, _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; }, @@ -1136,6 +1210,16 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.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); }, @@ -1152,8 +1236,9 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @param {Boolean} flipX true if the widget should be flipped horizontally, false otherwise. */ setFlippedX: function (flipX) { + var realScale = this.getScaleX(); this._flippedX = flipX; - this._updateFlippedX(); + this.setScaleX(realScale); }, /** @@ -1175,8 +1260,9 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @param {Boolean} flipY true if the widget should be flipped vertically, false otherwise. */ setFlippedY: function (flipY) { + var realScale = this.getScaleY(); this._flippedY = flipY; - this._updateFlippedY(); + this.setScaleY(realScale); }, /** @@ -1193,10 +1279,6 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ return this._flippedY; }, - _updateFlippedX: function () {}, - - _updateFlippedY: function () {}, - _adaptRenderers: function(){}, /** @@ -1586,31 +1668,120 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ } }, + /** + * @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){}, + addCCSEventListener: function(callback){ + this._ccEventCallback = callback; + }, //override the scale functions. - setScaleX: function(scaleX){}, - setScaleY: function(scaleY){}, - setScale: function(scaleX, scaleY){}, + 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(){ + cc.log(this.getScaleX() == this.getScaleY(), "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; + }, - getScaleX: function(){}, - getScaleY: function(){}, - getScale: function(){}, + /** + * 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(){ From 1d1539709ae9a30bc8dccb630272902012961b6a Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 12 Jan 2015 14:11:02 +0800 Subject: [PATCH 0122/1345] update build.xml --- tools/build.xml | 33 +++++++++++---------------------- 1 file changed, 11 insertions(+), 22 deletions(-) diff --git a/tools/build.xml b/tools/build.xml index e602c3e0e0..a703fea018 100644 --- a/tools/build.xml +++ b/tools/build.xml @@ -265,28 +265,17 @@ - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + From 8dd86729d79d52818abf4a0499b20cebff63aefa Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 12 Jan 2015 15:10:58 +0800 Subject: [PATCH 0123/1345] Fixed the audio path is error and add LabelBMFont preload info --- extensions/cocostudio/loader/parsers/timelineParser-2.x.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 746e6da38b..a0e7307595 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -935,6 +935,8 @@ widget.setString(text); loadTexture(json["LabelBMFontFile_CNB"], resourcePath, function(path, type){ + if(!cc.loader.getRes(path)) + cc.log("%s need to pre load", path); widget.setFntFile(path); }); return widget; @@ -1015,7 +1017,10 @@ if(volume != null) cc.audioEngine.setMusicVolume(volume); //var name = json["Name"]; - var resPath = (cc.loader.resPath + "/").replace(/\/\/$/, "/"); + var resPath = ""; + if(cc.loader.resPath) + resPath = (cc.loader.resPath + "/").replace(/\/\/$/, "/"); + loadTexture(json["FileData"], resourcePath, function(path, type){ cc.loader.load(path, function(){ cc.audioEngine.playMusic(resPath + path, loop); From 33298c3a74166cff8d7b4b666057c73b91d2b33e Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 12 Jan 2015 16:44:36 +0800 Subject: [PATCH 0124/1345] Issue #1267: update UIButton.js --- extensions/ccui/uiwidgets/UIButton.js | 306 ++++++++++++++------------ 1 file changed, 166 insertions(+), 140 deletions(-) diff --git a/extensions/ccui/uiwidgets/UIButton.js b/extensions/ccui/uiwidgets/UIButton.js index a440c02339..419e532f4f 100644 --- a/extensions/ccui/uiwidgets/UIButton.js +++ b/extensions/ccui/uiwidgets/UIButton.js @@ -126,6 +126,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ }, _initRenderer: function () { + //todo create Scale9Sprite this._buttonNormalRenderer = new cc.Sprite(); this._buttonClickedRenderer = new cc.Sprite(); this._buttonDisableRenderer = new cc.Sprite(); @@ -143,6 +144,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ * @param {Boolean} able true that using scale9 renderer, false otherwise. */ setScale9Enabled: function (able) { + //todo create Scale9Sprite if (this._scale9Enabled == able) return; @@ -201,13 +203,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ */ ignoreContentAdaptWithSize: function (ignore) { if(this._unifySize){ - if(this._scale9Enabled){ - ccui.ProtectedNode.prototype.setContentSize.call(this, this._customSize); - }else{ - var s = this.getVirtualRendererSize(); - ccui.ProtectedNode.prototype.setContentSize.call(this, s); - } - this._onSizeChanged(); + this._updateContentSize(); return; } if (!this._scale9Enabled || (this._scale9Enabled && !ignore)) { @@ -221,9 +217,12 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ * @returns {cc.Size} */ getVirtualRendererSize: function(){ + if (this._unifySize) + return this.getNormalSize(); + var titleSize = this._titleRenderer.getContentSize(); if (!this._normalTextureLoaded && this._titleRenderer.getString().length > 0) { - return titleSize; + return cc.size(titleSize); } return cc.size(this._normalTextureSize); }, @@ -272,41 +271,33 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ }); } - if (this._scale9Enabled) { - var normalRendererScale9 = this._buttonNormalRenderer; - switch (this._normalTexType){ - case ccui.Widget.LOCAL_TEXTURE: - normalRendererScale9.initWithFile(normal); - break; - case ccui.Widget.PLIST_TEXTURE: - normalRendererScale9.initWithSpriteFrameName(normal); - break; - default: - break; - } - normalRendererScale9.setCapInsets(this._capInsetsNormal); - } else { - var normalRenderer = this._buttonNormalRenderer; - 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; - } + var normalRenderer = this._buttonNormalRenderer; + 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; } + if (this._unifySize) + if (this._scale9Enabled){ + normalRenderer.setCapInsets(this._capInsetsNormal); + this._updateContentSizeWithTextureSize(this.getNormalSize()); + } + else + this._updateContentSizeWithTextureSize(this._normalTextureSize); + this._normalTextureSize = this._buttonNormalRenderer.getContentSize(); this._updateFlippedX(); this._updateFlippedY(); this._updateChildrenDisplayedRGBA(); - this._updateContentSizeWithTextureSize(this._normalTextureSize); this._normalTextureLoaded = true; this._normalTextureAdaptDirty = true; }, @@ -338,34 +329,23 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ }); } - if (this._scale9Enabled) { - var clickedRendererScale9 = this._buttonClickedRenderer; - switch (this._pressedTexType) { - case ccui.Widget.LOCAL_TEXTURE: - clickedRendererScale9.initWithFile(selected); - break; - case ccui.Widget.PLIST_TEXTURE: - clickedRendererScale9.initWithSpriteFrameName(selected); - break; - default: - break; - } - clickedRendererScale9.setCapInsets(this._capInsetsPressed); - } else { - var clickedRenderer = this._buttonClickedRenderer; - 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; - } + var clickedRenderer = this._buttonClickedRenderer; + 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._updateFlippedX(); this._updateFlippedY(); @@ -404,34 +384,23 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ }); } - if (this._scale9Enabled) { - var disabledScale9 = this._buttonDisableRenderer; - switch (this._disabledTexType) { - case ccui.Widget.LOCAL_TEXTURE: - disabledScale9.initWithFile(disabled); - break; - case ccui.Widget.PLIST_TEXTURE: - disabledScale9.initWithSpriteFrameName(disabled); - break; - default: - break; - } - disabledScale9.setCapInsets(this._capInsetsDisabled); - } else { - var disabledRenderer = this._buttonDisableRenderer; - 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; - } + var disabledRenderer = this._buttonDisableRenderer; + 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._updateFlippedX(); this._updateFlippedY(); @@ -500,7 +469,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ * @param {cc.Rect} capInsets */ setCapInsetsPressedRenderer: function (capInsets) { - if(!capInsets) + if(!capInsets || !this._scale9Enabled) return; var x = capInsets.x; @@ -525,8 +494,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ locInsets.y = y; locInsets.width = width; locInsets.height = height; - if (!this._scale9Enabled) - return; + this._buttonClickedRenderer.setCapInsets(rect); }, @@ -543,7 +511,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ * @param {cc.Rect} capInsets */ setCapInsetsDisabledRenderer: function (capInsets) { - if(!capInsets) + if(!capInsets || !this._scale9Enabled) return; var x = capInsets.x; @@ -569,8 +537,6 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ locInsets.width = width; locInsets.height = height; - if (!this._scale9Enabled) - return; this._buttonDisableRenderer.setCapInsets(rect); }, @@ -586,6 +552,8 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ this._buttonNormalRenderer.setVisible(true); this._buttonClickedRenderer.setVisible(false); this._buttonDisableRenderer.setVisible(false); + if (this._scale9Enabled) + this._buttonNormalRenderer.setState(0/*Scale9Sprite::State::NORMAL*/); if (this._pressedTextureLoaded) { if (this.pressedActionEnabled){ this._buttonNormalRenderer.stopAllActions(); @@ -595,18 +563,25 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ this._buttonClickedRenderer.setScale(this._pressedTextureScaleXInSize, this._pressedTextureScaleYInSize); this._titleRenderer.stopAllActions(); - this._titleRenderer.runAction(zoomAction.clone()); + if (this._unifySize){ + var zoomTitleAction = cc.scaleTo(0.05/*ZOOM_ACTION_TIME_STEP*/, 1, 1); + this._titleRenderer.runAction(zoomTitleAction); + }else + this._titleRenderer.runAction(zoomAction.clone()); } } else { - if (this._scale9Enabled){ - //todo checking here. old -> this._updateTexturesRGBA(); + this._buttonNormalRenderer.stopAllActions(); + this._buttonNormalRenderer.setScale(this._normalTextureScaleXInSize, this._normalTextureScaleYInSize); + + this._titleRenderer.stopAllActions(); + + if (this._scale9Enabled) this._buttonNormalRenderer.setColor(cc.color.WHITE); - } - else { - this._buttonNormalRenderer.stopAllActions(); - this._buttonNormalRenderer.setScale(this._normalTextureScaleXInSize, this._normalTextureScaleYInSize); - this._titleRenderer.stopAllActions(); + if(this._unifySize){ + this._titleRenderer.setScaleX(1); + this._titleRenderer.setScaleY(1); + }else{ this._titleRenderer.setScaleX(this._normalTextureScaleXInSize); this._titleRenderer.setScaleY(this._normalTextureScaleYInSize); } @@ -615,6 +590,9 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ _onPressStateChangedToPressed: function () { var locNormalRenderer = this._buttonNormalRenderer; + if (this._scale9Enabled) + locNormalRenderer.setState(0/*Scale9Sprite::State::NORMAL*/); + if (this._pressedTextureLoaded) { locNormalRenderer.setVisible(false); this._buttonClickedRenderer.setVisible(true); @@ -627,34 +605,67 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ locNormalRenderer.setScale(this._pressedTextureScaleXInSize + 0.1, this._pressedTextureScaleYInSize + 0.1); this._titleRenderer.stopAllActions(); - //we must call zoomAction->clone here - this._titleRenderer.runAction(zoomAction.clone()); + if (this._unifySize){ + var zoomTitleAction = cc.scaleTo(0.05, 1 + this._zoomScale, 1 + this._zoomScale); + this._titleRenderer.runAction(zoomTitleAction); + } + else + this._titleRenderer.runAction(zoomAction.clone()); } } else { locNormalRenderer.setVisible(true); this._buttonClickedRenderer.setVisible(true); this._buttonDisableRenderer.setVisible(false); + locNormalRenderer.stopAllActions(); + locNormalRenderer.setScale(this._normalTextureScaleXInSize + 0.1, this._normalTextureScaleYInSize + 0.1); + if (this._scale9Enabled) locNormalRenderer.setColor(cc.color.GRAY); - else { - locNormalRenderer.stopAllActions(); - locNormalRenderer.setScale(this._normalTextureScaleXInSize + 0.1, this._normalTextureScaleYInSize + 0.1); - this._titleRenderer.stopAllActions(); + this._titleRenderer.stopAllActions(); + if (this._unifySize){ + this._titleRenderer.setScaleX(1 + this._zoomScale); + this._titleRenderer.setScaleY(1 + this._zoomScale); + }else{ this._titleRenderer.setScaleX(this._normalTextureScaleXInSize + this._zoomScale); this._titleRenderer.setScaleY(this._normalTextureScaleYInSize + this._zoomScale); } + } }, _onPressStateChangedToDisabled: function () { - this._buttonNormalRenderer.setVisible(false); + + //if disable resource is null + if (!this._disabledTextureLoaded){ + if (this._normalTextureLoaded && this._scale9Enabled) + this._buttonNormalRenderer.setState(1/*Scale9Sprite::State::GRAY*/); + }else{ + this._buttonNormalRenderer.setVisible(false); + this._buttonDisableRenderer.setVisible(true); + } + this._buttonClickedRenderer.setVisible(false); - this._buttonDisableRenderer.setVisible(true); 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()); + }, + _updateFlippedX: function () { var flip = this._flippedX ? -1.0 : 1.0; this._titleRenderer.setScaleX(flip); @@ -720,22 +731,21 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ }, _normalTextureScaleChangedWithSize: function () { - if(this._unifySize){ - if (this._scale9Enabled) - this._buttonNormalRenderer.setPreferredSize(this._contentSize); - }else if (this._ignoreSize) { - if (!this._scale9Enabled) { - this._buttonNormalRenderer.setScale(1.0); + if(this._ignoreSize && !this._unifySize){ + if(!this._scale9Enabled){ + this._buttonNormalRenderer.setScale(1); this._normalTextureScaleXInSize = this._normalTextureScaleYInSize = 1; } - } else { - if (this._scale9Enabled) { + }else{ + if (this._scale9Enabled){ this._buttonNormalRenderer.setPreferredSize(this._contentSize); this._normalTextureScaleXInSize = this._normalTextureScaleYInSize = 1; - } else { + this._buttonNormalRenderer.setScale(this._normalTextureScaleXInSize, this._normalTextureScaleYInSize); + }else{ var textureSize = this._normalTextureSize; - if (textureSize.width <= 0.0 || textureSize.height <= 0.0) { - this._buttonNormalRenderer.setScale(1.0); + if (textureSize.width <= 0 || textureSize.height <= 0) + { + this._buttonNormalRenderer.setScale(1); return; } var scaleX = this._contentSize.width / textureSize.width; @@ -746,23 +756,24 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ this._normalTextureScaleYInSize = scaleY; } } - this._buttonNormalRenderer.setPosition(this._contentSize.width / 2.0, this._contentSize.height / 2.0); + this._buttonNormalRenderer.setPosition(this._contentSize.width / 2, this._contentSize.height / 2); }, _pressedTextureScaleChangedWithSize: function () { - if (this._ignoreSize) { + if (this._ignoreSize && !this._unifySize) { if (!this._scale9Enabled) { - this._buttonClickedRenderer.setScale(1.0); + 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.0 || textureSize.height <= 0.0) { - this._buttonClickedRenderer.setScale(1.0); + if (textureSize.width <= 0 || textureSize.height <= 0) { + this._buttonClickedRenderer.setScale(1); return; } var scaleX = this._contentSize.width / textureSize.width; @@ -773,23 +784,21 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ this._pressedTextureScaleYInSize = scaleY; } } - this._buttonClickedRenderer.setPosition(this._contentSize.width / 2.0, this._contentSize.height / 2.0); + this._buttonClickedRenderer.setPosition(this._contentSize.width / 2, this._contentSize.height / 2); }, _disabledTextureScaleChangedWithSize: function () { - if(this._unifySize){ - if (this._scale9Enabled) - this._buttonNormalRenderer.setPreferredSize(this._contentSize); - }else if (this._ignoreSize) { - if (!this._scale9Enabled) - this._buttonDisableRenderer.setScale(1.0); - } else { + 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 { + }else{ var textureSize = this._disabledTextureSize; - if (textureSize.width <= 0.0 || textureSize.height <= 0.0) { - this._buttonDisableRenderer.setScale(1.0); + if (textureSize.width <= 0 || textureSize.height <= 0) { + this._buttonDisableRenderer.setScale(1); return; } var scaleX = this._contentSize.width / textureSize.width; @@ -798,7 +807,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ this._buttonDisableRenderer.setScaleY(scaleY); } } - this._buttonDisableRenderer.setPosition(this._contentSize.width / 2.0, this._contentSize.height / 2.0); + this._buttonDisableRenderer.setPosition(this._contentSize.width / 2, this._contentSize.height / 2); }, _adaptRenderers: function(){ @@ -833,6 +842,8 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ * @param {String} text */ setTitleText: function (text) { + if(text == this.getTitleText()) + return; this._titleRenderer.setString(text); if (this._ignoreSize){ var s = this.getVirtualRendererSize(); @@ -872,6 +883,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ */ setTitleFontSize: function (size) { this._titleRenderer.setFontSize(size); + this._fontSize = size; }, /** @@ -956,6 +968,20 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ setColor: function(color){ cc.ProtectedNode.prototype.setColor.call(this, color); this._updateTexturesRGBA(); + }, + + 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); } }); From 97c40ad032264e737dc716c644ab936a4ef19e78 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Mon, 12 Jan 2015 16:51:06 +0800 Subject: [PATCH 0125/1345] Issue cocos2d/cocos2d-js/#1267: ccui.LayoutComponent has been migrated. --- extensions/ccui/layouts/UILayoutComponent.js | 668 +++++++++++++------ extensions/ccui/system/UIHelper.js | 16 +- 2 files changed, 466 insertions(+), 218 deletions(-) diff --git a/extensions/ccui/layouts/UILayoutComponent.js b/extensions/ccui/layouts/UILayoutComponent.js index b22d7b1a0e..14e40f5e86 100644 --- a/extensions/ccui/layouts/UILayoutComponent.js +++ b/extensions/ccui/layouts/UILayoutComponent.js @@ -41,284 +41,518 @@ ccui.LayoutComponent_SizeType = { PreSizeEnable: 2 }; +//refactor since v3.3 ccui.LayoutComponent = cc.Component.extend({ + _horizontalEdge: 0, + _verticalEdge: 0, - _percentContentSize: null, - _usingPercentContentSize: false, + _leftMargin: 0, + _rightMargin: 0, + _bottomMargin: 0, + _topMargin: 0, - _referencePoint: ccui.LayoutComponent_ReferencePoint.BOTTOM_LEFT, - _relativePosition: null, - _percentPosition: null, - _usingPercentPosition: false, - _actived: true, + _usingPositionPercentX: false, + _positionPercentX: 0, + _usingPositionPercentY: false, + _positionPercentY: 0, + + _usingStretchWidth: false, + _usingStretchHeight: false, + + _percentWidth: 0, + _usingPercentWidth: false, + _percentHeight: 0, + _usingPercentHeight: false, - init: function(){ + _actived: true, + ctor: function(){ + this._name = ccui.LayoutComponent.NAME; + }, + + init: function () { var ret = true; - do - { - if (!cc.Component.prototype.init.call(this)) - { - ret = false; - break; - } - //put layout component initalized code here + if (!cc.Component.prototype.init.call(this)) { + return false; + } + + //put layout component initalized code here - } while (0); return ret; }, - isUsingPercentPosition: function(){ - return this._usingPercentPosition; + getPercentContentSize: function(){ + return cc.p(this._percentWidth, this._percentHeight); }, - setUsingPercentPosition: function(flag){ - this._usingPercentPosition = flag; - this.RefreshLayoutPosition(ccui.LayoutComponent_PositionType.PreRelativePositionEnable, cc.p(0,0)); + setPercentContentSize: function(percent){ + this.setPercentWidth(percent.x); + this.setPercentHeight(percent.y); }, - getPercentPosition: function(){ - return this._percentPosition; + setUsingPercentContentSize: function(isUsed){ + this._usingPercentWidth = this._usingPercentHeight = isUsed; }, - setPercentPosition: function(percent){ - this.RefreshLayoutPosition(ccui.LayoutComponent_PositionType.PreRelativePosition, percent); + + //old + SetActiveEnable: function(enable){ + this._actived = enable; + }, + + //v3.3 + getUsingPercentContentSize: function(){ + return this._usingPercentWidth && this._usingPercentHeight; }, - getRelativePosition: function(){ - return this._relativePosition; + //position & margin + getAnchorPosition: function(){ + return this._owner.getAnchorPoint(); }, - setRelativePosition: function(position){ - this.RefreshLayoutPosition(ccui.LayoutComponent_PositionType.RelativePosition, position); + + 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(); + } }, - setReferencePoint: function(point){ - this._referencePoint = point; - this.RefreshLayoutPosition(ccui.LayoutComponent_PositionType.RelativePosition, this._relativePosition) + isPositionPercentYEnabled: function(){ + return this._usingPositionPercentY; }, - getReferencePoint: function(){ - return this._referencePoint; + setPositionPercentYEnabled: function(isUsed){ + this._usingPositionPercentY = isUsed; + if (this._usingPositionPercentY) + this._verticalEdge = ccui.LayoutComponent.verticalEdge.NONE; }, - getOwnerPosition: function(){ - return this.getOwner().getPosition(); + getPositionPercentY: function(){ + return this._positionPercentY; }, - setOwnerPosition: function(point){ - this.RefreshLayoutPosition(ccui.LayoutComponent_PositionType.Position, point); + setPositionPercentY: function(percentMargin){ + this._positionPercentY = percentMargin; + + var parent = this._getOwnerParent(); + if (parent != null) { + this._owner.setPositionY(parent.height * this._positionPercentY); + this._refreshVerticalMargin(); + } }, - RefreshLayoutPosition: function(pType, point){ - var parentNode = this.getOwner().getParent(); - var basePoint = point; - if (parentNode != null && this._actived) - { - var parentSize = parentNode.getContentSize(); + getHorizontalEdge: function(){ + return this._horizontalEdge; + }, + setHorizontalEdge: function(hEdge){ + this._horizontalEdge = hEdge; + if (this._horizontalEdge != cc.LayoutComponent.horizontalEdge.NONE) + this._usingPositionPercentX = false; - if ( pType == ccui.LayoutComponent_PositionType.PreRelativePosition) - { - this._percentPosition = point; - basePoint = cc.p(this._percentPosition.x * parentSize.width, this._percentPosition.y * parentSize.height); + 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); } - else if(pType == ccui.LayoutComponent_PositionType.PreRelativePositionEnable) - { - if (this._usingPercentPosition) - { - if (parentSize.width != 0) - { - this._percentPosition.x = this._relativePosition.x / parentSize.width; - } - else - { - this._percentPosition.x = 0; - this._relativePosition.x = 0; - } - - if (parentSize.height != 0) - { - this._percentPosition.y = this._relativePosition.y / parentSize.height; - } - else - { - this._percentPosition.y = 0; - this._relativePosition.y = 0; - } - } - basePoint = this._relativePosition; + 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(); + } + }, - var inversePoint = basePoint; - switch (this._referencePoint) - { - case ccui.LayoutComponent_ReferencePoint.TOP_LEFT: - inversePoint.y = parentSize.height - inversePoint.y; - break; - case ccui.LayoutComponent_ReferencePoint.BOTTOM_RIGHT: - inversePoint.x = parentSize.width - inversePoint.x; - break; - case ccui.LayoutComponent_ReferencePoint.TOP_RIGHT: - inversePoint.x = parentSize.width - inversePoint.x; - inversePoint.y = parentSize.height - inversePoint.y; - break; - default: - break; + 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; } - switch (pType) - { - case ccui.LayoutComponent_PositionType.Position: - this.getOwner().setPosition(basePoint); - this._relativePosition = inversePoint; - if (parentSize.width != 0 && parentSize.height != 0) - { - this._percentPosition = cc.p(this._relativePosition.x / parentSize.width, this._relativePosition.y / parentSize.height); - } - else - { - this._percentPosition = cc.p(0,0); - } - break; - case ccui.LayoutComponent_PositionType.RelativePosition: - this.getOwner().setPosition(inversePoint); - this._relativePosition = basePoint; - if (parentSize.width != 0 && parentSize.height != 0) - { - this._percentPosition = cc.p(this._relativePosition.x / parentSize.width, this._relativePosition.y / parentSize.height); - } - else - { - this._percentPosition = cc.p(0,0); - } - break; - case ccui.LayoutComponent_PositionType.PreRelativePosition: - this.getOwner().setPosition(inversePoint); - this._relativePosition = basePoint; - break; - case ccui.LayoutComponent_PositionType.PreRelativePositionEnable: - this.getOwner().setPosition(inversePoint); - this._relativePosition = basePoint; - break; - default: - break; + 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 - { - switch (pType) - { - case ccui.LayoutComponent_PositionType.Position: - this.getOwner().setPosition(basePoint); - if (this._referencePoint == ccui.LayoutComponent_ReferencePoint.BOTTOM_LEFT) - { - this._relativePosition = basePoint; - } - break; - case ccui.LayoutComponent_PositionType.RelativePosition: - this._relativePosition = basePoint; - break; - case ccui.LayoutComponent_PositionType.PreRelativePosition: - this._percentPosition = basePoint; - break; - default: - break; + 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(); } }, - getOwnerContentSize: function(){ - return this.getOwner().getContentSize(); + isPercentHeightEnabled: function(){ + return this._usingPercentHeight; }, - setOwnerContentSize: function(percent){ - this.RefreshLayoutSize(ccui.LayoutComponent_SizeType.Size, percent); + setPercentHeightEnabled: function(isUsed){ + this._usingPercentHeight = isUsed; + if (this._usingPercentHeight) + this._usingStretchHeight = false; }, - getPercentContentSize: function(){ - return this._percentContentSize; + getSizeHeight: function(){ + return this._owner.height; }, - setPercentContentSize: function(percent){ - this.RefreshLayoutSize(ccui.LayoutComponent_SizeType.PreSize, percent); + 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); }, - isUsingPercentContentSize: function(){ - return this._usingPercentContentSize; + getPercentHeight: function(){ + return this._percentHeight; }, - setUsingPercentContentSize: function(flag){ - this._usingPercentContentSize = flag; - this.RefreshLayoutSize(ccui.LayoutComponent_SizeType.PreSizeEnable, cc.p(0,0)); + 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(); + } }, - RefreshLayoutSize: function(sType, size){ - var parentNode = this.getOwner().getParent(); - if (parentNode != null && this._actived) - { - var parentSize = parentNode.getContentSize(); + isStretchWidthEnabled: function(){ + return this._usingStretchWidth; + }, + setStretchWidthEnabled: function(isUsed){ + this._usingStretchWidth = isUsed; + if (this._usingStretchWidth) + this._usingPercentWidth = false; + }, - switch (sType) - { - case ccui.LayoutComponent_SizeType.Size: - if (parentSize.width != 0 && parentSize.height != 0) - { - this._percentContentSize = cc.p(size.x/parentSize.width,size.y/parentSize.height); - } - else - { - this._percentContentSize = cc.p(0,0); + isStretchHeightEnabled: function(){ + return this._usingStretchHeight; + }, + setStretchHeightEnabled: function(isUsed){ + this._usingStretchHeight = isUsed; + if (this._usingStretchHeight) + this._usingPercentHeight = false; + }, + + setActiveEnabled: function(enable){ + this._actived = enable; + }, + refreshLayout: function(){ + var parent = this._getOwnerParent(); + if (parent == null) + return; + + var parentSize = parent.getContentSize(); + var ownerAnchor = this._owner.getAnchorPoint(), ownerSize = this._owner.getContentSize(); + var ownerPosition = this._owner.getPosition(); + + switch (this._horizontalEdge) { + case ccui.LayoutComponent.horizontalEdge.NONE: + if (this._usingStretchWidth){ + 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; } - this.getOwner().setContentSize(cc.size(size.x,size.y)); break; - case ccui.LayoutComponent_SizeType.PreSize: - cc.p_percentContentSize = size; - if (this._usingPercentContentSize) - { - this.getOwner().setContentSize(cc.size(size.x*parentSize.width,size.y*parentSize.height)); - } + case ccui.LayoutComponent.horizontalEdge.LEFT: + if (this._usingPercentWidth || this._usingStretchWidth) + ownerSize.width = parentSize.width * this._percentWidth; + ownerPosition.x = this._leftMargin + ownerAnchor.x * ownerSize.width; break; - case ccui.LayoutComponent_SizeType.PreSizeEnable: - if (this._usingPercentContentSize) - { - var baseSize = this.getOwner().getContentSize(); - if (parentSize.width != 0) - { - this._percentContentSize.x = baseSize.width/parentSize.width; - } - else - { - this._percentContentSize.x = 0; - baseSize.width = 0; - } - - if (parentSize.height != 0) - { - this._percentContentSize.y = baseSize.height/parentSize.height; - } - else - { - this._percentContentSize.y = 0; - baseSize.height = 0; - } - - this.getOwner().setContentSize(baseSize); - } + case ccui.LayoutComponent.horizontalEdge.RIGHT: + 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._usingPercentWidth || 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 + ownerPosition.x = parentSize.width * this._positionPercentX; break; default: break; - } } - else - { - switch (sType) - { - case ccui.LayoutComponent_SizeType.Size: - this.getOwner().setContentSize(cc.size(size.x,size.y)); + + switch (this._verticalEdge) { + case ccui.LayoutComponent.verticalEdge.NONE: + if (this._usingStretchHeight){ + 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_SizeType.PreSize: - this._percentContentSize = size; + case ccui.LayoutComponent.verticalEdge.BOTTOM: + 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._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._usingPercentHeight || 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 + ownerPosition.y = parentSize.height* this._positionPercentY; break; default: break; - } } + + this._owner.setPosition(ownerPosition); + this._owner.setContentSize(ownerSize); + + ccui.helper.doLayout(this._owner); }, - SetActiveEnable: function(enable){ - this._actived = enable; + + _getOwnerParent: function(){ + return this._owner ? this._owner.getParent() : null; + }, + _refreshHorizontalMargin: function(){ + var parent = this._getOwnerParent(); + if (parent == null) + return; + + var ownerPoint = this._owner.getPosition(), ownerAnchor = this._owner.getAnchorPoint(); + var ownerSize = this._owner.getContentSize(), parentSize = parent.getContentSize(); + + this._leftMargin = ownerPoint.x - ownerAnchor.x * ownerSize.width; + this._rightMargin = parentSize.width - (ownerPoint.x + (1 - ownerAnchor.x) * ownerSize.width); + }, + _refreshVerticalMargin: function(){ + var parent = this._getOwnerParent(); + if (parent == null) + return; + + var ownerPoint = this._owner.getPosition(), ownerAnchor = this._owner.getAnchorPoint(); + var ownerSize = this._owner.getContentSize(), parentSize = parent.getContentSize(); + + this._bottomMargin = ownerPoint.y - ownerAnchor.y * ownerSize.height; + this._topMargin = parentSize.height - (ownerPoint.y + (1 - ownerAnchor.y) * ownerSize.height); } +}); + +ccui.LayoutComponent.horizontalEdge = {NONE: 0, LEFT: 1, RIGHT: 2, CENTER: 3}; +ccui.LayoutComponent.verticalEdge = {NONE: 0, BOTTOM: 1, TOP: 2, CENTER: 3}; -}); \ No newline at end of file +ccui.LayoutComponent.NAME= "__ui_layout"; +ccui.LayoutComponent.bindLayoutComponent = function(node){ + var layout = node.getComponent(ccui.LayoutComponent.NAME); + if (layout != null) + return layout; + + layout = new ccui.LayoutComponent(); + if (layout && layout.init()){ + node.addComponent(layout); + return layout; + } + return null; +}; \ No newline at end of file diff --git a/extensions/ccui/system/UIHelper.js b/extensions/ccui/system/UIHelper.js index 73a5109681..802c0f65df 100644 --- a/extensions/ccui/system/UIHelper.js +++ b/extensions/ccui/system/UIHelper.js @@ -117,5 +117,19 @@ ccui.helper = { return res; } return null; - } + } , + + _activeLayout: false, + 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(); + } + } }; From 5b7fb171dad4ed8348c9bf4588782b5f2424a161 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 12 Jan 2015 16:59:54 +0800 Subject: [PATCH 0126/1345] Issue #1267: update UICheckBox.js --- extensions/ccui/uiwidgets/UICheckBox.js | 80 +++++++++++++++---------- 1 file changed, 49 insertions(+), 31 deletions(-) diff --git a/extensions/ccui/uiwidgets/UICheckBox.js b/extensions/ccui/uiwidgets/UICheckBox.js index ab04b6827c..12694cd4c2 100644 --- a/extensions/ccui/uiwidgets/UICheckBox.js +++ b/extensions/ccui/uiwidgets/UICheckBox.js @@ -55,6 +55,10 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ _frontCrossDisabledFileName: "", _className: "CheckBox", + _zoomScale: 0.1, + _backgroundTextureScaleX: 0.1, + _backgroundTextureScaleY: 0.1, + _backGroundBoxRendererAdaptDirty:true, _backGroundSelectedBoxRendererAdaptDirty:true, _frontCrossRendererAdaptDirty: true, @@ -139,7 +143,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ * @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType */ loadTextureBackGround: function (backGround, texType) { - if (!backGround) + if (!backGround || (this._backGroundFileName == backGround && this._backGroundTexType == texType)) return; texType = texType || ccui.Widget.LOCAL_TEXTURE; @@ -194,7 +198,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ * @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType */ loadTextureBackGroundSelected: function (backGroundSelected, texType) { - if (!backGroundSelected) + if (!backGroundSelected || (this._backGroundSelectedFileName == backGroundSelected && this._backGroundSelectedTexType == texType)) return; texType = texType || ccui.Widget.LOCAL_TEXTURE; @@ -240,7 +244,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ * @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType */ loadTextureFrontCross: function (cross, texType) { - if (!cross) + if (!cross || (this._frontCrossFileName == cross && this._frontCrossTexType == texType)) return; texType = texType || ccui.Widget.LOCAL_TEXTURE; this._frontCrossFileName = cross; @@ -284,7 +288,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ * @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType */ loadTextureBackGroundDisabled: function (backGroundDisabled, texType) { - if (!backGroundDisabled) + if (!backGroundDisabled || (this._backGroundDisabledFileName == backGroundDisabled && this._backGroundDisabledTexType == texType)) return; texType = texType || ccui.Widget.LOCAL_TEXTURE; this._backGroundDisabledFileName = backGroundDisabled; @@ -328,7 +332,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ * @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType */ loadTextureFrontCrossDisabled: function (frontCrossDisabled, texType) { - if (!frontCrossDisabled) + if (!frontCrossDisabled || (this._frontCrossDisabledFileName == frontCrossDisabled && this._frontCrossDisabledTexType == texType)) return; texType = texType || ccui.Widget.LOCAL_TEXTURE; this._frontCrossDisabledFileName = frontCrossDisabled; @@ -371,28 +375,50 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ this._backGroundSelectedBoxRenderer.setVisible(false); this._backGroundBoxDisabledRenderer.setVisible(false); this._frontCrossDisabledRenderer.setVisible(false); - if (this._isSelected){ + + this._backGroundBoxRenderer.setScale(this._backgroundTextureScaleX, this._backgroundTextureScaleY); + this._frontCrossRenderer.setScale(this._backgroundTextureScaleX, this._backgroundTextureScaleY); + + if (this._isSelected) this._frontCrossRenderer.setVisible(true); - } }, _onPressStateChangedToPressed: function () { - this._backGroundBoxRenderer.setVisible(false); - this._backGroundSelectedBoxRenderer.setVisible(true); - this._backGroundBoxDisabledRenderer.setVisible(false); - this._frontCrossDisabledRenderer.setVisible(false); + if (!this._backGroundSelectedFileName){ + this._backGroundBoxRenderer.setScale(this._backgroundTextureScaleX + this._zoomScale, this._backgroundTextureScaleY + this._zoomScale); + this._frontCrossRenderer.setScale(this._backgroundTextureScaleX + this._zoomScale, this._backgroundTextureScaleY + this._zoomScale); + }else{ + this._backGroundBoxRenderer.setVisible(false); + this._backGroundSelectedBoxRenderer.setVisible(true); + this._backGroundBoxDisabledRenderer.setVisible(false); + this._frontCrossDisabledRenderer.setVisible(false); + } }, _onPressStateChangedToDisabled: function () { - this._backGroundBoxRenderer.setVisible(false); + if (this._backGroundDisabledFileName && this._frontCrossDisabledFileName){ + this._backGroundBoxRenderer.setVisible(false); + this._backGroundBoxDisabledRenderer.setVisible(true); + } + this._backGroundSelectedBoxRenderer.setVisible(false); - this._backGroundBoxDisabledRenderer.setVisible(true); this._frontCrossRenderer.setVisible(false); + this._backGroundBoxRenderer.setScale(this._backgroundTextureScaleX, this._backgroundTextureScaleY); + this._frontCrossRenderer.setScale(this._backgroundTextureScaleX, this._backgroundTextureScaleY); + if (this._isSelected) { this._frontCrossDisabledRenderer.setVisible(true); } }, + setZoomScale: function(scale){ + this._zoomScale = scale; + }, + + getZoomScale: function(){ + return this._zoomScale; + }, + /** * @deprecated since v3.1, please use setSelected. */ @@ -483,22 +509,6 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ return this._backGroundBoxRenderer.getContentSize(); }, - _updateFlippedX: function () { - this._backGroundBoxRenderer.setFlippedX(this._flippedX); - this._backGroundSelectedBoxRenderer.setFlippedX(this._flippedX); - this._frontCrossRenderer.setFlippedX(this._flippedX); - this._backGroundBoxDisabledRenderer.setFlippedX(this._flippedX); - this._frontCrossDisabledRenderer.setFlippedX(this._flippedX); - }, - - _updateFlippedY: function () { - this._backGroundBoxRenderer.setFlippedY(this._flippedY); - this._backGroundSelectedBoxRenderer.setFlippedY(this._flippedY); - this._frontCrossRenderer.setFlippedY(this._flippedY); - this._backGroundBoxDisabledRenderer.setFlippedY(this._flippedY); - this._frontCrossDisabledRenderer.setFlippedY(this._flippedY); - }, - _onSizeChanged: function () { ccui.Widget.prototype._onSizeChanged.call(this); this._backGroundBoxRendererAdaptDirty = true; @@ -519,16 +529,20 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ _backGroundTextureScaleChangedWithSize: function () { var locRenderer = this._backGroundBoxRenderer, locContentSize = this._contentSize; - if (this._ignoreSize) + if (this._ignoreSize){ locRenderer.setScale(1.0); - else{ + this._backgroundTextureScaleX = this._backgroundTextureScaleY = 1; + }else{ var textureSize = locRenderer.getContentSize(); if (textureSize.width <= 0.0 || textureSize.height <= 0.0){ locRenderer.setScale(1.0); + this._backgroundTextureScaleX = this._backgroundTextureScaleY = 1; return; } var scaleX = locContentSize.width / textureSize.width; var scaleY = locContentSize.height / textureSize.height; + this._backgroundTextureScaleX = scaleX; + this._backgroundTextureScaleY = scaleY; locRenderer.setScaleX(scaleX); locRenderer.setScaleY(scaleY); } @@ -630,6 +644,10 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ this.setSelected(uiCheckBox._isSelected); this._checkBoxEventListener = uiCheckBox._checkBoxEventListener; this._checkBoxEventSelector = uiCheckBox._checkBoxEventSelector; + this._ccEventCallback = uiCheckBox._ccEventCallback; + this._zoomScale = uiCheckBox._zoomScale; + this._backgroundTextureScaleX = uiCheckBox._backgroundTextureScaleX; + this._backgroundTextureScaleY = uiCheckBox._backgroundTextureScaleY; } }, From f4433a4d4f6378e44af8f923f054f1950c3a3147 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 12 Jan 2015 17:02:05 +0800 Subject: [PATCH 0127/1345] Issue #1267: remove _updateFlipped --- extensions/ccui/uiwidgets/UIButton.js | 40 ------------------------- extensions/ccui/uiwidgets/UICheckBox.js | 20 ------------- 2 files changed, 60 deletions(-) diff --git a/extensions/ccui/uiwidgets/UIButton.js b/extensions/ccui/uiwidgets/UIButton.js index 419e532f4f..8cd10b38c7 100644 --- a/extensions/ccui/uiwidgets/UIButton.js +++ b/extensions/ccui/uiwidgets/UIButton.js @@ -258,8 +258,6 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ self._findLayout(); self._normalTextureSize = self._buttonNormalRenderer.getContentSize(); - self._updateFlippedX(); - self._updateFlippedY(); self._updateChildrenDisplayedRGBA(); self._buttonNormalRenderer.setColor(self.getColor()); @@ -293,8 +291,6 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ this._updateContentSizeWithTextureSize(this._normalTextureSize); this._normalTextureSize = this._buttonNormalRenderer.getContentSize(); - this._updateFlippedX(); - this._updateFlippedY(); this._updateChildrenDisplayedRGBA(); @@ -320,8 +316,6 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ self._findLayout(); self._pressedTextureSize = self._buttonClickedRenderer.getContentSize(); - self._updateFlippedX(); - self._updateFlippedY(); self._updateChildrenDisplayedRGBA(); self._pressedTextureLoaded = true; @@ -347,8 +341,6 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ clickedRenderer.setCapInsets(this._capInsetsPressed); this._pressedTextureSize = this._buttonClickedRenderer.getContentSize(); - this._updateFlippedX(); - this._updateFlippedY(); this._updateChildrenDisplayedRGBA(); @@ -375,8 +367,6 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ self._findLayout(); self._disabledTextureSize = self._buttonDisableRenderer.getContentSize(); - self._updateFlippedX(); - self._updateFlippedY(); self._updateChildrenDisplayedRGBA(); self._disabledTextureLoaded = true; @@ -402,8 +392,6 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ disabledRenderer.setCapInsets(this._capInsetsDisabled); this._disabledTextureSize = this._buttonDisableRenderer.getContentSize(); - this._updateFlippedX(); - this._updateFlippedY(); this._updateChildrenDisplayedRGBA(); @@ -666,34 +654,6 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ this.setContentSize(this.getVirtualRendererSize()); }, - _updateFlippedX: function () { - var flip = this._flippedX ? -1.0 : 1.0; - this._titleRenderer.setScaleX(flip); - if (this._scale9Enabled) { - this._buttonNormalRenderer.setScaleX(flip); - this._buttonClickedRenderer.setScaleX(flip); - this._buttonDisableRenderer.setScaleX(flip); - } else { - this._buttonNormalRenderer.setFlippedX(this._flippedX); - this._buttonClickedRenderer.setFlippedX(this._flippedX); - this._buttonDisableRenderer.setFlippedX(this._flippedX); - } - }, - - _updateFlippedY: function () { - var flip = this._flippedY ? -1.0 : 1.0; - this._titleRenderer.setScaleY(flip); - if (this._scale9Enabled) { - this._buttonNormalRenderer.setScaleY(flip); - this._buttonClickedRenderer.setScaleY(flip); - this._buttonDisableRenderer.setScaleY(flip); - } else { - this._buttonNormalRenderer.setFlippedY(this._flippedY); - this._buttonClickedRenderer.setFlippedY(this._flippedY); - this._buttonDisableRenderer.setFlippedY(this._flippedY); - } - }, - _updateTexturesRGBA: function(){ this._buttonNormalRenderer.setColor(this.getColor()); this._buttonClickedRenderer.setColor(this.getColor()); diff --git a/extensions/ccui/uiwidgets/UICheckBox.js b/extensions/ccui/uiwidgets/UICheckBox.js index 12694cd4c2..9a027bc98e 100644 --- a/extensions/ccui/uiwidgets/UICheckBox.js +++ b/extensions/ccui/uiwidgets/UICheckBox.js @@ -156,8 +156,6 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ bgBoxRenderer.addEventListener("load", function(){ self._findLayout(); - self._updateFlippedX(); - self._updateFlippedY(); self._updateChildrenDisplayedRGBA(); self._updateContentSizeWithTextureSize(self._backGroundBoxRenderer.getContentSize()); self._backGroundBoxRendererAdaptDirty = true; @@ -183,8 +181,6 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ this._updateContentSizeWithTextureSize(this._backGroundBoxRenderer.getContentSize()); }, this); } - this._updateFlippedX(); - this._updateFlippedY(); this._updateChildrenDisplayedRGBA(); @@ -210,8 +206,6 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ this._backGroundSelectedBoxRenderer.addEventListener("load", function(){ self._findLayout(); - self._updateFlippedX(); - self._updateFlippedY(); self._updateChildrenDisplayedRGBA(); self._backGroundSelectedBoxRendererAdaptDirty = true; }); @@ -230,8 +224,6 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ break; } - this._updateFlippedX(); - this._updateFlippedY(); this._updateChildrenDisplayedRGBA(); @@ -255,8 +247,6 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ this._frontCrossRenderer.addEventListener("load", function(){ self._findLayout(); - self._updateFlippedX(); - self._updateFlippedY(); self._updateChildrenDisplayedRGBA(); self._frontCrossRendererAdaptDirty = true; }); @@ -274,8 +264,6 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ default: break; } - this._updateFlippedX(); - this._updateFlippedY(); this._updateChildrenDisplayedRGBA(); @@ -299,8 +287,6 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ this._backGroundBoxDisabledRenderer.addEventListener("load", function(){ self._findLayout(); - self._updateFlippedX(); - self._updateFlippedY(); self._updateChildrenDisplayedRGBA(); self._backGroundBoxDisabledRendererAdaptDirty = true; }); @@ -318,8 +304,6 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ default: break; } - this._updateFlippedX(); - this._updateFlippedY(); this._updateChildrenDisplayedRGBA(); @@ -343,8 +327,6 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ this._frontCrossDisabledRenderer.addEventListener("load", function(){ self._findLayout(); - self._updateFlippedX(); - self._updateFlippedY(); self._updateChildrenDisplayedRGBA(); self._frontCrossDisabledRendererAdaptDirty = true; }); @@ -362,8 +344,6 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ default: break; } - this._updateFlippedX(); - this._updateFlippedY(); this._updateChildrenDisplayedRGBA(); From 82f0cd69e005009af259c86d850a59c05ec87dd7 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 12 Jan 2015 17:23:51 +0800 Subject: [PATCH 0128/1345] Issue #1267: update UIImageView.js --- extensions/ccui/uiwidgets/UIImageView.js | 52 +++++++++--------------- 1 file changed, 19 insertions(+), 33 deletions(-) diff --git a/extensions/ccui/uiwidgets/UIImageView.js b/extensions/ccui/uiwidgets/UIImageView.js index dba1462977..a951d07ed0 100644 --- a/extensions/ccui/uiwidgets/UIImageView.js +++ b/extensions/ccui/uiwidgets/UIImageView.js @@ -74,6 +74,7 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{ }, _initRenderer: function () { + //todo create Scale9Sprite and setScale9Enabled(false) this._imageRenderer = new cc.Sprite(); this.addProtectedChild(this._imageRenderer, ccui.ImageView.RENDERER_ZORDER, -1); }, @@ -88,6 +89,8 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{ * @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType */ loadTexture: function (fileName, texType) { + //todo use this code when _initRenderer use Scale9Sprite + //if (!fileName || (this._textureFile == fileName && this._imageTexType == texType)) { if (!fileName) { return; } @@ -97,6 +100,21 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{ this._imageTexType = texType; var imageRenderer = self._imageRenderer; + if(!imageRenderer.texture || !imageRenderer.texture.isLoaded()){ + imageRenderer.addEventListener("load", function(){ + self._findLayout(); + + self._imageTextureSize = imageRenderer.getContentSize(); + + self._updateChildrenDisplayedRGBA(); + + self._updateContentSizeWithTextureSize(self._imageTextureSize); + if(self._scale9Enabled) + self.setCapInsets(self._capInsets); + self._imageRendererAdaptDirty = true; + }); + } + switch (self._imageTexType) { case ccui.Widget.LOCAL_TEXTURE: if(self._scale9Enabled){ @@ -120,26 +138,7 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{ break; } - if(!imageRenderer.texture || !imageRenderer.texture.isLoaded()){ - imageRenderer.addEventListener("load", function(){ - self._findLayout(); - - self._imageTextureSize = imageRenderer.getContentSize(); - self._updateFlippedX(); - self._updateFlippedY(); - - self._updateChildrenDisplayedRGBA(); - - self._updateContentSizeWithTextureSize(self._imageTextureSize); - if(self._scale9Enabled) - self.setCapInsets(self._capInsets); - self._imageRendererAdaptDirty = true; - }); - } - self._imageTextureSize = imageRenderer.getContentSize(); - self._updateFlippedX(); - self._updateFlippedY(); this._updateChildrenDisplayedRGBA(); @@ -156,25 +155,12 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{ this._imageRenderer.setTextureRect(rect); }, - _updateFlippedX: function () { - if (this._scale9Enabled) - this._imageRenderer.setScaleX(this._flippedX ? -1 : 1); - else - this._imageRenderer.setFlippedX(this._flippedX); - }, - - _updateFlippedY: function () { - if (this._scale9Enabled) - this._imageRenderer.setScaleY(this._flippedY ? -1 : 1); - else - this._imageRenderer.setFlippedY(this._flippedY); - }, - /** * Sets if button is using scale9 renderer. * @param {Boolean} able */ setScale9Enabled: function (able) { + //todo setScale9Enabled if (this._scale9Enabled == able) return; From 0d7366355c9affe440c4cf8bc894f53971fbacb1 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 12 Jan 2015 17:38:57 +0800 Subject: [PATCH 0129/1345] Issue #1267: update UILoadingBar.js --- extensions/ccui/uiwidgets/UILoadingBar.js | 34 +++++++++++------------ 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/extensions/ccui/uiwidgets/UILoadingBar.js b/extensions/ccui/uiwidgets/UILoadingBar.js index bf7bc314f7..ed28c83720 100644 --- a/extensions/ccui/uiwidgets/UILoadingBar.js +++ b/extensions/ccui/uiwidgets/UILoadingBar.js @@ -68,6 +68,7 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{ }, _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); @@ -84,13 +85,13 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{ this._direction = dir; switch (this._direction) { case ccui.LoadingBar.TYPE_LEFT: - this._barRenderer.setAnchorPoint(0.0, 0.5); + 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, 0.5); + this._barRenderer.setAnchorPoint(1, 0.5); this._barRenderer.setPosition(this._totalLength,this._contentSize.height*0.5); if (!this._scale9Enabled) this._barRenderer.setFlippedX(true); @@ -151,20 +152,10 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{ switch (this._renderBarTexType) { case ccui.Widget.LOCAL_TEXTURE: - if (this._scale9Enabled){ - barRenderer.initWithFile(texture); - barRenderer.setCapInsets(this._capInsets); - } else - //SetTexture cannot load resource - barRenderer.initWithFile(texture); + barRenderer.initWithFile(texture); break; case ccui.Widget.PLIST_TEXTURE: - if (this._scale9Enabled) { - barRenderer.initWithSpriteFrameName(texture); - barRenderer.setCapInsets(this._capInsets); - } else - //SetTexture cannot load resource - barRenderer.initWithSpriteFrameName(texture); + barRenderer.initWithSpriteFrameName(texture); break; default: break; @@ -176,16 +167,19 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{ switch (this._direction) { case ccui.LoadingBar.TYPE_LEFT: - barRenderer.setAnchorPoint(0.0,0.5); + barRenderer.setAnchorPoint(0,0.5); if (!this._scale9Enabled) barRenderer.setFlippedX(false); break; case ccui.LoadingBar.TYPE_RIGHT: - barRenderer.setAnchorPoint(1.0,0.5); + 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); @@ -197,6 +191,7 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{ * @param {Boolean} enabled */ setScale9Enabled: function (enabled) { + //todo use setScale9Enabled if (this._scale9Enabled == enabled) return; this._scale9Enabled = enabled; @@ -254,7 +249,11 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{ * @param {number} percent percent value from 1 to 100. */ setPercent: function (percent) { - if (percent < 0 || percent > 100) + if(percent > 100) + percent = 100; + if(percent < 0) + percent = 0; + if (percent == this._percent) return; this._percent = percent; if (this._totalLength <= 0) @@ -341,7 +340,6 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{ _barRendererScaleChangedWithSize: function () { var locBarRender = this._barRenderer, locContentSize = this._contentSize; if(this._unifySize){ - //_barRenderer->setPreferredSize(_contentSize); this._totalLength = this._contentSize.width; this.setPercent(this._percent); }else if (this._ignoreSize) { From f768e9e26d86b4cac99eb6e6df168270e9cb8e2f Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Mon, 12 Jan 2015 17:45:55 +0800 Subject: [PATCH 0130/1345] Issue cocos2d/cocos2d-js/#1267: ccui.Layout has been migrated. --- extensions/ccui/layouts/UILayout.js | 75 ++++------ extensions/ccui/layouts/UILayoutComponent.js | 140 +++++++++---------- 2 files changed, 101 insertions(+), 114 deletions(-) diff --git a/extensions/ccui/layouts/UILayout.js b/extensions/ccui/layouts/UILayout.js index 7bd7f771a0..4a6273aeac 100644 --- a/extensions/ccui/layouts/UILayout.js +++ b/extensions/ccui/layouts/UILayout.js @@ -516,34 +516,19 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ this._backGroundImageFileName = fileName; this._bgImageTexType = texType; var locBackgroundImage = this._backGroundImage; - if (this._backGroundScale9Enabled) { - var bgiScale9 = locBackgroundImage; - switch (this._bgImageTexType) { - case ccui.Widget.LOCAL_TEXTURE: - bgiScale9.initWithFile(fileName); - break; - case ccui.Widget.PLIST_TEXTURE: - bgiScale9.initWithSpriteFrameName(fileName); - break; - default: - break; - } - bgiScale9.setPreferredSize(this._contentSize); - } else { - var sprite = locBackgroundImage; - switch (this._bgImageTexType){ - case ccui.Widget.LOCAL_TEXTURE: - //SetTexture cannot load resource - sprite.initWithFile(fileName); - break; - case ccui.Widget.PLIST_TEXTURE: - //SetTexture cannot load resource - sprite.initWithSpriteFrameName(fileName); - break; - default: - break; - } + 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(); @@ -597,13 +582,14 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ }, _addBackGroundImage: function () { + var contentSize = this._contentSize; if (this._backGroundScale9Enabled) { this._backGroundImage = new ccui.Scale9Sprite(); - this._backGroundImage.setPreferredSize(this._contentSize); + this._backGroundImage.setPreferredSize(contentSize); } else this._backGroundImage = new cc.Sprite(); this.addProtectedChild(this._backGroundImage, ccui.Layout.BACKGROUND_IMAGE_ZORDER, -1); - this._backGroundImage.setPosition(this._contentSize.width / 2.0, this._contentSize.height / 2.0); + this._backGroundImage.setPosition(contentSize.width * 0.5, contentSize.height * 0.5); }, /** @@ -863,7 +849,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ }, /** - * request do layout, it will do layout at visit calls + * request to refresh widget layout, it will do layout at visit calls */ requestDoLayout: function () { this._doLayoutDirty = true; @@ -1203,22 +1189,15 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ } } else return this._getNextFocusedWidget(direction, nextWidget); - } else { - if (current instanceof ccui.Layout) - return current; - else - return this._focusedWidget; - } + } else + return (current instanceof ccui.Layout) ? current : this._focusedWidget; } else{ if (this._isLastWidgetInContainer(current, direction)){ if (this._isWidgetAncestorSupportLoopFocus(this, direction)) - return this.findNextFocusedWidget(direction, this); - if (current instanceof ccui.Layout) - return current; - else - return this._focusedWidget; + return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, this); + return (current instanceof ccui.Layout) ? current : this._focusedWidget; } else - return this.findNextFocusedWidget(direction, this); + return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, this); } } }, @@ -1265,10 +1244,10 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ } else { if (this._isLastWidgetInContainer(current, direction)) { if (this._isWidgetAncestorSupportLoopFocus(this, direction)) - return this.findNextFocusedWidget(direction, this); + return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, this); return (current instanceof ccui.Layout) ? current : this._focusedWidget; } else - return this.findNextFocusedWidget(direction, this); + return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, this); } } }, @@ -1464,6 +1443,14 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ this._isInterceptTouch = layout._isInterceptTouch; }, + /** + * force refresh widget layout + */ + forceDoLayout: function(){ + this.requestDoLayout(); + this._doLayout(); + }, + _createRenderCmd: function(){ if(cc._renderType === cc._RENDER_TYPE_WEBGL) return new ccui.Layout.WebGLRenderCmd(this); diff --git a/extensions/ccui/layouts/UILayoutComponent.js b/extensions/ccui/layouts/UILayoutComponent.js index 14e40f5e86..73fbdff28b 100644 --- a/extensions/ccui/layouts/UILayoutComponent.js +++ b/extensions/ccui/layouts/UILayoutComponent.js @@ -43,7 +43,7 @@ ccui.LayoutComponent_SizeType = { //refactor since v3.3 ccui.LayoutComponent = cc.Component.extend({ - _horizontalEdge: 0, + _horizontalEdge: 0, _verticalEdge: 0, _leftMargin: 0, @@ -66,7 +66,7 @@ ccui.LayoutComponent = cc.Component.extend({ _usingPercentHeight: false, _actived: true, - ctor: function(){ + ctor: function () { this._name = ccui.LayoutComponent.NAME; }, @@ -82,34 +82,34 @@ ccui.LayoutComponent = cc.Component.extend({ return ret; }, - getPercentContentSize: function(){ + getPercentContentSize: function () { return cc.p(this._percentWidth, this._percentHeight); }, - setPercentContentSize: function(percent){ + setPercentContentSize: function (percent) { this.setPercentWidth(percent.x); this.setPercentHeight(percent.y); }, - setUsingPercentContentSize: function(isUsed){ + setUsingPercentContentSize: function (isUsed) { this._usingPercentWidth = this._usingPercentHeight = isUsed; }, //old - SetActiveEnable: function(enable){ + SetActiveEnable: function (enable) { this._actived = enable; }, //v3.3 - getUsingPercentContentSize: function(){ + getUsingPercentContentSize: function () { return this._usingPercentWidth && this._usingPercentHeight; }, //position & margin - getAnchorPosition: function(){ + getAnchorPosition: function () { return this._owner.getAnchorPoint(); }, - setAnchorPosition: function(point, y){ + setAnchorPosition: function (point, y) { var oldRect = this._owner.getBoundingBox(); this._owner.setAnchorPoint(point, y); var newRect = this._owner.getBoundingBox(); @@ -121,17 +121,17 @@ ccui.LayoutComponent = cc.Component.extend({ this.setPosition(ownerPosition); }, - getPosition: function(){ + getPosition: function () { return this._owner.getPosition(); }, - setPosition: function(position, y){ + setPosition: function (position, y) { var parent = this._getOwnerParent(), x; if (parent != null) { - if(y === undefined){ + if (y === undefined) { x = position.x; y = position.y; - }else + } else x = position; var parentSize = parent.getContentSize(); @@ -158,19 +158,19 @@ ccui.LayoutComponent = cc.Component.extend({ this._owner.setPosition(position, y); }, - isPositionPercentXEnabled: function(){ + isPositionPercentXEnabled: function () { return this._usingPositionPercentX; }, - setPositionPercentXEnabled: function(isUsed){ + setPositionPercentXEnabled: function (isUsed) { this._usingPositionPercentX = isUsed; if (this._usingPositionPercentX) this._horizontalEdge = ccui.LayoutComponent.horizontalEdge.NONE; }, - getPositionPercentX: function(){ + getPositionPercentX: function () { return this._positionPercentX; }, - setPositionPercentX: function(percentMargin){ + setPositionPercentX: function (percentMargin) { this._positionPercentX = percentMargin; var parent = this._getOwnerParent(); @@ -180,19 +180,19 @@ ccui.LayoutComponent = cc.Component.extend({ } }, - isPositionPercentYEnabled: function(){ + isPositionPercentYEnabled: function () { return this._usingPositionPercentY; }, - setPositionPercentYEnabled: function(isUsed){ + setPositionPercentYEnabled: function (isUsed) { this._usingPositionPercentY = isUsed; if (this._usingPositionPercentY) this._verticalEdge = ccui.LayoutComponent.verticalEdge.NONE; }, - getPositionPercentY: function(){ + getPositionPercentY: function () { return this._positionPercentY; }, - setPositionPercentY: function(percentMargin){ + setPositionPercentY: function (percentMargin) { this._positionPercentY = percentMargin; var parent = this._getOwnerParent(); @@ -202,10 +202,10 @@ ccui.LayoutComponent = cc.Component.extend({ } }, - getHorizontalEdge: function(){ + getHorizontalEdge: function () { return this._horizontalEdge; }, - setHorizontalEdge: function(hEdge){ + setHorizontalEdge: function (hEdge) { this._horizontalEdge = hEdge; if (this._horizontalEdge != cc.LayoutComponent.horizontalEdge.NONE) this._usingPositionPercentX = false; @@ -226,10 +226,10 @@ ccui.LayoutComponent = cc.Component.extend({ } }, - getVerticalEdge: function(){ + getVerticalEdge: function () { return this._verticalEdge; }, - setVerticalEdge: function(vEdge){ + setVerticalEdge: function (vEdge) { this._verticalEdge = vEdge; if (this._verticalEdge != ccui.LayoutComponent.verticalEdge.NONE) this._usingPositionPercentY = false; @@ -250,45 +250,45 @@ ccui.LayoutComponent = cc.Component.extend({ } }, - getLeftMargin: function(){ + getLeftMargin: function () { return this._leftMargin; }, - setLeftMargin: function(margin){ + setLeftMargin: function (margin) { this._leftMargin = margin; }, - getRightMargin: function(){ + getRightMargin: function () { return this._rightMargin; }, - setRightMargin: function(margin){ + setRightMargin: function (margin) { this._rightMargin = margin; }, - getTopMargin: function(){ + getTopMargin: function () { return this._topMargin; }, - setTopMargin: function(margin){ + setTopMargin: function (margin) { this._topMargin = margin; }, - getBottomMargin: function(){ + getBottomMargin: function () { return this._bottomMargin; }, - setBottomMargin: function(margin){ + setBottomMargin: function (margin) { this._bottomMargin = margin; }, //size & - getSize: function(){ + getSize: function () { return this.getOwner().getContentSize(); }, - setSize: function(size){ + 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; + this._percentWidth = ownerSize.width / parentSize.width; else { this._percentWidth = 0; if (this._usingPercentWidth) @@ -312,19 +312,19 @@ ccui.LayoutComponent = cc.Component.extend({ this._owner.setContentSize(size); }, - isPercentWidthEnabled: function(){ + isPercentWidthEnabled: function () { return this._usingPercentWidth; }, - setPercentWidthEnabled: function(isUsed){ + setPercentWidthEnabled: function (isUsed) { this._usingPercentWidth = isUsed; if (this._usingPercentWidth) this._usingStretchWidth = false; }, - getSizeWidth: function(){ + getSizeWidth: function () { return this._owner.width; }, - setSizeWidth: function(width){ + setSizeWidth: function (width) { var ownerSize = this._owner.getContentSize(); ownerSize.width = width; @@ -344,10 +344,10 @@ ccui.LayoutComponent = cc.Component.extend({ this._owner.setContentSize(ownerSize); }, - getPercentWidth: function(){ + getPercentWidth: function () { return this._percentWidth; }, - setPercentWidth: function(percentWidth){ + setPercentWidth: function (percentWidth) { this._percentWidth = percentWidth; var parent = this._getOwnerParent(); @@ -359,19 +359,19 @@ ccui.LayoutComponent = cc.Component.extend({ } }, - isPercentHeightEnabled: function(){ + isPercentHeightEnabled: function () { return this._usingPercentHeight; }, - setPercentHeightEnabled: function(isUsed){ + setPercentHeightEnabled: function (isUsed) { this._usingPercentHeight = isUsed; if (this._usingPercentHeight) this._usingStretchHeight = false; }, - getSizeHeight: function(){ + getSizeHeight: function () { return this._owner.height; }, - setSizeHeight: function(height){ + setSizeHeight: function (height) { var ownerSize = this._owner.getContentSize(); ownerSize.height = height; @@ -392,10 +392,10 @@ ccui.LayoutComponent = cc.Component.extend({ this._owner.setContentSize(ownerSize); }, - getPercentHeight: function(){ + getPercentHeight: function () { return this._percentHeight; }, - setPercentHeight: function(percentHeight){ + setPercentHeight: function (percentHeight) { this._percentHeight = percentHeight; var parent = this._getOwnerParent(); @@ -407,39 +407,39 @@ ccui.LayoutComponent = cc.Component.extend({ } }, - isStretchWidthEnabled: function(){ + isStretchWidthEnabled: function () { return this._usingStretchWidth; }, - setStretchWidthEnabled: function(isUsed){ + setStretchWidthEnabled: function (isUsed) { this._usingStretchWidth = isUsed; if (this._usingStretchWidth) this._usingPercentWidth = false; }, - isStretchHeightEnabled: function(){ + isStretchHeightEnabled: function () { return this._usingStretchHeight; }, - setStretchHeightEnabled: function(isUsed){ + setStretchHeightEnabled: function (isUsed) { this._usingStretchHeight = isUsed; if (this._usingStretchHeight) this._usingPercentHeight = false; }, - setActiveEnabled: function(enable){ + setActiveEnabled: function (enable) { this._actived = enable; }, - refreshLayout: function(){ + refreshLayout: function () { var parent = this._getOwnerParent(); if (parent == null) return; - var parentSize = parent.getContentSize(); - var ownerAnchor = this._owner.getAnchorPoint(), ownerSize = this._owner.getContentSize(); - var ownerPosition = this._owner.getPosition(); + 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){ + if (this._usingStretchWidth) { ownerSize.width = parentSize.width * this._percentWidth; ownerPosition.x = this._leftMargin + ownerAnchor.x * ownerSize.width; } else { @@ -460,7 +460,7 @@ ccui.LayoutComponent = cc.Component.extend({ ownerPosition.x = parentSize.width - (this._rightMargin + (1 - ownerAnchor.x) * ownerSize.width); break; case ccui.LayoutComponent.horizontalEdge.CENTER: - if (this._usingPercentWidth || this._usingStretchWidth){ + if (this._usingPercentWidth || this._usingStretchWidth) { ownerSize.width = parentSize.width - this._leftMargin - this._rightMargin; if (ownerSize.width < 0) ownerSize.width = 0; @@ -474,7 +474,7 @@ ccui.LayoutComponent = cc.Component.extend({ switch (this._verticalEdge) { case ccui.LayoutComponent.verticalEdge.NONE: - if (this._usingStretchHeight){ + if (this._usingStretchHeight) { ownerSize.height = parentSize.height * this._percentHeight; ownerPosition.y = this._bottomMargin + ownerAnchor.y * ownerSize.height; } else { @@ -501,22 +501,22 @@ ccui.LayoutComponent = cc.Component.extend({ ownerSize.height = 0; ownerPosition.y = this._bottomMargin + ownerAnchor.y * ownerSize.height; } else - ownerPosition.y = parentSize.height* this._positionPercentY; + ownerPosition.y = parentSize.height * this._positionPercentY; break; default: break; } - this._owner.setPosition(ownerPosition); - this._owner.setContentSize(ownerSize); + locOwner.setPosition(ownerPosition); + locOwner.setContentSize(ownerSize); - ccui.helper.doLayout(this._owner); + ccui.helper.doLayout(locOwner); }, - _getOwnerParent: function(){ + _getOwnerParent: function () { return this._owner ? this._owner.getParent() : null; }, - _refreshHorizontalMargin: function(){ + _refreshHorizontalMargin: function () { var parent = this._getOwnerParent(); if (parent == null) return; @@ -527,7 +527,7 @@ ccui.LayoutComponent = cc.Component.extend({ this._leftMargin = ownerPoint.x - ownerAnchor.x * ownerSize.width; this._rightMargin = parentSize.width - (ownerPoint.x + (1 - ownerAnchor.x) * ownerSize.width); }, - _refreshVerticalMargin: function(){ + _refreshVerticalMargin: function () { var parent = this._getOwnerParent(); if (parent == null) return; @@ -543,14 +543,14 @@ ccui.LayoutComponent = cc.Component.extend({ ccui.LayoutComponent.horizontalEdge = {NONE: 0, LEFT: 1, RIGHT: 2, CENTER: 3}; ccui.LayoutComponent.verticalEdge = {NONE: 0, BOTTOM: 1, TOP: 2, CENTER: 3}; -ccui.LayoutComponent.NAME= "__ui_layout"; -ccui.LayoutComponent.bindLayoutComponent = function(node){ +ccui.LayoutComponent.NAME = "__ui_layout"; +ccui.LayoutComponent.bindLayoutComponent = function (node) { var layout = node.getComponent(ccui.LayoutComponent.NAME); if (layout != null) return layout; layout = new ccui.LayoutComponent(); - if (layout && layout.init()){ + if (layout && layout.init()) { node.addComponent(layout); return layout; } From 1fdc125bfe7167b647980d1a262b99d0b9e8379a Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 12 Jan 2015 18:04:35 +0800 Subject: [PATCH 0131/1345] Issue #1267: update UISlider.js --- extensions/ccui/uiwidgets/UISlider.js | 56 ++++++++++++++++++++++----- 1 file changed, 47 insertions(+), 9 deletions(-) diff --git a/extensions/ccui/uiwidgets/UISlider.js b/extensions/ccui/uiwidgets/UISlider.js index 0b7756a1a6..48f725ac91 100644 --- a/extensions/ccui/uiwidgets/UISlider.js +++ b/extensions/ccui/uiwidgets/UISlider.js @@ -60,6 +60,11 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ _className: "Slider", _barRendererAdaptDirty: true, _progressBarRendererDirty: true, + _unifySize: false, + + _sliderBallNormalTextureScaleX: 1, + _sliderBallNormalTextureScaleY: 1, + _eventCallback: null, /** * allocates and initializes a UISlider. @@ -85,6 +90,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ }, _initRenderer: function () { + //todo use Scale9Sprite this._barRenderer = new cc.Sprite(); this._progressBarRenderer = new cc.Sprite(); this._progressBarRenderer.setAnchorPoint(0.0, 0.5); @@ -202,6 +208,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ * @param {Boolean} able */ setScale9Enabled: function (able) { + //todo use setScale9Enabled if (this._scale9Enabled == able) return; @@ -531,6 +538,13 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ else this._sliderEventSelector(this, ccui.Slider.EVENT_PERCENT_CHANGED); } + //todo check here + if (this._eventCallback){ + this._eventCallback(this, 0/*EventType::ON_PERCENTAGE_CHANGED*/); + } + if (this._ccEventCallback){ + this._ccEventCallback(this, 0/*static_cast(EventType::ON_PERCENTAGE_CHANGED)*/); + } }, /** @@ -577,11 +591,13 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ }, _barRendererScaleChangedWithSize: function () { - if (this._ignoreSize) { + 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 { + }else { this._barLength = this._contentSize.width; if (this._scale9Enabled) { this._barRenderer.setPreferredSize(this._contentSize); @@ -603,7 +619,9 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ }, _progressBarRendererScaleChangedWithSize: function () { - if (this._ignoreSize) { + 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; @@ -637,18 +655,35 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ this._slidBallNormalRenderer.setVisible(true); this._slidBallPressedRenderer.setVisible(false); this._slidBallDisabledRenderer.setVisible(false); + + this._slidBallNormalRenderer.setScale(this._sliderBallNormalTextureScaleX, this._sliderBallNormalTextureScaleY); }, _onPressStateChangedToPressed: function () { - this._slidBallNormalRenderer.setVisible(false); - this._slidBallPressedRenderer.setVisible(true); - this._slidBallDisabledRenderer.setVisible(false); + 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 () { - this._slidBallNormalRenderer.setVisible(false); + if (this._slidBallDisabledTextureFile){ + this._slidBallNormalRenderer.setVisible(false); + this._slidBallDisabledRenderer.setVisible(true); + } + this._slidBallNormalRenderer.setScale(this._sliderBallNormalTextureScaleX, this._sliderBallNormalTextureScaleY); this._slidBallPressedRenderer.setVisible(false); - this._slidBallDisabledRenderer.setVisible(true); + }, + + setZoomScale: function(scale){ + this._zoomScale = scale; + }, + + getZoomScale: function(){ + return this._zoomScale; }, /** @@ -674,6 +709,9 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ this.setPercent(slider.getPercent()); this._sliderEventListener = slider._sliderEventListener; this._sliderEventSelector = slider._sliderEventSelector; + this._zoomScale = slider._zoomScale; + this._eventCallback = slider._eventCallback; + this._ccEventCallback = slider._ccEventCallback; } }); From eab417d9d53a7357ad08e9f18a0128c82003ef29 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 12 Jan 2015 18:10:31 +0800 Subject: [PATCH 0132/1345] Issue #1267: update UIText.js --- extensions/ccui/uiwidgets/UIText.js | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/extensions/ccui/uiwidgets/UIText.js b/extensions/ccui/uiwidgets/UIText.js index 8e11a91d0b..70e4984049 100644 --- a/extensions/ccui/uiwidgets/UIText.js +++ b/extensions/ccui/uiwidgets/UIText.js @@ -114,6 +114,8 @@ ccui.Text = ccui.Widget.extend(/** @lends 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; @@ -210,6 +212,9 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ */ setTextAreaSize: function (size) { this._labelRenderer.setDimensions(size); + if (!this._ignoreSize){ + this._customSize = size; + } this._updateContentSizeWithTextureSize(this._labelRenderer.getContentSize()); this._labelRendererAdaptDirty = true; }, @@ -291,20 +296,6 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ _onPressStateChangedToDisabled: function () { }, - _updateFlippedX: function () { - if (this._flippedX) - this._labelRenderer.setScaleX(-1.0); - else - this._labelRenderer.setScaleX(1.0); - }, - - _updateFlippedY: function () { - if (this._flippedY) - this._labelRenderer.setScaleY(-1.0); - else - this._labelRenderer.setScaleY(1.0); - }, - _onSizeChanged: function () { ccui.Widget.prototype._onSizeChanged.call(this); this._labelRendererAdaptDirty = true; @@ -414,6 +405,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ this.setTextAreaSize(uiLabel._textAreaSize); this.setTextHorizontalAlignment(uiLabel._labelRenderer.getHorizontalAlignment()); this.setTextVerticalAlignment(uiLabel._labelRenderer.getVerticalAlignment()); + this.setContentSize(uiLabel.getContentSize()); } }, @@ -442,6 +434,14 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ cc.ProtectedNode.prototype.setColor.call(this, color); this._labelRenderer.setColor(color); } + //todo label add setTextColor +// setTextColor: function(color){ +// this._labelRenderer.setTextColor(color); +// }, +// +// getTextColor: function(){ +// return this._labelRenderer.getTextColor(); +// } }); var _p = ccui.Text.prototype; From 6105e3dca6258d8fbcb7fc7daa33d03ba343ee5d Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Mon, 12 Jan 2015 18:17:40 +0800 Subject: [PATCH 0133/1345] Issue cocos2d/cocos2d-js/#1267: ccui.helper has been migrated. --- extensions/ccui/layouts/UILayoutManager.js | 8 +++--- extensions/ccui/system/UIHelper.js | 31 +++++++++++++++++++++- 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/extensions/ccui/layouts/UILayoutManager.js b/extensions/ccui/layouts/UILayoutManager.js index fcbfc98993..d24e8996ab 100644 --- a/extensions/ccui/layouts/UILayoutManager.js +++ b/extensions/ccui/layouts/UILayoutManager.js @@ -60,7 +60,7 @@ ccui.linearVerticalLayoutManager = /** @lends ccui.linearVerticalLayoutManager# var ap = child.getAnchorPoint(); var cs = child.getContentSize(); var finalPosX = ap.x * cs.width; - var finalPosY = topBoundary - ((1.0-ap.y) * cs.height); + var finalPosY = topBoundary - ((1.0 - ap.y) * cs.height); switch (childGravity){ case ccui.LinearLayoutParameter.NONE: case ccui.LinearLayoutParameter.LEFT: @@ -69,7 +69,7 @@ ccui.linearVerticalLayoutManager = /** @lends ccui.linearVerticalLayoutManager# finalPosX = layoutSize.width - ((1.0 - ap.x) * cs.width); break; case ccui.LinearLayoutParameter.CENTER_HORIZONTAL: - finalPosX = layoutSize.width / 2.0 - cs.width * (0.5-ap.x); + finalPosX = layoutSize.width / 2.0 - cs.width * (0.5 - ap.x); break; default: break; @@ -78,7 +78,7 @@ ccui.linearVerticalLayoutManager = /** @lends ccui.linearVerticalLayoutManager# finalPosX += mg.left; finalPosY -= mg.top; child.setPosition(finalPosX, finalPosY); - topBoundary = child.getPositionY() - child.getAnchorPoint().y * child.getContentSize().height - mg.bottom; + topBoundary = child.getPositionY() - ap.y * cs.height - mg.bottom; } } } @@ -102,7 +102,7 @@ ccui.linearHorizontalLayoutManager = /** @lends ccui.linearHorizontalLayoutManag if (layoutParameter){ var childGravity = layoutParameter.getGravity(); var ap = child.getAnchorPoint(); - var cs = child.getSize(); + var cs = child.getContentSize(); var finalPosX = leftBoundary + (ap.x * cs.width); var finalPosY = layoutSize.height - (1.0 - ap.y) * cs.height; switch (childGravity){ diff --git a/extensions/ccui/system/UIHelper.js b/extensions/ccui/system/UIHelper.js index 802c0f65df..2c0263b35f 100644 --- a/extensions/ccui/system/UIHelper.js +++ b/extensions/ccui/system/UIHelper.js @@ -119,7 +119,11 @@ ccui.helper = { return null; } , - _activeLayout: false, + _activeLayout: true, + /** + * Refresh object and it's children layout state + * @param {cc.Node} rootNode + */ doLayout: function(rootNode){ if(!this._activeLayout) return; @@ -131,5 +135,30 @@ ccui.helper = { 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); } }; From c9aac6cea831d9789aa1a2a8ec184afe5f9d1c41 Mon Sep 17 00:00:00 2001 From: jianglong0156 Date: Tue, 13 Jan 2015 10:17:11 +0800 Subject: [PATCH 0134/1345] Issue #2563: fix the bug that trigger error in scene test --- extensions/cocostudio/loader/parsers/scene-1.x.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/extensions/cocostudio/loader/parsers/scene-1.x.js b/extensions/cocostudio/loader/parsers/scene-1.x.js index 8e01342094..96183b3606 100644 --- a/extensions/cocostudio/loader/parsers/scene-1.x.js +++ b/extensions/cocostudio/loader/parsers/scene-1.x.js @@ -41,6 +41,12 @@ 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.isUndefined(json["x"]))?0:json["x"]; var y = (cc.isUndefined(json["y"]))?0:json["y"]; From 964e4107c9f1fbdb1bdddf32b08453e0dbf98669 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Tue, 13 Jan 2015 10:51:13 +0800 Subject: [PATCH 0135/1345] Issue cocos2d/cocos2d-js/#1267: ccui.PageView and ccui.ScrollView have been migrated. --- .../uiwidgets/scroll-widget/UIPageView.js | 27 +++++------ .../uiwidgets/scroll-widget/UIScrollView.js | 45 ++++++++++++++----- 2 files changed, 45 insertions(+), 27 deletions(-) diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js b/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js index 36e5676ba4..cfedf69092 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js @@ -54,6 +54,7 @@ ccui.PageView = ccui.Layout.extend(/** @lends ccui.PageView# */{ _pageViewEventListener: null, _pageViewEventSelector: null, _className:"PageView", + //v3.2 _customScrollThreshold: 0, _usingCustomScrollThreshold: false, @@ -334,12 +335,9 @@ ccui.PageView = ccui.Layout.extend(/** @lends ccui.PageView# */{ * @param {cc.Event} event */ onTouchMoved: function (touch, event) { - ccui.Layout.prototype.onTouchMoved.call(this, touch, event); if (!this._isInterceptTouch) - { this._handleMoveLogic(touch); - } }, /** @@ -351,9 +349,7 @@ ccui.PageView = ccui.Layout.extend(/** @lends ccui.PageView# */{ onTouchEnded: function (touch, event) { ccui.Layout.prototype.onTouchEnded.call(this, touch, event); if (!this._isInterceptTouch) - { this._handleReleaseLogic(touch); - } this._isInterceptTouch = false; }, @@ -365,9 +361,7 @@ ccui.PageView = ccui.Layout.extend(/** @lends ccui.PageView# */{ onTouchCancelled: function (touch, event) { ccui.Layout.prototype.onTouchCancelled.call(this, touch, event); if (!this._isInterceptTouch) - { this._handleReleaseLogic(touch); - } this._isInterceptTouch = false; }, @@ -434,7 +428,8 @@ ccui.PageView = ccui.Layout.extend(/** @lends ccui.PageView# */{ }, /** - * Set CustomScrollThreshold + * 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){ @@ -444,21 +439,23 @@ ccui.PageView = ccui.Layout.extend(/** @lends ccui.PageView# */{ }, /** - * Gets the _customScrollThreshold. + * Returns user defined scroll page threshold. + * @since v3.2 */ getCustomScrollThreshold: function(){ return this._customScrollThreshold; }, /** - * Set the UsingCustomScrollThreshold + * 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; }, /** - * Gets the UsingCustomScrollThreshold + * Queries whether we are using user defined scroll page threshold or not */ isUsingCustomScrollThreshold: function(){ return this._usingCustomScrollThreshold; @@ -473,9 +470,8 @@ ccui.PageView = ccui.Layout.extend(/** @lends ccui.PageView# */{ var pageCount = this._pages.length; var curPageLocation = curPagePos.x; var pageWidth = this.getSize().width; - if (!this._usingCustomScrollThreshold) { + if (!this._usingCustomScrollThreshold) this._customScrollThreshold = pageWidth / 2.0; - } var boundary = this._customScrollThreshold; if (curPageLocation <= -boundary) { if (this._curPageIdx >= pageCount - 1) @@ -522,9 +518,7 @@ ccui.PageView = ccui.Layout.extend(/** @lends ccui.PageView# */{ this._touchEndPosition.y = touchPoint.y; this._handleReleaseLogic(touch); if (sender.isSwallowTouches()) - { this._isInterceptTouch = false; - } break; } }, @@ -536,6 +530,8 @@ ccui.PageView = ccui.Layout.extend(/** @lends ccui.PageView# */{ else this._pageViewEventSelector(this, ccui.PageView.EVENT_TURNING); } + if(this._ccEventCallback) + this._ccEventCallback(this, ccui.PageView.EVENT_TURNING); }, /** @@ -607,6 +603,7 @@ ccui.PageView = ccui.Layout.extend(/** @lends ccui.PageView# */{ _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; diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js index 92b6b72c07..4c1113aeab 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js @@ -701,7 +701,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ var icBottomPos, icLeftPos, icRightPos, icTopPos; var locContainer = this._innerContainer, locDestination = this._autoScrollDestination; switch (this.direction) { - case ccui.ScrollView.DIR_VERTICAL: // vertical + case ccui.ScrollView.DIR_VERTICAL: if (this._autoScrollDir.y > 0) { icBottomPos = locContainer.getBottomBoundary(); if (icBottomPos + touchOffsetY >= locDestination.y) { @@ -716,7 +716,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ } } break; - case ccui.ScrollView.DIR_HORIZONTAL: // horizontal + case ccui.ScrollView.DIR_HORIZONTAL: if (this._autoScrollDir.x > 0) { icLeftPos = locContainer.getLeftBoundary(); if (icLeftPos + touchOffsetX >= locDestination.x) { @@ -1321,19 +1321,20 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ if (!this._checkNeedBounce() && this.inertiaScrollEnabled) { if (this._slidTime <= 0.016) return; - var totalDis = 0; - var dir; + 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 = this._touchEndPosition.y - this._touchBeganPosition.y; + totalDis = touchEndPositionInNodeSpace.y - touchBeganPositionInNodeSpace.y; dir = (totalDis < 0) ? ccui.ScrollView.SCROLLDIR_DOWN : ccui.ScrollView.SCROLLDIR_UP; break; case ccui.ScrollView.DIR_HORIZONTAL: - totalDis = this._touchEndPosition.x - this._touchBeganPosition.x; + 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(this._touchEndPosition, this._touchBeganPosition); + var subVector = cc.pSub(touchEndPositionInNodeSpace, touchBeganPositionInNodeSpace); totalDis = cc.pLength(subVector); dir = cc.pNormalize(subVector); break; @@ -1352,7 +1353,9 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ }, _handleMoveLogic: function (touch) { - var delta = cc.pSub(touch.getLocation(), touch.getPreviousLocation()); + 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); @@ -1458,10 +1461,10 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ break; case ccui.Widget.TOUCH_MOVED: var offset = cc.pLength(cc.pSub(sender.getTouchBeganPosition(), touchPoint)); + this._touchMovePosition.x = touchPoint.x; + this._touchMovePosition.y = touchPoint.y; if (offset > this._childFocusCancelOffset) { sender.setHighlighted(false); - this._touchMovePosition.x = touchPoint.x; - this._touchMovePosition.y = touchPoint.y; this._handleMoveLogic(touch); } break; @@ -1470,9 +1473,8 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ this._touchEndPosition.x = touchPoint.x; this._touchEndPosition.y = touchPoint.y; this._handleReleaseLogic(touch); - if (sender.isSwallowTouches()){ + if (sender.isSwallowTouches()) this._isInterceptTouch = false; - } break; } }, @@ -1484,6 +1486,8 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ else this._scrollViewEventSelector(this, ccui.ScrollView.EVENT_SCROLL_TO_TOP); } + if(this._ccEventCallback) + this._ccEventCallback(this, ccui.ScrollView.EVENT_SCROLL_TO_TOP); }, _scrollToBottomEvent: function () { @@ -1493,6 +1497,8 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ else this._scrollViewEventSelector(this, ccui.ScrollView.EVENT_SCROLL_TO_BOTTOM); } + if(this._ccEventCallback) + this._ccEventCallback(this, ccui.ScrollView.EVENT_SCROLL_TO_BOTTOM); }, _scrollToLeftEvent: function () { @@ -1502,6 +1508,8 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ else this._scrollViewEventSelector(this, ccui.ScrollView.EVENT_SCROLL_TO_LEFT); } + if(this._ccEventCallback) + this._ccEventCallback(this, ccui.ScrollView.EVENT_SCROLL_TO_LEFT); }, _scrollToRightEvent: function () { @@ -1511,6 +1519,8 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ else this._scrollViewEventSelector(this, ccui.ScrollView.EVENT_SCROLL_TO_RIGHT); } + if(this._ccEventCallback) + this._ccEventCallback(this, ccui.ScrollView.EVENT_SCROLL_TO_RIGHT); }, _scrollingEvent: function () { @@ -1520,6 +1530,8 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ else this._scrollViewEventSelector(this, ccui.ScrollView.EVENT_SCROLLING); } + if(this._ccEventCallback) + this._ccEventCallback(this, ccui.ScrollView.EVENT_SCROLLING); }, _bounceTopEvent: function () { @@ -1529,6 +1541,8 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ else this._scrollViewEventSelector(this, ccui.ScrollView.EVENT_BOUNCE_TOP); } + if(this._ccEventCallback) + this._ccEventCallback(this, ccui.ScrollView.EVENT_BOUNCE_TOP); }, _bounceBottomEvent: function () { @@ -1538,6 +1552,8 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ else this._scrollViewEventSelector(this, ccui.ScrollView.EVENT_BOUNCE_BOTTOM); } + if(this._ccEventCallback) + this._ccEventCallback(this, ccui.ScrollView.EVENT_BOUNCE_BOTTOM); }, _bounceLeftEvent: function () { @@ -1547,6 +1563,8 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ else this._scrollViewEventSelector(this, ccui.ScrollView.EVENT_BOUNCE_LEFT); } + if(this._ccEventCallback) + this._ccEventCallback(this, ccui.ScrollView.EVENT_BOUNCE_LEFT); }, _bounceRightEvent: function () { @@ -1556,6 +1574,8 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ else this._scrollViewEventSelector(this, ccui.ScrollView.EVENT_BOUNCE_RIGHT); } + if(this._ccEventCallback) + this._ccEventCallback(this, ccui.ScrollView.EVENT_BOUNCE_RIGHT); }, /** @@ -1682,6 +1702,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ this.setInertiaScrollEnabled(scrollView.inertiaScrollEnabled); this._scrollViewEventListener = scrollView._scrollViewEventListener; this._scrollViewEventSelector = scrollView._scrollViewEventSelector; + this._ccEventCallback = scrollView._ccEventCallback; } }, From 0e5e3b5068a07ed70216d00a9a0d7a2905f66271 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Tue, 13 Jan 2015 11:09:45 +0800 Subject: [PATCH 0136/1345] Issue cocos2d/cocos2d-js/#1267: ccui.ListView has been migrated. --- extensions/ccui/uiwidgets/scroll-widget/UIListView.js | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIListView.js b/extensions/ccui/uiwidgets/scroll-widget/UIListView.js index 100116df96..9b2950218c 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIListView.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIListView.js @@ -471,6 +471,8 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ else this._listViewEventSelector(this, eventEnum); } + if(this._ccEventCallback) + this._ccEventCallback(this, eventEnum); }, /** @@ -538,6 +540,15 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ this._listViewEventListener = listView._listViewEventListener; this._listViewEventSelector = listView._listViewEventSelector; } + }, + + //v3.3 + forceDoLayout: function(){ + if (this._refreshViewDirty) { + this.refreshView(); + this._refreshViewDirty = false; + } + this._innerContainer.forceDoLayout(); } }); From 49e059ec11242e0b004c57ac100152d67adca277 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Tue, 13 Jan 2015 11:26:49 +0800 Subject: [PATCH 0137/1345] Issue #1267: ccui.TextAtlas and ccui.TextBMFont have been migrated. --- extensions/ccui/uiwidgets/UITextAtlas.js | 2 ++ extensions/ccui/uiwidgets/UITextBMFont.js | 2 ++ 2 files changed, 4 insertions(+) diff --git a/extensions/ccui/uiwidgets/UITextAtlas.js b/extensions/ccui/uiwidgets/UITextAtlas.js index f60254614b..cb4ad707cc 100644 --- a/extensions/ccui/uiwidgets/UITextAtlas.js +++ b/extensions/ccui/uiwidgets/UITextAtlas.js @@ -95,6 +95,8 @@ ccui.TextAtlas = ccui.Widget.extend(/** @lends ccui.TextAtlas# */{ * @param {String} value */ setString: function (value) { + if(value == this._labelAtlasRenderer.getString()) + return; this._stringValue = value; this._labelAtlasRenderer.setString(value); this._updateContentSizeWithTextureSize(this._labelAtlasRenderer.getContentSize()); diff --git a/extensions/ccui/uiwidgets/UITextBMFont.js b/extensions/ccui/uiwidgets/UITextBMFont.js index 2354261b46..0175981964 100644 --- a/extensions/ccui/uiwidgets/UITextBMFont.js +++ b/extensions/ccui/uiwidgets/UITextBMFont.js @@ -98,6 +98,8 @@ ccui.LabelBMFont = ccui.TextBMFont = ccui.Widget.extend(/** @lends ccui.TextBMFo * @param {String} value */ setString: function (value) { + if(value == this._labelBMFontRenderer.getString()) + return; this._stringValue = value; if (!this._fntFileHasInit) return; From f37facc6b3297b93878c24bb62cdd96e3232f7d3 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 13 Jan 2015 11:31:29 +0800 Subject: [PATCH 0138/1345] Fixed the guiReader parser 2.0 throw error --- extensions/cocostudio/loader/parsers/compatible.js | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/extensions/cocostudio/loader/parsers/compatible.js b/extensions/cocostudio/loader/parsers/compatible.js index 02a6ea00fe..c77028b367 100644 --- a/extensions/cocostudio/loader/parsers/compatible.js +++ b/extensions/cocostudio/loader/parsers/compatible.js @@ -44,7 +44,13 @@ var json = cc.loader.getRes(file); if(json) this._fileDesignSizes[file] = cc.size(json["designWidth"]||0, json["designHeight"]||0); - return ccs._load(file, "ccui"); + try{ + return ccs._load(file, "ccui"); + }catch(err){ + cc.warn("Not supported file types, Please try use the ccs.load"); + cc.log(err); + return null; + } }, //@deprecated This function will be deprecated sooner or later please use parser.registerParser From 79e01ff27f6fdb4428b4c291a074df9b01390fb2 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 13 Jan 2015 11:39:58 +0800 Subject: [PATCH 0139/1345] Update UITextFiled.js --- extensions/ccui/uiwidgets/UITextField.js | 28 ++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/extensions/ccui/uiwidgets/UITextField.js b/extensions/ccui/uiwidgets/UITextField.js index 987d67b4fc..b0718917c8 100644 --- a/extensions/ccui/uiwidgets/UITextField.js +++ b/extensions/ccui/uiwidgets/UITextField.js @@ -38,6 +38,8 @@ ccui._TextFieldRenderer = cc.TextFieldTTF.extend({ _deleteBackward: false, _className: "_TextFieldRenderer", _textFieldRendererAdaptDirty: true, + _ccEventCallback: null, + _eventCallback: null, ctor: function () { cc.TextFieldTTF.prototype.ctor.call(this); @@ -653,6 +655,9 @@ ccui.TextField = ccui.Widget.extend(/** @lends ccui.TextField# */{ else this._textFieldEventSelector(this, ccui.TextField.EVENT_ATTACH_WITH_IME); } + if (this._ccEventCallback){ + this._ccEventCallback(this, 0/*static_cast(EventType::ATTACH_WITH_IME)*/); + } }, _detachWithIMEEvent: function () { @@ -662,6 +667,12 @@ ccui.TextField = ccui.Widget.extend(/** @lends ccui.TextField# */{ else this._textFieldEventSelector(this, ccui.TextField.EVENT_DETACH_WITH_IME); } + if (this._eventCallback){ + this._eventCallback(this, 0/*EventType::DETACH_WITH_IME*/); + } + if (this._ccEventCallback){ + this._ccEventCallback(this, 0/*static_cast(EventType::DETACH_WITH_IME)*/); + } }, _insertTextEvent: function () { @@ -671,6 +682,12 @@ ccui.TextField = ccui.Widget.extend(/** @lends ccui.TextField# */{ else this._textFieldEventSelector(this, ccui.TextField.EVENT_INSERT_TEXT); } + if (this._eventCallback){ + this._eventCallback(this, 0/*EventType::INSERT_TEXT*/); + } + if (this._ccEventCallback){ + this._ccEventCallback(this, 0/*static_cast(EventType::INSERT_TEXT)*/); + } }, _deleteBackwardEvent: function () { @@ -680,6 +697,13 @@ ccui.TextField = ccui.Widget.extend(/** @lends ccui.TextField# */{ else this._textFieldEventSelector(this, ccui.TextField.EVENT_DELETE_BACKWARD); } + if (this._eventCallback){ + this._eventCallback(this, 0/*EventType::DELETE_BACKWARD*/); + } + if (this._ccEventCallback) + { + this._ccEventCallback(this, 0/*static_cast(EventType::DELETE_BACKWARD)*/); + } }, /** @@ -769,6 +793,10 @@ ccui.TextField = ccui.Widget.extend(/** @lends ccui.TextField# */{ this.setDetachWithIME(textField.getDetachWithIME()); this.setInsertText(textField.getInsertText()); this.setDeleteBackward(textField.getDeleteBackward()); + this._eventCallback = textField._eventCallback; + this._ccEventCallback = textField._ccEventCallback; + this._textFieldEventListener = textField._textFieldEventListener; + this._textFieldEventSelector = textField._textFieldEventSelector; }, /** From 5fa5ffa070ed6d8ead0a8670573c96a52bb22976 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Tue, 13 Jan 2015 11:48:57 +0800 Subject: [PATCH 0140/1345] Issue #1267: modified ccui.Button's codes --- extensions/ccui/uiwidgets/UIButton.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/extensions/ccui/uiwidgets/UIButton.js b/extensions/ccui/uiwidgets/UIButton.js index 8cd10b38c7..36eee19cee 100644 --- a/extensions/ccui/uiwidgets/UIButton.js +++ b/extensions/ccui/uiwidgets/UIButton.js @@ -220,9 +220,8 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ if (this._unifySize) return this.getNormalSize(); - var titleSize = this._titleRenderer.getContentSize(); if (!this._normalTextureLoaded && this._titleRenderer.getString().length > 0) { - return cc.size(titleSize); + return this._titleRenderer.getContentSize(); } return cc.size(this._normalTextureSize); }, From 904db1b218ee8f566d8c003443915e6fad14ed54 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 13 Jan 2015 12:51:20 +0800 Subject: [PATCH 0141/1345] Fixed the guiReader parser 2.0 throw error --- extensions/cocostudio/loader/parsers/compatible.js | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/compatible.js b/extensions/cocostudio/loader/parsers/compatible.js index c77028b367..326a138597 100644 --- a/extensions/cocostudio/loader/parsers/compatible.js +++ b/extensions/cocostudio/loader/parsers/compatible.js @@ -44,13 +44,14 @@ var json = cc.loader.getRes(file); if(json) this._fileDesignSizes[file] = cc.size(json["designWidth"]||0, json["designHeight"]||0); - try{ - return ccs._load(file, "ccui"); - }catch(err){ + + var version = json["Version"]; + var versionNum = ccs.uiReader.getVersionInteger(version); + if(!version || versionNum >= 1700){ cc.warn("Not supported file types, Please try use the ccs.load"); - cc.log(err); return null; } + return ccs._load(file, "ccui"); }, //@deprecated This function will be deprecated sooner or later please use parser.registerParser From ccd0885a35f9dfb3e60f827a5e49f8686500d590 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Tue, 13 Jan 2015 13:59:27 +0800 Subject: [PATCH 0142/1345] Fixed cocos2d/cocos2d-js/#1267: fixed a bug of ccui.Button --- extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js b/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js index 158eca0a47..aba5ca6b11 100644 --- a/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js +++ b/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js @@ -79,6 +79,8 @@ proto.setState = function (state) { var scale9Image = this._node._scale9Image; + if(scale9Image == null) + return; if (state === ccui.Scale9Sprite.state.NORMAL) { scale9Image.setShaderProgram(cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURECOLOR)); } else if (state === ccui.Scale9Sprite.state.GRAY) { From c1670ddf2f9b4dff15ecbcc2cd846dd2a54df57a Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Tue, 13 Jan 2015 14:39:44 +0800 Subject: [PATCH 0143/1345] Fixed cocos2d/cocos2d-js/#1267: fixed a bug of ccui.Button that its content size is incorrect. --- extensions/ccui/uiwidgets/UIButton.js | 58 +++++++++------------------ 1 file changed, 20 insertions(+), 38 deletions(-) diff --git a/extensions/ccui/uiwidgets/UIButton.js b/extensions/ccui/uiwidgets/UIButton.js index 36eee19cee..09f9c88b36 100644 --- a/extensions/ccui/uiwidgets/UIButton.js +++ b/extensions/ccui/uiwidgets/UIButton.js @@ -281,18 +281,17 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ default: break; } - if (this._unifySize) + + this._normalTextureSize = this._buttonNormalRenderer.getContentSize(); + this._updateChildrenDisplayedRGBA(); + if (this._unifySize){ if (this._scale9Enabled){ normalRenderer.setCapInsets(this._capInsetsNormal); this._updateContentSizeWithTextureSize(this.getNormalSize()); } - else + }else this._updateContentSizeWithTextureSize(this._normalTextureSize); - this._normalTextureSize = this._buttonNormalRenderer.getContentSize(); - - this._updateChildrenDisplayedRGBA(); - this._normalTextureLoaded = true; this._normalTextureAdaptDirty = true; }, @@ -340,7 +339,6 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ clickedRenderer.setCapInsets(this._capInsetsPressed); this._pressedTextureSize = this._buttonClickedRenderer.getContentSize(); - this._updateChildrenDisplayedRGBA(); this._pressedTextureLoaded = true; @@ -391,7 +389,6 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ disabledRenderer.setCapInsets(this._capInsetsDisabled); this._disabledTextureSize = this._buttonDisableRenderer.getContentSize(); - this._updateChildrenDisplayedRGBA(); this._disabledTextureLoaded = true; @@ -415,22 +412,17 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ setCapInsetsNormalRenderer: function (capInsets) { if(!capInsets) return; - var x = capInsets.x; - var y = capInsets.y; - var width = capInsets.width; - var height = capInsets.height; - if (this._normalTextureSize.width < width) - { + 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) - { + if (this._normalTextureSize.height < height){ y = 0; height = 0; } - var rect = cc.rect(x, y, width, height); var locInsets = this._capInsetsNormal; locInsets.x = x; @@ -440,7 +432,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ if (!this._scale9Enabled) return; - this._buttonNormalRenderer.setCapInsets(rect); + this._buttonNormalRenderer.setCapInsets(locInsets); }, /** @@ -459,22 +451,17 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ if(!capInsets || !this._scale9Enabled) return; - var x = capInsets.x; - var y = capInsets.y; - var width = capInsets.width; - var height = capInsets.height; + var x = capInsets.x, y = capInsets.y; + var width = capInsets.width, height = capInsets.height; - if (this._normalTextureSize.width < width) - { + if (this._normalTextureSize.width < width) { x = 0; width = 0; } - if (this._normalTextureSize.height < height) - { + if (this._normalTextureSize.height < height) { y = 0; height = 0; } - var rect = cc.rect(x, y, width, height); var locInsets = this._capInsetsPressed; locInsets.x = x; @@ -482,7 +469,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ locInsets.width = width; locInsets.height = height; - this._buttonClickedRenderer.setCapInsets(rect); + this._buttonClickedRenderer.setCapInsets(locInsets); }, /** @@ -501,22 +488,17 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ if(!capInsets || !this._scale9Enabled) return; - var x = capInsets.x; - var y = capInsets.y; - var width = capInsets.width; - var height = capInsets.height; + var x = capInsets.x, y = capInsets.y; + var width = capInsets.width, height = capInsets.height; - if (this._normalTextureSize.width < width) - { + if (this._normalTextureSize.width < width) { x = 0; width = 0; } - if (this._normalTextureSize.height < height) - { + if (this._normalTextureSize.height < height) { y = 0; height = 0; } - var rect = cc.rect(x, y, width, height); var locInsets = this._capInsetsDisabled; locInsets.x = x; @@ -524,7 +506,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ locInsets.width = width; locInsets.height = height; - this._buttonDisableRenderer.setCapInsets(rect); + this._buttonDisableRenderer.setCapInsets(locInsets); }, /** From b12022ba131f0023b3d4c71cf3e6d154708eab21 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 13 Jan 2015 15:03:32 +0800 Subject: [PATCH 0144/1345] update 2.0 layout parser --- .../loader/parsers/timelineParser-2.x.js | 84 ++++++++++++++----- 1 file changed, 64 insertions(+), 20 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index a0e7307595..0e4f9d244e 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -289,26 +289,70 @@ setContentSize(widget, json["Size"]); if(widget instanceof ccui.Layout){ - //todo update UILayoutComponent.bindLayoutComponent - var positionXPercentEnabled = json["PositionPercentXEnable"]; - var positionYPercentEnabled = json["PositionPercentYEnable"]; - var sizeXPercentEnable = json["PercentWidthEnable"]; - var sizeYPercentEnable = json["PercentHeightEnable"]; - var stretchHorizontalEnabled = json["StretchWidthEnable"]; - var stretchVerticalEnabled = json["StretchHeightEnable"]; - var horizontalEdge = json["HorizontalEdge"]; - var verticalEdge = json["VerticalEdge"]; - var leftMargin = json["LeftMargin"]; - var rightMargin = json["RightMargin"]; - var topMargin = json["TopMargin"]; - var bottomMargin = json["BottomMargin"]; - //var prePosition = json["PrePosition"]; - //if(prePosition) - // prePosition["X"], prePosition["Y"] - - //var preSize = json["PreSize"]; - //if(preSize) - // preSize["X"], preSize["Y"] + var layoutComponent = ccui.LayoutComponent.bindLayoutComponent(widget); + + var positionXPercentEnabled = json["PositionPercentXEnable"] || false; + var positionYPercentEnabled = json["PositionPercentYEnable"] || false; + var positionXPercent = 0, + positionYPercent = 0, + PrePosition = json["PrePosition"]; + if(PrePosition != null){ + positionXPercent = PrePosition["X"] || 0; + positionYPercent = PrePosition["Y"] || 0; + } + var sizeXPercentEnable = json["PercentWidthEnable"] || false; + var sizeYPercentEnable = json["PercentHeightEnable"] || false; + var sizeXPercent = 0, + sizeYPercent = 0, + PreSize = json["PreSize"]; + if(PrePosition != null){ + sizeXPercent = PreSize["X"] || 0; + sizeYPercent = PreSize["Y"] || 0; + } + var stretchHorizontalEnabled = json["StretchWidthEnable"] || false; + var stretchVerticalEnabled = json["StretchHeightEnable"] || false; + var horizontalEdge = json["HorizontalEdge"] = ccui.LayoutComponent.horizontalEdge.LEFT; + var verticalEdge = json["VerticalEdge"] = ccui.LayoutComponent.verticalEdge.TOP; + var leftMargin = json["LeftMargin"] || 0; + var rightMargin = json["RightMargin"] || 0; + var topMargin = json["TopMargin"] || 0; + var bottomMargin = json["BottomMargin"] || 0; + + layoutComponent.setPositionPercentXEnabled(positionXPercentEnabled); + layoutComponent.setPositionPercentYEnabled(positionYPercentEnabled); + layoutComponent.setPositionPercentX(positionXPercent); + layoutComponent.setPositionPercentY(positionYPercent); + layoutComponent.setPercentWidthEnabled(sizeXPercentEnable); + layoutComponent.setPercentHeightEnabled(sizeYPercentEnable); + layoutComponent.setPercentWidth(sizeXPercent); + layoutComponent.setPercentHeight(sizeYPercent); + layoutComponent.setStretchWidthEnabled(stretchHorizontalEnabled); + layoutComponent.setStretchHeightEnabled(stretchVerticalEnabled); + + var horizontalEdgeType = ccui.LayoutComponent.horizontalEdge.NONE; + if (horizontalEdge == "LeftEdge"){ + horizontalEdgeType = ccui.LayoutComponent.horizontalEdge.LEFT; + }else if (horizontalEdge == "RightEdge"){ + horizontalEdgeType = ccui.LayoutComponent.horizontalEdge.RIGHT; + }else if (horizontalEdge == "BothEdge"){ + horizontalEdgeType = ccui.LayoutComponent.horizontalEdge.CENTER; + } + layoutComponent.setHorizontalEdge(horizontalEdgeType); + + var verticalEdgeType = ccui.LayoutComponent.verticalEdge.NONE; + if (verticalEdge == "TopEdge"){ + verticalEdgeType = ccui.LayoutComponent.verticalEdge.TOP; + }else if (verticalEdge == "BottomEdge"){ + verticalEdgeType = ccui.LayoutComponent.verticalEdge.BOTTOM; + }else if (verticalEdge == "BothEdge"){ + verticalEdgeType = ccui.LayoutComponent.verticalEdge.CENTER; + } + layoutComponent.setVerticalEdge(verticalEdgeType); + + layoutComponent.setTopMargin(topMargin); + layoutComponent.setBottomMargin(bottomMargin); + layoutComponent.setLeftMargin(leftMargin); + layoutComponent.setRightMargin(rightMargin); } }; From 9ff1f27421a068d8eb24b01bca2660fa2a88abc2 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Tue, 13 Jan 2015 15:07:47 +0800 Subject: [PATCH 0145/1345] Fixed #1267: add 'isSwallowTouches' to cc._EventListenerTouchOneByOne --- cocos2d/core/event-manager/CCEventListener.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/cocos2d/core/event-manager/CCEventListener.js b/cocos2d/core/event-manager/CCEventListener.js index 2df66a3458..9cb338fed5 100644 --- a/cocos2d/core/event-manager/CCEventListener.js +++ b/cocos2d/core/event-manager/CCEventListener.js @@ -366,6 +366,10 @@ cc._EventListenerTouchOneByOne = cc.EventListener.extend({ this.swallowTouches = needSwallow; }, + isSwallowTouches: function(){ + return this.swallowTouches; + }, + clone: function () { var eventListener = new cc._EventListenerTouchOneByOne(); eventListener.onTouchBegan = this.onTouchBegan; From 36bb01f64c8485f784547aa0870682fa4ef67be5 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Tue, 13 Jan 2015 16:02:27 +0800 Subject: [PATCH 0146/1345] Fixed #1267: correct a jsDoc of ccui.Button --- extensions/ccui/uiwidgets/UIButton.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/ccui/uiwidgets/UIButton.js b/extensions/ccui/uiwidgets/UIButton.js index 09f9c88b36..4e3994c3c7 100644 --- a/extensions/ccui/uiwidgets/UIButton.js +++ b/extensions/ccui/uiwidgets/UIButton.js @@ -829,7 +829,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ /** * Returns title fontSize of ccui.Button. - * @returns {cc.Size} + * @returns {Number} */ getTitleFontSize: function () { return this._titleRenderer.getFontSize(); From 66dc7bbf7b19acff6fb309cfb778e273429e5a23 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 13 Jan 2015 16:46:21 +0800 Subject: [PATCH 0147/1345] Fixed the guiReader parser 2.0 throw error --- extensions/cocostudio/loader/parsers/compatible.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/cocostudio/loader/parsers/compatible.js b/extensions/cocostudio/loader/parsers/compatible.js index 326a138597..0969d257d5 100644 --- a/extensions/cocostudio/loader/parsers/compatible.js +++ b/extensions/cocostudio/loader/parsers/compatible.js @@ -45,7 +45,7 @@ if(json) this._fileDesignSizes[file] = cc.size(json["designWidth"]||0, json["designHeight"]||0); - var version = json["Version"]; + var version = json["Version"] || json["version"]; var versionNum = ccs.uiReader.getVersionInteger(version); if(!version || versionNum >= 1700){ cc.warn("Not supported file types, Please try use the ccs.load"); From ae2d03de4003c1ce94c6d240b649416a55b53552 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Tue, 13 Jan 2015 17:02:31 +0800 Subject: [PATCH 0148/1345] Fixed #1267: refactor ccui.Button, ccui.Slider and ccui.TextField's eventCallback --- .../ccui/base-classes/UIScale9Sprite.js | 3 +- extensions/ccui/base-classes/UIWidget.js | 3 +- extensions/ccui/uiwidgets/UIButton.js | 21 +++++++---- extensions/ccui/uiwidgets/UISlider.js | 15 ++------ extensions/ccui/uiwidgets/UITextField.js | 37 ++++++------------- 5 files changed, 33 insertions(+), 46 deletions(-) diff --git a/extensions/ccui/base-classes/UIScale9Sprite.js b/extensions/ccui/base-classes/UIScale9Sprite.js index a828908e64..e36ee5d569 100644 --- a/extensions/ccui/base-classes/UIScale9Sprite.js +++ b/extensions/ccui/base-classes/UIScale9Sprite.js @@ -1017,7 +1017,8 @@ ccui.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ }, getScale: function () { - cc.log(this.getScaleX() == this.getScaleY(), "Scale9Sprite#scale. ScaleX != ScaleY. Don't know which one to return"); + if(this.getScaleX() !== this.getScaleY()) + cc.log("Scale9Sprite#scale. ScaleX != ScaleY. Don't know which one to return"); return this.getScaleX(); }, diff --git a/extensions/ccui/base-classes/UIWidget.js b/extensions/ccui/base-classes/UIWidget.js index d7dc060958..b753d792ee 100644 --- a/extensions/ccui/base-classes/UIWidget.js +++ b/extensions/ccui/base-classes/UIWidget.js @@ -1726,7 +1726,8 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ return originalScale; }, getScale: function(){ - cc.log(this.getScaleX() == this.getScaleY(), "Widget#scale. ScaleX != ScaleY. Don't know which one to return"); + if(this.getScaleX() == this.getScaleY()) + cc.log("Widget#scale. ScaleX != ScaleY. Don't know which one to return"); return this.getScaleX(); }, diff --git a/extensions/ccui/uiwidgets/UIButton.js b/extensions/ccui/uiwidgets/UIButton.js index 4e3994c3c7..6dba636038 100644 --- a/extensions/ccui/uiwidgets/UIButton.js +++ b/extensions/ccui/uiwidgets/UIButton.js @@ -522,7 +522,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ this._buttonClickedRenderer.setVisible(false); this._buttonDisableRenderer.setVisible(false); if (this._scale9Enabled) - this._buttonNormalRenderer.setState(0/*Scale9Sprite::State::NORMAL*/); + this._buttonNormalRenderer.setState( ccui.Scale9Sprite.state.NORMAL); if (this._pressedTextureLoaded) { if (this.pressedActionEnabled){ this._buttonNormalRenderer.stopAllActions(); @@ -533,7 +533,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ this._titleRenderer.stopAllActions(); if (this._unifySize){ - var zoomTitleAction = cc.scaleTo(0.05/*ZOOM_ACTION_TIME_STEP*/, 1, 1); + var zoomTitleAction = cc.scaleTo(ccui.Button.ZOOM_ACTION_TIME_STEP, 1, 1); this._titleRenderer.runAction(zoomTitleAction); }else this._titleRenderer.runAction(zoomAction.clone()); @@ -560,7 +560,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ _onPressStateChangedToPressed: function () { var locNormalRenderer = this._buttonNormalRenderer; if (this._scale9Enabled) - locNormalRenderer.setState(0/*Scale9Sprite::State::NORMAL*/); + locNormalRenderer.setState(ccui.Scale9Sprite.state.NORMAL); if (this._pressedTextureLoaded) { locNormalRenderer.setVisible(false); @@ -962,30 +962,37 @@ ccui.Button.create = function (normalImage, selectedImage, disableImage, texType // Constants /** - * The normal renderer's zOrder value. + * The normal renderer's zOrder value of ccui.Button. * @constant * @type {number} */ ccui.Button.NORMAL_RENDERER_ZORDER = -2; /** - * The pressed renderer's zOrder value. + * The pressed renderer's zOrder value ccui.Button. * @constant * @type {number} */ ccui.Button.PRESSED_RENDERER_ZORDER = -2; /** - * The disabled renderer's zOrder value. + * The disabled renderer's zOrder value of ccui.Button. * @constant * @type {number} */ ccui.Button.DISABLED_RENDERER_ZORDER = -2; /** - * The title renderer's zOrder value. + * 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 */ diff --git a/extensions/ccui/uiwidgets/UISlider.js b/extensions/ccui/uiwidgets/UISlider.js index 48f725ac91..c2feccd6b6 100644 --- a/extensions/ccui/uiwidgets/UISlider.js +++ b/extensions/ccui/uiwidgets/UISlider.js @@ -64,7 +64,6 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ _sliderBallNormalTextureScaleX: 1, _sliderBallNormalTextureScaleY: 1, - _eventCallback: null, /** * allocates and initializes a UISlider. @@ -527,7 +526,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ * @param {Object} [target=] */ addEventListener: function(selector, target){ - this._sliderEventSelector = selector; + this._sliderEventSelector = selector; //when target is undefined, _sliderEventSelector = _eventCallback this._sliderEventListener = target; }, @@ -536,15 +535,10 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ if (this._sliderEventListener) this._sliderEventSelector.call(this._sliderEventListener, this, ccui.Slider.EVENT_PERCENT_CHANGED); else - this._sliderEventSelector(this, ccui.Slider.EVENT_PERCENT_CHANGED); - } - //todo check here - if (this._eventCallback){ - this._eventCallback(this, 0/*EventType::ON_PERCENTAGE_CHANGED*/); - } - if (this._ccEventCallback){ - this._ccEventCallback(this, 0/*static_cast(EventType::ON_PERCENTAGE_CHANGED)*/); + this._sliderEventSelector(this, ccui.Slider.EVENT_PERCENT_CHANGED); // _eventCallback } + if (this._ccEventCallback) + this._ccEventCallback(this, ccui.Slider.EVENT_PERCENT_CHANGED); }, /** @@ -710,7 +704,6 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ this._sliderEventListener = slider._sliderEventListener; this._sliderEventSelector = slider._sliderEventSelector; this._zoomScale = slider._zoomScale; - this._eventCallback = slider._eventCallback; this._ccEventCallback = slider._ccEventCallback; } diff --git a/extensions/ccui/uiwidgets/UITextField.js b/extensions/ccui/uiwidgets/UITextField.js index b0718917c8..056cc24d79 100644 --- a/extensions/ccui/uiwidgets/UITextField.js +++ b/extensions/ccui/uiwidgets/UITextField.js @@ -37,9 +37,6 @@ ccui._TextFieldRenderer = cc.TextFieldTTF.extend({ _insertText: false, _deleteBackward: false, _className: "_TextFieldRenderer", - _textFieldRendererAdaptDirty: true, - _ccEventCallback: null, - _eventCallback: null, ctor: function () { cc.TextFieldTTF.prototype.ctor.call(this); @@ -241,6 +238,8 @@ ccui.TextField = ccui.Widget.extend(/** @lends ccui.TextField# */{ _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. @@ -656,7 +655,7 @@ ccui.TextField = ccui.Widget.extend(/** @lends ccui.TextField# */{ this._textFieldEventSelector(this, ccui.TextField.EVENT_ATTACH_WITH_IME); } if (this._ccEventCallback){ - this._ccEventCallback(this, 0/*static_cast(EventType::ATTACH_WITH_IME)*/); + this._ccEventCallback(this, ccui.TextField.EVENT_ATTACH_WITH_IME); } }, @@ -667,12 +666,8 @@ ccui.TextField = ccui.Widget.extend(/** @lends ccui.TextField# */{ else this._textFieldEventSelector(this, ccui.TextField.EVENT_DETACH_WITH_IME); } - if (this._eventCallback){ - this._eventCallback(this, 0/*EventType::DETACH_WITH_IME*/); - } - if (this._ccEventCallback){ - this._ccEventCallback(this, 0/*static_cast(EventType::DETACH_WITH_IME)*/); - } + if (this._ccEventCallback) + this._ccEventCallback(this, ccui.TextField.EVENT_DETACH_WITH_IME); }, _insertTextEvent: function () { @@ -680,14 +675,10 @@ ccui.TextField = ccui.Widget.extend(/** @lends ccui.TextField# */{ if (this._textFieldEventListener) this._textFieldEventSelector.call(this._textFieldEventListener, this, ccui.TextField.EVENT_INSERT_TEXT); else - this._textFieldEventSelector(this, ccui.TextField.EVENT_INSERT_TEXT); - } - if (this._eventCallback){ - this._eventCallback(this, 0/*EventType::INSERT_TEXT*/); - } - if (this._ccEventCallback){ - this._ccEventCallback(this, 0/*static_cast(EventType::INSERT_TEXT)*/); + this._textFieldEventSelector(this, ccui.TextField.EVENT_INSERT_TEXT); //eventCallback } + if (this._ccEventCallback) + this._ccEventCallback(this, ccui.TextField.EVENT_INSERT_TEXT); }, _deleteBackwardEvent: function () { @@ -695,15 +686,10 @@ ccui.TextField = ccui.Widget.extend(/** @lends ccui.TextField# */{ if (this._textFieldEventListener) this._textFieldEventSelector.call(this._textFieldEventListener, this, ccui.TextField.EVENT_DELETE_BACKWARD); else - this._textFieldEventSelector(this, ccui.TextField.EVENT_DELETE_BACKWARD); - } - if (this._eventCallback){ - this._eventCallback(this, 0/*EventType::DELETE_BACKWARD*/); + this._textFieldEventSelector(this, ccui.TextField.EVENT_DELETE_BACKWARD); //eventCallback } if (this._ccEventCallback) - { - this._ccEventCallback(this, 0/*static_cast(EventType::DELETE_BACKWARD)*/); - } + this._ccEventCallback(this, ccui.TextField.EVENT_DELETE_BACKWARD); }, /** @@ -722,7 +708,7 @@ ccui.TextField = ccui.Widget.extend(/** @lends ccui.TextField# */{ * @param {Function} selector */ addEventListener: function(selector, target){ - this._textFieldEventSelector = selector; + this._textFieldEventSelector = selector; //when target is undefined, _textFieldEventSelector is ccEventCallback. this._textFieldEventListener = target; }, @@ -793,7 +779,6 @@ ccui.TextField = ccui.Widget.extend(/** @lends ccui.TextField# */{ this.setDetachWithIME(textField.getDetachWithIME()); this.setInsertText(textField.getInsertText()); this.setDeleteBackward(textField.getDeleteBackward()); - this._eventCallback = textField._eventCallback; this._ccEventCallback = textField._ccEventCallback; this._textFieldEventListener = textField._textFieldEventListener; this._textFieldEventSelector = textField._textFieldEventSelector; From 7d6d895e6a14802ceac9956703d899cd0562206d Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 13 Jan 2015 18:15:01 +0800 Subject: [PATCH 0149/1345] Modify the log text --- extensions/cocostudio/loader/parsers/scene-1.x.js | 2 +- .../loader/parsers/timelineParser-1.x.js | 2 +- .../loader/parsers/timelineParser-2.x.js | 14 +++++++------- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/scene-1.x.js b/extensions/cocostudio/loader/parsers/scene-1.x.js index 96183b3606..616350c613 100644 --- a/extensions/cocostudio/loader/parsers/scene-1.x.js +++ b/extensions/cocostudio/loader/parsers/scene-1.x.js @@ -217,7 +217,7 @@ cc.spriteFrameCache.addSpriteFrames(resourcePath + plist); }else{ if(!loadedPlist[resourcePath + plist]) - cc.log("%s need to pre load", resourcePath + plist); + cc.log("%s need to be pre loaded", resourcePath + plist); } } if(type !== 0) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-1.x.js b/extensions/cocostudio/loader/parsers/timelineParser-1.x.js index f4cbe3d9c3..b157859934 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-1.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-1.x.js @@ -38,7 +38,7 @@ 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 pre load", plist); + cc.log("%s need to be pre loaded", plist); else loadedPlist[plist] = true; cc.spriteFrameCache.addSpriteFrames( diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 0e4f9d244e..434114428d 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -194,7 +194,7 @@ self = this; loadTexture(json["FileData"], resourcePath, function(path, type){ if(!cc.loader.getRes(path)) - cc.log("%s need to pre load", path); + cc.log("%s need to be pre loaded", path); node = new cc.ParticleSystem(path); self.generalAttributes(node, json); node.setDrawMode(cc.ParticleSystem.TEXTURE_MODE); @@ -767,7 +767,7 @@ textureList.forEach(function(item){ loadTexture(json[item.name], resourcePath, function(path, type){ if(type == 0 && !loader.getRes(path)) - cc.log("%s need to pre load", path); + cc.log("%s need to be pre loaded", path); item.handle.call(widget, path, type); }); }); @@ -954,7 +954,7 @@ loadTexture(json["LabelAtlasFileImage_CNB"], resourcePath, function(path, type){ if(!cc.loader.getRes(path)) - cc.log("%s need to pre load", path); + cc.log("%s need to be pre loaded", path); if(type == 0){ widget.setProperty(stringValue, path, itemWidth, itemHeight, startCharMap); } @@ -980,7 +980,7 @@ loadTexture(json["LabelBMFontFile_CNB"], resourcePath, function(path, type){ if(!cc.loader.getRes(path)) - cc.log("%s need to pre load", path); + cc.log("%s need to be pre loaded", path); widget.setFntFile(path); }); return widget; @@ -1104,7 +1104,7 @@ if(cc.loader.getRes(file)) return ccs._load(file); else - cc.log("%s need to pre load", file); + cc.log("%s need to be pre loaded", file); } }; @@ -1136,7 +1136,7 @@ var plists, pngs; var armJson = cc.loader.getRes(path); if(!armJson) - cc.log("%s need to pre load", path); + cc.log("%s need to be pre loaded", path); else{ plists = armJson["config_file_path"]; pngs = armJson["config_png_path"]; @@ -1170,7 +1170,7 @@ cc.spriteFrameCache.addSpriteFrames(resourcePath + plist); }else{ if(!loadedPlist[resourcePath + plist]) - cc.log("%s need to pre load", resourcePath + plist); + cc.log("%s need to be pre loaded", resourcePath + plist); } } if(type !== 0) From 09eb5ca8f04a6d095e3de56fd3c4dfb2006b07ed Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Wed, 14 Jan 2015 14:55:29 +0800 Subject: [PATCH 0150/1345] Fixed cocos2d/cocos2d-js/#1309: ccui.Widget can't touch when it reused. --- extensions/ccui/base-classes/UIWidget.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/extensions/ccui/base-classes/UIWidget.js b/extensions/ccui/base-classes/UIWidget.js index b753d792ee..eb1df91975 100644 --- a/extensions/ccui/base-classes/UIWidget.js +++ b/extensions/ccui/base-classes/UIWidget.js @@ -145,6 +145,9 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @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); From 082ab2e9efa6ced5a522dbbe12542391086af7aa Mon Sep 17 00:00:00 2001 From: Joe Lafiosca Date: Wed, 14 Jan 2015 18:10:27 -0500 Subject: [PATCH 0151/1345] register loader for JavaScript (.js) files --- cocos2d/core/platform/CCLoaders.js | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/cocos2d/core/platform/CCLoaders.js b/cocos2d/core/platform/CCLoaders.js index d051a80b42..44aefd9f00 100644 --- a/cocos2d/core/platform/CCLoaders.js +++ b/cocos2d/core/platform/CCLoaders.js @@ -37,6 +37,13 @@ cc._jsonLoader = { }; cc.loader.register(["json", "ExportJson"], cc._jsonLoader); +cc._jsLoader = { + load : function(realUrl, url, res, cb){ + cc.loader.loadJs(realUrl, cb); + } +}; +cc.loader.register(["js"], cc._jsLoader); + cc._imgLoader = { load : function(realUrl, url, res, cb){ cc.loader.cache[url] = cc.loader.loadImg(realUrl, function(err, img){ From 599302e361614da49d23b1e87ae689708101077e Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Thu, 15 Jan 2015 13:42:21 +0800 Subject: [PATCH 0152/1345] Added Focus event, Focus event listener and added getSelectedItem function to cc.Menu --- cocos2d/core/event-manager/CCEvent.js | 16 +++++++- cocos2d/core/event-manager/CCEventListener.js | 37 ++++++++++++++++++- cocos2d/menus/CCMenuItem.js | 11 +++++- 3 files changed, 60 insertions(+), 4 deletions(-) diff --git a/cocos2d/core/event-manager/CCEvent.js b/cocos2d/core/event-manager/CCEvent.js index 74ac15c845..f5d8624830 100644 --- a/cocos2d/core/event-manager/CCEvent.js +++ b/cocos2d/core/event-manager/CCEvent.js @@ -420,4 +420,18 @@ cc.EventTouch = cc.Event.extend(/** @lends cc.EventTouch# */{ */ cc.EventTouch.MAX_TOUCHES = 5; -cc.EventTouch.EventCode = {BEGAN: 0, MOVED: 1, ENDED: 2, CANCELLED: 3}; \ No newline at end of file +cc.EventTouch.EventCode = {BEGAN: 0, MOVED: 1, ENDED: 2, CANCELLED: 3}; + +/** + * Focus change event for UI widget + * @class + * @extends cc.Event + */ +cc.EventFocus = cc.Event.extend(/** @lends cc.EventTouch# */{ + _widgetGetFocus: null, + _widgetLoseFocus: null, + ctor: function(widgetLoseFocus, widgetGetFocus){ + this._widgetGetFocus = widgetGetFocus; + this._widgetLoseFocus = widgetLoseFocus; + } +}); \ No newline at end of file diff --git a/cocos2d/core/event-manager/CCEventListener.js b/cocos2d/core/event-manager/CCEventListener.js index 9cb338fed5..96bee80700 100644 --- a/cocos2d/core/event-manager/CCEventListener.js +++ b/cocos2d/core/event-manager/CCEventListener.js @@ -269,6 +269,13 @@ cc.EventListener.ACCELERATION = 5; */ cc.EventListener.CUSTOM = 6; +/** + * The type code of Focus change event listener. + * @constant + * @type {number} + */ +cc.EventListener.FOCUS = 7; + cc._EventListenerCustom = cc.EventListener.extend({ _onCustomEvent: null, ctor: function (listenerId, callback) { @@ -470,11 +477,37 @@ cc.EventListener.create = function(argObj){ else if(listenerType === cc.EventListener.ACCELERATION){ listener = new cc._EventListenerAcceleration(argObj.callback); delete argObj.callback; - } + } else if(listenerType === cc.EventListener.FOCUS) + listener = new cc._EventListenerFocus(); for(var key in argObj) { listener[key] = argObj[key]; } return listener; -}; \ No newline at end of file +}; + +cc._EventListenerFocus = cc.EventListener.extend({ + clone: function(){ + var listener = new cc._EventListenerFocus(); + listener.onFocusChanged = this.onFocusChanged; + return listener; + }, + checkAvailable: function(){ + if(!this.onFocusChanged){ + cc.log("Invalid EventListenerFocus!"); + return false; + } + return true; + }, + onFocusChanged: null, + ctor: function(){ + var listener = function(event){ + if(this.onFocusChanged) + this.onFocusChanged(event._widgetLoseFocus, event._widgetGetFocus); + }; + cc.EventListener.prototype.ctor.call(this, cc.EventListener.FOCUS, cc._EventListenerFocus.LISTENER_ID, listener); + } +}); + +cc._EventListenerFocus.LISTENER_ID = ""; \ No newline at end of file diff --git a/cocos2d/menus/CCMenuItem.js b/cocos2d/menus/CCMenuItem.js index 0d92724556..8225c03cc6 100644 --- a/cocos2d/menus/CCMenuItem.js +++ b/cocos2d/menus/CCMenuItem.js @@ -1369,12 +1369,21 @@ cc.MenuItemToggle = cc.MenuItem.extend(/** @lends cc.MenuItemToggle# */{ }, /** - * returns the selected item + * 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'.
From a98914a17344b48b19340fde7e48ea275b278aa0 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 15 Jan 2015 13:45:40 +0800 Subject: [PATCH 0153/1345] HBox and VBox actor error --- extensions/ccui/layouts/UIHBox.js | 1 + extensions/ccui/layouts/UIVBox.js | 1 + 2 files changed, 2 insertions(+) diff --git a/extensions/ccui/layouts/UIHBox.js b/extensions/ccui/layouts/UIHBox.js index 1a0c65d36c..4e32002dd4 100644 --- a/extensions/ccui/layouts/UIHBox.js +++ b/extensions/ccui/layouts/UIHBox.js @@ -35,6 +35,7 @@ ccui.HBox = ccui.Layout.extend(/** @lends ccui.HBox# */{ * @param {cc.Size} [size] */ ctor: function(size){ + ccui.Layout.prototype.ctor.call(this, size); if(size !== undefined) this.initWithSize(size); else diff --git a/extensions/ccui/layouts/UIVBox.js b/extensions/ccui/layouts/UIVBox.js index 15c4871f71..d816c729db 100644 --- a/extensions/ccui/layouts/UIVBox.js +++ b/extensions/ccui/layouts/UIVBox.js @@ -35,6 +35,7 @@ ccui.VBox = ccui.Layout.extend(/** @lends ccui.VBox# */{ * @param {cc.Size} size */ ctor: function(size){ + ccui.Layout.prototype.ctor.call(this, size); if(size !== undefined) this.initWithSize(size); else From e047e4dc1b2250294b35ad280288a46fe9d92f81 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 15 Jan 2015 13:46:30 +0800 Subject: [PATCH 0154/1345] UIWidget get positionPercent error --- extensions/ccui/base-classes/UIWidget.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/ccui/base-classes/UIWidget.js b/extensions/ccui/base-classes/UIWidget.js index eb1df91975..94adbca007 100644 --- a/extensions/ccui/base-classes/UIWidget.js +++ b/extensions/ccui/base-classes/UIWidget.js @@ -1187,7 +1187,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ this._positionPercent.x = component.getPositionPercentX(); this._positionPercent.y = component.getPositionPercentY(); } - return cc.p(this.getNormalizedPosition()); + return cc.p(this._positionPercent); }, _getXPercent: function () { From 4ce4ccc48431f309d26fc5ef5fbfb3f9e1287776 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 15 Jan 2015 13:47:11 +0800 Subject: [PATCH 0155/1345] Fixed CheckBox and ImageView ctor problem --- extensions/ccui/uiwidgets/UICheckBox.js | 4 ++-- extensions/ccui/uiwidgets/UIImageView.js | 17 +++++++++++++++-- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/extensions/ccui/uiwidgets/UICheckBox.js b/extensions/ccui/uiwidgets/UICheckBox.js index 9a027bc98e..56639a17cf 100644 --- a/extensions/ccui/uiwidgets/UICheckBox.js +++ b/extensions/ccui/uiwidgets/UICheckBox.js @@ -81,8 +81,8 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ ctor: function (backGround, backGroundSelected,cross,backGroundDisabled,frontCrossDisabled,texType) { ccui.Widget.prototype.ctor.call(this); this.setTouchEnabled(true); - - texType !== undefined && this.init(backGround, backGroundSelected,cross,backGroundDisabled,frontCrossDisabled,texType); + texType = texType === undefined ? 0 : texType; + this.init(backGround, backGroundSelected,cross,backGroundDisabled,frontCrossDisabled,texType); }, /** diff --git a/extensions/ccui/uiwidgets/UIImageView.js b/extensions/ccui/uiwidgets/UIImageView.js index a951d07ed0..9a743dff29 100644 --- a/extensions/ccui/uiwidgets/UIImageView.js +++ b/extensions/ccui/uiwidgets/UIImageView.js @@ -52,8 +52,8 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{ this._capInsets = cc.rect(0,0,0,0); this._imageTextureSize = cc.size(this._capInsets.width, this._capInsets.height); ccui.Widget.prototype.ctor.call(this); - - texType !== undefined && this.init(imageFileName, texType); + texType = texType === undefined ? 0 : texType; + this.init(imageFileName, texType); }, /** @@ -298,6 +298,19 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{ this.loadTexture(imageView._textureFile, imageView._imageTexType); this.setCapInsets(imageView._capInsets); } + }, + /** + * 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){ + if(height) + contentSize = cc.size(contentSize, height); + ccui.Widget.prototype.setContentSize.call(this, contentSize); + this._imageRenderer.setContentSize(contentSize); } }); From 9e906f47aa29ee71202f5090b0ba266e4558e8e3 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 15 Jan 2015 13:47:45 +0800 Subject: [PATCH 0156/1345] Scale9Sprite setContentSize error --- .../ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js | 5 +++++ .../ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js | 10 ++++++++++ .../control-extension/CCScale9SpriteCanvasRenderCmd.js | 5 +++++ .../control-extension/CCScale9SpriteWebGLRenderCmd.js | 10 ++++++++++ 4 files changed, 30 insertions(+) diff --git a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js index a324dab733..e049c5abe6 100644 --- a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js +++ b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js @@ -62,6 +62,11 @@ proto.transform = function(parentCmd){ var node = this._node; + if (node._positionsAreDirty) { + node._updatePositions(); + node._positionsAreDirty = false; + node._scale9Dirty = true; + } this._cacheScale9Sprite(); cc.Node.CanvasRenderCmd.prototype.transform.call(this, parentCmd); diff --git a/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js b/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js index aba5ca6b11..150c685f2d 100644 --- a/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js +++ b/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js @@ -45,6 +45,16 @@ cc.Node.WebGLRenderCmd.prototype.visit.call(this, parentCmd); }; + proto.transform = function(){ + var node = this._node; + cc.Node.WebGLRenderCmd.prototype.transform.call(this); + if (node._positionsAreDirty) { + node._updatePositions(); + node._positionsAreDirty = false; + node._scale9Dirty = true; + } + }; + proto._updateDisplayColor = function(parentColor){ cc.Node.WebGLRenderCmd.prototype._updateDisplayColor.call(this, parentColor); diff --git a/extensions/gui/control-extension/CCScale9SpriteCanvasRenderCmd.js b/extensions/gui/control-extension/CCScale9SpriteCanvasRenderCmd.js index 8332b5cd80..ab2963b328 100644 --- a/extensions/gui/control-extension/CCScale9SpriteCanvasRenderCmd.js +++ b/extensions/gui/control-extension/CCScale9SpriteCanvasRenderCmd.js @@ -89,6 +89,11 @@ proto.transform = function(parentCmd){ var node = this._node; + if (node._positionsAreDirty) { + node._updatePositions(); + node._positionsAreDirty = false; + node._scale9Dirty = true; + } this._cacheScale9Sprite(); cc.Node.CanvasRenderCmd.prototype.transform.call(this, parentCmd); diff --git a/extensions/gui/control-extension/CCScale9SpriteWebGLRenderCmd.js b/extensions/gui/control-extension/CCScale9SpriteWebGLRenderCmd.js index 047d00ccc3..6a5826dd12 100644 --- a/extensions/gui/control-extension/CCScale9SpriteWebGLRenderCmd.js +++ b/extensions/gui/control-extension/CCScale9SpriteWebGLRenderCmd.js @@ -68,4 +68,14 @@ } cc.Node.WebGLRenderCmd.prototype.visit.call(this, parentCmd); }; + + proto.transform = function(){ + var node = this._node; + cc.Node.WebGLRenderCmd.prototype.transform.call(this); + if (node._positionsAreDirty) { + node._updatePositions(); + node._positionsAreDirty = false; + node._scale9Dirty = true; + } + }; })(); \ No newline at end of file From 296eab2f6501dabb52abc7a94c7a120659233310 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Thu, 15 Jan 2015 15:22:08 +0800 Subject: [PATCH 0157/1345] Added ccui._FocusNavigationController --- cocos2d/core/event-manager/CCEvent.js | 5 ++ extensions/ccui/base-classes/UIWidget.js | 104 ++++++++++++++++++----- 2 files changed, 87 insertions(+), 22 deletions(-) diff --git a/cocos2d/core/event-manager/CCEvent.js b/cocos2d/core/event-manager/CCEvent.js index f5d8624830..91e4d23c5b 100644 --- a/cocos2d/core/event-manager/CCEvent.js +++ b/cocos2d/core/event-manager/CCEvent.js @@ -430,6 +430,11 @@ cc.EventTouch.EventCode = {BEGAN: 0, MOVED: 1, ENDED: 2, CANCELLED: 3}; cc.EventFocus = cc.Event.extend(/** @lends cc.EventTouch# */{ _widgetGetFocus: null, _widgetLoseFocus: null, + /** + * Constructor function. + * @param {ccui.Widget} widgetLoseFocus + * @param {ccui.Widget} widgetGetFocus + */ ctor: function(widgetLoseFocus, widgetGetFocus){ this._widgetGetFocus = widgetGetFocus; this._widgetLoseFocus = widgetLoseFocus; diff --git a/extensions/ccui/base-classes/UIWidget.js b/extensions/ccui/base-classes/UIWidget.js index eb1df91975..26602c6fce 100644 --- a/extensions/ccui/base-classes/UIWidget.js +++ b/extensions/ccui/base-classes/UIWidget.js @@ -23,6 +23,62 @@ THE SOFTWARE. ****************************************************************************/ +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.down) { + this._firstFocusedWidget = this._firstFocusedWidget.findNextFocusedWidget(ccui.Widget.DOWN, this._firstFocusedWidget); + } + if (keyCode == cc.KEY.up){ + this._firstFocusedWidget = this._firstFocusedWidget.findNextFocusedWidget(ccui.Widget.UP, this._firstFocusedWidget); + } + if (keyCode == cc.KEY.left) { + this._firstFocusedWidget = this._firstFocusedWidget.findNextFocusedWidget(ccui.Widget.LEFT, this._firstFocusedWidget); + } + if (keyCode == cc.KEY.right) { + this._firstFocusedWidget = this._firstFocusedWidget.findNextFocusedWidget(ccui.Widget.RIGHT, this._firstFocusedWidget); + } + } + }, + + _addKeyboardEventListener: function(){ + if (!this._keyboardListener) { + this._keyboardListener = cc.EventListener.create({ + event: cc.EventListener.FOCUS, + 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"; /** @@ -269,10 +325,14 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ _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) + if (ccui.Widget._focusedWidget == this){ ccui.Widget._focusedWidget = null; + ccui.Widget._focusNavigationController = null; + } }, /** @@ -664,8 +724,11 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ setFocused: function (focus) { this._focused = focus; //make sure there is only one focusedWidget - if (focus) + if (focus){ ccui.Widget._focusedWidget = this; + if(ccui.Widget._focusNavigationController) + ccui.Widget._focusNavigationController._setFirstFocsuedWidget(this); + } }, /** @@ -735,7 +798,22 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @note it doesn't implemented on Web * @param {Boolean} enable set true to enable dpad focus navigation, otherwise disable dpad focus navigation */ - enableDpadNavigation: function(enable){}, + enableDpadNavigation: function(enable){ + if (enable){ + if (null == ccui.Widget._focusNavigationController) { + ccui.Widget._focusNavigationController = new ccui._FocusNavigationController(); + if (this._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; + } + } + }, /** *

@@ -1857,6 +1935,7 @@ ccui.Widget.create = function () { }; ccui.Widget._focusedWidget = null; //both layout & widget will be stored in this variable +ccui.Widget._focusNavigationController = null; /** * Gets the focused widget of current stage. @@ -1995,22 +2074,3 @@ ccui.Widget.POSITION_ABSOLUTE = 0; * @type {number} */ ccui.Widget.POSITION_PERCENT = 1; - -/** - * The widget focus event. - * @class - * @extends cc.Event - */ -cc.EventFocus = cc.Event.extend(/** @lends cc.EventFocus# */{ - _widgetGetFocus: null, - _widgetLoseFocus: null, - /** - * Constructor function. - * @param {ccui.Widget} widgetLoseFocus - * @param {ccui.Widget} widgetGetFocus - */ - ctor: function(widgetLoseFocus, widgetGetFocus){ - this._widgetGetFocus = widgetGetFocus; - this._widgetLoseFocus = widgetLoseFocus; - } -}); \ No newline at end of file From 39adb05cee55145229d415bd1f516747f81242d1 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 15 Jan 2015 17:10:46 +0800 Subject: [PATCH 0158/1345] Fixed Widget position error (percent) --- .../UIScale9SpriteCanvasRenderCmd.js | 2 +- .../UIScale9SpriteWebGLRenderCmd.js | 4 +-- extensions/ccui/base-classes/UIWidget.js | 33 +++++-------------- .../ccui/base-classes/UIWidgetRenderCmd.js | 26 +++++++++++++++ 4 files changed, 37 insertions(+), 28 deletions(-) diff --git a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js index e049c5abe6..b6714b5573 100644 --- a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js +++ b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js @@ -62,13 +62,13 @@ proto.transform = function(parentCmd){ var node = this._node; + cc.Node.CanvasRenderCmd.prototype.transform.call(this, parentCmd); if (node._positionsAreDirty) { node._updatePositions(); node._positionsAreDirty = false; node._scale9Dirty = true; } this._cacheScale9Sprite(); - cc.Node.CanvasRenderCmd.prototype.transform.call(this, parentCmd); var children = node._children; for(var i=0; i Date: Thu, 15 Jan 2015 17:37:06 +0800 Subject: [PATCH 0159/1345] UIWidgetRenderCmd webgl error (Missing code) --- extensions/ccui/base-classes/UIWidgetRenderCmd.js | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/extensions/ccui/base-classes/UIWidgetRenderCmd.js b/extensions/ccui/base-classes/UIWidgetRenderCmd.js index 5fdff70c21..7e9c18ba8f 100644 --- a/extensions/ccui/base-classes/UIWidgetRenderCmd.js +++ b/extensions/ccui/base-classes/UIWidgetRenderCmd.js @@ -80,7 +80,14 @@ if (cc._renderType === cc._RENDER_TYPE_CANVAS) { var node = this._node; if (node._visible) { node._adaptRenderers(); - cc.ProtectedNode.CanvasRenderCmd.prototype.transform.call(this, parentCmd, recursive); + + var widgetParent = node.getWidgetParent(); + if (widgetParent) { + var parentSize = widgetParent.getSize(); + 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); } }; })(); From a64593d6bfafa9f9e96c61f6b37525f2dabb6fcc Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 15 Jan 2015 17:37:40 +0800 Subject: [PATCH 0160/1345] UIText add TextColor --- extensions/ccui/uiwidgets/UIText.js | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/extensions/ccui/uiwidgets/UIText.js b/extensions/ccui/uiwidgets/UIText.js index 70e4984049..84e7123a70 100644 --- a/extensions/ccui/uiwidgets/UIText.js +++ b/extensions/ccui/uiwidgets/UIText.js @@ -433,15 +433,15 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ 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(); } - //todo label add setTextColor -// setTextColor: function(color){ -// this._labelRenderer.setTextColor(color); -// }, -// -// getTextColor: function(){ -// return this._labelRenderer.getTextColor(); -// } }); var _p = ccui.Text.prototype; From 9a5af6c0a91299b82ea2eef5264f3e7a01b28306 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Fri, 16 Jan 2015 10:31:14 +0800 Subject: [PATCH 0161/1345] Fixed some mistakes for UI focus feature. --- cocos2d/core/event-manager/CCEvent.js | 9 ++++++- cocos2d/core/event-manager/CCEventListener.js | 10 +++++-- cocos2d/core/event-manager/CCEventManager.js | 2 ++ extensions/ccui/base-classes/UIWidget.js | 10 +++---- extensions/ccui/layouts/UILayout.js | 27 +++++++++---------- 5 files changed, 36 insertions(+), 22 deletions(-) diff --git a/cocos2d/core/event-manager/CCEvent.js b/cocos2d/core/event-manager/CCEvent.js index 91e4d23c5b..fa5c47f5a1 100644 --- a/cocos2d/core/event-manager/CCEvent.js +++ b/cocos2d/core/event-manager/CCEvent.js @@ -106,12 +106,18 @@ cc.Event.ACCELERATION = 2; * @type {number} */ cc.Event.MOUSE = 3; +/** + * The type code of UI focus event. + * @constant + * @type {number} + */ +cc.Event.FOCUS = 4; /** * The type code of Custom event. * @constant * @type {number} */ -cc.Event.CUSTOM = 4; +cc.Event.CUSTOM = 6; /** * The Custom event @@ -436,6 +442,7 @@ cc.EventFocus = cc.Event.extend(/** @lends cc.EventTouch# */{ * @param {ccui.Widget} widgetGetFocus */ ctor: function(widgetLoseFocus, widgetGetFocus){ + cc.Event.prototype.ctor.call(this, cc.Event.FOCUS); this._widgetGetFocus = widgetGetFocus; this._widgetLoseFocus = widgetLoseFocus; } diff --git a/cocos2d/core/event-manager/CCEventListener.js b/cocos2d/core/event-manager/CCEventListener.js index 96bee80700..642d7d9e47 100644 --- a/cocos2d/core/event-manager/CCEventListener.js +++ b/cocos2d/core/event-manager/CCEventListener.js @@ -262,12 +262,18 @@ cc.EventListener.MOUSE = 4; * @type {number} */ cc.EventListener.ACCELERATION = 5; +/** + * The type code of focus event listener. + * @constant + * @type {number} + */ +cc.EventListener.ACCELERATION = 6; /** * The type code of custom event listener. * @constant * @type {number} */ -cc.EventListener.CUSTOM = 6; +cc.EventListener.CUSTOM = 8; /** * The type code of Focus change event listener. @@ -510,4 +516,4 @@ cc._EventListenerFocus = cc.EventListener.extend({ } }); -cc._EventListenerFocus.LISTENER_ID = ""; \ No newline at end of file +cc._EventListenerFocus.LISTENER_ID = "__cc_focus_event"; \ No newline at end of file diff --git a/cocos2d/core/event-manager/CCEventManager.js b/cocos2d/core/event-manager/CCEventManager.js index f827944f7c..f412e20b13 100644 --- a/cocos2d/core/event-manager/CCEventManager.js +++ b/cocos2d/core/event-manager/CCEventManager.js @@ -83,6 +83,8 @@ cc.__getListenerID = function (event) { return cc._EventListenerKeyboard.LISTENER_ID; if(getType === eventType.MOUSE) return cc._EventListenerMouse.LISTENER_ID; + if(getType === eventType.FOCUS) + return cc._EventListenerFocus.LISTENER_ID; if(getType === eventType.TOUCH){ // Touch listener is very special, it contains two kinds of listeners, EventListenerTouchOneByOne and EventListenerTouchAllAtOnce. // return UNKNOWN instead. diff --git a/extensions/ccui/base-classes/UIWidget.js b/extensions/ccui/base-classes/UIWidget.js index ec2c3422dd..c1ee916a4d 100644 --- a/extensions/ccui/base-classes/UIWidget.js +++ b/extensions/ccui/base-classes/UIWidget.js @@ -64,7 +64,7 @@ ccui._FocusNavigationController = cc.Class.extend({ _addKeyboardEventListener: function(){ if (!this._keyboardListener) { this._keyboardListener = cc.EventListener.create({ - event: cc.EventListener.FOCUS, + event: cc.EventListener.KEYBOARD, onKeyReleased: this._onKeyPressed.bind(this) }); cc.eventManager.addListener(this._keyboardListener, this._keyboardEventPriority); @@ -761,7 +761,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ var isLayout = current instanceof ccui.Layout; if (this.isFocused() || isLayout) { var layout = this.getParent(); - if (null == layout){ + if (null == layout || !(layout instanceof ccui.Layout)){ //the outer layout's default behaviour is : loop focus if (isLayout) return current.findNextFocusedWidget(direction, current); @@ -802,7 +802,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ if (enable){ if (null == ccui.Widget._focusNavigationController) { ccui.Widget._focusNavigationController = new ccui._FocusNavigationController(); - if (this._focusedWidget) { + if (ccui.Widget._focusedWidget) { ccui.Widget._focusNavigationController._setFirstFocsuedWidget(ccui.Widget._focusedWidget); } } @@ -1999,13 +1999,13 @@ ccui.Widget.RIGHT = 1; * @constant * @type {number} */ -ccui.Widget.UP = 0; +ccui.Widget.UP = 2; /** * The down of Focus direction for ccui.Widget * @constant * @type {number} */ -ccui.Widget.DOWN = 1; +ccui.Widget.DOWN = 3; //texture resource type /** diff --git a/extensions/ccui/layouts/UILayout.js b/extensions/ccui/layouts/UILayout.js index 4a6273aeac..08bb627824 100644 --- a/extensions/ccui/layouts/UILayout.js +++ b/extensions/ccui/layouts/UILayout.js @@ -66,7 +66,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ _backGroundImageOpacity:0, _loopFocus: false, //whether enable loop focus or not - __passFocusToChild: false, //on default, it will pass the focus to the next nearest widget + __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, @@ -162,7 +162,6 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ 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) { @@ -172,7 +171,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ return w; } - if (null == parent) + if (null == parent || !(parent instanceof ccui.Layout)) return this; parent._isFocusPassing = true; return parent.findNextFocusedWidget(direction, this); @@ -189,10 +188,10 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ case ccui.Widget.UP: if (this._isLastWidgetInContainer(this, direction)){ if (this._isWidgetAncestorSupportLoopFocus(current, direction)) - return this.findNextFocusedWidget(direction, this); + return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, this); return current; } else { - return this.findNextFocusedWidget(direction, this); + return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, this); } break; default: @@ -205,11 +204,11 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ case ccui.Widget.RIGHT: if (this._isLastWidgetInContainer(this, direction)) { if (this._isWidgetAncestorSupportLoopFocus(current, direction)) - return this.findNextFocusedWidget(direction, this); + return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, this); return current; } else - return this.findNextFocusedWidget(direction, this); + return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, this); break; case ccui.Widget.DOWN: return this._getNextFocusedWidget(direction, current); @@ -1094,7 +1093,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ if(widget) return widget; } else{ - if (child instanceof cc.Widget) + if (child instanceof ccui.Widget) return child; } } @@ -1190,12 +1189,12 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ } else return this._getNextFocusedWidget(direction, nextWidget); } else - return (current instanceof ccui.Layout) ? current : this._focusedWidget; + 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 : this._focusedWidget; + return (current instanceof ccui.Layout) ? current : ccui.Widget._focusedWidget; } else return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, this); } @@ -1240,12 +1239,12 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ } else return this._getPreviousFocusedWidget(direction, nextWidget); } else - return (current instanceof ccui.Layout) ? current : this._focusedWidget; + 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 : this._focusedWidget; + return (current instanceof ccui.Layout) ? current : ccui.Widget._focusedWidget; } else return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, this); } @@ -1289,7 +1288,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ */ _isLastWidgetInContainer:function(widget, direction){ var parent = widget.getParent(); - if (parent instanceof ccui.Layout) + if (parent == null || !(parent instanceof ccui.Layout)) return true; var container = parent.getChildren(); @@ -1345,7 +1344,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ */ _isWidgetAncestorSupportLoopFocus: function(widget, direction){ var parent = widget.getParent(); - if (parent == null) + if (parent == null || !(parent instanceof ccui.Layout)) return false; if (parent.isLoopFocus()) { var layoutType = parent.getLayoutType(); From c5adc50c7f8c5d4d283f7c77ffe204d5dc40e89b Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 16 Jan 2015 10:42:03 +0800 Subject: [PATCH 0162/1345] Modify the ui texture callback --- extensions/ccui/uiwidgets/UIButton.js | 28 +++---------------- extensions/ccui/uiwidgets/UICheckBox.js | 33 ++++------------------- extensions/ccui/uiwidgets/UIImageView.js | 11 +------- extensions/ccui/uiwidgets/UILoadingBar.js | 24 +---------------- extensions/ccui/uiwidgets/UISlider.js | 21 ++++----------- extensions/ccui/uiwidgets/UITextBMFont.js | 2 +- 6 files changed, 16 insertions(+), 103 deletions(-) diff --git a/extensions/ccui/uiwidgets/UIButton.js b/extensions/ccui/uiwidgets/UIButton.js index 6dba636038..2280b6eccd 100644 --- a/extensions/ccui/uiwidgets/UIButton.js +++ b/extensions/ccui/uiwidgets/UIButton.js @@ -254,17 +254,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ var self = this; if(!this._buttonNormalRenderer.texture || !this._buttonNormalRenderer.texture.isLoaded()){ this._buttonNormalRenderer.addEventListener("load", function(){ - self._findLayout(); - - self._normalTextureSize = self._buttonNormalRenderer.getContentSize(); - self._updateChildrenDisplayedRGBA(); - - self._buttonNormalRenderer.setColor(self.getColor()); - self._buttonNormalRenderer.setOpacity(self.getOpacity()); - - self._updateContentSizeWithTextureSize(self._normalTextureSize); - self._normalTextureLoaded = true; - self._normalTextureAdaptDirty = true; + self.loadTextureNormal(normal, texType); }); } @@ -311,13 +301,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ var self = this; if(!this._buttonClickedRenderer.texture || !this._buttonClickedRenderer.texture.isLoaded()){ this._buttonClickedRenderer.addEventListener("load", function(){ - self._findLayout(); - - self._pressedTextureSize = self._buttonClickedRenderer.getContentSize(); - self._updateChildrenDisplayedRGBA(); - - self._pressedTextureLoaded = true; - self._pressedTextureAdaptDirty = true; + self.loadTexturePressed(selected, texType); }); } @@ -361,13 +345,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ var self = this; if(!this._buttonDisableRenderer.texture || !this._buttonDisableRenderer.texture.isLoaded()){ this._buttonDisableRenderer.addEventListener("load", function() { - self._findLayout(); - - self._disabledTextureSize = self._buttonDisableRenderer.getContentSize(); - self._updateChildrenDisplayedRGBA(); - - self._disabledTextureLoaded = true; - self._disabledTextureAdaptDirty = true; + self.loadTextureDisabled(disabled, texType); }); } diff --git a/extensions/ccui/uiwidgets/UICheckBox.js b/extensions/ccui/uiwidgets/UICheckBox.js index 56639a17cf..9b5364ab7e 100644 --- a/extensions/ccui/uiwidgets/UICheckBox.js +++ b/extensions/ccui/uiwidgets/UICheckBox.js @@ -154,11 +154,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ var self = this; if(!bgBoxRenderer.texture || !bgBoxRenderer.texture.isLoaded()){ bgBoxRenderer.addEventListener("load", function(){ - self._findLayout(); - - self._updateChildrenDisplayedRGBA(); - self._updateContentSizeWithTextureSize(self._backGroundBoxRenderer.getContentSize()); - self._backGroundBoxRendererAdaptDirty = true; + self.loadTextureBackGround(backGround, texType); }); } @@ -175,13 +171,6 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ break; } - if (!bgBoxRenderer.textureLoaded()) { - this._backGroundBoxRenderer.setContentSize(this._customSize); - bgBoxRenderer.addEventListener("load", function () { - this._updateContentSizeWithTextureSize(this._backGroundBoxRenderer.getContentSize()); - }, this); - } - this._updateChildrenDisplayedRGBA(); this._updateContentSizeWithTextureSize(this._backGroundBoxRenderer.getContentSize()); @@ -204,10 +193,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ var self = this; if(!this._backGroundSelectedBoxRenderer.texture || !this._backGroundSelectedBoxRenderer.texture.isLoaded()){ this._backGroundSelectedBoxRenderer.addEventListener("load", function(){ - self._findLayout(); - - self._updateChildrenDisplayedRGBA(); - self._backGroundSelectedBoxRendererAdaptDirty = true; + self.loadTextureBackGroundSelected(backGroundSelected, texType); }); } @@ -245,10 +231,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ var self = this; if(!this._frontCrossRenderer.texture || !this._frontCrossRenderer.texture.isLoaded()){ this._frontCrossRenderer.addEventListener("load", function(){ - self._findLayout(); - - self._updateChildrenDisplayedRGBA(); - self._frontCrossRendererAdaptDirty = true; + self.loadTextureFrontCross(cross, texType); }); } @@ -285,10 +268,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ var self = this; if(!this._backGroundBoxDisabledRenderer.texture || !this._backGroundBoxDisabledRenderer.texture.isLoaded()){ this._backGroundBoxDisabledRenderer.addEventListener("load", function(){ - self._findLayout(); - - self._updateChildrenDisplayedRGBA(); - self._backGroundBoxDisabledRendererAdaptDirty = true; + self.loadTextureBackGroundDisabled(backGroundDisabled, texType); }); } @@ -325,10 +305,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ var self = this; if(!this._frontCrossDisabledRenderer.texture || !this._frontCrossDisabledRenderer.texture.isLoaded()){ this._frontCrossDisabledRenderer.addEventListener("load", function(){ - self._findLayout(); - - self._updateChildrenDisplayedRGBA(); - self._frontCrossDisabledRendererAdaptDirty = true; + self.loadTextureFrontCrossDisabled(frontCrossDisabled, texType); }); } diff --git a/extensions/ccui/uiwidgets/UIImageView.js b/extensions/ccui/uiwidgets/UIImageView.js index 9a743dff29..0aa6e71b28 100644 --- a/extensions/ccui/uiwidgets/UIImageView.js +++ b/extensions/ccui/uiwidgets/UIImageView.js @@ -102,16 +102,7 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{ if(!imageRenderer.texture || !imageRenderer.texture.isLoaded()){ imageRenderer.addEventListener("load", function(){ - self._findLayout(); - - self._imageTextureSize = imageRenderer.getContentSize(); - - self._updateChildrenDisplayedRGBA(); - - self._updateContentSizeWithTextureSize(self._imageTextureSize); - if(self._scale9Enabled) - self.setCapInsets(self._capInsets); - self._imageRendererAdaptDirty = true; + self.loadTexture(fileName, texType); }); } diff --git a/extensions/ccui/uiwidgets/UILoadingBar.js b/extensions/ccui/uiwidgets/UILoadingBar.js index ed28c83720..2d6467a9c5 100644 --- a/extensions/ccui/uiwidgets/UILoadingBar.js +++ b/extensions/ccui/uiwidgets/UILoadingBar.js @@ -124,29 +124,7 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{ var self = this; if(!barRenderer.texture || !barRenderer.texture.isLoaded()){ barRenderer.addEventListener("load", function(){ - - self._findLayout(); - - var bz = barRenderer.getContentSize(); - self._barRendererTextureSize.width = bz.width; - self._barRendererTextureSize.height = bz.height; - - switch (self._direction) { - case ccui.LoadingBar.TYPE_LEFT: - barRenderer.setAnchorPoint(0.0,0.5); - if (!self._scale9Enabled) - barRenderer/*.getSprite()*/.setFlippedX(false); - break; - case ccui.LoadingBar.TYPE_RIGHT: - barRenderer.setAnchorPoint(1.0,0.5); - if (!self._scale9Enabled) - barRenderer/*.getSprite()*/.setFlippedX(true); - break; - } - self._updateChildrenDisplayedRGBA(); - self._barRendererScaleChangedWithSize(); - self._updateContentSizeWithTextureSize(self._barRendererTextureSize); - self._barRendererAdaptDirty = true; + self.loadTexture(texture, texType); }); } diff --git a/extensions/ccui/uiwidgets/UISlider.js b/extensions/ccui/uiwidgets/UISlider.js index c2feccd6b6..292e53dea0 100644 --- a/extensions/ccui/uiwidgets/UISlider.js +++ b/extensions/ccui/uiwidgets/UISlider.js @@ -127,12 +127,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ var self = this; if(!barRenderer.texture || !barRenderer.texture.isLoaded()){ barRenderer.addEventListener("load", function(){ - self._findLayout(); - self._updateChildrenDisplayedRGBA(); - - self._barRendererAdaptDirty = true; - self._progressBarRendererDirty = true; - self._updateContentSizeWithTextureSize(self._barRenderer.getContentSize()); + self.loadBarTexture(fileName, texType); }); } @@ -172,13 +167,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ var self = this; if(!progressBarRenderer.texture || !progressBarRenderer.texture.isLoaded()){ progressBarRenderer.addEventListener("load", function(){ - self._findLayout(); - self._updateChildrenDisplayedRGBA(); - - self._progressBarRenderer.setAnchorPoint(cc.p(0, 0.5)); - var tz = self._progressBarRenderer.getContentSize(); - self._progressBarTextureSize = {width: tz.width, height: tz.height}; - self._progressBarRendererDirty = true; + self.loadProgressBarTexture(fileName, texType); }); } @@ -345,7 +334,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ var self = this; if(!this._slidBallNormalRenderer.texture || !this._slidBallNormalRenderer.texture.isLoaded()){ this._slidBallNormalRenderer.addEventListener("load", function(){ - self._updateChildrenDisplayedRGBA(); + self.loadSlidBallTextureNormal(normal, texType); }); } @@ -380,7 +369,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ var self = this; if(!this._slidBallPressedRenderer.texture || !this._slidBallPressedRenderer.texture.isLoaded()){ this._slidBallPressedRenderer.addEventListener("load", function(){ - self._updateChildrenDisplayedRGBA(); + self.loadSlidBallTexturePressed(pressed, texType); }); } @@ -415,7 +404,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ var self = this; if(!this._slidBallDisabledRenderer.texture || !this._slidBallDisabledRenderer.texture.isLoaded()){ this._slidBallDisabledRenderer.addEventListener("load", function(){ - self._updateChildrenDisplayedRGBA(); + self.loadSlidBallTextureDisabled(disabled, texType); }); } diff --git a/extensions/ccui/uiwidgets/UITextBMFont.js b/extensions/ccui/uiwidgets/UITextBMFont.js index 0175981964..e659906ebd 100644 --- a/extensions/ccui/uiwidgets/UITextBMFont.js +++ b/extensions/ccui/uiwidgets/UITextBMFont.js @@ -78,7 +78,7 @@ ccui.LabelBMFont = ccui.TextBMFont = ccui.Widget.extend(/** @lends ccui.TextBMFo var locRenderer = _self._labelBMFontRenderer; if(!locRenderer._textureLoaded){ locRenderer.addEventListener("load", function(){ - _self.updateSizeAndPosition(); + _self.setFntFile(fileName); }); } }, From 8f793826f962f2db9d13542eedf8096f5c5f4fba Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Fri, 16 Jan 2015 14:39:09 +0800 Subject: [PATCH 0163/1345] Fixed a bug of ccui.Widget that its percent position doesn't work --- extensions/ccui/base-classes/UIWidget.js | 44 +++++++++---------- .../ccui/base-classes/UIWidgetRenderCmd.js | 33 ++++++++------ 2 files changed, 41 insertions(+), 36 deletions(-) diff --git a/extensions/ccui/base-classes/UIWidget.js b/extensions/ccui/base-classes/UIWidget.js index ab0fb1dd44..4a6d48d56b 100644 --- a/extensions/ccui/base-classes/UIWidget.js +++ b/extensions/ccui/base-classes/UIWidget.js @@ -793,28 +793,6 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ return ccui.Widget._focusedWidget; }, - /** - * 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 - */ - 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; - } - } - }, - /** *

* When a widget lose/get focus, this method will be called. Be Caution when you provide your own version,
@@ -1920,6 +1898,28 @@ ccui.Widget.create = function () { 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 diff --git a/extensions/ccui/base-classes/UIWidgetRenderCmd.js b/extensions/ccui/base-classes/UIWidgetRenderCmd.js index 7e9c18ba8f..3faca0b751 100644 --- a/extensions/ccui/base-classes/UIWidgetRenderCmd.js +++ b/extensions/ccui/base-classes/UIWidgetRenderCmd.js @@ -40,22 +40,23 @@ if (cc._renderType === cc._RENDER_TYPE_CANVAS) { } }; - proto.transform = function(parentCmd, recursive){ + proto.transform = function (parentCmd, recursive) { var node = this._node; if (node._visible) { node._adaptRenderers(); - - var widgetParent = node.getWidgetParent(); - if (widgetParent) { - var parentSize = widgetParent.getSize(); - node._position.x = parentSize.width * node._positionPercent.x; - node._position.y = parentSize.height * node._positionPercent.y; + 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 { @@ -81,11 +82,15 @@ if (cc._renderType === cc._RENDER_TYPE_CANVAS) { if (node._visible) { node._adaptRenderers(); - var widgetParent = node.getWidgetParent(); - if (widgetParent) { - var parentSize = widgetParent.getSize(); - node._position.x = parentSize.width * node._positionPercent.x; - node._position.y = parentSize.height * node._positionPercent.y; + 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); } From c652b3e63b004e3571fd5a980d230f9788108d58 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 16 Jan 2015 16:00:25 +0800 Subject: [PATCH 0164/1345] Improve Cocos Studio Parser --- .../cocostudio/loader/parsers/action-2.x.js | 4 ++-- .../cocostudio/loader/parsers/scene-1.x.js | 4 ++-- .../loader/parsers/timelineParser-1.x.js | 4 ++-- .../loader/parsers/timelineParser-2.x.js | 18 +++++++++--------- 4 files changed, 15 insertions(+), 15 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/action-2.x.js b/extensions/cocostudio/loader/parsers/action-2.x.js index 41b52895b5..07c907192d 100644 --- a/extensions/cocostudio/loader/parsers/action-2.x.js +++ b/extensions/cocostudio/loader/parsers/action-2.x.js @@ -57,7 +57,7 @@ }); cache[file] = action; - + cache[file].retain(); return action.clone(); } @@ -226,4 +226,4 @@ load.registerParser("action", "2.*", parser); -})(ccs._load, ccs._parser); \ No newline at end of file +})(ccs._load, ccs._parser); diff --git a/extensions/cocostudio/loader/parsers/scene-1.x.js b/extensions/cocostudio/loader/parsers/scene-1.x.js index 616350c613..aad9b5a73b 100644 --- a/extensions/cocostudio/loader/parsers/scene-1.x.js +++ b/extensions/cocostudio/loader/parsers/scene-1.x.js @@ -217,7 +217,7 @@ cc.spriteFrameCache.addSpriteFrames(resourcePath + plist); }else{ if(!loadedPlist[resourcePath + plist]) - cc.log("%s need to be pre loaded", resourcePath + plist); + cc.log("%s need to be preloaded", resourcePath + plist); } } if(type !== 0) @@ -259,4 +259,4 @@ load.registerParser("scene", "*", parser); -})(ccs._load, ccs._parser); \ No newline at end of file +})(ccs._load, ccs._parser); diff --git a/extensions/cocostudio/loader/parsers/timelineParser-1.x.js b/extensions/cocostudio/loader/parsers/timelineParser-1.x.js index b157859934..e5f6b8ef8e 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-1.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-1.x.js @@ -38,7 +38,7 @@ 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 pre loaded", plist); + cc.log("%s need to be preloaded", plist); else loadedPlist[plist] = true; cc.spriteFrameCache.addSpriteFrames( @@ -288,4 +288,4 @@ load.registerParser("timeline", "*", parser); -})(ccs._load, ccs._parser); \ No newline at end of file +})(ccs._load, ccs._parser); diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 434114428d..4164b7f852 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -194,10 +194,10 @@ self = this; loadTexture(json["FileData"], resourcePath, function(path, type){ if(!cc.loader.getRes(path)) - cc.log("%s need to be pre loaded", path); + cc.log("%s need to be preloaded", path); node = new cc.ParticleSystem(path); self.generalAttributes(node, json); - node.setDrawMode(cc.ParticleSystem.TEXTURE_MODE); + !cc.sys.isNative && node.setDrawMode(cc.ParticleSystem.TEXTURE_MODE); }); return node; }; @@ -767,7 +767,7 @@ textureList.forEach(function(item){ loadTexture(json[item.name], resourcePath, function(path, type){ if(type == 0 && !loader.getRes(path)) - cc.log("%s need to be pre loaded", path); + cc.log("%s need to be preloaded", path); item.handle.call(widget, path, type); }); }); @@ -954,7 +954,7 @@ loadTexture(json["LabelAtlasFileImage_CNB"], resourcePath, function(path, type){ if(!cc.loader.getRes(path)) - cc.log("%s need to be pre loaded", path); + cc.log("%s need to be preloaded", path); if(type == 0){ widget.setProperty(stringValue, path, itemWidth, itemHeight, startCharMap); } @@ -1104,7 +1104,7 @@ if(cc.loader.getRes(file)) return ccs._load(file); else - cc.log("%s need to be pre loaded", file); + cc.log("%s need to be preloaded", file); } }; @@ -1136,13 +1136,13 @@ var plists, pngs; var armJson = cc.loader.getRes(path); if(!armJson) - cc.log("%s need to be pre loaded", path); + 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.addSpriteFrame(plist, pngs[index]); + cc.spriteFrameCache.addSpriteFrames(plist, pngs[index]); }); } ccs.armatureDataManager.addArmatureFileInfo(path); @@ -1170,7 +1170,7 @@ cc.spriteFrameCache.addSpriteFrames(resourcePath + plist); }else{ if(!loadedPlist[resourcePath + plist]) - cc.log("%s need to be pre loaded", resourcePath + plist); + cc.log("%s need to be preloaded", resourcePath + plist); } } if(type !== 0) @@ -1231,4 +1231,4 @@ load.registerParser("timeline", "2.*", parser); -})(ccs._load, ccs._parser); \ No newline at end of file +})(ccs._load, ccs._parser); From a80dab2d6caa8d302b47e7ca0f58050e200c5419 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 16 Jan 2015 16:18:40 +0800 Subject: [PATCH 0165/1345] Fix private property usage --- cocos2d/core/sprites/CCSpriteFrameCache.js | 1 - extensions/cocostudio/loader/parsers/action-2.x.js | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/cocos2d/core/sprites/CCSpriteFrameCache.js b/cocos2d/core/sprites/CCSpriteFrameCache.js index b65f265cda..79321e5327 100644 --- a/cocos2d/core/sprites/CCSpriteFrameCache.js +++ b/cocos2d/core/sprites/CCSpriteFrameCache.js @@ -330,7 +330,6 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{ if(!frame) delete self._spriteFramesAliases[name]; } } - if (!frame) cc.log(cc._LogInfos.spriteFrameCache_getSpriteFrame, name); return frame; }, diff --git a/extensions/cocostudio/loader/parsers/action-2.x.js b/extensions/cocostudio/loader/parsers/action-2.x.js index 07c907192d..25953fde53 100644 --- a/extensions/cocostudio/loader/parsers/action-2.x.js +++ b/extensions/cocostudio/loader/parsers/action-2.x.js @@ -176,7 +176,7 @@ var texture = options["TextureFile"]; if(texture != null) { var path = texture["Path"]; - var spriteFrame = cc.spriteFrameCache._spriteFrames[path]; + var spriteFrame = cc.spriteFrameCache.getSpriteFrames(path); if(spriteFrame == null){ path = resourcePath + path; } From 6e29c22a618e8050b7d0a0ae875e8102925d5d31 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 16 Jan 2015 16:23:17 +0800 Subject: [PATCH 0166/1345] Fixed UISlider bug --- extensions/ccui/uiwidgets/UISlider.js | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/extensions/ccui/uiwidgets/UISlider.js b/extensions/ccui/uiwidgets/UISlider.js index 292e53dea0..3d62508907 100644 --- a/extensions/ccui/uiwidgets/UISlider.js +++ b/extensions/ccui/uiwidgets/UISlider.js @@ -61,6 +61,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ _barRendererAdaptDirty: true, _progressBarRendererDirty: true, _unifySize: false, + _zoomScale: 0.1, _sliderBallNormalTextureScaleX: 1, _sliderBallNormalTextureScaleY: 1, @@ -72,11 +73,16 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ * // example * var uiSlider = new ccui.Slider(); */ - ctor: function () { + ctor: function (barTextureName, normalBallTextureName, resType) { this._progressBarTextureSize = cc.size(0, 0); this._capInsetsBarRenderer = cc.rect(0, 0, 0, 0); this._capInsetsProgressBarRenderer = cc.rect(0, 0, 0, 0); ccui.Widget.prototype.ctor.call(this); + + resType = resType == null ? 0 : resType; + this.setTouchEnabled(true); + barTextureName && this.loadBarTexture(barTextureName, resType); + normalBallTextureName && this.loadSlidBallTextures(normalBallTextureName, resType); }, /** @@ -712,8 +718,8 @@ _p = null; * @deprecated since v3.0, please use new ccui.Slider() instead. * @return {ccui.Slider} */ -ccui.Slider.create = function () { - return new ccui.Slider(); +ccui.Slider.create = function (barTextureName, normalBallTextureName, resType) { + return new ccui.Slider(barTextureName, normalBallTextureName, resType); }; // Constant From 8ac57078a7d400120c39702a70af2aecbcb2a31f Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 16 Jan 2015 16:46:19 +0800 Subject: [PATCH 0167/1345] Fix typo --- extensions/cocostudio/loader/parsers/action-2.x.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/cocostudio/loader/parsers/action-2.x.js b/extensions/cocostudio/loader/parsers/action-2.x.js index 25953fde53..f57709f8ad 100644 --- a/extensions/cocostudio/loader/parsers/action-2.x.js +++ b/extensions/cocostudio/loader/parsers/action-2.x.js @@ -176,7 +176,7 @@ var texture = options["TextureFile"]; if(texture != null) { var path = texture["Path"]; - var spriteFrame = cc.spriteFrameCache.getSpriteFrames(path); + var spriteFrame = cc.spriteFrameCache.getSpriteFrame(path); if(spriteFrame == null){ path = resourcePath + path; } From ebb1b77d8f62a869f3ac8f8bc50b1fbbf2f95529 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 16 Jan 2015 17:32:27 +0800 Subject: [PATCH 0168/1345] add _findLayout function --- extensions/ccui/uiwidgets/UIButton.js | 3 +++ extensions/ccui/uiwidgets/UICheckBox.js | 5 +++++ extensions/ccui/uiwidgets/UIImageView.js | 2 ++ extensions/ccui/uiwidgets/UILoadingBar.js | 1 + extensions/ccui/uiwidgets/UISlider.js | 5 +++++ 5 files changed, 16 insertions(+) diff --git a/extensions/ccui/uiwidgets/UIButton.js b/extensions/ccui/uiwidgets/UIButton.js index 2280b6eccd..d762e528c2 100644 --- a/extensions/ccui/uiwidgets/UIButton.js +++ b/extensions/ccui/uiwidgets/UIButton.js @@ -284,6 +284,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ this._normalTextureLoaded = true; this._normalTextureAdaptDirty = true; + this._findLayout(); }, /** @@ -327,6 +328,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ this._pressedTextureLoaded = true; this._pressedTextureAdaptDirty = true; + this._findLayout(); }, /** @@ -371,6 +373,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ this._disabledTextureLoaded = true; this._disabledTextureAdaptDirty = true; + this._findLayout(); }, /** diff --git a/extensions/ccui/uiwidgets/UICheckBox.js b/extensions/ccui/uiwidgets/UICheckBox.js index 9b5364ab7e..a1383533a9 100644 --- a/extensions/ccui/uiwidgets/UICheckBox.js +++ b/extensions/ccui/uiwidgets/UICheckBox.js @@ -175,6 +175,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ this._updateContentSizeWithTextureSize(this._backGroundBoxRenderer.getContentSize()); this._backGroundBoxRendererAdaptDirty = true; + this._findLayout(); }, /** @@ -214,6 +215,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ this._updateChildrenDisplayedRGBA(); this._backGroundSelectedBoxRendererAdaptDirty = true; + this._findLayout(); }, /** @@ -251,6 +253,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ this._updateChildrenDisplayedRGBA(); this._frontCrossRendererAdaptDirty = true; + this._findLayout(); }, /** @@ -288,6 +291,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ this._updateChildrenDisplayedRGBA(); this._backGroundBoxDisabledRendererAdaptDirty = true; + this._findLayout(); }, /** @@ -325,6 +329,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ this._updateChildrenDisplayedRGBA(); this._frontCrossDisabledRendererAdaptDirty = true; + this._findLayout(); }, _onPressStateChangedToNormal: function () { diff --git a/extensions/ccui/uiwidgets/UIImageView.js b/extensions/ccui/uiwidgets/UIImageView.js index 0aa6e71b28..2cb7325868 100644 --- a/extensions/ccui/uiwidgets/UIImageView.js +++ b/extensions/ccui/uiwidgets/UIImageView.js @@ -135,6 +135,8 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{ self._updateContentSizeWithTextureSize(self._imageTextureSize); self._imageRendererAdaptDirty = true; + self._findLayout(); + }, /** diff --git a/extensions/ccui/uiwidgets/UILoadingBar.js b/extensions/ccui/uiwidgets/UILoadingBar.js index 2d6467a9c5..86bb631dbb 100644 --- a/extensions/ccui/uiwidgets/UILoadingBar.js +++ b/extensions/ccui/uiwidgets/UILoadingBar.js @@ -162,6 +162,7 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{ this._barRendererScaleChangedWithSize(); this._updateContentSizeWithTextureSize(this._barRendererTextureSize); this._barRendererAdaptDirty = true; + this._findLayout(); }, /** diff --git a/extensions/ccui/uiwidgets/UISlider.js b/extensions/ccui/uiwidgets/UISlider.js index 3d62508907..b629b87196 100644 --- a/extensions/ccui/uiwidgets/UISlider.js +++ b/extensions/ccui/uiwidgets/UISlider.js @@ -154,6 +154,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ this._barRendererAdaptDirty = true; this._progressBarRendererDirty = true; this._updateContentSizeWithTextureSize(this._barRenderer.getContentSize()); + this._findLayout(); }, /** @@ -195,6 +196,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ var tz = this._progressBarRenderer.getContentSize(); this._progressBarTextureSize = {width: tz.width, height: tz.height}; this._progressBarRendererDirty = true; + this._findLayout(); }, /** @@ -357,6 +359,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ break; } this._updateChildrenDisplayedRGBA(); + this._findLayout(); }, /** @@ -392,6 +395,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ break; } this._updateChildrenDisplayedRGBA(); + this._findLayout(); }, /** @@ -427,6 +431,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ break; } this._updateChildrenDisplayedRGBA(); + this._findLayout(); }, /** From e94c40d32b3bfd4f3ac66d462db28477d7a4fe6a Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 19 Jan 2015 10:20:35 +0800 Subject: [PATCH 0169/1345] setContentSize doesn't changed texture for UIImageView --- extensions/ccui/layouts/UILayoutComponent.js | 2 +- extensions/ccui/uiwidgets/UIImageView.js | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/extensions/ccui/layouts/UILayoutComponent.js b/extensions/ccui/layouts/UILayoutComponent.js index 73fbdff28b..19f3c2158a 100644 --- a/extensions/ccui/layouts/UILayoutComponent.js +++ b/extensions/ccui/layouts/UILayoutComponent.js @@ -207,7 +207,7 @@ ccui.LayoutComponent = cc.Component.extend({ }, setHorizontalEdge: function (hEdge) { this._horizontalEdge = hEdge; - if (this._horizontalEdge != cc.LayoutComponent.horizontalEdge.NONE) + if (this._horizontalEdge != ccui.LayoutComponent.horizontalEdge.NONE) this._usingPositionPercentX = false; var parent = this._getOwnerParent(); diff --git a/extensions/ccui/uiwidgets/UIImageView.js b/extensions/ccui/uiwidgets/UIImageView.js index 2cb7325868..d99cb41dcd 100644 --- a/extensions/ccui/uiwidgets/UIImageView.js +++ b/extensions/ccui/uiwidgets/UIImageView.js @@ -303,7 +303,10 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{ if(height) contentSize = cc.size(contentSize, height); ccui.Widget.prototype.setContentSize.call(this, contentSize); - this._imageRenderer.setContentSize(contentSize); + var iContentSize = this._imageRenderer.getContentSize(); + this._imageRenderer.setScaleX(contentSize.width / iContentSize.width); + this._imageRenderer.setScaleY(contentSize.height / iContentSize.height); + } }); From 047b0d29fcd22143af9a9fa8473aef41c5f9697f Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 19 Jan 2015 13:59:40 +0800 Subject: [PATCH 0170/1345] setContentSize doesn't changed texture for UIImageView --- extensions/ccui/uiwidgets/UIImageView.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/ccui/uiwidgets/UIImageView.js b/extensions/ccui/uiwidgets/UIImageView.js index d99cb41dcd..5997c70d24 100644 --- a/extensions/ccui/uiwidgets/UIImageView.js +++ b/extensions/ccui/uiwidgets/UIImageView.js @@ -300,7 +300,7 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{ * @override */ setContentSize: function(contentSize, height){ - if(height) + if(height != null) contentSize = cc.size(contentSize, height); ccui.Widget.prototype.setContentSize.call(this, contentSize); var iContentSize = this._imageRenderer.getContentSize(); From 6e2b6e4266acee888940fa5f94bbd4f3148dd05b Mon Sep 17 00:00:00 2001 From: jianglong0156 Date: Mon, 19 Jan 2015 14:15:54 +0800 Subject: [PATCH 0171/1345] issue #1260:arranging the key code make it same with jsb key code --- cocos2d/core/platform/CCCommon.js | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/platform/CCCommon.js b/cocos2d/core/platform/CCCommon.js index a15cca1ede..9eeac574b5 100644 --- a/cocos2d/core/platform/CCCommon.js +++ b/cocos2d/core/platform/CCCommon.js @@ -52,15 +52,25 @@ cc.associateWithNative = function (jsObj, superclass) { }, this); */ cc.KEY = { + none:0, + + // android + back:6, + menu:18, + backspace:8, tab:9, + enter:13, + shift:16, //should use shiftkey instead ctrl:17, //should use ctrlkey alt:18, //should use altkey pause:19, capslock:20, + escape:27, + space:32, pageup:33, pagedown:34, end:35, @@ -69,6 +79,8 @@ cc.KEY = { up:38, right:39, down:40, + select:41, + insert:45, Delete:46, 0:48, @@ -107,6 +119,7 @@ cc.KEY = { x:88, y:89, z:90, + num0:96, num1:97, num2:98, @@ -134,8 +147,10 @@ cc.KEY = { f10:121, f11:122, f12:123, + numlock:144, scrolllock:145, + semicolon:186, ',':186, equal:187, @@ -149,11 +164,10 @@ cc.KEY = { grave:192, '[':219, openbracket:219, + backslash:220, ']':221, closebracket:221, - backslash:220, - quote:222, - space:32 + quote:222 }; /** From 275761f003f6d08aff4d7b2031de64e630e36b38 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 19 Jan 2015 14:22:54 +0800 Subject: [PATCH 0172/1345] setContentSize doesn't changed texture for UIImageView --- extensions/ccui/uiwidgets/UIImageView.js | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/extensions/ccui/uiwidgets/UIImageView.js b/extensions/ccui/uiwidgets/UIImageView.js index 5997c70d24..b8b8ad9029 100644 --- a/extensions/ccui/uiwidgets/UIImageView.js +++ b/extensions/ccui/uiwidgets/UIImageView.js @@ -303,9 +303,11 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{ if(height != null) contentSize = cc.size(contentSize, height); ccui.Widget.prototype.setContentSize.call(this, contentSize); - var iContentSize = this._imageRenderer.getContentSize(); - this._imageRenderer.setScaleX(contentSize.width / iContentSize.width); - this._imageRenderer.setScaleY(contentSize.height / iContentSize.height); + if(!this._scale9Enabled){ + var iContentSize = this._imageRenderer.getContentSize(); + this._imageRenderer.setScaleX(contentSize.width / iContentSize.width); + this._imageRenderer.setScaleY(contentSize.height / iContentSize.height); + } } From 264fbbbce296c416017db1d021b66bcdab979e02 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Mon, 19 Jan 2015 14:23:37 +0800 Subject: [PATCH 0173/1345] Fixed some mistakes of ccui.Button --- cocos2d/core/base-nodes/CCNode.js | 4 ++ .../UIScale9SpriteCanvasRenderCmd.js | 13 ++--- extensions/ccui/uiwidgets/UIButton.js | 48 +++++++++++-------- extensions/ccui/uiwidgets/UISlider.js | 1 + 4 files changed, 40 insertions(+), 26 deletions(-) diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index ec7988b01d..91b49f0d40 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -649,9 +649,13 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ setPosition: function (newPosOrxValue, yValue) { var locPosition = this._position; if (yValue === undefined) { + if(locPosition.x === newPosOrxValue.x && locPosition.y === newPosOrxValue.y) + return; locPosition.x = newPosOrxValue.x; locPosition.y = newPosOrxValue.y; } else { + if(locPosition.x === newPosOrxValue.x && locPosition.y === yValue) + return; locPosition.x = newPosOrxValue; locPosition.y = yValue; } diff --git a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js index b6714b5573..535451aca2 100644 --- a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js +++ b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js @@ -27,6 +27,7 @@ cc.Node.CanvasRenderCmd.call(this, renderable); this._cachedParent = null; this._cacheDirty = false; + this._state = ccui.Scale9Sprite.state.NORMAL; var node = this._node; var locCacheCanvas = this._cacheCanvas = cc.newElement('canvas'); @@ -115,9 +116,14 @@ node._scale9Image.visit(); //draw to cache canvas + var selTexture = node._scale9Image.getTexture(); + if(selTexture && this._state === ccui.Scale9Sprite.state.NORMAL) + selTexture._switchToGray(true); locContext.setTransform(1, 0, 0, 1, 0, 0); locContext.clearRect(0, 0, sizeInPixels.width, sizeInPixels.height); cc.renderer._renderingToCacheCanvas(wrapper, node.__instanceId, locScaleFactor, locScaleFactor); + if(selTexture && this._state === ccui.Scale9Sprite.state.NORMAL) + selTexture._switchToGray(false); if(contentSizeChanged) this._cacheSprite.setTextureRect(cc.rect(0,0, size.width, size.height)); @@ -130,12 +136,7 @@ var locScale9Image = this._node._scale9Image; if(!locScale9Image) return; - var selTexture = locScale9Image.getTexture(); - if(state === ccui.Scale9Sprite.state.NORMAL){ - selTexture._switchToGray(false); - } else if( state === ccui.Scale9Sprite.state.GRAY){ - selTexture._switchToGray(true); - } + this._state = state; this._cacheScale9Sprite(); }; })(); \ No newline at end of file diff --git a/extensions/ccui/uiwidgets/UIButton.js b/extensions/ccui/uiwidgets/UIButton.js index 6dba636038..51ead262dd 100644 --- a/extensions/ccui/uiwidgets/UIButton.js +++ b/extensions/ccui/uiwidgets/UIButton.js @@ -103,8 +103,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ this._titleColor = cc.color.WHITE; ccui.Widget.prototype.ctor.call(this); this.setTouchEnabled(true); - - texType !== undefined && this.init(normalImage, selectedImage, disableImage, texType); + this.init(normalImage, selectedImage, disableImage, texType); }, /** @@ -218,7 +217,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ */ getVirtualRendererSize: function(){ if (this._unifySize) - return this.getNormalSize(); + return this._getNormalSize(); if (!this._normalTextureLoaded && this._titleRenderer.getString().length > 0) { return this._titleRenderer.getContentSize(); @@ -287,7 +286,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ if (this._unifySize){ if (this._scale9Enabled){ normalRenderer.setCapInsets(this._capInsetsNormal); - this._updateContentSizeWithTextureSize(this.getNormalSize()); + this._updateContentSizeWithTextureSize(this._getNormalSize()); } }else this._updateContentSizeWithTextureSize(this._normalTextureSize); @@ -302,7 +301,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ * @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType */ loadTexturePressed: function (selected, texType) { - if (!selected) + if (!selected || (this._clickedFileName == selected && this._pressedTexType == texType)) return; texType = texType || ccui.Widget.LOCAL_TEXTURE; this._clickedFileName = selected; @@ -527,7 +526,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ if (this.pressedActionEnabled){ this._buttonNormalRenderer.stopAllActions(); this._buttonClickedRenderer.stopAllActions(); - var zoomAction = cc.scaleTo(0.05, this._normalTextureScaleXInSize, this._normalTextureScaleYInSize); + var zoomAction = cc.scaleTo(ccui.Button.ZOOM_ACTION_TIME_STEP, this._normalTextureScaleXInSize, this._normalTextureScaleYInSize); this._buttonNormalRenderer.runAction(zoomAction); this._buttonClickedRenderer.setScale(this._pressedTextureScaleXInSize, this._pressedTextureScaleYInSize); @@ -569,16 +568,16 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ if (this.pressedActionEnabled) { locNormalRenderer.stopAllActions(); this._buttonClickedRenderer.stopAllActions(); - var zoomAction = cc.scaleTo(0.05, this._pressedTextureScaleXInSize + 0.1,this._pressedTextureScaleYInSize + 0.1); + 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 + 0.1, this._pressedTextureScaleYInSize + 0.1); + locNormalRenderer.setScale(this._pressedTextureScaleXInSize + this._zoomScale, this._pressedTextureScaleYInSize + this._zoomScale); this._titleRenderer.stopAllActions(); if (this._unifySize){ - var zoomTitleAction = cc.scaleTo(0.05, 1 + this._zoomScale, 1 + this._zoomScale); + var zoomTitleAction = cc.scaleTo(ccui.Button.ZOOM_ACTION_TIME_STEP, 1 + this._zoomScale, 1 + this._zoomScale); this._titleRenderer.runAction(zoomTitleAction); - } - else + } else this._titleRenderer.runAction(zoomAction.clone()); } } else { @@ -586,10 +585,10 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ this._buttonClickedRenderer.setVisible(true); this._buttonDisableRenderer.setVisible(false); locNormalRenderer.stopAllActions(); - locNormalRenderer.setScale(this._normalTextureScaleXInSize + 0.1, this._normalTextureScaleYInSize + 0.1); + locNormalRenderer.setScale(this._normalTextureScaleXInSize + this._zoomScale, this._normalTextureScaleYInSize + this._zoomScale); if (this._scale9Enabled) - locNormalRenderer.setColor(cc.color.GRAY); + locNormalRenderer.setState(ccui.Scale9Sprite.state.GRAY); this._titleRenderer.stopAllActions(); if (this._unifySize){ @@ -599,16 +598,14 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ this._titleRenderer.setScaleX(this._normalTextureScaleXInSize + this._zoomScale); this._titleRenderer.setScaleY(this._normalTextureScaleYInSize + this._zoomScale); } - } }, _onPressStateChangedToDisabled: function () { - //if disable resource is null if (!this._disabledTextureLoaded){ if (this._normalTextureLoaded && this._scale9Enabled) - this._buttonNormalRenderer.setState(1/*Scale9Sprite::State::GRAY*/); + this._buttonNormalRenderer.setState(ccui.Scale9Sprite.state.GRAY); }else{ this._buttonNormalRenderer.setVisible(false); this._buttonDisableRenderer.setVisible(true); @@ -624,7 +621,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ if (this._scale9Enabled) ccui.ProtectedNode.setContentSize(this._customSize); else{ - var s = this.getNormalSize(); + var s = this._getNormalSize(); ccui.ProtectedNode.setContentSize(s); } this._onSizeChanged(); @@ -807,7 +804,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ * @param {cc.Color} color */ setTitleColor: function (color) { - this._titleRenderer.setColor(color); + this._titleRenderer.setFontFillColor(color); }, /** @@ -815,7 +812,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ * @returns {cc.Color} */ getTitleColor: function () { - return this._titleRenderer.getColor(); + return this._titleRenderer._getFillStyle(); }, /** @@ -835,10 +832,21 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ 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; }, @@ -911,7 +919,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ this._updateTexturesRGBA(); }, - getNormalSize: function(){ + _getNormalSize: function(){ var titleSize; if (this._titleRenderer != null) titleSize = this._titleRenderer.getContentSize(); diff --git a/extensions/ccui/uiwidgets/UISlider.js b/extensions/ccui/uiwidgets/UISlider.js index c2feccd6b6..e8fe47eef2 100644 --- a/extensions/ccui/uiwidgets/UISlider.js +++ b/extensions/ccui/uiwidgets/UISlider.js @@ -77,6 +77,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ this._capInsetsBarRenderer = cc.rect(0, 0, 0, 0); this._capInsetsProgressBarRenderer = cc.rect(0, 0, 0, 0); ccui.Widget.prototype.ctor.call(this); + this.setTouchEnabled(true); }, /** From bdc82fb8355fc881262e10cbf9930a80ea0b5bcd Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 19 Jan 2015 14:26:04 +0800 Subject: [PATCH 0174/1345] setContentSize doesn't changed texture for UIImageView --- extensions/ccui/uiwidgets/UIImageView.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/extensions/ccui/uiwidgets/UIImageView.js b/extensions/ccui/uiwidgets/UIImageView.js index b8b8ad9029..bfc4c85527 100644 --- a/extensions/ccui/uiwidgets/UIImageView.js +++ b/extensions/ccui/uiwidgets/UIImageView.js @@ -307,6 +307,8 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{ var iContentSize = this._imageRenderer.getContentSize(); this._imageRenderer.setScaleX(contentSize.width / iContentSize.width); this._imageRenderer.setScaleY(contentSize.height / iContentSize.height); + }else{ + this._imageRenderer.setContentSize(contentSize); } } From f624250c07cd4d4d433ecc24981cd3433014f677 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Mon, 19 Jan 2015 16:05:10 +0800 Subject: [PATCH 0175/1345] Fixed a bug of ccui.Widget that its setFocusEnabled doesn't work --- extensions/ccui/base-classes/UIWidget.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/ccui/base-classes/UIWidget.js b/extensions/ccui/base-classes/UIWidget.js index 4a6d48d56b..2554e18bce 100644 --- a/extensions/ccui/base-classes/UIWidget.js +++ b/extensions/ccui/base-classes/UIWidget.js @@ -744,7 +744,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @param {Boolean} enable true represent the widget could accept focus, false represent the widget couldn't accept focus */ setFocusEnabled: function(enable){ - this._focused = enable; + this._focusEnabled = enable; }, /** From b110682c9395744ffe183899edef1965eddf0dcf Mon Sep 17 00:00:00 2001 From: jianglong0156 Date: Mon, 19 Jan 2015 16:35:00 +0800 Subject: [PATCH 0176/1345] issue #1260: fix quote and comma key code error --- cocos2d/core/platform/CCCommon.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/platform/CCCommon.js b/cocos2d/core/platform/CCCommon.js index 9eeac574b5..8fdd7d3d84 100644 --- a/cocos2d/core/platform/CCCommon.js +++ b/cocos2d/core/platform/CCCommon.js @@ -151,11 +151,11 @@ cc.KEY = { numlock:144, scrolllock:145, + ';':186, semicolon:186, - ',':186, equal:187, '=':187, - ';':188, + ',':188, comma:188, dash:189, '.':190, From abc250d7e18b791e82a9e8a0c8c5f3714eece50a Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 19 Jan 2015 16:37:46 +0800 Subject: [PATCH 0177/1345] Parameter adaptation (CheckBox) --- extensions/ccui/uiwidgets/UICheckBox.js | 30 ++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/extensions/ccui/uiwidgets/UICheckBox.js b/extensions/ccui/uiwidgets/UICheckBox.js index a1383533a9..b86ee96ef0 100644 --- a/extensions/ccui/uiwidgets/UICheckBox.js +++ b/extensions/ccui/uiwidgets/UICheckBox.js @@ -81,6 +81,26 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends 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 Date: Mon, 19 Jan 2015 16:51:51 +0800 Subject: [PATCH 0178/1345] Fixed #2604: fixed a bug of cc.ActionInterval that its `_times` is conflict with cc.Blink --- cocos2d/actions/CCAction.js | 2 +- cocos2d/actions/CCActionInterval.js | 16 ++++++++-------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/cocos2d/actions/CCAction.js b/cocos2d/actions/CCAction.js index 3797077f71..1c3163e4bd 100644 --- a/cocos2d/actions/CCAction.js +++ b/cocos2d/actions/CCAction.js @@ -255,7 +255,7 @@ cc.FiniteTimeAction = cc.Action.extend(/** @lends cc.FiniteTimeAction# */{ * @return {Number} */ getDuration:function () { - return this._duration * (this._times || 1); + return this._duration * (this._timesForRepeat || 1); }, /** diff --git a/cocos2d/actions/CCActionInterval.js b/cocos2d/actions/CCActionInterval.js index c7e8ed2a19..fe0d0bc4c1 100644 --- a/cocos2d/actions/CCActionInterval.js +++ b/cocos2d/actions/CCActionInterval.js @@ -47,7 +47,7 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{ _elapsed:0, _firstTick:false, _easeList: null, - _times:1, + _timesForRepeat:1, _repeatForever: false, _repeatMethod: false,//Compatible with repeat class, Discard after can be deleted _speed: 1, @@ -59,7 +59,7 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{ */ ctor:function (d) { this._speed = 1; - this._times = 1; + this._timesForRepeat = 1; this._repeatForever = false; this.MAX_VALUE = 2; this._repeatMethod = false;//Compatible with repeat class, Discard after can be deleted @@ -107,7 +107,7 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{ _cloneDecoration: function(action){ action._repeatForever = this._repeatForever; action._speed = this._speed; - action._times = this._times; + action._timesForRepeat = this._timesForRepeat; action._easeList = this._easeList; action._speedMethod = this._speedMethod; action._repeatMethod = this._repeatMethod; @@ -180,9 +180,9 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{ this.update(t > 0 ? t : 0); //Compatible with repeat class, Discard after can be deleted (this._repeatMethod) - if(this._repeatMethod && this._times > 1 && this.isDone()){ + if(this._repeatMethod && this._timesForRepeat > 1 && this.isDone()){ if(!this._repeatForever){ - this._times--; + this._timesForRepeat--; } //var diff = locInnerAction.getElapsed() - locInnerAction._duration; this.startWithTarget(this.target); @@ -286,7 +286,7 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{ return this; } this._repeatMethod = true;//Compatible with repeat class, Discard after can be deleted - this._times *= times; + this._timesForRepeat *= times; return this; }, @@ -297,7 +297,7 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{ */ repeatForever: function(){ this._repeatMethod = true;//Compatible with repeat class, Discard after can be deleted - this._times = this.MAX_VALUE; + this._timesForRepeat = this.MAX_VALUE; this._repeatForever = true; return this; } @@ -466,7 +466,7 @@ cc.Sequence = cc.ActionInterval.extend(/** @lends cc.Sequence# */{ if (locLast !== found) actionFound.startWithTarget(this.target); - new_t = new_t * actionFound._times; + new_t = new_t * actionFound._timesForRepeat; actionFound.update(new_t > 1 ? new_t % 1 : new_t); this._last = found; }, From 2ed0a73bacf82cc3fb11e9553708e288b9ee9604 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 20 Jan 2015 09:42:56 +0800 Subject: [PATCH 0179/1345] Modifying the texture loaded condition judgment --- .../ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js | 4 ++-- extensions/ccui/uiwidgets/UIButton.js | 6 +++--- extensions/ccui/uiwidgets/UICheckBox.js | 10 +++++----- extensions/ccui/uiwidgets/UIImageView.js | 2 +- extensions/ccui/uiwidgets/UILoadingBar.js | 2 +- extensions/ccui/uiwidgets/UISlider.js | 10 +++++----- 6 files changed, 17 insertions(+), 17 deletions(-) diff --git a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js index 535451aca2..7c5abde255 100644 --- a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js +++ b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js @@ -117,12 +117,12 @@ //draw to cache canvas var selTexture = node._scale9Image.getTexture(); - if(selTexture && this._state === ccui.Scale9Sprite.state.NORMAL) + if(selTexture && this._state === ccui.Scale9Sprite.state.GRAY) selTexture._switchToGray(true); locContext.setTransform(1, 0, 0, 1, 0, 0); locContext.clearRect(0, 0, sizeInPixels.width, sizeInPixels.height); cc.renderer._renderingToCacheCanvas(wrapper, node.__instanceId, locScaleFactor, locScaleFactor); - if(selTexture && this._state === ccui.Scale9Sprite.state.NORMAL) + if(selTexture && this._state === ccui.Scale9Sprite.state.GRAY) selTexture._switchToGray(false); if(contentSizeChanged) diff --git a/extensions/ccui/uiwidgets/UIButton.js b/extensions/ccui/uiwidgets/UIButton.js index f82996171e..4d4d0e2171 100644 --- a/extensions/ccui/uiwidgets/UIButton.js +++ b/extensions/ccui/uiwidgets/UIButton.js @@ -251,7 +251,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ this._normalTexType = texType; var self = this; - if(!this._buttonNormalRenderer.texture || !this._buttonNormalRenderer.texture.isLoaded()){ + if(!this._textureLoaded){ this._buttonNormalRenderer.addEventListener("load", function(){ self.loadTextureNormal(normal, texType); }); @@ -299,7 +299,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ this._pressedTexType = texType; var self = this; - if(!this._buttonClickedRenderer.texture || !this._buttonClickedRenderer.texture.isLoaded()){ + if(!this._textureLoaded){ this._buttonClickedRenderer.addEventListener("load", function(){ self.loadTexturePressed(selected, texType); }); @@ -344,7 +344,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ this._disabledTexType = texType; var self = this; - if(!this._buttonDisableRenderer.texture || !this._buttonDisableRenderer.texture.isLoaded()){ + if(!this._textureLoaded){ this._buttonDisableRenderer.addEventListener("load", function() { self.loadTextureDisabled(disabled, texType); }); diff --git a/extensions/ccui/uiwidgets/UICheckBox.js b/extensions/ccui/uiwidgets/UICheckBox.js index b86ee96ef0..e282fac36d 100644 --- a/extensions/ccui/uiwidgets/UICheckBox.js +++ b/extensions/ccui/uiwidgets/UICheckBox.js @@ -172,7 +172,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ var bgBoxRenderer = this._backGroundBoxRenderer; var self = this; - if(!bgBoxRenderer.texture || !bgBoxRenderer.texture.isLoaded()){ + if(!bgBoxRenderer._textureLoaded){ bgBoxRenderer.addEventListener("load", function(){ self.loadTextureBackGround(backGround, texType); }); @@ -212,7 +212,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ this._backGroundSelectedTexType = texType; var self = this; - if(!this._backGroundSelectedBoxRenderer.texture || !this._backGroundSelectedBoxRenderer.texture.isLoaded()){ + if(!this._backGroundSelectedBoxRenderer._textureLoaded){ this._backGroundSelectedBoxRenderer.addEventListener("load", function(){ self.loadTextureBackGroundSelected(backGroundSelected, texType); }); @@ -251,7 +251,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ this._frontCrossTexType = texType; var self = this; - if(!this._frontCrossRenderer.texture || !this._frontCrossRenderer.texture.isLoaded()){ + if(!this._frontCrossRenderer._textureLoaded){ this._frontCrossRenderer.addEventListener("load", function(){ self.loadTextureFrontCross(cross, texType); }); @@ -289,7 +289,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ this._backGroundDisabledTexType = texType; var self = this; - if(!this._backGroundBoxDisabledRenderer.texture || !this._backGroundBoxDisabledRenderer.texture.isLoaded()){ + if(!this._backGroundBoxDisabledRenderer._textureLoaded){ this._backGroundBoxDisabledRenderer.addEventListener("load", function(){ self.loadTextureBackGroundDisabled(backGroundDisabled, texType); }); @@ -327,7 +327,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ this._frontCrossDisabledTexType = texType; var self = this; - if(!this._frontCrossDisabledRenderer.texture || !this._frontCrossDisabledRenderer.texture.isLoaded()){ + if(!this._frontCrossDisabledRenderer._textureLoaded){ this._frontCrossDisabledRenderer.addEventListener("load", function(){ self.loadTextureFrontCrossDisabled(frontCrossDisabled, texType); }); diff --git a/extensions/ccui/uiwidgets/UIImageView.js b/extensions/ccui/uiwidgets/UIImageView.js index bfc4c85527..9d33c6c678 100644 --- a/extensions/ccui/uiwidgets/UIImageView.js +++ b/extensions/ccui/uiwidgets/UIImageView.js @@ -100,7 +100,7 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{ this._imageTexType = texType; var imageRenderer = self._imageRenderer; - if(!imageRenderer.texture || !imageRenderer.texture.isLoaded()){ + if(!imageRenderer._textureLoaded){ imageRenderer.addEventListener("load", function(){ self.loadTexture(fileName, texType); }); diff --git a/extensions/ccui/uiwidgets/UILoadingBar.js b/extensions/ccui/uiwidgets/UILoadingBar.js index 86bb631dbb..68f4316c1f 100644 --- a/extensions/ccui/uiwidgets/UILoadingBar.js +++ b/extensions/ccui/uiwidgets/UILoadingBar.js @@ -122,7 +122,7 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{ var barRenderer = this._barRenderer; var self = this; - if(!barRenderer.texture || !barRenderer.texture.isLoaded()){ + if(!barRenderer._textureLoaded){ barRenderer.addEventListener("load", function(){ self.loadTexture(texture, texType); }); diff --git a/extensions/ccui/uiwidgets/UISlider.js b/extensions/ccui/uiwidgets/UISlider.js index b629b87196..7c3b4f5f13 100644 --- a/extensions/ccui/uiwidgets/UISlider.js +++ b/extensions/ccui/uiwidgets/UISlider.js @@ -131,7 +131,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ var barRenderer = this._barRenderer; var self = this; - if(!barRenderer.texture || !barRenderer.texture.isLoaded()){ + if(!barRenderer._textureLoaded){ barRenderer.addEventListener("load", function(){ self.loadBarTexture(fileName, texType); }); @@ -172,7 +172,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ var progressBarRenderer = this._progressBarRenderer; var self = this; - if(!progressBarRenderer.texture || !progressBarRenderer.texture.isLoaded()){ + if(!progressBarRenderer._textureLoaded){ progressBarRenderer.addEventListener("load", function(){ self.loadProgressBarTexture(fileName, texType); }); @@ -340,7 +340,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ this._ballNTexType = texType; var self = this; - if(!this._slidBallNormalRenderer.texture || !this._slidBallNormalRenderer.texture.isLoaded()){ + if(!this._slidBallNormalRenderer._textureLoaded){ this._slidBallNormalRenderer.addEventListener("load", function(){ self.loadSlidBallTextureNormal(normal, texType); }); @@ -376,7 +376,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ this._ballPTexType = texType; var self = this; - if(!this._slidBallPressedRenderer.texture || !this._slidBallPressedRenderer.texture.isLoaded()){ + if(!this._slidBallPressedRenderer._textureLoaded){ this._slidBallPressedRenderer.addEventListener("load", function(){ self.loadSlidBallTexturePressed(pressed, texType); }); @@ -412,7 +412,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ this._ballDTexType = texType; var self = this; - if(!this._slidBallDisabledRenderer.texture || !this._slidBallDisabledRenderer.texture.isLoaded()){ + if(!this._slidBallDisabledRenderer._textureLoaded){ this._slidBallDisabledRenderer.addEventListener("load", function(){ self.loadSlidBallTextureDisabled(disabled, texType); }); From ff751aef86c2a4d50a5e523961fa1fa32d46b71f Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 20 Jan 2015 11:20:17 +0800 Subject: [PATCH 0180/1345] Repair cannot click without pre load of CheckBox --- extensions/ccui/uiwidgets/UIButton.js | 19 ++++---- extensions/ccui/uiwidgets/UICheckBox.js | 63 +++++++++++++------------ 2 files changed, 43 insertions(+), 39 deletions(-) diff --git a/extensions/ccui/uiwidgets/UIButton.js b/extensions/ccui/uiwidgets/UIButton.js index 4d4d0e2171..7f54bdabed 100644 --- a/extensions/ccui/uiwidgets/UIButton.js +++ b/extensions/ccui/uiwidgets/UIButton.js @@ -251,13 +251,12 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ this._normalTexType = texType; var self = this; - if(!this._textureLoaded){ - this._buttonNormalRenderer.addEventListener("load", function(){ + var normalRenderer = this._buttonNormalRenderer; + if(!normalRenderer._textureLoaded){ + normalRenderer.addEventListener("load", function(){ self.loadTextureNormal(normal, texType); }); } - - var normalRenderer = this._buttonNormalRenderer; switch (this._normalTexType){ case ccui.Widget.LOCAL_TEXTURE: //SetTexture cannot load resource @@ -299,13 +298,13 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ this._pressedTexType = texType; var self = this; - if(!this._textureLoaded){ - this._buttonClickedRenderer.addEventListener("load", function(){ + var clickedRenderer = this._buttonClickedRenderer; + if(!clickedRenderer._textureLoaded){ + clickedRenderer.addEventListener("load", function(){ self.loadTexturePressed(selected, texType); }); } - var clickedRenderer = this._buttonClickedRenderer; switch (this._pressedTexType) { case ccui.Widget.LOCAL_TEXTURE: //SetTexture cannot load resource @@ -344,13 +343,13 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ this._disabledTexType = texType; var self = this; - if(!this._textureLoaded){ - this._buttonDisableRenderer.addEventListener("load", function() { + var disabledRenderer = this._buttonDisableRenderer; + if(!disabledRenderer._textureLoaded){ + disabledRenderer.addEventListener("load", function() { self.loadTextureDisabled(disabled, texType); }); } - var disabledRenderer = this._buttonDisableRenderer; switch (this._disabledTexType) { case ccui.Widget.LOCAL_TEXTURE: //SetTexture cannot load resource diff --git a/extensions/ccui/uiwidgets/UICheckBox.js b/extensions/ccui/uiwidgets/UICheckBox.js index e282fac36d..d62fdccf00 100644 --- a/extensions/ccui/uiwidgets/UICheckBox.js +++ b/extensions/ccui/uiwidgets/UICheckBox.js @@ -169,13 +169,15 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ texType = texType || ccui.Widget.LOCAL_TEXTURE; this._backGroundFileName = backGround; this._backGroundTexType = texType; - var bgBoxRenderer = this._backGroundBoxRenderer; - var self = this; + var bgBoxRenderer = this._backGroundBoxRenderer; if(!bgBoxRenderer._textureLoaded){ bgBoxRenderer.addEventListener("load", function(){ - self.loadTextureBackGround(backGround, texType); - }); + this._updateContentSizeWithTextureSize(this._backGroundBoxRenderer.getContentSize()); + this.loadTextureBackGround(backGround, texType); + }, this); + }else{ + this._backGroundBoxRenderer.setContentSize(this._customSize); } switch (this._backGroundTexType) { @@ -211,21 +213,21 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ this._backGroundSelectedFileName = backGroundSelected; this._backGroundSelectedTexType = texType; - var self = this; - if(!this._backGroundSelectedBoxRenderer._textureLoaded){ - this._backGroundSelectedBoxRenderer.addEventListener("load", function(){ - self.loadTextureBackGroundSelected(backGroundSelected, texType); - }); + var backGroundSelectedBoxRenderer = this._backGroundSelectedBoxRenderer; + if(!backGroundSelectedBoxRenderer._textureLoaded){ + backGroundSelectedBoxRenderer.addEventListener("load", function(){ + this.loadTextureBackGroundSelected(backGroundSelected, texType); + }, this); } switch (this._backGroundSelectedTexType) { case ccui.Widget.LOCAL_TEXTURE: //SetTexture cannot load resource - this._backGroundSelectedBoxRenderer.initWithFile(backGroundSelected); + backGroundSelectedBoxRenderer.initWithFile(backGroundSelected); break; case ccui.Widget.PLIST_TEXTURE: //SetTexture cannot load resource - this._backGroundSelectedBoxRenderer.initWithSpriteFrameName(backGroundSelected); + backGroundSelectedBoxRenderer.initWithSpriteFrameName(backGroundSelected); break; default: break; @@ -251,20 +253,21 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ this._frontCrossTexType = texType; var self = this; - if(!this._frontCrossRenderer._textureLoaded){ - this._frontCrossRenderer.addEventListener("load", function(){ - self.loadTextureFrontCross(cross, texType); - }); + var frontCrossRenderer = this._frontCrossRenderer; + if(!frontCrossRenderer._textureLoaded){ + frontCrossRenderer.addEventListener("load", function(){ + this.loadTextureFrontCross(cross, texType); + }, this); } switch (this._frontCrossTexType) { case ccui.Widget.LOCAL_TEXTURE: //SetTexture cannot load resource - this._frontCrossRenderer.initWithFile(cross); + frontCrossRenderer.initWithFile(cross); break; case ccui.Widget.PLIST_TEXTURE: //SetTexture cannot load resource - this._frontCrossRenderer.initWithSpriteFrameName(cross); + frontCrossRenderer.initWithSpriteFrameName(cross); break; default: break; @@ -289,20 +292,21 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ this._backGroundDisabledTexType = texType; var self = this; - if(!this._backGroundBoxDisabledRenderer._textureLoaded){ - this._backGroundBoxDisabledRenderer.addEventListener("load", function(){ - self.loadTextureBackGroundDisabled(backGroundDisabled, texType); - }); + var backGroundBoxDisabledRenderer = this._backGroundBoxDisabledRenderer; + if(!backGroundBoxDisabledRenderer._textureLoaded){ + backGroundBoxDisabledRenderer.addEventListener("load", function(){ + this.loadTextureBackGroundDisabled(backGroundDisabled, texType); + }, this); } switch (this._backGroundDisabledTexType) { case ccui.Widget.LOCAL_TEXTURE: //SetTexture cannot load resource - this._backGroundBoxDisabledRenderer.initWithFile(backGroundDisabled); + backGroundBoxDisabledRenderer.initWithFile(backGroundDisabled); break; case ccui.Widget.PLIST_TEXTURE: //SetTexture cannot load resource - this._backGroundBoxDisabledRenderer.initWithSpriteFrameName(backGroundDisabled); + backGroundBoxDisabledRenderer.initWithSpriteFrameName(backGroundDisabled); break; default: break; @@ -327,20 +331,21 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ this._frontCrossDisabledTexType = texType; var self = this; - if(!this._frontCrossDisabledRenderer._textureLoaded){ - this._frontCrossDisabledRenderer.addEventListener("load", function(){ - self.loadTextureFrontCrossDisabled(frontCrossDisabled, texType); - }); + var frontCrossDisabledRenderer = this._frontCrossDisabledRenderer; + if(!frontCrossDisabledRenderer._textureLoaded){ + frontCrossDisabledRenderer.addEventListener("load", function(){ + this.loadTextureFrontCrossDisabled(frontCrossDisabled, texType); + }, this); } switch (this._frontCrossDisabledTexType) { case ccui.Widget.LOCAL_TEXTURE: //SetTexture cannot load resource - this._frontCrossDisabledRenderer.initWithFile(frontCrossDisabled); + frontCrossDisabledRenderer.initWithFile(frontCrossDisabled); break; case ccui.Widget.PLIST_TEXTURE: //SetTexture cannot load resource - this._frontCrossDisabledRenderer.initWithSpriteFrameName(frontCrossDisabled); + frontCrossDisabledRenderer.initWithSpriteFrameName(frontCrossDisabled); break; default: break; From 9a3395870ade103bf9ae2ecfabc9aeea715dee7b Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 20 Jan 2015 13:57:03 +0800 Subject: [PATCH 0181/1345] update CCScale9Sprite --- .../gui/control-extension/CCScale9Sprite.js | 169 ++++++++++++++++-- .../CCScale9SpriteCanvasRenderCmd.js | 64 +++---- .../CCScale9SpriteWebGLRenderCmd.js | 102 ++++++++--- 3 files changed, 259 insertions(+), 76 deletions(-) diff --git a/extensions/gui/control-extension/CCScale9Sprite.js b/extensions/gui/control-extension/CCScale9Sprite.js index bc486b3b85..1188d28d44 100644 --- a/extensions/gui/control-extension/CCScale9Sprite.js +++ b/extensions/gui/control-extension/CCScale9Sprite.js @@ -68,7 +68,8 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ _originalSize: null, _preferredSize: null, - + _opacity: 0, + _color: null, _capInsets: null, _insetLeft: 0, _insetTop: 0, @@ -80,6 +81,10 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ _textureLoaded:false, _className:"Scale9Sprite", + //v3.3 + _flippedX: false, + _flippedY: false, + /** * return texture is loaded * @returns {boolean} @@ -131,14 +136,32 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ var sizableWidth = size.width - locTopLeftContentSize.width - locTopRight.getContentSize().width; var sizableHeight = size.height - locTopLeftContentSize.height - locBottomRight.getContentSize().height; - var scaleResult = this._renderCmd._computeSpriteScale(sizableWidth, sizableHeight, locCenterContentSize.width, locCenterContentSize.height); + var horizontalScale = sizableWidth / locCenterContentSize.width; + var verticalScale = sizableHeight / locCenterContentSize.height; - locCenter.setScaleX(scaleResult.horizontalScale); - locCenter.setScaleY(scaleResult.verticalScale); + var rescaledWidth = locCenterContentSize.width * horizontalScale; + var rescaledHeight = locCenterContentSize.height * verticalScale; var leftWidth = locBottomLeftContentSize.width; var bottomHeight = locBottomLeftContentSize.height; + if (cc._renderType == cc._RENDER_TYPE_WEBGL) { + //browser is in canvas mode, need to manually control rounding to prevent overlapping pixels + var roundedRescaledWidth = Math.round(rescaledWidth); + if (rescaledWidth != roundedRescaledWidth) { + rescaledWidth = roundedRescaledWidth; + horizontalScale = rescaledWidth / locCenterContentSize.width; + } + var roundedRescaledHeight = Math.round(rescaledHeight); + if (rescaledHeight != roundedRescaledHeight) { + rescaledHeight = roundedRescaledHeight; + verticalScale = rescaledHeight / locCenterContentSize.height; + } + } + + locCenter.setScaleX(horizontalScale); + locCenter.setScaleY(verticalScale); + var locLeft = this._left, locRight = this._right, locTop = this._top, locBottom = this._bottom; var tempAP = cc.p(0, 0); locBottomLeft.setAnchorPoint(tempAP); @@ -153,19 +176,19 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ // Position corners locBottomLeft.setPosition(0, 0); - locBottomRight.setPosition(leftWidth + scaleResult.rescaledWidth, 0); - locTopLeft.setPosition(0, bottomHeight + scaleResult.rescaledHeight); - locTopRight.setPosition(leftWidth + scaleResult.rescaledWidth, bottomHeight + scaleResult.rescaledHeight); + locBottomRight.setPosition(leftWidth + rescaledWidth, 0); + locTopLeft.setPosition(0, bottomHeight + rescaledHeight); + locTopRight.setPosition(leftWidth + rescaledWidth, bottomHeight + rescaledHeight); // Scale and position borders locLeft.setPosition(0, bottomHeight); - locLeft.setScaleY(scaleResult.verticalScale); - locRight.setPosition(leftWidth + scaleResult.rescaledWidth, bottomHeight); - locRight.setScaleY(scaleResult.verticalScale); + locLeft.setScaleY(verticalScale); + locRight.setPosition(leftWidth + rescaledWidth, bottomHeight); + locRight.setScaleY(verticalScale); locBottom.setPosition(leftWidth, 0); - locBottom.setScaleX(scaleResult.horizontalScale); - locTop.setPosition(leftWidth, bottomHeight + scaleResult.rescaledHeight); - locTop.setScaleX(scaleResult.horizontalScale); + locBottom.setScaleX(horizontalScale); + locTop.setPosition(leftWidth, bottomHeight + rescaledHeight); + locTop.setScaleX(horizontalScale); // Position centre locCenter.setPosition(leftWidth, bottomHeight); @@ -203,13 +226,14 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ } }, + getSprite: function () { + return this._scale9Image; + }, + /** Original sprite's size. */ getOriginalSize: function () { return cc.size(this._originalSize); }, - getSprite: function () { - return this._scale9Image; - }, //if the preferredSize component is given as -1, it is ignored getPreferredSize: function () { @@ -600,7 +624,7 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ } // Set the given rect's size as original size - //this._spriteRect = rect; + this._spriteRect = rect; var locSpriteRect = this._spriteRect; locSpriteRect.x = rect.x; locSpriteRect.y = rect.y; @@ -847,7 +871,8 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ } this.setContentSize(rect.width, rect.height); - this._renderCmd.addBatchNodeToChildren(locScale9Image); + if(cc._renderType === cc._RENDER_TYPE_WEBGL) + this.addChild(locScale9Image); if (this._spritesGenerated) { // Restore color and opacity @@ -887,6 +912,111 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ this._insetBottom = 0; }, + //v3.3 + /** + * Sets cc.Scale9Sprite's state + * @since v3.3 + * @param {Number} state + */ + setState: function(state){ + this._renderCmd.setState(state); + }, + + //setScale9Enabled implement late + + /** + * Sets whether the widget should be flipped horizontally or not. + * @since v3.3 + * @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);
+ *

+ * @since v3.3 + * @return {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. + * @since v3.3 + * @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);
+ *

+ * @since v3.3 + * @return {Boolean} true if the widget is flipped vertically, false otherwise. + */ + isFlippedY:function(){ + return this._flippedY; + }, + + 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("Scale9Sprite#scale. ScaleX != ScaleY. Don't know which one to return"); + return this.getScaleX(); + }, + _createRenderCmd: function(){ if(cc._renderType === cc._RENDER_TYPE_CANVAS) return new cc.Scale9Sprite.CanvasRenderCmd(this); @@ -964,3 +1094,6 @@ cc.Scale9Sprite.POSITIONS_BOTTOM = 4; cc.Scale9Sprite.POSITIONS_TOPRIGHT = 5; cc.Scale9Sprite.POSITIONS_TOPLEFT = 6; cc.Scale9Sprite.POSITIONS_BOTTOMRIGHT = 7; + +cc.Scale9Sprite.state = {NORMAL: 0, GRAY: 1}; + diff --git a/extensions/gui/control-extension/CCScale9SpriteCanvasRenderCmd.js b/extensions/gui/control-extension/CCScale9SpriteCanvasRenderCmd.js index ab2963b328..4d91c032d6 100644 --- a/extensions/gui/control-extension/CCScale9SpriteCanvasRenderCmd.js +++ b/extensions/gui/control-extension/CCScale9SpriteCanvasRenderCmd.js @@ -27,6 +27,7 @@ cc.Node.CanvasRenderCmd.call(this, renderable); this._cachedParent = null; this._cacheDirty = false; + this._state = cc.Scale9Sprite.state.NORMAL; var node = this._node; var locCacheCanvas = this._cacheCanvas = cc.newElement('canvas'); @@ -44,21 +45,10 @@ var proto = cc.Scale9Sprite.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); proto.constructor = cc.Scale9Sprite.CanvasRenderCmd; - proto.addBatchNodeToChildren = function(batchNode){ - //needn't add to children on canvas mode. - }; - - proto._computeSpriteScale = function(sizableWidth, sizableHeight, centerWidth, centerHeight){ - var horizontalScale = sizableWidth / centerWidth, verticalScale = sizableHeight / centerHeight; - return {horizontalScale: horizontalScale, verticalScale: verticalScale, - rescaledWidth: centerWidth * horizontalScale, rescaledHeight: centerHeight * verticalScale} - }; - proto.visit = function(parentCmd){ var node = this._node; - if(!node._visible){ + if(!node._visible) return; - } if (node._positionsAreDirty) { node._updatePositions(); @@ -71,6 +61,22 @@ cc.Node.CanvasRenderCmd.prototype.visit.call(this, parentCmd); }; + proto.transform = function(parentCmd){ + var node = this._node; + cc.Node.CanvasRenderCmd.prototype.transform.call(this, parentCmd); + if (node._positionsAreDirty) { + node._updatePositions(); + node._positionsAreDirty = false; + node._scale9Dirty = true; + } + this._cacheScale9Sprite(); + + var children = node._children; + for(var i=0; i Date: Tue, 20 Jan 2015 14:02:59 +0800 Subject: [PATCH 0182/1345] Fixed a bug of ccui.TextField and cc.TextFieldTTF --- cocos2d/text-input/CCTextFieldTTF.js | 5 ++++- extensions/ccui/uiwidgets/UITextField.js | 4 ++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/cocos2d/text-input/CCTextFieldTTF.js b/cocos2d/text-input/CCTextFieldTTF.js index a27bea0d3e..2624093618 100644 --- a/cocos2d/text-input/CCTextFieldTTF.js +++ b/cocos2d/text-input/CCTextFieldTTF.js @@ -181,6 +181,8 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ this.colorSpaceHolder.g = value.g; this.colorSpaceHolder.b = value.b; this.colorSpaceHolder.a = cc.isUndefined(value.a) ? 255 : value.a; + if(!this._inputText.length) + this.setColor(this.colorSpaceHolder); }, /** @@ -192,6 +194,8 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ this._colorText.g = textColor.g; this._colorText.b = textColor.b; this._colorText.a = cc.isUndefined(textColor.a) ? 255 : textColor.a; + if(this._inputText.length) + this.setColor(this._colorText); }, /** @@ -451,7 +455,6 @@ cc.defineGetterSetter(_p, "charCount", _p.getCharCount); _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. diff --git a/extensions/ccui/uiwidgets/UITextField.js b/extensions/ccui/uiwidgets/UITextField.js index 056cc24d79..927585f959 100644 --- a/extensions/ccui/uiwidgets/UITextField.js +++ b/extensions/ccui/uiwidgets/UITextField.js @@ -488,6 +488,10 @@ ccui.TextField = ccui.Widget.extend(/** @lends ccui.TextField# */{ setTimeout(function(){ self._textFieldRenderer.attachWithIME(); }, 0); + }else{ + setTimeout(function(){ + self._textFieldRenderer.detachWithIME(); + }, 0); } return pass; }, From c9ba30b385a62fadedc66bf0861a05e23c5df743 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 20 Jan 2015 15:35:47 +0800 Subject: [PATCH 0183/1345] Fix an issue of RenderCmd's _updateDisplayOpacity function --- cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js index c9bb546c1d..671d259538 100644 --- a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js @@ -157,7 +157,7 @@ cc.Node.RenderCmd.prototype = { var i, len, selChildren, item; if (this._cascadeOpacityEnabledDirty && !node._cascadeOpacityEnabled) { this._displayedOpacity = node._realOpacity; - selChildren = this._children; + selChildren = node._children; for (i = 0, len = selChildren.length; i < len; i++) { item = selChildren[i]; if (item && item._renderCmd) From 6a82ad42947014cc4d02186eb9bdff02540924ee Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 20 Jan 2015 17:14:27 +0800 Subject: [PATCH 0184/1345] Fix release texture issue in canvas mode --- cocos2d/core/textures/CCTexture2D.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index b5c95da37f..6d3f8a3e53 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -247,7 +247,7 @@ if (cc._renderType === cc._RENDER_TYPE_CANVAS) { }, releaseTexture: function () { - //support only in WebGl rendering mode + cc.loader.release(this.url); }, getName: function () { From c5b515c22a660a2f9c0a3a799f3abd5281d13115 Mon Sep 17 00:00:00 2001 From: Daisuke Hashimoto Date: Wed, 21 Jan 2015 13:12:42 +0900 Subject: [PATCH 0185/1345] fix ccs.actionManager bug _actionDic keys are just filename --- extensions/cocostudio/action/CCActionManager.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/extensions/cocostudio/action/CCActionManager.js b/extensions/cocostudio/action/CCActionManager.js index 88d2bbe626..903de51d8c 100644 --- a/extensions/cocostudio/action/CCActionManager.js +++ b/extensions/cocostudio/action/CCActionManager.js @@ -59,7 +59,10 @@ ccs.actionManager = /** @lends ccs.actionManager# */{ * @returns {ccs.ActionObject} */ getActionByName: function (jsonName, actionName) { - var actionList = this._actionDic[jsonName]; + var path = jsonName; + var pos = path.lastIndexOf("/"); + var fileName = path.substr(pos + 1, path.length); + var actionList = this._actionDic[fileName]; if (!actionList) return null; for (var i = 0; i < actionList.length; i++) { From fa17bca4b6733070eb62a4872c3ac9356baa9d67 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 21 Jan 2015 14:00:29 +0800 Subject: [PATCH 0186/1345] Repair some values doesn't update in setTexture --- cocos2d/core/sprites/CCSprite.js | 43 +++++++++++++++++++++----------- 1 file changed, 28 insertions(+), 15 deletions(-) diff --git a/cocos2d/core/sprites/CCSprite.js b/cocos2d/core/sprites/CCSprite.js index ac0733d9c7..c6d5d7a984 100644 --- a/cocos2d/core/sprites/CCSprite.js +++ b/cocos2d/core/sprites/CCSprite.js @@ -924,29 +924,42 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * @param {cc.Texture2D|String} texture */ setTexture: function (texture) { - var _t = this; - if(texture && (cc.isString(texture))){ + if(!texture) + return this._renderCmd._setTexture(null); + + if(cc.isString(texture)){ texture = cc.textureCache.addImage(texture); - _t.setTexture(texture); - //TODO - var size = texture.getContentSize(); - _t.setTextureRect(cc.rect(0,0, size.width, size.height)); - //If image isn't loaded. Listen for the load event. + if(!texture._textureLoaded){ texture.addEventListener("load", function(){ - var size = texture.getContentSize(); - _t.setTextureRect(cc.rect(0,0, size.width, size.height)); - _t._textureLoaded = true; + this._renderCmd._setTexture(texture); + this._changeRectWithTexture(texture.getContentSize()); + this.setColor(this._realColor); + this._textureLoaded = true; }, this); }else{ - _t._textureLoaded = true; + this._renderCmd._setTexture(texture); + this._changeRectWithTexture(texture.getContentSize()); + this.setColor(this._realColor); + this._textureLoaded = true; } - return; + }else{ + // CCSprite: setTexture doesn't work when the sprite is rendered using a CCSpriteSheet + cc.assert(texture instanceof cc.Texture2D, cc._LogInfos.Sprite_setTexture_2); + this._changeRectWithTexture(texture.getContentSize()); + this._renderCmd._setTexture(texture); } - // CCSprite: setTexture doesn't work when the sprite is rendered using a CCSpriteSheet - cc.assert(!texture || texture instanceof cc.Texture2D, cc._LogInfos.Sprite_setTexture_2); + }, - this._renderCmd._setTexture(texture); + _changeRectWithTexture: function(rect){ + if(!rect || (!rect.width && !rect.height)) return; + var textureRect = this.getTextureRect(); + if(textureRect.height || textureRect.width) return; + rect.x = rect.x || 0; + rect.y = rect.y || 0; + rect.width = rect.width || 0; + rect.height = rect.height || 0; + this.setTextureRect(rect); }, _createRenderCmd: function(){ From c089b748e4cb329ead7a5194d45170204715c906 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 21 Jan 2015 14:01:07 +0800 Subject: [PATCH 0187/1345] Allow set the texture to null --- .../core/sprites/CCSpriteCanvasRenderCmd.js | 9 ++++++--- .../core/sprites/CCSpriteWebGLRenderCmd.js | 19 +++++++++++-------- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js index 5828aeab12..05984018fd 100644 --- a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js @@ -58,10 +58,13 @@ proto._setTexture = function (texture) { var node = this._node; if (node._texture != texture) { - if (texture && texture.getHtmlElementObj() instanceof HTMLImageElement) { - this._originalTexture = texture; + if (texture) { + if(texture.getHtmlElementObj() instanceof HTMLImageElement) + this._originalTexture = texture; + node._textureLoaded = texture._textureLoaded; + }else{ + node._textureLoaded = false; } - node._textureLoaded = texture._textureLoaded; node._texture = texture; } }; diff --git a/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js b/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js index 376d227e62..cd53080796 100644 --- a/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js @@ -286,9 +286,17 @@ proto._setTexture = function (texture) { var node = this._node; // If batchnode, then texture id should be the same - if (node._batchNode && node._batchNode.texture != texture) { - cc.log(cc._LogInfos.Sprite_setTexture); - return; + if (node._batchNode) { + if(node._batchNode.texture != texture){ + cc.log(cc._LogInfos.Sprite_setTexture); + return; + } + }else{ + if(node._texture != texture){ + node._textureLoaded = texture ? texture._textureLoaded : false; + node._texture = texture; + this._updateBlendFunc(); + } } if (texture) @@ -296,11 +304,6 @@ else this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_COLOR); - if (!node._batchNode && node._texture != texture) { - node._textureLoaded = texture._textureLoaded; - node._texture = texture; - this._updateBlendFunc(); - } }; proto.updateTransform = function () { //called only at batching. From f027028e9f2d206c6b9cdfcfccfc9e49c466722e Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Wed, 21 Jan 2015 15:34:39 +0800 Subject: [PATCH 0188/1345] Fixed a bug of cc.Sprite that it can't draw without texture on WebGL mode --- cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js b/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js index cd53080796..56ac66f8b2 100644 --- a/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js @@ -415,11 +415,11 @@ }; proto.rendering = function (ctx) { - var node = this._node; - if (!node._textureLoaded || this._displayedOpacity === 0) + var node = this._node, locTexture = node._texture; + if ((locTexture &&!locTexture._textureLoaded) || this._displayedOpacity === 0) return; - var gl = ctx || cc._renderContext, locTexture = node._texture; + var gl = ctx || cc._renderContext ; //cc.assert(!_t._batchNode, "If cc.Sprite is being rendered by cc.SpriteBatchNode, cc.Sprite#draw SHOULD NOT be called"); if (locTexture) { From f800da25061a9afb77fd469bb493a51d25b7d0ef Mon Sep 17 00:00:00 2001 From: jianglong0156 Date: Wed, 21 Jan 2015 17:57:18 +0800 Subject: [PATCH 0189/1345] issue #1260:sync jsb key code --- cocos2d/core/platform/CCCommon.js | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/platform/CCCommon.js b/cocos2d/core/platform/CCCommon.js index 8fdd7d3d84..9edef5f478 100644 --- a/cocos2d/core/platform/CCCommon.js +++ b/cocos2d/core/platform/CCCommon.js @@ -167,7 +167,14 @@ cc.KEY = { backslash:220, ']':221, closebracket:221, - quote:222 + quote:222, + + // gamepad controll + dpadLeft:1000, + dpadRight:1001, + dpadUp:1003, + dpadDown:1004, + dpadCenter:1005 }; /** From d90147c472e739ee2669eed20650d328066bd3c1 Mon Sep 17 00:00:00 2001 From: jianglong0156 Date: Wed, 21 Jan 2015 18:03:30 +0800 Subject: [PATCH 0190/1345] issue #1260:It's samme with cocos2d-x that modify the key code in UIWidget --- extensions/ccui/base-classes/UIWidget.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/extensions/ccui/base-classes/UIWidget.js b/extensions/ccui/base-classes/UIWidget.js index 2554e18bce..d3cea43929 100644 --- a/extensions/ccui/base-classes/UIWidget.js +++ b/extensions/ccui/base-classes/UIWidget.js @@ -46,16 +46,16 @@ ccui._FocusNavigationController = cc.Class.extend({ _onKeyPressed: function(keyCode, event){ if (this._enableFocusNavigation && this._firstFocusedWidget) { - if (keyCode == cc.KEY.down) { + if (keyCode == cc.KEY.dpadDown) { this._firstFocusedWidget = this._firstFocusedWidget.findNextFocusedWidget(ccui.Widget.DOWN, this._firstFocusedWidget); } - if (keyCode == cc.KEY.up){ + if (keyCode == cc.KEY.dpadUp){ this._firstFocusedWidget = this._firstFocusedWidget.findNextFocusedWidget(ccui.Widget.UP, this._firstFocusedWidget); } - if (keyCode == cc.KEY.left) { + if (keyCode == cc.KEY.dpadLeft) { this._firstFocusedWidget = this._firstFocusedWidget.findNextFocusedWidget(ccui.Widget.LEFT, this._firstFocusedWidget); } - if (keyCode == cc.KEY.right) { + if (keyCode == cc.KEY.dpadRight) { this._firstFocusedWidget = this._firstFocusedWidget.findNextFocusedWidget(ccui.Widget.RIGHT, this._firstFocusedWidget); } } From 3a548048c5118491e24f26ab3f73cd7c4538f963 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Thu, 22 Jan 2015 09:57:56 +0800 Subject: [PATCH 0191/1345] Added a condition when texture is null in SpriteBatchNode --- cocos2d/core/sprites/CCSpriteBatchNodeWebGLRenderCmd.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/sprites/CCSpriteBatchNodeWebGLRenderCmd.js b/cocos2d/core/sprites/CCSpriteBatchNodeWebGLRenderCmd.js index d01556387c..8c371d0635 100644 --- a/cocos2d/core/sprites/CCSpriteBatchNodeWebGLRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteBatchNodeWebGLRenderCmd.js @@ -134,7 +134,8 @@ proto.setTexture = function(texture){ this._textureAtlas.setTexture(texture); - this._updateBlendFunc(); + if(texture) + this._updateBlendFunc(); }; proto.removeAllQuads = function(){ From d13a5d747fb7b8bf9369a8e8bd2d58907fca67ad Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 22 Jan 2015 11:11:05 +0800 Subject: [PATCH 0192/1345] Audio - Baidu browser play music may be fail --- cocos2d/audio/CCAudio.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index 96a480dd8b..fdd9559ba0 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -55,10 +55,12 @@ supportTable[sys.BROWSER_TYPE_WECHAT] = {multichannel: false, webAudio: false, auto: false, replay: true , emptied: true }; supportTable[sys.BROWSER_TYPE_360] = {multichannel: false, webAudio: false, auto: true }; supportTable[sys.BROWSER_TYPE_MIUI] = {multichannel: false, webAudio: false, auto: true }; - supportTable[sys.BROWSER_TYPE_BAIDU] = {multichannel: false, webAudio: false, auto: true , emptied: true }; - supportTable[sys.BROWSER_TYPE_BAIDU_APP]= {multichannel: false, webAudio: false, auto: true , emptied: true }; supportTable[sys.BROWSER_TYPE_LIEBAO] = {multichannel: false, webAudio: false, auto: false, replay: true , emptied: true }; supportTable[sys.BROWSER_TYPE_SOUGOU] = {multichannel: false, webAudio: false, auto: false, replay: true , emptied: true }; + //"Baidu" browser can automatically play + //But because it may be play failed, so need to replay and auto + supportTable[sys.BROWSER_TYPE_BAIDU] = {multichannel: false, webAudio: false, auto: false, replay: true , emptied: true }; + supportTable[sys.BROWSER_TYPE_BAIDU_APP]= {multichannel: false, webAudio: false, auto: false, replay: true , emptied: // APPLE // supportTable[sys.BROWSER_TYPE_SAFARI] = {multichannel: true , webAudio: true , auto: false, webAudioCallback: function(realUrl){ From ebe9c2870758a92ad6cc8ea814f46aaadba0ab2e Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 22 Jan 2015 11:37:34 +0800 Subject: [PATCH 0193/1345] Audio - Baidu browser play music may be fail --- cocos2d/audio/CCAudio.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index fdd9559ba0..0500abad0c 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -60,7 +60,7 @@ //"Baidu" browser can automatically play //But because it may be play failed, so need to replay and auto supportTable[sys.BROWSER_TYPE_BAIDU] = {multichannel: false, webAudio: false, auto: false, replay: true , emptied: true }; - supportTable[sys.BROWSER_TYPE_BAIDU_APP]= {multichannel: false, webAudio: false, auto: false, replay: true , emptied: + supportTable[sys.BROWSER_TYPE_BAIDU_APP]= {multichannel: false, webAudio: false, auto: false, replay: true , emptied: true }; // APPLE // supportTable[sys.BROWSER_TYPE_SAFARI] = {multichannel: true , webAudio: true , auto: false, webAudioCallback: function(realUrl){ From b9aaa9305037f4b47381261e6c501a81f4737b12 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 22 Jan 2015 14:44:21 +0800 Subject: [PATCH 0194/1345] UILayout background error --- .../cocostudio/loader/parsers/timelineParser-2.x.js | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 4164b7f852..feb1306484 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -392,12 +392,19 @@ var bgStartColor = json["FirstColor"]; var bgEndColor = json["EndColor"]; - if(bgStartColor != null && bgEndColor != null) - widget.setBackGroundColor( getColor(bgStartColor), getColor(bgEndColor) ); + if(bgStartColor != null && bgEndColor != null){ + var startC = getColor(bgStartColor); + var endC; + if(bgEndColor["R"] == null && bgEndColor["G"] == null && bgEndColor["B"] == null) + endC = null; + else + endC = getColor(bgEndColor); + widget.setBackGroundColor( startC, endC ); + } var colorVector = json["ColorVector"]; if(colorVector != null) - colorVector["ScaleX"]; + widget.setBackGroundColorVector(cc.p(colorVector["ScaleX"], colorVector["ScaleY"])); loadTexture(json["FileData"], resourcePath, function(path, type){ widget.setBackGroundImage(path, type); From 3e48b6ce8ac4524a3e0e21794b23cf4da57fabb6 Mon Sep 17 00:00:00 2001 From: jianglong0156 Date: Thu, 22 Jan 2015 15:07:31 +0800 Subject: [PATCH 0195/1345] fix listview direction error, and modify the gravity default value --- extensions/ccui/uiwidgets/scroll-widget/UIListView.js | 2 +- extensions/cocostudio/loader/parsers/timelineParser-2.x.js | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIListView.js b/extensions/ccui/uiwidgets/scroll-widget/UIListView.js index 9b2950218c..aacc0be62e 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIListView.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIListView.js @@ -59,7 +59,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ ctor: function () { ccui.ScrollView.prototype.ctor.call(this); this._items = []; - this._gravity = ccui.ListView.GRAVITY_CENTER_HORIZONTAL; + this._gravity = ccui.ListView.GRAVITY_CENTER_VERTICAL; this.setTouchEnabled(true); this.init(); diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index feb1306484..cc2e3e7134 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -890,7 +890,7 @@ var verticalType = json["VerticalType"]; var horizontalType = json["HorizontalType"]; if(!directionType){ - widget.setDirection(ccui.ListView.DIR_HORIZONTAL); + widget.setDirection(ccui.ScrollView.DIR_HORIZONTAL); if(verticalType == "Align_Bottom") widget.setGravity(ccui.ListView.GRAVITY_BOTTOM); else if(verticalType == "Align_VerticalCenter") @@ -898,7 +898,7 @@ else widget.setGravity(ccui.ListView.GRAVITY_TOP); }else if(directionType == "Vertical"){ - widget.setDirection(ccui.ListView.DIR_VERTICAL); + widget.setDirection(ccui.ScrollView.DIR_VERTICAL); if (horizontalType == "") widget.setGravity(ccui.ListView.GRAVITY_LEFT); else if (horizontalType == "Align_Right") From f5310410a18bc6ff8a053abcd6bea6f31f9a7c3a Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 22 Jan 2015 15:52:53 +0800 Subject: [PATCH 0196/1345] UIImageView setContentSize error --- .../loader/parsers/timelineParser-2.x.js | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index feb1306484..ccbb970b76 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -693,34 +693,34 @@ var widget = new ccui.ImageView(); - this.widgetAttributes(widget, json); + 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"]; var scale9OriginY = json["Scale9OriginY"]; var scale9Width = json["Scale9Width"]; var scale9Height = json["Scale9Height"]; widget.setCapInsets(cc.rect( - scale9OriginX || 0, - scale9OriginY || 0, - scale9Width || 0, - scale9Height || 0 + scale9OriginX || 0, + scale9OriginY || 0, + scale9Width || 0, + scale9Height || 0 )); - } + } else + setContentSize(widget, json["Size"]); - setContentSize(widget, json["Size"]); + widget.ignoreContentAdaptWithSize(false); - loadTexture(json["FileData"], resourcePath, function(path, type){ - widget.loadTexture(path, type); - }); - loadTexture(json["ImageFileData"], resourcePath, function(path, type){ - widget.loadTexture(path, type); - }); + this.widgetAttributes(widget, json); return widget; }; From d48cd7216efd61879bb3bd1407fc4664047ba749 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 22 Jan 2015 15:57:05 +0800 Subject: [PATCH 0197/1345] [3.3b] Update version --- cocos2d/core/platform/CCConfig.js | 2 +- tools/build.xml | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/cocos2d/core/platform/CCConfig.js b/cocos2d/core/platform/CCConfig.js index d9a9563c10..f960492f24 100644 --- a/cocos2d/core/platform/CCConfig.js +++ b/cocos2d/core/platform/CCConfig.js @@ -31,7 +31,7 @@ * @type {String} * @name cc.ENGINE_VERSION */ -window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.2"; +window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.3 Beta0"; /** *

diff --git a/tools/build.xml b/tools/build.xml index a2638b99de..384d8eb2e4 100644 --- a/tools/build.xml +++ b/tools/build.xml @@ -5,8 +5,8 @@ classpath="./compiler/compiler.jar"/> - + debug="false" output="./../lib/cocos2d-js-v3.3-beta0-min.js"> + @@ -297,8 +297,8 @@ - + debug="false" output="./../lib/cocos2d-js-v3.3-beta0-core-min.js"> + From 28918c60b1f2fa663324b4ba507b7b621506bc3e Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 22 Jan 2015 16:29:19 +0800 Subject: [PATCH 0198/1345] UIImageView setContentSize error --- .../cocostudio/loader/parsers/timelineParser-2.x.js | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 91b3227bb3..8a204c0645 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -208,6 +208,14 @@ //////////// parser.widgetAttributes = function(widget, json){ + widget.setCascadeColorEnabled(true); + widget.setCascadeOpacityEnabled(true); + + widget.setUnifySizeEnabled(false); + widget.setLayoutComponentEnabled(true); + widget.ignoreContentAdaptWithSize(false); + setContentSize(widget, json["Size"]); + var name = json["Name"]; if(name) widget.setName(name); @@ -286,8 +294,6 @@ if(color != null) widget.setColor(getColor(color)); - setContentSize(widget, json["Size"]); - if(widget instanceof ccui.Layout){ var layoutComponent = ccui.LayoutComponent.bindLayoutComponent(widget); @@ -704,6 +710,7 @@ if(scale9Enabled){ widget.setScale9Enabled(true); widget.setUnifySizeEnabled(false); + widget.ignoreContentAdaptWithSize(false); var scale9OriginX = json["Scale9OriginX"]; var scale9OriginY = json["Scale9OriginY"]; @@ -718,8 +725,6 @@ } else setContentSize(widget, json["Size"]); - widget.ignoreContentAdaptWithSize(false); - this.widgetAttributes(widget, json); return widget; From c16e73f1250c51d55b38308ccaecc307df32b938 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Thu, 22 Jan 2015 16:34:49 +0800 Subject: [PATCH 0199/1345] Fixed a bug of cc.EditBox that its position is incorrect on Canvas Mode and its string value is wrong when PlaceHolder is showing. --- .../labelttf/CCLabelTTFCanvasRenderCmd.js | 2 ++ extensions/editbox/CCEditBox.js | 24 +++++++++++-------- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js index dc5d9b6f99..a851398cfe 100644 --- a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js +++ b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js @@ -61,6 +61,8 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; var node = this._node; if (!this._labelCanvas) { var locCanvas = cc.newElement("canvas"); + locCanvas.width = 1; + locCanvas.height = 1; var labelTexture = new cc.Texture2D(); labelTexture.initWithElement(locCanvas); node.setTexture(labelTexture); diff --git a/extensions/editbox/CCEditBox.js b/extensions/editbox/CCEditBox.js index 6a15a12dc4..ef9beca447 100644 --- a/extensions/editbox/CCEditBox.js +++ b/extensions/editbox/CCEditBox.js @@ -280,6 +280,10 @@ cc.EditBox = cc.ControlButton.extend({ this.value = ""; this.style.fontSize = selfPointer._edFontSize + "px"; this.style.color = cc.colorToHex(selfPointer._textColor); + if (selfPointer._editBoxInputFlag == cc.EDITBOX_INPUT_FLAG_PASSWORD) + selfPointer._edTxt.type = "password"; + else + selfPointer._edTxt.type = "text"; } if (selfPointer._delegate && selfPointer._delegate.editBoxEditingDidBegin) selfPointer._delegate.editBoxEditingDidBegin(selfPointer); @@ -290,6 +294,7 @@ cc.EditBox = cc.ControlButton.extend({ 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); @@ -360,6 +365,10 @@ cc.EditBox = cc.ControlButton.extend({ if (this._edTxt.value != this._placeholderText) { this._edTxt.style.fontFamily = this._edFontName; this._edTxt.style.fontSize = this._edFontSize + "px"; + if (this._editBoxInputFlag == cc.EDITBOX_INPUT_FLAG_PASSWORD) + this._edTxt.type = "password"; + else + this._edTxt.type = "text"; } }, @@ -370,15 +379,7 @@ cc.EditBox = cc.ControlButton.extend({ */ setText: function (text) { cc.log("Please use the setString"); - if (text != null) { - if (text == "") { - this._edTxt.value = this._placeholderText; - this._edTxt.style.color = cc.colorToHex(this._placeholderColor); - } else { - this._edTxt.value = text; - this._edTxt.style.color = cc.colorToHex(this._textColor); - } - } + this.setString(text); }, /** @@ -487,6 +488,7 @@ cc.EditBox = cc.ControlButton.extend({ if (this._edTxt.value == this._placeholderText) { this._edTxt.style.fontFamily = this._placeholderFontName; this._edTxt.style.fontSize = this._placeholderFontSize + "px"; + this._edTxt.type = "text"; } }, @@ -508,7 +510,7 @@ cc.EditBox = cc.ControlButton.extend({ */ setInputFlag: function (inputFlag) { this._editBoxInputFlag = inputFlag; - if (inputFlag == cc.EDITBOX_INPUT_FLAG_PASSWORD) + if ((this._edTxt.value !== this._placeholderText) && (inputFlag == cc.EDITBOX_INPUT_FLAG_PASSWORD)) this._edTxt.type = "password"; else this._edTxt.type = "text"; @@ -529,6 +531,8 @@ cc.EditBox = cc.ControlButton.extend({ * @return {string} */ getString: function () { + if(this._edTxt.value === this._placeholderText) + return ""; return this._edTxt.value; }, From 246aa7c88999477c9ab954aa7587469736c763db Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 22 Jan 2015 16:42:31 +0800 Subject: [PATCH 0200/1345] UIImageView setContentSize error --- extensions/cocostudio/loader/parsers/timelineParser-2.x.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 8a204c0645..226a5348ab 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -212,7 +212,7 @@ widget.setCascadeOpacityEnabled(true); widget.setUnifySizeEnabled(false); - widget.setLayoutComponentEnabled(true); + //widget.setLayoutComponentEnabled(true); widget.ignoreContentAdaptWithSize(false); setContentSize(widget, json["Size"]); From 9f78916b7a5b5763718e769ee000d2b06d37a626 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Thu, 22 Jan 2015 16:45:50 +0800 Subject: [PATCH 0201/1345] Fixed a bug of cc.EditBox that its position is incorrect on Canvas Mode and its string value is wrong when PlaceHolder is showing. --- extensions/editbox/CCEditBox.js | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/extensions/editbox/CCEditBox.js b/extensions/editbox/CCEditBox.js index ef9beca447..561e771d77 100644 --- a/extensions/editbox/CCEditBox.js +++ b/extensions/editbox/CCEditBox.js @@ -243,8 +243,7 @@ cc.EditBox = cc.ControlButton.extend({ this._placeholderColor = cc.color.GRAY; this.setContentSize(size); var tmpDOMSprite = this._domInputSprite = new cc.Sprite(); - tmpDOMSprite.draw = function () { - }; //redefine draw function + tmpDOMSprite.draw = function () {}; //redefine draw function this.addChild(tmpDOMSprite); var selfPointer = this; var tmpEdTxt = this._edTxt = cc.newElement("input"); @@ -259,9 +258,7 @@ cc.EditBox = cc.ControlButton.extend({ tmpEdTxt.style.active = 0; tmpEdTxt.style.outline = "medium"; tmpEdTxt.style.padding = "0"; - var onCanvasClick = function() { - tmpEdTxt.blur(); - }; + var onCanvasClick = function() { tmpEdTxt.blur();}; // TODO the event listener will be remove when EditBox removes from parent. cc._addEventListener(tmpEdTxt, "input", function () { @@ -317,7 +314,6 @@ cc.EditBox = cc.ControlButton.extend({ if (this.initWithSizeAndBackgroundSprite(size, normal9SpriteBg)) { if (press9SpriteBg) this.setBackgroundSpriteForState(press9SpriteBg, cc.CONTROL_STATE_HIGHLIGHTED); - if (disabled9SpriteBg) this.setBackgroundSpriteForState(disabled9SpriteBg, cc.CONTROL_STATE_DISABLED); } @@ -391,9 +387,14 @@ cc.EditBox = cc.ControlButton.extend({ if (text == "") { this._edTxt.value = this._placeholderText; this._edTxt.style.color = cc.colorToHex(this._placeholderColor); + this._edTxt.type = "text"; } else { this._edTxt.value = text; this._edTxt.style.color = cc.colorToHex(this._textColor); + if (this._editBoxInputFlag == cc.EDITBOX_INPUT_FLAG_PASSWORD) + this._edTxt.type = "password"; + else + this._edTxt.type = "text"; } } }, From b5b6c592948f5a996c0f50c1fc427fa7160cbec1 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 22 Jan 2015 17:05:37 +0800 Subject: [PATCH 0202/1345] Parser anchor error --- extensions/cocostudio/loader/parsers/timelineParser-2.x.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 226a5348ab..362cd0358d 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -288,7 +288,7 @@ var anchorPoint = json["AnchorPoint"]; if(anchorPoint != null) - widget.setAnchorPoint(anchorPoint["ScaleX"] || 0.5, anchorPoint["ScaleY"] || 0.5); + widget.setAnchorPoint(anchorPoint["ScaleX"] || 0, anchorPoint["ScaleY"] || 0); var color = json["CColor"]; if(color != null) From bc08d06adf74973375474546749e63a546153fbe Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Thu, 22 Jan 2015 18:02:39 +0800 Subject: [PATCH 0203/1345] Fixed a bug of cc.loader that its loadImage doesn't work when image is crossOrigin --- CCBoot.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CCBoot.js b/CCBoot.js index f777148fc1..c0b3919823 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -783,11 +783,13 @@ cc.loader = /** @lends cc.loader# */{ callback(null, img); }; + var self = this; var errorCallback = function () { this.removeEventListener('error', errorCallback, false); if(img.crossOrigin && img.crossOrigin.toLowerCase() == "anonymous"){ opt.isCrossOrigin = false; + self.release(url); cc.loader.loadImg(url, opt, callback); }else{ typeof callback == "function" && callback("load image failed"); From c86e008996182aa8a8bee25b1e9f10a9179a4cd8 Mon Sep 17 00:00:00 2001 From: jianglong0156 Date: Thu, 22 Jan 2015 18:05:31 +0800 Subject: [PATCH 0204/1345] update function setBackgroundColor judgement, avoid the error in jsb --- extensions/cocostudio/loader/parsers/timelineParser-2.x.js | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 362cd0358d..fef266a3cc 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -402,10 +402,9 @@ var startC = getColor(bgStartColor); var endC; if(bgEndColor["R"] == null && bgEndColor["G"] == null && bgEndColor["B"] == null) - endC = null; + widget.setBackGroundColor( startC ); else - endC = getColor(bgEndColor); - widget.setBackGroundColor( startC, endC ); + widget.setBackGroundColor( startC, getColor(bgEndColor) ); } var colorVector = json["ColorVector"]; From 37f15170499e00be215058e43893fe3e08638b80 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Fri, 23 Jan 2015 11:52:12 +0800 Subject: [PATCH 0205/1345] Fixed a bug of ccui.TextField that its contentSize is incorrect in textFieldEvent --- extensions/ccui/uiwidgets/UITextField.js | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/extensions/ccui/uiwidgets/UITextField.js b/extensions/ccui/uiwidgets/UITextField.js index 927585f959..90deb83d4f 100644 --- a/extensions/ccui/uiwidgets/UITextField.js +++ b/extensions/ccui/uiwidgets/UITextField.js @@ -574,16 +574,18 @@ ccui.TextField = ccui.Widget.extend(/** @lends ccui.TextField# */{ this.setDetachWithIME(false); } if (this.getInsertText()) { - this._insertTextEvent(); - this.setInsertText(false); this._textFieldRendererAdaptDirty = true; this._updateContentSizeWithTextureSize(this._textFieldRenderer.getContentSize()); + + this._insertTextEvent(); + this.setInsertText(false); } if (this.getDeleteBackward()) { - this._deleteBackwardEvent(); - this.setDeleteBackward(false); this._textFieldRendererAdaptDirty = true; this._updateContentSizeWithTextureSize(this._textFieldRenderer.getContentSize()); + + this._deleteBackwardEvent(); + this.setDeleteBackward(false); } }, From c9eaa7f852e63256615a637da463e78ebea20dce Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 23 Jan 2015 18:03:01 +0800 Subject: [PATCH 0206/1345] update build.xml --- tools/build.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/build.xml b/tools/build.xml index a2638b99de..49f7f37950 100644 --- a/tools/build.xml +++ b/tools/build.xml @@ -270,6 +270,7 @@ + From 7c9ec7ac7938da49140421ad94a7d49fcb809fc2 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Fri, 23 Jan 2015 18:51:36 +0800 Subject: [PATCH 0207/1345] Update the authors for v3.3 beta0 --- AUTHORS.txt | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/AUTHORS.txt b/AUTHORS.txt index 2f5bbfe7d6..5777d39dcd 100644 --- a/AUTHORS.txt +++ b/AUTHORS.txt @@ -224,6 +224,15 @@ Tim @duhaibo0404 ccs.csLoader bug fix Hermanto @man2 cc.loader bug fix +Long Jiang @jianglong0156 cc.LabelBMFont bug fix + KeyCode bug fix + ccui.ListView bug fix + +Joe Lafiosca @lafiosca Added Javascript file loader + +galapagosit @galapagosit ccs.actionManager bug fix + + Retired Core Developers: Shengxiang Chen (Nero Chan) Xingsen Ma From 8b2cd11a7b603489a68596caa9136031b1c40fb0 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Sat, 24 Jan 2015 12:22:15 +0800 Subject: [PATCH 0208/1345] Update changelog for v3.3 beta --- CHANGELOG.txt | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/CHANGELOG.txt b/CHANGELOG.txt index 0c340d480b..c61ba3f643 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,5 +1,36 @@ ChangeLog: +Cocos2d-JS v3.3 Beta @ Jan.24, 2015 + +* Added Cocos Studio v2.x parser and refactored 1.x parser. +* Upgraded new flow layout UI system in web engine. +* Refactored `load` events of texture2d, sprite and so on to be more intuitive. +* Added JavaScript file loader. +* Allowed set texture to null in `cc.Sprite`. +* Added full test cases for Cocos Studio v2.x parser and the new flow layout UI system. +* Upgraded MoonWarriors sample's UI and graphic design. + +* Bug fixes: + 1. Fixed a bug of Cocos2d UI, their focus event has been supported. + 2. Fixed a buf of `ccui.Widget` that its percent position doesn't work. + 3. Fixed a bug of `ccs.Armature` that its position doesn't update in visit on WebGL render mode. + 4. Fixed a bug of `cc.Sprite` that its `setTextureRect` function doesn't work when `setColor` invoked. + 5. Fixed a bug of `cc.PhysicsSprite` that its position is incorrect. + 6. Fixed a bug of `ccs.Bone` that its `setOpacity` and `setColor` doesn't work. + 7. Fixed a bug of `cc.LabelBMFont` that its word wrap doesn't work. + 8. Fixed a bug of `cc.sys` that it gets the incorrect OS type when system is Linux. + 9. Fixed a bug of `cc.audioEngine` that its loading path is incorrect. + 10. Fixed a bug of `ccui.Widget` that it can't touch when it's reused. + 11. Fixed a bug of UI system that the `setNormalizedPosition` doesn't work. + 12. Fixed a bug of `cc.ActionInterval` that its `_times` conflict with `cc.Blink`. + 13. Fixed release texture issue in canvas mode. + 14. Fixed a bug of `ccs.actionManager` that its `getActionByName` doesn't work. + 15. Fixed a bug of `cc.Sprite` that it can't draw without texture on WebGL mode. + 16. Fixed a bug of `cc.audioEngine` that it doesn't work on baidu browser. + 17. Fixed a bug of `cc.EditBox` that its position is incorrect on Canvas Mode and its string value is wrong when PlaceHolder is showing. + 18. Fixed a bug of `cc.loader` that its `loadImg` function doesn't work when image is accessed cross origin. + 19. Fixed a bug of `ccui.TextField` that its `contentSize` is incorrect in text field event. + Cocos2d-JS v3.2 @ Dec.29, 2014 * Replaced `transform` function with `setTransform` function under canvas render mode for better performance. From 9feb7f77be4546709be82fb1aeee29948412f9ec Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Sun, 25 Jan 2015 10:52:54 +0800 Subject: [PATCH 0209/1345] studio parser modify default value --- .../cocostudio/loader/parsers/action-2.x.js | 3 +- .../loader/parsers/timelineParser-2.x.js | 214 ++++++++---------- 2 files changed, 98 insertions(+), 119 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/action-2.x.js b/extensions/cocostudio/loader/parsers/action-2.x.js index f57709f8ad..e04dd83017 100644 --- a/extensions/cocostudio/loader/parsers/action-2.x.js +++ b/extensions/cocostudio/loader/parsers/action-2.x.js @@ -216,7 +216,8 @@ frames.forEach(function(frameData){ var frame = item.handle(frameData, resourcePath); frame.setFrameIndex(frameData["FrameIndex"]); - frame.setTween(frameData["Tween"]); + var tween = frameData["Tween"] != null ? frameData["Tween"] : true; + frame.setTween(tween); timeline.addFrame(frame); }); } diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index fef266a3cc..04ef310735 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -48,6 +48,13 @@ var parser = new Parser(); + var getParam = function(value, dValue){ + if(value === undefined) + return dValue; + else + return value; + }; + ////////// // NODE // ////////// @@ -90,20 +97,17 @@ if (json["ZOrder"] != null) node.setLocalZOrder(json["ZOrder"]); - var visible = json["VisibleForFrame"]; - if (visible != null) - node.setVisible(visible == "True"); + var visible = getParam(json["VisibleForFrame"], true); + node.setVisible(visible); setContentSize(node, json["Size"]); if (json["Alpha"] != null) node.setOpacity(json["Alpha"]); - if (json["Tag"] != null) - node.setTag(json["Tag"]); + node.setTag(json["Tag"] || 0); - if (json["ActionTag"] != null) - node.setUserObject(new ccs.ActionTimelineData(json["ActionTag"])); + node.setUserObject(new ccs.ActionTimelineData(json["ActionTag"] || 0)); node.setCascadeColorEnabled(true); node.setCascadeOpacityEnabled(true); @@ -220,11 +224,9 @@ if(name) widget.setName(name); - var actionTag = json["ActionTag"]; - if(actionTag){ - widget.setActionTag(actionTag); - widget.setUserObject(new ccs.ActionTimelineData(actionTag)); - } + var actionTag = json["ActionTag"] || 0; + widget.setActionTag(actionTag); + widget.setUserObject(new ccs.ActionTimelineData(actionTag)); var rotationSkewX = json["RotationSkewX"]; if(rotationSkewX) @@ -250,17 +252,14 @@ //var visible = json["Visible"]; - var visible = json["VisibleForFrame"]; - if(visible != null) - widget.setVisible(visible); + var visible = getParam(json["VisibleForFrame"], true); + widget.setVisible(visible); var alpha = json["Alpha"]; if(alpha != null) widget.setOpacity(alpha); - var tag = json["Tag"]; - if(tag != null) - widget.setTag(tag); + widget.setTag(json["Tag"] || 0); var touchEnabled = json["TouchEnable"]; if(touchEnabled) @@ -317,8 +316,8 @@ } 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 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; @@ -378,29 +377,26 @@ if(clipEnabled != null) widget.setClippingEnabled(clipEnabled); - var colorType = json["ComboBoxIndex"]; - if(colorType != null) - widget.setBackGroundColorType(colorType); + var colorType = getParam(json["ComboBoxIndex"], 0); + widget.setBackGroundColorType(colorType); - var bgColorOpacity = json["BackColorAlpha"]; - if(bgColorOpacity != null) - widget.setBackGroundColorOpacity(bgColorOpacity); + var bgColorOpacity = getParam(json["BackColorAlpha"], 255); + widget.setBackGroundColorOpacity(bgColorOpacity); var backGroundScale9Enabled = json["Scale9Enable"]; if(backGroundScale9Enabled != null) widget.setBackGroundImageScale9Enabled(backGroundScale9Enabled); - var scale9OriginX = json["Scale9OriginX"]; - var scale9OriginY = json["Scale9OriginY"]; + var scale9OriginX = json["Scale9OriginX"] || 0; + var scale9OriginY = json["Scale9OriginY"] || 0; - var scale9Width = json["Scale9Width"]; - var scale9Height = json["Scale9Height"]; + var scale9Width = json["Scale9Width"] || 0; + var scale9Height = json["Scale9Height"] || 0; var bgStartColor = json["FirstColor"]; var bgEndColor = json["EndColor"]; if(bgStartColor != null && bgEndColor != null){ var startC = getColor(bgStartColor); - var endC; if(bgEndColor["R"] == null && bgEndColor["G"] == null && bgEndColor["B"] == null) widget.setBackGroundColor( startC ); else @@ -450,7 +446,7 @@ if(areaWidth && areaHeight) widget.setTextAreaSize(cc.size(areaWidth, areaHeight)); - var h_alignment = json["HorizontalAlignmentType"]; + var h_alignment = json["HorizontalAlignmentType"] || "HT_Left"; switch(h_alignment){ case "HT_Right": h_alignment = 2; break; @@ -462,7 +458,7 @@ } widget.setTextHorizontalAlignment(h_alignment); - var v_alignment = json["VerticalAlignmentType"]; + var v_alignment = json["VerticalAlignmentType"] || "VT_Top"; switch(v_alignment){ case "VT_Bottom": v_alignment = 2; break; @@ -511,7 +507,7 @@ this.widgetAttributes(widget, json); - var scale9Enabled = json["Scale9Enable"]; + var scale9Enabled = getParam(json["Scale9Enable"], false); if(scale9Enabled){ widget.setScale9Enabled(scale9Enabled); widget.setUnifySizeEnabled(false); @@ -542,17 +538,14 @@ if(fontName != null) widget.setTitleFontName(fontName); - var displaystate = json["DisplayState"]; - if(displaystate != null){ - widget.setBright(displaystate); - widget.setEnabled(displaystate); - } + var displaystate = getParam(json["DisplayState"], true); + widget.setBright(displaystate); + widget.setEnabled(displaystate); var textColor = json["TextColor"]; if(textColor != null) widget.setTitleColor(getColor(textColor)); - loadTexture(json["NormalFileData"], resourcePath, function(path, type){ widget.loadTextureNormal(path, type); }); @@ -587,15 +580,12 @@ this.widgetAttributes(widget, json); - var selectedState = json["CheckedState"]; - if(selectedState) - widget.setSelected(true); + var selectedState = getParam(json["CheckedState"], false); + widget.setSelected(selectedState); - var displaystate = json["DisplayState"]; - if(displaystate){ - widget.setBright(displaystate); - widget.setEnabled(displaystate); - } + var displaystate = getParam(json["DisplayState"], true); + widget.setBright(displaystate); + widget.setEnabled(displaystate); var dataList = [ {name: "NormalBackFileData", handle: widget.loadTextureBackGround}, @@ -628,9 +618,8 @@ if(clipEnabled) widget.setClippingEnabled(true); - var colorType = json["ComboBoxIndex"]; - if(colorType != null) - widget.setBackGroundColorType(colorType); + var colorType = getParam(json["ComboBoxIndex"], 0); + widget.setBackGroundColorType(colorType); var bgColorOpacity = json["BackColorAlpha"]; if(bgColorOpacity) @@ -641,11 +630,11 @@ widget.setBackGroundImageScale9Enabled(true); } - var scale9OriginX = json["Scale9OriginX"]; - var scale9OriginY = json["Scale9OriginY"]; + var scale9OriginX = json["Scale9OriginX"] || 0; + var scale9OriginY = json["Scale9OriginY"] || 0; - var scale9Width = json["Scale9Width"]; - var scale9Height = json["Scale9Height"]; + var scale9Width = json["Scale9Width"] || 0; + var scale9Height = json["Scale9Height"] || 0; //todo please check it setContentSize(widget, json["Size"]); @@ -682,9 +671,8 @@ if(json["ScrollDirectionType"] == "Vertical_Horizontal") direction = 3; widget.setDirection(direction); - var bounceEnabled = json["IsBounceEnabled"]; - if(bounceEnabled) - widget.setBounceEnabled(bounceEnabled); + var bounceEnabled = getParam(json["IsBounceEnabled"], false); + widget.setBounceEnabled(bounceEnabled); return widget; }; @@ -711,15 +699,15 @@ widget.setUnifySizeEnabled(false); widget.ignoreContentAdaptWithSize(false); - var scale9OriginX = json["Scale9OriginX"]; - var scale9OriginY = json["Scale9OriginY"]; - var scale9Width = json["Scale9Width"]; - var scale9Height = json["Scale9Height"]; + 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 || 0, - scale9OriginY || 0, - scale9Width || 0, - scale9Height || 0 + scale9OriginX , + scale9OriginY, + scale9Width, + scale9Height )); } else setContentSize(widget, json["Size"]); @@ -748,7 +736,7 @@ var direction = json["ProgressType"]; widget.setDirection((direction != "Left_To_Right") | 0); - var percent = json["ProgressInfo"]; + var percent = getParam(json["ProgressInfo"], 80); if(percent != null) widget.setPercent(percent); @@ -783,15 +771,12 @@ }); }); - var percent = json["PercentInfo"]; - if(percent != null) - widget.setPercent(percent); + var percent = json["PercentInfo"] || 0; + widget.setPercent(percent); - var displaystate = json["DisplayState"]; - if(displaystate != null){ - widget.setBright(displaystate); - widget.setEnabled(displaystate); - } + var displaystate = getParam(json["DisplayState"], true); + widget.setBright(displaystate); + widget.setEnabled(displaystate); return widget; }; @@ -815,21 +800,20 @@ if(backGroundScale9Enabled){ widget.setBackGroundImageScale9Enabled(true); - var scale9OriginX = json["Scale9OriginX"]; - var scale9OriginY = json["Scale9OriginY"]; - var scale9Width = json["Scale9Width"]; - var scale9Height = json["Scale9Height"]; + 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 || 0, - scale9OriginY || 0, - scale9Width || 0, - scale9Height || 0 + scale9OriginX, + scale9OriginY, + scale9Width, + scale9Height )); } - var colorType = json["ComboBoxIndex"]; - if(colorType != null) - widget.setBackGroundColorType(colorType); + var colorType = getParam(json["ComboBoxIndex"], 0); + widget.setBackGroundColorType(colorType); var bgColorOpacity = json["BackColorAlpha"]; var bgColor = getColor(json["SingleColor"]); @@ -869,30 +853,29 @@ if(clipEnabled) widget.setClippingEnabled(true); - var colorType = json["ComboBoxIndex"]; - if(colorType != null) - widget.setBackGroundColorType(colorType); + var colorType = getParam(json["ComboBoxIndex"], 0); + widget.setBackGroundColorType(colorType); - var bgColorOpacity = json["BackColorAlpha"]; + var bgColorOpacity = getParam(json["BackColorAlpha"], 255); var backGroundScale9Enabled = json["Scale9Enable"]; if(backGroundScale9Enabled){ widget.setBackGroundImageScale9Enabled(true); - var scale9OriginX = json["Scale9OriginX"]; - var scale9OriginY = json["Scale9OriginY"]; - var scale9Width = json["Scale9Width"]; - var scale9Height = json["Scale9Height"]; + 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 || 0, - scale9OriginY || 0, - scale9Width || 0, - scale9Height || 0 + scale9OriginX, + scale9OriginY, + scale9Width, + scale9Height )); } - var directionType = json["DirectionType"]; - var verticalType = json["VerticalType"]; - var horizontalType = json["HorizontalType"]; + 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") @@ -912,13 +895,11 @@ } - var bounceEnabled = json["IsBounceEnabled"]; - if(bounceEnabled) - widget.setBounceEnabled(true); - var itemMargin = json["ItemMargin"]; - if(itemMargin != null){ - widget.setItemsMargin(itemMargin); - } + var bounceEnabled = getParam(json["IsBounceEnabled"], false); + widget.setBounceEnabled(bounceEnabled); + + var itemMargin = json["ItemMargin"] || 0; + widget.setItemsMargin(itemMargin); var innerSize = json["InnerNodeSize"]; //Width @@ -1009,9 +990,8 @@ var passwordEnabled = json["PasswordEnable"]; if(passwordEnabled){ widget.setPasswordEnabled(true); - var passwordStyleText = json["PasswordStyleText"]; - if(passwordStyleText != null) - widget.setPasswordStyleText(passwordStyleText); + var passwordStyleText = json["PasswordStyleText"] || "*"; + widget.setPasswordStyleText(passwordStyleText); } var placeHolder = json["PlaceHolderText"]; @@ -1029,9 +1009,8 @@ var maxLengthEnabled = json["MaxLengthEnable"]; if(maxLengthEnabled){ widget.setMaxLengthEnabled(true); - var maxLength = json["MaxLengthText"]; - if(maxLength != null) - widget.setMaxLength(maxLength); + var maxLength = json["MaxLengthText"] || 0; + widget.setMaxLength(maxLength); } //var isCustomSize = json["IsCustomSize"]; @@ -1067,10 +1046,9 @@ */ parser.initSimpleAudio = function(json, resourcePath){ - var loop = json["Loop"]; - var volume = json["Volume"]; - if(volume != null) - cc.audioEngine.setMusicVolume(volume); + var loop = json["Loop"] || false; + var volume = json["Volume"] || 0; + cc.audioEngine.setMusicVolume(volume); //var name = json["Name"]; var resPath = ""; if(cc.loader.resPath) From 417c17a7ba4ca5738efa25d896f30ab0fd76a916 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Sun, 25 Jan 2015 11:17:12 +0800 Subject: [PATCH 0210/1345] #114840 background color error --- .../cocostudio/loader/parsers/action-2.x.js | 3 +- .../loader/parsers/timelineParser-2.x.js | 47 +++++++++++-------- 2 files changed, 29 insertions(+), 21 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/action-2.x.js b/extensions/cocostudio/loader/parsers/action-2.x.js index e04dd83017..f57709f8ad 100644 --- a/extensions/cocostudio/loader/parsers/action-2.x.js +++ b/extensions/cocostudio/loader/parsers/action-2.x.js @@ -216,8 +216,7 @@ frames.forEach(function(frameData){ var frame = item.handle(frameData, resourcePath); frame.setFrameIndex(frameData["FrameIndex"]); - var tween = frameData["Tween"] != null ? frameData["Tween"] : true; - frame.setTween(tween); + frame.setTween(frameData["Tween"]); timeline.addFrame(frame); }); } diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 04ef310735..14f7b745a8 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -639,11 +639,13 @@ //todo please check it setContentSize(widget, json["Size"]); - if(json["FirstColor"] && json["EndColor"]){ - var bgStartColor, bgEndColor; - bgStartColor = getColor(json["FirstColor"]); - bgEndColor = getColor(json["EndColor"]); - widget.setBackGroundColor(bgStartColor, bgEndColor); + var firstColor = json["FirstColor"]; + var endColor = json["EndColor"]; + if(firstColor && endColor){ + if(endColor["R"] != null && endColor["G"] != null && endColor["B"] != null) + widget.setBackGroundColor(getColor(firstColor), getColor(endColor)); + else + widget.setBackGroundColor(getColor(firstColor)); }else{ widget.setBackGroundColor(getColor(json["SingleColor"])); } @@ -816,13 +818,16 @@ widget.setBackGroundColorType(colorType); var bgColorOpacity = json["BackColorAlpha"]; - var bgColor = getColor(json["SingleColor"]); - var bgEndColor = getColor(json["EndColor"]); - var bgStartColor = getColor(json["FirstColor"]); - if(bgEndColor && bgStartColor) - widget.setBackGroundColor(bgStartColor, bgEndColor); - else - widget.setBackGroundColor(bgColor); + var firstColor = json["FirstColor"]; + var endColor = json["EndColor"]; + if(firstColor && endColor){ + if(endColor["R"] != null && endColor["G"] != null && endColor["B"] != null) + widget.setBackGroundColor(getColor(firstColor), getColor(endColor)); + else + widget.setBackGroundColor(getColor(firstColor)); + }else{ + widget.setBackGroundColor(getColor(json["SingleColor"])); + } var colorVector = json["ColorVector"]; if(colorVector != null && colorVector["ScaleX"] != null && colorVector["ScaleY"] != null) @@ -906,13 +911,17 @@ if(innerSize != null) widget.setInnerContainerSize(cc.size(innerSize["Widget"]||0, innerSize["Height"]||0)); - var bgColor = getColor(json["SingleColor"]); - var bgEndColor = getColor(json["EndColor"]); - var bgStartColor = getColor(json["FirstColor"]); - if(bgEndColor && bgStartColor) - widget.setBackGroundColor(bgStartColor, bgEndColor); - else - widget.setBackGroundColor(bgColor); + var firstColor = json["FirstColor"]; + var endColor = json["EndColor"]; + if(firstColor && endColor){ + if(endColor["R"] != null && endColor["G"] != null && endColor["B"] != null) + widget.setBackGroundColor(getColor(firstColor), getColor(endColor)); + else + widget.setBackGroundColor(getColor(firstColor)); + }else{ + widget.setBackGroundColor(getColor(json["SingleColor"])); + } + var colorVector = json["ColorVector"]; if(colorVector != null && colorVector["ScaleX"] != null && colorVector["ScaleY"] != null) widget.setBackGroundColorVector(colorVector["ScaleX"], colorVector["ScaleY"]); From f4d448ebb4fb4c963067a7a1cf4126af7b467231 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Sun, 25 Jan 2015 11:37:49 +0800 Subject: [PATCH 0211/1345] #14780 The listView parameter is missing --- extensions/cocostudio/loader/parsers/timelineParser-2.x.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 14f7b745a8..0ac47f244a 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -854,6 +854,8 @@ var widget = new ccui.ListView(); + this.widgetAttributes(widget, json); + var clipEnabled = json["ClipAble"]; if(clipEnabled) widget.setClippingEnabled(true); From bc2619276293a74e3201c847e23f04f3b305337c Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Sun, 25 Jan 2015 12:54:54 +0800 Subject: [PATCH 0212/1345] #14837 UIText setFontName error --- .../loader/parsers/timelineParser-2.x.js | 42 ++++++++++++++----- 1 file changed, 31 insertions(+), 11 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 0ac47f244a..e277406c2f 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -481,8 +481,12 @@ var path = fontResource["Path"]; //resoutceType = fontResource["Type"]; if(path != null){ - fontName = path.match(/([^\/]+)\.ttf/); - fontName = fontName ? fontName[1] : ""; + if (cc.sys.isNative && cc.sys.os == cc.sys.OS_ANDROID) { + fontName = cc.path.join(cc.loader.resPath, resourcePath, path); + } else { + fontName = path.match(/([^\/]+)\.ttf/); + fontName = fontName ? fontName[1] : ""; + } widget.setFontName(fontName); } } @@ -556,13 +560,18 @@ widget.loadTextureDisabled(path, type); }); - var fontResourcePath, fontResourceResourceType, fontResourcePlistFile; - var fontResource = json["FontResource"]; if(fontResource != null){ - //console.log(fontResource["Path"]); - // fontResourcePath = fontResource["Path"]; - // fontResourceResourceType = fontResource["Type"] == "Default" ? 0 : 1; - // fontResourcePlistFile = fontResource["Plist"]; + var path = fontResource["Path"]; + //resoutceType = fontResource["Type"]; + if(path != null){ + if (cc.sys.isNative && cc.sys.os == cc.sys.OS_ANDROID) { + fontName = cc.path.join(cc.loader.resPath, resourcePath, path); + } else { + fontName = path.match(/([^\/]+)\.ttf/); + fontName = fontName ? fontName[1] : ""; + } + widget._labelRenderer.setFontName(fontName); + } } return widget; @@ -1031,9 +1040,20 @@ if(text != null) widget.setString(text); - loadTexture(json["FontResource"], resourcePath, function(path, type){ - widget.setFontName(path); - }); + var fontResource = json["FontResource"]; + if(fontResource != null){ + var path = fontResource["Path"]; + //resoutceType = fontResource["Type"]; + if(path != null){ + if (cc.sys.isNative && cc.sys.os == cc.sys.OS_ANDROID) { + fontName = cc.path.join(cc.loader.resPath, resourcePath, path); + } else { + fontName = path.match(/([^\/]+)\.ttf/); + fontName = fontName ? fontName[1] : ""; + } + widget.setFontName(fontName); + } + } widget.setUnifySizeEnabled(false); widget.ignoreContentAdaptWithSize(false); From bd07572da6f07a1fd406b96b04f928263b232b72 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Sun, 25 Jan 2015 15:31:43 +0800 Subject: [PATCH 0213/1345] #14836 layout scale9Sprite error --- .../loader/parsers/timelineParser-2.x.js | 58 ++++++++++++------- 1 file changed, 38 insertions(+), 20 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index e277406c2f..3d33210d68 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -261,9 +261,8 @@ widget.setTag(json["Tag"] || 0); - var touchEnabled = json["TouchEnable"]; - if(touchEnabled) - widget.setTouchEnabled(true); + var touchEnabled = json["TouchEnable"] || false; + widget.setTouchEnabled(touchEnabled); // -- var frameEvent = json["FrameEvent"]; @@ -387,11 +386,31 @@ if(backGroundScale9Enabled != null) widget.setBackGroundImageScale9Enabled(backGroundScale9Enabled); - var scale9OriginX = json["Scale9OriginX"] || 0; - var scale9OriginY = json["Scale9OriginY"] || 0; + var opacity = json["Alpha"] || 255; + widget.setOpacity(opacity); - var scale9Width = json["Scale9Width"] || 0; - var scale9Height = json["Scale9Height"] || 0; + 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"]); + } + + } var bgStartColor = json["FirstColor"]; var bgEndColor = json["EndColor"]; @@ -407,10 +426,6 @@ if(colorVector != null) widget.setBackGroundColorVector(cc.p(colorVector["ScaleX"], colorVector["ScaleY"])); - loadTexture(json["FileData"], resourcePath, function(path, type){ - widget.setBackGroundImage(path, type); - }); - return widget; }; @@ -481,7 +496,7 @@ var path = fontResource["Path"]; //resoutceType = fontResource["Type"]; if(path != null){ - if (cc.sys.isNative && cc.sys.os == cc.sys.OS_ANDROID) { + if (cc.sys.isNative) { fontName = cc.path.join(cc.loader.resPath, resourcePath, path); } else { fontName = path.match(/([^\/]+)\.ttf/); @@ -542,10 +557,6 @@ if(fontName != null) widget.setTitleFontName(fontName); - var displaystate = getParam(json["DisplayState"], true); - widget.setBright(displaystate); - widget.setEnabled(displaystate); - var textColor = json["TextColor"]; if(textColor != null) widget.setTitleColor(getColor(textColor)); @@ -560,17 +571,22 @@ widget.loadTextureDisabled(path, type); }); + 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 && cc.sys.os == cc.sys.OS_ANDROID) { + if (cc.sys.isNative) { fontName = cc.path.join(cc.loader.resPath, resourcePath, path); } else { fontName = path.match(/([^\/]+)\.ttf/); fontName = fontName ? fontName[1] : ""; } - widget._labelRenderer.setFontName(fontName); + widget.setTitleFontName(fontName); } } @@ -1045,7 +1061,7 @@ var path = fontResource["Path"]; //resoutceType = fontResource["Type"]; if(path != null){ - if (cc.sys.isNative && cc.sys.os == cc.sys.OS_ANDROID) { + if (cc.sys.isNative) { fontName = cc.path.join(cc.loader.resPath, resourcePath, path); } else { fontName = path.match(/([^\/]+)\.ttf/); @@ -1064,7 +1080,9 @@ if (!widget.isIgnoreContentAdaptWithSize()) setContentSize(widget, json["Size"]); - //widget.getVirtualRenderer().setLineBreakWithoutSpace(true); + + if (cc.sys.isNative) + widget.getVirtualRenderer().setLineBreakWithoutSpace(true); return widget; From 0236a3963185a1309dfda35d91634d1b5bebf637 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Sun, 25 Jan 2015 17:02:36 +0800 Subject: [PATCH 0214/1345] #14843 Fixed ColorFrame throw error --- extensions/cocostudio/timeline/Frame.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/extensions/cocostudio/timeline/Frame.js b/extensions/cocostudio/timeline/Frame.js index 8b39c62ca6..89a755f4fe 100644 --- a/extensions/cocostudio/timeline/Frame.js +++ b/extensions/cocostudio/timeline/Frame.js @@ -975,15 +975,18 @@ ccs.ColorFrame = ccs.Frame.extend({ */ apply: function(percent){ if (this._tween && (this._betweenAlpha !=0 || this._betweenRed != 0 || this._betweenGreen != 0 || this._betweenBlue != 0)){ - var alpha = this._alpha + this._betweenAlpha * percent; var color = cc.color(255, 255, 255); color.r = this._color.r + this._betweenRed * percent; color.g = this._color.g + this._betweenGreen * percent; color.b = this._color.b + this._betweenBlue * percent; - this._node.setOpacity(alpha); this._node.setColor(color); + if(this._alpha != null){ + var alpha = this._alpha + this._betweenAlpha * percent; + this._node.setOpacity(alpha); + } + } }, From f66d3fef3a040c29cfb3fde3d787a69097632462 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Sun, 25 Jan 2015 17:03:01 +0800 Subject: [PATCH 0215/1345] #14843 Fixed ColorFrame throw error --- .../cocostudio/loader/parsers/action-2.x.js | 3 +- .../loader/parsers/timelineParser-2.x.js | 38 +++++++++++-------- 2 files changed, 24 insertions(+), 17 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/action-2.x.js b/extensions/cocostudio/loader/parsers/action-2.x.js index f57709f8ad..e04dd83017 100644 --- a/extensions/cocostudio/loader/parsers/action-2.x.js +++ b/extensions/cocostudio/loader/parsers/action-2.x.js @@ -216,7 +216,8 @@ frames.forEach(function(frameData){ var frame = item.handle(frameData, resourcePath); frame.setFrameIndex(frameData["FrameIndex"]); - frame.setTween(frameData["Tween"]); + var tween = frameData["Tween"] != null ? frameData["Tween"] : true; + frame.setTween(tween); timeline.addFrame(frame); }); } diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 3d33210d68..096e1a3725 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -380,7 +380,8 @@ widget.setBackGroundColorType(colorType); var bgColorOpacity = getParam(json["BackColorAlpha"], 255); - widget.setBackGroundColorOpacity(bgColorOpacity); + if(bgColorOpacity != null) + widget.setBackGroundColorOpacity(bgColorOpacity); var backGroundScale9Enabled = json["Scale9Enable"]; if(backGroundScale9Enabled != null) @@ -490,7 +491,6 @@ if(isCustomSize != null) widget.ignoreContentAdaptWithSize(!isCustomSize); - //todo check it var fontResource = json["FontResource"]; if(fontResource != null){ var path = fontResource["Path"]; @@ -647,22 +647,25 @@ widget.setBackGroundColorType(colorType); var bgColorOpacity = json["BackColorAlpha"]; - if(bgColorOpacity) + 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; - - //todo please check it - setContentSize(widget, json["Size"]); + 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"]); + } var firstColor = json["FirstColor"]; var endColor = json["EndColor"]; @@ -857,7 +860,8 @@ var colorVector = json["ColorVector"]; if(colorVector != null && colorVector["ScaleX"] != null && colorVector["ScaleY"] != null) widget.setBackGroundColorVector(colorVector["ScaleX"], colorVector["ScaleY"]); - widget.setBackGroundColorOpacity(bgColorOpacity); + if(bgColorOpacity != null) + widget.setBackGroundColorOpacity(bgColorOpacity); loadTexture(json["FileData"], resourcePath, function(path, type){ widget.setBackGroundImage(path, type); @@ -952,7 +956,8 @@ var colorVector = json["ColorVector"]; if(colorVector != null && colorVector["ScaleX"] != null && colorVector["ScaleY"] != null) widget.setBackGroundColorVector(colorVector["ScaleX"], colorVector["ScaleY"]); - widget.setBackGroundColorOpacity(bgColorOpacity); + if(bgColorOpacity != null) + widget.setBackGroundColorOpacity(bgColorOpacity); loadTexture(json["FileData"], resourcePath, function(path, type){ @@ -1078,11 +1083,12 @@ if(color != null) widget.setTextColor(getColor(color)); - if (!widget.isIgnoreContentAdaptWithSize()) + if (!widget.isIgnoreContentAdaptWithSize()){ setContentSize(widget, json["Size"]); + if (cc.sys.isNative) + widget.getVirtualRenderer().setLineBreakWithoutSpace(true); + } - if (cc.sys.isNative) - widget.getVirtualRenderer().setLineBreakWithoutSpace(true); return widget; From 2b1267f3ac6d9a6ea9f6128de58184d5a4d87615 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Mon, 26 Jan 2015 15:17:39 +0800 Subject: [PATCH 0216/1345] Fixed #2024: Added font-style and font-weight functions to cc.LabelTTF --- cocos2d/core/labelttf/CCLabelTTF.js | 39 ++++++++++++++++--- .../labelttf/CCLabelTTFCanvasRenderCmd.js | 19 +++++---- 2 files changed, 45 insertions(+), 13 deletions(-) diff --git a/cocos2d/core/labelttf/CCLabelTTF.js b/cocos2d/core/labelttf/CCLabelTTF.js index e9847c0fe7..db818091b6 100644 --- a/cocos2d/core/labelttf/CCLabelTTF.js +++ b/cocos2d/core/labelttf/CCLabelTTF.js @@ -96,6 +96,10 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ _lineHeight: 0, + //for web + _fontStyle: "normal", + _fontWeight: "normal", + /** * Initializes the cc.LabelTTF with a font name, alignment, dimension and font size, do not call it by yourself, * you should pass the correct arguments in constructor to initialize the label. @@ -126,7 +130,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ this._vAlignment = vAlignment; this._fontSize = fontSize; - this._renderCmd._setFontStyle(this._fontName, fontSize); + this._renderCmd._setFontStyle(this._fontName, fontSize, this._fontStyle, this._fontWeight); this.string = strInfo; this._renderCmd._setColorsString(); this._renderCmd._updateTexture(); @@ -500,7 +504,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ this._fontName = textDefinition.fontName; this._fontSize = textDefinition.fontSize || 12; - this._renderCmd._setFontStyle(this._fontName, this._fontSize) + this._renderCmd._setFontStyle(this._fontName, this._fontSize, this._fontStyle, this._fontWeight); // shadow if (textDefinition.shadowEnabled) @@ -666,7 +670,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ setFontSize: function (fontSize) { if (this._fontSize !== fontSize) { this._fontSize = fontSize; - this._renderCmd._setFontStyle(this._fontName, this._fontSize); + this._renderCmd._setFontStyle(this._fontName, this._fontSize, this._fontStyle, this._fontWeight); // Force update this._setUpdateTextureDirty(); } @@ -679,7 +683,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ setFontName: function (fontName) { if (this._fontName && this._fontName != fontName) { this._fontName = fontName; - this._renderCmd._setFontStyle(this._fontName, this._fontSize); + this._renderCmd._setFontStyle(this._fontName, this._fontSize, this._fontStyle, this._fontWeight); // Force update this._setUpdateTextureDirty(); } @@ -693,7 +697,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ if (res) { this._fontSize = parseInt(res[1]); this._fontName = res[2]; - this._renderCmd._setFontStyle(this._fontName, this._fontSize); + this._renderCmd._setFontStyle(this._fontName, this._fontSize, this._fontStyle, this._fontWeight); // Force update this._setUpdateTextureDirty(); @@ -731,6 +735,31 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ return new cc.LabelTTF.CanvasRenderCmd(this); else return new cc.LabelTTF.WebGLRenderCmd(this); + }, + + //For web only + _setFontStyle: function(fontStyle){ + if (this._fontStyle != fontStyle) { + this._fontStyle = fontStyle; + this._renderCmd._setFontStyle(this._fontName, this._fontSize, this._fontStyle, this._fontWeight); + this._setUpdateTextureDirty(); + } + }, + + _getFontStyle: function(){ + return this._fontStyle; + }, + + _setFontWeight: function(fontWeight){ + if (this._fontWeight != fontWeight) { + this._fontWeight = fontWeight; + this._renderCmd._setFontStyle(this._fontName, this._fontSize, this._fontStyle, this._fontWeight); + this._setUpdateTextureDirty(); + } + }, + + _getFontWeight: function(){ + return this._fontWeight; } }); diff --git a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js index a851398cfe..835175bd50 100644 --- a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js +++ b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js @@ -72,8 +72,8 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; return this._labelContext; }; - proto._setFontStyle = function (fontName, fontSize) { - this._fontStyleStr = fontSize + "px '" + fontName + "'"; + proto._setFontStyle = function (fontName, fontSize, fontStyle, fontWeight) { + this._fontStyleStr = fontStyle + " " + fontWeight + " " + fontSize + "px '" + fontName + "'"; this._fontClientHeight = cc.LabelTTF.__getFontHeightByDiv(fontName, fontSize); }; @@ -161,21 +161,24 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; //get offset for stroke and shadow if (locDimensionsWidth === 0) { if (this._isMultiLine) - locSize = cc.size(0 | (Math.max.apply(Math, locLineWidth) + locStrokeShadowOffsetX), - 0 | ((this._fontClientHeight * this._strings.length) + locStrokeShadowOffsetY)); + locSize = cc.size(Math.ceil(Math.max.apply(Math, locLineWidth) + locStrokeShadowOffsetX), + Math.ceil((this._fontClientHeight * this._strings.length) + locStrokeShadowOffsetY)); else - locSize = cc.size(0 | (this._measure(node._string) + locStrokeShadowOffsetX), 0 | (this._fontClientHeight + locStrokeShadowOffsetY)); + locSize = cc.size(Math.ceil(this._measure(node._string) + locStrokeShadowOffsetX), Math.ceil(this._fontClientHeight + locStrokeShadowOffsetY)); } else { if (node._dimensions.height === 0) { if (this._isMultiLine) - locSize = cc.size(0 | (locDimensionsWidth + locStrokeShadowOffsetX), 0 | ((node.getLineHeight() * this._strings.length) + locStrokeShadowOffsetY)); + locSize = cc.size(Math.ceil(locDimensionsWidth + locStrokeShadowOffsetX), Math.ceil((node.getLineHeight() * this._strings.length) + locStrokeShadowOffsetY)); else - locSize = cc.size(0 | (locDimensionsWidth + locStrokeShadowOffsetX), 0 | (node.getLineHeight() + locStrokeShadowOffsetY)); + locSize = cc.size(Math.ceil(locDimensionsWidth + locStrokeShadowOffsetX), Math.ceil(node.getLineHeight() + locStrokeShadowOffsetY)); } else { //dimension is already set, contentSize must be same as dimension - locSize = cc.size(0 | (locDimensionsWidth + locStrokeShadowOffsetX), 0 | (node._dimensions.height + locStrokeShadowOffsetY)); + locSize = cc.size(Math.ceil(locDimensionsWidth + locStrokeShadowOffsetX), Math.ceil(node._dimensions.height + locStrokeShadowOffsetY)); } } + if(node._getFontStyle() != "normal"){ //add width for 'italic' and 'oblique' + locSize.width = Math.ceil(locSize.width + node._fontSize * 0.3); + } node.setContentSize(locSize); node._strokeShadowOffsetX = locStrokeShadowOffsetX; node._strokeShadowOffsetY = locStrokeShadowOffsetY; From fdbddaa32578d3726d98199f0c8be2279bc484ff Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 26 Jan 2015 15:46:43 +0800 Subject: [PATCH 0217/1345] canvas transform --- .../core/base-nodes/CCNodeCanvasRenderCmd.js | 89 ++++++++++--------- 1 file changed, 49 insertions(+), 40 deletions(-) diff --git a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js index 671d259538..aa1c39e09f 100644 --- a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js @@ -242,6 +242,11 @@ cc.Node.RenderCmd.prototype = { cc.Node.RenderCmd.call(this, renderable); this._cachedParent = null; this._cacheDirty = false; + + this._orginalPoint = { + x: 0, + y: 0 + }; }; var proto = cc.Node.CanvasRenderCmd.prototype = Object.create(cc.Node.RenderCmd.prototype); @@ -255,16 +260,13 @@ cc.Node.RenderCmd.prototype = { 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 - - var plt = parentCmd._transform; - var xOffset = -(plt.b + plt.c) * t.ty; - var yOffset = -(plt.b + plt.c) * t.tx; - worldT.tx = (t.tx * pt.a + t.ty * pt.c + pt.tx + xOffset); //tx - worldT.ty = (t.tx * pt.b + t.ty * pt.d + pt.ty + yOffset); //ty + worldT.a = pt.a * t.a + pt.b * t.c; //a + worldT.b = pt.a * t.b + pt.b * t.d; //b + worldT.c = pt.c * t.a + pt.d * t.c; //c + worldT.d = pt.c * t.b + pt.d * t.d; //d + + worldT.tx = pt.a * t.tx + pt.b * t.ty + pt.tx ; + worldT.ty = pt.c * t.tx + pt.d * t.ty + pt.ty; } else { worldT.a = t.a; worldT.b = t.b; @@ -301,17 +303,23 @@ cc.Node.RenderCmd.prototype = { t.ty = node._position.y; // rotation Cos and Sin - var Cos = 1, Sin = 0; + var A = 1, B = 0, + C = 0, D = 1; if (node._rotationX) { var rotationRadiansX = node._rotationX * 0.017453292519943295; //0.017453292519943295 = (Math.PI / 180); for performance - Cos = Math.cos(rotationRadiansX); - Sin = Math.sin(rotationRadiansX); + B = -Math.sin(rotationRadiansX); + D = Math.cos(rotationRadiansX); } - // base abcd - t.a = t.d = Cos; - t.b = -Sin; - t.c = Sin; + if (node._rotationY) { + var rotationRadiansY = node._rotationY * 0.017453292519943295; //0.017453292519943295 = (Math.PI / 180); for performance + A = Math.cos(rotationRadiansY); + C = Math.sin(rotationRadiansY); + } + t.a = A; + t.b = B; + t.c = C; + t.d = D; var lScaleX = node._scaleX, lScaleY = node._scaleY; var appX = this._anchorPointInPoints.x, appY = this._anchorPointInPoints.y; @@ -321,6 +329,14 @@ cc.Node.RenderCmd.prototype = { var sx = (lScaleX < 0.000001 && lScaleX > -0.000001) ? 0.000001 : lScaleX, sy = (lScaleY < 0.000001 && lScaleY > -0.000001) ? 0.000001 : lScaleY; + // scale + if (lScaleX !== 1 || lScaleY !== 1) { + t.a *= sx; + t.c *= sx; + t.b *= sy; + t.d *= sy; + } + // skew if (node._skewX || node._skewY) { // offset the anchorpoint @@ -332,31 +348,24 @@ cc.Node.RenderCmd.prototype = { sky = 99999999; var xx = appY * skx * sx; var yy = appX * sky * sy; - t.a = Cos + -Sin * sky; - t.b = Cos * skx + -Sin; - t.c = Sin + Cos * sky; - t.d = Sin * skx + Cos; - t.tx += Cos * xx + -Sin * yy; - t.ty += Sin * xx + Cos * yy; + t.a = A + B * sky; + t.b = A * skx + B; + t.c = C + D * sky; + t.d = C * skx + D; + t.tx += A * xx + B * yy; + t.ty += C * xx + D * yy; } - // scale - if (lScaleX !== 1 || lScaleY !== 1) { - t.a *= sx; - t.c *= sx; - t.b *= sy; - t.d *= sy; - } - - // adjust anchorPoint - t.tx += Cos * -appX * sx + -Sin * appY * sy; - t.ty -= Sin * -appX * sx + Cos * appY * sy; - - // if ignore anchorPoint - if (node._ignoreAnchorPointForPosition) { - t.tx += appX; - t.ty += appY; - } +// var appX = this._anchorPointInPoints.x, appY = this._anchorPointInPoints.y; +// // adjust anchorPoint +// t.tx += A * -appX * sx + B * appY * sy; +// t.ty -= C * -appX * sx + D * appY * sy; +// +// // if ignore anchorPoint +// if (node._ignoreAnchorPointForPosition) { +// t.tx += appX; +// t.ty += appY; +// } if (node._additionalTransformDirty) { this._transform = cc.affineTransformConcat(t, node._additionalTransform); From 62316eec21e3c3fac8a2027eec6f38aa77bef6ba Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 26 Jan 2015 19:53:04 +0800 Subject: [PATCH 0218/1345] #14901 Update InnerFrame --- .../cocostudio/timeline/ActionTimeline.js | 2 +- extensions/cocostudio/timeline/Frame.js | 62 ++++++++++++++++++- extensions/cocostudio/timeline/Timeline.js | 4 +- 3 files changed, 63 insertions(+), 5 deletions(-) diff --git a/extensions/cocostudio/timeline/ActionTimeline.js b/extensions/cocostudio/timeline/ActionTimeline.js index 7bf9b7aed8..bc5a60cc00 100644 --- a/extensions/cocostudio/timeline/ActionTimeline.js +++ b/extensions/cocostudio/timeline/ActionTimeline.js @@ -374,7 +374,7 @@ ccs.ActionTimeline = cc.Action.extend({ } this._time += delta * this._timeSpeed; - this._currentFrame = this._time / this._frameInternal; + this._currentFrame = this._time / this._frameInternal | 0; this._stepToFrame(this._currentFrame); diff --git a/extensions/cocostudio/timeline/Frame.js b/extensions/cocostudio/timeline/Frame.js index 89a755f4fe..a813e07ca4 100644 --- a/extensions/cocostudio/timeline/Frame.js +++ b/extensions/cocostudio/timeline/Frame.js @@ -859,6 +859,11 @@ ccs.InnerActionFrame = ccs.Frame.extend({ _innerActionType: null, _startFrameIndex: null, + _endFrameIndex:0, + _singleFrameIndex: 0, + _enterWithName: false, + _animationName: "", + ctor: function(){ ccs.Frame.prototype.ctor.call(this); @@ -871,7 +876,62 @@ ccs.InnerActionFrame = ccs.Frame.extend({ * @param {ccs.Frame} nextFrame */ onEnter: function(nextFrame){ - //override + var innerActiontimeline = this._node.getActionByTag(this._node.getTag()); + if (/*ccs.InnerActionType.SingleFrame*/"SingleFrame" == this._innerActionType){ + innerActiontimeline.gotoFrameAndPause(this._singleFrameIndex); + return; + } + + var innerStart = this._startFrameIndex; + var innerEnd = this._endFrameIndex; + if (this._enterWithName){ + if (this._animationName == "-- ALL --"){ + innerStart = 0; + innerEnd = innerActiontimeline.getDuration(); + } else if(innerActiontimeline.IsAnimationInfoExists(this._animationName)) { + var info = innerActiontimeline.getAnimationInfo(this._animationName); + innerStart = info.startIndex; + innerEnd = info.endIndex; + }else{ + cc.log("Animation %s not exists!", this._animationName); + } + } + + var duration = this._timeline.getActionTimeline().getDuration(); + var odddiff = duration - this._frameIndex - innerEnd + innerStart; + if (odddiff < 0){ + innerEnd += odddiff; + } + + if (/*ccs.InnerActionType.NoLoopAction*/"NoLoopAction" == this._innerActionType){ + innerActiontimeline.gotoFrameAndPlay(innerStart, innerEnd, false); + }else if (/*ccs.InnerActionType.LoopAction*/"LoopAction" == this._innerActionType){ + innerActiontimeline.gotoFrameAndPlay(innerStart, innerEnd, true); + } + }, + + setAnimationName: function(animationName){ + if(!this._enterWithName){ + cc.log(" cannot set aniamtioname when enter frame with index. setEnterWithName true firstly!"); + }else{ + this._animationName = animationName; + } + }, + + setSingleFrameIndex: function(frameIndex){ + this._singleFrameIndex = frameIndex; + }, + + getSingleFrameIndex: function(){ + return this._startFrameIndex; + }, + + setEnterWithName: function(isEnterWithName){ + this._enterWithName = isEnterWithName; + }, + + getEnterWithName: function(){ + return this._enterWithName; }, /** diff --git a/extensions/cocostudio/timeline/Timeline.js b/extensions/cocostudio/timeline/Timeline.js index 176c35419c..783d97fd26 100644 --- a/extensions/cocostudio/timeline/Timeline.js +++ b/extensions/cocostudio/timeline/Timeline.js @@ -134,12 +134,10 @@ ccs.Timeline = ccs.Class.extend({ * @param {cc.Node} node */ setNode: function(node){ - for (var i=0; i Date: Mon, 26 Jan 2015 19:53:26 +0800 Subject: [PATCH 0219/1345] #14901 Add actionValue parser --- extensions/cocostudio/loader/load.js | 2 ++ .../cocostudio/loader/parsers/action-2.x.js | 20 +++++++++++++++++++ .../loader/parsers/timelineParser-2.x.js | 13 +++++++++--- 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/extensions/cocostudio/loader/load.js b/extensions/cocostudio/loader/load.js index e031a7dbff..8d893ae562 100644 --- a/extensions/cocostudio/loader/load.js +++ b/extensions/cocostudio/loader/load.js @@ -180,6 +180,8 @@ ccs.load = function(file){ object.node = ccs._load(file); object.action = ccs._load(file, "action"); + if(object.action && object.action.tag === -1) + object.action.tag = object.node.tag; return object; }; diff --git a/extensions/cocostudio/loader/parsers/action-2.x.js b/extensions/cocostudio/loader/parsers/action-2.x.js index e04dd83017..0cae03dfeb 100644 --- a/extensions/cocostudio/loader/parsers/action-2.x.js +++ b/extensions/cocostudio/loader/parsers/action-2.x.js @@ -201,6 +201,26 @@ var frame = new ccs.ZOrderFrame(); var zorder = options["Value"]; frame.setZOrder(zorder); + return frame; + } + }, + { + name: "ActionValue", + handle: function(options){ + + var frame = new ccs.InnerActionFrame(); + var innerActionType = options["InnerActionType"]; + + var currentAnimationFrame = options["CurrentAniamtionName"]; + + var singleFrameIndex = options["SingleFrameIndex"]; + + frame.setInnerActionType(innerActionType); + frame.setSingleFrameIndex(singleFrameIndex); + + frame.setEnterWithName(true); + frame.setAnimationName(currentAnimationFrame); + return frame; } } diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 096e1a3725..39d586e363 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -1145,9 +1145,16 @@ var projectFile = json["FileData"]; if(projectFile != null && projectFile["Path"]){ var file = resourcePath + projectFile["Path"]; - if(cc.loader.getRes(file)) - return ccs._load(file); - else + if(cc.loader.getRes(file)){ + var obj = ccs.load(file); + parser.generalAttributes(obj.node, json); + if(obj.action){ + obj.action.tag = obj.node.tag; + obj.node.runAction(obj.action); + obj.action.gotoFrameAndPause(0); + } + return obj.node; + } else cc.log("%s need to be preloaded", file); } }; From 0275ba6fd32e836ceb35dbc3668e0b8fe627c5cc Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 26 Jan 2015 20:20:53 +0800 Subject: [PATCH 0220/1345] #14897 Fixed setBackGroundColorVector --- extensions/cocostudio/loader/parsers/timelineParser-2.x.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 39d586e363..59a123024f 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -859,7 +859,7 @@ var colorVector = json["ColorVector"]; if(colorVector != null && colorVector["ScaleX"] != null && colorVector["ScaleY"] != null) - widget.setBackGroundColorVector(colorVector["ScaleX"], colorVector["ScaleY"]); + widget.setBackGroundColorVector(cc.p(colorVector["ScaleX"], colorVector["ScaleY"])); if(bgColorOpacity != null) widget.setBackGroundColorOpacity(bgColorOpacity); @@ -955,7 +955,7 @@ var colorVector = json["ColorVector"]; if(colorVector != null && colorVector["ScaleX"] != null && colorVector["ScaleY"] != null) - widget.setBackGroundColorVector(colorVector["ScaleX"], colorVector["ScaleY"]); + widget.setBackGroundColorVector(cc.p(colorVector["ScaleX"], colorVector["ScaleY"])); if(bgColorOpacity != null) widget.setBackGroundColorOpacity(bgColorOpacity); From 05aec015c3158f22596ec80e13bef19948e852b7 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 26 Jan 2015 20:26:53 +0800 Subject: [PATCH 0221/1345] #14890 Fixed clipEnable error --- .../loader/parsers/timelineParser-2.x.js | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 59a123024f..1ed6131218 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -639,9 +639,8 @@ this.widgetAttributes(widget, json); - var clipEnabled = json["ClipAble"]; - if(clipEnabled) - widget.setClippingEnabled(true); + var clipEnabled = json["ClipAble"] || false; + widget.setClippingEnabled(clipEnabled); var colorType = getParam(json["ComboBoxIndex"], 0); widget.setBackGroundColorType(colorType); @@ -822,9 +821,8 @@ this.widgetAttributes(widget, json); - var clipEnabled = json["ClipAble"]; - if(clipEnabled) - widget.setClippingEnabled(true); + var clipEnabled = json["ClipAble"] || false; + widget.setClippingEnabled(clipEnabled); var backGroundScale9Enabled = json["Scale9Enable"]; if(backGroundScale9Enabled){ @@ -885,9 +883,8 @@ this.widgetAttributes(widget, json); - var clipEnabled = json["ClipAble"]; - if(clipEnabled) - widget.setClippingEnabled(true); + var clipEnabled = json["ClipAble"] || false; + widget.setClippingEnabled(clipEnabled); var colorType = getParam(json["ComboBoxIndex"], 0); widget.setBackGroundColorType(colorType); From a89a3308331a0064fc8dd491b5cc506715617151 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 26 Jan 2015 20:59:59 +0800 Subject: [PATCH 0222/1345] #14891 param error --- .../loader/parsers/timelineParser-2.x.js | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 1ed6131218..dd44818d1f 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -280,8 +280,10 @@ var scale = json["Scale"]; if(scale != null){ - widget.setScaleX(scale["ScaleX"] || 1); - widget.setScaleY(scale["ScaleY"] || 1); + var scaleX = getParam(scale["ScaleX"], 1); + var scaleY = getParam(scale["ScaleY"], 1); + widget.setScaleX(scaleX); + widget.setScaleY(scaleY); } var anchorPoint = json["AnchorPoint"]; @@ -387,7 +389,7 @@ if(backGroundScale9Enabled != null) widget.setBackGroundImageScale9Enabled(backGroundScale9Enabled); - var opacity = json["Alpha"] || 255; + var opacity = getParam(json["Alpha"], 255); widget.setOpacity(opacity); loadTexture(json["FileData"], resourcePath, function(path, type){ @@ -639,7 +641,7 @@ this.widgetAttributes(widget, json); - var clipEnabled = json["ClipAble"] || false; + var clipEnabled = json["ClipAble"]; widget.setClippingEnabled(clipEnabled); var colorType = getParam(json["ComboBoxIndex"], 0); @@ -680,7 +682,9 @@ var colorVector = json["ColorVector"]; if(colorVector){ - widget.setBackGroundColorVector(cc.p(colorVector["ScaleX"] || 1, colorVector["ScaleY"] || 1)); + var colorVectorX = getParam(colorVector["ScaleX"], 1); + var colorVectorY = getParam(colorVector["ScaleY"], 1); + widget.setBackGroundColorVector(cc.p(colorVectorX, colorVectorY)); } loadTexture(json["FileData"], resourcePath, function(path, type){ @@ -924,7 +928,7 @@ else if (horizontalType == "Align_Right") widget.setGravity(ccui.ListView.GRAVITY_RIGHT); else if (horizontalType == "Align_HorizontalCenter") - widget.setGravity(ccui.ListView.GRAVITY_CENTER_VERTICAL); + widget.setGravity(ccui.ListView.GRAVITY_CENTER_HORIZONTAL); } From 0e65a1f0567769465c885f8b3fcd63a9b5d64de4 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 26 Jan 2015 21:03:12 +0800 Subject: [PATCH 0223/1345] #14885 #14886 --- extensions/cocostudio/loader/parsers/timelineParser-2.x.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index dd44818d1f..d3df868603 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -374,7 +374,7 @@ this.widgetAttributes(widget, json); - var clipEnabled = json["ClipAple"]; + var clipEnabled = json["ClipAble"]; if(clipEnabled != null) widget.setClippingEnabled(clipEnabled); @@ -693,8 +693,8 @@ var innerNodeSize = json["InnerNodeSize"]; var innerSize = cc.size( - innerNodeSize["width"] || 0, - innerNodeSize["height"] || 0 + innerNodeSize["Width"] || 0, + innerNodeSize["Height"] || 0 ); widget.setInnerContainerSize(innerSize); From af2bbee86248b17a30f2582adef9814f622a8e0e Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Mon, 26 Jan 2015 21:07:06 +0800 Subject: [PATCH 0224/1345] Fixed a bug of cc.Tween that its _currentPercent is wrong in updateHandler function --- .../cocostudio/armature/animation/CCArmatureAnimation.js | 7 +++---- extensions/cocostudio/armature/animation/CCTween.js | 2 +- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/extensions/cocostudio/armature/animation/CCArmatureAnimation.js b/extensions/cocostudio/armature/animation/CCArmatureAnimation.js index 42ea8b5d9d..fda7946a17 100644 --- a/extensions/cocostudio/armature/animation/CCArmatureAnimation.js +++ b/extensions/cocostudio/armature/animation/CCArmatureAnimation.js @@ -234,7 +234,7 @@ ccs.ArmatureAnimation = ccs.ProcessBase.extend(/** @lends ccs.ArmatureAnimation# * play animation by animation name. * @param {String} animationName The animation name you want to play * @param {Number} [durationTo=-1] - * he frames between two animation changing-over.It's meaning is changing to this animation need how many frames + * 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. @@ -278,10 +278,9 @@ ccs.ArmatureAnimation = ccs.ProcessBase.extend(/** @lends ccs.ArmatureAnimation# this._durationTween = durationTween; } - var movementBoneData; - this._tweenList = []; + this._tweenList.length = 0; - var map = this._armature.getBoneDic(); + var movementBoneData, map = this._armature.getBoneDic(); for(var element in map) { var bone = map[element]; movementBoneData = this._movementData.movBoneDataDic[bone.getName()]; diff --git a/extensions/cocostudio/armature/animation/CCTween.js b/extensions/cocostudio/armature/animation/CCTween.js index 2139e7f46c..f35dbb9f33 100644 --- a/extensions/cocostudio/armature/animation/CCTween.js +++ b/extensions/cocostudio/armature/animation/CCTween.js @@ -156,7 +156,7 @@ ccs.Tween = ccs.ProcessBase.extend(/** @lends ccs.Tween# */{ * update will call this handler, you can handle your logic here */ updateHandler:function () { - var locCurrentPercent = this._currentPercent || 1; + var locCurrentPercent = this._currentPercent == null ? 1 : this._currentPercent; var locLoopType = this._loopType; if (locCurrentPercent >= 1) { switch (locLoopType) { From 5deec86b9a9884fb0db94501a1febb46b6322d5e Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 26 Jan 2015 21:41:56 +0800 Subject: [PATCH 0225/1345] #14883 Add LayerObjectData parser --- extensions/cocostudio/loader/load.js | 2 +- extensions/cocostudio/loader/parsers/timelineParser-2.x.js | 7 ++++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/extensions/cocostudio/loader/load.js b/extensions/cocostudio/loader/load.js index 8d893ae562..ec49ad7e9a 100644 --- a/extensions/cocostudio/loader/load.js +++ b/extensions/cocostudio/loader/load.js @@ -180,7 +180,7 @@ ccs.load = function(file){ object.node = ccs._load(file); object.action = ccs._load(file, "action"); - if(object.action && object.action.tag === -1) + if(object.action && object.action.tag === -1 && object.node) object.action.tag = object.node.tag; return object; }; diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index d3df868603..53edf4ceba 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -1131,6 +1131,8 @@ loadTexture(json["FileData"], resourcePath, function(path, type){ if(type == 0) node = new cc.TMXTiledMap(path); + + parser.generalAttributes(node, json); }); return node; @@ -1149,7 +1151,7 @@ if(cc.loader.getRes(file)){ var obj = ccs.load(file); parser.generalAttributes(obj.node, json); - if(obj.action){ + if(obj.action && obj.node){ obj.action.tag = obj.node.tag; obj.node.runAction(obj.action); obj.action.gotoFrameAndPause(0); @@ -1184,6 +1186,8 @@ var currentAnimationName = json["CurrentAnimationName"]; + parser.generalAttributes(node, json); + loadTexture(json["FileData"], resourcePath, function(path, type){ var plists, pngs; var armJson = cc.loader.getRes(path); @@ -1249,6 +1253,7 @@ var register = [ {name: "SingleNodeObjectData", handle: parser.initSingleNode}, + {name: "LayerObjectData", handle: parser.initSingleNode}, {name: "SpriteObjectData", handle: parser.initSprite}, {name: "ParticleObjectData", handle: parser.initParticle}, {name: "PanelObjectData", handle: parser.initPanel}, From dc1eb8efa34eb610a7a2451a670b593563708f15 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 26 Jan 2015 22:00:54 +0800 Subject: [PATCH 0226/1345] parser error --- extensions/cocostudio/loader/parsers/action-2.x.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/cocostudio/loader/parsers/action-2.x.js b/extensions/cocostudio/loader/parsers/action-2.x.js index 0cae03dfeb..e5a0cad7c7 100644 --- a/extensions/cocostudio/loader/parsers/action-2.x.js +++ b/extensions/cocostudio/loader/parsers/action-2.x.js @@ -215,7 +215,7 @@ var singleFrameIndex = options["SingleFrameIndex"]; - frame.setInnerActionType(innerActionType); + frame.setInnerActionType(ccs.InnerActionType[innerActionType]); frame.setSingleFrameIndex(singleFrameIndex); frame.setEnterWithName(true); From 055d55bdf3f9640b899c698f3f3396a298e933af Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 26 Jan 2015 22:49:02 +0800 Subject: [PATCH 0227/1345] action parser error --- .../cocostudio/loader/parsers/action-2.x.js | 16 ++++++++++++++++ extensions/cocostudio/timeline/Frame.js | 4 ++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/action-2.x.js b/extensions/cocostudio/loader/parsers/action-2.x.js index e5a0cad7c7..8916285cbf 100644 --- a/extensions/cocostudio/loader/parsers/action-2.x.js +++ b/extensions/cocostudio/loader/parsers/action-2.x.js @@ -43,6 +43,7 @@ action.setDuration(json["Duration"]); action.setTimeSpeed(json["Speed"] || 1); + //The process of analysis var timelines = json["Timelines"]; timelines.forEach(function(timeline){ @@ -59,6 +60,21 @@ cache[file] = action; cache[file].retain(); return action.clone(); + }, + + deferred: function(json, resourcePath, action, file){ + if(cc.sys.isNative) { + var animationlist = json["Content"]["Content"]["AnimationList"]; + var length = animationlist ? animationlist.length : 0; + for (var i = 0; i < length; i++) { + var animationdata = animationlist[i]; + var info = { name: null, startIndex: null, endIndex: null }; + info.name = animationdata["Name"]; + info.startIndex = animationdata["StartIndex"]; + info.endIndex = animationdata["EndIndex"]; + action.addAnimationInfo(info); + } + } } }); diff --git a/extensions/cocostudio/timeline/Frame.js b/extensions/cocostudio/timeline/Frame.js index a813e07ca4..83013aa842 100644 --- a/extensions/cocostudio/timeline/Frame.js +++ b/extensions/cocostudio/timeline/Frame.js @@ -903,9 +903,9 @@ ccs.InnerActionFrame = ccs.Frame.extend({ innerEnd += odddiff; } - if (/*ccs.InnerActionType.NoLoopAction*/"NoLoopAction" == this._innerActionType){ + if (ccs.InnerActionType.NoLoopAction == this._innerActionType){ innerActiontimeline.gotoFrameAndPlay(innerStart, innerEnd, false); - }else if (/*ccs.InnerActionType.LoopAction*/"LoopAction" == this._innerActionType){ + }else if (ccs.InnerActionType.LoopAction == this._innerActionType){ innerActiontimeline.gotoFrameAndPlay(innerStart, innerEnd, true); } }, From f82c62b85d9ac338597fa9975219fb3ddc835d09 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 27 Jan 2015 00:04:26 +0800 Subject: [PATCH 0228/1345] #14831 Scale9Sprite error --- .../loader/parsers/timelineParser-2.x.js | 52 +++++++++---------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 53edf4ceba..811086e193 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -526,27 +526,21 @@ var widget = new ccui.Button(); - this.widgetAttributes(widget, json); + 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){ + if(scale9Enabled) { widget.setScale9Enabled(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"]); - var text = json["ButtonText"]; if(text != null) widget.setTitleText(text); @@ -563,16 +557,6 @@ if(textColor != null) widget.setTitleColor(getColor(textColor)); - 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 displaystate = getParam(json["DisplayState"], true); widget.setBright(displaystate); widget.setEnabled(displaystate); @@ -591,6 +575,22 @@ widget.setTitleFontName(fontName); } } + 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; From 942d2469d3a033e62ee9e60913df79ecbfb924c8 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 27 Jan 2015 00:14:07 +0800 Subject: [PATCH 0229/1345] #14830 --- .../loader/parsers/timelineParser-2.x.js | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 811086e193..29094dd81d 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -607,13 +607,6 @@ this.widgetAttributes(widget, json); - var selectedState = getParam(json["CheckedState"], false); - widget.setSelected(selectedState); - - var displaystate = getParam(json["DisplayState"], true); - widget.setBright(displaystate); - widget.setEnabled(displaystate); - var dataList = [ {name: "NormalBackFileData", handle: widget.loadTextureBackGround}, {name: "PressedBackFileData", handle: widget.loadTextureBackGroundSelected}, @@ -628,6 +621,13 @@ }); }); + var selectedState = getParam(json["CheckedState"], false); + widget.setSelected(selectedState); + + var displaystate = getParam(json["DisplayState"], true); + widget.setBright(displaystate); + widget.setEnabled(displaystate); + return widget; }; From a9d70baf20cc9a4e6a7da976c7d959b89035a774 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Tue, 27 Jan 2015 11:36:16 +0800 Subject: [PATCH 0230/1345] Fixed cocos2d/cocos2d-js/#1267: migrated the up-to-date -x UI --- extensions/ccui/layouts/UILayoutComponent.js | 39 ++++- extensions/ccui/uiwidgets/UIButton.js | 50 +++--- extensions/ccui/uiwidgets/UIImageView.js | 8 +- extensions/ccui/uiwidgets/UILoadingBar.js | 6 +- extensions/ccui/uiwidgets/UISlider.js | 15 +- extensions/ccui/uiwidgets/UIText.js | 14 +- extensions/ccui/uiwidgets/UITextBMFont.js | 13 +- extensions/ccui/uiwidgets/UITextField.js | 23 ++- .../uiwidgets/scroll-widget/UIListView.js | 161 ++++++++---------- 9 files changed, 185 insertions(+), 144 deletions(-) diff --git a/extensions/ccui/layouts/UILayoutComponent.js b/extensions/ccui/layouts/UILayoutComponent.js index 19f3c2158a..a178d9ed8d 100644 --- a/extensions/ccui/layouts/UILayoutComponent.js +++ b/extensions/ccui/layouts/UILayoutComponent.js @@ -66,6 +66,8 @@ ccui.LayoutComponent = cc.Component.extend({ _usingPercentHeight: false, _actived: true, + _isPercentOnly: false, + ctor: function () { this._name = ccui.LayoutComponent.NAME; }, @@ -425,10 +427,17 @@ ccui.LayoutComponent = cc.Component.extend({ 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; @@ -439,7 +448,7 @@ ccui.LayoutComponent = cc.Component.extend({ switch (this._horizontalEdge) { case ccui.LayoutComponent.horizontalEdge.NONE: - if (this._usingStretchWidth) { + if (this._usingStretchWidth && !this._isPercentOnly) { ownerSize.width = parentSize.width * this._percentWidth; ownerPosition.x = this._leftMargin + ownerAnchor.x * ownerSize.width; } else { @@ -450,23 +459,32 @@ ccui.LayoutComponent = cc.Component.extend({ } 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._usingPercentWidth || this._usingStretchWidth) { + 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 + } else { + if (this._usingPercentWidth) + ownerSize.width = parentSize.width * this._percentWidth; ownerPosition.x = parentSize.width * this._positionPercentX; + } break; default: break; @@ -474,7 +492,7 @@ ccui.LayoutComponent = cc.Component.extend({ switch (this._verticalEdge) { case ccui.LayoutComponent.verticalEdge.NONE: - if (this._usingStretchHeight) { + if (this._usingStretchHeight && !this._isPercentOnly) { ownerSize.height = parentSize.height * this._percentHeight; ownerPosition.y = this._bottomMargin + ownerAnchor.y * ownerSize.height; } else { @@ -485,23 +503,32 @@ ccui.LayoutComponent = cc.Component.extend({ } 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._usingPercentHeight || this._usingStretchHeight) { + 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 + } else { + if(this._usingPercentHeight) + ownerSize.height = parentSize.height * this._percentHeight; ownerPosition.y = parentSize.height * this._positionPercentY; + } break; default: break; diff --git a/extensions/ccui/uiwidgets/UIButton.js b/extensions/ccui/uiwidgets/UIButton.js index 7f54bdabed..593992f201 100644 --- a/extensions/ccui/uiwidgets/UIButton.js +++ b/extensions/ccui/uiwidgets/UIButton.js @@ -185,6 +185,10 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ this.setCapInsetsPressedRenderer(this._capInsetsPressed); this.setCapInsetsDisabledRenderer(this._capInsetsDisabled); this.setBright(this._bright); + + this._normalTextureAdaptDirty = true; + this._pressedTextureAdaptDirty = true; + this._disabledTextureAdaptDirty = true; }, /** @@ -506,33 +510,31 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ if (this.pressedActionEnabled){ this._buttonNormalRenderer.stopAllActions(); this._buttonClickedRenderer.stopAllActions(); - var zoomAction = cc.scaleTo(ccui.Button.ZOOM_ACTION_TIME_STEP, this._normalTextureScaleXInSize, this._normalTextureScaleYInSize); - this._buttonNormalRenderer.runAction(zoomAction); + //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.runAction(zoomAction.clone()); + }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); - if(this._unifySize){ - this._titleRenderer.setScaleX(1); - this._titleRenderer.setScaleY(1); - }else{ - this._titleRenderer.setScaleX(this._normalTextureScaleXInSize); - this._titleRenderer.setScaleY(this._normalTextureScaleYInSize); - } + this._titleRenderer.setScaleX(1); + this._titleRenderer.setScaleY(1); } }, @@ -554,11 +556,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ locNormalRenderer.setScale(this._pressedTextureScaleXInSize + this._zoomScale, this._pressedTextureScaleYInSize + this._zoomScale); this._titleRenderer.stopAllActions(); - if (this._unifySize){ - var zoomTitleAction = cc.scaleTo(ccui.Button.ZOOM_ACTION_TIME_STEP, 1 + this._zoomScale, 1 + this._zoomScale); - this._titleRenderer.runAction(zoomTitleAction); - } else - this._titleRenderer.runAction(zoomAction.clone()); + this._titleRenderer.runAction(cc.scaleTo(ccui.Button.ZOOM_ACTION_TIME_STEP, 1 + this._zoomScale, 1 + this._zoomScale)); } } else { locNormalRenderer.setVisible(true); @@ -571,13 +569,8 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ locNormalRenderer.setState(ccui.Scale9Sprite.state.GRAY); this._titleRenderer.stopAllActions(); - if (this._unifySize){ - this._titleRenderer.setScaleX(1 + this._zoomScale); - this._titleRenderer.setScaleY(1 + this._zoomScale); - }else{ - this._titleRenderer.setScaleX(this._normalTextureScaleXInSize + this._zoomScale); - this._titleRenderer.setScaleY(this._normalTextureScaleYInSize + this._zoomScale); - } + this._titleRenderer.setScaleX(1 + this._zoomScale); + this._titleRenderer.setScaleY(1 + this._zoomScale); } }, @@ -831,6 +824,15 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ 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 diff --git a/extensions/ccui/uiwidgets/UIImageView.js b/extensions/ccui/uiwidgets/UIImageView.js index 9d33c6c678..7f4519bc23 100644 --- a/extensions/ccui/uiwidgets/UIImageView.js +++ b/extensions/ccui/uiwidgets/UIImageView.js @@ -174,6 +174,7 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{ } else this.ignoreContentAdaptWithSize(this._prevIgnoreSize); this.setCapInsets(this._capInsets); + this._imageRendererAdaptDirty = true; }, /** @@ -256,10 +257,11 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{ if (!this._scale9Enabled) this._imageRenderer.setScale(1.0); } else { - if (this._scale9Enabled) + if (this._scale9Enabled){ this._imageRenderer.setPreferredSize(this._contentSize); - else { - var textureSize = this._imageRenderer.getContentSize(); + this._imageRenderer.setScale(1); + } else { + var textureSize = this._imageTextureSize; if (textureSize.width <= 0.0 || textureSize.height <= 0.0) { this._imageRenderer.setScale(1.0); return; diff --git a/extensions/ccui/uiwidgets/UILoadingBar.js b/extensions/ccui/uiwidgets/UILoadingBar.js index 68f4316c1f..68cd78f917 100644 --- a/extensions/ccui/uiwidgets/UILoadingBar.js +++ b/extensions/ccui/uiwidgets/UILoadingBar.js @@ -188,6 +188,7 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{ this.ignoreContentAdaptWithSize(this._prevIgnoreSize); this.setCapInsets(this._capInsets); this.setPercent(this._percent); + this._barRendererAdaptDirty = true; }, /** @@ -328,9 +329,10 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{ } } else { this._totalLength = locContentSize.width; - if (this._scale9Enabled) + if (this._scale9Enabled){ this._setScale9Scale(); - else { + locBarRender.setScale(1.0); + } else { var textureSize = this._barRendererTextureSize; if (textureSize.width <= 0.0 || textureSize.height <= 0.0) { locBarRender.setScale(1.0); diff --git a/extensions/ccui/uiwidgets/UISlider.js b/extensions/ccui/uiwidgets/UISlider.js index 7c3b4f5f13..4c3a61fef6 100644 --- a/extensions/ccui/uiwidgets/UISlider.js +++ b/extensions/ccui/uiwidgets/UISlider.js @@ -33,6 +33,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ _barRenderer: null, _progressBarRenderer: null, + _barTextureSize: null, _progressBarTextureSize: null, _slidBallNormalRenderer: null, _slidBallPressedRenderer: null, @@ -74,6 +75,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ * var uiSlider = new ccui.Slider(); */ ctor: function (barTextureName, normalBallTextureName, resType) { + this._barTextureSize = cc.size(0,0); this._progressBarTextureSize = cc.size(0, 0); this._capInsetsBarRenderer = cc.rect(0, 0, 0, 0); this._capInsetsProgressBarRenderer = cc.rect(0, 0, 0, 0); @@ -155,6 +157,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ this._progressBarRendererDirty = true; this._updateContentSizeWithTextureSize(this._barRenderer.getContentSize()); this._findLayout(); + this._barTextureSize = this._barRenderer.getContentSize(); }, /** @@ -233,6 +236,8 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ } this.setCapInsetsBarRenderer(this._capInsetsBarRenderer); this.setCapInsetProgressBarRenderer(this._capInsetsProgressBarRenderer); + this._barRendererAdaptDirty = true; + this._progressBarRendererDirty = true; }, /** @@ -448,7 +453,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ var dis = this._barLength * res; this._slidBallRenderer.setPosition(dis, this._contentSize.height / 2); if (this._scale9Enabled) - this._progressBarRenderer.setPreferredSize(cc.size(dis, this._progressBarTextureSize.height)); + this._progressBarRenderer.setPreferredSize(cc.size(dis, this._contentSize.height)); else { var spriteRenderer = this._progressBarRenderer; var rect = spriteRenderer.getTextureRect(); @@ -595,9 +600,9 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ this._barLength = this._contentSize.width; if (this._scale9Enabled) { this._barRenderer.setPreferredSize(this._contentSize); - } - else { - var btextureSize = this._barRenderer.getContentSize(); + this._barRenderer.setScale(1.0); + } else { + var btextureSize = this._barTextureSize; if (btextureSize.width <= 0.0 || btextureSize.height <= 0.0) { this._barRenderer.setScale(1.0); return; @@ -627,7 +632,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ else { if (this._scale9Enabled) { this._progressBarRenderer.setPreferredSize(this._contentSize); - this._progressBarTextureSize = this._progressBarRenderer.getContentSize(); + this._progressBarRenderer.setScale(1); } else { var ptextureSize = this._progressBarTextureSize; diff --git a/extensions/ccui/uiwidgets/UIText.js b/extensions/ccui/uiwidgets/UIText.js index 84e7123a70..857e4663d4 100644 --- a/extensions/ccui/uiwidgets/UIText.js +++ b/extensions/ccui/uiwidgets/UIText.js @@ -23,7 +23,6 @@ THE SOFTWARE. ****************************************************************************/ - /** * The text control of Cocos UI. * @class @@ -85,9 +84,9 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ init: function (textContent, fontName, fontSize) { if (ccui.Widget.prototype.init.call(this)) { if(arguments.length > 0){ - this.setString(textContent); this.setFontName(fontName); this.setFontSize(fontSize); + this.setString(textContent); } return true; } @@ -325,6 +324,17 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ 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) { diff --git a/extensions/ccui/uiwidgets/UITextBMFont.js b/extensions/ccui/uiwidgets/UITextBMFont.js index e659906ebd..e50733de8e 100644 --- a/extensions/ccui/uiwidgets/UITextBMFont.js +++ b/extensions/ccui/uiwidgets/UITextBMFont.js @@ -68,13 +68,14 @@ ccui.LabelBMFont = ccui.TextBMFont = ccui.Widget.extend(/** @lends ccui.TextBMFo setFntFile: function (fileName) { if (!fileName) return; + this._fntFileName = fileName; - var _self = this; - _self._fntFileName = fileName; - - _self._fntFileHasInit = true; - _self._labelBMFontRenderer.initWithString(this._stringValue, 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.addEventListener("load", function(){ @@ -101,9 +102,9 @@ ccui.LabelBMFont = ccui.TextBMFont = ccui.Widget.extend(/** @lends ccui.TextBMFo if(value == this._labelBMFontRenderer.getString()) return; this._stringValue = value; + this._labelBMFontRenderer.setString(value); if (!this._fntFileHasInit) return; - this._labelBMFontRenderer.setString(value); this._updateContentSizeWithTextureSize(this._labelBMFontRenderer.getContentSize()); this._labelBMFontRendererAdaptDirty = true; }, diff --git a/extensions/ccui/uiwidgets/UITextField.js b/extensions/ccui/uiwidgets/UITextField.js index 90deb83d4f..859fec09dc 100644 --- a/extensions/ccui/uiwidgets/UITextField.js +++ b/extensions/ccui/uiwidgets/UITextField.js @@ -252,12 +252,12 @@ ccui.TextField = ccui.Widget.extend(/** @lends ccui.TextField# */{ */ ctor: function (placeholder, fontName, fontSize) { ccui.Widget.prototype.ctor.call(this); - if (placeholder) - this.setPlaceHolder(placeholder); if (fontName) this.setFontName(fontName); if (fontSize) this.setFontSize(fontSize); + if (placeholder) + this.setPlaceHolder(placeholder); }, /** @@ -565,14 +565,14 @@ ccui.TextField = ccui.Widget.extend(/** @lends ccui.TextField# */{ }, update: function (dt) { - if (this.getAttachWithIME()) { - this._attachWithIMEEvent(); - this.setAttachWithIME(false); - } 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()); @@ -736,6 +736,17 @@ ccui.TextField = ccui.Widget.extend(/** @lends ccui.TextField# */{ 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} diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIListView.js b/extensions/ccui/uiwidgets/scroll-widget/UIListView.js index aacc0be62e..3ea7385fde 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIListView.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIListView.js @@ -83,8 +83,11 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ * @param {ccui.Widget} model */ setItemModel: function (model) { - if (!model) + if (!model){ + cc.log("Can't set a null to item model!"); return; + } + this._model = model; }, @@ -113,104 +116,80 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ }, _remedyLayoutParameter: function (item) { - if (!item) - return; - var llp; - switch (this.direction) { - case ccui.ScrollView.DIR_VERTICAL: - llp = item.getLayoutParameter(); - if (!llp) { - var defaultLp = new ccui.LinearLayoutParameter(); - switch (this._gravity) { - case ccui.ListView.GRAVITY_LEFT: - defaultLp.setGravity(ccui.LinearLayoutParameter.LEFT); - break; - case ccui.ListView.GRAVITY_RIGHT: - defaultLp.setGravity(ccui.LinearLayoutParameter.RIGHT); - break; - case ccui.ListView.GRAVITY_CENTER_HORIZONTAL: - defaultLp.setGravity(ccui.LinearLayoutParameter.CENTER_HORIZONTAL); - break; - default: - break; - } - if (this.getIndex(item) == 0) - defaultLp.setMargin(ccui.MarginZero()); - else - defaultLp.setMargin(new ccui.Margin(0.0, this._itemsMargin, 0.0, 0.0)); - item.setLayoutParameter(defaultLp); - } else { - if (this.getIndex(item) == 0) - llp.setMargin(ccui.MarginZero()); - else - llp.setMargin(new ccui.Margin(0, this._itemsMargin, 0, 0)); - switch (this._gravity) { - case ccui.ListView.GRAVITY_LEFT: - llp.setGravity(ccui.LinearLayoutParameter.LEFT); - break; - case ccui.ListView.GRAVITY_RIGHT: - llp.setGravity(ccui.LinearLayoutParameter.RIGHT); - break; - case ccui.ListView.GRAVITY_CENTER_HORIZONTAL: - llp.setGravity(ccui.LinearLayoutParameter.CENTER_HORIZONTAL); - break; - default: - break; - } - } + cc.assert(null != item, "ListView Item can't be nil!"); + + var linearLayoutParameter = item.getLayoutParameter(); + var isLayoutParameterExists = true; + if (!linearLayoutParameter) { + linearLayoutParameter = new ccui.LinearLayoutParameter(); + isLayoutParameterExists = false; + } + var itemIndex = this.getIndex(item); + switch (this._direction) { + case ccui.ListView.DIR_VERTICAL: + this._remedyVerticalLayoutParameter(linearLayoutParameter, itemIndex); break; - case ccui.ScrollView.DIR_HORIZONTAL: - llp = item.getLayoutParameter(); - if (!llp) { - var defaultLp = new ccui.LinearLayoutParameter(); - switch (this._gravity) { - case ccui.ListView.GRAVITY_TOP: - defaultLp.setGravity(ccui.LinearLayoutParameter.TOP); - break; - case ccui.ListView.GRAVITY_BOTTOM: - defaultLp.setGravity(ccui.LinearLayoutParameter.BOTTOM ); - break; - case ccui.ListView.GRAVITY_CENTER_VERTICAL: - defaultLp.setGravity(ccui.LinearLayoutParameter.CENTER_VERTICAL); - break; - default: - break; - } - if (this.getIndex(item) == 0) - defaultLp.setMargin(ccui.MarginZero()); - else - defaultLp.setMargin(new ccui.Margin(this._itemsMargin, 0.0, 0.0, 0.0)); - item.setLayoutParameter(defaultLp); - } else { - if (this.getIndex(item) == 0) - llp.setMargin(ccui.MarginZero()); - else - llp.setMargin(new ccui.Margin(this._itemsMargin, 0.0, 0.0, 0.0)); - switch (this._gravity) { - case ccui.ListView.GRAVITY_TOP: - llp.setGravity(ccui.LinearLayoutParameter.TOP); - break; - case ccui.ListView.GRAVITY_BOTTOM: - llp.setGravity(ccui.LinearLayoutParameter.BOTTOM); - break; - case ccui.ListView.GRAVITY_CENTER_VERTICAL: - llp.setGravity(ccui.LinearLayoutParameter.CENTER_VERTICAL); - break; - default: - break; - } - } + case ccui.ListView.DIR_HORIZONTAL: + this._remedyHorizontalLayoutParameter(linearLayoutParameter, itemIndex); + break; + default: + break; + } + if (!isLayoutParameterExists) + item.setLayoutParameter(linearLayoutParameter); + }, + + //@since v3.3 + _remedyVerticalLayoutParameter: function (layoutParameter, itemIndex) { + cc.assert(null != layoutParameter, "Layout parameter can't be nil!"); + + switch (this._gravity) { + case ccui.ListView.GRAVITY_LEFT: + layoutParameter.setGravity(ccui.LinearLayoutParameter.LEFT); + break; + case ccui.ListView.GRAVITY_RIGHT: + layoutParameter.setGravity(ccui.LinearLayoutParameter.RIGHT); + break; + case ccui.ListView.GRAVITY_CENTER_HORIZONTAL: + layoutParameter.setGravity(ccui.LinearLayoutParameter.CENTER_HORIZONTAL); + break; + default: + break; + } + if (0 == itemIndex) + layoutParameter.setMargin(ccui.MarginZero()); + else + layoutParameter.setMargin(new ccui.Margin(0.0, this._itemsMargin, 0.0, 0.0)); + }, + + //@since v3.3 + _remedyHorizontalLayoutParameter: function (layoutParameter, itemIndex) { + cc.assert(null != layoutParameter, "Layout parameter can't be nil!"); + + switch (this._gravity) { + case ccui.ListView.GRAVITY_TOP: + layoutParameter.setGravity(ccui.LinearLayoutParameter.TOP); + break; + case ccui.ListView.GRAVITY_BOTTOM: + layoutParameter.setGravity(ccui.LinearLayoutParameter.BOTTOM); + break; + case ccui.ListView.GRAVITY_CENTER_VERTICAL: + layoutParameter.setGravity(ccui.LinearLayoutParameter.CENTER_VERTICAL); break; default: break; } + if (0 == itemIndex) + layoutParameter.setMargin(ccui.MarginZero()); + else + layoutParameter.setMargin(new ccui.Margin(this._itemsMargin, 0.0, 0.0, 0.0)); }, /** * Push back a default item(create by a cloned model) into ListView. */ pushBackDefaultItem: function () { - if (!this._model) + if (this._model == null) return; var newItem = this._model.clone(); this._remedyLayoutParameter(newItem); @@ -223,7 +202,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ * @param {Number} index */ insertDefaultItem: function (index) { - if (!this._model) + if (this._model == null) return; var newItem = this._model.clone(); this._items.splice(index, 0, newItem); @@ -309,7 +288,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ */ removeItem: function (index) { var item = this.getItem(index); - if (!item) + if (item == null) return; this.removeChild(item, true); this._refreshViewDirty = true; @@ -354,6 +333,8 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ * @returns {Number} the index of item. */ getIndex: function (item) { + if(item == null) + return -1; return this._items.indexOf(item); }, From ef96ed10c33f135287983d4050c08e4a3b2913af Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 27 Jan 2015 11:44:05 +0800 Subject: [PATCH 0231/1345] Studio loader error - loadingBar direction --- extensions/cocostudio/loader/parsers/timelineParser-2.x.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 29094dd81d..6c1cfbb85c 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -766,8 +766,8 @@ widget.loadTexture(path, type); }); - var direction = json["ProgressType"]; - widget.setDirection((direction != "Left_To_Right") | 0); + var direction = json["ProgressType"] === "Right_To_Left" ? 1 : 0; + widget.setDirection(direction); var percent = getParam(json["ProgressInfo"], 80); if(percent != null) From 056a72b373ad7f900d14932fac0d1b120e66a70d Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Tue, 27 Jan 2015 14:35:45 +0800 Subject: [PATCH 0232/1345] Fixed a bug of ccui.Button that its state in incorrect in _onPressStateChangedToNormal --- extensions/ccui/uiwidgets/UIButton.js | 3 --- 1 file changed, 3 deletions(-) diff --git a/extensions/ccui/uiwidgets/UIButton.js b/extensions/ccui/uiwidgets/UIButton.js index 593992f201..23dd90d41b 100644 --- a/extensions/ccui/uiwidgets/UIButton.js +++ b/extensions/ccui/uiwidgets/UIButton.js @@ -565,9 +565,6 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ locNormalRenderer.stopAllActions(); locNormalRenderer.setScale(this._normalTextureScaleXInSize + this._zoomScale, this._normalTextureScaleYInSize + this._zoomScale); - if (this._scale9Enabled) - locNormalRenderer.setState(ccui.Scale9Sprite.state.GRAY); - this._titleRenderer.stopAllActions(); this._titleRenderer.setScaleX(1 + this._zoomScale); this._titleRenderer.setScaleY(1 + this._zoomScale); From a898614cfa55d589ad6bd9e64f54f985d8136abb Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Tue, 27 Jan 2015 14:56:29 +0800 Subject: [PATCH 0233/1345] Corrected a mistake of ccui.ListView --- extensions/ccui/uiwidgets/scroll-widget/UIListView.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIListView.js b/extensions/ccui/uiwidgets/scroll-widget/UIListView.js index 3ea7385fde..89610664e2 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIListView.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIListView.js @@ -125,11 +125,11 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ isLayoutParameterExists = false; } var itemIndex = this.getIndex(item); - switch (this._direction) { - case ccui.ListView.DIR_VERTICAL: + switch (this.direction) { + case ccui.ScrollView.DIR_VERTICAL: this._remedyVerticalLayoutParameter(linearLayoutParameter, itemIndex); break; - case ccui.ListView.DIR_HORIZONTAL: + case ccui.ScrollView.DIR_HORIZONTAL: this._remedyHorizontalLayoutParameter(linearLayoutParameter, itemIndex); break; default: From 3042f5b8be913e9054352d665c3e1bf152dc83a5 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 27 Jan 2015 18:55:32 +0800 Subject: [PATCH 0234/1345] status --- .../core/base-nodes/CCNodeCanvasRenderCmd.js | 30 ++++++++++++++++--- .../core/sprites/CCSpriteCanvasRenderCmd.js | 10 ++++--- 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js index aa1c39e09f..ba8820695f 100644 --- a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js @@ -243,7 +243,7 @@ cc.Node.RenderCmd.prototype = { this._cachedParent = null; this._cacheDirty = false; - this._orginalPoint = { + this.__point = { x: 0, y: 0 }; @@ -258,15 +258,34 @@ cc.Node.RenderCmd.prototype = { worldT = this._worldTransform; //get the world transform if (parentCmd) { - var pt = parentCmd._worldTransform; + var pt = parentCmd._worldTransform, + pn = parentCmd._node; + var pAnchor = parentCmd._anchorPointInPoints; + + var tx, ty; + if (pn && !pn._ignoreAnchorPointForPosition) { + tx = pt.tx - pAnchor.x; + ty = pt.ty - pAnchor.y; + + }else{ + tx = pt.tx; + ty = pt.ty; + } + // cc.AffineTransformConcat is incorrect at get world transform worldT.a = pt.a * t.a + pt.b * t.c; //a worldT.b = pt.a * t.b + pt.b * t.d; //b worldT.c = pt.c * t.a + pt.d * t.c; //c worldT.d = pt.c * t.b + pt.d * t.d; //d - worldT.tx = pt.a * t.tx + pt.b * t.ty + pt.tx ; - worldT.ty = pt.c * t.tx + pt.d * t.ty + pt.ty; + worldT.tx = pt.a * (t.tx - pAnchor.x) + pt.b * (t.ty - pAnchor.y) + pt.tx; + worldT.ty = pt.c * (t.tx - pAnchor.x) + pt.d * (t.ty - pAnchor.y) + pt.ty; + if(pn && !pn._ignoreAnchorPointForPosition){ + }else{ + worldT.tx += pAnchor.x; + worldT.ty += pAnchor.y; + } + } else { worldT.a = t.a; worldT.b = t.b; @@ -360,6 +379,9 @@ cc.Node.RenderCmd.prototype = { // // adjust anchorPoint // t.tx += A * -appX * sx + B * appY * sy; // t.ty -= C * -appX * sx + D * appY * sy; + + this.__point.x = A * -appX * sx + B * appY * sy; + this.__point.y = C * -appX * sx + D * appY * sy; // // // if ignore anchorPoint // if (node._ignoreAnchorPointForPosition) { diff --git a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js index 05984018fd..92567ad6c5 100644 --- a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js @@ -119,6 +119,8 @@ || !node._texture._textureLoaded)) || alpha === 0) return; + var anchor = this._anchorPointInPoints; + 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; @@ -142,16 +144,16 @@ image = node._texture._htmlElementObj; if (node._texture._pattern != "") { wrapper.setFillStyle(context.createPattern(image, node._texture._pattern)); - context.fillRect(locX * scaleX, locY * scaleY, locWidth * scaleX, locHeight * scaleY); + context.fillRect((locX - anchor.x) * scaleX, (locY + anchor.y) * scaleY, locWidth * scaleX, locHeight * scaleY); } else { if (this._colorized) { context.drawImage(image, 0, 0, locTextureCoord.width,locTextureCoord.height, - locX * scaleX,locY * scaleY, locWidth * scaleX, locHeight * scaleY); + (locX-anchor.x) * scaleX, (locY+anchor.y) * 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); + (locX-anchor.x) * scaleX, (locY+anchor.y) * scaleY, locWidth * scaleX, locHeight * scaleY); } } } else { @@ -159,7 +161,7 @@ if (locTextureCoord.validRect) { var curColor = this._displayedColor; wrapper.setFillStyle("rgba(" + curColor.r + "," + curColor.g + "," + curColor.b + ",1)"); - context.fillRect(locX * scaleX, locY * scaleY, contentSize.width * scaleX, contentSize.height * scaleY); + context.fillRect((locX-anchor.x) * scaleX, (locY + anchor.y) * scaleY, contentSize.width * scaleX, contentSize.height * scaleY); } } if(node._flippedX || node._flippedY) From 49c7afc44b1959a5309746a701b4e78c6ff8ea00 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 28 Jan 2015 15:24:09 +0800 Subject: [PATCH 0235/1345] matrix algorithm (add anchorPoint) --- .../core/base-nodes/CCNodeCanvasRenderCmd.js | 18 ++++-------------- 1 file changed, 4 insertions(+), 14 deletions(-) diff --git a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js index ba8820695f..77076067d6 100644 --- a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js @@ -262,28 +262,18 @@ cc.Node.RenderCmd.prototype = { pn = parentCmd._node; var pAnchor = parentCmd._anchorPointInPoints; - var tx, ty; - if (pn && !pn._ignoreAnchorPointForPosition) { - tx = pt.tx - pAnchor.x; - ty = pt.ty - pAnchor.y; - - }else{ - tx = pt.tx; - ty = pt.ty; - } - // cc.AffineTransformConcat is incorrect at get world transform worldT.a = pt.a * t.a + pt.b * t.c; //a worldT.b = pt.a * t.b + pt.b * t.d; //b worldT.c = pt.c * t.a + pt.d * t.c; //c worldT.d = pt.c * t.b + pt.d * t.d; //d - worldT.tx = pt.a * (t.tx - pAnchor.x) + pt.b * (t.ty - pAnchor.y) + pt.tx; - worldT.ty = pt.c * (t.tx - pAnchor.x) + pt.d * (t.ty - pAnchor.y) + pt.ty; if(pn && !pn._ignoreAnchorPointForPosition){ + worldT.tx = pt.a * (t.tx - pAnchor.x) - pt.b * (t.ty - pAnchor.y) + pt.tx; + worldT.ty = -pt.c * (t.tx - pAnchor.x) + pt.d * (t.ty - pAnchor.y) + pt.ty; }else{ - worldT.tx += pAnchor.x; - worldT.ty += pAnchor.y; + worldT.tx = pt.a * t.tx - pt.b * t.ty + pt.tx; + worldT.ty = -pt.c * t.tx + pt.d * t.ty + pt.ty; } } else { From 465252d77265b8eb0ea0406aa05f5479b9c39f57 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 28 Jan 2015 17:27:28 +0800 Subject: [PATCH 0236/1345] param error (CCProtectedNodeCanvasRenderCmd) --- extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js b/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js index 1a1a34f113..564b30be35 100644 --- a/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js +++ b/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js @@ -78,7 +78,7 @@ var i, len, selChildren, item; if (this._cascadeOpacityEnabledDirty && !node._cascadeOpacityEnabled) { this._displayedOpacity = node._realOpacity; - selChildren = this._children; + selChildren = node._children; for (i = 0, len = selChildren.length; i < len; i++) { item = selChildren[i]; if (item && item._renderCmd) From d9888249635d798399308b1c21a760d81373f081 Mon Sep 17 00:00:00 2001 From: Park Hyun Chen Date: Wed, 28 Jan 2015 20:22:36 +0900 Subject: [PATCH 0237/1345] Update CCArmatureAnimation.js --- .../cocostudio/armature/animation/CCArmatureAnimation.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/cocostudio/armature/animation/CCArmatureAnimation.js b/extensions/cocostudio/armature/animation/CCArmatureAnimation.js index fda7946a17..06fd7f75f3 100644 --- a/extensions/cocostudio/armature/animation/CCArmatureAnimation.js +++ b/extensions/cocostudio/armature/animation/CCArmatureAnimation.js @@ -526,7 +526,7 @@ ccs.ArmatureAnimation = ccs.ProcessBase.extend(/** @lends ccs.ArmatureAnimation# */ setMovementEventCallFunc: function (callFunc, target) { if(arguments.length == 1){ - this._frameEventListener = callFunc; + this._movementEventListener = callFunc; }else if(arguments.length == 2){ this._movementEventTarget = target; this._movementEventCallFunc = callFunc; @@ -666,4 +666,4 @@ _p = null; */ ccs.ArmatureAnimation.create = function (armature) { return new ccs.ArmatureAnimation(armature); -}; \ No newline at end of file +}; From 29e2f5a0bc205f8e53b4c4ce48290a364ce27108 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 29 Jan 2015 13:37:15 +0800 Subject: [PATCH 0238/1345] repair queue repeat errors --- cocos2d/actions/CCActionInterval.js | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/cocos2d/actions/CCActionInterval.js b/cocos2d/actions/CCActionInterval.js index fe0d0bc4c1..7b97fb9b57 100644 --- a/cocos2d/actions/CCActionInterval.js +++ b/cocos2d/actions/CCActionInterval.js @@ -501,12 +501,25 @@ cc.sequence = function (/*Multiple Arguments*/tempArray) { if ((paramArray.length > 0) && (paramArray[paramArray.length - 1] == null)) cc.log("parameters should not be ending with null in Javascript"); - var prev = paramArray[0]; - for (var i = 1; i < paramArray.length; i++) { - if (paramArray[i]) - prev = cc.Sequence._actionOneTwo(prev, paramArray[i]); + var result, current, i, repeat; + while(paramArray && paramArray.length > 0){ + current = Array.prototype.shift.call(paramArray); + repeat = current._timesForRepeat || 1; + current._repeatMethod = false; + current._timesForRepeat = 1; + + i = 0; + if(!result){ + result = current; + i = 1; + } + + for(i; i Date: Thu, 29 Jan 2015 14:09:28 +0800 Subject: [PATCH 0239/1345] Listen orientation change event for resolution policy --- cocos2d/core/platform/CCEGLView.js | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/cocos2d/core/platform/CCEGLView.js b/cocos2d/core/platform/CCEGLView.js index c54f79024a..7375997f0b 100644 --- a/cocos2d/core/platform/CCEGLView.js +++ b/cocos2d/core/platform/CCEGLView.js @@ -195,8 +195,15 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ }else{ view = cc.view; } + + // Check frame size changed or not + var prevFrameW = view._frameSize.width, prevFrameH = view._frameSize.height; + view._initFrameSize(); + if (view._frameSize.width == prevFrameW && view._frameSize.height == prevFrameH) + return; + + // Frame size changed, do resize works if (view._resizeCallback) { - view._initFrameSize(); view._resizeCallback.call(); } var width = view._originalDesignResolutionSize.width; @@ -239,13 +246,15 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ //enable if (!this.__resizeWithBrowserSize) { this.__resizeWithBrowserSize = true; - cc._addEventListener(window, 'resize', this._resizeEvent, false); + cc._addEventListener(window, 'resize', this._resizeEvent); + cc._addEventListener(window, 'orientationchange', this._resizeEvent); } } else { //disable if (this.__resizeWithBrowserSize) { this.__resizeWithBrowserSize = false; - window.removeEventListener('resize', this._resizeEvent, false); + window.removeEventListener('resize', this._resizeEvent); + window.removeEventListener('orientationchange', this._resizeEvent); } } }, @@ -552,6 +561,9 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ return; } + // Reinit frame size + this._initFrameSize(); + this.setResolutionPolicy(resolutionPolicy); var policy = this._resolutionPolicy; if (!policy){ @@ -560,12 +572,9 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ } policy.preApply(this); - // Reinit frame size if(cc.sys.isMobile) this._setViewPortMeta(); - this._initFrameSize(); - this._originalDesignResolutionSize.width = this._designResolutionSize.width = width; this._originalDesignResolutionSize.height = this._designResolutionSize.height = height; From f7a6cff563e66471e1d928b3329e66514c3bc435 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 29 Jan 2015 14:12:51 +0800 Subject: [PATCH 0240/1345] Fix _anchorPointInPoints usage issue --- cocos2d/node-grid/CCNodeGrid.js | 5 +++-- extensions/editbox/CCdomNode.js | 12 ++++++++---- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/cocos2d/node-grid/CCNodeGrid.js b/cocos2d/node-grid/CCNodeGrid.js index 3c0e1d6f8a..f75ce939f8 100644 --- a/cocos2d/node-grid/CCNodeGrid.js +++ b/cocos2d/node-grid/CCNodeGrid.js @@ -84,8 +84,9 @@ cc.NodeGrid = cc.Node.extend({ // XXX: Expensive calls. Camera should be integrated into the cached affine matrix if (this._camera != null && !(this.grid && this.grid.isActive())) { - var apx = this._anchorPointInPoints.x, apy = this._anchorPointInPoints.y; - var translate = (apx !== 0.0 || apy !== 0.0); + 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; diff --git a/extensions/editbox/CCdomNode.js b/extensions/editbox/CCdomNode.js index a90efb3702..1c49130546 100644 --- a/extensions/editbox/CCdomNode.js +++ b/extensions/editbox/CCdomNode.js @@ -168,12 +168,13 @@ cc.DOM.methods = /** @lends cc.DOM# */{ */ _setAnchorX:function (x) { var locAnchorPoint = this._anchorPoint; + var cmd = this._renderCmd; if (x === locAnchorPoint.x) return; locAnchorPoint.x = x; - var locAPP = this._anchorPointInPoints, locSize = this._contentSize; + 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'; @@ -192,12 +193,13 @@ cc.DOM.methods = /** @lends cc.DOM# */{ */ _setAnchorY:function (y) { var locAnchorPoint = this._anchorPoint; + var cmd = this._renderCmd; if (y === locAnchorPoint.y) return; locAnchorPoint.y = y; - var locAPP = this._anchorPointInPoints, locSize = this._contentSize; + 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'; @@ -246,11 +248,12 @@ cc.DOM.methods = /** @lends cc.DOM# */{ */ _setWidth:function (width) { var locContentSize = this._contentSize; + var cmd = this._renderCmd; if (width === locContentSize.width) return; locContentSize.width = width; - var locAPP = this._anchorPointInPoints, locAnchorPoint = this._anchorPoint; + var locAPP = cmd._anchorPointInPoints, locAnchorPoint = this._anchorPoint; locAPP.x = locContentSize.width * locAnchorPoint.x; this.dom.width = locContentSize.width; this.anchorX = locAnchorPoint.x; @@ -267,11 +270,12 @@ cc.DOM.methods = /** @lends cc.DOM# */{ */ _setHeight:function (height) { var locContentSize = this._contentSize; + var cmd = this._renderCmd; if (height === locContentSize.height) return; locContentSize.height = height; - var locAPP = this._anchorPointInPoints, locAnchorPoint = this._anchorPoint; + var locAPP = cmd._anchorPointInPoints, locAnchorPoint = this._anchorPoint; locAPP.y = locContentSize.height * locAnchorPoint.y; this.dom.height = locContentSize.height; this.anchorY = locAnchorPoint.y; From 3057b33eec8c046e65729c0982057ba6111f52f9 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 29 Jan 2015 14:13:10 +0800 Subject: [PATCH 0241/1345] Fix EditBox position issue on web --- extensions/editbox/CCdomNode.js | 80 +++++++++++++++++++-------------- 1 file changed, 46 insertions(+), 34 deletions(-) diff --git a/extensions/editbox/CCdomNode.js b/extensions/editbox/CCdomNode.js index 1c49130546..fb62932ed3 100644 --- a/extensions/editbox/CCdomNode.js +++ b/extensions/editbox/CCdomNode.js @@ -426,13 +426,13 @@ cc.DOM.methods = /** @lends cc.DOM# */{ }; cc.DOM._resetEGLViewDiv = function(){ - var eglViewDiv = cc.$("#EGLViewDiv"); - if(eglViewDiv){ - var eglViewer = cc.view; - var designSize = eglViewer.getDesignResolutionSize(); - var viewPortRect = eglViewer.getViewPortRect(); - var screenSize = eglViewer.getFrameSize(); - var pixelRatio = eglViewer.getDevicePixelRatio(); + 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; @@ -444,15 +444,21 @@ cc.DOM._resetEGLViewDiv = function(){ viewPortWidth = screenSize.width; } - eglViewDiv.style.position = 'absolute'; + div.style.position = 'absolute'; //x.dom.style.display='block'; - eglViewDiv.style.width = designSizeWidth + "px"; - eglViewDiv.style.maxHeight = designSizeHeight + "px"; - eglViewDiv.style.margin = 0; - - eglViewDiv.resize(eglViewer.getScaleX()/pixelRatio, eglViewer.getScaleY()/pixelRatio); - eglViewDiv.style.left = (viewPortWidth - designSizeWidth) / 2 + "px"; - eglViewDiv.style.bottom = "0px"; + 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"; + } } }; @@ -493,17 +499,17 @@ cc.DOM.parentDOM = function (x) { }; cc.DOM._createEGLViewDiv = function(p){ - var eglViewDiv = cc.$("#EGLViewDiv"); - if(!eglViewDiv){ - eglViewDiv = cc.$new("div"); - eglViewDiv.id = "EGLViewDiv"; + var div = cc.$("#EGLViewDiv"); + if(!div){ + div = cc.$new("div"); + div.id = "EGLViewDiv"; } - var eglViewer = cc.view; - var designSize = eglViewer.getDesignResolutionSize(); - var viewPortRect = eglViewer.getViewPortRect(); - var screenSize = eglViewer.getFrameSize(); - var pixelRatio = eglViewer.getDevicePixelRatio(); + 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; @@ -515,18 +521,24 @@ cc.DOM._createEGLViewDiv = function(p){ viewPortWidth = screenSize.width; } - eglViewDiv.style.position = 'absolute'; + div.style.position = 'absolute'; //x.dom.style.display='block'; - eglViewDiv.style.width = designSizeWidth + "px"; - eglViewDiv.style.maxHeight = designSizeHeight + "px"; - eglViewDiv.style.margin = 0; - - eglViewDiv.resize(eglViewer.getScaleX()/pixelRatio, eglViewer.getScaleY()/pixelRatio); - eglViewDiv.style.left = (viewPortWidth - designSizeWidth) / 2 + "px"; - eglViewDiv.style.bottom = "0px"; + 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(eglViewDiv); - eglViewDiv.appendTo(cc.container); + p.dom.appendTo(div); + div.appendTo(cc.container); }; /** From 6f9c61f22c8ff10f26ffb67b809b67d8b703d2c7 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Thu, 29 Jan 2015 14:59:58 +0800 Subject: [PATCH 0242/1345] Add a message to Armature that it doesn't support to add widget as its child. --- extensions/cocostudio/armature/CCArmature.js | 8 ++++++++ .../cocostudio/armature/CCArmatureWebGLRenderCmd.js | 3 ++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/extensions/cocostudio/armature/CCArmature.js b/extensions/cocostudio/armature/CCArmature.js index 9577d3c831..d743c19b25 100644 --- a/extensions/cocostudio/armature/CCArmature.js +++ b/extensions/cocostudio/armature/CCArmature.js @@ -151,6 +151,14 @@ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{ 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 diff --git a/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js b/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js index 42985ca1e0..54bf4e762a 100644 --- a/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js +++ b/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js @@ -83,7 +83,8 @@ } else if (selBone instanceof cc.Node) { selBone.setShaderProgram(this._shaderProgram); selBone._renderCmd.transform(); - selBone._renderCmd.rendering(ctx); + if(selBone._renderCmd.rendering) + selBone._renderCmd.rendering(ctx); } } if(!dontChangeMatrix) From 230f04984ac4aad2739f19a72e2298465af7aa0c Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Thu, 29 Jan 2015 15:50:44 +0800 Subject: [PATCH 0243/1345] Fixed #2651: fixed a bug of cc.GLProgram that it doesn't work on some devices which isn't supported highp float precision. --- cocos2d/shaders/CCGLProgram.js | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/cocos2d/shaders/CCGLProgram.js b/cocos2d/shaders/CCGLProgram.js index 831b91fd7a..1b429a9734 100644 --- a/cocos2d/shaders/CCGLProgram.js +++ b/cocos2d/shaders/CCGLProgram.js @@ -83,8 +83,8 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ if (!source || !shader) return false; - //var preStr = (type == this._glContext.VERTEX_SHADER) ? "precision highp float;\n" : "precision mediump float;\n"; - source = "precision highp float; \n" + 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" @@ -731,6 +731,17 @@ 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 From 69f106b0131b61f7a89f603dd054848c5490ec01 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 29 Jan 2015 16:16:52 +0800 Subject: [PATCH 0244/1345] change node transform --- .../core/base-nodes/CCNodeCanvasRenderCmd.js | 90 ++++++++----------- .../core/sprites/CCSpriteCanvasRenderCmd.js | 10 +-- 2 files changed, 39 insertions(+), 61 deletions(-) diff --git a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js index 77076067d6..9b0859b5bf 100644 --- a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js @@ -243,39 +243,45 @@ cc.Node.RenderCmd.prototype = { this._cachedParent = null; this._cacheDirty = false; - this.__point = { - x: 0, - y: 0 - }; }; var proto = cc.Node.CanvasRenderCmd.prototype = Object.create(cc.Node.RenderCmd.prototype); proto.constructor = cc.Node.CanvasRenderCmd; proto.transform = function (parentCmd, recursive) { + var node = this._node; // transform for canvas var t = this.getNodeToParentTransform(), worldT = this._worldTransform; //get the world transform if (parentCmd) { - var pt = parentCmd._worldTransform, - pn = parentCmd._node; - var pAnchor = parentCmd._anchorPointInPoints; - + var pt = parentCmd._worldTransform; // cc.AffineTransformConcat is incorrect at get world transform worldT.a = pt.a * t.a + pt.b * t.c; //a worldT.b = pt.a * t.b + pt.b * t.d; //b worldT.c = pt.c * t.a + pt.d * t.c; //c worldT.d = pt.c * t.b + pt.d * t.d; //d - if(pn && !pn._ignoreAnchorPointForPosition){ - worldT.tx = pt.a * (t.tx - pAnchor.x) - pt.b * (t.ty - pAnchor.y) + pt.tx; - worldT.ty = -pt.c * (t.tx - pAnchor.x) + pt.d * (t.ty - pAnchor.y) + pt.ty; - }else{ - worldT.tx = pt.a * t.tx - pt.b * t.ty + pt.tx; - worldT.ty = -pt.c * t.tx + pt.d * t.ty + pt.ty; - } + worldT.tx = pt.a * t.tx - pt.b * t.ty + pt.tx ; + worldT.ty = -pt.c * t.tx + pt.d * t.ty + pt.ty; + var lScaleX = node._scaleX, lScaleY = node._scaleY; + // Firefox on Vista and XP crashes + // GPU thread in case of scale(0.0, 0.0) + var sx = (lScaleX < 0.000001 && lScaleX > -0.000001) ? 0.000001 : lScaleX, + sy = (lScaleY < 0.000001 && lScaleY > -0.000001) ? 0.000001 : lScaleY; + var appX = this._anchorPointInPoints.x / lScaleX, + appY = this._anchorPointInPoints.y / lScaleY; + + // adjust anchorPoint + worldT.tx += worldT.a * -appX * sx + worldT.b * appY * sy; + worldT.ty -= worldT.c * -appX * sx + worldT.d * appY * sy; + + // if ignore anchorPoint + if (this._node._ignoreAnchorPointForPosition) { + worldT.tx += appX; + worldT.ty += appY; + } } else { worldT.a = t.a; worldT.b = t.b; @@ -311,41 +317,33 @@ cc.Node.RenderCmd.prototype = { t.tx = node._position.x; t.ty = node._position.y; + var lScaleX = node._scaleX, lScaleY = node._scaleY; + + // Firefox on Vista and XP crashes + // GPU thread in case of scale(0.0, 0.0) + var sx = (lScaleX < 0.000001 && lScaleX > -0.000001) ? 0.000001 : lScaleX, + sy = (lScaleY < 0.000001 && lScaleY > -0.000001) ? 0.000001 : lScaleY; + // rotation Cos and Sin - var A = 1, B = 0, - C = 0, D = 1; + var A = sx, B = 0, + C = 0, D = sy; if (node._rotationX) { var rotationRadiansX = node._rotationX * 0.017453292519943295; //0.017453292519943295 = (Math.PI / 180); for performance - B = -Math.sin(rotationRadiansX); - D = Math.cos(rotationRadiansX); + B = -Math.sin(rotationRadiansX) * sy; + D = Math.cos(rotationRadiansX) * sy; } if (node._rotationY) { var rotationRadiansY = node._rotationY * 0.017453292519943295; //0.017453292519943295 = (Math.PI / 180); for performance - A = Math.cos(rotationRadiansY); - C = Math.sin(rotationRadiansY); + A = Math.cos(rotationRadiansY) * sx; + C = Math.sin(rotationRadiansY) * sx; } + t.a = A; t.b = B; t.c = C; t.d = D; - var lScaleX = node._scaleX, lScaleY = node._scaleY; - var appX = this._anchorPointInPoints.x, appY = this._anchorPointInPoints.y; - - // Firefox on Vista and XP crashes - // GPU thread in case of scale(0.0, 0.0) - var sx = (lScaleX < 0.000001 && lScaleX > -0.000001) ? 0.000001 : lScaleX, - sy = (lScaleY < 0.000001 && lScaleY > -0.000001) ? 0.000001 : lScaleY; - - // scale - if (lScaleX !== 1 || lScaleY !== 1) { - t.a *= sx; - t.c *= sx; - t.b *= sy; - t.d *= sy; - } - // skew if (node._skewX || node._skewY) { // offset the anchorpoint @@ -355,30 +353,12 @@ cc.Node.RenderCmd.prototype = { skx = 99999999; if (sky === Infinity) sky = 99999999; - var xx = appY * skx * sx; - var yy = appX * sky * sy; t.a = A + B * sky; t.b = A * skx + B; t.c = C + D * sky; t.d = C * skx + D; - t.tx += A * xx + B * yy; - t.ty += C * xx + D * yy; } -// var appX = this._anchorPointInPoints.x, appY = this._anchorPointInPoints.y; -// // adjust anchorPoint -// t.tx += A * -appX * sx + B * appY * sy; -// t.ty -= C * -appX * sx + D * appY * sy; - - this.__point.x = A * -appX * sx + B * appY * sy; - this.__point.y = C * -appX * sx + D * appY * sy; -// -// // if ignore anchorPoint -// if (node._ignoreAnchorPointForPosition) { -// t.tx += appX; -// t.ty += appY; -// } - if (node._additionalTransformDirty) { this._transform = cc.affineTransformConcat(t, node._additionalTransform); node._additionalTransformDirty = false; diff --git a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js index 92567ad6c5..05984018fd 100644 --- a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js @@ -119,8 +119,6 @@ || !node._texture._textureLoaded)) || alpha === 0) return; - var anchor = this._anchorPointInPoints; - 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; @@ -144,16 +142,16 @@ image = node._texture._htmlElementObj; if (node._texture._pattern != "") { wrapper.setFillStyle(context.createPattern(image, node._texture._pattern)); - context.fillRect((locX - anchor.x) * scaleX, (locY + anchor.y) * scaleY, locWidth * scaleX, locHeight * scaleY); + context.fillRect(locX * scaleX, locY * scaleY, locWidth * scaleX, locHeight * scaleY); } else { if (this._colorized) { context.drawImage(image, 0, 0, locTextureCoord.width,locTextureCoord.height, - (locX-anchor.x) * scaleX, (locY+anchor.y) * scaleY, locWidth * scaleX, locHeight * scaleY); + locX * scaleX,locY * scaleY, locWidth * scaleX, locHeight * scaleY); } else { context.drawImage(image, locTextureCoord.renderX, locTextureCoord.renderY, locTextureCoord.width, locTextureCoord.height, - (locX-anchor.x) * scaleX, (locY+anchor.y) * scaleY, locWidth * scaleX, locHeight * scaleY); + locX * scaleX, locY * scaleY, locWidth * scaleX, locHeight * scaleY); } } } else { @@ -161,7 +159,7 @@ if (locTextureCoord.validRect) { var curColor = this._displayedColor; wrapper.setFillStyle("rgba(" + curColor.r + "," + curColor.g + "," + curColor.b + ",1)"); - context.fillRect((locX-anchor.x) * scaleX, (locY + anchor.y) * scaleY, contentSize.width * scaleX, contentSize.height * scaleY); + context.fillRect(locX * scaleX, locY * scaleY, contentSize.width * scaleX, contentSize.height * scaleY); } } if(node._flippedX || node._flippedY) From 0d7d06f2d008a002e17831400db8d9c8624ec915 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 29 Jan 2015 16:32:14 +0800 Subject: [PATCH 0245/1345] change ccui transform --- .../CCProtectedNodeCanvasRenderCmd.js | 40 ++++++++++++------- 1 file changed, 26 insertions(+), 14 deletions(-) diff --git a/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js b/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js index 564b30be35..60d1c3dc84 100644 --- a/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js +++ b/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js @@ -206,21 +206,33 @@ node._changePosition(); var t = node.getNodeToParentTransform(), worldT = this._worldTransform; - if(parentCmd){ + if (parentCmd) { var pt = parentCmd._worldTransform; - 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 - if(node._skewX || node._skewY){ - var plt = parentCmd._transform; - var xOffset = -(plt.b + plt.c) * t.ty ; - var yOffset = -(plt.b + plt.c) * t.tx; - worldT.tx = (t.tx * pt.a + t.ty * pt.c + pt.tx + xOffset); //tx - worldT.ty = (t.tx * pt.b + t.ty * pt.d + pt.ty + yOffset); //ty - }else{ - worldT.tx = (t.tx * pt.a + t.ty * pt.c + pt.tx); //tx - worldT.ty = (t.tx * pt.b + t.ty * pt.d + pt.ty); //ty + // cc.AffineTransformConcat is incorrect at get world transform + worldT.a = pt.a * t.a + pt.b * t.c; //a + worldT.b = pt.a * t.b + pt.b * t.d; //b + worldT.c = pt.c * t.a + pt.d * t.c; //c + worldT.d = pt.c * t.b + pt.d * t.d; //d + + worldT.tx = pt.a * t.tx - pt.b * t.ty + pt.tx ; + worldT.ty = -pt.c * t.tx + pt.d * t.ty + pt.ty; + + var lScaleX = node._scaleX, lScaleY = node._scaleY; + // Firefox on Vista and XP crashes + // GPU thread in case of scale(0.0, 0.0) + var sx = (lScaleX < 0.000001 && lScaleX > -0.000001) ? 0.000001 : lScaleX, + sy = (lScaleY < 0.000001 && lScaleY > -0.000001) ? 0.000001 : lScaleY; + var appX = this._anchorPointInPoints.x / lScaleX, + appY = this._anchorPointInPoints.y / lScaleY; + + // adjust anchorPoint + worldT.tx += worldT.a * -appX * sx + worldT.b * appY * sy; + worldT.ty -= worldT.c * -appX * sx + worldT.d * appY * sy; + + // if ignore anchorPoint + if (this._node._ignoreAnchorPointForPosition) { + worldT.tx += appX; + worldT.ty += appY; } } else { worldT.a = t.a; From 375b33fbb8268738e5adf36a53bdd5872d4f4a32 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Thu, 29 Jan 2015 17:57:39 +0800 Subject: [PATCH 0246/1345] Fixed #2488: fixed a bug of cc.FadeOut and cc.FadeIn that they don't work when duration is 0 --- cocos2d/actions/CCActionInterval.js | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/cocos2d/actions/CCActionInterval.js b/cocos2d/actions/CCActionInterval.js index 7b97fb9b57..4d6243b1dc 100644 --- a/cocos2d/actions/CCActionInterval.js +++ b/cocos2d/actions/CCActionInterval.js @@ -2654,7 +2654,6 @@ cc.FadeTo = cc.ActionInterval.extend(/** @lends cc.FadeTo# */{ time = this._computeEaseTime(time); var fromOpacity = this._fromOpacity !== undefined ? this._fromOpacity : 255; this.target.opacity = fromOpacity + (this._toOpacity - fromOpacity) * time; - }, /** @@ -2706,7 +2705,9 @@ cc.FadeIn = cc.FadeTo.extend(/** @lends cc.FadeIn# */{ */ ctor:function (duration) { cc.FadeTo.prototype.ctor.call(this); - duration && this.initWithDuration(duration, 255); + if (duration == null) + duration = 0; + this.initWithDuration(duration, 255); }, /** @@ -2780,7 +2781,9 @@ cc.FadeOut = cc.FadeTo.extend(/** @lends cc.FadeOut# */{ */ ctor:function (duration) { cc.FadeTo.prototype.ctor.call(this); - duration && this.initWithDuration(duration, 0); + if (duration == null) + duration = 0; + this.initWithDuration(duration, 0); }, /** From b18fac6eecce140d7f4b8f9ae1bcd3786b238005 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 30 Jan 2015 10:08:47 +0800 Subject: [PATCH 0247/1345] Listen orientation change event for resolution policy --- cocos2d/core/platform/CCEGLView.js | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/cocos2d/core/platform/CCEGLView.js b/cocos2d/core/platform/CCEGLView.js index 7375997f0b..068ab4188f 100644 --- a/cocos2d/core/platform/CCEGLView.js +++ b/cocos2d/core/platform/CCEGLView.js @@ -60,6 +60,12 @@ cc.__BrowserGetter = { switch(cc.sys.browserType){ case cc.sys.BROWSER_TYPE_SAFARI: cc.__BrowserGetter.meta["minimal-ui"] = "true"; + cc.__BrowserGetter.availWidth = function(frame){ + return frame.clientWidth; + }; + cc.__BrowserGetter.availHeight = function(frame){ + return frame.clientHeight; + }; break; case cc.sys.BROWSER_TYPE_CHROME: cc.__BrowserGetter.__defineGetter__("target-densitydpi", function(){ @@ -246,15 +252,15 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ //enable if (!this.__resizeWithBrowserSize) { this.__resizeWithBrowserSize = true; - cc._addEventListener(window, 'resize', this._resizeEvent); - cc._addEventListener(window, 'orientationchange', this._resizeEvent); + cc._addEventListener(window, 'resize', this._resizeEvent, false); + cc._addEventListener(window, 'orientationchange', this._resizeEvent, false); } } else { //disable if (this.__resizeWithBrowserSize) { - this.__resizeWithBrowserSize = false; - window.removeEventListener('resize', this._resizeEvent); - window.removeEventListener('orientationchange', this._resizeEvent); + this.__resizeWithBrowserSize = true; + window.removeEventListener('resize', this._resizeEvent, false); + window.removeEventListener('orientationchange', this._resizeEvent, false); } } }, @@ -561,9 +567,6 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ return; } - // Reinit frame size - this._initFrameSize(); - this.setResolutionPolicy(resolutionPolicy); var policy = this._resolutionPolicy; if (!policy){ @@ -572,9 +575,12 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ } policy.preApply(this); + // Reinit frame size if(cc.sys.isMobile) this._setViewPortMeta(); + this._initFrameSize(); + this._originalDesignResolutionSize.width = this._designResolutionSize.width = width; this._originalDesignResolutionSize.height = this._designResolutionSize.height = height; From aba727f4999eca506cb76576c43afabe376c99e1 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 30 Jan 2015 10:27:56 +0800 Subject: [PATCH 0248/1345] onended callback time is error (Second plays will direct callback) --- cocos2d/audio/CCAudio.js | 4 ---- 1 file changed, 4 deletions(-) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index 0500abad0c..aa39edcd72 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -302,10 +302,6 @@ cc.Audio = cc.Class.extend({ audio["noteOn"](0); } this._currentSource = audio; - var self = this; - audio["onended"] = function(){ - self._playing = false; - }; }, _playOfAudio: function(){ From c2c50433f03d7e6c40aae86cbb47c1d4866b0614 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 30 Jan 2015 10:31:00 +0800 Subject: [PATCH 0249/1345] Listen orientation change event for resolution policy --- cocos2d/core/platform/CCEGLView.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/cocos2d/core/platform/CCEGLView.js b/cocos2d/core/platform/CCEGLView.js index 068ab4188f..78184ce5c5 100644 --- a/cocos2d/core/platform/CCEGLView.js +++ b/cocos2d/core/platform/CCEGLView.js @@ -252,15 +252,15 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ //enable if (!this.__resizeWithBrowserSize) { this.__resizeWithBrowserSize = true; - cc._addEventListener(window, 'resize', this._resizeEvent, false); - cc._addEventListener(window, 'orientationchange', this._resizeEvent, false); + cc._addEventListener(window, 'resize', this._resizeEvent); + cc._addEventListener(window, 'orientationchange', this._resizeEvent); } } else { //disable if (this.__resizeWithBrowserSize) { - this.__resizeWithBrowserSize = true; - window.removeEventListener('resize', this._resizeEvent, false); - window.removeEventListener('orientationchange', this._resizeEvent, false); + this.__resizeWithBrowserSize = false; + window.removeEventListener('resize', this._resizeEvent); + window.removeEventListener('orientationchange', this._resizeEvent); } } }, From beecce14fc934cef11d7e0bff9112e4e3e4fd1ad Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 30 Jan 2015 11:24:49 +0800 Subject: [PATCH 0250/1345] Listen orientation change event for resolution policy --- cocos2d/audio/CCAudio.js | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index aa39edcd72..d47cb112a7 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -174,6 +174,8 @@ cc.Audio = cc.Class.extend({ _context: null, _volume: null, + _ignoreEnded: false, + //DOM Audio _element: null, @@ -262,9 +264,10 @@ cc.Audio = cc.Class.extend({ return; } if(!this._pause && cs){ - if(this._context.currentTime === 0 || this._currentTime + this._context.currentTime - this._startTime > this._currentSource.buffer.duration) + if(this._context.currentTime === 0 || this._currentTime + this._context.currentTime - this._startTime > this._currentSource.buffer.duration){ + this._ignoreEnded = true; this._stopOfWebAudio(); - else + }else return; } var audio = this._context["createBufferSource"](); @@ -302,6 +305,14 @@ cc.Audio = cc.Class.extend({ audio["noteOn"](0); } this._currentSource = audio; + var self = this; + audio["onended"] = function(){ + if(self._ignoreEnded){ + self._ignoreEnded = false; + }else{ + self._playing = false; + } + }; }, _playOfAudio: function(){ @@ -1010,5 +1021,4 @@ cc.Audio = cc.Class.extend({ cc.audioEngine._resumePlaying(); }); - })(cc.__audioSupport); From 544e3d6e305806cb82e29c1f959a5dc02626db3b Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 30 Jan 2015 11:45:21 +0800 Subject: [PATCH 0251/1345] Listen orientation change event for resolution policy --- cocos2d/audio/CCAudio.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index d47cb112a7..ab5dc5478a 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -264,10 +264,9 @@ cc.Audio = cc.Class.extend({ return; } if(!this._pause && cs){ - if(this._context.currentTime === 0 || this._currentTime + this._context.currentTime - this._startTime > this._currentSource.buffer.duration){ - this._ignoreEnded = true; + if(this._context.currentTime === 0 || this._currentTime + this._context.currentTime - this._startTime > this._currentSource.buffer.duration) this._stopOfWebAudio(); - }else + else return; } var audio = this._context["createBufferSource"](); @@ -334,6 +333,7 @@ cc.Audio = cc.Class.extend({ _stopOfWebAudio: function(){ var audio = this._currentSource; + this._ignoreEnded = true; if(audio){ audio.stop(0); this._currentSource = null; From 666cc06e128d343c90ee191d2096d568394d1dfe Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 30 Jan 2015 16:20:43 +0800 Subject: [PATCH 0252/1345] update version string --- cocos2d/core/platform/CCConfig.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/platform/CCConfig.js b/cocos2d/core/platform/CCConfig.js index f960492f24..7208062c13 100644 --- a/cocos2d/core/platform/CCConfig.js +++ b/cocos2d/core/platform/CCConfig.js @@ -31,7 +31,7 @@ * @type {String} * @name cc.ENGINE_VERSION */ -window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.3 Beta0"; +window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.3 RC0"; /** *

From fe902a05901bf87c642be5a4ca9b41f046e292ad Mon Sep 17 00:00:00 2001 From: pandamicro Date: Sat, 31 Jan 2015 01:22:22 +0800 Subject: [PATCH 0253/1345] Fix CCB animation auto play issue --- extensions/ccb-reader/CCBReader.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/extensions/ccb-reader/CCBReader.js b/extensions/ccb-reader/CCBReader.js index 98d8512233..cde09e6f92 100644 --- a/extensions/ccb-reader/CCBReader.js +++ b/extensions/ccb-reader/CCBReader.js @@ -1080,6 +1080,9 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) { } } + //auto play animations + animationManager.runAnimations(animationManager.getAutoPlaySequenceId(), 0); + return node; }; From 1641bdad29ede27ae1f23485f8ad3d62476128a9 Mon Sep 17 00:00:00 2001 From: Igor Mats Date: Sat, 31 Jan 2015 11:58:15 +0200 Subject: [PATCH 0254/1345] Add MESH to the attachment types. --- extensions/spine/CCSkeleton.js | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/extensions/spine/CCSkeleton.js b/extensions/spine/CCSkeleton.js index e60491d668..0e4aadd472 100644 --- a/extensions/spine/CCSkeleton.js +++ b/extensions/spine/CCSkeleton.js @@ -48,14 +48,15 @@ sp.VERTEX_INDEX = { }; /** - * The attachment type of spine. It contains three type: REGION(0), BOUNDING_BOX(1) and REGION_SEQUENCE(2). + * The attachment type of spine. It contains three type: REGION(0), BOUNDING_BOX(1), REGION_SEQUENCE(2) and MESH(2). * @constant - * @type {{REGION: number, BOUNDING_BOX: number, REGION_SEQUENCE: number}} + * @type {{REGION: number, BOUNDING_BOX: number, REGION_SEQUENCE: number, MESH: number}} */ sp.ATTACHMENT_TYPE = { REGION: 0, BOUNDING_BOX: 1, - REGION_SEQUENCE: 2 + REGION_SEQUENCE: 2, + MESH: 2 }; /** From b69d9b543f2fa83d812098a10272a6d7457f561b Mon Sep 17 00:00:00 2001 From: Igor Mats Date: Sat, 31 Jan 2015 12:00:05 +0200 Subject: [PATCH 0255/1345] Add update verticles method for meshAttachment. --- extensions/spine/CCSkeletonWebGLRenderCmd.js | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/extensions/spine/CCSkeletonWebGLRenderCmd.js b/extensions/spine/CCSkeletonWebGLRenderCmd.js index 4b12770e79..9b78bbd0eb 100644 --- a/extensions/spine/CCSkeletonWebGLRenderCmd.js +++ b/extensions/spine/CCSkeletonWebGLRenderCmd.js @@ -54,7 +54,7 @@ for (i = 0, n = locSkeleton.slots.length; i < n; i++) { slot = locSkeleton.drawOrder[i]; - if (!slot.attachment || slot.attachment.type != sp.ATTACHMENT_TYPE.REGION) + if (!slot.attachment) continue; attachment = slot.attachment; var regionTextureAtlas = node.getTextureAtlas(attachment); @@ -80,7 +80,15 @@ return; } - sp._regionAttachment_updateQuad(attachment, slot, quad, node._premultipliedAlpha); + switch(slot.attachment.type) { + case sp.ATTACHMENT_TYPE.REGION: + sp._regionAttachment_updateQuad(attachment, slot, quad, node._premultipliedAlpha); + break; + case sp.ATTACHMENT_TYPE.MESH: + sp._meshAttachment_updateQuad(attachment, slot, quad, node._premultipliedAlpha); + break; + } + textureAtlas.updateQuad(quad, quadCount); } From 5a11b64da33801a3b861447189d90f02e20202a8 Mon Sep 17 00:00:00 2001 From: Igor Mats Date: Sat, 31 Jan 2015 12:01:30 +0200 Subject: [PATCH 0256/1345] Add _meshAttachment_updateQuad method. --- extensions/spine/CCSkeletonAnimation.js | 39 +++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/extensions/spine/CCSkeletonAnimation.js b/extensions/spine/CCSkeletonAnimation.js index c71948ea80..19a2884e9b 100644 --- a/extensions/spine/CCSkeletonAnimation.js +++ b/extensions/spine/CCSkeletonAnimation.js @@ -116,6 +116,45 @@ sp._regionAttachment_updateQuad = function(self, slot, quad, premultipliedAlpha) quad.br.texCoords.v = self.uvs[VERTEX.Y4]; }; +sp._meshAttachment_updateQuad = function(self, slot, quad, premultipliedAlpha) { + var vertices = {}; + self.computeVertices(slot.skeleton.x, slot.skeleton.y, slot, vertices); + var r = slot.skeleton.r * slot.r * 255; + var g = slot.skeleton.g * slot.g * 255; + var b = slot.skeleton.b * slot.b * 255; + var normalizedAlpha = slot.skeleton.a * slot.a; + if (premultipliedAlpha) { + r *= normalizedAlpha; + g *= normalizedAlpha; + b *= normalizedAlpha; + } + var a = normalizedAlpha * 255; + + quad.bl.colors.r = quad.tl.colors.r = quad.tr.colors.r = quad.br.colors.r = r; + quad.bl.colors.g = quad.tl.colors.g = quad.tr.colors.g = quad.br.colors.g = g; + quad.bl.colors.b = quad.tl.colors.b = quad.tr.colors.b = quad.br.colors.b = b; + quad.bl.colors.a = quad.tl.colors.a = quad.tr.colors.a = quad.br.colors.a = a; + + var VERTEX = sp.VERTEX_INDEX; + quad.bl.vertices.x = vertices[VERTEX.X1]; + quad.bl.vertices.y = vertices[VERTEX.Y1]; + quad.tl.vertices.x = vertices[VERTEX.X2]; + quad.tl.vertices.y = vertices[VERTEX.Y2]; + quad.tr.vertices.x = vertices[VERTEX.X3]; + quad.tr.vertices.y = vertices[VERTEX.Y3]; + quad.br.vertices.x = vertices[VERTEX.X4]; + quad.br.vertices.y = vertices[VERTEX.Y4]; + + quad.bl.texCoords.u = self.uvs[VERTEX.X1]; + quad.bl.texCoords.v = self.uvs[VERTEX.Y1]; + quad.tl.texCoords.u = self.uvs[VERTEX.X2]; + quad.tl.texCoords.v = self.uvs[VERTEX.Y2]; + quad.tr.texCoords.u = self.uvs[VERTEX.X3]; + quad.tr.texCoords.v = self.uvs[VERTEX.Y3]; + quad.br.texCoords.u = self.uvs[VERTEX.X4]; + quad.br.texCoords.v = self.uvs[VERTEX.Y4]; +}; + sp._regionAttachment_updateSlotForCanvas = function(self, slot, points) { if(!points) return; From ef695a754f43caba819b6f6e4727fcbf284f169f Mon Sep 17 00:00:00 2001 From: Igor Mats Date: Sat, 31 Jan 2015 12:04:38 +0200 Subject: [PATCH 0257/1345] Update Spine.js from official spine runtimes repo. --- extensions/spine/Spine.js | 638 +++++++++++++++++++++++++++++++------- 1 file changed, 529 insertions(+), 109 deletions(-) diff --git a/extensions/spine/Spine.js b/extensions/spine/Spine.js index a5bd20cc0f..c446ff7247 100644 --- a/extensions/spine/Spine.js +++ b/extensions/spine/Spine.js @@ -26,7 +26,13 @@ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ -var spine = spine || {}; +var spine = 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; @@ -161,7 +167,6 @@ spine.Skin.prototype = { return this.attachments[slotIndex + ":" + name]; }, _attachAll: function (skeleton, oldSkin) { - console.log(oldSkin.attachments); for (var key in oldSkin.attachments) { var colon = key.indexOf(":"); var slotIndex = parseInt(key.substring(0, colon)); @@ -811,7 +816,9 @@ spine.Event.prototype = { spine.AttachmentType = { region: 0, - boundingbox: 1 + boundingbox: 1, + mesh: 2, + skinnedmesh: 3 }; spine.RegionAttachment = function (name) { @@ -883,7 +890,8 @@ spine.RegionAttachment.prototype = { offset[6/*X4*/] = localX2Cos - localYSin; offset[7/*Y4*/] = localYCos + localX2Sin; }, - computeVertices: function (x, y, bone, vertices) { + computeVertices: function (x, y, slot, vertices) { + var bone = slot.bone; x += bone.worldX; y += bone.worldY; var m00 = bone.m00; @@ -902,6 +910,141 @@ spine.RegionAttachment.prototype = { } }; +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; + } + } + }, + computeVertices: function (x, y, slot, vertices) { + var bone = slot.bone; + x += bone.worldX; + y += bone.worldY; + var m00 = bone.m00, m01 = bone.m01, m10 = bone.m10, m11 = bone.m11; + var verticesCount = this.vertices.length; + if (slot.attachment.length == verticesCount) this.vertices = slot.attachment; + for (var i = 0; i < verticesCount; i += 2) { + var vx = this.vertices[i]; + var vy = this.vertices[i + 1]; + vertices[i] = vx * m00 + vy * m01 + x; + vertices[i + 1] = vx * m10 + vy * m11 + y; + } + } +}; + +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 = []; @@ -1143,8 +1286,18 @@ spine.SkeletonJson = function (attachmentLoader) { }; spine.SkeletonJson.prototype = { scale: 1, - readSkeletonData: function (root) { + 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"]; @@ -1160,13 +1313,37 @@ spine.SkeletonJson.prototype = { boneData.x = (boneMap["x"] || 0) * this.scale; boneData.y = (boneMap["y"] || 0) * this.scale; boneData.rotation = (boneMap["rotation"] || 0); - boneData.scaleX = boneMap["scaleX"] || 1; - boneData.scaleY = boneMap["scaleY"] || 1; - boneData.inheritScale = !boneMap["inheritScale"] || boneMap["inheritScale"] == "true"; - boneData.inheritRotation = !boneMap["inheritRotation"] || boneMap["inheritRotation"] == "true"; + 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 "IK bone not found: " + bones[ii]; + ikConstraintData.bones.push(bone); + } + + ikConstraintData.target = skeletonData.findBone(ikMap["target"]); + if (!ikConstraintData.target) throw "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++) { @@ -1177,10 +1354,10 @@ spine.SkeletonJson.prototype = { var color = slotMap["color"]; if (color) { - slotData.r = spine.SkeletonJson.toColor(color, 0); - slotData.g = spine.SkeletonJson.toColor(color, 1); - slotData.b = spine.SkeletonJson.toColor(color, 2); - slotData.a = spine.SkeletonJson.toColor(color, 3); + 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"]; @@ -1202,7 +1379,7 @@ spine.SkeletonJson.prototype = { for (var attachmentName in slotEntry) { if (!slotEntry.hasOwnProperty(attachmentName)) continue; var attachment = this.readAttachment(skin, attachmentName, slotEntry[attachmentName]); - if (attachment != null) skin.addAttachment(slotIndex, attachmentName, attachment); + if (attachment) skin.addAttachment(slotIndex, attachmentName, attachment); } } skeletonData.skins.push(skin); @@ -1234,29 +1411,150 @@ spine.SkeletonJson.prototype = { name = map["name"] || name; var type = spine.AttachmentType[map["type"] || "region"]; - var attachment = this.attachmentLoader.newAttachment(skin, type, name); - + var path = map["path"] || name; + + var scale = this.scale; if (type == spine.AttachmentType.region) { - attachment.x = (map["x"] || 0) * this.scale; - attachment.y = (map["y"] || 0) * this.scale; - attachment.scaleX = map["scaleX"] || 1; - attachment.scaleY = map["scaleY"] || 1; - attachment.rotation = map["rotation"] || 0; - attachment.width = (map["width"] || 32) * this.scale; - attachment.height = (map["height"] || 32) * this.scale; - attachment.updateOffset(); - } else if (type == spine.AttachmentType.boundingBox) { + 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] * this.scale); + attachment.vertices.push(vertices[i] * scale); + return attachment; } - - return attachment; + throw "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 "Invalid timeline type for a slot: " + timelineName + " (" + slotName + ")"; + } + } + var bones = map["bones"]; for (var boneName in bones) { if (!bones.hasOwnProperty(boneName)) continue; @@ -1275,7 +1573,7 @@ spine.SkeletonJson.prototype = { for (var i = 0, n = values.length; i < n; i++) { var valueMap = values[i]; timeline.setFrame(frameIndex, valueMap["time"], valueMap["angle"]); - spine.SkeletonJson.readCurve(timeline, frameIndex, valueMap); + this.readCurve(timeline, frameIndex, valueMap); frameIndex++; } timelines.push(timeline); @@ -1298,81 +1596,116 @@ spine.SkeletonJson.prototype = { var x = (valueMap["x"] || 0) * timelineScale; var y = (valueMap["y"] || 0) * timelineScale; timeline.setFrame(frameIndex, valueMap["time"], x, y); - spine.SkeletonJson.readCurve(timeline, frameIndex, valueMap); + this.readCurve(timeline, frameIndex, valueMap); frameIndex++; } timelines.push(timeline); duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 3 - 3]); - } else - throw "Invalid timeline type for a bone: " + timelineName + " (" + boneName + ")"; - } - } - - 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; + } 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]; - var color = valueMap["color"]; - var r = spine.SkeletonJson.toColor(color, 0); - var g = spine.SkeletonJson.toColor(color, 1); - var b = spine.SkeletonJson.toColor(color, 2); - var a = spine.SkeletonJson.toColor(color, 3); - timeline.setFrame(frameIndex, valueMap["time"], r, g, b, a); - spine.SkeletonJson.readCurve(timeline, frameIndex, valueMap); + timeline.setFrame(frameIndex, valueMap["time"], valueMap[field] || false); frameIndex++; } timelines.push(timeline); - duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 5 - 5]); + duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 2 - 2]); + } else + throw "Invalid timeline type for a bone: " + timelineName + " (" + boneName + ")"; + } + } - } else if (timelineName == "attachment") { - var timeline = new spine.AttachmentTimeline(values.length); + 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 "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]; - timeline.setFrame(frameIndex++, valueMap["time"], valueMap["name"]); + 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.push(timeline); - duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]); - - } else - throw "Invalid timeline type for a slot: " + timelineName + " (" + slotName + ")"; - } - } - - 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 "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[timelines.length] = timeline; + duration = Math.max(duration, timeline.frames[timeline.frameCount - 1]); + } } - timelines.push(timeline); - duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]); } - var drawOrderValues = map["draworder"]; + var drawOrderValues = map["drawOrder"]; + if (!drawOrderValues) drawOrderValues = map["draworder"]; if (drawOrderValues) { var timeline = new spine.DrawOrderTimeline(drawOrderValues.length); var slotCount = skeletonData.slots.length; @@ -1412,7 +1745,58 @@ spine.SkeletonJson.prototype = { 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 "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 "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; } }; @@ -1441,15 +1825,20 @@ spine.Atlas = function (atlasText, textureLoader) { var page = null; while (true) { var line = reader.readLine(); - if (line == null) break; + if (line === null) break; line = reader.trim(line); - if (line.length == 0) + if (!line.length) page = null; else if (!page) { page = new spine.AtlasPage(); page.name = line; - page.format = spine.Atlas.Format[reader.readValue()]; + 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]]; @@ -1468,6 +1857,7 @@ spine.Atlas = function (atlasText, textureLoader) { textureLoader.load(page, line, this); this.pages.push(page); + } else { var region = new spine.AtlasRegion(); region.name = line; @@ -1624,7 +2014,7 @@ spine.AtlasReader.prototype = { if (colon == -1) throw "Invalid line: " + line; return this.trim(line.substring(colon + 1)); }, - /** Returns the number of tuple values read (2 or 4). */ + /** Returns the number of tuple values read (1, 2 or 4). */ readTuple: function (tuple) { var line = this.readLine(); var colon = line.indexOf(":"); @@ -1632,10 +2022,7 @@ spine.AtlasReader.prototype = { var i = 0, lastMatch = colon + 1; for (; i < 3; i++) { var comma = line.indexOf(",", lastMatch); - if (comma == -1) { - if (i == 0) throw "Invalid line: " + line; - break; - } + if (comma == -1) break; tuple[i] = this.trim(line.substr(lastMatch, comma - lastMatch)); lastMatch = comma + 1; } @@ -1648,25 +2035,58 @@ spine.AtlasAttachmentLoader = function (atlas) { this.atlas = atlas; }; spine.AtlasAttachmentLoader.prototype = { - newAttachment: function (skin, type, name) { - switch (type) { - case spine.AttachmentType.boundingbox: - return new spine.BoundingBoxAttachment(name); - case spine.AttachmentType.region: - var region = this.atlas.findRegion(name); - if (!region) throw "Region not found in atlas: " + name + " (" + type + ")"; - 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; - } - throw "Unknown attachment type: " + type; + newRegionAttachment: function (skin, name, path) { + var region = this.atlas.findRegion(name); + if (!region) throw "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(name); + if (!region) throw "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(name); + if (!region) throw "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); } }; From b36b7d6f94fe1d54178e2251cb786cba49e27716 Mon Sep 17 00:00:00 2001 From: Igor Mats Date: Sat, 31 Jan 2015 12:10:09 +0200 Subject: [PATCH 0258/1345] Fix issue with spine content size. --- extensions/spine/CCSkeleton.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/extensions/spine/CCSkeleton.js b/extensions/spine/CCSkeleton.js index 0e4aadd472..cf64429e28 100644 --- a/extensions/spine/CCSkeleton.js +++ b/extensions/spine/CCSkeleton.js @@ -291,6 +291,8 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ * @param {spine.SkeletonData} ownsSkeletonData */ setSkeletonData: function (skeletonData, ownsSkeletonData) { + this.setContentSize(skeletonData.width / cc.director.getContentScaleFactor(), skeletonData.height / cc.director.getContentScaleFactor()); + this._skeleton = new spine.Skeleton(skeletonData); this._rootBone = this._skeleton.getRootBone(); this._ownsSkeletonData = ownsSkeletonData; From f53e471e9befdd6d22908245c8e9dbd79810d62d Mon Sep 17 00:00:00 2001 From: pandamicro Date: Sun, 1 Feb 2015 17:24:41 +0800 Subject: [PATCH 0259/1345] Upgrade docs for v3.3 RC0 release --- AUTHORS.txt | 1 + CHANGELOG.txt | 28 ++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/AUTHORS.txt b/AUTHORS.txt index 5777d39dcd..f38d11180d 100644 --- a/AUTHORS.txt +++ b/AUTHORS.txt @@ -187,6 +187,7 @@ Xiaodong Liu @tianxing113 cc.Spawn.create bug fix Park Hyun Chen @sincntx Touch anywhere of screen to finish input when using cc.EditBox ccui.TextBMFont bug fix cc.game bug fix + Fixed an issue of cc.ArmatureAnimation's setMovementEventCallFunc Ninja Lau @mutoo A typo bug in UILayout fix One-loop CCArmatureAnimation can't finish when setSpeedScale is less than 1.0 bug fix diff --git a/CHANGELOG.txt b/CHANGELOG.txt index c61ba3f643..e72346566d 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,5 +1,33 @@ ChangeLog: +Cocos2d-JS v3.3 RC0 @ Reb.1, 2015 + +* Added web exclusive functions: `_getFontStyle`, `_setFontStyle`, `_getFontWeight` and `_setFontWeight` APIs to `cc.LabelTTF`. +* Observed orientation change event on mobile for resolution policy adaptation. + +* Bug fixes: + 1. Fixed Cocos Studio JSON parser's issues for parsing nested animation. + 2. Fixed Cocos Studio JSON parser's parameters parsing issues. + 3. Fixed Cocos Studio JSON parser's issue for parsing layer. + 4. Fixed Cocos Studio JSON action parser's issues. + 5. Fixed Cocos Studio JSON parser's issue for parsing Scale9Sprite. + 6. Fixed Cocos Studio JSON parser's issues caused by parsing process order. + 7. Fixed Cocos Studio JSON parser's issue for parsing loading bar's direction. + 8. Fixed UI layout system issues. + 9. Fixed `cc.EditBox`'s position issue under certain resolution policies. + 10. Fixed `ccui.ListView`'s issue for setting direction. + 11. Fixed an issue of `cc.Tween` that its `_currentPercent` is incorrect in `updateHandler` function. + 12. Fixed an issue of `ccui.Button` that its state is incorrect in `_onPressStateChangedToNormal`. + 13. Fixed an issue of `cc.ArmatureAnimation`'s `setMovementEventCallFunc`. + 14. Fixed an issue of `cc.Sequence` action when it's repeated. + 15. Fixed `_anchorPointInPoints` usage issue. + 16. Fixed an issue of `cc.GLProgram` that it doesn't work on some devices which didn't support highp float precision. + 17. Fixed an issue of fade actions that they don't work when duration is 0. + 18. Fixed `onended` callback issue of audio engine on iOS. + 19. Fixed Cocos Builder's parser issue for auto playing animations. + 20. Added a message to `ccs.Armature` that it doesn't support adding widget as its child. + 21. Improved test cases for stability. + Cocos2d-JS v3.3 Beta @ Jan.24, 2015 * Added Cocos Studio v2.x parser and refactored 1.x parser. From c95fa77176624904d3546ec1cd3aa6cd608c3766 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 2 Feb 2015 11:45:16 +0800 Subject: [PATCH 0260/1345] ccs.load add info for armature file --- extensions/cocostudio/loader/load.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/extensions/cocostudio/loader/load.js b/extensions/cocostudio/loader/load.js index ec49ad7e9a..ee106266c7 100644 --- a/extensions/cocostudio/loader/load.js +++ b/extensions/cocostudio/loader/load.js @@ -59,6 +59,12 @@ ccs._load = (function(){ 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 new ccs.Armature('name');"); + return new cc.Node(); + } var currentParser = getParser(parse, version); if(!currentParser){ cc.log("Can't find the parser : %s", file); From b139f9e94c3417387156d00a61c3776dba900240 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 3 Feb 2015 09:46:58 +0800 Subject: [PATCH 0261/1345] Fixed ccs.load warn info --- extensions/cocostudio/loader/load.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/cocostudio/loader/load.js b/extensions/cocostudio/loader/load.js index ee106266c7..4a46b956b7 100644 --- a/extensions/cocostudio/loader/load.js +++ b/extensions/cocostudio/loader/load.js @@ -62,7 +62,7 @@ ccs._load = (function(){ 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 new ccs.Armature('name');"); + cc.warn(" var armature = new ccs.Armature('name');"); return new cc.Node(); } var currentParser = getParser(parse, version); From 537d9af305cbea468ea812d4a033823e4a13a3c9 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Tue, 3 Feb 2015 11:53:44 +0800 Subject: [PATCH 0262/1345] Fixed some issues for the latest spine runtime. --- cocos2d/core/sprites/CCSprite.js | 5 ++-- .../core/sprites/CCSpriteCanvasRenderCmd.js | 16 +++++++++---- extensions/spine/CCSkeleton.js | 3 ++- extensions/spine/CCSkeletonAnimation.js | 4 ++-- extensions/spine/CCSkeletonCanvasRenderCmd.js | 24 +++++++++++++++---- 5 files changed, 37 insertions(+), 15 deletions(-) diff --git a/cocos2d/core/sprites/CCSprite.js b/cocos2d/core/sprites/CCSprite.js index c6d5d7a984..e47ecb4f52 100644 --- a/cocos2d/core/sprites/CCSprite.js +++ b/cocos2d/core/sprites/CCSprite.js @@ -679,14 +679,15 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * @param {cc.Texture2D|HTMLImageElement|HTMLCanvasElement} texture A pointer to an existing CCTexture2D object. You can use a CCTexture2D object for many sprites. * @param {cc.Rect} [rect] Only the contents inside rect of this texture will be applied for this sprite. * @param {Boolean} [rotated] Whether or not the texture rectangle is rotated. + * @param {Boolean} [counterclockwise=true] Whether or not the texture rectangle rotation is counterclockwise (texture package is counterclockwise, spine is clockwise). * @return {Boolean} true if the sprite is initialized properly, false otherwise. */ - initWithTexture: function (texture, rect, rotated) { + initWithTexture: function (texture, rect, rotated, counterclockwise) { var _t = this; cc.assert(arguments.length != 0, cc._LogInfos.CCSpriteBatchNode_initWithTexture); rotated = rotated || false; - texture = this._renderCmd._handleTextureForRotatedTexture(texture, rect, rotated); + texture = this._renderCmd._handleTextureForRotatedTexture(texture, rect, rotated, counterclockwise); if (!cc.Node.prototype.init.call(_t)) return false; diff --git a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js index 05984018fd..51ae6f1524 100644 --- a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js @@ -88,14 +88,15 @@ return true; }; - proto._handleTextureForRotatedTexture = function (texture, rect, rotated) { + proto._handleTextureForRotatedTexture = function (texture, rect, rotated, counterclockwise) { if (rotated && texture.isLoaded()) { var tempElement = texture.getHtmlElementObj(); - tempElement = cc.Sprite.CanvasRenderCmd._cutRotateImageToCanvas(tempElement, rect); + tempElement = cc.Sprite.CanvasRenderCmd._cutRotateImageToCanvas(tempElement, rect, counterclockwise); var tempTexture = new cc.Texture2D(); tempTexture.initWithElement(tempElement); tempTexture.handleLoadedTexture(); texture = tempTexture; + rect.x = rect.y = 0; this._node._rect = cc.rect(0, 0, rect.width, rect.height); } return texture; @@ -123,9 +124,9 @@ 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); - wrapper.setTransform(this._worldTransform, scaleX, scaleY); if(node._flippedX || node._flippedY) wrapper.save(); @@ -493,19 +494,24 @@ cc.Sprite.CanvasRenderCmd._generateTextureCacheForColor.tempCanvas = cc.newElement('canvas'); cc.Sprite.CanvasRenderCmd._generateTextureCacheForColor.tempCtx = cc.Sprite.CanvasRenderCmd._generateTextureCacheForColor.tempCanvas.getContext('2d'); - cc.Sprite.CanvasRenderCmd._cutRotateImageToCanvas = function (texture, rect) { + cc.Sprite.CanvasRenderCmd._cutRotateImageToCanvas = function (texture, rect, counterclockwise) { if (!texture) return null; if (!rect) return texture; + counterclockwise = counterclockwise == null? true: counterclockwise; // texture package is counterclockwise, spine is clockwise + var nCanvas = cc.newElement("canvas"); nCanvas.width = rect.width; nCanvas.height = rect.height; var ctx = nCanvas.getContext("2d"); ctx.translate(nCanvas.width / 2, nCanvas.height / 2); - ctx.rotate(-1.5707963267948966); + if(counterclockwise) + ctx.rotate(-1.5707963267948966); + else + ctx.rotate(1.5707963267948966); ctx.drawImage(texture, rect.x, rect.y, rect.height, rect.width, -rect.height / 2, -rect.width / 2, rect.height, rect.width); return nCanvas; }; diff --git a/extensions/spine/CCSkeleton.js b/extensions/spine/CCSkeleton.js index cf64429e28..28b49bebd1 100644 --- a/extensions/spine/CCSkeleton.js +++ b/extensions/spine/CCSkeleton.js @@ -291,7 +291,8 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ * @param {spine.SkeletonData} ownsSkeletonData */ setSkeletonData: function (skeletonData, ownsSkeletonData) { - this.setContentSize(skeletonData.width / cc.director.getContentScaleFactor(), skeletonData.height / cc.director.getContentScaleFactor()); + 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._rootBone = this._skeleton.getRootBone(); diff --git a/extensions/spine/CCSkeletonAnimation.js b/extensions/spine/CCSkeletonAnimation.js index 19a2884e9b..58ecb7351a 100644 --- a/extensions/spine/CCSkeletonAnimation.js +++ b/extensions/spine/CCSkeletonAnimation.js @@ -79,7 +79,7 @@ sp._regionAttachment_computeWorldVertices = function(self, x, y, bone, vertices) sp._regionAttachment_updateQuad = function(self, slot, quad, premultipliedAlpha) { var vertices = {}; - self.computeVertices(slot.skeleton.x, slot.skeleton.y, slot.bone, vertices); + self.computeVertices(slot.skeleton.x, slot.skeleton.y, slot, vertices); var r = slot.skeleton.r * slot.r * 255; var g = slot.skeleton.g * slot.g * 255; var b = slot.skeleton.b * slot.b * 255; @@ -160,7 +160,7 @@ sp._regionAttachment_updateSlotForCanvas = function(self, slot, points) { return; var vertices = {}; - self.computeVertices(slot.skeleton.x, slot.skeleton.y, slot.bone, vertices); + self.computeVertices(slot.skeleton.x, slot.skeleton.y, slot, vertices); var VERTEX = sp.VERTEX_INDEX; points.length = 0; points.push(cc.p(vertices[VERTEX.X1], vertices[VERTEX.Y1])); diff --git a/extensions/spine/CCSkeletonCanvasRenderCmd.js b/extensions/spine/CCSkeletonCanvasRenderCmd.js index 5bad93ef87..d887f6d791 100644 --- a/extensions/spine/CCSkeletonCanvasRenderCmd.js +++ b/extensions/spine/CCSkeletonCanvasRenderCmd.js @@ -43,7 +43,7 @@ wrapper._switchToArmatureMode(true, this._worldTransform, scaleX, scaleY); for(i = 0, n = sprites.length; i < n; i++){ selSpriteCmd = sprites[i]._renderCmd; - if(selSpriteCmd && selSpriteCmd.rendering){ + if(sprites[i]._visible && selSpriteCmd && selSpriteCmd.rendering){ selSpriteCmd.rendering(wrapper, scaleX, scaleY); selSpriteCmd._dirtyFlag = 0; } @@ -111,7 +111,12 @@ continue; rendererObject = attachment.rendererObject; rect = cc.rect(rendererObject.x, rendererObject.y, rendererObject.width,rendererObject.height); - var sprite = new cc.Sprite(rendererObject.page._texture, rect, rendererObject.rotate); + var sprite = new cc.Sprite(); + sprite.initWithTexture(rendererObject.page._texture, rect, rendererObject.rotate, false); + sprite._rect.width = attachment.width; + sprite._rect.height = attachment.height; + sprite.setContentSize(attachment.width, attachment.height); + sprite.setRotation(-(slot.bone.worldRotation + attachment.rotation)); this._skeletonSprites.push(sprite); slot.currentSprite = sprite; } @@ -133,9 +138,13 @@ if(!selSprite){ var rendererObject = attachment.rendererObject; var rect = cc.rect(rendererObject.x, rendererObject.y, rendererObject.width,rendererObject.height); - var sprite = new cc.Sprite(rendererObject.page._texture, rect, rendererObject.rotate); + var sprite = new cc.Sprite(); + sprite.initWithTexture(rendererObject.page._texture, rect, rendererObject.rotate, false); + sprite._rect.width = attachment.width; + sprite._rect.height = attachment.height; + sprite.setContentSize(attachment.width, attachment.height); this._skeletonSprites.push(sprite); - slot.currentSprite = sprite; + selSprite = slot.currentSprite = sprite; } selSprite.setVisible(true); //update color and blendFunc @@ -145,7 +154,12 @@ selSprite.setPosition(bone.worldX + attachment.x * bone.m00 + attachment.y * bone.m01, bone.worldY + attachment.x * bone.m10 + attachment.y * bone.m11); selSprite.setScale(bone.worldScaleX, bone.worldScaleY); - selSprite.setRotation(- (slot.bone.worldRotation + attachment.rotation)); + selSprite.setRotation(-(slot.bone.worldRotation + attachment.rotation)); + selSprite.setOpacity(0 | (slot.skeleton.a * slot.a * 255)); + var r = 0 | (slot.skeleton.r * slot.r * 255); + var g = 0 | (slot.skeleton.g * slot.g * 255); + var b = 0 | (slot.skeleton.b * slot.b * 255); + selSprite.setColor(cc.color(r,g,b)); } }; })(); \ No newline at end of file From 28c9dc0038654f2447cbc78b65fb030c8d5a9a33 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Tue, 3 Feb 2015 14:36:04 +0800 Subject: [PATCH 0263/1345] Fixed a bug of cc.Sprite that its setSpriteFrame doesn't work when SpriteFrame's rotated is true. --- cocos2d/core/sprites/CCSprite.js | 6 +----- extensions/cocostudio/loader/parsers/timelineParser-2.x.js | 1 - 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/cocos2d/core/sprites/CCSprite.js b/cocos2d/core/sprites/CCSprite.js index e47ecb4f52..876b5def45 100644 --- a/cocos2d/core/sprites/CCSprite.js +++ b/cocos2d/core/sprites/CCSprite.js @@ -831,8 +831,6 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ _t._unflippedOffsetPositionFromCenter.y = frameOffset.y; // update rect - _t._rectRotated = newFrame.isRotated(); - var pNewTexture = newFrame.getTexture(); var locTextureLoaded = newFrame.textureLoaded(); if (!locTextureLoaded) { @@ -850,10 +848,8 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ // update texture before updating texture rect if (pNewTexture != _t._texture) _t.texture = pNewTexture; - - _t.setTextureRect(newFrame.getRect(), _t._rectRotated, newFrame.getOriginalSize()); + _t.setTextureRect(newFrame.getRect(), newFrame.isRotated(), newFrame.getOriginalSize()); } - this._renderCmd._updateForSetSpriteFrame(pNewTexture); }, diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 6c1cfbb85c..5ecff16100 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -171,7 +171,6 @@ var spriteFrame = cc.spriteFrameCache.getSpriteFrame(path); node.setSpriteFrame(spriteFrame); } - }); if(json["FlipX"]) From 101138176baadfec0a0891cc3ac6656ab69ceb4b Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 3 Feb 2015 15:36:50 +0800 Subject: [PATCH 0264/1345] Project.json add noCache options --- CCBoot.js | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/CCBoot.js b/CCBoot.js index c0b3919823..ca81412fce 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -604,8 +604,15 @@ cc.loader = /** @lends cc.loader# */{ _createScript: function (jsPath, isAsync, cb) { var d = document, self = this, s = cc.newElement('script'); s.async = isAsync; - s.src = jsPath; self._jsCache[jsPath] = true; + if(cc.game.config["noCache"] && typeof jsPath === "string"){ + if(self._noCacheRex.test(jsPath)) + s.src = jsPath + "&_t=" + (new Date() - 0); + else + s.src = jsPath + "?_t=" + (new Date() - 0); + }else{ + s.src = jsPath; + } cc._addEventListener(s, 'load', function () { s.parentNode.removeChild(s); this.removeEventListener('load', arguments.callee, false); @@ -834,6 +841,12 @@ cc.loader = /** @lends cc.loader# */{ } var basePath = loader.getBasePath ? loader.getBasePath() : self.resPath; var realUrl = self.getUrl(basePath, url); + if(cc.game.config["noCache"] && typeof realUrl === "string"){ + if(self._noCacheRex.test(realUrl)) + realUrl += "&_t=" + (new Date() - 0); + else + realUrl += "?_t=" + (new Date() - 0); + } loader.load(realUrl, url, item, function (err, data) { if (err) { cc.log(err); @@ -846,6 +859,7 @@ cc.loader = /** @lends cc.loader# */{ } }); }, + _noCacheRex: /\?/, /** * Get url with basePath. From ca035cc34e6bbf9861f28a3c08041578b510402c Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 3 Feb 2015 15:36:50 +0800 Subject: [PATCH 0265/1345] Project.json add noCache options --- CCBoot.js | 16 +++++++++++++++- template/project.json | 1 + 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/CCBoot.js b/CCBoot.js index c0b3919823..ca81412fce 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -604,8 +604,15 @@ cc.loader = /** @lends cc.loader# */{ _createScript: function (jsPath, isAsync, cb) { var d = document, self = this, s = cc.newElement('script'); s.async = isAsync; - s.src = jsPath; self._jsCache[jsPath] = true; + if(cc.game.config["noCache"] && typeof jsPath === "string"){ + if(self._noCacheRex.test(jsPath)) + s.src = jsPath + "&_t=" + (new Date() - 0); + else + s.src = jsPath + "?_t=" + (new Date() - 0); + }else{ + s.src = jsPath; + } cc._addEventListener(s, 'load', function () { s.parentNode.removeChild(s); this.removeEventListener('load', arguments.callee, false); @@ -834,6 +841,12 @@ cc.loader = /** @lends cc.loader# */{ } var basePath = loader.getBasePath ? loader.getBasePath() : self.resPath; var realUrl = self.getUrl(basePath, url); + if(cc.game.config["noCache"] && typeof realUrl === "string"){ + if(self._noCacheRex.test(realUrl)) + realUrl += "&_t=" + (new Date() - 0); + else + realUrl += "?_t=" + (new Date() - 0); + } loader.load(realUrl, url, item, function (err, data) { if (err) { cc.log(err); @@ -846,6 +859,7 @@ cc.loader = /** @lends cc.loader# */{ } }); }, + _noCacheRex: /\?/, /** * Get url with basePath. diff --git a/template/project.json b/template/project.json index 0c277b291a..6c2c93bd3d 100644 --- a/template/project.json +++ b/template/project.json @@ -1,5 +1,6 @@ { "debugMode" : 1, + "noCache": true, "showFPS" : true, "frameRate" : 60, "id" : "gameCanvas", From fb620c870bfe9d67cadf33ab6b555803e60e121a Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 3 Feb 2015 16:08:21 +0800 Subject: [PATCH 0266/1345] Project.json add noCache options --- cocos2d/audio/CCAudio.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index ab5dc5478a..4c4b565d32 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -504,8 +504,8 @@ cc.Audio = cc.Class.extend({ var audio; - if(loader.cache[realUrl]) - return cb(null, loader.cache[realUrl]); + if(loader.cache[url]) + return cb(null, loader.cache[url]); if(SWA){ var volume = context["createGain"](); @@ -518,7 +518,7 @@ cc.Audio = cc.Class.extend({ this.loadAudioFromExtList(realUrl, typeList, audio, cb); - loader.cache[realUrl] = audio; + loader.cache[url] = audio; }, From ea88b6e4c213d778f2cd539d0de16f67c39ff46a Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Wed, 4 Feb 2015 11:12:50 +0800 Subject: [PATCH 0267/1345] Fixed #2556: set the default value of ParticleSystem's draw mode to texture mode --- cocos2d/particle/CCParticleSystemCanvasRenderCmd.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js b/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js index 7b316d3ed3..8420e8e1e2 100644 --- a/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js +++ b/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js @@ -30,7 +30,7 @@ cc.Node.CanvasRenderCmd.call(this, renderable); this._needDraw = true; - this._drawMode = cc.ParticleSystem.SHAPE_MODE; + this._drawMode = cc.ParticleSystem.TEXTURE_MODE; this._shapeType = cc.ParticleSystem.BALL_SHAPE; this._pointRect = cc.rect(0, 0, 0, 0); @@ -82,9 +82,9 @@ var i, particle, lpx, alpha; var particleCount = this._node.particleCount, particles = this._node._particles; - if (node.drawMode == cc.ParticleSystem.TEXTURE_MODE) { + if (node.drawMode !== cc.ParticleSystem.SHAPE_MODE && node._texture) { // Delay drawing until the texture is fully loaded by the browser - if (!node._texture || !node._texture._textureLoaded) { + if (!node._texture._textureLoaded) { wrapper.restore(); return; } From ceee24c74f0d769dc835fa7d6c98e623c08b1183 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 4 Feb 2015 14:20:47 +0800 Subject: [PATCH 0268/1345] =?UTF-8?q?Issue=20#2670:=20We=20should=20judge?= =?UTF-8?q?=20whether=20the=20stencil=20is=20drawNode,=20don=E2=80=98t=20j?= =?UTF-8?q?udge=20is=20Sprite?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js b/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js index 4f2b5ece54..5e237d7c48 100644 --- a/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js +++ b/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js @@ -180,10 +180,10 @@ parentCmd = parentCmd || this.getParentRenderCmd(); if( parentCmd) this._curLevel = parentCmd._curLevel + 1; - var transformRenderCmd = (node._stencil instanceof cc.Sprite) ? this : null; + var transformRenderCmd = this; // Composition mode, costy but support texture stencil - this._clipElemType = (this._cangodhelpme() || node._stencil instanceof cc.Sprite); + this._clipElemType = !(!this._cangodhelpme() && node._stencil instanceof cc.DrawNode); if (!node._stencil || !node._stencil.visible) { if (this.inverted) cc.Node.CanvasRenderCmd.prototype.visit.call(this, parentCmd); // draw everything From d97d9a521b936cec2261afe7fd756a653426c764 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 4 Feb 2015 14:50:43 +0800 Subject: [PATCH 0269/1345] Fixed ccui position error --- extensions/cocostudio/loader/parsers/timelineParser-2.x.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index 5ecff16100..7b719077a0 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -132,8 +132,6 @@ var anchor = node.getAnchorPoint(); child.setPositionPercent(cc.p(position.x + anchor.x, position.y + anchor.y)); } - var AnchorPointIn = node.getAnchorPointInPoints(); - child.setPosition(cc.p(child.getPositionX() + AnchorPointIn.x, child.getPositionY() + AnchorPointIn.y)); } node.addChild(child); } From 048f51398bc3552d41ce22536691acc58543f1b7 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 4 Feb 2015 14:55:45 +0800 Subject: [PATCH 0270/1345] Fixed ccui position error --- extensions/cocostudio/loader/parsers/timelineParser-1.x.js | 1 + 1 file changed, 1 insertion(+) diff --git a/extensions/cocostudio/loader/parsers/timelineParser-1.x.js b/extensions/cocostudio/loader/parsers/timelineParser-1.x.js index e5f6b8ef8e..5b0c849df9 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-1.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-1.x.js @@ -147,6 +147,7 @@ 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)); } From 3769b24f5ce10d0ea665e01fbb00d00b3c7f319c Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 4 Feb 2015 17:19:30 +0800 Subject: [PATCH 0271/1345] UPDATE CANVAS TRANSFORM --- .../core/base-nodes/CCNodeCanvasRenderCmd.js | 73 ++++++++++--------- 1 file changed, 38 insertions(+), 35 deletions(-) diff --git a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js index 9b0859b5bf..25eb9d0e84 100644 --- a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js @@ -249,7 +249,6 @@ cc.Node.RenderCmd.prototype = { proto.constructor = cc.Node.CanvasRenderCmd; proto.transform = function (parentCmd, recursive) { - var node = this._node; // transform for canvas var t = this.getNodeToParentTransform(), worldT = this._worldTransform; //get the world transform @@ -262,26 +261,8 @@ cc.Node.RenderCmd.prototype = { worldT.c = pt.c * t.a + pt.d * t.c; //c worldT.d = pt.c * t.b + pt.d * t.d; //d - worldT.tx = pt.a * t.tx - pt.b * t.ty + pt.tx ; - worldT.ty = -pt.c * t.tx + pt.d * t.ty + pt.ty; - - var lScaleX = node._scaleX, lScaleY = node._scaleY; - // Firefox on Vista and XP crashes - // GPU thread in case of scale(0.0, 0.0) - var sx = (lScaleX < 0.000001 && lScaleX > -0.000001) ? 0.000001 : lScaleX, - sy = (lScaleY < 0.000001 && lScaleY > -0.000001) ? 0.000001 : lScaleY; - var appX = this._anchorPointInPoints.x / lScaleX, - appY = this._anchorPointInPoints.y / lScaleY; - - // adjust anchorPoint - worldT.tx += worldT.a * -appX * sx + worldT.b * appY * sy; - worldT.ty -= worldT.c * -appX * sx + worldT.d * appY * sy; - - // if ignore anchorPoint - if (this._node._ignoreAnchorPointForPosition) { - worldT.tx += appX; - worldT.ty += appY; - } + worldT.tx = pt.a * t.tx - pt.b * t.ty + pt.tx; + worldT.ty = pt.d * t.ty + pt.ty - pt.c * t.tx; } else { worldT.a = t.a; worldT.b = t.b; @@ -317,33 +298,33 @@ cc.Node.RenderCmd.prototype = { t.tx = node._position.x; t.ty = node._position.y; - var lScaleX = node._scaleX, lScaleY = node._scaleY; - - // Firefox on Vista and XP crashes - // GPU thread in case of scale(0.0, 0.0) - var sx = (lScaleX < 0.000001 && lScaleX > -0.000001) ? 0.000001 : lScaleX, - sy = (lScaleY < 0.000001 && lScaleY > -0.000001) ? 0.000001 : lScaleY; - // rotation Cos and Sin - var A = sx, B = 0, - C = 0, D = sy; + var A = 1, B = 0, + C = 0, D = 1; if (node._rotationX) { var rotationRadiansX = node._rotationX * 0.017453292519943295; //0.017453292519943295 = (Math.PI / 180); for performance - B = -Math.sin(rotationRadiansX) * sy; - D = Math.cos(rotationRadiansX) * sy; + B = -Math.sin(rotationRadiansX); + D = Math.cos(rotationRadiansX); } if (node._rotationY) { var rotationRadiansY = node._rotationY * 0.017453292519943295; //0.017453292519943295 = (Math.PI / 180); for performance - A = Math.cos(rotationRadiansY) * sx; - C = Math.sin(rotationRadiansY) * sx; + A = Math.cos(rotationRadiansY); + C = Math.sin(rotationRadiansY); } - t.a = A; t.b = B; t.c = C; t.d = D; + var lScaleX = node._scaleX, lScaleY = node._scaleY; + var appX = this._anchorPointInPoints.x, appY = this._anchorPointInPoints.y; + + // Firefox on Vista and XP crashes + // GPU thread in case of scale(0.0, 0.0) + var sx = (lScaleX < 0.000001 && lScaleX > -0.000001) ? 0.000001 : lScaleX, + sy = (lScaleY < 0.000001 && lScaleY > -0.000001) ? 0.000001 : lScaleY; + // skew if (node._skewX || node._skewY) { // offset the anchorpoint @@ -353,10 +334,32 @@ cc.Node.RenderCmd.prototype = { skx = 99999999; if (sky === Infinity) sky = 99999999; + var xx = appY * skx * sx; + var yy = appX * sky * sy; t.a = A + B * sky; t.b = A * skx + B; t.c = C + D * sky; t.d = C * skx + D; + t.tx += A * xx + B * yy; + t.ty += C * xx + D * yy; + } + + // scale + if (lScaleX !== 1 || lScaleY !== 1) { + t.a *= sx; + t.c *= sx; + t.b *= sy; + t.d *= sy; + } + + // adjust anchorPoint + t.tx += A * -appX * sx + B * appY * sy; + t.ty -= C * -appX * sx + D * appY * sy; + + // if ignore anchorPoint + if (node._ignoreAnchorPointForPosition) { + t.tx += appX; + t.ty += appY; } if (node._additionalTransformDirty) { From 6dbe0e5a2836ef27ff929a150c992cb5a8e9f597 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 4 Feb 2015 17:28:46 +0800 Subject: [PATCH 0272/1345] UPDATE CANVAS TRANSFORM --- .../CCProtectedNodeCanvasRenderCmd.js | 22 ++----------------- 1 file changed, 2 insertions(+), 20 deletions(-) diff --git a/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js b/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js index 60d1c3dc84..25cfd9169d 100644 --- a/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js +++ b/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js @@ -214,26 +214,8 @@ worldT.c = pt.c * t.a + pt.d * t.c; //c worldT.d = pt.c * t.b + pt.d * t.d; //d - worldT.tx = pt.a * t.tx - pt.b * t.ty + pt.tx ; - worldT.ty = -pt.c * t.tx + pt.d * t.ty + pt.ty; - - var lScaleX = node._scaleX, lScaleY = node._scaleY; - // Firefox on Vista and XP crashes - // GPU thread in case of scale(0.0, 0.0) - var sx = (lScaleX < 0.000001 && lScaleX > -0.000001) ? 0.000001 : lScaleX, - sy = (lScaleY < 0.000001 && lScaleY > -0.000001) ? 0.000001 : lScaleY; - var appX = this._anchorPointInPoints.x / lScaleX, - appY = this._anchorPointInPoints.y / lScaleY; - - // adjust anchorPoint - worldT.tx += worldT.a * -appX * sx + worldT.b * appY * sy; - worldT.ty -= worldT.c * -appX * sx + worldT.d * appY * sy; - - // if ignore anchorPoint - if (this._node._ignoreAnchorPointForPosition) { - worldT.tx += appX; - worldT.ty += appY; - } + worldT.tx = pt.a * t.tx - pt.b * t.ty + pt.tx; + worldT.ty = pt.d * t.ty + pt.ty - pt.c * t.tx; } else { worldT.a = t.a; worldT.b = t.b; From 76b7c9baf9875b7dfd8d228d7f4755924d547d88 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 4 Feb 2015 18:15:46 +0800 Subject: [PATCH 0273/1345] UPDATE CANVAS TRANSFORM --- .../core/base-nodes/CCNodeCanvasRenderCmd.js | 36 +++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js index 25eb9d0e84..9027f2ab0d 100644 --- a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js @@ -299,23 +299,23 @@ cc.Node.RenderCmd.prototype = { t.ty = node._position.y; // rotation Cos and Sin - var A = 1, B = 0, - C = 0, D = 1; + var a = 1, b = 0, + c = 0, d = 1; if (node._rotationX) { var rotationRadiansX = node._rotationX * 0.017453292519943295; //0.017453292519943295 = (Math.PI / 180); for performance - B = -Math.sin(rotationRadiansX); - D = Math.cos(rotationRadiansX); + b = -Math.sin(rotationRadiansX); + d = Math.cos(rotationRadiansX); } if (node._rotationY) { var rotationRadiansY = node._rotationY * 0.017453292519943295; //0.017453292519943295 = (Math.PI / 180); for performance - A = Math.cos(rotationRadiansY); - C = Math.sin(rotationRadiansY); + a = Math.cos(rotationRadiansY); + c = Math.sin(rotationRadiansY); } - t.a = A; - t.b = B; - t.c = C; - t.d = D; + t.a = a; + t.b = b; + t.c = c; + t.d = d; var lScaleX = node._scaleX, lScaleY = node._scaleY; var appX = this._anchorPointInPoints.x, appY = this._anchorPointInPoints.y; @@ -336,12 +336,12 @@ cc.Node.RenderCmd.prototype = { sky = 99999999; var xx = appY * skx * sx; var yy = appX * sky * sy; - t.a = A + B * sky; - t.b = A * skx + B; - t.c = C + D * sky; - t.d = C * skx + D; - t.tx += A * xx + B * yy; - t.ty += C * xx + D * yy; + t.a = a + b * sky; + t.b = a * skx + b; + t.c = c + d * sky; + t.d = c * skx + d; + t.tx += a * xx + b * yy; + t.ty += c * xx + d * yy; } // scale @@ -353,8 +353,8 @@ cc.Node.RenderCmd.prototype = { } // adjust anchorPoint - t.tx += A * -appX * sx + B * appY * sy; - t.ty -= C * -appX * sx + D * appY * sy; + t.tx += a * -appX * sx + b * appY * sy; + t.ty -= c * -appX * sx + d * appY * sy; // if ignore anchorPoint if (node._ignoreAnchorPointForPosition) { From 8031e0ddbd72b13c070ce07be07342b03e14ece8 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Thu, 5 Feb 2015 10:37:56 +0800 Subject: [PATCH 0274/1345] Fixed #2674: Fixed a bug of cc.PhysicsSprite that setIgnoreBodyRotation doesn't work --- cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js | 2 +- cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js | 8 +++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js b/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js index cb67531c89..ae95d94df9 100644 --- a/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js +++ b/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js @@ -59,7 +59,7 @@ // rotation Cos and Sin var radians = -locBody.a; var Cos = 1, Sin = 0; - if (radians) { + if (radians && !node._ignoreBodyRotation) { Cos = Math.cos(radians); Sin = Math.sin(radians); } diff --git a/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js b/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js index 893c272953..332c8e5d6f 100644 --- a/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js +++ b/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js @@ -59,9 +59,11 @@ } // Make matrix - var radians = locBody.a; - var c = Math.cos(radians); - var s = Math.sin(radians); + 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. From f44f8e87d1755664eca5ead93e3f9f4ad9022e4c Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 5 Feb 2015 11:15:06 +0800 Subject: [PATCH 0275/1345] FiFixed ccui.Button can't set pressed texture, after set setScale9Enabled --- extensions/ccui/uiwidgets/UIButton.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/ccui/uiwidgets/UIButton.js b/extensions/ccui/uiwidgets/UIButton.js index 23dd90d41b..060838e963 100644 --- a/extensions/ccui/uiwidgets/UIButton.js +++ b/extensions/ccui/uiwidgets/UIButton.js @@ -295,7 +295,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ * @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType */ loadTexturePressed: function (selected, texType) { - if (!selected || (this._clickedFileName == selected && this._pressedTexType == texType)) + if (!selected) return; texType = texType || ccui.Widget.LOCAL_TEXTURE; this._clickedFileName = selected; From bdf20698384b806d098fe06007c90b5f97d68984 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Thu, 5 Feb 2015 16:40:13 +0800 Subject: [PATCH 0276/1345] Fixed a bug of ccui.ScrollView that its dir is null when direction is DIR_NONE in _endRecordSlidAction --- extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js index 4c1113aeab..b3bc3e5957 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js @@ -1321,7 +1321,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ if (!this._checkNeedBounce() && this.inertiaScrollEnabled) { if (this._slidTime <= 0.016) return; - var totalDis = 0, dir; + var totalDis = 0, dir = cc.p(0,0); var touchEndPositionInNodeSpace = this.convertToNodeSpace(this._touchEndPosition); var touchBeganPositionInNodeSpace = this.convertToNodeSpace(this._touchBeganPosition); switch (this.direction) { From a86fd5e879573b2f170454322dc482ffc05f512a Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Thu, 5 Feb 2015 16:41:55 +0800 Subject: [PATCH 0277/1345] Fixed a bug of ccui.ScrollView that its dir is null when direction is DIR_NONE in _endRecordSlidAction --- extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js index b3bc3e5957..3bfa11913d 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js @@ -1321,7 +1321,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ if (!this._checkNeedBounce() && this.inertiaScrollEnabled) { if (this._slidTime <= 0.016) return; - var totalDis = 0, dir = cc.p(0,0); + var totalDis = 0, dir; var touchEndPositionInNodeSpace = this.convertToNodeSpace(this._touchEndPosition); var touchBeganPositionInNodeSpace = this.convertToNodeSpace(this._touchBeganPosition); switch (this.direction) { @@ -1339,6 +1339,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ 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); From ef0473f230b6a1d61455b069c013564088293f32 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Fri, 6 Feb 2015 10:13:10 +0800 Subject: [PATCH 0278/1345] Update the AUTHORS.txt for v3.3 final --- AUTHORS.txt | 1 + CHANGELOG.txt | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/AUTHORS.txt b/AUTHORS.txt index f38d11180d..56a564aebf 100644 --- a/AUTHORS.txt +++ b/AUTHORS.txt @@ -220,6 +220,7 @@ Robert Rouhani @Robmaister cc.TMXMapInfo bug fix cc.TMXLayer bug fix Igor Mats @IgorMats cc.Scale9Sprite bug fix + Spine runtime update Tim @duhaibo0404 ccs.csLoader bug fix diff --git a/CHANGELOG.txt b/CHANGELOG.txt index e72346566d..7eb4179d7c 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,6 +1,6 @@ ChangeLog: -Cocos2d-JS v3.3 RC0 @ Reb.1, 2015 +Cocos2d-JS v3.3 RC0 @ Feb.1, 2015 * Added web exclusive functions: `_getFontStyle`, `_setFontStyle`, `_getFontWeight` and `_setFontWeight` APIs to `cc.LabelTTF`. * Observed orientation change event on mobile for resolution policy adaptation. From 2fc54d1d15e8e6a9733890f7155f65882563de21 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 6 Feb 2015 13:36:49 +0800 Subject: [PATCH 0279/1345] [Cocos2d-JS] v3.3 Release doc --- CHANGELOG.txt | 18 +++++++++++++++++- cocos2d/core/platform/CCConfig.js | 2 +- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.txt b/CHANGELOG.txt index e72346566d..58ea7b6413 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,6 +1,22 @@ ChangeLog: -Cocos2d-JS v3.3 RC0 @ Reb.1, 2015 +Cocos2d-JS v3.3 @ Feb.9, 2015 + +* Upgraded spine runtime to support the latest version and updated its test case. +* Added an option "noCache" for debugging on browsers. +* Set the default value of `cc.ParticleSystem`'s draw mode to texture mode. +* Added message to `ccs.load` when loading armature json file. +* Improved particle system test case. + +* Bug fixes: + 1. Fixed a bug of `cc.Sprite` that its `setSpriteFrame` doesn't work when sprite frame's `rotated` property is true. + 2. Fixed a bug of `cc.ClippingNode` when its stencil is `cc.Node` object in canvas mode. + 3. Fixed a ccui bug that the position of widgets is incorrect after loaded v2.x json file with `ccs.load`. + 4. Fixed a bug of `cc.PhysicsSprite` that `setIgnoreBodyRotation` function doesn't work. + 5. Fixed a bug of `ccui.Button` that setting pressed texture doesn't work when scale9 enabled. + 6. Fixed a bug of `ccui.ScrollView` that its `dir` property is null when passing `DIR_NONE` as `direction` in `_endRecordSlidAction` function. + +Cocos2d-JS v3.3 RC0 @ Feb.1, 2015 * Added web exclusive functions: `_getFontStyle`, `_setFontStyle`, `_getFontWeight` and `_setFontWeight` APIs to `cc.LabelTTF`. * Observed orientation change event on mobile for resolution policy adaptation. diff --git a/cocos2d/core/platform/CCConfig.js b/cocos2d/core/platform/CCConfig.js index 7208062c13..e33721a2b8 100644 --- a/cocos2d/core/platform/CCConfig.js +++ b/cocos2d/core/platform/CCConfig.js @@ -31,7 +31,7 @@ * @type {String} * @name cc.ENGINE_VERSION */ -window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.3 RC0"; +window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.3"; /** *

From 2def33e0eea0f0cbdac6271d64a57cc876707af0 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 6 Feb 2015 15:00:25 +0800 Subject: [PATCH 0280/1345] Fix setAdditionalTransform errors --- cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js index 9027f2ab0d..37410dbd4b 100644 --- a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js @@ -363,7 +363,20 @@ cc.Node.RenderCmd.prototype = { } if (node._additionalTransformDirty) { - this._transform = cc.affineTransformConcat(t, node._additionalTransform); + var additionalTransform = node._additionalTransform; + lScaleX = additionalTransform.a; + lScaleY = additionalTransform.d; + additionalTransform.a = 1; + additionalTransform.d = 1; + this._transform = cc.affineTransformConcat(t, additionalTransform); + + this._transform.a *= lScaleX; + this._transform.d *= lScaleY; + if((lScaleX < 0 && lScaleY > 0) || (lScaleX > 0 && lScaleY < 0)){ + this._transform.b *= -1; + this._transform.c *= -1; + } + node._additionalTransformDirty = false; } } From d32e5e4e2af6a33de98761fe1e5f5426dae9c24d Mon Sep 17 00:00:00 2001 From: Dany Ellement Date: Fri, 6 Feb 2015 10:21:41 -0500 Subject: [PATCH 0281/1345] Allow child renderer to be affected by ccui.RichText's opacity --- extensions/ccui/uiwidgets/UIRichText.js | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/extensions/ccui/uiwidgets/UIRichText.js b/extensions/ccui/uiwidgets/UIRichText.js index 6b44784902..f2f01b523a 100644 --- a/extensions/ccui/uiwidgets/UIRichText.js +++ b/extensions/ccui/uiwidgets/UIRichText.js @@ -545,6 +545,14 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ */ getDescription: function(){ return "RichText"; + }, + /** + * Allow child renderer to be affected by ccui.RichText's opacity + * @param {boolean} value + */ + setCascadeOpacityEnabled: function(value) { + this._super(value); + this._elementRenderersContainer.setCascadeOpacityEnabled(value); } }); From 87bf752f56546577474d4d7589836798bd42cc86 Mon Sep 17 00:00:00 2001 From: Dany Ellement Date: Fri, 6 Feb 2015 10:36:39 -0500 Subject: [PATCH 0282/1345] cc.FontDefinition - inline definition usefull for constructor injection This will be usefull for avoiding countless parameters for LabelTTF and also to allow injection an new instance of FontDefinition directly in LabelTTF constructor --- cocos2d/core/platform/CCTypes.js | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/platform/CCTypes.js b/cocos2d/core/platform/CCTypes.js index fcc16a9b77..4b94fefc96 100644 --- a/cocos2d/core/platform/CCTypes.js +++ b/cocos2d/core/platform/CCTypes.js @@ -338,10 +338,27 @@ cc._Dictionary = cc.Class.extend({ }); /** + * 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 cc.FontDefinition + * @param {Object} properties - (OPTIONAL) Allow inline FontDefinition * @constructor */ -cc.FontDefinition = function () { +cc.FontDefinition = function (properties) { var _t = this; _t.fontName = "Arial"; _t.fontSize = 12; @@ -360,6 +377,14 @@ cc.FontDefinition = function () { _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]; + } + } + }; if (cc._renderType === cc._RENDER_TYPE_WEBGL) { From 7e77e4f1e97efa1d1b5155cb99ad355598a6bf73 Mon Sep 17 00:00:00 2001 From: Dany Ellement Date: Fri, 6 Feb 2015 15:30:27 -0500 Subject: [PATCH 0283/1345] Added LineHeight support in ccui.RichText & FontDefinition Support for RichTextElement - cc.LabelTTF.__getFontHeightByDiv can be resolved by FontDefinition - Added getCanvasFontStr() to cc.FontDefinition + lineHeight support - small fix for clipped text issue --- cocos2d/core/labelttf/CCLabelTTF.js | 29 ++++- .../labelttf/CCLabelTTFCanvasRenderCmd.js | 17 ++- cocos2d/core/platform/CCTypes.js | 11 +- extensions/ccui/uiwidgets/UIRichText.js | 118 +++++++++++++++--- 4 files changed, 152 insertions(+), 23 deletions(-) diff --git a/cocos2d/core/labelttf/CCLabelTTF.js b/cocos2d/core/labelttf/CCLabelTTF.js index db818091b6..02f2b7a21a 100644 --- a/cocos2d/core/labelttf/CCLabelTTF.js +++ b/cocos2d/core/labelttf/CCLabelTTF.js @@ -504,7 +504,12 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ this._fontName = textDefinition.fontName; this._fontSize = textDefinition.fontSize || 12; - this._renderCmd._setFontStyle(this._fontName, this._fontSize, this._fontStyle, this._fontWeight); + + if(textDefinition.lineHeight) + this._lineHeight = textDefinition.lineHeight + + this._renderCmd._setFontStyle(textDefinition); + // shadow if (textDefinition.shadowEnabled) @@ -814,6 +819,27 @@ document.body ? }, false); cc.LabelTTF.__getFontHeightByDiv = function (fontName, fontSize) { + + if(fontName instanceof cc.FontDefinition){ + /** @type cc.FontDefinition */ + var fontDef = fontName; + var clientHeight = cc.LabelTTF.__fontHeightCache[fontDef.getCanvasFontStr()]; + if (clientHeight > 0) return clientHeight; + var labelDiv = cc.LabelTTF.__labelHeightDiv; + labelDiv.innerHTML = "ajghl~!"; + labelDiv.style.fontFamily = fontDef.fontName; + labelDiv.style.fontSize = fontDef.fontSize + "px"; + labelDiv.style.fontStyle = fontDef.fontStyle; + labelDiv.style.fontWeight = fontDef.fontWeight; + //labelDiv.style.lineHeight = fontDef.lineHeight + "px"; //FIXME: the text get clipped here + + clientHeight = labelDiv.clientHeight; + cc.LabelTTF.__fontHeightCache[fontDef.getCanvasFontStr()] = clientHeight; + labelDiv.innerHTML = ""; + return clientHeight; + } + + //Default var clientHeight = cc.LabelTTF.__fontHeightCache[fontName + "." + fontSize]; if (clientHeight > 0) return clientHeight; var labelDiv = cc.LabelTTF.__labelHeightDiv; @@ -824,6 +850,7 @@ cc.LabelTTF.__getFontHeightByDiv = function (fontName, fontSize) { cc.LabelTTF.__fontHeightCache[fontName + "." + fontSize] = clientHeight; labelDiv.innerHTML = ""; return clientHeight; + }; cc.LabelTTF.__fontHeightCache = {}; \ No newline at end of file diff --git a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js index 835175bd50..c167d84f1f 100644 --- a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js +++ b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js @@ -72,9 +72,16 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; return this._labelContext; }; - proto._setFontStyle = function (fontName, fontSize, fontStyle, fontWeight) { - this._fontStyleStr = fontStyle + " " + fontWeight + " " + fontSize + "px '" + fontName + "'"; - this._fontClientHeight = cc.LabelTTF.__getFontHeightByDiv(fontName, fontSize); + proto._setFontStyle = function (fontNameOrFontDef, fontSize, fontStyle, fontWeight) { + + if(fontNameOrFontDef instanceof cc.FontDefinition){ + this._fontStyleStr = fontNameOrFontDef.getCanvasFontStr(); + this._fontClientHeight = cc.LabelTTF.__getFontHeightByDiv(fontNameOrFontDef); + + }else { + this._fontStyleStr = fontStyle + " " + fontWeight + " " + fontSize + "px '" + fontNameOrFontDef + "'"; + this._fontClientHeight = cc.LabelTTF.__getFontHeightByDiv(fontNameOrFontDef, fontSize); + } }; proto._getFontStyle = function () { @@ -197,7 +204,9 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; var locContentSizeHeight = node._contentSize.height - locStrokeShadowOffsetY, locVAlignment = node._vAlignment, locHAlignment = node._hAlignment, locStrokeSize = node._strokeSize; - context.setTransform(1, 0, 0, 1, 0 + locStrokeShadowOffsetX * 0.5, locContentSizeHeight + locStrokeShadowOffsetY * 0.5); + + //locContentSizeHeight *1.1 resolve the clipping of the text + context.setTransform(1, 0, 0, 1, 0 + locStrokeShadowOffsetX * 0.5, locContentSizeHeight *1.1 + locStrokeShadowOffsetY * 0.5); //this is fillText for canvas if (context.font != this._fontStyleStr) diff --git a/cocos2d/core/platform/CCTypes.js b/cocos2d/core/platform/CCTypes.js index 4b94fefc96..817e935fb3 100644 --- a/cocos2d/core/platform/CCTypes.js +++ b/cocos2d/core/platform/CCTypes.js @@ -371,6 +371,9 @@ cc.FontDefinition = function (properties) { _t.strokeEnabled = false; _t.strokeStyle = cc.color(255, 255, 255, 255); _t.lineWidth = 1; + _t.lineHeight = _t.fontSize; + _t.fontStyle = "normal"; + _t.fontWeight = "normal"; _t.shadowEnabled = false; _t.shadowOffsetX = 0; @@ -384,7 +387,13 @@ cc.FontDefinition = function (properties) { _t[key] = properties[key]; } } - +}; +/** + * + * Web ONLY + * */ +cc.FontDefinition.prototype.getCanvasFontStr = function(){ + return this.fontStyle + " " + this.fontWeight + " " + this.fontSize + "px/" + this.lineHeight+"px '" + this.fontName + "'"; }; if (cc._renderType === cc._RENDER_TYPE_WEBGL) { diff --git a/extensions/ccui/uiwidgets/UIRichText.js b/extensions/ccui/uiwidgets/UIRichText.js index f2f01b523a..bc40f170ca 100644 --- a/extensions/ccui/uiwidgets/UIRichText.js +++ b/extensions/ccui/uiwidgets/UIRichText.js @@ -70,23 +70,43 @@ 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: 12, + * marginTop: 0, + * marginBottom: 0, + * marginRight: 0, + * marginLeft: 0 + * }), 255, "Some Text"); + * * Constructor of ccui.RichElementText * @param {Number} tag - * @param {cc.Color} color + * @param {cc.Color|cc.FontDefinition} colorOrFontDef * @param {Number} opacity * @param {String} text * @param {String} fontName * @param {Number} fontSize */ - ctor: function (tag, color, opacity, text, fontName, 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; - fontSize && this.init(tag, color, opacity, text, fontName, fontSize); + if( colorOrFontDef && colorOrFontDef instanceof cc.FontDefinition) + this.initWithStringAndTextDefinition(tag, text, colorOrFontDef, opacity); + else + fontSize && this.init(tag, colorOrFontDef, opacity, text, fontName, fontSize); }, /** @@ -104,6 +124,15 @@ ccui.RichElementText = ccui.RichElement.extend(/** @lends ccui.RichElementText# 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; + } }); @@ -238,6 +267,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ _leftSpaceWidth: 0, _verticalSpace: 0, _elementRenderersContainer: null, + _lineBreakOnSpace: false, /** * create a rich text @@ -306,8 +336,10 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ var elementRenderer = null; switch (element._type) { case ccui.RichElement.TEXT: - //todo: There may be ambiguous - elementRenderer = new cc.LabelTTF(element._text, element._fontName, element._fontSize); + 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); @@ -328,7 +360,10 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ element = locRichElements[i]; switch (element._type) { case ccui.RichElement.TEXT: - this._handleTextRenderer(element._text, element._fontName, element._fontSize, element._color); + 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); @@ -345,9 +380,25 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ 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) { - _handleTextRenderer: function (text, fontName, fontSize, color) { - var textRenderer = new cc.LabelTTF(text, fontName, fontSize); + 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) { @@ -357,18 +408,38 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ var leftLength = stringLength * (1 - overstepPercent); var leftWords = curText.substr(0, leftLength); var cutWords = curText.substr(leftLength, curText.length - 1); - if (leftLength > 0) { - var leftRenderer = new cc.LabelTTF(leftWords.substr(0, leftLength), fontName, fontSize); - leftRenderer.setColor(color); - leftRenderer.setOpacity(color.a); + 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, fontName, fontSize, color); + this._handleTextRenderer(cutWords, fontNameOrFontDef, fontSize, color); } else { - textRenderer.setColor(color); - textRenderer.setOpacity(color.a); + 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); } }, @@ -412,7 +483,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ locRenderersContainer.addChild(l, 1, j); var iSize = l.getContentSize(); newContentSizeWidth += iSize.width; - newContentSizeHeight = Math.max(newContentSizeHeight, iSize.height); + newContentSizeHeight = Math.max(Math.min(newContentSizeHeight, l.getLineHeight()), iSize.height); nextPosX += iSize.width; } locRenderersContainer.setContentSize(newContentSizeWidth, newContentSizeHeight); @@ -423,7 +494,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ var maxHeight = 0; for (j = 0; j < row.length; j++) { l = row[j]; - maxHeight = Math.max(l.getContentSize().height, maxHeight); + maxHeight = Math.max(Math.min(l.getContentSize().height, l.getLineHeight()), maxHeight); } maxHeights[i] = maxHeight; newContentSizeHeight += maxHeights[i]; @@ -454,6 +525,9 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ this.setContentSize(this._ignoreSize?this.getVirtualRendererSize():this._customSize); this._updateContentSizeWithTextureSize(this._contentSize); + + //locRenderersContainer.setPosition(this._contentSize.width * 0.5, this._contentSize.height * 0.5); + locRenderersContainer.setPosition(this._contentSize.width * 0.5, this._contentSize.height * 0.5); }, @@ -553,6 +627,16 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ setCascadeOpacityEnabled: function(value) { this._super(value); this._elementRenderersContainer.setCascadeOpacityEnabled(value); + }, + /** + * This allow the RichText layout to break line on space only like in Latin text format + * by default the property is false, which break the line on characters + * @param value + */ + setLineBreakOnSpace: function(value){ + this._lineBreakOnSpace = value; + this._formatTextDirty = true; + this.formatText(); } }); From 353df19ea870c247521ccd29f265f5646bdf87e9 Mon Sep 17 00:00:00 2001 From: Dany Ellement Date: Fri, 6 Feb 2015 15:55:28 -0500 Subject: [PATCH 0284/1345] setting the multiplication to 1.03 still solve the text clipping issue without disturbing too much the normal vertical alignment of LabelTTF It worth mentioning that this is a uggly fix, ill look into it later for now it work --- cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js index c167d84f1f..fff249bc30 100644 --- a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js +++ b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js @@ -205,8 +205,8 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; locHAlignment = node._hAlignment, locStrokeSize = node._strokeSize; - //locContentSizeHeight *1.1 resolve the clipping of the text - context.setTransform(1, 0, 0, 1, 0 + locStrokeShadowOffsetX * 0.5, locContentSizeHeight *1.1 + locStrokeShadowOffsetY * 0.5); + //locContentSizeHeight *1.03 resolve the clipping of the text + context.setTransform(1, 0, 0, 1, 0 + locStrokeShadowOffsetX * 0.5, locContentSizeHeight *1.03 + locStrokeShadowOffsetY * 0.5); //this is fillText for canvas if (context.font != this._fontStyleStr) From f53bcb3cb06297a9d95bf91d69b34fcb2b1c94a7 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 9 Feb 2015 11:55:54 +0800 Subject: [PATCH 0285/1345] Fixed affect its value --- cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js index 37410dbd4b..9919c0b07c 100644 --- a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js @@ -369,6 +369,8 @@ cc.Node.RenderCmd.prototype = { additionalTransform.a = 1; additionalTransform.d = 1; this._transform = cc.affineTransformConcat(t, additionalTransform); + additionalTransform.a = lScaleX; + additionalTransform.d = lScaleY; this._transform.a *= lScaleX; this._transform.d *= lScaleY; From b5e90c4cfdec37e7f8136158f73216474c05d028 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 9 Feb 2015 15:20:46 +0800 Subject: [PATCH 0286/1345] Remove _loadTxtSync, Because chrome(40) deprecated this API --- CCBoot.js | 58 ++++++++++++++++++++++++++----------------------------- 1 file changed, 27 insertions(+), 31 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index ca81412fce..11dcd5661b 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -690,26 +690,6 @@ cc.loader = /** @lends cc.loader# */{ }); } }, - _loadTxtSync: function (url) { - if (!cc._isNodeJs) { - var xhr = this.getXMLHttpRequest(); - xhr.open("GET", url, false); - if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) { - // IE-specific logic here - xhr.setRequestHeader("Accept-Charset", "utf-8"); - } else { - if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=utf-8"); - } - xhr.send(null); - if (!xhr.readyState == 4 || xhr.status != 200) { - return null; - } - return xhr.responseText; - } else { - var fs = require("fs"); - return fs.readFileSync(url).toString(); - } - }, loadCsb: function(url, cb){ var xhr = new XMLHttpRequest(); @@ -1964,6 +1944,7 @@ cc.game = /** @lends cc.game# */{ DEBUG_MODE_INFO_FOR_WEB_PAGE: 4, DEBUG_MODE_WARN_FOR_WEB_PAGE: 5, DEBUG_MODE_ERROR_FOR_WEB_PAGE: 6, + _ready: false, EVENT_HIDE: "game_on_hide", EVENT_SHOW: "game_on_show", @@ -2101,6 +2082,12 @@ cc.game = /** @lends cc.game# */{ * Run game. */ run: function (id) { + if(this._ready === false){ + this._ready = id === undefined ? true : id; + return; + }else if(typeof this._ready !== "boolean"){ + id = this._ready; + } var self = this; var _run = function () { if (id) { @@ -2143,7 +2130,13 @@ cc.game = /** @lends cc.game# */{ cfg[CONFIG_KEY.frameRate] = cfg[CONFIG_KEY.frameRate] || 60; if(cfg[CONFIG_KEY.renderMode] == null) cfg[CONFIG_KEY.renderMode] = 1; - return cfg; + //init debug move to CCDebugger + cc._initSys(cfg, CONFIG_KEY); + self.config = cfg; + if(cc.game._ready !== false){ + self._ready = true; + cc.game.run(); + } }; if (document["ccConfig"]) { self.config = _init(document["ccConfig"]); @@ -2154,7 +2147,7 @@ cc.game = /** @lends cc.game# */{ var _t = cocos_script[i].getAttribute('cocos'); if(_t == '' || _t){break;} } - var _src, txt, _resPath; + var _src, _resPath; if(i < cocos_script.length){ _src = cocos_script[i].src; if(_src){ @@ -2162,20 +2155,23 @@ cc.game = /** @lends cc.game# */{ cc.loader.resPath = _resPath; _src = cc.path.join(_resPath, 'project.json'); } - txt = cc.loader._loadTxtSync(_src); - } - if(!txt){ - txt = cc.loader._loadTxtSync("project.json"); + cc.loader.loadTxt(_src, function(err, txt){ + if(err) + return cc.error(err); + _init(JSON.parse(txt) || {}); + }); + }else{ + cc.loader.loadTxt("project.json", function(err, txt){ + if(err) + return cc.error(err); + _init(JSON.parse(txt) || {}); + }); } - var data = JSON.parse(txt); - self.config = _init(data || {}); } catch (e) { cc.log("Failed to read or parse project.json"); - self.config = _init({}); + _init({}); } } - //init debug move to CCDebugger - cc._initSys(self.config, CONFIG_KEY); }, //cache for js and module that has added into jsList to be loaded. From 4e87d5c6d026e12966e58f5cf68d2635c120f4b9 Mon Sep 17 00:00:00 2001 From: Dany Ellement Date: Mon, 9 Feb 2015 11:07:01 -0500 Subject: [PATCH 0287/1345] removed the ugly fix as it just make no sense to me --- cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js index fff249bc30..868a1ef98c 100644 --- a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js +++ b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js @@ -204,9 +204,7 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; var locContentSizeHeight = node._contentSize.height - locStrokeShadowOffsetY, locVAlignment = node._vAlignment, locHAlignment = node._hAlignment, locStrokeSize = node._strokeSize; - - //locContentSizeHeight *1.03 resolve the clipping of the text - context.setTransform(1, 0, 0, 1, 0 + locStrokeShadowOffsetX * 0.5, locContentSizeHeight *1.03 + locStrokeShadowOffsetY * 0.5); + context.setTransform(1, 0, 0, 1, 0 + locStrokeShadowOffsetX * 0.5, locContentSizeHeight + locStrokeShadowOffsetY * 0.5); //this is fillText for canvas if (context.font != this._fontStyleStr) From 12a69696f4cb99a97b2a4903be34639a04a84666 Mon Sep 17 00:00:00 2001 From: Dany Ellement Date: Mon, 9 Feb 2015 11:30:52 -0500 Subject: [PATCH 0288/1345] Added getLineHeight check in the formatRenderers so it doesnt break with other type of Renderer --- extensions/ccui/uiwidgets/UIRichText.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/extensions/ccui/uiwidgets/UIRichText.js b/extensions/ccui/uiwidgets/UIRichText.js index bc40f170ca..a707f6c656 100644 --- a/extensions/ccui/uiwidgets/UIRichText.js +++ b/extensions/ccui/uiwidgets/UIRichText.js @@ -481,9 +481,10 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ l.setAnchorPoint(cc.p(0, 0)); l.setPosition(nextPosX, 0); locRenderersContainer.addChild(l, 1, j); + var lineHeight = l.getLineHeight ? l.getLineHeight() : newContentSizeHeight; var iSize = l.getContentSize(); newContentSizeWidth += iSize.width; - newContentSizeHeight = Math.max(Math.min(newContentSizeHeight, l.getLineHeight()), iSize.height); + newContentSizeHeight = Math.max(Math.min(newContentSizeHeight, lineHeight), iSize.height); nextPosX += iSize.width; } locRenderersContainer.setContentSize(newContentSizeWidth, newContentSizeHeight); @@ -494,7 +495,8 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ var maxHeight = 0; for (j = 0; j < row.length; j++) { l = row[j]; - maxHeight = Math.max(Math.min(l.getContentSize().height, l.getLineHeight()), maxHeight); + var lineHeight = l.getLineHeight ? l.getLineHeight() : l.getContentSize().height; + maxHeight = Math.max(Math.min(l.getContentSize().height, lineHeight), maxHeight); } maxHeights[i] = maxHeight; newContentSizeHeight += maxHeights[i]; From ad219d19566f62fd150903615fe142f62290892f Mon Sep 17 00:00:00 2001 From: Dany Ellement Date: Mon, 9 Feb 2015 13:44:07 -0500 Subject: [PATCH 0289/1345] Added Horizontal Alignment feature to ccui.Richtext --- extensions/ccui/uiwidgets/UIRichText.js | 38 +++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/extensions/ccui/uiwidgets/UIRichText.js b/extensions/ccui/uiwidgets/UIRichText.js index a707f6c656..6e2f31f5bf 100644 --- a/extensions/ccui/uiwidgets/UIRichText.js +++ b/extensions/ccui/uiwidgets/UIRichText.js @@ -268,6 +268,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ _verticalSpace: 0, _elementRenderersContainer: null, _lineBreakOnSpace: false, + _textHorizontalAlignment: null, /** * create a rich text @@ -282,6 +283,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ this._elementRenders = []; this._leftSpaceWidth = 0; this._verticalSpace = 0; + this._textHorizontalAlignment = cc.TEXT_ALIGNMENT_LEFT; }, _initRenderer: function () { @@ -476,6 +478,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ var newContentSizeWidth = 0; row = locElementRenders[0]; nextPosX = 0; + for (j = 0; j < row.length; j++) { l = row[j]; l.setAnchorPoint(cc.p(0, 0)); @@ -487,6 +490,18 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ newContentSizeHeight = Math.max(Math.min(newContentSizeHeight, lineHeight), iSize.height); nextPosX += iSize.width; } + + //Text flow alignment: + if(this._textHorizontalAlignment != cc.TEXT_ALIGNMENT_LEFT) { + var offsetX = 0; + if (this._textHorizontalAlignment == cc.TEXT_ALIGNMENT_RIGHT) + offsetX = this._contentSize.width - nextPosX; + else if (this._textHorizontalAlignment == cc.TEXT_ALIGNMENT_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 = []; @@ -515,6 +530,17 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ locRenderersContainer.addChild(l, 1); nextPosX += l.getContentSize().width; } + //Text flow alignment: (duplicate code) refactor? + if(this._textHorizontalAlignment != cc.TEXT_ALIGNMENT_LEFT) { + var offsetX = 0; + if (this._textHorizontalAlignment == cc.TEXT_ALIGNMENT_RIGHT) + offsetX = this._contentSize.width - nextPosX; + else if (this._textHorizontalAlignment == cc.TEXT_ALIGNMENT_CENTER) + offsetX = (this._contentSize.width - nextPosX) / 2; + for (j = 0; j < row.length; j++) + row[j].x += offsetX; + } + } locRenderersContainer.setContentSize(this._contentSize); } @@ -639,6 +665,18 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ this._lineBreakOnSpace = value; this._formatTextDirty = true; this.formatText(); + }, + /** + * Set the renderer horizontal flow alignment for the Control + * although it is named TextHorizontalAlignment, it should work with all type of renderer too. + * NOTE: we should rename this to setHorizontalAlignment directly + * @param {Number} value - example cc.TEXT_ALIGNMENT_LEFT + */ + setTextHorizontalAlignment: function(value){ + if(value != this._textHorizontalAlignment) { + this._textHorizontalAlignment = value; + this.formatText(); + } } }); From 17da0b67845d21de739924c7b5d7790f054e137c Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 10 Feb 2015 10:03:14 +0800 Subject: [PATCH 0290/1345] Fix setAdditionalTransform errors T.T --- .../core/base-nodes/CCNodeCanvasRenderCmd.js | 20 ++++++------------- 1 file changed, 6 insertions(+), 14 deletions(-) diff --git a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js index 9919c0b07c..d561d1858d 100644 --- a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js @@ -364,20 +364,12 @@ cc.Node.RenderCmd.prototype = { if (node._additionalTransformDirty) { var additionalTransform = node._additionalTransform; - lScaleX = additionalTransform.a; - lScaleY = additionalTransform.d; - additionalTransform.a = 1; - additionalTransform.d = 1; - this._transform = cc.affineTransformConcat(t, additionalTransform); - additionalTransform.a = lScaleX; - additionalTransform.d = lScaleY; - - this._transform.a *= lScaleX; - this._transform.d *= lScaleY; - if((lScaleX < 0 && lScaleY > 0) || (lScaleX > 0 && lScaleY < 0)){ - this._transform.b *= -1; - this._transform.c *= -1; - } + this._transform = cc.affineTransformConcat(t, { + a: 1 , b: -additionalTransform.c, tx: additionalTransform.tx, + c: -additionalTransform.b , d: 1, ty: additionalTransform.ty + }); + this._transform.a *= additionalTransform.a; + this._transform.d *= additionalTransform.d; node._additionalTransformDirty = false; } From 32bfb64379ecf7e817bcbfaf4ca2686b97bf8551 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 10 Feb 2015 11:27:22 +0800 Subject: [PATCH 0291/1345] The ccui.text default font setting error --- extensions/ccui/uiwidgets/UIText.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/extensions/ccui/uiwidgets/UIText.js b/extensions/ccui/uiwidgets/UIText.js index 857e4663d4..8ae99ecb62 100644 --- a/extensions/ccui/uiwidgets/UIText.js +++ b/extensions/ccui/uiwidgets/UIText.js @@ -87,6 +87,8 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ this.setFontName(fontName); this.setFontSize(fontSize); this.setString(textContent); + }else{ + this.setFontName("Thonburi"); } return true; } From d07faab5b4c7f4c552e89481c97002818496bde6 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 10 Feb 2015 11:38:47 +0800 Subject: [PATCH 0292/1345] The ccui.text default font setting error --- extensions/ccui/uiwidgets/UIText.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/ccui/uiwidgets/UIText.js b/extensions/ccui/uiwidgets/UIText.js index 8ae99ecb62..d52f7bba17 100644 --- a/extensions/ccui/uiwidgets/UIText.js +++ b/extensions/ccui/uiwidgets/UIText.js @@ -88,7 +88,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ this.setFontSize(fontSize); this.setString(textContent); }else{ - this.setFontName("Thonburi"); + this.setFontName(this._fontName); } return true; } From 6a7c7bf4dba59de40c75531ab98f5f8660e07d27 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 10 Feb 2015 17:54:25 +0800 Subject: [PATCH 0293/1345] Fixed pageView getPage code error... --- extensions/ccui/uiwidgets/scroll-widget/UIPageView.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js b/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js index cfedf69092..8dd03b0b5a 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js @@ -576,7 +576,7 @@ ccui.PageView = ccui.Layout.extend(/** @lends ccui.PageView# */{ * @returns {ccui.Layout} */ getPage: function(index){ - if (index < 0 || index >= this.getPages().size()) + if (index < 0 || index >= this._pages.length) return null; return this._pages[index]; }, From 60b84fa1f9197097d2c8a42eecacdd99631d03d9 Mon Sep 17 00:00:00 2001 From: Dany Ellement Date: Tue, 10 Feb 2015 14:50:55 -0500 Subject: [PATCH 0294/1345] Added Vertical Alignment to ccui.RichText --- extensions/ccui/uiwidgets/UIRichText.js | 36 +++++++++++++++++++++---- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/extensions/ccui/uiwidgets/UIRichText.js b/extensions/ccui/uiwidgets/UIRichText.js index 6e2f31f5bf..695e6aaaf6 100644 --- a/extensions/ccui/uiwidgets/UIRichText.js +++ b/extensions/ccui/uiwidgets/UIRichText.js @@ -269,6 +269,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ _elementRenderersContainer: null, _lineBreakOnSpace: false, _textHorizontalAlignment: null, + _textVerticalAlignment: null, /** * create a rich text @@ -284,6 +285,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ this._leftSpaceWidth = 0; this._verticalSpace = 0; this._textHorizontalAlignment = cc.TEXT_ALIGNMENT_LEFT; + this._textVerticalAlignment = cc.VERTICAL_TEXT_ALIGNMENT_TOP; }, _initRenderer: function () { @@ -498,6 +500,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ offsetX = this._contentSize.width - nextPosX; else if (this._textHorizontalAlignment == cc.TEXT_ALIGNMENT_CENTER) offsetX = (this._contentSize.width - nextPosX) / 2; + for (j = 0; j < row.length; j++) row[j].x += offsetX; } @@ -518,6 +521,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ } var nextPosY = this._customSize.height; + for (i = 0; i < locElementRenders.length; i++) { row = locElementRenders[i]; nextPosX = 0; @@ -530,18 +534,28 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ locRenderersContainer.addChild(l, 1); nextPosX += l.getContentSize().width; } - //Text flow alignment: (duplicate code) refactor? - if(this._textHorizontalAlignment != cc.TEXT_ALIGNMENT_LEFT) { + //Text flow Horizontal alignment + if( this._textHorizontalAlignment != cc.TEXT_ALIGNMENT_LEFT || this._textVerticalAlignment != cc.VERTICAL_TEXT_ALIGNMENT_TOP) { var offsetX = 0; if (this._textHorizontalAlignment == cc.TEXT_ALIGNMENT_RIGHT) offsetX = this._contentSize.width - nextPosX; else if (this._textHorizontalAlignment == cc.TEXT_ALIGNMENT_CENTER) offsetX = (this._contentSize.width - nextPosX) / 2; - for (j = 0; j < row.length; j++) - row[j].x += offsetX; - } + var offsetY = 0; + if (this._textVerticalAlignment == cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM) + offsetY = this._customSize.height - newContentSizeHeight; + else if (this._textVerticalAlignment == cc.VERTICAL_TEXT_ALIGNMENT_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); } @@ -677,6 +691,18 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ this._textHorizontalAlignment = value; this.formatText(); } + }, + /** + * Set the renderer vertical flow alignment for the Control + * although it is named TextHorizontalAlignment, it should work with all type of renderer too. + * NOTE: we should rename this to setVerticalAlignment directly + * @param {Number} value - example cc.VERTICAL_TEXT_ALIGNMENT_TOP + */ + setTextVerticalAlignment: function(value){ + if(value != this._textVerticalAlignment) { + this._textVerticalAlignment = value; + this.formatText(); + } } }); From 9d6b6bdcd36edf6d9791a86c477a866cab6066a4 Mon Sep 17 00:00:00 2001 From: Dany Ellement Date: Tue, 10 Feb 2015 14:57:11 -0500 Subject: [PATCH 0295/1345] Little changes to comments for RichText alignment --- extensions/ccui/uiwidgets/UIRichText.js | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/extensions/ccui/uiwidgets/UIRichText.js b/extensions/ccui/uiwidgets/UIRichText.js index 695e6aaaf6..ee75e8e0cc 100644 --- a/extensions/ccui/uiwidgets/UIRichText.js +++ b/extensions/ccui/uiwidgets/UIRichText.js @@ -684,7 +684,12 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ * Set the renderer horizontal flow alignment for the Control * although it is named TextHorizontalAlignment, it should work with all type of renderer too. * NOTE: we should rename this to setHorizontalAlignment directly - * @param {Number} value - example cc.TEXT_ALIGNMENT_LEFT + * + * @example + * var richText = new ccui.RichText(); + * richText.setTextHorizontalAlignment(cc.Text_ALIGNMENT_RIGHT); + * + * @param {Number} value - example cc.TEXT_ALIGNMENT_RIGHT */ setTextHorizontalAlignment: function(value){ if(value != this._textHorizontalAlignment) { @@ -694,9 +699,13 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ }, /** * Set the renderer vertical flow alignment for the Control - * although it is named TextHorizontalAlignment, it should work with all type of renderer too. - * NOTE: we should rename this to setVerticalAlignment directly - * @param {Number} value - example cc.VERTICAL_TEXT_ALIGNMENT_TOP + * although it is named TextVerticalAlignment, it should work with all type of renderer too. + * + * @example + * var richText = new ccui.RichText(); + * richText.setTextVerticalAlignment(cc.VERTICAL_TEXT_ALIGNMENT_CENTER); + * + * @param {Number} value - example cc.VERTICAL_TEXT_ALIGNMENT_CENTER */ setTextVerticalAlignment: function(value){ if(value != this._textVerticalAlignment) { From bd9b9be0de72098cad8402601c64397683035631 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 11 Feb 2015 13:55:06 +0800 Subject: [PATCH 0296/1345] Fix setAdditionalTransform errors T.T --- cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js index d561d1858d..954b5e3cb8 100644 --- a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js @@ -364,13 +364,13 @@ cc.Node.RenderCmd.prototype = { if (node._additionalTransformDirty) { var additionalTransform = node._additionalTransform; - this._transform = cc.affineTransformConcat(t, { - a: 1 , b: -additionalTransform.c, tx: additionalTransform.tx, - c: -additionalTransform.b , d: 1, ty: additionalTransform.ty - }); - this._transform.a *= additionalTransform.a; - this._transform.d *= additionalTransform.d; - + var tb = this._transform.b; + this._transform.b = -this._transform.c; + this._transform.c = -tb; + this._transform = cc.affineTransformConcat(t, additionalTransform); + tb = this._transform.b; + this._transform.b = -this._transform.c; + this._transform.c = -tb; node._additionalTransformDirty = false; } } From c706770e5bc56e7a1342ef207aadedc809133c21 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 11 Feb 2015 17:52:10 +0800 Subject: [PATCH 0297/1345] transform.b, transform.c is contrary in the canvas --- cocos2d/core/base-nodes/CCNode.js | 2 + .../core/base-nodes/CCNodeCanvasRenderCmd.js | 57 ++++++++----------- cocos2d/core/renderer/RendererCanvas.js | 4 +- 3 files changed, 28 insertions(+), 35 deletions(-) diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index 91b49f0d40..a82ded43a2 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -1811,6 +1811,8 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * spriteB.setAdditionalTransform(t); */ setAdditionalTransform: function (additionalTransform) { + if(additionalTransform == null) + return this._additionalTransformDirty = false; this._additionalTransform = additionalTransform; this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty); this._additionalTransformDirty = true; diff --git a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js index 954b5e3cb8..5e4fdb724b 100644 --- a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js @@ -261,8 +261,8 @@ cc.Node.RenderCmd.prototype = { worldT.c = pt.c * t.a + pt.d * t.c; //c worldT.d = pt.c * t.b + pt.d * t.d; //d - worldT.tx = pt.a * t.tx - pt.b * t.ty + pt.tx; - worldT.ty = pt.d * t.ty + pt.ty - pt.c * t.tx; + 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; @@ -303,14 +303,14 @@ cc.Node.RenderCmd.prototype = { c = 0, d = 1; if (node._rotationX) { var rotationRadiansX = node._rotationX * 0.017453292519943295; //0.017453292519943295 = (Math.PI / 180); for performance - b = -Math.sin(rotationRadiansX); + c = Math.sin(rotationRadiansX); d = Math.cos(rotationRadiansX); } if (node._rotationY) { var rotationRadiansY = node._rotationY * 0.017453292519943295; //0.017453292519943295 = (Math.PI / 180); for performance a = Math.cos(rotationRadiansY); - c = Math.sin(rotationRadiansY); + b = -Math.sin(rotationRadiansY); } t.a = a; t.b = b; @@ -325,6 +325,14 @@ cc.Node.RenderCmd.prototype = { var sx = (lScaleX < 0.000001 && lScaleX > -0.000001) ? 0.000001 : lScaleX, sy = (lScaleY < 0.000001 && lScaleY > -0.000001) ? 0.000001 : lScaleY; + // scale + if (lScaleX !== 1 || lScaleY !== 1) { + a = t.a *= sx; + b = t.b *= sx; + c = t.c *= sy; + d = t.d *= sy; + } + // skew if (node._skewX || node._skewY) { // offset the anchorpoint @@ -334,27 +342,19 @@ cc.Node.RenderCmd.prototype = { skx = 99999999; if (sky === Infinity) sky = 99999999; - var xx = appY * skx * sx; - var yy = appX * sky * sy; - t.a = a + b * sky; - t.b = a * skx + b; - t.c = c + d * sky; - t.d = c * skx + d; - t.tx += a * xx + b * yy; - t.ty += c * xx + d * yy; - } - - // scale - if (lScaleX !== 1 || lScaleY !== 1) { - t.a *= sx; - t.c *= sx; - t.b *= sy; - t.d *= sy; + var xx = appY * skx; + var yy = appX * sky; + t.a = a - c * sky; + t.b = b - d * sky; + t.c = c - a * skx; + t.d = d - b * skx; + t.tx += a * xx + c * yy; + t.ty += b * xx + d * yy; } // adjust anchorPoint - t.tx += a * -appX * sx + b * appY * sy; - t.ty -= c * -appX * sx + d * appY * sy; + t.tx -= a * appX + c * appY; + t.ty -= b * appX + d * appY; // if ignore anchorPoint if (node._ignoreAnchorPointForPosition) { @@ -362,17 +362,8 @@ cc.Node.RenderCmd.prototype = { t.ty += appY; } - if (node._additionalTransformDirty) { - var additionalTransform = node._additionalTransform; - var tb = this._transform.b; - this._transform.b = -this._transform.c; - this._transform.c = -tb; - this._transform = cc.affineTransformConcat(t, additionalTransform); - tb = this._transform.b; - this._transform.b = -this._transform.c; - this._transform.c = -tb; - node._additionalTransformDirty = false; - } + if (node._additionalTransformDirty) + this._transform = cc.affineTransformConcat(t, node._additionalTransform); } return this._transform; }; diff --git a/cocos2d/core/renderer/RendererCanvas.js b/cocos2d/core/renderer/RendererCanvas.js index db1bbff120..855207715b 100644 --- a/cocos2d/core/renderer/RendererCanvas.js +++ b/cocos2d/core/renderer/RendererCanvas.js @@ -254,9 +254,9 @@ if (cc._renderType === cc._RENDER_TYPE_CANVAS) //ugly for armature this.restore(); this.save(); - this._context.transform(t.a, t.c, t.b, t.d, t.tx * scaleX, -(t.ty * scaleY)); + this._context.transform(t.a, -t.b, -t.c, t.d, t.tx * scaleX, -(t.ty * scaleY)); } else { - this._context.setTransform(t.a, t.c, t.b, t.d, this._offsetX + t.tx * scaleX, this._realOffsetY - (t.ty * scaleY)); + this._context.setTransform(t.a, -t.b, -t.c, t.d, this._offsetX + t.tx * scaleX, this._realOffsetY - (t.ty * scaleY)); } }; From 4f9ee0d2fd73dbb352463ad70a8a3124dc5cf905 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 11 Feb 2015 17:57:11 +0800 Subject: [PATCH 0298/1345] update ccui transform --- .../ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js b/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js index 25cfd9169d..120ba9c1b3 100644 --- a/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js +++ b/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js @@ -214,8 +214,8 @@ worldT.c = pt.c * t.a + pt.d * t.c; //c worldT.d = pt.c * t.b + pt.d * t.d; //d - worldT.tx = pt.a * t.tx - pt.b * t.ty + pt.tx; - worldT.ty = pt.d * t.ty + pt.ty - pt.c * t.tx; + worldT.tx = pt.a * t.tx + pt.c * t.ty + pt.tx; + worldT.ty = pt.d * t.ty + pt.ty + pt.b * t.tx; } else { worldT.a = t.a; worldT.b = t.b; From 5805d609979f4e476722b16d54918bb605486642 Mon Sep 17 00:00:00 2001 From: Dany Ellement Date: Wed, 11 Feb 2015 11:30:07 -0500 Subject: [PATCH 0299/1345] Renamed getCanvasFontStr to _getCanvasFontStr & Added support for lineHeight "normal" on LabelTTF --- cocos2d/core/labelttf/CCLabelTTF.js | 14 ++++++++------ .../core/labelttf/CCLabelTTFCanvasRenderCmd.js | 2 +- cocos2d/core/platform/CCTypes.js | 8 ++++---- extensions/ccui/uiwidgets/UIRichText.js | 15 ++++++--------- 4 files changed, 19 insertions(+), 20 deletions(-) diff --git a/cocos2d/core/labelttf/CCLabelTTF.js b/cocos2d/core/labelttf/CCLabelTTF.js index 02f2b7a21a..95b2e776fe 100644 --- a/cocos2d/core/labelttf/CCLabelTTF.js +++ b/cocos2d/core/labelttf/CCLabelTTF.js @@ -94,11 +94,10 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ _lineWidths: null, _className: "LabelTTF", - _lineHeight: 0, - //for web _fontStyle: "normal", _fontWeight: "normal", + _lineHeight: "normal", /** * Initializes the cc.LabelTTF with a font name, alignment, dimension and font size, do not call it by yourself, @@ -186,7 +185,9 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ }, getLineHeight: function () { - return this._lineHeight || this._renderCmd._getFontClientHeight(); + return !this._lineHeight || this._lineHeight.charAt ? + this._renderCmd._getFontClientHeight() : + this._lineHeight || this._renderCmd._getFontClientHeight(); }, setLineHeight: function (lineHeight) { @@ -507,6 +508,8 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ if(textDefinition.lineHeight) this._lineHeight = textDefinition.lineHeight + else + this._lineHeight = this._fontSize; this._renderCmd._setFontStyle(textDefinition); @@ -823,7 +826,7 @@ cc.LabelTTF.__getFontHeightByDiv = function (fontName, fontSize) { if(fontName instanceof cc.FontDefinition){ /** @type cc.FontDefinition */ var fontDef = fontName; - var clientHeight = cc.LabelTTF.__fontHeightCache[fontDef.getCanvasFontStr()]; + var clientHeight = cc.LabelTTF.__fontHeightCache[fontDef._getCanvasFontStr()]; if (clientHeight > 0) return clientHeight; var labelDiv = cc.LabelTTF.__labelHeightDiv; labelDiv.innerHTML = "ajghl~!"; @@ -831,10 +834,9 @@ cc.LabelTTF.__getFontHeightByDiv = function (fontName, fontSize) { labelDiv.style.fontSize = fontDef.fontSize + "px"; labelDiv.style.fontStyle = fontDef.fontStyle; labelDiv.style.fontWeight = fontDef.fontWeight; - //labelDiv.style.lineHeight = fontDef.lineHeight + "px"; //FIXME: the text get clipped here clientHeight = labelDiv.clientHeight; - cc.LabelTTF.__fontHeightCache[fontDef.getCanvasFontStr()] = clientHeight; + cc.LabelTTF.__fontHeightCache[fontDef._getCanvasFontStr()] = clientHeight; labelDiv.innerHTML = ""; return clientHeight; } diff --git a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js index 868a1ef98c..276ef15313 100644 --- a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js +++ b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js @@ -75,7 +75,7 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; proto._setFontStyle = function (fontNameOrFontDef, fontSize, fontStyle, fontWeight) { if(fontNameOrFontDef instanceof cc.FontDefinition){ - this._fontStyleStr = fontNameOrFontDef.getCanvasFontStr(); + this._fontStyleStr = fontNameOrFontDef._getCanvasFontStr(); this._fontClientHeight = cc.LabelTTF.__getFontHeightByDiv(fontNameOrFontDef); }else { diff --git a/cocos2d/core/platform/CCTypes.js b/cocos2d/core/platform/CCTypes.js index 817e935fb3..06ed754cce 100644 --- a/cocos2d/core/platform/CCTypes.js +++ b/cocos2d/core/platform/CCTypes.js @@ -371,7 +371,7 @@ cc.FontDefinition = function (properties) { _t.strokeEnabled = false; _t.strokeStyle = cc.color(255, 255, 255, 255); _t.lineWidth = 1; - _t.lineHeight = _t.fontSize; + _t.lineHeight = "normal"; _t.fontStyle = "normal"; _t.fontWeight = "normal"; @@ -389,11 +389,11 @@ cc.FontDefinition = function (properties) { } }; /** - * * Web ONLY * */ -cc.FontDefinition.prototype.getCanvasFontStr = function(){ - return this.fontStyle + " " + this.fontWeight + " " + this.fontSize + "px/" + this.lineHeight+"px '" + this.fontName + "'"; +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 + "'"; }; if (cc._renderType === cc._RENDER_TYPE_WEBGL) { diff --git a/extensions/ccui/uiwidgets/UIRichText.js b/extensions/ccui/uiwidgets/UIRichText.js index ee75e8e0cc..a5fe79a187 100644 --- a/extensions/ccui/uiwidgets/UIRichText.js +++ b/extensions/ccui/uiwidgets/UIRichText.js @@ -81,11 +81,7 @@ ccui.RichElementText = ccui.RichElement.extend(/** @lends ccui.RichElementText# * fontSize: 12, * fontWeight: "bold", * fontStyle: "normal", - * lineHeight: 12, - * marginTop: 0, - * marginBottom: 0, - * marginRight: 0, - * marginLeft: 0 + * lineHeight: 14 * }), 255, "Some Text"); * * Constructor of ccui.RichElementText @@ -486,14 +482,16 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ l.setAnchorPoint(cc.p(0, 0)); l.setPosition(nextPosX, 0); locRenderersContainer.addChild(l, 1, j); + var 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 alignment: + //Text flow horizontal alignment: if(this._textHorizontalAlignment != cc.TEXT_ALIGNMENT_LEFT) { var offsetX = 0; if (this._textHorizontalAlignment == cc.TEXT_ALIGNMENT_RIGHT) @@ -514,6 +512,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ for (j = 0; j < row.length; j++) { l = row[j]; var lineHeight = l.getLineHeight ? l.getLineHeight() : l.getContentSize().height; + cc.log(lineHeight); maxHeight = Math.max(Math.min(l.getContentSize().height, lineHeight), maxHeight); } maxHeights[i] = maxHeight; @@ -534,7 +533,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ locRenderersContainer.addChild(l, 1); nextPosX += l.getContentSize().width; } - //Text flow Horizontal alignment + //Text flow alignment(s) if( this._textHorizontalAlignment != cc.TEXT_ALIGNMENT_LEFT || this._textVerticalAlignment != cc.VERTICAL_TEXT_ALIGNMENT_TOP) { var offsetX = 0; if (this._textHorizontalAlignment == cc.TEXT_ALIGNMENT_RIGHT) @@ -568,8 +567,6 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ this.setContentSize(this._ignoreSize?this.getVirtualRendererSize():this._customSize); this._updateContentSizeWithTextureSize(this._contentSize); - //locRenderersContainer.setPosition(this._contentSize.width * 0.5, this._contentSize.height * 0.5); - locRenderersContainer.setPosition(this._contentSize.width * 0.5, this._contentSize.height * 0.5); }, From 28ef3eb8a8968825f18c16106fb7adff8b2c9c93 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Thu, 12 Feb 2015 14:33:05 +0800 Subject: [PATCH 0300/1345] Added 'setVirtualViewport' to cc.RenderTexture --- cocos2d/render-texture/CCRenderTexture.js | 10 ++++++ .../CCRenderTextureCanvasRenderCmd.js | 2 ++ .../CCRenderTextureWebGLRenderCmd.js | 31 ++++++++++++++++--- 3 files changed, 38 insertions(+), 5 deletions(-) diff --git a/cocos2d/render-texture/CCRenderTexture.js b/cocos2d/render-texture/CCRenderTexture.js index 56763ee666..3a8f14da69 100644 --- a/cocos2d/render-texture/CCRenderTexture.js +++ b/cocos2d/render-texture/CCRenderTexture.js @@ -156,6 +156,16 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ this.sprite = sprite; }, + /** + * Used for grab part of screen to a texture. + * @param {cc.Point} 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 diff --git a/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js b/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js index d93c976aa1..1f302501e1 100644 --- a/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js +++ b/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js @@ -42,6 +42,8 @@ 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 + ")"; }; diff --git a/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js b/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js index ae567f689b..4a2e48cb63 100644 --- a/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js +++ b/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js @@ -31,11 +31,23 @@ 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; @@ -122,6 +134,8 @@ 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); @@ -213,6 +227,8 @@ cc.kmGLMatrixMode(cc.KM_GL_MODELVIEW); cc.kmGLPushMatrix(); + var gl = cc._renderContext; + var director = cc.director; director.setProjection(director.getProjection()); @@ -223,16 +239,21 @@ var widthRatio = size.width / texSize.width; var heightRatio = size.height / texSize.height; - var gl = cc._renderContext; - - // Adjust the orthographic projection and viewport - gl.viewport(0, 0, texSize.width, texSize.height); - var orthoMatrix = new cc.kmMat4(); cc.kmMat4OrthographicProjection(orthoMatrix, -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 From ab69c9c12fcbc6ad45f4ceaee1b32b8992b1c38a Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 12 Feb 2015 17:06:56 +0800 Subject: [PATCH 0301/1345] follow https://github.com/cocos2d/cocos2d-x/pull/9963/files --- cocos2d/core/event-manager/CCEventManager.js | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/event-manager/CCEventManager.js b/cocos2d/core/event-manager/CCEventManager.js index f412e20b13..d45126255c 100644 --- a/cocos2d/core/event-manager/CCEventManager.js +++ b/cocos2d/core/event-manager/CCEventManager.js @@ -381,15 +381,16 @@ cc.eventManager = /** @lends cc.eventManager# */{ _updateListeners: function (event) { var locInDispatch = this._inDispatch; cc.assert(locInDispatch > 0, cc._LogInfos.EventManager__updateListeners); + + if(locInDispatch > 1) + return; + if (event.getType() == cc.Event.TOUCH) { this._onUpdateListeners(cc._EventListenerTouchOneByOne.LISTENER_ID); this._onUpdateListeners(cc._EventListenerTouchAllAtOnce.LISTENER_ID); } else this._onUpdateListeners(cc.__getListenerID(event)); - if(locInDispatch > 1) - return; - cc.assert(locInDispatch == 1, cc._LogInfos.EventManager__updateListeners_2); var locListenersMap = this._listenersMap, locPriorityDirtyFlagMap = this._priorityDirtyFlagMap; for (var selKey in locListenersMap) { From cbd2acd929854b62b648d29e7cb4bd1654f0f259 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 13 Feb 2015 18:15:53 +0800 Subject: [PATCH 0302/1345] Fixed #2568: Matrix of the partial reversal --- cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js | 8 ++++---- .../ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js index 5e4fdb724b..dbcdaf8101 100644 --- a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js @@ -256,10 +256,10 @@ cc.Node.RenderCmd.prototype = { if (parentCmd) { var pt = parentCmd._worldTransform; // cc.AffineTransformConcat is incorrect at get world transform - worldT.a = pt.a * t.a + pt.b * t.c; //a - worldT.b = pt.a * t.b + pt.b * t.d; //b - worldT.c = pt.c * t.a + pt.d * t.c; //c - worldT.d = pt.c * t.b + pt.d * t.d; //d + 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; diff --git a/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js b/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js index 120ba9c1b3..c3ecd0bb7d 100644 --- a/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js +++ b/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js @@ -209,10 +209,10 @@ if (parentCmd) { var pt = parentCmd._worldTransform; // cc.AffineTransformConcat is incorrect at get world transform - worldT.a = pt.a * t.a + pt.b * t.c; //a - worldT.b = pt.a * t.b + pt.b * t.d; //b - worldT.c = pt.c * t.a + pt.d * t.c; //c - worldT.d = pt.c * t.b + pt.d * t.d; //d + 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; From c648d8bf614d94992746730e15f3c1409661328c Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Sun, 15 Feb 2015 10:25:47 +0800 Subject: [PATCH 0303/1345] Fixed a bug of ccui.ImageView that its loadTexture doesn't work when calling loadTexture multiple times at same frame. --- extensions/ccui/uiwidgets/UIImageView.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/ccui/uiwidgets/UIImageView.js b/extensions/ccui/uiwidgets/UIImageView.js index 7f4519bc23..2a0a14f28b 100644 --- a/extensions/ccui/uiwidgets/UIImageView.js +++ b/extensions/ccui/uiwidgets/UIImageView.js @@ -102,7 +102,7 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{ if(!imageRenderer._textureLoaded){ imageRenderer.addEventListener("load", function(){ - self.loadTexture(fileName, texType); + self.loadTexture(self._textureFile, self._imageTexType); }); } From bc95107462b34bbae39b31978c60543f38276096 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Sun, 15 Feb 2015 11:30:46 +0800 Subject: [PATCH 0304/1345] Fixed a bug of ccui that its load event callbacks have some mistakes --- extensions/ccui/uiwidgets/UIButton.js | 6 +++--- extensions/ccui/uiwidgets/UICheckBox.js | 10 +++++----- extensions/ccui/uiwidgets/UILoadingBar.js | 2 +- extensions/ccui/uiwidgets/UISlider.js | 10 +++++----- extensions/ccui/uiwidgets/UITextBMFont.js | 2 +- 5 files changed, 15 insertions(+), 15 deletions(-) diff --git a/extensions/ccui/uiwidgets/UIButton.js b/extensions/ccui/uiwidgets/UIButton.js index 060838e963..dd76a26d8a 100644 --- a/extensions/ccui/uiwidgets/UIButton.js +++ b/extensions/ccui/uiwidgets/UIButton.js @@ -258,7 +258,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ var normalRenderer = this._buttonNormalRenderer; if(!normalRenderer._textureLoaded){ normalRenderer.addEventListener("load", function(){ - self.loadTextureNormal(normal, texType); + self.loadTextureNormal(self._normalFileName, self._normalTexType); }); } switch (this._normalTexType){ @@ -305,7 +305,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ var clickedRenderer = this._buttonClickedRenderer; if(!clickedRenderer._textureLoaded){ clickedRenderer.addEventListener("load", function(){ - self.loadTexturePressed(selected, texType); + self.loadTexturePressed(self._clickedFileName, self._pressedTexType); }); } @@ -350,7 +350,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ var disabledRenderer = this._buttonDisableRenderer; if(!disabledRenderer._textureLoaded){ disabledRenderer.addEventListener("load", function() { - self.loadTextureDisabled(disabled, texType); + self.loadTextureDisabled(self._disabledFileName, self._disabledTexType); }); } diff --git a/extensions/ccui/uiwidgets/UICheckBox.js b/extensions/ccui/uiwidgets/UICheckBox.js index d62fdccf00..9f9f257fc4 100644 --- a/extensions/ccui/uiwidgets/UICheckBox.js +++ b/extensions/ccui/uiwidgets/UICheckBox.js @@ -174,7 +174,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ if(!bgBoxRenderer._textureLoaded){ bgBoxRenderer.addEventListener("load", function(){ this._updateContentSizeWithTextureSize(this._backGroundBoxRenderer.getContentSize()); - this.loadTextureBackGround(backGround, texType); + this.loadTextureBackGround(this._backGroundFileName, this._backGroundTexType); }, this); }else{ this._backGroundBoxRenderer.setContentSize(this._customSize); @@ -216,7 +216,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ var backGroundSelectedBoxRenderer = this._backGroundSelectedBoxRenderer; if(!backGroundSelectedBoxRenderer._textureLoaded){ backGroundSelectedBoxRenderer.addEventListener("load", function(){ - this.loadTextureBackGroundSelected(backGroundSelected, texType); + this.loadTextureBackGroundSelected(this._backGroundSelectedFileName, this._backGroundSelectedTexType); }, this); } @@ -256,7 +256,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ var frontCrossRenderer = this._frontCrossRenderer; if(!frontCrossRenderer._textureLoaded){ frontCrossRenderer.addEventListener("load", function(){ - this.loadTextureFrontCross(cross, texType); + this.loadTextureFrontCross(this._frontCrossFileName, this._frontCrossTexType); }, this); } @@ -295,7 +295,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ var backGroundBoxDisabledRenderer = this._backGroundBoxDisabledRenderer; if(!backGroundBoxDisabledRenderer._textureLoaded){ backGroundBoxDisabledRenderer.addEventListener("load", function(){ - this.loadTextureBackGroundDisabled(backGroundDisabled, texType); + this.loadTextureBackGroundDisabled(this._backGroundDisabledFileName, this._backGroundDisabledTexType); }, this); } @@ -334,7 +334,7 @@ ccui.CheckBox = ccui.Widget.extend(/** @lends ccui.CheckBox# */{ var frontCrossDisabledRenderer = this._frontCrossDisabledRenderer; if(!frontCrossDisabledRenderer._textureLoaded){ frontCrossDisabledRenderer.addEventListener("load", function(){ - this.loadTextureFrontCrossDisabled(frontCrossDisabled, texType); + this.loadTextureFrontCrossDisabled(this._frontCrossDisabledFileName, this._frontCrossDisabledTexType); }, this); } diff --git a/extensions/ccui/uiwidgets/UILoadingBar.js b/extensions/ccui/uiwidgets/UILoadingBar.js index 68cd78f917..dc3331a68f 100644 --- a/extensions/ccui/uiwidgets/UILoadingBar.js +++ b/extensions/ccui/uiwidgets/UILoadingBar.js @@ -124,7 +124,7 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{ var self = this; if(!barRenderer._textureLoaded){ barRenderer.addEventListener("load", function(){ - self.loadTexture(texture, texType); + self.loadTexture(self._renderBarTexType, self._textureFile); }); } diff --git a/extensions/ccui/uiwidgets/UISlider.js b/extensions/ccui/uiwidgets/UISlider.js index 4c3a61fef6..e36244fa92 100644 --- a/extensions/ccui/uiwidgets/UISlider.js +++ b/extensions/ccui/uiwidgets/UISlider.js @@ -135,7 +135,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ var self = this; if(!barRenderer._textureLoaded){ barRenderer.addEventListener("load", function(){ - self.loadBarTexture(fileName, texType); + self.loadBarTexture(self._textureFile, self._barTexType); }); } @@ -177,7 +177,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ var self = this; if(!progressBarRenderer._textureLoaded){ progressBarRenderer.addEventListener("load", function(){ - self.loadProgressBarTexture(fileName, texType); + self.loadProgressBarTexture(self._progressBarTextureFile, self._progressBarTexType); }); } @@ -347,7 +347,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ var self = this; if(!this._slidBallNormalRenderer._textureLoaded){ this._slidBallNormalRenderer.addEventListener("load", function(){ - self.loadSlidBallTextureNormal(normal, texType); + self.loadSlidBallTextureNormal(self._slidBallNormalTextureFile, self._ballNTexType); }); } @@ -383,7 +383,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ var self = this; if(!this._slidBallPressedRenderer._textureLoaded){ this._slidBallPressedRenderer.addEventListener("load", function(){ - self.loadSlidBallTexturePressed(pressed, texType); + self.loadSlidBallTexturePressed(self._slidBallPressedTextureFile, self._ballPTexType); }); } @@ -419,7 +419,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ var self = this; if(!this._slidBallDisabledRenderer._textureLoaded){ this._slidBallDisabledRenderer.addEventListener("load", function(){ - self.loadSlidBallTextureDisabled(disabled, texType); + self.loadSlidBallTextureDisabled(self._slidBallDisabledTextureFile, self._ballDTexType); }); } diff --git a/extensions/ccui/uiwidgets/UITextBMFont.js b/extensions/ccui/uiwidgets/UITextBMFont.js index e50733de8e..b0af3462c1 100644 --- a/extensions/ccui/uiwidgets/UITextBMFont.js +++ b/extensions/ccui/uiwidgets/UITextBMFont.js @@ -79,7 +79,7 @@ ccui.LabelBMFont = ccui.TextBMFont = ccui.Widget.extend(/** @lends ccui.TextBMFo var locRenderer = _self._labelBMFontRenderer; if(!locRenderer._textureLoaded){ locRenderer.addEventListener("load", function(){ - _self.setFntFile(fileName); + _self.setFntFile(_self._fntFileName); }); } }, From 471855f108050180200d42bde7e00ccadf051013 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Sun, 15 Feb 2015 17:39:15 +0800 Subject: [PATCH 0305/1345] Fixed a bug of cc.Layer that its bake function doesn't work when the layer has a parent node --- .../core/base-nodes/CCNodeCanvasRenderCmd.js | 4 +- cocos2d/core/layers/CCLayerCanvasRenderCmd.js | 37 ++++--------------- 2 files changed, 10 insertions(+), 31 deletions(-) diff --git a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js index dbcdaf8101..a61ba7ee65 100644 --- a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js @@ -252,7 +252,7 @@ cc.Node.RenderCmd.prototype = { // transform for canvas var t = this.getNodeToParentTransform(), worldT = this._worldTransform; //get the world transform - + this._cacheDirty = true; if (parentCmd) { var pt = parentCmd._worldTransform; // cc.AffineTransformConcat is incorrect at get world transform @@ -447,7 +447,7 @@ cc.Node.RenderCmd.prototype = { proto.setDirtyFlag = function (dirtyFlag) { cc.Node.RenderCmd.prototype.setDirtyFlag.call(this, dirtyFlag); - this._setCacheDirty(); + this._setCacheDirty(); //TODO it should remove from here. if(this._cachedParent) this._cachedParent.setDirtyFlag(dirtyFlag); }; diff --git a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js index a7f3c6a24b..436cde4ad8 100644 --- a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js +++ b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js @@ -55,7 +55,7 @@ if (!this._bakeSprite){ this._bakeSprite = new cc.BakeSprite(); - this._bakeSprite._parent = this._node; + this._bakeSprite.setAnchorPoint(0,0); } } }; @@ -93,19 +93,8 @@ var ctx = bakeContext.getContext(); locBakeSprite.resetCanvasSize(boundingBox.width, boundingBox.height); - var anchor = locBakeSprite.getAnchorPointInPoints(), locPos = node._position; - if(node._ignoreAnchorPointForPosition){ - //bakeContext.translate(0 - boundingBox.x + locPos.x, boundingBox.height + boundingBox.y - locPos.y); - bakeContext.setOffset(0 - boundingBox.x, ctx.canvas.height - boundingBox.height + boundingBox.y ); - //reset the bake sprite's position - locBakeSprite.setPosition(anchor.x + boundingBox.x - locPos.x, anchor.y + boundingBox.y - locPos.y); - } else { - var selfAnchor = this.getAnchorPointInPoints(); - var selfPos = {x: locPos.x - selfAnchor.x, y: locPos.y - selfAnchor.y}; - //bakeContext.translate(0 - boundingBox.x + selfPos.x, boundingBox.height + boundingBox.y - selfPos.y); - bakeContext.setOffset(0 - boundingBox.x, ctx.canvas.height - boundingBox.height + boundingBox.y); - locBakeSprite.setPosition(anchor.x + boundingBox.x - selfPos.x, anchor.y + boundingBox.y - selfPos.y); - } + bakeContext.setOffset(0 - boundingBox.x, ctx.canvas.height - boundingBox.height + boundingBox.y ); + locBakeSprite.setPosition(boundingBox.x, boundingBox.y); //visit for canvas node.sortAllChildren(); @@ -114,7 +103,7 @@ children[i].visit(this); } cc.renderer._renderingToCacheCanvas(bakeContext, this.__instanceId); - locBakeSprite.transform(this); //because bake sprite's position was changed at rendering. + locBakeSprite.transform(); //because bake sprite's position was changed at rendering. this._cacheDirty = false; } }; @@ -234,19 +223,9 @@ var bakeContext = locBakeSprite.getCacheContext(); var ctx = bakeContext.getContext(); locBakeSprite.resetCanvasSize(boundingBox.width, boundingBox.height); - var anchor = locBakeSprite.getAnchorPointInPoints(), locPos = node._position; - if(node._ignoreAnchorPointForPosition){ - //bakeContext.translate(0 - boundingBox.x + locPos.x, boundingBox.height + boundingBox.y - locPos.y); - bakeContext.setOffset(0 - boundingBox.x, ctx.canvas.height - boundingBox.height + boundingBox.y ); - //reset the bake sprite's position - locBakeSprite.setPosition(anchor.x + boundingBox.x - locPos.x, anchor.y + boundingBox.y - locPos.y); - } else { - var selfAnchor = this.getAnchorPointInPoints(); - var selfPos = {x: locPos.x - selfAnchor.x, y: locPos.y - selfAnchor.y}; - //bakeContext.translate(0 - boundingBox.x + selfPos.x, boundingBox.height + boundingBox.y - selfPos.y); - bakeContext.setOffset(0 - boundingBox.x, ctx.canvas.height - boundingBox.height + boundingBox.y); - locBakeSprite.setPosition(anchor.x + boundingBox.x - selfPos.x, anchor.y + boundingBox.y - selfPos.y); - } + + bakeContext.setOffset(0 - boundingBox.x, ctx.canvas.height - boundingBox.height + boundingBox.y ); + locBakeSprite.setPosition(boundingBox.x, boundingBox.y); var child; cc.renderer._turnToCacheMode(this.__instanceId); @@ -268,7 +247,7 @@ } else cc.renderer.pushRenderCommand(this); cc.renderer._renderingToCacheCanvas(bakeContext, this.__instanceId); - locBakeSprite.transform(this); + locBakeSprite.transform(); this._cacheDirty = false; } }; From 6702831e467b74feeb9e41de939e8dedc1404ca1 Mon Sep 17 00:00:00 2001 From: Mykyta Usikov Date: Mon, 16 Feb 2015 18:11:16 +0200 Subject: [PATCH 0306/1345] fixed typos in cc.ClippingNode.WebGLRenderCmd and cc.ParticleSystem.WebGLRenderCmd creation --- cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js | 2 +- cocos2d/particle/CCParticleSystemWebGLRenderCmd.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js b/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js index a1ce0ae0d6..451fb6ab7f 100644 --- a/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js +++ b/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js @@ -44,7 +44,7 @@ this._mask_layer_le = null; }; - var proto = cc.ClippingNode.WebGLRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); + var proto = cc.ClippingNode.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype); proto.constructor = cc.ClippingNode.WebGLRenderCmd; cc.ClippingNode.WebGLRenderCmd._init_once = null; diff --git a/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js b/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js index 0bdd3462f3..87f501510f 100644 --- a/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js +++ b/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js @@ -36,7 +36,7 @@ this._quadsArrayBuffer = null; }; var proto = cc.ParticleSystem.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype); - proto.constructor = cc.ParticleSystem.CanvasRenderCmd; + proto.constructor = cc.ParticleSystem.WebGLRenderCmd; proto.getDrawMode = function(){}; proto.setDrawMode = function(drawMode){}; From 750b1406c8a070452c2d16b751afff29e46df54d Mon Sep 17 00:00:00 2001 From: Dany Ellement Date: Mon, 16 Feb 2015 14:52:55 -0500 Subject: [PATCH 0307/1345] Added GradientStops Feature to LayerGradient (Canvas Mode) --- cocos2d/core/layers/CCLayer.js | 64 +++++++++++++++++-- cocos2d/core/layers/CCLayerCanvasRenderCmd.js | 29 ++++++++- 2 files changed, 84 insertions(+), 9 deletions(-) diff --git a/cocos2d/core/layers/CCLayer.js b/cocos2d/core/layers/CCLayer.js index 297217e3b6..a072e282a3 100644 --- a/cocos2d/core/layers/CCLayer.js +++ b/cocos2d/core/layers/CCLayer.js @@ -322,21 +322,38 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{ _alongVector: null, _compressedInterpolation: false, _className: "LayerGradient", + _colorStops: [], /** * Constructor of cc.LayerGradient * @param {cc.Color} start * @param {cc.Color} end * @param {cc.Point} [v=cc.p(0, -1)] - */ - ctor: function (start, end, v) { + * @param {Array|Null} stops + * + * @example Using ColorStops argument: + * //startColor & endColor are for default and backward compatibility + * var layerGradient = new cc.LayerGradient(cc.color.RED, new cc.Color(255,0,0,0), cc.p(0, -1), + * [{p:0, color: cc.color.RED}, + * {p:.5, color: new cc.Color(0,0,0,0)}, + * {p:1, color: cc.color.RED}]); + * //where p = A value between 0.0 and 1.0 that represents the position between start and end in a gradient + * + */ + ctor: function (start, end, v, stops) { var _t = this; cc.LayerColor.prototype.ctor.call(_t); _t._endColor = cc.color(0, 0, 0, 255); _t._alongVector = cc.p(0, -1); _t._startOpacity = 255; _t._endOpacity = 255; - cc.LayerGradient.prototype.init.call(_t, start, end, v); + + if(stops && stops instanceof Array) + _t._colorStops = stops; + else + _t._colorStops = [{p:0, color: start}, {p:1, color: end}]; + + cc.LayerGradient.prototype.init.call(_t, start, end, v, stops); }, /** @@ -344,9 +361,10 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{ * @param {cc.Color} start starting color * @param {cc.Color} end * @param {cc.Point|Null} v + * @param {Array|Null} stops * @return {Boolean} */ - init: function (start, end, v) { + init: function (start, end, v, stops) { start = start || cc.color(0, 0, 0, 255); end = end || cc.color(0, 0, 0, 255); v = v || cc.p(0, -1); @@ -498,6 +516,36 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.gradientDirty); }, + /** + * Return an array of Object representing a colorStop for the gradient, if no stops was specified + * start & endColor will be provided as default values + * @example + * [{p: 0, color: cc.color.RED},{p: 1, color: cc.color.RED},...] + * @returns {Array} + */ + getColorStops: function(){ + return this._colorStops; + }, + /** + * Set the colorStops to create the gradient using multiple point & color + * + * @param colorStops + * + * @example + * //startColor & endColor are for default and backward compatibility + * var layerGradient = new cc.LayerGradient(cc.color.RED, new cc.Color(255,0,0,0), cc.p(0, -1)); + * layerGradient.setColorStops([{p:0, color: cc.color.RED}, + * {p:.5, color: new cc.Color(0,0,0,0)}, + * {p:1, color: cc.color.RED}]); + * //where p = A value between 0.0 and 1.0 that represents the position between start and end in a gradient + * + */ + setColorStops: function(colorStops){ + + this._colorStops = colorStops; + this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty|cc.Node._dirtyFlags.opacityDirty|cc.Node._dirtyFlags.gradientDirty); + }, + _createRenderCmd: function(){ if (cc._renderType === cc._RENDER_TYPE_CANVAS) return new cc.LayerGradient.CanvasRenderCmd(this); @@ -513,10 +561,11 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{ * @param {cc.Color} start starting color * @param {cc.Color} end ending color * @param {cc.Point|Null} v + * @param {Array|NULL} stops * @return {cc.LayerGradient} */ -cc.LayerGradient.create = function (start, end, v) { - return new cc.LayerGradient(start, end, v); +cc.LayerGradient.create = function (start, end, v, stops) { + return new cc.LayerGradient(start, end, v, stops); }; //LayerGradient - Getter Setter (function(){ @@ -537,6 +586,9 @@ cc.LayerGradient.create = function (start, end, v) { /** @expose */ proto.vector; cc.defineGetterSetter(proto, "vector", proto.getVector, proto.setVector); + /** @expose */ + proto.colorStops; + cc.defineGetterSetter(proto, "colorStops", proto.getColorStops, proto.setColorStops); })(); /** diff --git a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js index a7f3c6a24b..cf8ce7abfd 100644 --- a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js +++ b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js @@ -369,9 +369,18 @@ var locWidth = node._contentSize.width, locHeight = node._contentSize.height; wrapper.setCompositeOperation(this._blendFuncStr); wrapper.setGlobalAlpha(opacity); - var gradient = context.createLinearGradient(this._startPoint.x, this._startPoint.y, this._endPoint.x, this._endPoint.y); - gradient.addColorStop(0, this._startStopStr); - gradient.addColorStop(1, this._endStopStr); + var gradient = context.createLinearGradient(this._startPoint.x*scaleX, this._startPoint.y*scaleY, this._endPoint.x*scaleX, this._endPoint.y*scaleY); + + if(node._colorStops){ //Should always fall here now + for(var i=0; i < node._colorStops.length; i++) { + var stop = node._colorStops[i]; + gradient.addColorStop(stop.p, this._colorStopsStr[i]); + } + }else{ + gradient.addColorStop(0, this._startStopStr); + gradient.addColorStop(1, this._endStopStr); + } + wrapper.setFillStyle(gradient); wrapper.setTransform(this._worldTransform, scaleX, scaleY); @@ -430,5 +439,19 @@ + Math.round(locStartColor.b) + "," + startOpacity.toFixed(4) + ")"; this._endStopStr = "rgba(" + Math.round(locEndColor.r) + "," + Math.round(locEndColor.g) + "," + Math.round(locEndColor.b) + "," + endOpacity.toFixed(4) + ")"; + + if( node._colorStops){ + this._startOpacity = 0; + this._endOpacity = 0; + + this._colorStopsStr = []; + for(var i =0; i < node._colorStops.length; i++){ + var stopColor = node._colorStops[i].color; + var stopOpacity = stopColor.a/255; + this._colorStopsStr.push("rgba(" + Math.round(stopColor.r) + "," + Math.round(stopColor.g) + "," + + Math.round(stopColor.b) + "," + stopOpacity.toFixed(4) + ")"); + } + } + }; })(); \ No newline at end of file From 521235099fff435c7e7749f38ce1ef1f024fb4e2 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Thu, 26 Feb 2015 09:58:50 +0800 Subject: [PATCH 0308/1345] Fixed #2416: fixed a bug of cc.Sprite in setTextureRect --- cocos2d/core/labelttf/CCLabelTTF.js | 6 +++--- cocos2d/core/sprites/CCSprite.js | 10 +++++----- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/cocos2d/core/labelttf/CCLabelTTF.js b/cocos2d/core/labelttf/CCLabelTTF.js index 95b2e776fe..106e92bc19 100644 --- a/cocos2d/core/labelttf/CCLabelTTF.js +++ b/cocos2d/core/labelttf/CCLabelTTF.js @@ -642,7 +642,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ this._dimensions.width = width; this._dimensions.height = height; this._updateString(); - // Force udpate + // Force update this._setUpdateTextureDirty(); } }, @@ -654,7 +654,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ if (width != this._dimensions.width) { this._dimensions.width = width; this._updateString(); - // Force udpate + // Force update this._setUpdateTextureDirty(); } }, @@ -666,7 +666,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ if (height != this._dimensions.height) { this._dimensions.height = height; this._updateString(); - // Force udpate + // Force update this._setUpdateTextureDirty(); } }, diff --git a/cocos2d/core/sprites/CCSprite.js b/cocos2d/core/sprites/CCSprite.js index 876b5def45..7bcd41db64 100644 --- a/cocos2d/core/sprites/CCSprite.js +++ b/cocos2d/core/sprites/CCSprite.js @@ -759,14 +759,14 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ _t.setVertexRect(rect); _t._renderCmd._setTextureCoords(rect, needConvert); - var relativeOffset = _t._unflippedOffsetPositionFromCenter; + var relativeOffsetX = _t._unflippedOffsetPositionFromCenter.x, relativeOffsetY = _t._unflippedOffsetPositionFromCenter.y; if (_t._flippedX) - relativeOffset.x = -relativeOffset.x; + relativeOffsetX = -relativeOffsetX; if (_t._flippedY) - relativeOffset.y = -relativeOffset.y; + relativeOffsetY = -relativeOffsetY; var locRect = _t._rect; - _t._offsetPosition.x = relativeOffset.x + (_t._contentSize.width - locRect.width) / 2; - _t._offsetPosition.y = relativeOffset.y + (_t._contentSize.height - locRect.height) / 2; + _t._offsetPosition.x = relativeOffsetX + (_t._contentSize.width - locRect.width) / 2; + _t._offsetPosition.y = relativeOffsetY + (_t._contentSize.height - locRect.height) / 2; // rendering using batch node if (_t._batchNode) { From 9cdb4c03cf444f33105d384159692f48db502a4f Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 27 Feb 2015 11:20:24 +0800 Subject: [PATCH 0309/1345] update scheduler cocos2d/cocos2d-js#1316 --- cocos2d/core/CCDirector.js | 2 +- cocos2d/core/CCScheduler.js | 785 ++++++++++++------ cocos2d/core/base-nodes/CCNode.js | 75 +- .../armature/utils/CCDataReaderHelper.js | 2 +- 4 files changed, 617 insertions(+), 247 deletions(-) diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js index c4111ffdc3..ab18b55675 100644 --- a/cocos2d/core/CCDirector.js +++ b/cocos2d/core/CCDirector.js @@ -154,7 +154,7 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ this._scheduler = new cc.Scheduler(); //action manager this._actionManager = cc.ActionManager ? new cc.ActionManager() : null; - this._scheduler.scheduleUpdateForTarget(this._actionManager, cc.Scheduler.PRIORITY_SYSTEM, false); + this._scheduler.scheduleUpdate(this._actionManager, cc.Scheduler.PRIORITY_SYSTEM, false); this._eventAfterDraw = new cc.EventCustom(cc.Director.EVENT_AFTER_DRAW); this._eventAfterDraw.setUserData(this); diff --git a/cocos2d/core/CCScheduler.js b/cocos2d/core/CCScheduler.js index df1f7354cc..6bc4a72b0b 100644 --- a/cocos2d/core/CCScheduler.js +++ b/cocos2d/core/CCScheduler.js @@ -39,14 +39,16 @@ cc.PRIORITY_NON_SYSTEM = cc.PRIORITY_SYSTEM + 1; * @name cc.ListEntry * @param {cc.ListEntry} prev * @param {cc.ListEntry} next + * @param {function} callback * @param {cc.Class} target not retained (retained by hashUpdateEntry) * @param {Number} priority * @param {Boolean} paused * @param {Boolean} markedForDeletion selector will no longer be called and entry will be removed at end of the next tick */ -cc.ListEntry = function (prev, next, target, priority, paused, markedForDeletion) { +cc.ListEntry = function (prev, next, callback, target, priority, paused, markedForDeletion) { this.prev = prev; this.next = next; + this.callback = callback; this.target = target; this.priority = priority; this.paused = paused; @@ -60,12 +62,14 @@ cc.ListEntry = function (prev, next, target, priority, paused, markedForDeletion * @param {cc.ListEntry} list Which list does it belong to ? * @param {cc.ListEntry} entry entry in the list * @param {cc.Class} target hash key (retained) + * @param {function} callback * @param {Array} hh */ -cc.HashUpdateEntry = function (list, entry, target, hh) { +cc.HashUpdateEntry = function (list, entry, target, callback, hh) { this.list = list; this.entry = entry; this.target = target; + this.callback = callback; this.hh = hh; }; @@ -81,7 +85,7 @@ cc.HashUpdateEntry = function (list, entry, target, hh) { * @param {Boolean} paused * @param {Array} hh */ -cc.HashTimerEntry = function (timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused, hh) { +cc.HashTimerEntry = cc.hashSelectorEntry = function (timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused, hh) { var _t = this; _t.timers = timers; _t.target = target; @@ -98,17 +102,18 @@ cc.HashTimerEntry = function (timers, target, timerIndex, currentTimer, currentT * @extends cc.Class */ cc.Timer = cc.Class.extend(/** @lends cc.Timer# */{ - _interval:0.0, - _callback:null,//is called _callback before - - _target:null,//target of _callback + _scheduler: null, _elapsed:0.0, - _runForever:false, _useDelay:false, _timesExecuted:0, _repeat:0, //0 = once, 1 is 2 x executed _delay:0, + _interval:0.0, + + //_callback:null,//is called _callback before + //_target:null,//target of _callback + /** * @return {Number} returns interval of timer @@ -119,10 +124,30 @@ cc.Timer = cc.Class.extend(/** @lends cc.Timer# */{ */ setInterval : function(interval){this._interval = interval;}, + setupTimerWithInterval: function(seconds, repeat, delay){ + //todo checking here + this._elapsed = -1; + this._interval = seconds; + this._delay = delay; + this._useDelay = this._delay > 0 ? true : false; + this._repeat = repeat; + this._runForever = this._repeat == cc.REPEAT_FOREVER ? true : false; + }, + + //todo checking here + trigger: function(){ + return 0; + }, + + //todo checking here + cancel: function(){ + return 0; + }, + /** * @return {String|function} returns callback */ - getCallback : function(){return this._callback}, + //getCallback : function(){return this._callback}, /** @@ -135,23 +160,14 @@ cc.Timer = cc.Class.extend(/** @lends cc.Timer# */{ * @param {Number} [delay=0] delay */ ctor:function (target, callback, interval, repeat, delay) { - var self = this; - self._target = target; - self._callback = callback; - self._elapsed = -1; - self._interval = interval || 0; - self._delay = delay || 0; - self._useDelay = self._delay > 0; - self._repeat = (repeat == null) ? cc.REPEAT_FOREVER : repeat; - self._runForever = (self._repeat == cc.REPEAT_FOREVER); - }, - - _doCallback:function(){ - var self = this; - if (cc.isString(self._callback)) - self._target[self._callback](self._elapsed); - else // if (typeof(this._callback) == "function") { - self._callback.call(self._target, self._elapsed); + this._scheduler = null; + this._elapsed = -1; + this._runForever = false; + this._useDelay = false; + this._timesExecuted = 0; + this._repeat = 0; + this._delay = 0; + this._interval = 0; }, /** @@ -159,47 +175,119 @@ cc.Timer = cc.Class.extend(/** @lends cc.Timer# */{ * @param {Number} dt delta time */ update:function (dt) { - var self = this; - if (self._elapsed == -1) { - self._elapsed = 0; - self._timesExecuted = 0; + if (this._elapsed == -1) { + this._elapsed = 0; + this._timesExecuted = 0; } else { - var locTarget = self._target, locCallback = self._callback; - self._elapsed += dt;//standard timer usage - if (self._runForever && !self._useDelay) { - if (self._elapsed >= self._interval) { - if (locTarget && locCallback) - self._doCallback(); - self._elapsed = 0; + this._elapsed += dt; + if (this._runForever && !this._useDelay) {//standard timer usage + if (this._elapsed >= this._interval) { + this.trigger(); + this._elapsed = 0; } - } else { - //advanced usage - if (self._useDelay) { - if (self._elapsed >= self._delay) { - if (locTarget && locCallback) - self._doCallback(); - - self._elapsed = self._elapsed - self._delay; - self._timesExecuted += 1; - self._useDelay = false; + } else {//advanced usage + if (this._useDelay) { + if (this._elapsed >= this._delay) { + this.trigger(); + + this._elapsed -= this._delay; + this._timesExecuted += 1; + this._useDelay = false; } } else { - if (self._elapsed >= self._interval) { - if (locTarget && locCallback) - self._doCallback(); + if (this._elapsed >= this._interval) { + this.trigger(); - self._elapsed = 0; - self._timesExecuted += 1; + this._elapsed = 0; + this._timesExecuted += 1; } } - if (self._timesExecuted > self._repeat) - cc.director.getScheduler().unscheduleCallbackForTarget(locTarget, locCallback); + if (!this._runForever && this._timesExecuted > this._repeat) + this.cancel(); } } } }); +cc.TimerTargetSelector = cc.Timer.extend({ + + _target: null, + _selector: null, + + ctor: function(){ + this._target = null; + this._selector = null; + }, + + initWithSelector: function(scheduler, selector, target, seconds, repeat, delay){ + this._scheduler = scheduler; + this._target = target; + this._selector = selector; + this.setupTimerWithInterval(seconds, repeat, delay); + return true; + }, + + getSelector: function(){ + return this._selector; + }, + + trigger: function(){ + //override + if (this._target && this._selector){ + this._target.call(this._selector, this._elapsed); + } + }, + + cancel: function(){ + //override + this._scheduler.unschedule(this._selector, this._target); + } + +}); + +cc.TimerTargetCallback = cc.Timer.extend({ + + _target: null, + _callback: null, + _key: null, + + ctor: function(){ + this._target = null; + this._callback = null; + }, + + initWithCallback: function(scheduler, callback, target, key, seconds, repeat, delay){ + //todo checking here + this._scheduler = scheduler; + this._target = target; + this._callback = callback; + this._key = key; + this.setupTimerWithInterval(seconds, repeat, delay); + return true; + }, + + getCallback: function(){ + return this._callback; + }, + + getKey: function(){ + return this._key; + }, + + trigger: function(){ + //override + if(this._callback) + this._callback.call(this._target, this._elapsed); + }, + + cancel: function(){ + //override + this._scheduler.unschedule(this._key, this._target); + } + +}); + /** *

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

when all the resource are downloaded it will invoke call function

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

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

Running benchmarks...

+
+
+

+ +
+
+

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

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

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

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