From 3f4d6f38d35e4f14202ad47155f0862b99b226f4 Mon Sep 17 00:00:00 2001 From: Talisca Date: Mon, 30 Nov 2015 12:02:07 +0100 Subject: [PATCH 01/34] fix scale9sprite opacity update --- extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js b/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js index 861727552a..19a5fbb1c5 100644 --- a/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js +++ b/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js @@ -106,8 +106,8 @@ proto._syncStatus = function (parentCmd){ cc.Node.WebGLRenderCmd.prototype._syncStatus.call(this, parentCmd); - this._updateDisplayColor(this._displayedColor); - this._updateDisplayOpacity(this._displayedOpacity); + this._updateDisplayColor(this._node._displayedColor); + this._updateDisplayOpacity(this._node._displayedOpacity); }; proto._updateDisplayColor = function(parentColor){ From ed45554f0e211aee4336b6e7f5b91f1c25052163 Mon Sep 17 00:00:00 2001 From: Talisca Date: Mon, 30 Nov 2015 12:41:46 +0100 Subject: [PATCH 02/34] update artifacts by stretching texel --- cocos2d/core/platform/CCConfig.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/platform/CCConfig.js b/cocos2d/core/platform/CCConfig.js index 1e3adc4e4c..8c1a6bb1be 100644 --- a/cocos2d/core/platform/CCConfig.js +++ b/cocos2d/core/platform/CCConfig.js @@ -56,7 +56,7 @@ window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.9"; * @constant * @type {Number} */ -cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL = 0; +cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL = 1; /** * Position of the FPS (Default: 0,0 (bottom-left corner))
@@ -300,4 +300,4 @@ cc.ENABLE_STACKABLE_ACTIONS = 1; * @constant * @type {Number} */ -cc.ENABLE_GL_STATE_CACHE = 1; \ No newline at end of file +cc.ENABLE_GL_STATE_CACHE = 1; From ae20de26066462bad79fcd2d68eefbd44e665245 Mon Sep 17 00:00:00 2001 From: Talisca Date: Mon, 30 Nov 2015 13:32:49 +0100 Subject: [PATCH 03/34] fix scrollview webgl renderer: resolved flickering and black screen --- .../uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js index 43b7cf5237..0752cbe195 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js @@ -17,8 +17,8 @@ return; var currentID = this._node.__instanceId; - cc.renderer.pushRenderCommand(this); - cc.renderer._turnToCacheMode(currentID); + //cc.renderer.pushRenderCommand(this); + //cc.renderer._turnToCacheMode(currentID); ccui.Layout.WebGLRenderCmd.prototype.visit.call(this, parentCmd); // Need to update children after do layout From c3b7abc5df57096caeca1724ece59ed49d13d4d6 Mon Sep 17 00:00:00 2001 From: Talisca Date: Mon, 30 Nov 2015 12:02:07 +0100 Subject: [PATCH 04/34] fix scale9sprite opacity update --- extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js b/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js index a288c05841..484a561e97 100644 --- a/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js +++ b/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js @@ -111,8 +111,8 @@ proto._syncStatus = function (parentCmd){ cc.Node.WebGLRenderCmd.prototype._syncStatus.call(this, parentCmd); - this._updateDisplayColor(this._displayedColor); - this._updateDisplayOpacity(this._displayedOpacity); + this._updateDisplayColor(this._node._displayedColor); + this._updateDisplayOpacity(this._node._displayedOpacity); }; proto._updateDisplayColor = function(parentColor){ From fa1648c27551c8c84b68b5fc57252d2294a908fe Mon Sep 17 00:00:00 2001 From: Talisca Date: Mon, 30 Nov 2015 12:41:46 +0100 Subject: [PATCH 05/34] update artifacts by stretching texel --- cocos2d/core/platform/CCConfig.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/platform/CCConfig.js b/cocos2d/core/platform/CCConfig.js index 5c4b185739..59e08703d4 100644 --- a/cocos2d/core/platform/CCConfig.js +++ b/cocos2d/core/platform/CCConfig.js @@ -56,7 +56,7 @@ window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.10"; * @constant * @type {Number} */ -cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL = 0; +cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL = 1; /** * Position of the FPS (Default: 0,0 (bottom-left corner))
@@ -300,4 +300,4 @@ cc.ENABLE_STACKABLE_ACTIONS = 1; * @constant * @type {Number} */ -cc.ENABLE_GL_STATE_CACHE = 1; \ No newline at end of file +cc.ENABLE_GL_STATE_CACHE = 1; From 14d6b41680214ee7a7c99edeb6d3447285b90fae Mon Sep 17 00:00:00 2001 From: Talisca Date: Mon, 30 Nov 2015 13:32:49 +0100 Subject: [PATCH 06/34] fix scrollview webgl renderer: resolved flickering and black screen --- .../uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js index 43b7cf5237..0752cbe195 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js @@ -17,8 +17,8 @@ return; var currentID = this._node.__instanceId; - cc.renderer.pushRenderCommand(this); - cc.renderer._turnToCacheMode(currentID); + //cc.renderer.pushRenderCommand(this); + //cc.renderer._turnToCacheMode(currentID); ccui.Layout.WebGLRenderCmd.prototype.visit.call(this, parentCmd); // Need to update children after do layout From 6113a3c656ac321bf069cc1d2f08502679abffa0 Mon Sep 17 00:00:00 2001 From: Markus Jankowski Date: Mon, 22 Feb 2016 14:00:54 +0100 Subject: [PATCH 07/34] fix scale9sprites opacity --- .../UIScale9SpriteCanvasRenderCmd.js | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js index aa57c91ab7..ba7eb85263 100644 --- a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js +++ b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js @@ -98,6 +98,25 @@ } }; + proto._updateDisplayOpacity = function (parentOpacity) { + cc.Node.WebGLRenderCmd.prototype._updateDisplayOpacity.call(this, parentOpacity); + var node = this._node; + if (!node) return; + var scale9Image = node._scale9Image; + parentOpacity = this._displayedOpacity; + if (node._scale9Enabled) { + var pChildren = node._renderers; + for (var i = 0; i < pChildren.length; i++) { + pChildren[i]._renderCmd._updateDisplayOpacity(parentOpacity); + pChildren[i]._renderCmd._updateColor(); + } + } + else { + scale9Image._renderCmd._updateDisplayOpacity(parentOpacity); + scale9Image._renderCmd._updateColor(); + } + }; + proto.updateStatus = function () { var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag; @@ -120,6 +139,9 @@ this._cacheScale9Sprite(); this._dirtyFlag = this._dirtyFlag & flags.cacheDirty ^ this._dirtyFlag; } + + if(!this._dirtyFlag) + this._cacheScale9Sprite(); } proto._cacheScale9Sprite = function() { From eeacead2ea871bc1f4528e6434e68ad78c4a37c5 Mon Sep 17 00:00:00 2001 From: Travis Gesslein Date: Wed, 2 Mar 2016 22:34:16 +0100 Subject: [PATCH 08/34] annihilated some useless canvas render cmds --- cocos2d/clipping-nodes/CCClippingNode.js | 3 - .../CCClippingNodeCanvasRenderCmd.js | 215 ------------ .../labelttf/CCLabelTTFCanvasRenderCmd.js | 93 ------ cocos2d/core/sprites/CCSprite.js | 3 - .../core/sprites/CCSpriteCanvasRenderCmd.js | 307 ------------------ cocos2d/core/sprites/CCSpriteFrame.js | 11 - cocos2d/physics/CCPhysicsSprite.js | 3 - .../physics/CCPhysicsSpriteCanvasRenderCmd.js | 93 ------ .../ccui/base-classes/UIScale9Sprite.js | 3 - .../UIScale9SpriteCanvasRenderCmd.js | 215 ------------ .../armature/display/CCSkinCanvasRenderCmd.js | 58 ---- 11 files changed, 1004 deletions(-) diff --git a/cocos2d/clipping-nodes/CCClippingNode.js b/cocos2d/clipping-nodes/CCClippingNode.js index a9f301a658..5dea8bcf4c 100644 --- a/cocos2d/clipping-nodes/CCClippingNode.js +++ b/cocos2d/clipping-nodes/CCClippingNode.js @@ -195,9 +195,6 @@ cc.ClippingNode = cc.Node.extend(/** @lends cc.ClippingNode# */{ }, _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) - return new cc.ClippingNode.CanvasRenderCmd(this); - else return new cc.ClippingNode.WebGLRenderCmd(this); } }); diff --git a/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js b/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js index 5c60928ab0..e69de29bb2 100644 --- a/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js +++ b/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js @@ -1,215 +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. - ****************************************************************************/ - -//-------------------------- ClippingNode's canvas render cmd -------------------------------- -(function(){ - cc.ClippingNode.CanvasRenderCmd = function(renderable){ - cc.Node.CanvasRenderCmd.call(this, renderable); - this._needDraw = false; - - this._godhelpme = false; - this._clipElemType = false; - - this._rendererSaveCmd = new cc.CustomRenderCmd(this, this._saveCmdCallback); - this._rendererClipCmd = new cc.CustomRenderCmd(this, this._clipCmdCallback); - this._rendererRestoreCmd = new cc.CustomRenderCmd(this, this._restoreCmdCallback); - }; - var proto = cc.ClippingNode.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); - proto.constructor = cc.ClippingNode.CanvasRenderCmd; - - proto.initStencilBits = function(){}; - - proto.setStencil = function(stencil){ - if(stencil == null) - return; - - this._node._stencil = stencil; - - // For shape stencil, rewrite the draw of stencil ,only init the clip path and draw nothing. - //else - if (stencil instanceof cc.DrawNode) { - if(stencil._buffer){ - for(var i=0; i 0; j--) - context.lineTo(vertices[j].x * scaleX, -vertices[j].y * scaleY); - } - }; - }else{ - stencil._parent = this._node; - } - }; - - proto._saveCmdCallback = function(ctx, scaleX, scaleY) { - var wrapper = ctx || cc._renderContext, context = wrapper.getContext(); - - if (this._clipElemType) { - var locCache = cc.ClippingNode.CanvasRenderCmd._getSharedCache(); - var canvas = context.canvas; - locCache.width = canvas.width; - locCache.height = canvas.height; //note: on some browser, it can't clear the canvas, e.g. baidu - var locCacheCtx = locCache.getContext("2d"); - locCacheCtx.drawImage(canvas, 0, 0); //save the result to shareCache canvas - } else { - wrapper.save(); - context.beginPath(); //save for clip - //Because drawNode's content size is zero - wrapper.setTransform(this._worldTransform, scaleX, scaleY); - - if (this._node.inverted) { - context.rect(0, 0, context.canvas.width, -context.canvas.height); - context.clip(); - } - } - }; - - proto._setStencilCompositionOperation = function(stencil){ - if(!stencil) - return; - var node = this._node; - if(stencil._renderCmd && stencil._renderCmd._blendFuncStr) //it is a hack way. - stencil._renderCmd._blendFuncStr = (node.inverted ? "destination-out" : "destination-in"); - - if(!stencil._children) - return; - var children = stencil._children; - for(var i = 0, len = children.length; i < len; i++){ - this._setStencilCompositionOperation(children[i]); - } - }; - - proto._clipCmdCallback = function(ctx) { - var node = this._node; - var wrapper = ctx || cc._renderContext, context = wrapper.getContext(); - - if (this._clipElemType) { - //hack - this._setStencilCompositionOperation(node._stencil); - } else { - context.clip(); - } - }; - - proto._restoreCmdCallback = function (ctx) { - var locCache = cc.ClippingNode.CanvasRenderCmd._getSharedCache(); - var wrapper = ctx || cc._renderContext, context = wrapper.getContext(); - if (this._clipElemType) { - // Redraw the cached canvas, so that the clipped area shows the background etc. - context.save(); - context.setTransform(1, 0, 0, 1, 0, 0); - context.globalCompositeOperation = "destination-over"; - context.drawImage(locCache, 0, 0); - context.restore(); - this._dirtyFlag = 0; - } else { - wrapper.restore(); //use for restore clip operation - } - }; - - proto.transform = function(parentCmd, recursive){ - cc.Node.CanvasRenderCmd.prototype.transform.call(this, parentCmd, recursive); - var node = this._node; - if(node._stencil && node._stencil._renderCmd) - node._stencil._renderCmd.transform(this, recursive); - }; - - proto._cangodhelpme = function (godhelpme) { - if (godhelpme === true || godhelpme === false) - cc.ClippingNode.CanvasRenderCmd.prototype._godhelpme = godhelpme; - return cc.ClippingNode.CanvasRenderCmd.prototype._godhelpme; - }; - - proto.visit = function(parentCmd){ - var node = this._node; - // quick return if not visible - if (!node._visible) - return; - - parentCmd = parentCmd || this.getParentRenderCmd(); - if( parentCmd) - this._curLevel = parentCmd._curLevel + 1; - var transformRenderCmd = this; - - // Composition mode, costy but support texture stencil - 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 - return; - } - - this._syncStatus(parentCmd); - cc.renderer.pushRenderCommand(this._rendererSaveCmd); - if(this._clipElemType){ - // Draw everything first using node visit function - cc.Node.CanvasRenderCmd.prototype.visit.call(this, parentCmd); - }else{ - node._stencil.visit(this); - } - cc.renderer.pushRenderCommand(this._rendererClipCmd); - - if(this._clipElemType){ - node._stencil.visit(transformRenderCmd); - }else{ - var i, children = node._children; - // Clip mode doesn't support recursive stencil, so once we used a clip stencil, - // so if it has ClippingNode as a child, the child must uses composition stencil. - this._cangodhelpme(true); - var len = children.length; - if (len > 0) { - node.sortAllChildren(); - for (i = 0; i < len; i++) - children[i]._renderCmd.visit(this); - } - this._cangodhelpme(false); - } - - cc.renderer.pushRenderCommand(this._rendererRestoreCmd); - this._dirtyFlag = 0; - }; - - cc.ClippingNode.CanvasRenderCmd._sharedCache = null; - cc.ClippingNode.CanvasRenderCmd._getSharedCache = function () { - return (cc.ClippingNode.CanvasRenderCmd._sharedCache) || (cc.ClippingNode.CanvasRenderCmd._sharedCache = document.createElement("canvas")); - }; -})(); \ No newline at end of file diff --git a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js index 27023ed440..08245e0ceb 100644 --- a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js +++ b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js @@ -412,97 +412,4 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; return this._labelContext.measureText(text).width; }; -})(); - -(function(){ - cc.LabelTTF.CacheCanvasRenderCmd = function (renderable) { - cc.Sprite.CanvasRenderCmd.call(this, renderable); - cc.LabelTTF.CacheRenderCmd.call(this); - }; - - var proto = cc.LabelTTF.CacheCanvasRenderCmd.prototype = Object.create(cc.Sprite.CanvasRenderCmd.prototype); - cc.inject(cc.LabelTTF.CacheRenderCmd.prototype, proto); - proto.constructor = cc.LabelTTF.CacheCanvasRenderCmd; -})(); - -(function(){ - cc.LabelTTF.CanvasRenderCmd = function (renderable) { - cc.Sprite.CanvasRenderCmd.call(this, renderable); - cc.LabelTTF.RenderCmd.call(this); - }; - - cc.LabelTTF.CanvasRenderCmd.prototype = Object.create(cc.Sprite.CanvasRenderCmd.prototype); - cc.inject(cc.LabelTTF.RenderCmd.prototype, cc.LabelTTF.CanvasRenderCmd.prototype); - - var proto = cc.LabelTTF.CanvasRenderCmd.prototype; - proto.constructor = cc.LabelTTF.CanvasRenderCmd; - - proto._measureConfig = function () {}; - - proto._measure = function (text) { - var context = cc._renderContext.getContext(); - context.font = this._fontStyleStr; - return context.measureText(text).width; - }; - - proto._updateTexture = function () { - this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.textDirty ^ this._dirtyFlag; - var node = this._node; - var locContentSize = node._contentSize; - this._updateTTF(); - var width = locContentSize.width, height = locContentSize.height; - if (node._string.length === 0) { - node.setTextureRect(cc.rect(0, 0, 1, locContentSize.height)); - return true; - } - this._saveStatus(); - node.setTextureRect(cc.rect(0, 0, width, height)); - return true; - }; - - proto.rendering = function(ctx) { - var scaleX = cc.view.getScaleX(), - scaleY = cc.view.getScaleY(); - var wrapper = ctx || cc._renderContext, context = wrapper.getContext(); - if (!context) - return; - var node = this._node; - wrapper.computeRealOffsetY(); - if(this._status.length <= 0) - return; - var locIndex = (this._renderingIndex >= this._status.length)? this._renderingIndex-this._status.length:this._renderingIndex; - var status = this._status[locIndex]; - this._renderingIndex = locIndex+1; - - var locHeight = node._rect.height, - locX = node._offsetPosition.x, - locY = -node._offsetPosition.y - locHeight; - - var alpha = (this._displayedOpacity / 255); - - wrapper.setTransform(this._worldTransform, scaleX, scaleY); - wrapper.setCompositeOperation(this._blendFuncStr); - wrapper.setGlobalAlpha(alpha); - - wrapper.save(); - - if (node._flippedX) { - locX = -locX - node._rect.width; - context.scale(-1, 1); - } - if (node._flippedY) { - locY = node._offsetPosition.y; - context.scale(1, -1); - } - - var xOffset = status.xOffset + status.contextTransform.x + locX * scaleX; - var yOffsetArray = []; - - var locStrLen = this._strings.length; - for (var i = 0; i < locStrLen; i++) - yOffsetArray.push(status.OffsetYArray[i] + status.contextTransform.y + locY * scaleY); - - this.drawLabels(context, xOffset, yOffsetArray); - wrapper.restore(); - }; })(); \ No newline at end of file diff --git a/cocos2d/core/sprites/CCSprite.js b/cocos2d/core/sprites/CCSprite.js index c6082ccd83..42be73e482 100644 --- a/cocos2d/core/sprites/CCSprite.js +++ b/cocos2d/core/sprites/CCSprite.js @@ -976,9 +976,6 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ }, _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) - return new cc.Sprite.CanvasRenderCmd(this); - else return new cc.Sprite.WebGLRenderCmd(this); } }); diff --git a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js index eca55cd61d..e69de29bb2 100644 --- a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js @@ -1,307 +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. - ****************************************************************************/ - -(function() { - cc.Sprite.CanvasRenderCmd = function (renderable) { - cc.Node.CanvasRenderCmd.call(this, renderable); - this._needDraw = true; - this._textureCoord = { - renderX: 0, //the x of texture coordinate for render, when texture tinted, its value doesn't equal x. - renderY: 0, //the y of texture coordinate for render, when texture tinted, its value doesn't equal y. - x: 0, //the x of texture coordinate for node. - y: 0, //the y of texture coordinate for node. - width: 0, - height: 0, - validRect: false - }; - this._blendFuncStr = "source-over"; - this._colorized = false; - - this._textureToRender = null; - }; - - var proto = cc.Sprite.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); - proto.constructor = cc.Sprite.CanvasRenderCmd; - - proto._init = function () {}; - - proto.setDirtyRecursively = function (value) {}; - - proto._resetForBatchNode = function () {}; - - proto._setTexture = function (texture) { - var node = this._node; - if (node._texture !== texture) { - if (texture) { - node._textureLoaded = texture._textureLoaded; - }else{ - node._textureLoaded = false; - } - node._texture = texture; - this._updateColor(); - } - }; - - proto._setColorDirty = function () { - this.setDirtyFlag(cc.Node._dirtyFlags.colorDirty | cc.Node._dirtyFlags.opacityDirty); - }; - - proto.isFrameDisplayed = function (frame) { //TODO there maybe has a bug - var node = this._node; - if (frame.getTexture() !== node._texture) - return false; - return cc.rectEqualToRect(frame.getRect(), node._rect); - }; - - proto.updateBlendFunc = function (blendFunc) { - this._blendFuncStr = cc.Node.CanvasRenderCmd._getCompositeOperationByBlendFunc(blendFunc); - }; - - proto._setBatchNodeForAddChild = function (child) { - return true; - }; - - proto._handleTextureForRotatedTexture = function (texture, rect, rotated, counterclockwise) { - if (rotated && texture.isLoaded()) { - var tempElement = texture.getHtmlElementObj(); - 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; - }; - - 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) - cc.error(cc._LogInfos.RectWidth, texture.url); - if (_y > texture.height) - cc.error(cc._LogInfos.RectHeight, texture.url); - } - }; - - proto.rendering = function (ctx, scaleX, scaleY) { - var node = this._node; - var locTextureCoord = this._textureCoord, alpha = (this._displayedOpacity / 255); - - var texture = this._textureToRender || node._texture; - - if ((texture && (locTextureCoord.width === 0 || locTextureCoord.height === 0|| !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); - } - - var sx, sy, sw, sh, x, y, w, h; - if (this._colorized) { - sx = 0; - sy = 0; - }else{ - sx = locTextureCoord.renderX; - sy = locTextureCoord.renderY; - } - sw = locTextureCoord.width; - sh = locTextureCoord.height; - - x = locX * scaleX; - y = locY * scaleY; - w = locWidth * scaleX; - h = locHeight * scaleY; - - if (texture) { - image = texture._htmlElementObj; - if (texture._pattern !== "") { - wrapper.setFillStyle(context.createPattern(image, texture._pattern)); - context.fillRect(x, y, w, h); - } else { - context.drawImage(image, - sx, sy, sw, sh, - x, y, w, h); - } - } else { - var contentSize = node._contentSize; - if (locTextureCoord.validRect) { - var curColor = this._displayedColor; - wrapper.setFillStyle("rgba(" + curColor.r + "," + curColor.g + "," + curColor.b + ",1)"); - context.fillRect(x, y, contentSize.width * scaleX, contentSize.height * scaleY); - } - } - if(node._flippedX || node._flippedY) - wrapper.restore(); - cc.g_NumberOfDraws++; - }; - - proto._updateColor = function(){ - var node = this._node; - - var texture = node._texture, rect = this._textureCoord; - var dColor = this._displayedColor; - - if(texture){ - if(dColor.r !== 255 || dColor.g !== 255 || dColor.b !== 255){ - this._textureToRender = texture._generateColorTexture(dColor.r, dColor.g, dColor.b, rect); - this._colorized = true; - }else if(texture){ - this._textureToRender = texture; - this._colorized = false; - } - } - }; - - proto.getQuad = function () { - //throw an error. it doesn't support this function. - return null; - }; - - proto._updateForSetSpriteFrame = function (pNewTexture, textureLoaded){ - this._colorized = false; - this._textureCoord.renderX = this._textureCoord.x; - this._textureCoord.renderY = this._textureCoord.y; - textureLoaded = textureLoaded || pNewTexture._textureLoaded; - if (textureLoaded) { - var curColor = this._node.getColor(); - if (curColor.r !== 255 || curColor.g !== 255 || curColor.b !== 255) - this._updateColor(); - } - }; - - proto.updateTransform = function () { //TODO need delete, because Canvas needn't - var _t = this, node = this._node; - - // re-calculate matrix only if it is dirty - 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)) { - node._shouldBeHidden = true; - } else { - node._shouldBeHidden = false; - - 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"); - node._transformToBatch = cc.affineTransformConcat(_t.getNodeToParentTransform(), locParent._transformToBatch); - } - } - node._recursiveDirty = false; - node.dirty = false; - } - - // recursively iterate over children - if (node._hasChildren) - node._arrayMakeObjectsPerformSelector(node._children, cc.Node._stateCallbackType.updateTransform); - }; - - proto._spriteFrameLoadedCallback = function (spriteFrame) { - var node = this; - node.setTextureRect(spriteFrame.getRect(), spriteFrame.isRotated(), spriteFrame.getOriginalSize()); - - node._renderCmd._updateColor(); - node.dispatchEvent("load"); - }; - - proto._textureLoadedCallback = function (sender) { - var node = this; - if (node._textureLoaded) - return; - - 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)) { - locRect.width = sender.width; - locRect.height = sender.height; - } - - node.texture = sender; - node.setTextureRect(locRect, node._rectRotated); - - //set the texture's color after the it loaded - var locColor = locRenderCmd._displayedColor; - if (locColor.r !== 255 || locColor.g !== 255 || locColor.b !== 255) - locRenderCmd._updateColor(); - - // by default use "Self Render". - // if the sprite is added to a batchnode, then it will automatically switch to "batchnode Render" - node.setBatchNode(node._batchNode); - node.dispatchEvent("load"); - }; - - proto._setTextureCoords = function (rect, needConvert) { - if (needConvert === undefined) - needConvert = true; - var locTextureRect = this._textureCoord, - scaleFactor = needConvert ? cc.contentScaleFactor() : 1; - locTextureRect.renderX = locTextureRect.x = 0 | (rect.x * scaleFactor); - locTextureRect.renderY = locTextureRect.y = 0 | (rect.y * scaleFactor); - 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); - }; - - 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 = document.createElement("canvas"); - nCanvas.width = rect.width; - nCanvas.height = rect.height; - var ctx = nCanvas.getContext("2d"); - ctx.translate(nCanvas.width / 2, nCanvas.height / 2); - 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/cocos2d/core/sprites/CCSpriteFrame.js b/cocos2d/core/sprites/CCSpriteFrame.js index a203e7d439..b2c19fd731 100644 --- a/cocos2d/core/sprites/CCSpriteFrame.js +++ b/cocos2d/core/sprites/CCSpriteFrame.js @@ -243,17 +243,6 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ if(!locLoaded){ texture.addEventListener("load", function(sender){ this._textureLoaded = true; - if(this._rotated && cc._renderType === cc.game.RENDER_TYPE_CANVAS){ - var tempElement = sender.getHtmlElementObj(); - tempElement = cc.Sprite.CanvasRenderCmd._cutRotateImageToCanvas(tempElement, this.getRect()); - var tempTexture = new cc.Texture2D(); - tempTexture.initWithElement(tempElement); - tempTexture.handleLoadedTexture(); - this.setTexture(tempTexture); - - var rect = this.getRect(); - this.setRect(cc.rect(0, 0, rect.width, rect.height)); - } var locRect = this._rect; if(locRect.width === 0 && locRect.height === 0){ var w = sender.width, h = sender.height; diff --git a/cocos2d/physics/CCPhysicsSprite.js b/cocos2d/physics/CCPhysicsSprite.js index 0bb9db8627..862a4d775d 100644 --- a/cocos2d/physics/CCPhysicsSprite.js +++ b/cocos2d/physics/CCPhysicsSprite.js @@ -404,9 +404,6 @@ }, _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) - return new cc.PhysicsSprite.CanvasRenderCmd(this); - else return new cc.PhysicsSprite.WebGLRenderCmd(this); } }; diff --git a/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js b/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js index ae95d94df9..e69de29bb2 100644 --- a/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js +++ b/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js @@ -1,93 +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. - ****************************************************************************/ - -/** - * cc.PhysicsSprite's rendering objects of Canvas - */ -(function(){ - cc.PhysicsSprite.CanvasRenderCmd = function(renderableObject){ - cc.Sprite.CanvasRenderCmd.call(this, renderableObject); - this._needDraw = true; - }; - - var proto = cc.PhysicsSprite.CanvasRenderCmd.prototype = Object.create(cc.Sprite.CanvasRenderCmd.prototype); - proto.constructor = cc.PhysicsSprite.CanvasRenderCmd; - - proto.rendering = function(ctx, scaleX, scaleY){ - // This is a special class - // Sprite can not obtain sign - // So here must to calculate of each frame - var node = this._node; - node._syncPosition(); - if(!node._ignoreBodyRotation) - node._syncRotation(); - this.transform(this.getParentRenderCmd()); - - cc.Sprite.CanvasRenderCmd.prototype.rendering.call(this, ctx, scaleX, scaleY); - }; - - proto.getNodeToParentTransform = function(){ - var node = this._node; - - var t = this._transform;// quick reference - // base position - var locBody = node._body, locScaleX = node._scaleX, locScaleY = node._scaleY, locAnchorPIP = this._anchorPointInPoints; - t.tx = locBody.p.x; - t.ty = locBody.p.y; - - // rotation Cos and Sin - var radians = -locBody.a; - var Cos = 1, Sin = 0; - if (radians && !node._ignoreBodyRotation) { - Cos = Math.cos(radians); - Sin = Math.sin(radians); - } - - // base abcd - t.a = t.d = Cos; - t.b = -Sin; - t.c = Sin; - - // scale - if (locScaleX !== 1 || locScaleY !== 1) { - t.a *= locScaleX; - t.c *= locScaleX; - t.b *= locScaleY; - t.d *= locScaleY; - } - - // adjust anchorPoint - t.tx += Cos * -locAnchorPIP.x * locScaleX + -Sin * locAnchorPIP.y * locScaleY; - t.ty -= Sin * -locAnchorPIP.x * locScaleX + Cos * locAnchorPIP.y * locScaleY; - - // if ignore anchorPoint - if (this._ignoreAnchorPointForPosition) { - t.tx += locAnchorPIP.x; - t.ty += locAnchorPIP.y; - } - - return this._transform; - }; - -})(); \ No newline at end of file diff --git a/extensions/ccui/base-classes/UIScale9Sprite.js b/extensions/ccui/base-classes/UIScale9Sprite.js index 23eb7aeb96..26df4b3c34 100644 --- a/extensions/ccui/base-classes/UIScale9Sprite.js +++ b/extensions/ccui/base-classes/UIScale9Sprite.js @@ -1114,9 +1114,6 @@ ccui.Scale9Sprite = cc.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprit }, _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) - return new ccui.Scale9Sprite.CanvasRenderCmd(this); - else return new ccui.Scale9Sprite.WebGLRenderCmd(this); } }); diff --git a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js index ba7eb85263..e69de29bb2 100644 --- a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js +++ b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js @@ -1,215 +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. - ****************************************************************************/ - -(function() { - ccui.Scale9Sprite.CanvasRenderCmd = function (renderable) { - 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 = document.createElement('canvas'); - locCacheCanvas.width = 1; - locCacheCanvas.height = 1; - this._cacheContext = new cc.CanvasContextWrapper(locCacheCanvas.getContext("2d")); - var locTexture = this._cacheTexture = new cc.Texture2D(); - locTexture.initWithElement(locCacheCanvas); - locTexture.handleLoadedTexture(); - this._cacheSprite = new cc.Sprite(locTexture); - this._cacheSprite.setAnchorPoint(0,0); - node.addChild(this._cacheSprite); - }; - - var proto = ccui.Scale9Sprite.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); - proto.constructor = ccui.Scale9Sprite.CanvasRenderCmd; - - proto.visit = function(parentCmd){ - var node = this._node; - if(!node._visible) - return; - - if (node._positionsAreDirty) { - node._updatePositions(); - node._positionsAreDirty = false; - } - - 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; - } - - var children = node._children; - for(var i=0; i Date: Wed, 2 Mar 2016 22:56:00 +0100 Subject: [PATCH 09/34] nuked more canvas --- cocos2d/core/CCDirectorCanvas.js | 82 ---- cocos2d/core/CCDrawingPrimitivesCanvas.js | 438 ----------------- cocos2d/core/base-nodes/CCAtlasNode.js | 3 - .../base-nodes/CCAtlasNodeCanvasRenderCmd.js | 91 ---- cocos2d/core/base-nodes/CCNode.js | 3 - cocos2d/core/labelttf/CCLabelTTF.js | 2 - cocos2d/core/layers/CCLayer.js | 9 - cocos2d/core/layers/CCLayerCanvasRenderCmd.js | 458 ------------------ cocos2d/core/sprites/CCSpriteBatchNode.js | 4 +- .../CCSpriteBatchNodeCanvasRenderCmd.js | 100 ---- cocos2d/core/sprites/CCSpriteFrameCache.js | 17 +- cocos2d/labels/CCLabelAtlas.js | 3 - cocos2d/labels/CCLabelAtlasCanvasRenderCmd.js | 110 ----- cocos2d/labels/CCLabelBMFont.js | 6 +- .../labels/CCLabelBMFontCanvasRenderCmd.js | 107 ---- cocos2d/node-grid/CCNodeGrid.js | 3 - cocos2d/parallax/CCParallaxNode.js | 3 - cocos2d/parallax/CCParallaxNodeRenderCmd.js | 19 - cocos2d/particle/CCParticleBatchNode.js | 3 - .../CCParticleBatchNodeCanvasRenderCmd.js | 38 -- cocos2d/particle/CCParticleSystem.js | 3 - .../CCParticleSystemCanvasRenderCmd.js | 199 -------- cocos2d/physics/CCPhysicsDebugNode.js | 3 - .../CCPhysicsDebugNodeCanvasRenderCmd.js | 52 -- cocos2d/progress-timer/CCProgressTimer.js | 3 - .../CCProgressTimerCanvasRenderCmd.js | 274 ----------- cocos2d/render-texture/CCRenderTexture.js | 3 - .../CCRenderTextureCanvasRenderCmd.js | 107 ---- cocos2d/shape-nodes/CCDrawNode.js | 344 +------------ .../shape-nodes/CCDrawNodeCanvasRenderCmd.js | 131 ----- cocos2d/tilemap/CCTMXLayer.js | 3 - cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js | 220 --------- .../ccui/base-classes/CCProtectedNode.js | 3 - .../CCProtectedNodeCanvasRenderCmd.js | 99 ---- extensions/ccui/base-classes/UIWidget.js | 6 +- .../ccui/base-classes/UIWidgetRenderCmd.js | 38 +- extensions/ccui/layouts/UILayout.js | 3 - .../ccui/layouts/UILayoutCanvasRenderCmd.js | 179 ------- .../uiwidgets/scroll-widget/UIScrollView.js | 5 +- .../UIScrollViewCanvasRenderCmd.js | 45 -- extensions/cocostudio/armature/CCArmature.js | 3 - .../armature/CCArmatureCanvasRenderCmd.js | 148 ------ extensions/cocostudio/armature/CCBone.js | 13 - .../cocostudio/armature/display/CCSkin.js | 3 - extensions/cocostudio/timeline/CCBoneNode.js | 33 -- extensions/gui/scrollview/CCScrollView.js | 7 +- .../scrollview/CCScrollViewCanvasRenderCmd.js | 80 --- extensions/spine/CCSkeleton.js | 3 - extensions/spine/CCSkeletonCanvasRenderCmd.js | 213 -------- external/gaf/Library/GAFSprite.js | 3 - .../gaf/Library/GAFSpriteCanvasRenderCmd.js | 233 --------- 51 files changed, 11 insertions(+), 3947 deletions(-) diff --git a/cocos2d/core/CCDirectorCanvas.js b/cocos2d/core/CCDirectorCanvas.js index 12deec5914..e69de29bb2 100644 --- a/cocos2d/core/CCDirectorCanvas.js +++ b/cocos2d/core/CCDirectorCanvas.js @@ -1,82 +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.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { - - if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) { - var _p = cc.Director.prototype; - - _p.getProjection = function (projection) { - return this._projection; - }; - - _p.setProjection = function (projection) { - this._projection = projection; - cc.eventManager.dispatchEvent(this._eventProjectionChanged); - }; - - _p.setDepthTest = function () { - }; - - _p.setClearColor = function (clearColor) { - cc.renderer._clearColor = clearColor; - cc.renderer._clearFillStyle = 'rgb(' + clearColor.r + ',' + clearColor.g + ',' + clearColor.b +')' ; - }; - - _p.setOpenGLView = function (openGLView) { - // set size - this._winSizeInPoints.width = cc._canvas.width; //this._openGLView.getDesignResolutionSize(); - this._winSizeInPoints.height = cc._canvas.height; - this._openGLView = openGLView || cc.view; - if (cc.eventManager) - cc.eventManager.setEnabled(true); - }; - - _p.getVisibleSize = function () { - //if (this._openGLView) { - //return this._openGLView.getVisibleSize(); - //} else { - return this.getWinSize(); - //} - }; - - _p.getVisibleOrigin = function () { - //if (this._openGLView) { - //return this._openGLView.getVisibleOrigin(); - //} else { - return cc.p(0, 0); - //} - }; - } else { - cc.Director._fpsImage = new Image(); - cc.Director._fpsImage.addEventListener("load", function () { - cc.Director._fpsImageLoaded = true; - }); - if (cc._fpsImage) { - cc.Director._fpsImage.src = cc._fpsImage; - } - } -}); diff --git a/cocos2d/core/CCDrawingPrimitivesCanvas.js b/cocos2d/core/CCDrawingPrimitivesCanvas.js index a08dfbe38c..e69de29bb2 100644 --- a/cocos2d/core/CCDrawingPrimitivesCanvas.js +++ b/cocos2d/core/CCDrawingPrimitivesCanvas.js @@ -1,438 +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. - ****************************************************************************/ -/** - * @const - * @type {number} - */ -cc.PI2 = Math.PI * 2; - -/** - * Canvas of DrawingPrimitive implement version use for canvasMode - * @class - * @extends cc.Class - * @param {CanvasRenderingContext2D} renderContext - */ -cc.DrawingPrimitiveCanvas = cc.Class.extend(/** @lends cc.DrawingPrimitiveCanvas# */{ - _cacheArray:[], - _renderContext:null, - /** - * Constructor of cc.DrawingPrimitiveCanvas - * @param {cc.CanvasContextWrapper} renderContext - */ - ctor:function (renderContext) { - this._renderContext = renderContext; - }, - - /** - * draws a point given x and y coordinate measured in points - * @override - * @param {cc.Point} point - * @param {Number} size - */ - drawPoint:function (point, size) { - if (!size) { - size = 1; - } - var locScaleX = cc.view.getScaleX(), locScaleY = cc.view.getScaleY(); - var newPoint = cc.p(point.x * locScaleX, point.y * locScaleY); - var ctx = this._renderContext.getContext(); - ctx.beginPath(); - ctx.arc(newPoint.x, -newPoint.y, size * locScaleX, 0, Math.PI * 2, false); - ctx.closePath(); - ctx.fill(); - }, - - /** - * draws an array of points. - * @override - * @param {Array} points point of array - * @param {Number} numberOfPoints - * @param {Number} size - */ - drawPoints:function (points, numberOfPoints, size) { - if (points == null) - return; - - if (!size) { - size = 1; - } - var locContext = this._renderContext.getContext(),locScaleX = cc.view.getScaleX(), locScaleY = cc.view.getScaleY(); - - locContext.beginPath(); - for (var i = 0, len = points.length; i < len; i++) - locContext.arc(points[i].x * locScaleX, -points[i].y * locScaleY, size * locScaleX, 0, Math.PI * 2, false); - locContext.closePath(); - locContext.fill(); - }, - - /** - * draws a line given the origin and destination point measured in points - * @override - * @param {cc.Point} origin - * @param {cc.Point} destination - */ - drawLine:function (origin, destination) { - var locContext = this._renderContext.getContext(), locScaleX = cc.view.getScaleX(), locScaleY = cc.view.getScaleY(); - locContext.beginPath(); - locContext.moveTo(origin.x * locScaleX, -origin.y * locScaleY); - locContext.lineTo(destination.x * locScaleX, -destination.y * locScaleY); - locContext.closePath(); - locContext.stroke(); - }, - - /** - * draws a rectangle given the origin and destination point measured in points. - * @param {cc.Point} origin - * @param {cc.Point} destination - */ - drawRect:function (origin, destination) { - //todo need optimize for performance - this.drawLine(cc.p(origin.x, origin.y), cc.p(destination.x, origin.y)); - this.drawLine(cc.p(destination.x, origin.y), cc.p(destination.x, destination.y)); - this.drawLine(cc.p(destination.x, destination.y), cc.p(origin.x, destination.y)); - this.drawLine(cc.p(origin.x, destination.y), cc.p(origin.x, origin.y)); - }, - - /** - * draws a solid rectangle given the origin and destination point measured in points. - * @param {cc.Point} origin - * @param {cc.Point} destination - * @param {cc.Color} color - */ - drawSolidRect:function (origin, destination, color) { - var vertices = [ - origin, - cc.p(destination.x, origin.y), - destination, - cc.p(origin.x, destination.y) - ]; - - this.drawSolidPoly(vertices, 4, color); - }, - - /** - * draws a polygon given a pointer to cc.Point coordinates and the number of vertices measured in points. - * @override - * @param {Array} vertices a pointer to cc.Point coordinates - * @param {Number} numOfVertices the number of vertices measured in points - * @param {Boolean} closePolygon The polygon can be closed or open - * @param {Boolean} [fill=] The polygon can be closed or open and optionally filled with current color - */ - drawPoly:function (vertices, numOfVertices, closePolygon, fill) { - fill = fill || false; - - if (vertices == null) - return; - - if (vertices.length < 3) - throw new Error("Polygon's point must greater than 2"); - - var firstPoint = vertices[0], locContext = this._renderContext.getContext(); - var locScaleX = cc.view.getScaleX(), locScaleY = cc.view.getScaleY(); - locContext.beginPath(); - locContext.moveTo(firstPoint.x * locScaleX, -firstPoint.y * locScaleY); - for (var i = 1, len = vertices.length; i < len; i++) - locContext.lineTo(vertices[i].x * locScaleX, -vertices[i].y * locScaleY); - - if (closePolygon) - locContext.closePath(); - - if (fill) - locContext.fill(); - else - locContext.stroke(); - }, - - /** - * draws a solid polygon given a pointer to CGPoint coordinates, the number of vertices measured in points, and a color. - * @param {Array} polygons - * @param {Number} numberOfPoints - * @param {cc.Color} color - */ - drawSolidPoly:function (polygons, numberOfPoints, color) { - this.setDrawColor(color.r, color.g, color.b, color.a); - this.drawPoly(polygons, numberOfPoints, true, true); - }, - - /** - * draws a circle given the center, radius and number of segments. - * @override - * @param {cc.Point} center center of circle - * @param {Number} radius - * @param {Number} angle angle in radians - * @param {Number} segments - * @param {Boolean} [drawLineToCenter=] - */ - drawCircle: function (center, radius, angle, segments, drawLineToCenter) { - drawLineToCenter = drawLineToCenter || false; - var locContext = this._renderContext.getContext(); - var locScaleX = cc.view.getScaleX(), locScaleY = cc.view.getScaleY(); - locContext.beginPath(); - var endAngle = angle - Math.PI * 2; - locContext.arc(0 | (center.x * locScaleX), 0 | -(center.y * locScaleY), radius * locScaleX, -angle, -endAngle, false); - if (drawLineToCenter) { - locContext.lineTo(0 | (center.x * locScaleX), 0 | -(center.y * locScaleY)); - } - locContext.stroke(); - }, - - /** - * draws a quad bezier path - * @override - * @param {cc.Point} origin - * @param {cc.Point} control - * @param {cc.Point} destination - * @param {Number} segments - */ - drawQuadBezier:function (origin, control, destination, segments) { - //this is OpenGL Algorithm - var vertices = this._cacheArray; - vertices.length =0; - - var t = 0.0; - for (var i = 0; i < segments; i++) { - var x = Math.pow(1 - t, 2) * origin.x + 2.0 * (1 - t) * t * control.x + t * t * destination.x; - var y = Math.pow(1 - t, 2) * origin.y + 2.0 * (1 - t) * t * control.y + t * t * destination.y; - vertices.push(cc.p(x, y)); - t += 1.0 / segments; - } - vertices.push(cc.p(destination.x, destination.y)); - - this.drawPoly(vertices, segments + 1, false, false); - }, - - /** - * draws a cubic bezier path - * @override - * @param {cc.Point} origin - * @param {cc.Point} control1 - * @param {cc.Point} control2 - * @param {cc.Point} destination - * @param {Number} segments - */ - drawCubicBezier:function (origin, control1, control2, destination, segments) { - //this is OpenGL Algorithm - var vertices = this._cacheArray; - vertices.length =0; - - var t = 0; - for (var i = 0; i < segments; i++) { - var x = Math.pow(1 - t, 3) * origin.x + 3.0 * Math.pow(1 - t, 2) * t * control1.x + 3.0 * (1 - t) * t * t * control2.x + t * t * t * destination.x; - var y = Math.pow(1 - t, 3) * origin.y + 3.0 * Math.pow(1 - t, 2) * t * control1.y + 3.0 * (1 - t) * t * t * control2.y + t * t * t * destination.y; - vertices.push(cc.p(x , y )); - t += 1.0 / segments; - } - vertices.push(cc.p(destination.x , destination.y)); - - this.drawPoly(vertices, segments + 1, false, false); - }, - - /** - * draw a CatmullRom curve - * @override - * @param {Array} points - * @param {Number} segments - */ - drawCatmullRom:function (points, segments) { - this.drawCardinalSpline(points, 0.5, segments); - }, - - /** - * draw a cardinal spline path - * @override - * @param {Array} config - * @param {Number} tension - * @param {Number} segments - */ - drawCardinalSpline:function (config, tension, segments) { - //lazy_init(); - cc._renderContext.setStrokeStyle("rgba(255,255,255,1)"); - var points = this._cacheArray; - points.length = 0; - var p, lt; - var deltaT = 1.0 / config.length; - - for (var i = 0; i < segments + 1; i++) { - var dt = i / segments; - - // border - if (dt === 1) { - p = config.length - 1; - lt = 1; - } else { - p = 0 | (dt / deltaT); - lt = (dt - deltaT * p) / deltaT; - } - - // Interpolate - var newPos = cc.CardinalSplineAt( - cc.getControlPointAt(config, p - 1), - cc.getControlPointAt(config, p - 0), - cc.getControlPointAt(config, p + 1), - cc.getControlPointAt(config, p + 2), - tension, lt); - points.push(newPos); - } - this.drawPoly(points, segments + 1, false, false); - }, - - /** - * draw an image - * @override - * @param {HTMLImageElement|HTMLCanvasElement} image - * @param {cc.Point} sourcePoint - * @param {cc.Size} sourceSize - * @param {cc.Point} destPoint - * @param {cc.Size} destSize - */ - drawImage:function (image, sourcePoint, sourceSize, destPoint, destSize) { - var len = arguments.length; - var ctx = this._renderContext.getContext(); - switch (len) { - case 2: - var height = image.height; - ctx.drawImage(image, sourcePoint.x, -(sourcePoint.y + height)); - break; - case 3: - ctx.drawImage(image, sourcePoint.x, -(sourcePoint.y + sourceSize.height), sourceSize.width, sourceSize.height); - break; - case 5: - ctx.drawImage(image, sourcePoint.x, sourcePoint.y, sourceSize.width, sourceSize.height, destPoint.x, -(destPoint.y + destSize.height), - destSize.width, destSize.height); - break; - default: - throw new Error("Argument must be non-nil"); - break; - } - }, - - /** - * draw a star - * @param {cc.CanvasContextWrapper} ctx canvas context - * @param {Number} radius - * @param {cc.Color} color - */ - drawStar:function (ctx, radius, color) { - var wrapper = ctx || this._renderContext; - var context = wrapper.getContext(); - radius *= cc.view.getScaleX(); - var colorStr = "rgba(" + (0 | color.r) + "," + (0 | color.g) + "," + (0 | color.b); - wrapper.setFillStyle(colorStr + ",1)"); - //context.fillStyle = colorStr + ",1)"; - var subRadius = radius / 10; - - context.beginPath(); - context.moveTo(-radius, radius); - context.lineTo(0, subRadius); - context.lineTo(radius, radius); - context.lineTo(subRadius, 0); - context.lineTo(radius, -radius); - context.lineTo(0, -subRadius); - context.lineTo(-radius, -radius); - context.lineTo(-subRadius, 0); - context.lineTo(-radius, radius); - context.closePath(); - context.fill(); - - var rg = context.createRadialGradient(0, 0, subRadius, 0, 0, radius); - rg.addColorStop(0, colorStr + ", 1)"); - rg.addColorStop(0.3, colorStr + ", 0.8)"); - rg.addColorStop(1.0, colorStr + ", 0.0)"); - wrapper.setFillStyle(rg); - //context.fillStyle = g1; - context.beginPath(); - var startAngle_1 = 0; - var endAngle_1 = cc.PI2; - context.arc(0, 0, radius - subRadius, startAngle_1, endAngle_1, false); - context.closePath(); - context.fill(); - }, - - /** - * draw a color ball - * @param {cc.CanvasContextWrapper} ctx canvas context - * @param {Number} radius - * @param {cc.Color} color - */ - drawColorBall:function (ctx, radius, color) { - var wrapper = ctx || this._renderContext; - var context = wrapper.getContext(); - radius *= cc.view.getScaleX(); - var colorStr = "rgba(" +(0|color.r) + "," + (0|color.g) + "," + (0|color.b); - var subRadius = radius / 10; - - var g1 = context.createRadialGradient(0, 0, subRadius, 0, 0, radius); - g1.addColorStop(0, colorStr + ", 1)"); - g1.addColorStop(0.3, colorStr + ", 0.8)"); - g1.addColorStop(0.6, colorStr + ", 0.4)"); - g1.addColorStop(1.0, colorStr + ", 0.0)"); - wrapper.setFillStyle(g1); - //context.fillStyle = g1; - context.beginPath(); - var startAngle_1 = 0; - var endAngle_1 = cc.PI2; - context.arc(0, 0, radius, startAngle_1, endAngle_1, false); - context.closePath(); - context.fill(); - }, - - /** - * fill text - * @param {String} strText - * @param {Number} x - * @param {Number} y - */ - fillText:function (strText, x, y) { - this._renderContext.getContext().fillText(strText, x, -y); - }, - - /** - * set the drawing color with 4 unsigned bytes - * @param {Number} r red value (0 to 255) - * @param {Number} g green value (0 to 255) - * @param {Number} b blue value (0 to 255) - * @param {Number} a Alpha value (0 to 255) - */ - setDrawColor:function (r, g, b, a) { - this._renderContext.setFillStyle("rgba(" + r + "," + g + "," + b + "," + a / 255 + ")"); - this._renderContext.setStrokeStyle("rgba(" + r + "," + g + "," + b + "," + a / 255 + ")"); - }, - - /** - * set the point size in points. Default 1. - * @param {Number} pointSize - */ - setPointSize:function (pointSize) { - }, - - /** - * set the line width. Default 1. - * @param {Number} width - */ - setLineWidth:function (width) { - this._renderContext.getContext().lineWidth = width * cc.view.getScaleX(); - } -}); \ No newline at end of file diff --git a/cocos2d/core/base-nodes/CCAtlasNode.js b/cocos2d/core/base-nodes/CCAtlasNode.js index 336ab7cc57..88bac2a720 100644 --- a/cocos2d/core/base-nodes/CCAtlasNode.js +++ b/cocos2d/core/base-nodes/CCAtlasNode.js @@ -86,9 +86,6 @@ cc.AtlasNode = cc.Node.extend(/** @lends cc.AtlasNode# */{ }, _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) - this._renderCmd = new cc.AtlasNode.CanvasRenderCmd(this); - else this._renderCmd = new cc.AtlasNode.WebGLRenderCmd(this); }, diff --git a/cocos2d/core/base-nodes/CCAtlasNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCAtlasNodeCanvasRenderCmd.js index 3d0162aed3..e69de29bb2 100644 --- a/cocos2d/core/base-nodes/CCAtlasNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCAtlasNodeCanvasRenderCmd.js @@ -1,91 +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. - ****************************************************************************/ - -/** - * cc.AtlasNode's rendering objects of Canvas - */ -(function(){ - cc.AtlasNode.CanvasRenderCmd = function(renderableObject){ - cc.Node.CanvasRenderCmd.call(this, renderableObject); - this._needDraw = false; - this._colorUnmodified = cc.color.WHITE; - this._textureToRender = null; - }; - - var proto = cc.AtlasNode.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); - proto.constructor = cc.AtlasNode.CanvasRenderCmd; - - proto.initWithTexture = function(texture, tileWidth, tileHeight, itemsToRender){ - var node = this._node; - node._itemWidth = tileWidth; - node._itemHeight = tileHeight; - - node._opacityModifyRGB = true; - node._texture = texture; - if (!node._texture) { - cc.log(cc._LogInfos.AtlasNode__initWithTexture); - return false; - } - this._textureToRender = texture; - this._calculateMaxItems(); - - node.quadsToDraw = itemsToRender; - return true; - }; - - 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)) - return; - this._colorUnmodified = color3; - this._changeTextureColor(); - }; - - proto._changeTextureColor = function(){ - var node = this._node; - var texture = node._texture, - color = this._colorUnmodified, - element = texture.getHtmlElementObj(); - var textureRect = cc.rect(0, 0, element.width, element.height); - if(texture === this._textureToRender) - this._textureToRender = texture._generateColorTexture(color.r, color.g, color.b, textureRect); - else - texture._generateColorTexture(color.r, color.g, color.b, textureRect, this._textureToRender.getHtmlElementObj()); - }; - - proto.setOpacity = function(opacity){ - var node = this._node; - cc.Node.prototype.setOpacity.call(node, opacity); - }; - - proto._calculateMaxItems = function(){ - var node = this._node; - var selTexture = node._texture; - var size = selTexture.getContentSize(); - - node._itemsPerColumn = 0 | (size.height / node._itemHeight); - node._itemsPerRow = 0 | (size.width / node._itemWidth); - }; -})(); diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index eeb788535e..e93ac9fe9d 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -2438,9 +2438,6 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ }, _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) - return new cc.Node.CanvasRenderCmd(this); - else return new cc.Node.WebGLRenderCmd(this); }, diff --git a/cocos2d/core/labelttf/CCLabelTTF.js b/cocos2d/core/labelttf/CCLabelTTF.js index 4e1756e9ad..ee9ef951c7 100644 --- a/cocos2d/core/labelttf/CCLabelTTF.js +++ b/cocos2d/core/labelttf/CCLabelTTF.js @@ -752,8 +752,6 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ return new cc.LabelTTF.WebGLRenderCmd(this); else if (this._onCacheCanvasMode) return new cc.LabelTTF.CacheCanvasRenderCmd(this); - else - return new cc.LabelTTF.CanvasRenderCmd(this); }, //For web only diff --git a/cocos2d/core/layers/CCLayer.js b/cocos2d/core/layers/CCLayer.js index e9457535a6..6dfbc08c7a 100644 --- a/cocos2d/core/layers/CCLayer.js +++ b/cocos2d/core/layers/CCLayer.js @@ -92,9 +92,6 @@ cc.Layer = cc.Node.extend(/** @lends cc.Layer# */{ }, _createRenderCmd: function(){ - if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) - return new cc.Layer.CanvasRenderCmd(this); - else return new cc.Layer.WebGLRenderCmd(this); } }); @@ -255,9 +252,6 @@ cc.LayerColor = cc.Layer.extend(/** @lends cc.LayerColor# */{ }, _createRenderCmd: function(){ - if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) - return new cc.LayerColor.CanvasRenderCmd(this); - else return new cc.LayerColor.WebGLRenderCmd(this); } }); @@ -574,9 +568,6 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{ }, _createRenderCmd: function(){ - if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) - return new cc.LayerGradient.CanvasRenderCmd(this); - else return new cc.LayerGradient.WebGLRenderCmd(this); } }); diff --git a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js index 7ae79ca588..e69de29bb2 100644 --- a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js +++ b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js @@ -1,458 +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. - ****************************************************************************/ - -//-----------------------// -// 1. cc.Layer // -// 2. cc.LayerColor // -// 3. cc.LayerGradient // -//-----------------------// - -/** - * cc.Layer's rendering objects of Canvas - */ -(function(){ - //Layer's canvas render command - cc.Layer.CanvasRenderCmd = function(renderable){ - cc.Node.CanvasRenderCmd.call(this, renderable); - this._isBaked = false; - this._bakeSprite = null; - this._updateCache = 2; // 2: Updated child visit 1: Rendering 0: Nothing to do - }; - - var proto = cc.Layer.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); - proto.constructor = cc.Layer.CanvasRenderCmd; - - proto._setCacheDirty = function(child){ - if(child && this._updateCache === 0) - this._updateCache = 2; - if (this._cacheDirty === false) { - this._cacheDirty = true; - var cachedP = this._cachedParent; - cachedP && cachedP !== this && cachedP._setNodeDirtyForCache && cachedP._setNodeDirtyForCache(); - } - }; - - proto.updateStatus = function () { - var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag; - if (locFlag & flags.orderDirty) { - this._cacheDirty = true; - if(this._updateCache === 0) - this._updateCache = 2; - this._dirtyFlag = this._dirtyFlag & flags.orderDirty ^ this._dirtyFlag; - } - - cc.Node.RenderCmd.prototype.updateStatus.call(this); - }; - - proto._syncStatus = function (parentCmd) { - var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag; - if (locFlag & flags.orderDirty) { - this._cacheDirty = true; - if(this._updateCache === 0) - this._updateCache = 2; - this._dirtyFlag = this._dirtyFlag & flags.orderDirty ^ this._dirtyFlag; - } - cc.Node.RenderCmd.prototype._syncStatus.call(this, parentCmd); - }; - - proto.transform = function (parentCmd, recursive) { - var wt = this._worldTransform; - var a = wt.a, b = wt.b, c = wt.c, d = wt.d, tx = wt.tx, ty = wt.ty; - cc.Node.CanvasRenderCmd.prototype.transform.call(this, parentCmd, recursive); - if(( wt.a !== a || wt.b !== b || wt.c !== c || wt.d !== d ) && this._updateCache === 0) - this._updateCache = 2; - }; - - proto.bake = function(){ - if (!this._isBaked) { - this._needDraw = true; - cc.renderer.childrenOrderDirty = true; - //limit: 1. its children's blendfunc are invalid. - this._isBaked = this._cacheDirty = true; - if(this._updateCache === 0) - this._updateCache = 2; - - var children = this._node._children; - for(var i = 0, len = children.length; i < len; i++) - children[i]._renderCmd._setCachedParent(this); - - if (!this._bakeSprite){ - this._bakeSprite = new cc.BakeSprite(); - this._bakeSprite.setAnchorPoint(0,0); - } - } - }; - - proto.unbake = function(){ - if (this._isBaked) { - cc.renderer.childrenOrderDirty = true; - this._needDraw = false; - this._isBaked = false; - this._cacheDirty = true; - if(this._updateCache === 0) - this._updateCache = 2; - - var children = this._node._children; - for(var i = 0, len = children.length; i < len; i++) - children[i]._renderCmd._setCachedParent(null); - } - }; - - proto.isBaked = function(){ - return this._isBaked; - }; - - proto.rendering = function(){ - if(this._cacheDirty){ - var node = this._node; - var children = node._children, locBakeSprite = this._bakeSprite; - - //compute the bounding box of the bake layer. - this.transform(this.getParentRenderCmd(), true); - - var boundingBox = this._getBoundingBoxForBake(); - boundingBox.width = 0|(boundingBox.width+0.5); - boundingBox.height = 0|(boundingBox.height+0.5); - - var bakeContext = locBakeSprite.getCacheContext(); - var ctx = bakeContext.getContext(); - - locBakeSprite.setPosition(boundingBox.x, boundingBox.y); - - if(this._updateCache > 0){ - locBakeSprite.resetCanvasSize(boundingBox.width, boundingBox.height); - bakeContext.setOffset(0 - boundingBox.x, ctx.canvas.height - boundingBox.height + boundingBox.y ); - //visit for canvas - node.sortAllChildren(); - cc.renderer._turnToCacheMode(this.__instanceId); - for (var i = 0, len = children.length; i < len; i++) { - children[i].visit(this); - } - cc.renderer._renderingToCacheCanvas(bakeContext, this.__instanceId); - locBakeSprite.transform(); //because bake sprite's position was changed at rendering. - this._updateCache--; - } - - this._cacheDirty = false; - } - }; - - proto.visit = function(parentCmd){ - if(!this._isBaked){ - cc.Node.CanvasRenderCmd.prototype.visit.call(this, parentCmd); - return; - } - - var node = this._node, children = node._children; - var len = children.length; - // quick return if not visible - if (!node._visible || len === 0) - return; - - this._syncStatus(parentCmd); - cc.renderer.pushRenderCommand(this); - - //the bakeSprite is drawing - this._bakeSprite.visit(this); - this._dirtyFlag = 0; - }; - - proto._bakeForAddChild = function(child){ - if(child._parent === this._node && this._isBaked) - child._renderCmd._setCachedParent(this); - }; - - proto._getBoundingBoxForBake = function(){ - var rect = null, node = this._node; - - //query child's BoundingBox - if (!node._children || node._children.length === 0) - return cc.rect(0, 0, 10, 10); - var trans = node.getNodeToWorldTransform(); - - var locChildren = node._children; - for (var i = 0, len = locChildren.length; i < len; i++) { - var child = locChildren[i]; - if (child && child._visible) { - if(rect){ - var childRect = child._getBoundingBoxToCurrentNode(trans); - if (childRect) - rect = cc.rectUnion(rect, childRect); - }else{ - rect = child._getBoundingBoxToCurrentNode(trans); - } - } - } - return rect; - }; -})(); - -/** - * cc.LayerColor's rendering objects of Canvas - */ -(function(){ - //LayerColor's canvas render command - cc.LayerColor.CanvasRenderCmd = function(renderable){ - cc.Layer.CanvasRenderCmd.call(this, renderable); - this._needDraw = true; - this._blendFuncStr = "source-over"; - this._bakeRenderCmd = new cc.CustomRenderCmd(this, this._bakeRendering); - }; - var proto = cc.LayerColor.CanvasRenderCmd.prototype = Object.create(cc.Layer.CanvasRenderCmd.prototype); - proto.constructor = cc.LayerColor.CanvasRenderCmd; - - proto.unbake = function(){ - cc.Layer.CanvasRenderCmd.prototype.unbake.call(this); - this._needDraw = true; - }; - - proto.rendering = function (ctx, scaleX, scaleY) { - var wrapper = ctx || cc._renderContext, context = wrapper.getContext(), - node = this._node, - curColor = this._displayedColor, - opacity = this._displayedOpacity / 255, - locWidth = node._contentSize.width, - locHeight = node._contentSize.height; - - if (opacity === 0) - return; - - wrapper.setCompositeOperation(this._blendFuncStr); - wrapper.setGlobalAlpha(opacity); - wrapper.setFillStyle("rgba(" + (0 | curColor.r) + "," + (0 | curColor.g) + "," - + (0 | curColor.b) + ", 1)"); //TODO: need cache the color string - - wrapper.setTransform(this._worldTransform, scaleX, scaleY); - context.fillRect(0, 0, locWidth * scaleX, -locHeight * scaleY); - - cc.g_NumberOfDraws++; - }; - - proto.updateBlendFunc = function(blendFunc){ - this._blendFuncStr = cc.Node.CanvasRenderCmd._getCompositeOperationByBlendFunc(blendFunc); - }; - - proto._updateSquareVertices = - proto._updateSquareVerticesWidth = - proto._updateSquareVerticesHeight = function(){}; - - proto._bakeRendering = function(){ - if(this._cacheDirty){ - var node = this._node; - var locBakeSprite = this._bakeSprite, children = node._children; - var len = children.length, i; - - //compute the bounding box of the bake layer. - this.transform(this.getParentRenderCmd(), true); - //compute the bounding box of the bake layer. - var boundingBox = this._getBoundingBoxForBake(); - boundingBox.width = 0|(boundingBox.width+0.5); - boundingBox.height = 0|(boundingBox.height+0.5); - - var bakeContext = locBakeSprite.getCacheContext(); - var ctx = bakeContext.getContext(); - - locBakeSprite.setPosition(boundingBox.x, boundingBox.y); - - if(this._updateCache > 0) { - ctx.fillStyle = bakeContext._currentFillStyle; - locBakeSprite.resetCanvasSize(boundingBox.width, boundingBox.height); - bakeContext.setOffset(0 - boundingBox.x, ctx.canvas.height - boundingBox.height + boundingBox.y ); - - var child; - cc.renderer._turnToCacheMode(this.__instanceId); - //visit for canvas - if (len > 0) { - node.sortAllChildren(); - // draw children zOrder < 0 - for (i = 0; i < len; i++) { - child = children[i]; - if (child._localZOrder < 0) - child._renderCmd.visit(this); - else - break; - } - cc.renderer.pushRenderCommand(this); - for (; i < len; i++) { - children[i]._renderCmd.visit(this); - } - } else - cc.renderer.pushRenderCommand(this); - cc.renderer._renderingToCacheCanvas(bakeContext, this.__instanceId); - locBakeSprite.transform(); - this._updateCache--; - } - this._cacheDirty = false; - } - }; - - proto.visit = function(parentCmd){ - if(!this._isBaked){ - cc.Node.CanvasRenderCmd.prototype.visit.call(this); - return; - } - - var node = this._node; - // quick return if not visible - if (!node._visible) - return; - - this._syncStatus(parentCmd); - - cc.renderer.pushRenderCommand(this._bakeRenderCmd); - - //the bakeSprite is drawing - this._bakeSprite._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty); - this._bakeSprite.visit(this); - this._dirtyFlag = 0; - }; - - proto._getBoundingBoxForBake = function(){ - var node = this._node; - //default size - var rect = cc.rect(0, 0, node._contentSize.width, node._contentSize.height); - var trans = node.getNodeToWorldTransform(); - rect = cc.rectApplyAffineTransform(rect, node.getNodeToWorldTransform()); - - //query child's BoundingBox - if (!node._children || node._children.length === 0) - return rect; - - var locChildren = node._children; - for (var i = 0; i < locChildren.length; i++) { - var child = locChildren[i]; - if (child && child._visible) { - var childRect = child._getBoundingBoxToCurrentNode(trans); - rect = cc.rectUnion(rect, childRect); - } - } - return rect; - }; -})(); - -/** - * cc.LayerGradient's rendering objects of Canvas - */ -(function(){ - cc.LayerGradient.RenderCmd = { - updateStatus: function () { - var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag; - if (locFlag & flags.gradientDirty) { - this._dirtyFlag |= flags.colorDirty; - this._dirtyFlag = this._dirtyFlag & flags.gradientDirty ^ this._dirtyFlag; - } - - cc.Node.RenderCmd.prototype.updateStatus.call(this); - } - }; - - cc.LayerGradient.CanvasRenderCmd = function(renderable){ - cc.LayerColor.CanvasRenderCmd.call(this, renderable); - this._needDraw = true; - this._startPoint = cc.p(0, 0); - this._endPoint = cc.p(0, 0); - this._startStopStr = null; - this._endStopStr = null; - }; - var proto = cc.LayerGradient.CanvasRenderCmd.prototype = Object.create(cc.LayerColor.CanvasRenderCmd.prototype); - cc.inject(cc.LayerGradient.RenderCmd, proto); - proto.constructor = cc.LayerGradient.CanvasRenderCmd; - - proto.rendering = function (ctx, scaleX, scaleY) { - var wrapper = ctx || cc._renderContext, context = wrapper.getContext(), - node = this._node, - opacity = this._displayedOpacity / 255; - - if (opacity === 0) - return; - - var locWidth = node._contentSize.width, locHeight = node._contentSize.height; - wrapper.setCompositeOperation(this._blendFuncStr); - wrapper.setGlobalAlpha(opacity); - 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); - context.fillRect(0, 0, locWidth * scaleX, -locHeight * scaleY); - cc.g_NumberOfDraws++; - }; - - proto._syncStatus = function (parentCmd) { - var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag; - if (locFlag & flags.gradientDirty) { - this._dirtyFlag |= flags.colorDirty; - this._dirtyFlag = locFlag & flags.gradientDirty ^ locFlag; - } - - cc.Node.RenderCmd.prototype._syncStatus.call(this, parentCmd); - }; - - proto._updateColor = function(){ - var node = this._node; - var contentSize = node._contentSize; - var tWidth = contentSize.width * 0.5, tHeight = contentSize.height * 0.5; - this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.gradientDirty ^ this._dirtyFlag; - - //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; - this._startStopStr = "rgba(" + Math.round(locStartColor.r) + "," + Math.round(locStartColor.g) + "," - + 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 == null ? 1 : 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 diff --git a/cocos2d/core/sprites/CCSpriteBatchNode.js b/cocos2d/core/sprites/CCSpriteBatchNode.js index 5bbfd89784..36569a6b24 100644 --- a/cocos2d/core/sprites/CCSpriteBatchNode.js +++ b/cocos2d/core/sprites/CCSpriteBatchNode.js @@ -627,9 +627,7 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{ }, _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) - return new cc.SpriteBatchNode.CanvasRenderCmd(this); - else + return new cc.SpriteBatchNode.WebGLRenderCmd(this); } }); diff --git a/cocos2d/core/sprites/CCSpriteBatchNodeCanvasRenderCmd.js b/cocos2d/core/sprites/CCSpriteBatchNodeCanvasRenderCmd.js index facfbb0277..e69de29bb2 100644 --- a/cocos2d/core/sprites/CCSpriteBatchNodeCanvasRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteBatchNodeCanvasRenderCmd.js @@ -1,100 +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. - ****************************************************************************/ - -(function(){ - //SpriteBatchNode's canvas render command - cc.SpriteBatchNode.CanvasRenderCmd = function(renderable){ - cc.Node.CanvasRenderCmd.call(this, renderable); - - this._texture = null; - this._textureToRender = null; - }; - - var proto = cc.SpriteBatchNode.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); - proto.constructor = cc.SpriteBatchNode.CanvasRenderCmd; - - proto.checkAtlasCapacity = function(){}; - - proto.isValidChild = function(child){ - if (!(child instanceof cc.Sprite)) { - cc.log(cc._LogInfos.Sprite_addChild_4); - return false; - } - return true; - }; - - proto.initWithTexture = function(texture, capacity){ - this._textureToRender = this._texture = texture; - }; - - proto.insertQuad = function(sprite, index){}; - - proto.increaseAtlasCapacity = function(){}; - - proto.removeQuadAtIndex = function(){}; - - proto.removeAllQuads = function(){}; - - proto.getTexture = function(){ - return this._texture; - }; - - proto.setTexture = function(texture){ - this._texture = texture; - var locChildren = this._node._children; - for (var i = 0; i < locChildren.length; i++) - locChildren[i].setTexture(texture); - }; - - proto.updateChildrenAtlasIndex = function(children){ - this._node._descendants.length = 0; - //update _descendants after sortAllChildren - for (var i = 0, len = children.length; i < len; i++) - this._updateAtlasIndex(children[i]); - }; - - proto._updateAtlasIndex = function (sprite) { - var locDescendants = this._node._descendants; - var pArray = sprite.children, i, len = pArray.length; - for (i = 0; i < len; i++) { - if (pArray[i]._localZOrder < 0) { - locDescendants.push(pArray[i]); - } else - break - } - locDescendants.push(sprite); - for (; i < len; i++) { - locDescendants.push(pArray[i]); - } - }; - - proto.getTextureAtlas = function(){}; - - proto.setTextureAtlas = function(textureAtlas){}; - - proto.cutting = function(sprite, index){ - var node = this._node; - node._children.splice(index, 0, sprite); - } -})(); \ No newline at end of file diff --git a/cocos2d/core/sprites/CCSpriteFrameCache.js b/cocos2d/core/sprites/CCSpriteFrameCache.js index 6152c54b23..5aa7a3e508 100644 --- a/cocos2d/core/sprites/CCSpriteFrameCache.js +++ b/cocos2d/core/sprites/CCSpriteFrameCache.js @@ -179,22 +179,7 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{ spAliases[alias] = key; } } - - if (cc._renderType === cc.game.RENDER_TYPE_CANVAS && spriteFrame.isRotated()) { - //clip to canvas - var locTexture = spriteFrame.getTexture(); - if (locTexture.isLoaded()) { - var tempElement = spriteFrame.getTexture().getHtmlElementObj(); - tempElement = cc.Sprite.CanvasRenderCmd._cutRotateImageToCanvas(tempElement, spriteFrame.getRectInPixels()); - var tempTexture = new cc.Texture2D(); - tempTexture.initWithElement(tempElement); - tempTexture.handleLoadedTexture(); - spriteFrame.setTexture(tempTexture); - - var rect = spriteFrame._rect; - spriteFrame.setRect(cc.rect(0, 0, rect.width, rect.height)); - } - } + spriteFrames[key] = spriteFrame; } } diff --git a/cocos2d/labels/CCLabelAtlas.js b/cocos2d/labels/CCLabelAtlas.js index 2b8c06178f..f2dd4affd9 100644 --- a/cocos2d/labels/CCLabelAtlas.js +++ b/cocos2d/labels/CCLabelAtlas.js @@ -75,10 +75,7 @@ cc.LabelAtlas = cc.AtlasNode.extend(/** @lends cc.LabelAtlas# */{ }, _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_WEBGL) return new cc.LabelAtlas.WebGLRenderCmd(this); - else - return new cc.LabelAtlas.CanvasRenderCmd(this); }, /** diff --git a/cocos2d/labels/CCLabelAtlasCanvasRenderCmd.js b/cocos2d/labels/CCLabelAtlasCanvasRenderCmd.js index 890c98be25..e69de29bb2 100644 --- a/cocos2d/labels/CCLabelAtlasCanvasRenderCmd.js +++ b/cocos2d/labels/CCLabelAtlasCanvasRenderCmd.js @@ -1,110 +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. - ****************************************************************************/ - -(function(){ - cc.LabelAtlas.CanvasRenderCmd = function(renderableObject){ - cc.AtlasNode.CanvasRenderCmd.call(this, renderableObject); - this._needDraw = false; - }; - - var proto = cc.LabelAtlas.CanvasRenderCmd.prototype = Object.create(cc.AtlasNode.CanvasRenderCmd.prototype); - proto.constructor = cc.LabelAtlas.CanvasRenderCmd; - - proto.setCascade = function(){ - var node = this._node; - node._cascadeOpacityEnabled = true; - node._cascadeColorEnabled = false; - }; - - proto.updateAtlasValues = function(){ - var node = this._node; - var locString = node._string || ""; - var n = locString.length; - var texture = this._textureToRender; - var locItemWidth = node._itemWidth , locItemHeight = node._itemHeight; //needn't multiply cc.contentScaleFactor(), because sprite's draw will do this - - for (var i = 0, cr = -1; i < n; i++) { - var a = locString.charCodeAt(i) - node._mapStartChar.charCodeAt(0); - var row = parseInt(a % node._itemsPerRow, 10); - var col = parseInt(a / node._itemsPerRow, 10); - if(row < 0 || col < 0) - continue; - var rect = cc.rect(row * locItemWidth, col * locItemHeight, locItemWidth, locItemHeight); - var textureContent = texture._contentSize; - if(rect.x < 0 || rect.y < 0 || rect.x + rect.width > textureContent.width || rect.y + rect.height > textureContent.height) - continue; - - cr++; - var c = locString.charCodeAt(i); - var fontChar = node.getChildByTag(i); - if (!fontChar) { - fontChar = new cc.Sprite(); - if (c === 32) { - fontChar.init(); - fontChar.setTextureRect(cc.rect(0, 0, 10, 10), false, cc.size(0, 0)); - } else - fontChar.initWithTexture(texture, rect); - - cc.Node.prototype.addChild.call(node, fontChar, 0, i); - } else { - if (c === 32) { - fontChar.init(); - fontChar.setTextureRect(cc.rect(0, 0, 10, 10), false, cc.size(0, 0)); - } else { - // reusing fonts - fontChar.initWithTexture(texture, rect); - // restore to default in case they were modified - fontChar.visible = true; - } - } - fontChar.setPosition(cr * locItemWidth + locItemWidth / 2, locItemHeight / 2); - } - this.updateContentSize(i, cr+1); - }; - - proto.updateContentSize = function(i, cr){ - var node = this._node, - contentSize = node._contentSize; - if(i !== cr && i*node._itemWidth === contentSize.width && node._itemHeight === contentSize.height){ - node.setContentSize(cr * node._itemWidth, node._itemHeight); - } - }; - - proto.setString = function(label){ - var node = this._node; - if (node._children) { - var locChildren = node._children; - var len = locChildren.length; - for (var i = 0; i < len; i++) { - var child = locChildren[i]; - if (child && !child._lateChild) - child.visible = false; - } - } - }; - - proto._addChild = function(){ - child._lateChild = true; - }; -})(); \ No newline at end of file diff --git a/cocos2d/labels/CCLabelBMFont.js b/cocos2d/labels/CCLabelBMFont.js index 474eb0067a..46e386ce6f 100644 --- a/cocos2d/labels/CCLabelBMFont.js +++ b/cocos2d/labels/CCLabelBMFont.js @@ -114,10 +114,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ _className: "LabelBMFont", _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_WEBGL) return new cc.LabelBMFont.WebGLRenderCmd(this); - else - return new cc.LabelBMFont.CanvasRenderCmd(this); }, _setString: function (newString, needUpdateLabel) { @@ -207,7 +204,8 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ }, /** - * Initialization of the node, please do not call this function by yourself, you should pass the parameters to constructor to initialize it
. + * Initialization of the node, please do not call this function by yourself, you should pass the parameters to constructor to initialize it +. */ init: function () { return this.initWithString(null, null, null, null, null); diff --git a/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js b/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js index 1d43842993..e69de29bb2 100644 --- a/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js +++ b/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js @@ -1,107 +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. - - Use any of these editors to generate BMFonts: - http://glyphdesigner.71squared.com/ (Commercial, Mac OS X) - http://www.n4te.com/hiero/hiero.jnlp (Free, Java) - http://slick.cokeandcode.com/demos/hiero.jnlp (Free, Java) - http://www.angelcode.com/products/bmfont/ (Free, Windows only) - ****************************************************************************/ - -(function(){ - cc.LabelBMFont.CanvasRenderCmd = function(renderableObject){ - cc.SpriteBatchNode.CanvasRenderCmd.call(this, renderableObject); - this._needDraw = true; - }; - - var proto = cc.LabelBMFont.CanvasRenderCmd.prototype = Object.create(cc.SpriteBatchNode.CanvasRenderCmd.prototype); - proto.constructor = cc.LabelBMFont.CanvasRenderCmd; - - proto.rendering = function(){ - void 0; - }; - - proto._updateCharTexture = function(fontChar, rect, key){ - if (key === 32) { - fontChar.setTextureRect(rect, false, cc.size(0, 0)); - } else { - // updating previous sprite - fontChar.setTextureRect(rect, false); - // restore to default in case they were modified - fontChar.visible = true; - } - }; - - proto._updateCharColorAndOpacity = function(fontChar){ - // Color MUST be set before opacity, since opacity might change color if OpacityModifyRGB is on - fontChar._displayedColor = this._displayedColor; - fontChar._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty); - fontChar._displayedOpacity = this._displayedOpacity; - fontChar._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.opacityDirty); - }; - - proto.setTexture = function (texture) { - var node = this._node; - var locChildren = node._children; - var locDisplayedColor = this._displayedColor; - for (var i = 0; i < locChildren.length; i++) { - var selChild = locChildren[i]; - var cm = selChild._renderCmd; - var childDColor = cm._displayedColor; - if (this._texture !== cm._texture && (childDColor.r !== locDisplayedColor.r || - childDColor.g !== locDisplayedColor.g || childDColor.b !== locDisplayedColor.b)) - continue; - selChild.texture = texture; - } - this._texture = texture; - }; - - proto._changeTextureColor = function(){ - var node = this._node; - var texture = this._textureToRender, - contentSize = texture.getContentSize(); - - var oTexture = node._texture, - oElement = oTexture.getHtmlElementObj(); - var disColor = this._displayedColor; - var textureRect = cc.rect(0, 0, oElement.width, oElement.height); - if(texture && contentSize.width > 0){ - if(!oElement) - return; - this._textureToRender = oTexture._generateColorTexture(disColor.r, disColor.g, disColor.b, textureRect); - } - }; - - proto._updateChildrenDisplayedOpacity = function(locChild){ - cc.Node.prototype.updateDisplayedOpacity.call(locChild, this._displayedOpacity); - }; - - proto._updateChildrenDisplayedColor = function(locChild){ - cc.Node.prototype.updateDisplayedColor.call(locChild, this._displayedColor); - }; - - proto._initBatchTexture = function(){}; - -})(); \ No newline at end of file diff --git a/cocos2d/node-grid/CCNodeGrid.js b/cocos2d/node-grid/CCNodeGrid.js index f1cb9b4658..fa3199fa16 100644 --- a/cocos2d/node-grid/CCNodeGrid.js +++ b/cocos2d/node-grid/CCNodeGrid.js @@ -123,10 +123,7 @@ cc.NodeGrid = cc.Node.extend({ }, _createRenderCmd: function(){ - if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) return new cc.NodeGrid.WebGLRenderCmd(this); - else - return new cc.Node.CanvasRenderCmd(this); // cc.NodeGrid doesn't support Canvas mode. } }); diff --git a/cocos2d/parallax/CCParallaxNode.js b/cocos2d/parallax/CCParallaxNode.js index a994709bc2..2b0a759984 100644 --- a/cocos2d/parallax/CCParallaxNode.js +++ b/cocos2d/parallax/CCParallaxNode.js @@ -232,9 +232,6 @@ cc.ParallaxNode = cc.Node.extend(/** @lends cc.ParallaxNode# */{ }, _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) - return new cc.ParallaxNode.CanvasRenderCmd(this); - else return new cc.ParallaxNode.WebGLRenderCmd(this); } }); diff --git a/cocos2d/parallax/CCParallaxNodeRenderCmd.js b/cocos2d/parallax/CCParallaxNodeRenderCmd.js index 8a248b737e..de092928fb 100644 --- a/cocos2d/parallax/CCParallaxNodeRenderCmd.js +++ b/cocos2d/parallax/CCParallaxNodeRenderCmd.js @@ -24,25 +24,6 @@ //TODO find a way to simple these code. -(function(){ - cc.ParallaxNode.CanvasRenderCmd = function(renderable){ - cc.Node.CanvasRenderCmd.call(this, renderable); - this._needDraw = false; - }; - - var proto = cc.ParallaxNode.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); - proto.constructor = cc.ParallaxNode.CanvasRenderCmd; - - proto.updateStatus = function(){ - this._node._updateParallaxPosition(); - cc.Node.CanvasRenderCmd.prototype.updateStatus.call(this); - }; - - proto._syncStatus = function(parentCmd){ - this._node._updateParallaxPosition(); - cc.Node.CanvasRenderCmd.prototype._syncStatus.call(this, parentCmd); - } -})(); cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { if(cc._renderType !== cc.game.RENDER_TYPE_WEBGL) diff --git a/cocos2d/particle/CCParticleBatchNode.js b/cocos2d/particle/CCParticleBatchNode.js index 1c786386fc..a61ecb2c84 100644 --- a/cocos2d/particle/CCParticleBatchNode.js +++ b/cocos2d/particle/CCParticleBatchNode.js @@ -102,9 +102,6 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ }, _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) - return new cc.ParticleBatchNode.CanvasRenderCmd(this); - else return new cc.ParticleBatchNode.WebGLRenderCmd(this); }, diff --git a/cocos2d/particle/CCParticleBatchNodeCanvasRenderCmd.js b/cocos2d/particle/CCParticleBatchNodeCanvasRenderCmd.js index 36da185ecb..e69de29bb2 100644 --- a/cocos2d/particle/CCParticleBatchNodeCanvasRenderCmd.js +++ b/cocos2d/particle/CCParticleBatchNodeCanvasRenderCmd.js @@ -1,38 +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. - ****************************************************************************/ - -(function(){ - /** - * cc.ParticleBatchNode's rendering objects of Canvas - */ - cc.ParticleBatchNode.CanvasRenderCmd = function(renderable){ - cc.Node.CanvasRenderCmd.call(this, renderable); - this._needDraw = false; - }; - - var proto = cc.ParticleBatchNode.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); - proto.constructor = cc.ParticleBatchNode.CanvasRenderCmd; - - proto._initWithTexture = function(){}; -})(); diff --git a/cocos2d/particle/CCParticleSystem.js b/cocos2d/particle/CCParticleSystem.js index f12686d03d..ee1bc8cf67 100644 --- a/cocos2d/particle/CCParticleSystem.js +++ b/cocos2d/particle/CCParticleSystem.js @@ -349,9 +349,6 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ }, _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) - return new cc.ParticleSystem.CanvasRenderCmd(this); - else return new cc.ParticleSystem.WebGLRenderCmd(this); }, diff --git a/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js b/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js index de78252346..e69de29bb2 100644 --- a/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js +++ b/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js @@ -1,199 +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. - ****************************************************************************/ - -/** - * ParticleSystem's canvas render command - */ -(function(){ - cc.ParticleSystem.CanvasRenderCmd = function(renderable){ - cc.Node.CanvasRenderCmd.call(this, renderable); - this._needDraw = true; - - this._drawMode = cc.ParticleSystem.TEXTURE_MODE; - this._shapeType = cc.ParticleSystem.BALL_SHAPE; - - this._pointRect = cc.rect(0, 0, 0, 0); - this._tintCache = document.createElement("canvas"); - }; - var proto = cc.ParticleSystem.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); - proto.constructor = cc.ParticleSystem.CanvasRenderCmd; - - proto.getDrawMode = function(){ - return this._drawMode; - }; - - proto.setDrawMode = function(drawMode){ - this._drawMode = drawMode; - }; - - proto.getShapeType = function(){ - return this._shapeType; - }; - - proto.setShapeType = function(shapeType){ - this._shapeType = shapeType; - }; - - proto.setBatchNode = function(batchNode){ - if (this._batchNode !== batchNode) { - this._node._batchNode = batchNode; - } - }; - - proto.updateQuadWithParticle = function (particle, newPosition) { - //do nothing - }; - - proto.updateParticlePosition = function(particle, position){ - cc.pIn(particle.drawPos, position); - }; - - proto.rendering = function (ctx, scaleX, scaleY) { - //TODO: need refactor rendering for performance - var wrapper = ctx || cc._renderContext, context = wrapper.getContext(), - node = this._node, pointRect = this._pointRect; - - wrapper.setTransform(this._worldTransform, scaleX, scaleY); - wrapper.save(); - if (node.isBlendAdditive()) - context.globalCompositeOperation = 'lighter'; - else - context.globalCompositeOperation = 'source-over'; - - var i, particle, lpx, alpha; - var particleCount = this._node.particleCount, particles = this._node._particles; - if (node.drawMode !== cc.ParticleSystem.SHAPE_MODE && node._texture) { - // Delay drawing until the texture is fully loaded by the browser - if (!node._texture._textureLoaded) { - wrapper.restore(); - return; - } - var element = node._texture.getHtmlElementObj(); - if (!element.width || !element.height) { - wrapper.restore(); - return; - } - - var drawElement = element; - for (i = 0; i < particleCount; i++) { - particle = particles[i]; - lpx = (0 | (particle.size * 0.5)); - - alpha = particle.color.a / 255; - if (alpha === 0) continue; - context.globalAlpha = alpha; - - context.save(); - context.translate((0 | particle.drawPos.x), -(0 | particle.drawPos.y)); - - var size = Math.floor(particle.size / 4) * 4; - var w = pointRect.width; - var h = pointRect.height; - - context.scale(Math.max((1 / w) * size, 0.000001), Math.max((1 / h) * size, 0.000001)); - if (particle.rotation) - context.rotate(cc.degreesToRadians(particle.rotation)); - - drawElement = particle.isChangeColor ? this._changeTextureColor(node._texture, particle.color, this._pointRect) : element; - context.drawImage(drawElement, -(0 | (w / 2)), -(0 | (h / 2))); - context.restore(); - } - } else { - var drawTool = cc._drawingUtil; - for (i = 0; i < particleCount; i++) { - particle = particles[i]; - lpx = (0 | (particle.size * 0.5)); - alpha = particle.color.a / 255; - if (alpha === 0) continue; - context.globalAlpha = alpha; - - context.save(); - context.translate(0 | particle.drawPos.x, -(0 | particle.drawPos.y)); - if (node.shapeType === cc.ParticleSystem.STAR_SHAPE) { - if (particle.rotation) - context.rotate(cc.degreesToRadians(particle.rotation)); - drawTool.drawStar(wrapper, lpx, particle.color); - } else - drawTool.drawColorBall(wrapper, lpx, particle.color); - context.restore(); - } - } - wrapper.restore(); - cc.g_NumberOfDraws++; - }; - - proto._changeTextureColor = function(texture, color, rect){ - var tintCache = this._tintCache; - var textureContentSize = texture.getContentSize(); - tintCache.width = textureContentSize.width; - tintCache.height = textureContentSize.height; - return texture._generateColorTexture(color.r, color.g, color.b, rect, tintCache); - }; - - proto.initTexCoordsWithRect = function(pointRect){ - this._pointRect = pointRect; - }; - - proto.setTotalParticles = function(tp){ - //cc.assert(tp <= this._allocatedParticles, "Particle: resizing particle array only supported for quads"); - this._node._totalParticles = (tp < 200) ? tp : 200; - }; - - proto.addParticle = function(){ - var node = this._node, - particles = node._particles, - particle; - if (node.particleCount < particles.length) { - particle = particles[node.particleCount]; - } else { - particle = new cc.Particle(); - particles.push(particle); - } - return particle; - }; - - proto._setupVBO = function(){}; - proto._allocMemory = function(){ - return true; - }; - - proto.postStep = function(){}; - - proto._setBlendAdditive = function(){ - var locBlendFunc = this._node._blendFunc; - locBlendFunc.src = cc.BLEND_SRC; - locBlendFunc.dst = cc.BLEND_DST; - }; - - proto._initWithTotalParticles = function(totalParticles){}; - proto._updateDeltaColor = function(selParticle, dt){ - if (!this._node._dontTint) { - selParticle.color.r += selParticle.deltaColor.r * dt; - selParticle.color.g += selParticle.deltaColor.g * dt; - selParticle.color.b += selParticle.deltaColor.b * dt; - selParticle.color.a += selParticle.deltaColor.a * dt; - selParticle.isChangeColor = true; - } - }; -})(); diff --git a/cocos2d/physics/CCPhysicsDebugNode.js b/cocos2d/physics/CCPhysicsDebugNode.js index 003bfe3f74..2f3e7291ae 100644 --- a/cocos2d/physics/CCPhysicsDebugNode.js +++ b/cocos2d/physics/CCPhysicsDebugNode.js @@ -194,9 +194,6 @@ cc.PhysicsDebugNode = cc.DrawNode.extend({ }, _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) - return new cc.PhysicsDebugNode.CanvasRenderCmd(this); - else return new cc.PhysicsDebugNode.WebGLRenderCmd(this); } }); diff --git a/cocos2d/physics/CCPhysicsDebugNodeCanvasRenderCmd.js b/cocos2d/physics/CCPhysicsDebugNodeCanvasRenderCmd.js index be1f6f14ba..e69de29bb2 100644 --- a/cocos2d/physics/CCPhysicsDebugNodeCanvasRenderCmd.js +++ b/cocos2d/physics/CCPhysicsDebugNodeCanvasRenderCmd.js @@ -1,52 +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. - ****************************************************************************/ - -/** - * cc.PhysicsDebugNode's rendering objects of Canvas - */ -(function(){ - cc.PhysicsDebugNode.CanvasRenderCmd = function(renderableObject){ - cc.Node.CanvasRenderCmd.call(this, renderableObject); - this._buffer = renderableObject._buffer; - this._needDraw = true; - }; - - var proto = cc.PhysicsDebugNode.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); - proto.constructor = cc.PhysicsDebugNode.CanvasRenderCmd; - - proto.rendering = function(ctx, scaleX, scaleY){ - var node = this._node; - if (!node._space) - return; - node._space.eachShape(cc.DrawShape.bind(node)); - node._space.eachConstraint(cc.DrawConstraint.bind(node)); - cc.DrawNode.CanvasRenderCmd.prototype.rendering.call(this, ctx, scaleX, scaleY); - node.clear(); - }; - - proto._drawDot = cc.DrawNode.CanvasRenderCmd.prototype._drawDot; - proto._drawSegment = cc.DrawNode.CanvasRenderCmd.prototype._drawSegment; - proto._drawPoly = cc.DrawNode.CanvasRenderCmd.prototype._drawPoly; - -})(); diff --git a/cocos2d/progress-timer/CCProgressTimer.js b/cocos2d/progress-timer/CCProgressTimer.js index 8b7443db23..65cad9542c 100644 --- a/cocos2d/progress-timer/CCProgressTimer.js +++ b/cocos2d/progress-timer/CCProgressTimer.js @@ -278,9 +278,6 @@ cc.ProgressTimer = cc.Node.extend(/** @lends cc.ProgressTimer# */{ }, _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) - return new cc.ProgressTimer.CanvasRenderCmd(this); - else return new cc.ProgressTimer.WebGLRenderCmd(this); } }); diff --git a/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js b/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js index 715fd6c50f..e69de29bb2 100644 --- a/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js +++ b/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js @@ -1,274 +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. - ****************************************************************************/ - -/** - * cc.ProgressTimer's rendering objects of Canvas - */ -(function(){ - cc.ProgressTimer.CanvasRenderCmd = function(renderableObject){ - cc.Node.CanvasRenderCmd.call(this, renderableObject); - this._needDraw = true; - - this._PI180 = Math.PI / 180; - this._barRect = cc.rect(0, 0, 0, 0); - this._origin = cc.p(0, 0); - this._radius = 0; - this._startAngle = 270; - this._endAngle = 270; - this._counterClockWise = false; - }; - - var proto = cc.ProgressTimer.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); - proto.constructor = cc.ProgressTimer.CanvasRenderCmd; - - proto.rendering = function (ctx, scaleX, scaleY) { - var wrapper = ctx || cc._renderContext,context = wrapper.getContext(), node = this._node, locSprite = node._sprite; - var locTextureCoord = locSprite._renderCmd._textureCoord, alpha = locSprite._renderCmd._displayedOpacity / 255; - - if (locTextureCoord.width === 0 || locTextureCoord.height === 0) - return; - if (!locSprite._texture || !locTextureCoord.validRect || alpha === 0) - return; - - wrapper.setTransform(this._worldTransform, scaleX, scaleY); - wrapper.setCompositeOperation(locSprite._blendFuncStr); - wrapper.setGlobalAlpha(alpha); - - var locRect = locSprite._rect, locOffsetPosition = locSprite._offsetPosition; - var locX = locOffsetPosition.x, - locY = -locOffsetPosition.y - locRect.height, - locWidth = locRect.width, - locHeight = locRect.height; - - wrapper.save(); - if (locSprite._flippedX) { - locX = -locX - locWidth; - context.scale(-1, 1); - } - if (locSprite._flippedY) { - locY = locOffsetPosition.y; - context.scale(1, -1); - } - - //clip - if (node._type === cc.ProgressTimer.TYPE_BAR) { - var locBarRect = this._barRect; - context.beginPath(); - context.rect(locBarRect.x * scaleX, locBarRect.y * scaleY, locBarRect.width * scaleX, locBarRect.height * scaleY); - context.clip(); - context.closePath(); - } else if (node._type === cc.ProgressTimer.TYPE_RADIAL) { - var locOriginX = this._origin.x * scaleX; - var locOriginY = this._origin.y * scaleY; - context.beginPath(); - context.arc(locOriginX, locOriginY, this._radius * scaleY, this._PI180 * this._startAngle, this._PI180 * this._endAngle, this._counterClockWise); - context.lineTo(locOriginX, locOriginY); - context.clip(); - context.closePath(); - } - - //draw sprite - var image = locSprite._texture.getHtmlElementObj(); - if (locSprite._renderCmd._colorized) { - context.drawImage(image, - 0, 0, locTextureCoord.width, locTextureCoord.height, - locX * scaleX, locY * scaleY, locWidth * scaleX, locHeight * scaleY); - } else { - context.drawImage(image, - locTextureCoord.renderX, locTextureCoord.renderY, locTextureCoord.width, locTextureCoord.height, - locX * scaleX, locY * scaleY, locWidth * scaleX, locHeight * scaleY); - } - wrapper.restore(); - cc.g_NumberOfDraws++; - }; - - proto.releaseData = function(){}; - - proto.initCmd = function(){}; - - proto._updateProgress = function(){ - var node = this._node; - var locSprite = node._sprite; - var sw = locSprite.width, sh = locSprite.height; - var locMidPoint = node._midPoint; - - if (node._type === cc.ProgressTimer.TYPE_RADIAL) { - this._radius = Math.round(Math.sqrt(sw * sw + sh * sh)); - var locStartAngle, locEndAngle, locCounterClockWise = false, locOrigin = this._origin; - locOrigin.x = sw * locMidPoint.x; - locOrigin.y = -sh * locMidPoint.y; - - if (node._reverseDirection) { - locEndAngle = 270; - locStartAngle = 270 - 3.6 * node._percentage; - } else { - locStartAngle = -90; - locEndAngle = -90 + 3.6 * node._percentage; - } - - if (locSprite._flippedX) { - locOrigin.x -= sw * (node._midPoint.x * 2); - locStartAngle = -locStartAngle; - locEndAngle = -locEndAngle; - locStartAngle -= 180; - locEndAngle -= 180; - locCounterClockWise = !locCounterClockWise; - } - if (locSprite._flippedY) { - locOrigin.y += sh * (node._midPoint.y * 2); - locCounterClockWise = !locCounterClockWise; - locStartAngle = -locStartAngle; - locEndAngle = -locEndAngle; - } - - this._startAngle = locStartAngle; - this._endAngle = locEndAngle; - this._counterClockWise = locCounterClockWise; - } else { - var locBarChangeRate = node._barChangeRate; - var percentageF = node._percentage / 100; - var locBarRect = this._barRect; - - var drewSize = cc.size((sw * (1 - locBarChangeRate.x)), (sh * (1 - locBarChangeRate.y))); - var drawingSize = cc.size((sw - drewSize.width) * percentageF, (sh - drewSize.height) * percentageF); - var currentDrawSize = cc.size(drewSize.width + drawingSize.width, drewSize.height + drawingSize.height); - - var startPoint = cc.p(sw * locMidPoint.x, sh * locMidPoint.y); - - var needToLeft = startPoint.x - currentDrawSize.width / 2; - if ((locMidPoint.x > 0.5) && (currentDrawSize.width / 2 >= sw - startPoint.x)) - needToLeft = sw - currentDrawSize.width; - - var needToTop = startPoint.y - currentDrawSize.height / 2; - if ((locMidPoint.y > 0.5) && (currentDrawSize.height / 2 >= sh - startPoint.y)) - needToTop = sh - currentDrawSize.height; - - //left pos - locBarRect.x = 0; - var flipXNeed = 1; - if (locSprite._flippedX) { - locBarRect.x -= currentDrawSize.width; - flipXNeed = -1; - } - - if (needToLeft > 0) - locBarRect.x += needToLeft * flipXNeed; - - //right pos - locBarRect.y = 0; - var flipYNeed = 1; - if (locSprite._flippedY) { - locBarRect.y += currentDrawSize.height; - flipYNeed = -1; - } - - if (needToTop > 0) - locBarRect.y -= needToTop * flipYNeed; - - //clip width and clip height - locBarRect.width = currentDrawSize.width; - locBarRect.height = -currentDrawSize.height; - } - }; - - proto._updateColor = function(){}; - - proto._syncStatus = function (parentCmd) { - var node = this._node; - if(!node._sprite) - return; - var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag; - var parentNode = parentCmd ? parentCmd._node : null; - - if(parentNode && parentNode._cascadeColorEnabled && (parentCmd._dirtyFlag & flags.colorDirty)) - locFlag |= flags.colorDirty; - - if(parentNode && parentNode._cascadeOpacityEnabled && (parentCmd._dirtyFlag & flags.opacityDirty)) - locFlag |= flags.opacityDirty; - - if(parentCmd && (parentCmd._dirtyFlag & flags.transformDirty)) - locFlag |= flags.transformDirty; - - this._dirtyFlag = locFlag; - - var spriteCmd = node._sprite._renderCmd; - var spriteFlag = spriteCmd._dirtyFlag; - - var colorDirty = spriteFlag & flags.colorDirty, - opacityDirty = spriteFlag & flags.opacityDirty; - - if (colorDirty){ - spriteCmd._syncDisplayColor(); - } - - if (opacityDirty){ - spriteCmd._syncDisplayOpacity(); - } - - if(colorDirty || opacityDirty){ - spriteCmd._updateColor(); - //this._updateColor(); - } - - if (locFlag & flags.transformDirty) { - //update the transform - this.transform(parentCmd); - } - - if (locFlag & flags.orderDirty) { - this._dirtyFlag = this._dirtyFlag & flags.orderDirty ^ this._dirtyFlag; - } - }; - - proto.updateStatus = function () { - var node = this._node; - if(!node._sprite) - return; - var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag; - var spriteCmd = node._sprite._renderCmd; - var spriteFlag = spriteCmd._dirtyFlag; - - var colorDirty = spriteFlag & flags.colorDirty, - opacityDirty = spriteFlag & flags.opacityDirty; - - if(colorDirty){ - spriteCmd._updateDisplayColor(); - } - - if(opacityDirty){ - spriteCmd._updateDisplayOpacity(); - } - - if(colorDirty || opacityDirty){ - spriteCmd._updateColor(); - //this._updateColor(); - } - - if(locFlag & flags.transformDirty){ - //update the transform - this.transform(this.getParentRenderCmd(), true); - } - this._dirtyFlag = 0; - }; -})(); \ No newline at end of file diff --git a/cocos2d/render-texture/CCRenderTexture.js b/cocos2d/render-texture/CCRenderTexture.js index 5ce1a44e3a..c689c9ead0 100644 --- a/cocos2d/render-texture/CCRenderTexture.js +++ b/cocos2d/render-texture/CCRenderTexture.js @@ -126,9 +126,6 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ }, _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) - return new cc.RenderTexture.CanvasRenderCmd(this); - else return new cc.RenderTexture.WebGLRenderCmd(this); }, diff --git a/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js b/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js index 854ebba1cc..e69de29bb2 100644 --- a/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js +++ b/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js @@ -1,107 +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. - ****************************************************************************/ - -(function(){ - cc.RenderTexture.CanvasRenderCmd = function(renderableObject){ - cc.Node.CanvasRenderCmd.call(this, renderableObject); - this._needDraw = true; - this._clearColorStr = "rgba(255,255,255,1)"; - - this._cacheCanvas = document.createElement('canvas'); - this._cacheContext = new cc.CanvasContextWrapper(this._cacheCanvas.getContext('2d')); - }; - - var proto = cc.RenderTexture.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); - proto.constructor = cc.RenderTexture.CanvasRenderCmd; - - proto.cleanup = function(){ - this._cacheContext = null; - this._cacheCanvas = null; - }; - - proto.clearStencil = function (stencilValue) { }; - - proto.setVirtualViewport = function(rtBegin, fullRect, fullViewport) {}; - - proto.updateClearColor = function(clearColor){ - this._clearColorStr = "rgba(" + (0 | clearColor.r) + "," + (0 | clearColor.g) + "," + (0 | clearColor.b) + "," + clearColor.a / 255 + ")"; - }; - - proto.initWithWidthAndHeight = function(width, height, format, depthStencilFormat){ - var node = this._node; - var locCacheCanvas = this._cacheCanvas, locScaleFactor = cc.contentScaleFactor(); - locCacheCanvas.width = 0 | (width * locScaleFactor); - locCacheCanvas.height = 0 | (height * locScaleFactor); - - var texture = new cc.Texture2D(); - texture.initWithElement(locCacheCanvas); - texture.handleLoadedTexture(); - - var locSprite = node.sprite = new cc.Sprite(texture); - locSprite.setBlendFunc(cc.ONE, cc.ONE_MINUS_SRC_ALPHA); - // Disabled by default. - node.autoDraw = false; - // add sprite for backward compatibility - node.addChild(locSprite); - return true; - }; - - proto.begin = function(){}; - - proto._beginWithClear = function(r, g, b, a, depthValue, stencilValue, flags){ - r = r || 0; - g = g || 0; - b = b || 0; - a = isNaN(a) ? 255 : a; - - var context = this._cacheContext.getContext(); - var locCanvas = this._cacheCanvas; - context.setTransform(1,0,0,1,0,0); - this._cacheContext.setFillStyle("rgba(" + (0 | r) + "," + (0 | g) + "," + (0 | b) + "," + a / 255 + ")"); - context.clearRect(0, 0, locCanvas.width, locCanvas.height); - context.fillRect(0, 0, locCanvas.width, locCanvas.height); - }; - - proto.end = function(){ - var node = this._node; - - var scale = cc.contentScaleFactor(); - cc.renderer._renderingToCacheCanvas(this._cacheContext, node.__instanceId, scale, scale); - }; - - proto.clearRect = function(x, y, width, height){ - this._cacheContext.clearRect(x, y, width, -height); - }; - - proto.clearDepth = function(depthValue){ - cc.log("clearDepth isn't supported on Cocos2d-Html5"); - }; - - proto.visit = function(parentCmd){ - var node = this._node; - this._syncStatus(parentCmd); - node.sprite.visit(this); - this._dirtyFlag = 0; - }; -})(); \ No newline at end of file diff --git a/cocos2d/shape-nodes/CCDrawNode.js b/cocos2d/shape-nodes/CCDrawNode.js index b534b3cf39..8424d460c9 100644 --- a/cocos2d/shape-nodes/CCDrawNode.js +++ b/cocos2d/shape-nodes/CCDrawNode.js @@ -170,349 +170,7 @@ cc.DrawNode.TYPE_SEGMENT = 1; cc.DrawNode.TYPE_POLY = 2; cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { - if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) { - - cc._DrawNodeElement = function (type, verts, fillColor, lineWidth, lineColor, lineCap, isClosePolygon, isFill, isStroke) { - var _t = this; - _t.type = type; - _t.verts = verts || null; - _t.fillColor = fillColor || null; - _t.lineWidth = lineWidth || 0; - _t.lineColor = lineColor || null; - _t.lineCap = lineCap || "butt"; - _t.isClosePolygon = isClosePolygon || false; - _t.isFill = isFill || false; - _t.isStroke = isStroke || false; - }; - - cc.extend(cc.DrawNode.prototype, /** @lends cc.DrawNode# */{ - _className:"DrawNodeCanvas", - - /** - *

The cc.DrawNodeCanvas's constructor.
- * This function will automatically be invoked when you create a node using new construction: "var node = new cc.DrawNodeCanvas()".
- * Override it to extend its behavior, remember to call "this._super()" in the extended "ctor" function.

- */ - ctor: function () { - cc.Node.prototype.ctor.call(this); - var locCmd = this._renderCmd; - locCmd._buffer = this._buffer = []; - locCmd._drawColor = this._drawColor = cc.color(255, 255, 255, 255); - locCmd._blendFunc = this._blendFunc = new cc.BlendFunc(cc.SRC_ALPHA, cc.ONE_MINUS_SRC_ALPHA); - - this.init(); - }, - - /** - * draws a rectangle given the origin and destination point measured in points. - * @param {cc.Point} origin - * @param {cc.Point} destination - * @param {cc.Color} fillColor - * @param {Number} lineWidth - * @param {cc.Color} lineColor - */ - drawRect: function (origin, destination, fillColor, lineWidth, lineColor) { - lineWidth = (lineWidth == null) ? this._lineWidth : lineWidth; - lineColor = lineColor || this.getDrawColor(); - if(lineColor.a == null) - lineColor.a = 255; - - var vertices = [ - origin, - cc.p(destination.x, origin.y), - destination, - cc.p(origin.x, destination.y) - ]; - var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY); - element.verts = vertices; - element.lineWidth = lineWidth; - element.lineColor = lineColor; - element.isClosePolygon = true; - element.isStroke = true; - element.lineCap = "butt"; - element.fillColor = fillColor; - if (fillColor) { - if(fillColor.a == null) - fillColor.a = 255; - element.isFill = true; - } - this._buffer.push(element); - }, - - /** - * draws a circle given the center, radius and number of segments. - * @override - * @param {cc.Point} center center of circle - * @param {Number} radius - * @param {Number} angle angle in radians - * @param {Number} segments - * @param {Boolean} drawLineToCenter - * @param {Number} lineWidth - * @param {cc.Color} color - */ - drawCircle: function (center, radius, angle, segments, drawLineToCenter, lineWidth, color) { - lineWidth = lineWidth || this._lineWidth; - color = color || this.getDrawColor(); - if (color.a == null) - color.a = 255; - - var coef = 2.0 * Math.PI / segments; - var vertices = []; - for (var i = 0; i <= segments; i++) { - var rads = i * coef; - var j = radius * Math.cos(rads + angle) + center.x; - var k = radius * Math.sin(rads + angle) + center.y; - vertices.push(cc.p(j, k)); - } - if (drawLineToCenter) { - vertices.push(cc.p(center.x, center.y)); - } - - var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY); - element.verts = vertices; - element.lineWidth = lineWidth; - element.lineColor = color; - element.isClosePolygon = true; - element.isStroke = true; - this._buffer.push(element); - }, - - /** - * draws a quad bezier path - * @override - * @param {cc.Point} origin - * @param {cc.Point} control - * @param {cc.Point} destination - * @param {Number} segments - * @param {Number} lineWidth - * @param {cc.Color} color - */ - drawQuadBezier: function (origin, control, destination, segments, lineWidth, color) { - lineWidth = lineWidth || this._lineWidth; - color = color || this.getDrawColor(); - if (color.a == null) - color.a = 255; - - var vertices = [], t = 0.0; - for (var i = 0; i < segments; i++) { - var x = Math.pow(1 - t, 2) * origin.x + 2.0 * (1 - t) * t * control.x + t * t * destination.x; - var y = Math.pow(1 - t, 2) * origin.y + 2.0 * (1 - t) * t * control.y + t * t * destination.y; - vertices.push(cc.p(x, y)); - t += 1.0 / segments; - } - vertices.push(cc.p(destination.x, destination.y)); - - var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY); - element.verts = vertices; - element.lineWidth = lineWidth; - element.lineColor = color; - element.isStroke = true; - element.lineCap = "round"; - this._buffer.push(element); - }, - - /** - * draws a cubic bezier path - * @override - * @param {cc.Point} origin - * @param {cc.Point} control1 - * @param {cc.Point} control2 - * @param {cc.Point} destination - * @param {Number} segments - * @param {Number} lineWidth - * @param {cc.Color} color - */ - drawCubicBezier: function (origin, control1, control2, destination, segments, lineWidth, color) { - lineWidth = lineWidth || this._lineWidth; - color = color || this.getDrawColor(); - if (color.a == null) - color.a = 255; - - var vertices = [], t = 0; - for (var i = 0; i < segments; i++) { - var x = Math.pow(1 - t, 3) * origin.x + 3.0 * Math.pow(1 - t, 2) * t * control1.x + 3.0 * (1 - t) * t * t * control2.x + t * t * t * destination.x; - var y = Math.pow(1 - t, 3) * origin.y + 3.0 * Math.pow(1 - t, 2) * t * control1.y + 3.0 * (1 - t) * t * t * control2.y + t * t * t * destination.y; - vertices.push(cc.p(x, y)); - t += 1.0 / segments; - } - vertices.push(cc.p(destination.x, destination.y)); - - var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY); - element.verts = vertices; - element.lineWidth = lineWidth; - element.lineColor = color; - element.isStroke = true; - element.lineCap = "round"; - this._buffer.push(element); - }, - - /** - * draw a CatmullRom curve - * @override - * @param {Array} points - * @param {Number} segments - * @param {Number} lineWidth - * @param {cc.Color} color - */ - drawCatmullRom: function (points, segments, lineWidth, color) { - this.drawCardinalSpline(points, 0.5, segments, lineWidth, color); - }, - - /** - * draw a cardinal spline path - * @override - * @param {Array} config - * @param {Number} tension - * @param {Number} segments - * @param {Number} lineWidth - * @param {cc.Color} color - */ - drawCardinalSpline: function (config, tension, segments, lineWidth, color) { - lineWidth = lineWidth || this._lineWidth; - color = color || this.getDrawColor(); - if(color.a == null) - color.a = 255; - - var vertices = [], p, lt, deltaT = 1.0 / config.length; - for (var i = 0; i < segments + 1; i++) { - var dt = i / segments; - // border - if (dt === 1) { - p = config.length - 1; - lt = 1; - } else { - p = 0 | (dt / deltaT); - lt = (dt - deltaT * p) / deltaT; - } - - // Interpolate - var newPos = cc.cardinalSplineAt( - cc.getControlPointAt(config, p - 1), - cc.getControlPointAt(config, p - 0), - cc.getControlPointAt(config, p + 1), - cc.getControlPointAt(config, p + 2), - tension, lt); - vertices.push(newPos); - } - - var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY); - element.verts = vertices; - element.lineWidth = lineWidth; - element.lineColor = color; - element.isStroke = true; - element.lineCap = "round"; - this._buffer.push(element); - }, - - /** - * draw a dot at a position, with a given radius and color - * @param {cc.Point} pos - * @param {Number} radius - * @param {cc.Color} color - */ - drawDot: function (pos, radius, color) { - color = color || this.getDrawColor(); - if (color.a == null) - color.a = 255; - var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_DOT); - element.verts = [pos]; - element.lineWidth = radius; - element.fillColor = color; - this._buffer.push(element); - }, - - /** - * draws an array of points. - * @override - * @param {Array} points point of array - * @param {Number} radius - * @param {cc.Color} color - */ - drawDots: function(points, radius, color){ - if(!points || points.length == 0) - return; - color = color || this.getDrawColor(); - if (color.a == null) - color.a = 255; - for(var i = 0, len = points.length; i < len; i++) - this.drawDot(points[i], radius, color); - }, - - /** - * draw a segment with a radius and color - * @param {cc.Point} from - * @param {cc.Point} to - * @param {Number} lineWidth - * @param {cc.Color} color - */ - drawSegment: function (from, to, lineWidth, color) { - lineWidth = lineWidth || this._lineWidth; - color = color || this.getDrawColor(); - if (color.a == null) - color.a = 255; - var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY); - element.verts = [from, to]; - element.lineWidth = lineWidth * 2; - element.lineColor = color; - element.isStroke = true; - element.lineCap = "round"; - this._buffer.push(element); - }, - - /** - * draw a polygon with a fill color and line color without copying the vertex list - * @param {Array} verts - * @param {cc.Color} fillColor - * @param {Number} lineWidth - * @param {cc.Color} color - */ - drawPoly_: function (verts, fillColor, lineWidth, color) { - lineWidth = (lineWidth == null ) ? this._lineWidth : lineWidth; - color = color || this.getDrawColor(); - if (color.a == null) - color.a = 255; - var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY); - - element.verts = verts; - element.fillColor = fillColor; - element.lineWidth = lineWidth; - element.lineColor = color; - element.isClosePolygon = true; - element.isStroke = true; - element.lineCap = "round"; - if (fillColor) - element.isFill = true; - this._buffer.push(element); - }, - - /** - * draw a polygon with a fill color and line color, copying the vertex list - * @param {Array} verts - * @param {cc.Color} fillColor - * @param {Number} lineWidth - * @param {cc.Color} color - */ - drawPoly: function (verts, fillColor, lineWidth, color) { - var vertsCopy = []; - for (var i=0; i < verts.length; i++) { - vertsCopy.push(cc.p(verts[i].x, verts[i].y)); - } - return this.drawPoly_(vertsCopy, fillColor, lineWidth, color); - }, - - /** - * Clear the geometry in the node's buffer. - */ - clear: function () { - this._buffer.length = 0; - }, - - _createRenderCmd: function(){ - return new cc.DrawNode.CanvasRenderCmd(this); - } - }); - } - else if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { + if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { cc.extend(cc.DrawNode.prototype, { _bufferCapacity:0, diff --git a/cocos2d/shape-nodes/CCDrawNodeCanvasRenderCmd.js b/cocos2d/shape-nodes/CCDrawNodeCanvasRenderCmd.js index 5be88269f2..e69de29bb2 100644 --- a/cocos2d/shape-nodes/CCDrawNodeCanvasRenderCmd.js +++ b/cocos2d/shape-nodes/CCDrawNodeCanvasRenderCmd.js @@ -1,131 +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. - ****************************************************************************/ - -(function(){ - - cc.DrawNode.CanvasRenderCmd = function(renderableObject){ - cc.Node.CanvasRenderCmd.call(this, renderableObject); - this._needDraw = true; - this._buffer = null; - this._drawColor = null; - this._blendFunc = null; - }; - - cc.DrawNode.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); - cc.DrawNode.CanvasRenderCmd.prototype.constructor = cc.DrawNode.CanvasRenderCmd; - cc.extend( cc.DrawNode.CanvasRenderCmd.prototype, { - rendering: function (ctx, scaleX, scaleY) { - var wrapper = ctx || cc._renderContext, context = wrapper.getContext(), node = this._node; - var alpha = node._displayedOpacity / 255; - if (alpha === 0) - return; - - wrapper.setTransform(this._worldTransform, scaleX, scaleY); - - //context.save(); - wrapper.setGlobalAlpha(alpha); - if ((this._blendFunc && (this._blendFunc.src === cc.SRC_ALPHA) && (this._blendFunc.dst === cc.ONE))) - wrapper.setCompositeOperation('lighter'); //todo: need refactor - var locBuffer = this._buffer; - for (var i = 0, len = locBuffer.length; i < len; i++) { - var element = locBuffer[i]; - switch (element.type) { - case cc.DrawNode.TYPE_DOT: - this._drawDot(wrapper, element, scaleX, scaleY); - break; - case cc.DrawNode.TYPE_SEGMENT: - this._drawSegment(wrapper, element, scaleX, scaleY); - break; - case cc.DrawNode.TYPE_POLY: - this._drawPoly(wrapper, element, scaleX, scaleY); - break; - } - } - //context.restore(); //todo It can be reserve - }, - - _drawDot: function (wrapper, element, scaleX, scaleY) { - var locColor = element.fillColor, locPos = element.verts[0], locRadius = element.lineWidth; - - var ctx = wrapper.getContext(); - wrapper.setFillStyle("rgba(" + (0 | locColor.r) + "," + (0 | locColor.g) + "," + (0 | locColor.b) + "," + locColor.a / 255 + ")"); - - ctx.beginPath(); - ctx.arc(locPos.x * scaleX, -locPos.y * scaleY, locRadius * scaleX, 0, Math.PI * 2, false); - ctx.closePath(); - ctx.fill(); - }, - - _drawSegment: function (wrapper, element, scaleX, scaleY) { - var locColor = element.lineColor; - var locFrom = element.verts[0], locTo = element.verts[1]; - var locLineWidth = element.lineWidth, locLineCap = element.lineCap; - - var ctx = wrapper.getContext(); - wrapper.setStrokeStyle("rgba(" + (0 | locColor.r) + "," + (0 | locColor.g) + "," + (0 | locColor.b) + "," + locColor.a / 255 + ")"); - - ctx.lineWidth = locLineWidth * scaleX; - ctx.beginPath(); - ctx.lineCap = locLineCap; - ctx.moveTo(locFrom.x * scaleX, -locFrom.y * scaleY); - ctx.lineTo(locTo.x * scaleX, -locTo.y * scaleY); - ctx.stroke(); - }, - - _drawPoly: function (wrapper, element, scaleX, scaleY) { - var locVertices = element.verts, locLineCap = element.lineCap; - if (locVertices == null) - return; - - var locFillColor = element.fillColor, locLineWidth = element.lineWidth; - var locLineColor = element.lineColor, locIsClosePolygon = element.isClosePolygon; - var locIsFill = element.isFill, locIsStroke = element.isStroke; - - var ctx = wrapper.getContext(); - var firstPoint = locVertices[0]; - ctx.lineCap = locLineCap; - if (locFillColor) - wrapper.setFillStyle("rgba(" + (0 | locFillColor.r) + "," + (0 | locFillColor.g) + "," - + (0 | locFillColor.b) + "," + locFillColor.a / 255 + ")"); - if (locLineWidth) - ctx.lineWidth = locLineWidth * scaleX; - if (locLineColor) - wrapper.setStrokeStyle("rgba(" + (0 | locLineColor.r) + "," + (0 | locLineColor.g) + "," - + (0 | locLineColor.b) + "," + locLineColor.a / 255 + ")"); - - ctx.beginPath(); - ctx.moveTo(firstPoint.x * scaleX, -firstPoint.y * scaleY); - for (var i = 1, len = locVertices.length; i < len; i++) - ctx.lineTo(locVertices[i].x * scaleX, -locVertices[i].y * scaleY); - - if (locIsClosePolygon) - ctx.closePath(); - if (locIsFill) - ctx.fill(); - if (locIsStroke) - ctx.stroke(); - } - }); - -})(); diff --git a/cocos2d/tilemap/CCTMXLayer.js b/cocos2d/tilemap/CCTMXLayer.js index a2877df2c3..cb9afecca6 100644 --- a/cocos2d/tilemap/CCTMXLayer.js +++ b/cocos2d/tilemap/CCTMXLayer.js @@ -99,9 +99,6 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ }, _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) - return new cc.TMXLayer.CanvasRenderCmd(this); - else return new cc.TMXLayer.WebGLRenderCmd(this); }, diff --git a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js index 79a1ff197d..e69de29bb2 100644 --- a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js +++ b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js @@ -1,220 +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. - ****************************************************************************/ - -(function(){ - cc.TMXLayer.CanvasRenderCmd = function(renderable){ - cc.SpriteBatchNode.CanvasRenderCmd.call(this, renderable); - this._needDraw = true; - this._realWorldTransform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0}; - - var locCanvas = cc._canvas; - var tmpCanvas = document.createElement('canvas'); - tmpCanvas.width = locCanvas.width; - tmpCanvas.height = locCanvas.height; - this._cacheCanvas = tmpCanvas; - this._cacheContext = new cc.CanvasContextWrapper(this._cacheCanvas.getContext('2d')); - var tempTexture = new cc.Texture2D(); - tempTexture.initWithElement(tmpCanvas); - tempTexture.handleLoadedTexture(); - this._cacheTexture = tempTexture; - // This class uses cache, so its default cachedParent should be himself - this._cacheDirty = false; - }; - - var proto = cc.TMXLayer.CanvasRenderCmd.prototype = Object.create(cc.SpriteBatchNode.CanvasRenderCmd.prototype); - proto.constructor = cc.TMXLayer.CanvasRenderCmd; - - //set the cache dirty flag for canvas - proto._setNodeDirtyForCache = function () { - this._cacheDirty = true; - }; - - proto._renderingChildToCache = function () { - if (this._cacheDirty) { - var wrapper = this._cacheContext, - context = wrapper.getContext(), locCanvas = this._cacheCanvas; - - //wrapper.save(); - context.setTransform(1, 0, 0, 1, 0, 0); - context.clearRect(0, 0, locCanvas.width, locCanvas.height); - //reset the cache context - - var locChildren = this._node._children; - for (var i = 0, len = locChildren.length; i < len; i++) { - if (locChildren[i]){ - var selCmd = locChildren[i]._renderCmd; - if(selCmd){ - selCmd.rendering(wrapper, 1, 1); - selCmd._cacheDirty = false; - } - } - } - - //wrapper.restore(); - this._cacheDirty = false; - } - }; - - proto.rendering = function (ctx, scaleX, scaleY) { - var alpha = this._displayedOpacity / 255; - if (alpha <= 0) - return; - - var node = this._node; - this._renderingChildToCache(); - var wrapper = ctx || cc._renderContext, context = wrapper.getContext(); - wrapper.setGlobalAlpha(alpha); - - var locCacheCanvas = this._cacheCanvas; - //direct draw image by canvas drawImage - if (locCacheCanvas && locCacheCanvas.width !== 0 && locCacheCanvas.height !== 0) { - wrapper.setTransform(this._realWorldTransform, scaleX, scaleY); - var locCanvasHeight = locCacheCanvas.height * scaleY; - if (node.layerOrientation === cc.TMX_ORIENTATION_HEX) { - var halfTileSize = node._mapTileSize.height * 0.5 * scaleY; - context.drawImage(locCacheCanvas, 0, 0, locCacheCanvas.width, locCacheCanvas.height, - 0, -locCanvasHeight + halfTileSize, locCacheCanvas.width * scaleX, locCanvasHeight); - } else { - context.drawImage(locCacheCanvas, 0, 0, locCacheCanvas.width, locCacheCanvas.height, - 0, -locCanvasHeight, locCacheCanvas.width * scaleX, locCanvasHeight); - } - } - cc.g_NumberOfDraws++; - }; - - proto._updateCacheContext = function(size, height){ - var node = this._node, - locContentSize = node._contentSize, - locCanvas = this._cacheCanvas, - scaleFactor = cc.contentScaleFactor(); - locCanvas.width = 0 | (locContentSize.width * 1.5 * scaleFactor); - locCanvas.height = 0 | (locContentSize.height * 1.5 * scaleFactor); - - //todo: need change the wrapper's height - if(node.layerOrientation === cc.TMX_ORIENTATION_HEX) - this._cacheContext.setOffset(0, -node._mapTileSize.height * 0.5); //translate for hexagonal - else - this._cacheContext.setOffset(0, 0); - var locTexContentSize = this._cacheTexture._contentSize; - locTexContentSize.width = locCanvas.width; - locTexContentSize.height = locCanvas.height; - }; - - proto.getTexture = function(){ - return this._cacheTexture; - }; - - proto.visit = function(parentCmd){ - var node = this._node; - //TODO: it will implement dynamic compute child cutting automation. - var i, len, locChildren = node._children; - // quick return if not visible - if (!node._visible || !locChildren || locChildren.length === 0) - return; - - parentCmd = parentCmd || this.getParentRenderCmd(); - if (parentCmd) - this._curLevel = parentCmd._curLevel + 1; - - this._syncStatus(parentCmd); - if (this._cacheDirty) { - var wrapper = this._cacheContext, locCanvas = this._cacheCanvas, context = wrapper.getContext(), - instanceID = node.__instanceId, renderer = cc.renderer; - //begin cache - renderer._turnToCacheMode(instanceID); - - node.sortAllChildren(); - for (i = 0, len = locChildren.length; i < len; i++) { - if (locChildren[i]){ - var selCmd = locChildren[i]._renderCmd; - if(selCmd){ - selCmd.visit(this); - selCmd._cacheDirty = false; - } - } - } - - //wrapper.save(); - context.setTransform(1, 0, 0, 1, 0, 0); - context.clearRect(0, 0, locCanvas.width, locCanvas.height); - //set the wrapper's offset - - //draw to cache canvas - renderer._renderingToCacheCanvas(wrapper, instanceID); - //wrapper.restore(); //todo: it can be reserve. - this._cacheDirty = false - } - cc.renderer.pushRenderCommand(this); - this._dirtyFlag = 0; - }; - - proto.transform = function (parentCmd, recursive) { - // transform for canvas - var t = this.getNodeToParentTransform(), - worldT = this._realWorldTransform; //get the world transform - - if (parentCmd) { - var pt = parentCmd._worldTransform; - // cc.AffineTransformConcat is incorrect at get world transform - worldT.a = t.a * pt.a + t.b * pt.c; //a - worldT.b = t.a * pt.b + t.b * pt.d; //b - worldT.c = t.c * pt.a + t.d * pt.c; //c - worldT.d = t.c * pt.b + t.d * pt.d; //d - - worldT.tx = pt.a * t.tx + pt.c * t.ty + pt.tx; - worldT.ty = pt.d * t.ty + pt.ty + pt.b * t.tx; - } else { - worldT.a = t.a; - worldT.b = t.b; - worldT.c = t.c; - worldT.d = t.d; - worldT.tx = t.tx; - worldT.ty = t.ty; - } - if (recursive) { - var locChildren = this._node._children; - if (!locChildren || locChildren.length === 0) - return; - var i, len; - for (i = 0, len = locChildren.length; i < len; i++) { - locChildren[i]._renderCmd.transform(this, recursive); - } - } - }; - - proto.initImageSize = function(){ - var node = this._node; - node.tileset.imageSize = this._texture.getContentSizeInPixels(); - }; - - proto._reusedTileWithRect = function(rect){ - var node = this._node; - node._reusedTile = new cc.Sprite(); - node._reusedTile.initWithTexture(this._texture, rect, false); - node._reusedTile.batchNode = node; - node._reusedTile.parent = node; - node._reusedTile._renderCmd._cachedParent = node._renderCmd; - return node._reusedTile; - }; -})(); \ No newline at end of file diff --git a/extensions/ccui/base-classes/CCProtectedNode.js b/extensions/ccui/base-classes/CCProtectedNode.js index e3b1d976f0..4fdcdabb0a 100644 --- a/extensions/ccui/base-classes/CCProtectedNode.js +++ b/extensions/ccui/base-classes/CCProtectedNode.js @@ -288,9 +288,6 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{ }, _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) - return new cc.ProtectedNode.CanvasRenderCmd(this); - else return new cc.ProtectedNode.WebGLRenderCmd(this); } }); diff --git a/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js b/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js index c3ecd0bb7d..aff1e7d5ca 100644 --- a/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js +++ b/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js @@ -138,103 +138,4 @@ } }; - cc.ProtectedNode.CanvasRenderCmd = function (renderable) { - cc.Node.CanvasRenderCmd.call(this, renderable); - this._cachedParent = null; - this._cacheDirty = false; - }; - - var proto = cc.ProtectedNode.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); - cc.inject(cc.ProtectedNode.RenderCmd, proto); - proto.constructor = cc.ProtectedNode.CanvasRenderCmd; - - proto.visit = function(parentCmd){ - var node = this._node; - // quick return if not visible - if (!node._visible) - return; - - //visit for canvas - var i, j; - var children = node._children, child; - var locChildren = node._children, locProtectedChildren = node._protectedChildren; - var childLen = locChildren.length, pLen = locProtectedChildren.length; - - this._syncStatus(parentCmd); - - node.sortAllChildren(); - node.sortAllProtectedChildren(); - - var pChild; - // draw children zOrder < 0 - for (i = 0; i < childLen; i++) { - child = children[i]; - if (child._localZOrder < 0) - child.visit(this); - else - break; - } - for (j = 0; j < pLen; j++) { - pChild = locProtectedChildren[j]; - if (pChild && pChild._localZOrder < 0){ - this._changeProtectedChild(pChild); - pChild.visit(this); - } - else - break; - } - - cc.renderer.pushRenderCommand(this); - - for (; i < childLen; i++) - children[i] && children[i].visit(this); - for (; j < pLen; j++){ - pChild = locProtectedChildren[j]; - if(!pChild) continue; - this._changeProtectedChild(pChild); - pChild.visit(this); - } - - this._dirtyFlag = 0; - this._cacheDirty = false; - }; - - proto.transform = function(parentCmd, recursive){ - var node = this._node; - - if(node._changePosition) - node._changePosition(); - - var t = node.getNodeToParentTransform(), worldT = this._worldTransform; - if (parentCmd) { - var pt = parentCmd._worldTransform; - // cc.AffineTransformConcat is incorrect at get world transform - worldT.a = t.a * pt.a + t.b * pt.c; //a - worldT.b = t.a * pt.b + t.b * pt.d; //b - worldT.c = t.c * pt.a + t.d * pt.c; //c - worldT.d = t.c * pt.b + t.d * pt.d; //d - - worldT.tx = pt.a * t.tx + pt.c * t.ty + pt.tx; - worldT.ty = pt.d * t.ty + pt.ty + pt.b * t.tx; - } else { - worldT.a = t.a; - worldT.b = t.b; - worldT.c = t.c; - worldT.d = t.d; - worldT.tx = t.tx; - worldT.ty = t.ty; - } - var i, len, locChildren = node._children; - if(recursive && locChildren && locChildren.length !== 0){ - for(i = 0, len = locChildren.length; i< len; i++){ - locChildren[i]._renderCmd.transform(this, recursive); - } - } - locChildren = node._protectedChildren; - if(recursive && locChildren && locChildren.length !== 0){ - for(i = 0, len = locChildren.length; i< len; i++){ - locChildren[i]._renderCmd.transform(this, recursive); - } - } - }; })(); \ No newline at end of file diff --git a/extensions/ccui/base-classes/UIWidget.js b/extensions/ccui/base-classes/UIWidget.js index 325b3188bb..a0cff5f317 100644 --- a/extensions/ccui/base-classes/UIWidget.js +++ b/extensions/ccui/base-classes/UIWidget.js @@ -178,7 +178,8 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ }, /** - * initializes state of widget. please do not call this function by yourself, you should pass the parameters to constructor to initialize it
. + * initializes state of widget. please do not call this function by yourself, you should pass the parameters to constructor to initialize it +. * @returns {boolean} */ init: function () { @@ -1829,10 +1830,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ _createRenderCmd: function(){ - if(cc._renderType === cc.game.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 index 07e1a004af..eeb7da031f 100644 --- a/extensions/ccui/base-classes/UIWidgetRenderCmd.js +++ b/extensions/ccui/base-classes/UIWidgetRenderCmd.js @@ -23,42 +23,6 @@ ****************************************************************************/ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { - if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) { - ccui.Widget.CanvasRenderCmd = function (renderable) { - cc.ProtectedNode.CanvasRenderCmd.call(this, renderable); - this._needDraw = false; - }; - - var proto = ccui.Widget.CanvasRenderCmd.prototype = Object.create(cc.ProtectedNode.CanvasRenderCmd.prototype); - proto.constructor = ccui.Widget.CanvasRenderCmd; - - proto.visit = function (parentCmd) { - var node = this._node; - if (node._visible) { - node._adaptRenderers(); - cc.ProtectedNode.CanvasRenderCmd.prototype.visit.call(this, parentCmd); - } - }; - - proto.transform = function (parentCmd, recursive) { - var node = this._node; - - if (node._visible) { - node._adaptRenderers(); - if(!this._usingLayoutComponent){ - var widgetParent = node.getWidgetParent(); - if (widgetParent) { - var parentSize = widgetParent.getContentSize(); - if (parentSize.width !== 0 && parentSize.height !== 0) { - node._position.x = parentSize.width * node._positionPercent.x; - node._position.y = parentSize.height * node._positionPercent.y; - } - } - } - cc.ProtectedNode.CanvasRenderCmd.prototype.transform.call(this, parentCmd, recursive); - } - }; - } else { ccui.Widget.WebGLRenderCmd = function (renderable) { cc.ProtectedNode.WebGLRenderCmd.call(this, renderable); this._needDraw = false; @@ -93,5 +57,5 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { cc.ProtectedNode.WebGLRenderCmd.prototype.transform.call(this, parentCmd, recursive); } }; - } + }); diff --git a/extensions/ccui/layouts/UILayout.js b/extensions/ccui/layouts/UILayout.js index 23ac2d61da..cc27cf32c2 100644 --- a/extensions/ccui/layouts/UILayout.js +++ b/extensions/ccui/layouts/UILayout.js @@ -1451,10 +1451,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ }, _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_WEBGL) return new ccui.Layout.WebGLRenderCmd(this); - else - return new ccui.Layout.CanvasRenderCmd(this); } }); diff --git a/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js b/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js index df53a60560..e69de29bb2 100644 --- a/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js +++ b/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js @@ -1,179 +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(){ - ccui.Layout.CanvasRenderCmd = function(renderable){ - ccui.ProtectedNode.CanvasRenderCmd.call(this, renderable); - this._needDraw = false; - - this._clipElemType = false; - this._locCache = null; - this._rendererSaveCmd = new cc.CustomRenderCmd(this, this._onRenderSaveCmd); - this._rendererSaveCmdSprite = new cc.CustomRenderCmd(this, this._onRenderSaveSpriteCmd); - this._rendererClipCmd = new cc.CustomRenderCmd(this, this._onRenderClipCmd); - this._rendererRestoreCmd = new cc.CustomRenderCmd(this, this._onRenderRestoreCmd); - }; - - var proto = ccui.Layout.CanvasRenderCmd.prototype = Object.create(ccui.ProtectedNode.CanvasRenderCmd.prototype); - proto.constructor = ccui.Layout.CanvasRenderCmd; - - proto.visit = function(parentCmd){ - var node = this._node; - if (!node._visible) - return; - node._adaptRenderers(); - node._doLayout(); - - if (node._clippingEnabled) { - switch (node._clippingType) { - case ccui.Layout.CLIPPING_STENCIL: - this.stencilClippingVisit(parentCmd); - break; - case ccui.Layout.CLIPPING_SCISSOR: - this.scissorClippingVisit(parentCmd); - break; - default: - break; - } - } else - ccui.Widget.CanvasRenderCmd.prototype.visit.call(this, parentCmd); - }; - - proto._onRenderSaveCmd = function(ctx, scaleX, scaleY){ - var wrapper = ctx || cc._renderContext, context = wrapper.getContext(); - if (this._clipElemType) { - var canvas = context.canvas; - this._locCache = ccui.Layout.CanvasRenderCmd._getSharedCache(); - this._locCache.width = canvas.width; - this._locCache.height = canvas.height; - var locCacheCtx = this._locCache.getContext("2d"); - locCacheCtx.drawImage(canvas, 0, 0); - } else { - wrapper.save(); - wrapper.save(); - wrapper.setTransform(this._worldTransform, scaleX, scaleY); - } - }; - - proto._onRenderSaveSpriteCmd = function(ctx){ - var wrapper = ctx || cc._renderContext; - //var node = this._node; - if (this._clipElemType) { - wrapper.setCompositeOperation("destination-in"); - } - }; - - proto._onRenderClipCmd = function(ctx){ - var wrapper = ctx || cc._renderContext, context = wrapper.getContext(); - if (!this._clipElemType) { - wrapper.restore(); - context.clip(); - } - }; - - proto._onRenderRestoreCmd = function(ctx){ - var wrapper = ctx || cc._renderContext, context = wrapper.getContext(); - - if (this._clipElemType) { - // Redraw the cached canvas, so that the cliped area shows the background etc. - context.save(); - context.setTransform(1, 0, 0, 1, 0, 0); - context.globalCompositeOperation = "destination-over"; - context.drawImage(this._locCache, 0, 0); - context.restore(); - }else{ - wrapper.restore(); //use for restore clip operation - } - }; - - proto.rebindStencilRendering = function(stencil){ - stencil._renderCmd.rendering = this.__stencilDraw; - }; - - proto.__stencilDraw = function(ctx,scaleX, scaleY){ //Only for Canvas - var wrapper = ctx || cc._renderContext, locContext = wrapper.getContext(), buffer = this._buffer; - - for (var i = 0, bufLen = buffer.length; i < bufLen; i++) { - var element = buffer[i], vertices = element.verts; - var firstPoint = vertices[0]; - locContext.beginPath(); - locContext.moveTo(firstPoint.x * scaleX, -firstPoint.y * scaleY); - for (var j = 1, len = vertices.length; j < len; j++) - locContext.lineTo(vertices[j].x * scaleX, -vertices[j].y * scaleY); - locContext.closePath(); - } - }; - - proto.stencilClippingVisit = proto.scissorClippingVisit = function(parentCmd){ - var node = this._node; - if (!node._clippingStencil || !node._clippingStencil.isVisible()) - return; - - this._clipElemType = node._stencil instanceof cc.Sprite; - this._syncStatus(parentCmd); - - cc.renderer.pushRenderCommand(this._rendererSaveCmd); - if (this._clipElemType) { - cc.ProtectedNode.prototype.visit.call(node, parentCmd); - cc.renderer.pushRenderCommand(this._rendererSaveCmdSprite); - } - node._clippingStencil.visit(this); - - cc.renderer.pushRenderCommand(this._rendererClipCmd); - if (!this._clipElemType) { - node.sortAllChildren(); - node.sortAllProtectedChildren(); - - var children = node._children; - var j=0, locProtectChildren = node._protectedChildren, i = 0, locChild; - var iLen = children.length, jLen = locProtectChildren.length; - - for( ; i < iLen; i++ ){ - locChild = children[i]; - if ( locChild && locChild.getLocalZOrder() < 0 ) - locChild.visit(this); - else - break; - } - for( ; j < jLen; j++ ) { - locChild = locProtectChildren[j]; - if ( locChild && locChild.getLocalZOrder() < 0 ) - locChild.visit(this); - else - break; - } - for (; i < iLen; i++) - children[i].visit(this); - for (; j < jLen; j++) - locProtectChildren[j].visit(this); - cc.renderer.pushRenderCommand(this._rendererRestoreCmd); - } - this._dirtyFlag = 0; - }; - - ccui.Layout.CanvasRenderCmd._getSharedCache = function () { - return (cc.ClippingNode._sharedCache) || (cc.ClippingNode._sharedCache = document.createElement("canvas")); - }; -})(); \ No newline at end of file diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js index db44fc6e28..051037d863 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js @@ -152,10 +152,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ }, _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_WEBGL) - return new ccui.ScrollView.WebGLRenderCmd(this); - else - return new ccui.ScrollView.CanvasRenderCmd(this); + return new ccui.ScrollView.WebGLRenderCmd(this); }, _onSizeChanged: function () { diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewCanvasRenderCmd.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewCanvasRenderCmd.js index 95a865840d..e69de29bb2 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewCanvasRenderCmd.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewCanvasRenderCmd.js @@ -1,45 +0,0 @@ -(function(){ - if(!ccui.ProtectedNode.CanvasRenderCmd) - return; - ccui.ScrollView.CanvasRenderCmd = function(renderable){ - ccui.Layout.CanvasRenderCmd.call(this, renderable); - this._needDraw = true; - this._dirty = false; - }; - - var proto = ccui.ScrollView.CanvasRenderCmd.prototype = Object.create(ccui.Layout.CanvasRenderCmd.prototype); - proto.constructor = ccui.ScrollView.CanvasRenderCmd; - - proto.visit = function(parentCmd) { - var node = this._node; - if (!node._visible) - return; - var currentID = node.__instanceId; - - cc.renderer.pushRenderCommand(this); - cc.renderer._turnToCacheMode(currentID); - - ccui.Layout.CanvasRenderCmd.prototype.visit.call(this, parentCmd); - - this._dirtyFlag = 0; - cc.renderer._turnToNormalMode(); - }; - - proto.rendering = function (ctx) { - var currentID = this._node.__instanceId; - var locCmds = cc.renderer._cacheToCanvasCmds[currentID], i, len, - scaleX = cc.view.getScaleX(), - scaleY = cc.view.getScaleY(); - var context = ctx || cc._renderContext; - context.computeRealOffsetY(); - - for (i = 0, len = locCmds.length; i < len; i++) { - var checkNode = locCmds[i]._node; - if(checkNode instanceof ccui.ScrollView) - continue; - if(checkNode && checkNode._parent && checkNode._parent._inViewRect === false) - continue; - locCmds[i].rendering(context, scaleX, scaleY); - } - }; -})(); diff --git a/extensions/cocostudio/armature/CCArmature.js b/extensions/cocostudio/armature/CCArmature.js index 2f03c1710e..640b2f74d1 100644 --- a/extensions/cocostudio/armature/CCArmature.js +++ b/extensions/cocostudio/armature/CCArmature.js @@ -545,9 +545,6 @@ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{ }, _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) - return new ccs.Armature.CanvasRenderCmd(this); - else return new ccs.Armature.WebGLRenderCmd(this); } }); diff --git a/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js b/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js index 4d0a4f06f3..bf865ba416 100644 --- a/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js +++ b/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js @@ -39,152 +39,4 @@ return cc.p(this._realAnchorPointInPoints); } }; -})(); - -(function(){ - ccs.Armature.CanvasRenderCmd = function(renderableObject){ - cc.Node.CanvasRenderCmd.call(this, renderableObject); - this._needDraw = true; - - this._realAnchorPointInPoints = new cc.Point(0,0); - this._startRenderCmd = new cc.CustomRenderCmd(this, this._startCmdCallback); - this._RestoreRenderCmd = new cc.CustomRenderCmd(this, this._RestoreCmdCallback); - }; - - var proto = ccs.Armature.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); - cc.inject(ccs.Armature.RenderCmd, proto); - proto.constructor = ccs.Armature.CanvasRenderCmd; - - proto._startCmdCallback = function(ctx, scaleX, scaleY){ - var node = this._node, parent = node._parent; - this.transform(parent ? parent._renderCmd : null); - - var wrapper = ctx || cc._renderContext; - wrapper.save(); - - //set to armature mode - wrapper._switchToArmatureMode(true, this._worldTransform, scaleX, scaleY); - }; - - proto.transform = function(parentCmd, recursive){ - ccs.Node.CanvasRenderCmd.prototype.transform.call(this, parentCmd, recursive); - - var locChildren = this._node._children; - for (var i = 0, len = locChildren.length; i< len; i++) { - var selBone = locChildren[i]; - if (selBone && selBone.getDisplayRenderNode) { - var selNode = selBone.getDisplayRenderNode(); - if (selNode && selNode._renderCmd){ - var cmd = selNode._renderCmd; - cmd.transform(null); //must be null, use transform in armature mode - - //update displayNode's color and opacity, because skin didn't call visit() - var parentColor = selBone._renderCmd._displayedColor, parentOpacity = selBone._renderCmd._displayedOpacity; - var flags = cc.Node._dirtyFlags, locFlag = cmd._dirtyFlag; - var colorDirty = locFlag & flags.colorDirty, - opacityDirty = locFlag & flags.opacityDirty; - if(colorDirty) - cmd._updateDisplayColor(parentColor); - if(opacityDirty) - cmd._updateDisplayOpacity(parentOpacity); - } - } - } - }; - - proto._RestoreCmdCallback = function(wrapper){ - this._cacheDirty = false; - //wrapper.restore(); - wrapper._switchToArmatureMode(false); - wrapper.restore(); - }; - - proto.initShaderCache = function(){}; - proto.setShaderProgram = function(){}; - proto.updateChildPosition = function(ctx, dis){ - //dis.visit(ctx); - cc.renderer.pushRenderCommand(dis._renderCmd); - }; - - proto.rendering = function(ctx, scaleX, scaleY){ - var node = this._node; - var locChildren = node._children; - var alphaPremultiplied = cc.BlendFunc.ALPHA_PREMULTIPLIED, alphaNonPremultipled = cc.BlendFunc.ALPHA_NON_PREMULTIPLIED; - for (var i = 0, len = locChildren.length; i< len; i++) { - var selBone = locChildren[i]; - if (selBone && selBone.getDisplayRenderNode) { - var selNode = selBone.getDisplayRenderNode(); - if (null === selNode) - continue; - - switch (selBone.getDisplayRenderNodeType()) { - case ccs.DISPLAY_TYPE_SPRITE: - if(selNode instanceof ccs.Skin) - this.updateChildPosition(ctx, selNode, selBone, alphaPremultiplied, alphaNonPremultipled); - break; - case ccs.DISPLAY_TYPE_ARMATURE: - selNode._renderCmd.rendering(ctx, scaleX, scaleY); - break; - default: - selNode.visit(this); - break; - } - } else if(selBone instanceof cc.Node) { - this._visitNormalChild(selBone); - //selBone.visit(this); - } - } - }; - - proto._visitNormalChild = function(childNode){ - if(childNode == null) - return; - - var cmd = childNode._renderCmd; - // quick return if not visible - if (!childNode._visible) - return; - cmd._curLevel = this._curLevel + 1; - - //visit for canvas - var i, children = childNode._children, child; - cmd._syncStatus(this); - //because armature use transform, not setTransform - cmd.transform(null); - - var len = children.length; - if (len > 0) { - childNode.sortAllChildren(); - // draw children zOrder < 0 - for (i = 0; i < len; i++) { - child = children[i]; - if (child._localZOrder < 0) - child._renderCmd.visit(cmd); - else - break; - } - cc.renderer.pushRenderCommand(cmd); - for (; i < len; i++) - children[i]._renderCmd.visit(cmd); - } else { - cc.renderer.pushRenderCommand(cmd); - } - this._dirtyFlag = 0; - }; - - proto.visit = function(parentCmd){ - var node = this._node; - // quick return if not visible. children won't be drawn. - if (!node._visible) - return; - - this.updateStatus(parentCmd); - node.sortAllChildren(); - - cc.renderer.pushRenderCommand(this._startRenderCmd); - this.rendering(); - cc.renderer.pushRenderCommand(this._RestoreRenderCmd); - - this._cacheDirty = false; - }; })(); \ No newline at end of file diff --git a/extensions/cocostudio/armature/CCBone.js b/extensions/cocostudio/armature/CCBone.js index 8f116fa6e8..8923ba6bf5 100644 --- a/extensions/cocostudio/armature/CCBone.js +++ b/extensions/cocostudio/armature/CCBone.js @@ -630,9 +630,6 @@ ccs.Bone = ccs.Node.extend(/** @lends ccs.Bone# */{ }, _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) - return new ccs.Bone.CanvasRenderCmd(this); - else return new ccs.Bone.WebGLRenderCmd(this); } }); @@ -688,16 +685,6 @@ ccs.Bone.RenderCmd = { } }; -(function(){ - ccs.Bone.CanvasRenderCmd = function(renderable){ - cc.Node.CanvasRenderCmd.call(this, renderable); - this._needDraw = false; - }; - - var proto = ccs.Bone.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); - cc.inject(ccs.Bone.RenderCmd, proto); - proto.constructor = ccs.Bone.CanvasRenderCmd; -})(); (function(){ if(!cc.Node.WebGLRenderCmd) diff --git a/extensions/cocostudio/armature/display/CCSkin.js b/extensions/cocostudio/armature/display/CCSkin.js index 4553cf568b..617fd4f546 100644 --- a/extensions/cocostudio/armature/display/CCSkin.js +++ b/extensions/cocostudio/armature/display/CCSkin.js @@ -174,9 +174,6 @@ ccs.Skin = ccs.Sprite.extend(/** @lends ccs.Skin# */{ }, _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) - return new ccs.Skin.CanvasRenderCmd(this); - else return new ccs.Skin.WebGLRenderCmd(this); } }); diff --git a/extensions/cocostudio/timeline/CCBoneNode.js b/extensions/cocostudio/timeline/CCBoneNode.js index 2f6a95e1b0..e7df8d33f2 100644 --- a/extensions/cocostudio/timeline/CCBoneNode.js +++ b/extensions/cocostudio/timeline/CCBoneNode.js @@ -518,39 +518,6 @@ ccs.BoneNode = (function () { return new ccui.BoneNode(length, color); }; - var BoneNodeCanvasCmd = (function () { - - var BoneNodeCanvasCmd = function (node) { - Node.CanvasRenderCmd.call(this, node); - this._debug = false; - this._color = cc.color.WHITE; - this._drawNode = new cc.DrawNode(); - }; - - var proto = BoneNodeCanvasCmd.prototype = Object.create(Node.CanvasRenderCmd.prototype); - proto.constructor = BoneNodeCanvasCmd; - - proto.visit = function (parentCmd) { - var node = this._node; - node._visit && node._visit(parentCmd); - }; - proto.updateDebugPoint = function (points) { - this._drawNode.clear(); - this._drawNode.drawPoly(points, this._color, 0, this._color); - }; - - proto.transform = function (parentCmd, recursive) { - var rootSkeleton = this._node._rootSkeleton; - Node.CanvasRenderCmd.prototype.transform.call(this, parentCmd, recursive); - if (rootSkeleton && rootSkeleton._renderCmd._debug) { - this._drawNode._renderCmd.transform(this); - } - }; - - return BoneNodeCanvasCmd; - - })(); - var BoneNodeWebGLCmd = (function () { var BoneNodeWebGLCmd = function (node) { diff --git a/extensions/gui/scrollview/CCScrollView.js b/extensions/gui/scrollview/CCScrollView.js index 3aaeeb4ac0..ae7d178492 100644 --- a/extensions/gui/scrollview/CCScrollView.js +++ b/extensions/gui/scrollview/CCScrollView.js @@ -776,11 +776,8 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ }, _createRenderCmd: function(){ - if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) { - return new cc.ScrollView.CanvasRenderCmd(this); - } else { - return new cc.ScrollView.WebGLRenderCmd(this); - } + return new cc.ScrollView.WebGLRenderCmd(this); + } }); diff --git a/extensions/gui/scrollview/CCScrollViewCanvasRenderCmd.js b/extensions/gui/scrollview/CCScrollViewCanvasRenderCmd.js index 3fdc92851f..8b13789179 100644 --- a/extensions/gui/scrollview/CCScrollViewCanvasRenderCmd.js +++ b/extensions/gui/scrollview/CCScrollViewCanvasRenderCmd.js @@ -1,81 +1 @@ -/**************************************************************************** - Copyright (c) 2013-2014 Chukong Technologies Inc. - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -(function() { - cc.ScrollView.CanvasRenderCmd = function(renderable){ - cc.Layer.CanvasRenderCmd.call(this, renderable); - this._needDraw = false; - - this.startCmd = new cc.CustomRenderCmd(this, this._startCmd); - this.endCmd = new cc.CustomRenderCmd(this, this._endCmd); - }; - - var proto = cc.ScrollView.CanvasRenderCmd.prototype = Object.create(cc.Layer.CanvasRenderCmd.prototype); - proto.constructor = cc.ScrollView.CanvasRenderCmd; - - proto._startCmd = function(ctx, scaleX, scaleY){ - var node = this._node; - var wrapper = ctx || cc._renderContext, context = wrapper.getContext(); - wrapper.save(); - - if (node._clippingToBounds) { - this._scissorRestored = false; - wrapper.setTransform(this._worldTransform, scaleX, scaleY); - - var locScaleX = node.getScaleX(), locScaleY = node.getScaleY(); - - var getWidth = (node._viewSize.width * locScaleX) * scaleX; - var getHeight = (node._viewSize.height * locScaleY) * scaleY; - - context.beginPath(); - context.rect(0, 0, getWidth, -getHeight); - context.closePath(); - context.clip(); - } - }; - - proto._endCmd = function(wrapper){ - wrapper = wrapper || cc._renderContext; - wrapper.restore(); - }; - - proto.visit = function(parentCmd){ - var node = this._node; - if (!node._visible) return; - - var i, locChildren = node._children, childrenLen; - - this.transform(parentCmd); - cc.renderer.pushRenderCommand(this.startCmd); - - if (locChildren && locChildren.length > 0) { - childrenLen = locChildren.length; - node.sortAllChildren(); - for (i = 0; i < childrenLen; i++) { - locChildren[i]._renderCmd.visit(this); - } - } - cc.renderer.pushRenderCommand(this.endCmd); - }; -})(); diff --git a/extensions/spine/CCSkeleton.js b/extensions/spine/CCSkeleton.js index 9bab9e8d16..f49dc59cd8 100644 --- a/extensions/spine/CCSkeleton.js +++ b/extensions/spine/CCSkeleton.js @@ -93,9 +93,6 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ }, _createRenderCmd:function () { - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) - return new sp.Skeleton.CanvasRenderCmd(this); - else return new sp.Skeleton.WebGLRenderCmd(this); }, diff --git a/extensions/spine/CCSkeletonCanvasRenderCmd.js b/extensions/spine/CCSkeletonCanvasRenderCmd.js index 1b4f873cd1..e69de29bb2 100644 --- a/extensions/spine/CCSkeletonCanvasRenderCmd.js +++ b/extensions/spine/CCSkeletonCanvasRenderCmd.js @@ -1,213 +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. - ****************************************************************************/ - -(function(){ - sp.Skeleton.CanvasRenderCmd = function(renderableObject){ - cc.Node.CanvasRenderCmd.call(this, renderableObject); - this._needDraw = true; - }; - - var proto = sp.Skeleton.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); - proto.constructor = sp.Skeleton.CanvasRenderCmd; - - proto.rendering = function (wrapper, scaleX, scaleY) { - var node = this._node, i, n, slot, slotNode; - wrapper = wrapper || cc._renderContext; - - var locSkeleton = node._skeleton, drawOrder = locSkeleton.drawOrder; - for(i = 0, n = drawOrder.length; i < n; i++){ - slot = drawOrder[i]; - slotNode = slot._slotNode; - if(slotNode._visible && slotNode._renderCmd && slot.currentSprite){ - slotNode._renderCmd.transform(this, true); - slot.currentSprite._renderCmd.rendering(wrapper, scaleX, scaleY); - slotNode._renderCmd._dirtyFlag = slot.currentSprite._renderCmd._dirtyFlag = 0; - } - } - - if (!node._debugSlots && !node._debugBones) - return; - - wrapper.setTransform(this._worldTransform, scaleX, scaleY); - wrapper.setGlobalAlpha(1); - var attachment, drawingUtil = cc._drawingUtil; - if (node._debugSlots) { - // Slots. - drawingUtil.setDrawColor(0, 0, 255, 255); - drawingUtil.setLineWidth(1); - - var points = []; - for (i = 0, n = locSkeleton.slots.length; i < n; i++) { - slot = locSkeleton.drawOrder[i]; - if (!slot.attachment || slot.attachment.type != sp.ATTACHMENT_TYPE.REGION) - continue; - attachment = slot.attachment; - this._updateRegionAttachmentSlot(attachment, slot, points); - drawingUtil.drawPoly(points, 4, true); - } - } - - if (node._debugBones) { - // Bone lengths. - var bone; - drawingUtil.setLineWidth(2); - drawingUtil.setDrawColor(255, 0, 0, 255); - - for (i = 0, n = locSkeleton.bones.length; i < n; i++) { - bone = locSkeleton.bones[i]; - var x = bone.data.length * bone.m00 + bone.worldX; - var y = bone.data.length * bone.m10 + bone.worldY; - drawingUtil.drawLine( - {x: bone.worldX, y: bone.worldY}, - {x: x, y: y}); - } - - // Bone origins. - drawingUtil.setPointSize(4); - drawingUtil.setDrawColor(0, 0, 255, 255); // Root bone is blue. - - for (i = 0, n = locSkeleton.bones.length; i < n; i++) { - bone = locSkeleton.bones[i]; - drawingUtil.drawPoint({x: bone.worldX, y: bone.worldY}); - if (i === 0) - drawingUtil.setDrawColor(0, 255, 0, 255); - } - } - }; - - proto._updateRegionAttachmentSlot = function(attachment, slot, points) { - if(!points) - return; - - var vertices = {}, VERTEX = sp.VERTEX_INDEX, bone = slot.bone; - attachment.computeVertices(bone.skeleton.x, bone.skeleton.y, bone, vertices); - points.length = 0; - points.push(cc.p(vertices[VERTEX.X1], vertices[VERTEX.Y1])); - points.push(cc.p(vertices[VERTEX.X4], vertices[VERTEX.Y4])); - points.push(cc.p(vertices[VERTEX.X3], vertices[VERTEX.Y3])); - points.push(cc.p(vertices[VERTEX.X2], vertices[VERTEX.Y2])); - }; - - proto._createChildFormSkeletonData = function(){ - var node = this._node; - var locSkeleton = node._skeleton, spriteName, sprite; - for (var i = 0, n = locSkeleton.slots.length; i < n; i++) { - var slot = locSkeleton.slots[i], attachment = slot.attachment; - var slotNode = new cc.Node(); - slot._slotNode = slotNode; - - if(attachment instanceof spine.RegionAttachment){ - spriteName = attachment.rendererObject.name; - sprite = this._createSprite(slot, attachment); - slot.currentSprite = sprite; - slot.currentSpriteName = spriteName; - slotNode.addChild(sprite); - } else if(attachment instanceof spine.MeshAttachment){ - //todo for mesh - } - } - }; - - proto._createSprite = function(slot, attachment){ - var rendererObject = attachment.rendererObject; - var texture = rendererObject.page._texture; - var rect = new cc.Rect(rendererObject.x, rendererObject.y, rendererObject.width, rendererObject.height); - var sprite = new cc.Sprite(); - sprite.initWithTexture(rendererObject.page._texture, rect, rendererObject.rotate, false); - sprite._rect.width = attachment.width; - sprite._rect.height = attachment.height; - sprite.setContentSize(attachment.width, attachment.height); - sprite.setRotation(-attachment.rotation); - sprite.setScale(rendererObject.width / rendererObject.originalWidth * attachment.scaleX, - rendererObject.height / rendererObject.originalHeight * attachment.scaleY); - - slot.sprites = slot.sprites || {}; - slot.sprites[rendererObject.name] = sprite; - - return sprite; - }; - - proto._updateChild = function(){ - var locSkeleton = this._node._skeleton, slots = locSkeleton.slots; - var i, n, selSprite; - - var slot, attachment, slotNode; - for(i = 0, n = slots.length; i < n; i++){ - slot = slots[i]; - attachment = slot.attachment; - slotNode = slot._slotNode; - if(!attachment){ - slotNode.setVisible(false); - continue; - } - var type = attachment.type; - if (type === spine.AttachmentType.region){ - if(attachment.rendererObject){ - if(!slot.currentSpriteName || slot.currentSpriteName !== attachment.name){ - var spriteName = attachment.rendererObject.name; - if(slot.currentSprite !== undefined) - slot.currentSprite.setVisible(false); - slot.sprites = slot.sprites ||{}; - if(slot.sprites[spriteName] !== undefined) - slot.sprites[spriteName].setVisible(true); - else{ - var sprite = this._createSprite(slot, attachment); - slotNode.addChild(sprite); - } - slot.currentSprite = slot.sprites[spriteName]; - slot.currentSpriteName = spriteName; - } - } - var bone = slot.bone; - slotNode.setPosition(bone.worldX + attachment.x * bone.m00 + attachment.y * bone.m01, - bone.worldY + attachment.x * bone.m10 + attachment.y * bone.m11); - slotNode.setScale(bone.worldScaleX, bone.worldScaleY); - - //set the color and opacity - selSprite = slot.currentSprite; - selSprite._flippedX = bone.worldFlipX; - selSprite._flippedY = bone.worldFlipY; - if(selSprite._flippedY || selSprite._flippedX){ - slotNode.setRotation(bone.worldRotation); - selSprite.setRotation(attachment.rotation); - }else{ - slotNode.setRotation(-bone.worldRotation); - selSprite.setRotation(-attachment.rotation); - } - - //hack for sprite - selSprite._renderCmd._displayedOpacity = 0 | (locSkeleton.a * slot.a * 255); - var r = 0 | (locSkeleton.r * slot.r * 255), g = 0 | (locSkeleton.g * slot.g * 255), b = 0 | (locSkeleton.b * slot.b * 255); - selSprite.setColor(cc.color(r,g,b)); - selSprite._renderCmd._updateColor(); - } else if (type === spine.AttachmentType.skinnedmesh) { - //todo for mesh - } else { - slotNode.setVisible(false); - continue; - } - slotNode.setVisible(true); - } - }; -})(); \ No newline at end of file diff --git a/external/gaf/Library/GAFSprite.js b/external/gaf/Library/GAFSprite.js index 2387bf92df..15583a4338 100644 --- a/external/gaf/Library/GAFSprite.js +++ b/external/gaf/Library/GAFSprite.js @@ -92,9 +92,6 @@ gaf.Sprite = gaf.Object.extend }, _gafCreateRenderCmd: function(item){ - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) - return new gaf.Sprite.CanvasRenderCmd(item); - else return new gaf.Sprite.WebGLRenderCmd(item); } }); diff --git a/external/gaf/Library/GAFSpriteCanvasRenderCmd.js b/external/gaf/Library/GAFSpriteCanvasRenderCmd.js index bb807cc220..e69de29bb2 100644 --- a/external/gaf/Library/GAFSpriteCanvasRenderCmd.js +++ b/external/gaf/Library/GAFSpriteCanvasRenderCmd.js @@ -1,233 +0,0 @@ - -(function() { - gaf.Sprite.CanvasRenderCmd = function (renderable) { - cc.Sprite.CanvasRenderCmd.call(this, renderable); - this._hasTintMult = false; - this._hasTintOffset = false; - this._hasCtx = false; - this._tintMult = cc.color(255,255,255,255); - this._tintOffset = cc.color(0,0,0,0); - this._textureDirty = false; - }; - var proto = gaf.Sprite.CanvasRenderCmd.prototype = Object.create(cc.Sprite.CanvasRenderCmd.prototype); - proto.constructor = gaf.Sprite.CanvasRenderCmd; - - proto._disableCtx = function(){ - this._hasTintOffset = false; - this._hasCtx = false; - this._textureDirty = true; - this.setDirtyFlag(cc.Node._dirtyFlags.colorDirty); - this._tintMult = cc.color(255,255,255,255); - this._tintOffset = cc.color(0,0,0,0); - }; - - proto._enableCtx = function(){ - - }; - - proto._applyCtxState = function(gafObject){ - - var tintMult = gafObject._cascadeColorMult; - var tintOffset = gafObject._cascadeColorOffset; - var opacity = tintMult.a; - - // Apply opacity - if(this._node.getOpacity() != opacity) - { - this._node.setOpacity(opacity); - } - - // Check Tint multiplicator - var multDirty = !cc.colorEqual(this._tintMult, tintMult); - if(multDirty) - { - this._node.setColor(tintMult); - this._tintMult = tintMult; - this._hasTintMult = - (tintMult.r !== 255 || - tintMult.g !== 255 || - tintMult.b !== 255 ); - } - - // Check Tint offset - var offfsetDirty = - (this._tintOffset.r != tintOffset.r) || - (this._tintOffset.g != tintOffset.g) || - (this._tintOffset.b != tintOffset.b) || - (this._tintOffset.a != tintOffset.a); - - if(offfsetDirty) - { - this._tintOffset = tintOffset; - this._hasTintOffset = - (tintOffset.r !== 0 || - tintOffset.g !== 0 || - tintOffset.b !== 0 || - tintOffset.a !== 0 ); - } - - // Update dirty flag - this._textureDirty = multDirty || offfsetDirty; - if(this._textureDirty) - { - this.setDirtyFlag(cc.Node._dirtyFlags.colorDirty); - } - - - this._hasCtx = gafObject._filterStack.length > 0 && gafObject._filterStack[0].type === gaf.EFFECT_COLOR_MATRIX; - - }; - - proto.rendering = function(ctx, scaleX, scaleY) - { - var node = this._node; - var locTextureCoord = this._textureCoord, - alpha = (this._displayedOpacity / 255); - - if ((node._texture && ((locTextureCoord.width === 0 || locTextureCoord.height === 0) //set texture but the texture isn't loaded. - || !node._texture._textureLoaded)) || alpha === 0) - return; - - var wrapper = ctx || cc._renderContext, - context = wrapper.getContext(); - var locX = node._offsetPosition.x, - locHeight = node._rect.height, - locWidth = node._rect.width, - locY = -node._offsetPosition.y - locHeight, - image; - - wrapper.setTransform(this._worldTransform, scaleX, scaleY); - wrapper.setCompositeOperation(this._blendFuncStr); - wrapper.setGlobalAlpha(alpha); - - if(node._flippedX || node._flippedY) - wrapper.save(); - if (node._flippedX) { - locX = -locX - locWidth; - context.scale(-1, 1); - } - if (node._flippedY) { - locY = node._offsetPosition.y; - context.scale(1, -1); - } - - image = node._texture._htmlElementObj; - - if (this._colorized) { - context.drawImage(image, - 0, 0, locTextureCoord.width,locTextureCoord.height, - locX * scaleX,locY * scaleY, locWidth * scaleX, locHeight * scaleY); - } else { - context.drawImage(image, - locTextureCoord.renderX, locTextureCoord.renderY, locTextureCoord.width, locTextureCoord.height, - locX * scaleX, locY * scaleY, locWidth * scaleX, locHeight * scaleY); - } - - if(node._flippedX || node._flippedY) - wrapper.restore(); - cc.g_NumberOfDraws++; - }; - - if(cc.sys._supportCanvasNewBlendModes){ - proto._updateColor = function () { - var displayedColor = this._displayedColor, node = this._node; - this._hasTintMult |= (displayedColor.r !== 255 || displayedColor.g !== 255 || displayedColor.b !== 255); - - // If no color changes - if(this._textureDirty) - { - this._textureDirty = false; - if (this._colorized) { - this._colorized = false; - node.texture = this._originalTexture; - } - } - else - { - return; - } - - var locElement, locTexture = node._texture, locRect = this._textureCoord; - if(this._hasTintMult) - { - if (locTexture && locRect.validRect && this._originalTexture) { - locElement = locTexture.getHtmlElementObj(); - if (!locElement) - return; - - this._colorized = true; - if (this._hasTintOffset || this._hasCtx) displayedColor = this._tintMult; - - locElement = cc.Sprite.CanvasRenderCmd._generateTintImageWithMultiply(this._originalTexture._htmlElementObj, displayedColor, locRect); - locTexture = new cc.Texture2D(); - locTexture.initWithElement(locElement); - locTexture.handleLoadedTexture(); - node.texture = locTexture; - } - } - - locTexture = node._texture; - if(this._hasTintOffset) - { - var cacheTextureForColor = cc.textureCache.getTextureColors(this._originalTexture.getHtmlElementObj()); - if (locTexture && locRect.validRect && this._originalTexture) { - locElement = locTexture.getHtmlElementObj(); - if (!locElement) - return; - if(this._colorized) - var texRect = cc.rect(0,0,locRect.width, locRect.height); - else - texRect = locRect; - locElement = this._gafGenerateTintImage(node.texture._htmlElementObj, texRect, cacheTextureForColor, this._tintOffset, locRect); - locTexture = new cc.Texture2D(); - locTexture.initWithElement(locElement); - locTexture.handleLoadedTexture(); - node.texture = locTexture; - this._colorized = true; - } - } - - - }; - - proto._gafGenerateTintImage = function(texture, texRect, tintedImgCache, color, rect, renderCanvas){ - if (!rect) - rect = cc.rect(0, 0, texture.width, texture.height); - - // Create a new buffer if required - var w = Math.min(rect.width, tintedImgCache[0].width); - var h = Math.min(rect.height, tintedImgCache[0].height); - var buff = renderCanvas, ctx; - if (!buff) { - buff = document.createElement("canvas"); - buff.width = w; - buff.height = h; - ctx = buff.getContext("2d"); - } else { - ctx = buff.getContext("2d"); - ctx.clearRect(0, 0, w, h); - } - ctx.save(); - - // draw a channel with alpha of the original image - ctx.globalCompositeOperation = 'source-over'; - //ctx.globalAlpha = 1; - ctx.drawImage(tintedImgCache[2], rect.x, rect.y, w, h, 0, 0, w, h); - - // draw a rect of specified color - ctx.globalCompositeOperation = 'source-in'; - ctx.fillStyle = 'rgba(' + Math.round(color.r) + ',' + Math.round(color.g) + ',' + Math.round(color.b) + ',1)'; - ctx.fillRect(0, 0, w, h); - - // add the desired image to the drawn - ctx.globalCompositeOperation = 'lighter'; - ctx.drawImage(texture, texRect.x, texRect.y, w, h, 0, 0, w, h); - - - ctx.restore(); - return buff; - - }; - } - -})(); From a60e0605aea5b3ba7e01455155dce6e42f4f0fd6 Mon Sep 17 00:00:00 2001 From: Travis Gesslein Date: Wed, 2 Mar 2016 23:05:04 +0100 Subject: [PATCH 10/34] applying punishment to canvas --- cocos2d/core/platform/CCEGLView.js | 6 - cocos2d/core/platform/CCTypes.js | 10 +- cocos2d/core/textures/CCTexture2D.js | 501 +------------------ cocos2d/core/textures/CCTextureCache.js | 70 +-- cocos2d/text-input/CCTextFieldTTF.js | 2 - cocos2d/tilemap/CCTMXLayer.js | 7 - extensions/ccui/layouts/UILayout.js | 5 +- extensions/cocostudio/timeline/CCBoneNode.js | 3 - 8 files changed, 4 insertions(+), 600 deletions(-) diff --git a/cocos2d/core/platform/CCEGLView.js b/cocos2d/core/platform/CCEGLView.js index cc76c6fb54..1fe5e45a77 100644 --- a/cocos2d/core/platform/CCEGLView.js +++ b/cocos2d/core/platform/CCEGLView.js @@ -956,12 +956,6 @@ cc.ContentStrategy = cc.Class.extend(/** @lends cc.ContentStrategy# */{ Math.round((containerH - contentH) / 2), contentW, contentH); - // Translate the content - if (cc._renderType === cc.game.RENDER_TYPE_CANVAS){ - //TODO: modify something for setTransform - //cc._renderContext.translate(viewport.x, viewport.y + contentH); - } - this._result.scale = [scaleX, scaleY]; this._result.viewport = viewport; return this._result; diff --git a/cocos2d/core/platform/CCTypes.js b/cocos2d/core/platform/CCTypes.js index 99aa6e86fd..306c971ce3 100644 --- a/cocos2d/core/platform/CCTypes.js +++ b/cocos2d/core/platform/CCTypes.js @@ -394,12 +394,4 @@ cc.FontDefinition = function (properties) { 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 + "'"; -}; - -cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { - if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) { - cc.assert(cc.isFunction(cc._tmp.PrototypeColor), cc._LogInfos.MissingFile, "CCTypesPropertyDefine.js"); - cc._tmp.PrototypeColor(); - delete cc._tmp.PrototypeColor; - } -}); +}; \ No newline at end of file diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index 9cbf90e222..423b79de9b 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -98,506 +98,7 @@ cc.PVRHaveAlphaPremultiplied_ = false; cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) { - - var proto = { - _contentSize: null, - _textureLoaded: false, - _htmlElementObj: null, - url: null, - _pattern: null, - - ctor: function () { - this._contentSize = cc.size(0, 0); - this._textureLoaded = false; - this._htmlElementObj = null; - this._pattern = ""; - }, - - /** - * get width in pixels - * @return {Number} - */ - getPixelsWide: function () { - return this._contentSize.width; - }, - - /** - * get height of in pixels - * @return {Number} - */ - getPixelsHigh: function () { - return this._contentSize.height; - }, - - /** - * get content size - * @returns {cc.Size} - */ - getContentSize: function () { - var locScaleFactor = cc.contentScaleFactor(); - return cc.size(this._contentSize.width / locScaleFactor, this._contentSize.height / locScaleFactor); - }, - - _getWidth: function () { - return this._contentSize.width / cc.contentScaleFactor(); - }, - _getHeight: function () { - return this._contentSize.height / cc.contentScaleFactor(); - }, - - /** - * get content size in pixels - * @returns {cc.Size} - */ - getContentSizeInPixels: function () { - return this._contentSize; - }, - - /** - * init with HTML element - * @param {HTMLImageElement|HTMLCanvasElement} element - */ - initWithElement: function (element) { - if (!element) - return; - this._htmlElementObj = element; - this._contentSize.width = element.width; - this._contentSize.height = element.height; - this._textureLoaded = true; - }, - - /** - * HTMLElement Object getter - * @return {HTMLImageElement|HTMLCanvasElement} - */ - getHtmlElementObj: function () { - return this._htmlElementObj; - }, - - /** - * check whether texture is loaded - * @returns {boolean} - */ - isLoaded: function () { - return this._textureLoaded; - }, - - /** - * handle loaded texture - */ - handleLoadedTexture: function () { - var self = this; - if (self._textureLoaded) return; - if (!self._htmlElementObj) { - var img = cc.loader.getRes(self.url); - if (!img) return; - self.initWithElement(img); - } - - var locElement = self._htmlElementObj; - self._contentSize.width = locElement.width; - self._contentSize.height = locElement.height; - - //dispatch load event to listener. - self.dispatchEvent("load"); - }, - - /** - * description of cc.Texture2D - * @returns {string} - */ - description: function () { - return ""; - }, - - initWithData: function (data, pixelFormat, pixelsWide, pixelsHigh, contentSize) { - //support only in WebGl rendering mode - return false; - }, - - initWithImage: function (uiImage) { - //support only in WebGl rendering mode - return false; - }, - - initWithString: function (text, fontName, fontSize, dimensions, hAlignment, vAlignment) { - //support only in WebGl rendering mode - return false; - }, - - releaseTexture: function () { - cc.loader.release(this.url); - }, - - getName: function () { - //support only in WebGl rendering mode - return null; - }, - - getMaxS: function () { - //support only in WebGl rendering mode - return 1; - }, - - setMaxS: function (maxS) { - //support only in WebGl rendering mode - }, - - getMaxT: function () { - return 1; - }, - - setMaxT: function (maxT) { - //support only in WebGl rendering mode - }, - - getPixelFormat: function () { - //support only in WebGl rendering mode - return null; - }, - - getShaderProgram: function () { - //support only in WebGl rendering mode - return null; - }, - - setShaderProgram: function (shaderProgram) { - //support only in WebGl rendering mode - }, - - hasPremultipliedAlpha: function () { - //support only in WebGl rendering mode - return false; - }, - - hasMipmaps: function () { - //support only in WebGl rendering mode - return false; - }, - - releaseData: function (data) { - //support only in WebGl rendering mode - data = null; - }, - - keepData: function (data, length) { - //support only in WebGl rendering mode - return data; - }, - - drawAtPoint: function (point) { - //support only in WebGl rendering mode - }, - - drawInRect: function (rect) { - //support only in WebGl rendering mode - }, - - /** - * init with ETC file - * @warning does not support on HTML5 - */ - initWithETCFile: function (file) { - cc.log(cc._LogInfos.Texture2D_initWithETCFile); - return false; - }, - - /** - * init with PVR file - * @warning does not support on HTML5 - */ - initWithPVRFile: function (file) { - cc.log(cc._LogInfos.Texture2D_initWithPVRFile); - return false; - }, - - /** - * init with PVRTC data - * @warning does not support on HTML5 - */ - initWithPVRTCData: function (data, level, bpp, hasAlpha, length, pixelFormat) { - cc.log(cc._LogInfos.Texture2D_initWithPVRTCData); - return false; - }, - - setTexParameters: function (texParams, magFilter, wrapS, wrapT) { - if(magFilter !== undefined) - texParams = {minFilter: texParams, magFilter: magFilter, wrapS: wrapS, wrapT: wrapT}; - - if(texParams.wrapS === cc.REPEAT && texParams.wrapT === cc.REPEAT){ - this._pattern = "repeat"; - return; - } - - if(texParams.wrapS === cc.REPEAT ){ - this._pattern = "repeat-x"; - return; - } - - if(texParams.wrapT === cc.REPEAT){ - this._pattern = "repeat-y"; - return; - } - - this._pattern = ""; - }, - - setAntiAliasTexParameters: function () { - //support only in WebGl rendering mode - }, - - setAliasTexParameters: function () { - //support only in WebGl rendering mode - }, - - generateMipmap: function () { - //support only in WebGl rendering mode - }, - - stringForFormat: function () { - //support only in WebGl rendering mode - return ""; - }, - - bitsPerPixelForFormat: function (format) { - //support only in WebGl rendering mode - return -1; - }, - - /** - * add listener for loaded event - * @param {Function} callback - * @param {cc.Node} target - * @deprecated since 3.1, please use addEventListener instead - */ - addLoadedEventListener: function (callback, target) { - this.addEventListener("load", callback, target); - }, - - /** - * remove listener from listeners by target - * @param {cc.Node} target - */ - removeLoadedEventListener: function (target) { - this.removeEventListener("load", target); - }, - - _generateColorTexture: function(){/*overide*/}, - _generateTextureCacheForColor: function(){ - if (this.channelCache) - return this.channelCache; - - var textureCache = [ - document.createElement("canvas"), - document.createElement("canvas"), - document.createElement("canvas"), - document.createElement("canvas") - ]; - //todo texture onload - renderToCache(this._htmlElementObj, textureCache); - return this.channelCache = textureCache; - }, - - //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; - } - } - }; - - var renderToCache = function(image, cache){ - var w = image.width; - var h = image.height; - - cache[0].width = w; - cache[0].height = h; - cache[1].width = w; - cache[1].height = h; - cache[2].width = w; - cache[2].height = h; - cache[3].width = w; - cache[3].height = h; - - var cacheCtx = cache[3].getContext("2d"); - cacheCtx.drawImage(image, 0, 0); - var pixels = cacheCtx.getImageData(0, 0, w, h).data; - - var ctx; - for (var rgbI = 0; rgbI < 4; rgbI++) { - ctx = cache[rgbI].getContext("2d"); - - var to = ctx.getImageData(0, 0, w, h); - var data = to.data; - for (var i = 0; i < pixels.length; i += 4) { - data[i ] = (rgbI === 0) ? pixels[i ] : 0; - data[i + 1] = (rgbI === 1) ? pixels[i + 1] : 0; - data[i + 2] = (rgbI === 2) ? pixels[i + 2] : 0; - data[i + 3] = pixels[i + 3]; - } - ctx.putImageData(to, 0, 0); - } - image.onload = null; - }; - - //change color function - if(cc.sys._supportCanvasNewBlendModes){ - //multiply mode - //Primary afferent, Draw a new texture based on rect - proto._generateColorTexture = function(r, g, b, rect, canvas){ - var onlyCanvas = false; - if(canvas) - onlyCanvas = true; - else - canvas = document.createElement("canvas"); - var textureImage = this._htmlElementObj; - if(!rect) - rect = cc.rect(0, 0, textureImage.width, textureImage.height); - - canvas.width = rect.width; - canvas.height = rect.height; - - var context = canvas.getContext("2d"); - context.globalCompositeOperation = "source-over"; - context.fillStyle = "rgb(" + (r|0) + "," + (g|0) + "," + (b|0) + ")"; - context.fillRect(0, 0, rect.width, rect.height); - context.globalCompositeOperation = "multiply"; - context.drawImage( - textureImage, - rect.x, rect.y, rect.width, rect.height, - 0, 0, rect.width, rect.height - ); - context.globalCompositeOperation = "destination-atop"; - context.drawImage( - textureImage, - rect.x, rect.y, rect.width, rect.height, - 0, 0, rect.width, rect.height - ); - if(onlyCanvas) - return canvas; - var newTexture = new cc.Texture2D(); - newTexture.initWithElement(canvas); - newTexture.handleLoadedTexture(); - return newTexture; - }; - }else{ - //Four color map overlay - proto._generateColorTexture = function(r, g, b, rect, canvas){ - var onlyCanvas = false; - if(canvas) - onlyCanvas = true; - else - canvas = document.createElement("canvas"); - - var textureImage = this._htmlElementObj; - if(!rect) - rect = cc.rect(0, 0, textureImage.width, textureImage.height); - var x, y, w, h; - x = rect.x; y = rect.y; w = rect.width; h = rect.height; - if(!w || !h) - return; - - canvas.width = w; - canvas.height = h; - - var context = canvas.getContext("2d"); - var tintedImgCache = cc.textureCache.getTextureColors(this); - context.globalCompositeOperation = 'lighter'; - context.drawImage( - tintedImgCache[3], - x, y, w, h, - 0, 0, w, h - ); - if (r > 0) { - context.globalAlpha = r / 255; - context.drawImage( - tintedImgCache[0], - x, y, w, h, - 0, 0, w, h - ); - } - if (g > 0) { - context.globalAlpha = g / 255; - context.drawImage( - tintedImgCache[1], - x, y, w, h, - 0, 0, w, h - ); - } - if (b > 0) { - context.globalAlpha = b / 255; - context.drawImage( - tintedImgCache[2], - x, y, w, h, - 0, 0, w, h - ); - } - if(onlyCanvas) - return canvas; - - var newTexture = new cc.Texture2D(); - newTexture.initWithElement(canvas); - newTexture.handleLoadedTexture(); - return newTexture; - }; - } - - /** - *

- * This class allows to easily create OpenGL or Canvas 2D textures from images, text or raw data.
- * The created cc.Texture2D object will always have power-of-two dimensions.
- * Depending on how you create the cc.Texture2D object, the actual image area of the texture might be smaller than the texture dimensions
- * i.e. "contentSize" != (pixelsWide, pixelsHigh) and (maxS, maxT) != (1.0, 1.0).
- * Be aware that the content of the generated textures will be upside-down!

- * @name cc.Texture2D - * @class - * @extends cc.Class - * - * @property {WebGLTexture} name - <@readonly> WebGLTexture Object - * @property {Number} pixelFormat - <@readonly> Pixel format of the texture - * @property {Number} pixelsWidth - <@readonly> Width in pixels - * @property {Number} pixelsHeight - <@readonly> Height in pixels - * @property {Number} width - Content width in points - * @property {Number} height - Content height in points - * @property {cc.GLProgram} shaderProgram - The shader program used by drawAtPoint and drawInRect - * @property {Number} maxS - Texture max S - * @property {Number} maxT - Texture max T - */ - cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */proto); - - cc.Texture2D._generateGrayTexture = function(texture, rect, renderCanvas){ - if (texture === null) - return null; - renderCanvas = renderCanvas || document.createElement("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 if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { + if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { cc.assert(cc.isFunction(cc._tmp.WebGLTexture2D), cc._LogInfos.MissingFile, "TexturesWebGL.js"); cc._tmp.WebGLTexture2D(); delete cc._tmp.WebGLTexture2D; diff --git a/cocos2d/core/textures/CCTextureCache.js b/cocos2d/core/textures/CCTextureCache.js index 3e80519bb3..894ff62fa3 100644 --- a/cocos2d/core/textures/CCTextureCache.js +++ b/cocos2d/core/textures/CCTextureCache.js @@ -306,75 +306,7 @@ cc.textureCache = /** @lends cc.textureCache# */{ }; cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { - if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) { - - var _p = cc.textureCache; - - _p.handleLoadedTexture = function (url) { - var locTexs = this._textures; - //remove judge - var tex = locTexs[url]; - if (!tex) { - tex = locTexs[url] = new cc.Texture2D(); - tex.url = url; - } - tex.handleLoadedTexture(); - }; - - /** - *

Returns a Texture2D object given an file image
- * If the file image was not previously loaded, it will create a new Texture2D
- * object and it will return it. It will use the filename as a key.
- * Otherwise it will return a reference of a previously loaded image.
- * Supported image extensions: .png, .jpg, .gif

- * @param {String} url - * @param {Function} cb - * @param {Object} target - * @return {cc.Texture2D} - * @example - * //example - * cc.textureCache.addImage("hello.png"); - */ - _p.addImage = function (url, cb, target) { - - cc.assert(url, cc._LogInfos.Texture2D_addImage); - - var locTexs = this._textures; - //remove judge - var tex = locTexs[url] || locTexs[cc.loader._getAliase(url)]; - if (tex) { - if(tex.isLoaded()) { - cb && cb.call(target, tex); - return tex; - } - else - { - tex.addEventListener("load", function(){ - cb && cb.call(target, tex); - }, target); - return tex; - } - } - - tex = locTexs[url] = new cc.Texture2D(); - tex.url = url; - var loadFunc = cc.loader._checkIsImageURL(url) ? cc.loader.load : cc.loader.loadImg; - loadFunc.call(cc.loader, url, function (err, img) { - if (err) - return cb && cb.call(target, err); - cc.textureCache.handleLoadedTexture(url); - - var texResult = locTexs[url]; - cb && cb.call(target, texResult); - }); - - return tex; - }; - - _p.addImageAsync = _p.addImage; - _p = null; - - } else if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { + if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { cc.assert(cc.isFunction(cc._tmp.WebGLTextureCache), cc._LogInfos.MissingFile, "TexturesWebGL.js"); cc._tmp.WebGLTextureCache(); delete cc._tmp.WebGLTextureCache; diff --git a/cocos2d/text-input/CCTextFieldTTF.js b/cocos2d/text-input/CCTextFieldTTF.js index 716a85fbd9..e59dcb3515 100644 --- a/cocos2d/text-input/CCTextFieldTTF.js +++ b/cocos2d/text-input/CCTextFieldTTF.js @@ -257,8 +257,6 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ cc.LabelTTF.prototype.setString.call(this,this._inputText); this.setColor(this._colorText); } - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) - this._renderCmd._updateTexture(); this._charCount = this._inputText.length; }, diff --git a/cocos2d/tilemap/CCTMXLayer.js b/cocos2d/tilemap/CCTMXLayer.js index cb9afecca6..a581e24999 100644 --- a/cocos2d/tilemap/CCTMXLayer.js +++ b/cocos2d/tilemap/CCTMXLayer.js @@ -493,8 +493,6 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ var gid = this.getTileGIDAt(pos); if (gid !== 0) { - if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) - this._setNodeDirtyForCache(); var z = 0 | (pos.x + pos.y * this._layerSize.width); var atlasIndex = this._atlasIndexForExistantZ(z); // remove tile from GID map @@ -572,8 +570,6 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ // Parse cocos2d properties this._parseInternalProperties(); - if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) - this._setNodeDirtyForCache(); var locLayerHeight = this._layerSize.height, locLayerWidth = this._layerSize.width; for (var y = 0; y < locLayerHeight; y++) { @@ -621,9 +617,6 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ cc.log("cc.TMXLayer.removeChild(): Tile does not belong to TMXLayer"); return; } - - if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) - this._setNodeDirtyForCache(); var atlasIndex = sprite.atlasIndex; var zz = this._atlasIndexArray[atlasIndex]; this.tiles[zz] = 0; diff --git a/extensions/ccui/layouts/UILayout.js b/extensions/ccui/layouts/UILayout.js index cc27cf32c2..5fc3473366 100644 --- a/extensions/ccui/layouts/UILayout.js +++ b/extensions/ccui/layouts/UILayout.js @@ -369,10 +369,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ setClippingType: function (type) { if (type === this._clippingType) return; - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS && type === ccui.Layout.CLIPPING_SCISSOR){ - cc.log("Only supports STENCIL on canvas mode."); - return; - } + var clippingEnabled = this.isClippingEnabled(); this.setClippingEnabled(false); this._clippingType = type; diff --git a/extensions/cocostudio/timeline/CCBoneNode.js b/extensions/cocostudio/timeline/CCBoneNode.js index e7df8d33f2..9d7d5d2a68 100644 --- a/extensions/cocostudio/timeline/CCBoneNode.js +++ b/extensions/cocostudio/timeline/CCBoneNode.js @@ -504,9 +504,6 @@ ccs.BoneNode = (function () { }, _createRenderCmd: function () { - if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) - return new BoneNodeCanvasCmd(this); - else return new BoneNodeWebGLCmd(this); } }); From 319b04ab215bdcadac18b818eddac9c44f6976a0 Mon Sep 17 00:00:00 2001 From: Travis Gesslein Date: Thu, 3 Mar 2016 02:32:39 +0100 Subject: [PATCH 11/34] bombarded the GAF stuff from orbit --- 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 | 97 ---- 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.js | 219 ------- 20 files changed, 3156 deletions(-) diff --git a/external/gaf/GAFBoot.js b/external/gaf/GAFBoot.js index 0baccc7ecd..e69de29bb2 100644 --- a/external/gaf/GAFBoot.js +++ b/external/gaf/GAFBoot.js @@ -1,24 +0,0 @@ -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 index ef34cc8f5d..e69de29bb2 100644 --- a/external/gaf/GAFMacros.js +++ b/external/gaf/GAFMacros.js @@ -1,33 +0,0 @@ -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 index 23804e61ff..e69de29bb2 100644 --- a/external/gaf/Library/GAFAsset.js +++ b/external/gaf/Library/GAFAsset.js @@ -1,429 +0,0 @@ -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 index 8514e09f2d..e69de29bb2 100644 --- a/external/gaf/Library/GAFAssetPreload.js +++ b/external/gaf/Library/GAFAssetPreload.js @@ -1,270 +0,0 @@ - -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 index 152bba0788..e69de29bb2 100644 --- a/external/gaf/Library/GAFAtlasLoader.js +++ b/external/gaf/Library/GAFAtlasLoader.js @@ -1,50 +0,0 @@ -/** - * 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 index 3affbe1335..e69de29bb2 100644 --- a/external/gaf/Library/GAFDataReader.js +++ b/external/gaf/Library/GAFDataReader.js @@ -1,229 +0,0 @@ -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 index 3e40c33947..e69de29bb2 100644 --- a/external/gaf/Library/GAFLoader.js +++ b/external/gaf/Library/GAFLoader.js @@ -1,75 +0,0 @@ -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 index 34ca20681c..e69de29bb2 100644 --- a/external/gaf/Library/GAFMask.js +++ b/external/gaf/Library/GAFMask.js @@ -1,36 +0,0 @@ - -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 index 6074fd1279..e69de29bb2 100644 --- a/external/gaf/Library/GAFMaskProto.js +++ b/external/gaf/Library/GAFMaskProto.js @@ -1,16 +0,0 @@ - -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 index 7d5375abe5..e69de29bb2 100644 --- a/external/gaf/Library/GAFObject.js +++ b/external/gaf/Library/GAFObject.js @@ -1,426 +0,0 @@ -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 index 49b7ffba0f..e69de29bb2 100644 --- a/external/gaf/Library/GAFShaderManager.js +++ b/external/gaf/Library/GAFShaderManager.js @@ -1,63 +0,0 @@ - -gaf._glShaderInit = function() { - gaf._Uniforms = { - ColorTransformMult: -1, - ColorTransformOffset: -1, - ColorMatrixBody: -1, - ColorMatrixAppendix: -1, - BlurTexelOffset: -1, - GlowTexelOffset: -1, - GlowColor: -1 - }; - - gaf._shaderCreate = function (fs, vs) { - var program = new cc.GLProgram(); - var result = program.initWithVertexShaderByteArray(vs, fs); - cc.assert(result, "Shader init error"); - program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION); - program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR); - program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS); - result = program.link(); - cc.assert(result, "Shader linking error"); - program.updateUniforms(); - return program; - }; - - gaf._shaderCreateAlpha = function () { - var program = gaf._shaderCreate(gaf.SHADER_COLOR_MATRIX_FRAG, cc.SHADER_POSITION_TEXTURE_COLOR_VERT); - gaf._Uniforms.ColorTransformMult = program.getUniformLocationForName(gaf.UNIFORM_ALPHA_TINT_MULT); - gaf._Uniforms.ColorTransformOffset = program.getUniformLocationForName(gaf.UNIFORM_ALPHA_TINT_OFFSET); - gaf._Uniforms.ColorMatrixBody = program.getUniformLocationForName(gaf.UNIFORM_ALPHA_COLOR_MATRIX_BODY); - gaf._Uniforms.ColorMatrixAppendix = program.getUniformLocationForName(gaf.UNIFORM_ALPHA_COLOR_MATRIX_APPENDIX); - return program; - }; - - gaf._shaderCreateBlur = function () { - var program = gaf._shaderCreate(gaf.SHADER_GAUSSIAN_BLUR_FRAG, cc.SHADER_POSITION_TEXTURE_COLOR_VERT); - gaf._Uniforms.BlurTexelOffset = program._glContext.getUniformLocation(program._programObj, gaf.UNIFORM_BLUR_TEXEL_OFFSET); - - return program; - }; - - gaf._shaderCreateGlow = function () { - var program = gaf._shaderCreate(gaf.SHADER_GLOW_FRAG, cc.SHADER_POSITION_TEXTURE_COLOR_VERT); - gaf._Uniforms.GlowTexelOffset = program._glContext.getUniformLocation(program._programObj, gaf.UNIFORM_GLOW_TEXEL_OFFSET); - gaf._Uniforms.GlowColor = program._glContext.getUniformLocation(program._programObj, gaf.UNIFORM_GLOW_COLOR); - return program; - }; - - gaf._Shaders = { - Alpha: gaf._shaderCreateAlpha(), - Blur: gaf._shaderCreateBlur(), - Glow: gaf._shaderCreateGlow() - }; -}; - -gaf._setupShaders = function() { - if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { - gaf._glShaderInit(); - } - else { - delete gaf._glShaderInit; - } -}; diff --git a/external/gaf/Library/GAFShaders.js b/external/gaf/Library/GAFShaders.js index 7d91537285..e69de29bb2 100644 --- a/external/gaf/Library/GAFShaders.js +++ b/external/gaf/Library/GAFShaders.js @@ -1,58 +0,0 @@ -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 index 15583a4338..e69de29bb2 100644 --- a/external/gaf/Library/GAFSprite.js +++ b/external/gaf/Library/GAFSprite.js @@ -1,97 +0,0 @@ - -gaf.Sprite = gaf.Object.extend -({ - _className: "GAFSprite", - - _hasCtx: false, - _hasFilter: false, - - ctor : function(gafSpriteProto, usedScale) - { - this._super(usedScale); - cc.assert(gafSpriteProto, "Error! Missing mandatory parameter."); - this._gafproto = gafSpriteProto; - }, - - // Private - - _init : function() - { - var frame = this._gafproto.getFrame(); - cc.assert(frame instanceof cc.SpriteFrame, "Error. Wrong object type."); - - // Create sprite with custom render command from frame - this._sprite = new cc.Sprite(); - this._sprite._renderCmd = this._gafCreateRenderCmd(this._sprite); - this._sprite.initWithSpriteFrame(frame); - - this._sprite.setAnchorPoint(this._gafproto.getAnchor()); - this.addChild(this._sprite); - //this._sprite.setCascadeColorEnabled(true); - //this._sprite.setCascadeOpacityEnabled(true); - this._sprite.setOpacityModifyRGB(true); - - if(cc._renderType === cc.game.RENDER_TYPE_WEBGL) - this._sprite.setBlendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); - }, - - _applyState : function(state, parent) - { - this._applyStateSuper(state, parent); - if(this._needsCtx) - { - // Enable ctx state if wasn't enabled - if(!this._hasCtx) - { - this._enableCtx(); - this._hasCtx = true; - } - // Set ctx shader - this._applyCtxState(state); - } - else - { - // Disable ctx state if was enabled - if(this._hasCtx) - { - this._disableCtx(); - this._hasCtx = false; - } - // Apply color - if(!cc.colorEqual(this._sprite._realColor, this._cascadeColorMult)) - { - this._sprite.setColor(this._cascadeColorMult); - } - // Apply opacity - if(this._sprite.getOpacity() != this._cascadeColorMult.a) - { - this._sprite.setOpacity(this._cascadeColorMult.a); - } - - } - }, - - _enableCtx: function() - { - this._sprite._renderCmd._enableCtx(); - }, - - _disableCtx: function() - { - this._sprite._renderCmd._disableCtx(); - }, - - _applyCtxState: function(state){ - this._sprite._renderCmd._applyCtxState(this); - }, - - getBoundingBoxForCurrentFrame: function () - { - var result = this._sprite.getBoundingBox(); - return cc._rectApplyAffineTransformIn(result, this.getNodeToParentTransform()); - }, - - _gafCreateRenderCmd: function(item){ - return new gaf.Sprite.WebGLRenderCmd(item); - } -}); diff --git a/external/gaf/Library/GAFSpriteProto.js b/external/gaf/Library/GAFSpriteProto.js index 6e33fa7d5f..e69de29bb2 100644 --- a/external/gaf/Library/GAFSpriteProto.js +++ b/external/gaf/Library/GAFSpriteProto.js @@ -1,36 +0,0 @@ - -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 index eabe25b0c9..e69de29bb2 100644 --- a/external/gaf/Library/GAFSpriteWebGLRenderCmd.js +++ b/external/gaf/Library/GAFSpriteWebGLRenderCmd.js @@ -1,132 +0,0 @@ - -(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 index 09f8186538..e69de29bb2 100644 --- a/external/gaf/Library/GAFTags.js +++ b/external/gaf/Library/GAFTags.js @@ -1,378 +0,0 @@ - -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 index 04f9744920..e69de29bb2 100644 --- a/external/gaf/Library/GAFTextField.js +++ b/external/gaf/Library/GAFTextField.js @@ -1,6 +0,0 @@ - -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 index ef9387aa46..e69de29bb2 100644 --- a/external/gaf/Library/GAFTimeLine.js +++ b/external/gaf/Library/GAFTimeLine.js @@ -1,547 +0,0 @@ - -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 index 9d78b219d9..e69de29bb2 100644 --- a/external/gaf/Library/GAFTimeLineProto.js +++ b/external/gaf/Library/GAFTimeLineProto.js @@ -1,32 +0,0 @@ - -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.js b/external/gaf/gaf_viewer.js index db5bdbea7f..e69de29bb2 100644 --- a/external/gaf/gaf_viewer.js +++ b/external/gaf/gaf_viewer.js @@ -1,219 +0,0 @@ - /* - * 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 From 8c0375abeac24b3cccaf4f31743b0fbc19efe457 Mon Sep 17 00:00:00 2001 From: Travis Gesslein Date: Thu, 3 Mar 2016 02:40:10 +0100 Subject: [PATCH 12/34] removed more --- extensions/spine/CCSkeleton.js | 402 - extensions/spine/CCSkeletonAnimation.js | 348 - extensions/spine/CCSkeletonWebGLRenderCmd.js | 260 - extensions/spine/Spine.js | 2731 ------- external/socketio/socket.io.js | 7000 ------------------ external/socketio/socket.io.min.js | 3 - 6 files changed, 10744 deletions(-) diff --git a/extensions/spine/CCSkeleton.js b/extensions/spine/CCSkeleton.js index f49dc59cd8..e69de29bb2 100644 --- a/extensions/spine/CCSkeleton.js +++ b/extensions/spine/CCSkeleton.js @@ -1,402 +0,0 @@ -/**************************************************************************** - Copyright (c) 2011-2012 cocos2d-x.org - Copyright (c) 2013-2014 Chukong Technologies Inc. - Copyright (c) 2014 Shengxiang Chen (Nero Chan) - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -/** - * The main namespace of Spine, all classes, functions, properties and constants of Spine are defined in this namespace - * @namespace - * @name sp - */ -var sp = sp || {}; - -/** - * The vertex index of spine. - * @constant - * @type {{X1: number, Y1: number, X2: number, Y2: number, X3: number, Y3: number, X4: number, Y4: number}} - */ -sp.VERTEX_INDEX = { - X1: 0, - Y1: 1, - X2: 2, - Y2: 3, - X3: 4, - Y3: 5, - X4: 6, - Y4: 7 -}; - -/** - * The attachment type of spine. It contains three type: REGION(0), BOUNDING_BOX(1), MESH(2) and SKINNED_MESH. - * @constant - * @type {{REGION: number, BOUNDING_BOX: number, REGION_SEQUENCE: number, MESH: number}} - */ -sp.ATTACHMENT_TYPE = { - REGION: 0, - BOUNDING_BOX: 1, - MESH: 2, - SKINNED_MESH:3 -}; - -/** - *

- * The skeleton of Spine.
- * Skeleton has a reference to a SkeletonData and stores the state for skeleton instance, - * which consists of the current pose's bone SRT, slot colors, and which slot attachments are visible.
- * Multiple skeletons can use the same SkeletonData (which includes all animations, skins, and attachments).
- *

- * @class - * @extends cc.Node - */ -sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ - _skeleton: null, - _rootBone: null, - _timeScale: 1, - _debugSlots: false, - _debugBones: false, - _premultipliedAlpha: false, - _ownsSkeletonData: null, - _atlas: null, - _blendFunc: null, - - /** - * The constructor of sp.Skeleton. override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. - */ - ctor:function(skeletonDataFile, atlasFile, scale){ - cc.Node.prototype.ctor.call(this); - - if(arguments.length === 0) - this.init(); - else - this.initWithArgs(skeletonDataFile, atlasFile, scale); - }, - - _createRenderCmd:function () { - return new sp.Skeleton.WebGLRenderCmd(this); - }, - - /** - * Initializes a sp.Skeleton. please do not call this function by yourself, you should pass the parameters to constructor to initialize it. - */ - init: function () { - cc.Node.prototype.init.call(this); - this._premultipliedAlpha = (cc._renderType === cc.game.RENDER_TYPE_WEBGL && cc.OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA); - this._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST}; - this.scheduleUpdate(); - }, - - /** - * Sets whether open debug slots. - * @param {boolean} enable true to open, false to close. - */ - setDebugSolots:function(enable){ - this._debugSlots = enable; - }, - - /** - * Sets whether open debug bones. - * @param {boolean} enable - */ - setDebugBones:function(enable){ - this._debugBones = enable; - }, - - /** - * Sets whether open debug slots. - * @param {boolean} enabled true to open, false to close. - */ - setDebugSlotsEnabled: function(enabled) { - this._debugSlots = enabled; - }, - - /** - * Gets whether open debug slots. - * @returns {boolean} true to open, false to close. - */ - getDebugSlotsEnabled: function() { - return this._debugSlots; - }, - - /** - * Sets whether open debug bones. - * @param {boolean} enabled - */ - setDebugBonesEnabled: function(enabled) { - this._debugBones = enabled; - }, - - /** - * Gets whether open debug bones. - * @returns {boolean} true to open, false to close. - */ - getDebugBonesEnabled: function() { - return this._debugBones; - }, - - /** - * Sets the time scale of sp.Skeleton. - * @param {Number} scale - */ - setTimeScale:function(scale){ - this._timeScale = scale; - }, - - getTimeScale: function(){ - return this._timeScale; - }, - - /** - * Initializes sp.Skeleton with Data. - * @param {spine.SkeletonData|String} skeletonDataFile - * @param {String|spine.Atlas|spine.SkeletonData} atlasFile atlas filename or atlas data or owns SkeletonData - * @param {Number} [scale] scale can be specified on the JSON or binary loader which will scale the bone positions, image sizes, and animation translations. - */ - initWithArgs: function (skeletonDataFile, atlasFile, scale) { - var argSkeletonFile = skeletonDataFile, argAtlasFile = atlasFile, - skeletonData, atlas, ownsSkeletonData; - - if (cc.isString(argSkeletonFile)) { - if (cc.isString(argAtlasFile)) { - var data = cc.loader.getRes(argAtlasFile); - sp._atlasLoader.setAtlasFile(argAtlasFile); - atlas = new spine.Atlas(data, sp._atlasLoader); - } else { - atlas = atlasFile; - } - scale = scale || 1 / cc.director.getContentScaleFactor(); - - var attachmentLoader = new spine.AtlasAttachmentLoader(atlas); - var skeletonJsonReader = new spine.SkeletonJson(attachmentLoader); - skeletonJsonReader.scale = scale; - - var skeletonJson = cc.loader.getRes(argSkeletonFile); - skeletonData = skeletonJsonReader.readSkeletonData(skeletonJson); - atlas.dispose(skeletonJsonReader); - ownsSkeletonData = true; - } else { - skeletonData = skeletonDataFile; - ownsSkeletonData = atlasFile; - } - this.setSkeletonData(skeletonData, ownsSkeletonData); - this.init(); - }, - - /** - * Returns the bounding box of sp.Skeleton. - * @returns {cc.Rect} - */ - getBoundingBox: function () { - var minX = cc.FLT_MAX, minY = cc.FLT_MAX, maxX = cc.FLT_MIN, maxY = cc.FLT_MIN; - var scaleX = this.getScaleX(), scaleY = this.getScaleY(), vertices = [], - slots = this._skeleton.slots, VERTEX = sp.VERTEX_INDEX; - - for (var i = 0, slotCount = slots.length; i < slotCount; ++i) { - var slot = slots[i]; - if (!slot.attachment || slot.attachment.type != sp.ATTACHMENT_TYPE.REGION) - continue; - var attachment = slot.attachment; - this._computeRegionAttachmentWorldVertices(attachment, slot.bone.skeleton.x, slot.bone.skeleton.y, slot.bone, vertices); - minX = Math.min(minX, vertices[VERTEX.X1] * scaleX, vertices[VERTEX.X4] * scaleX, vertices[VERTEX.X2] * scaleX, vertices[VERTEX.X3] * scaleX); - minY = Math.min(minY, vertices[VERTEX.Y1] * scaleY, vertices[VERTEX.Y4] * scaleY, vertices[VERTEX.Y2] * scaleY, vertices[VERTEX.Y3] * scaleY); - maxX = Math.max(maxX, vertices[VERTEX.X1] * scaleX, vertices[VERTEX.X4] * scaleX, vertices[VERTEX.X2] * scaleX, vertices[VERTEX.X3] * scaleX); - maxY = Math.max(maxY, vertices[VERTEX.Y1] * scaleY, vertices[VERTEX.Y4] * scaleY, vertices[VERTEX.Y2] * scaleY, vertices[VERTEX.Y3] * scaleY); - } - var position = this.getPosition(); - return cc.rect(position.x + minX, position.y + minY, maxX - minX, maxY - minY); - }, - - _computeRegionAttachmentWorldVertices : function(self, x, y, bone, vertices){ - var offset = self.offset, vertexIndex = sp.VERTEX_INDEX; - x += bone.worldX; - y += bone.worldY; - vertices[vertexIndex.X1] = offset[vertexIndex.X1] * bone.m00 + offset[vertexIndex.Y1] * bone.m01 + x; - vertices[vertexIndex.Y1] = offset[vertexIndex.X1] * bone.m10 + offset[vertexIndex.Y1] * bone.m11 + y; - vertices[vertexIndex.X2] = offset[vertexIndex.X2] * bone.m00 + offset[vertexIndex.Y2] * bone.m01 + x; - vertices[vertexIndex.Y2] = offset[vertexIndex.X2] * bone.m10 + offset[vertexIndex.Y2] * bone.m11 + y; - vertices[vertexIndex.X3] = offset[vertexIndex.X3] * bone.m00 + offset[vertexIndex.Y3] * bone.m01 + x; - vertices[vertexIndex.Y3] = offset[vertexIndex.X3] * bone.m10 + offset[vertexIndex.Y3] * bone.m11 + y; - vertices[vertexIndex.X4] = offset[vertexIndex.X4] * bone.m00 + offset[vertexIndex.Y4] * bone.m01 + x; - vertices[vertexIndex.Y4] = offset[vertexIndex.X4] * bone.m10 + offset[vertexIndex.Y4] * bone.m11 + y; - }, - - /** - * Computes the world SRT from the local SRT for each bone. - */ - updateWorldTransform: function () { - this._skeleton.updateWorldTransform(); - }, - - /** - * Sets the bones and slots to the setup pose. - */ - setToSetupPose: function () { - this._skeleton.setToSetupPose(); - }, - - /** - * Sets the bones to the setup pose, using the values from the `BoneData` list in the `SkeletonData`. - */ - setBonesToSetupPose: function () { - this._skeleton.setBonesToSetupPose(); - }, - - /** - * Sets the slots to the setup pose, using the values from the `SlotData` list in the `SkeletonData`. - */ - setSlotsToSetupPose: function () { - this._skeleton.setSlotsToSetupPose(); - }, - - /** - * Finds a bone by name. This does a string comparison for every bone. - * @param {String} boneName - * @returns {spine.Bone} - */ - findBone: function (boneName) { - return this._skeleton.findBone(boneName); - }, - - /** - * Finds a slot by name. This does a string comparison for every slot. - * @param {String} slotName - * @returns {spine.Slot} - */ - findSlot: function (slotName) { - return this._skeleton.findSlot(slotName); - }, - - /** - * Finds a skin by name and makes it the active skin. This does a string comparison for every skin. Note that setting the skin does not change which attachments are visible. - * @param {string} skinName - * @returns {spine.Skin} - */ - setSkin: function (skinName) { - return this._skeleton.setSkinByName(skinName); - }, - - /** - * Returns the attachment for the slot and attachment name. The skeleton looks first in its skin, then in the skeleton data’s default skin. - * @param {String} slotName - * @param {String} attachmentName - * @returns {spine.RegionAttachment|spine.BoundingBoxAttachment} - */ - getAttachment: function (slotName, attachmentName) { - return this._skeleton.getAttachmentBySlotName(slotName, attachmentName); - }, - - /** - * Sets the attachment for the slot and attachment name. The skeleton looks first in its skin, then in the skeleton data’s default skin. - * @param {String} slotName - * @param {String} attachmentName - */ - setAttachment: function (slotName, attachmentName) { - this._skeleton.setAttachment(slotName, attachmentName); - }, - - /** - * Sets the premultiplied alpha value to sp.Skeleton. - * @param {Number} alpha - */ - setPremultipliedAlpha: function (premultiplied) { - this._premultipliedAlpha = premultiplied; - }, - - /** - * Returns whether to enable premultiplied alpha. - * @returns {boolean} - */ - isPremultipliedAlpha: function () { - return this._premultipliedAlpha; - }, - - /** - * Sets skeleton data to sp.Skeleton. - * @param {spine.SkeletonData} skeletonData - * @param {spine.SkeletonData} ownsSkeletonData - */ - setSkeletonData: function (skeletonData, ownsSkeletonData) { - if(skeletonData.width != null && skeletonData.height != null) - this.setContentSize(skeletonData.width / cc.director.getContentScaleFactor(), skeletonData.height / cc.director.getContentScaleFactor()); - - this._skeleton = new spine.Skeleton(skeletonData); - this._skeleton.updateWorldTransform(); - this._rootBone = this._skeleton.getRootBone(); - this._ownsSkeletonData = ownsSkeletonData; - - this._renderCmd._createChildFormSkeletonData(); - }, - - /** - * Return the renderer of attachment. - * @param {spine.RegionAttachment|spine.BoundingBoxAttachment} regionAttachment - * @returns {cc.Node} - */ - getTextureAtlas: function (regionAttachment) { - return regionAttachment.rendererObject.page.rendererObject; - }, - - /** - * Returns the blendFunc of sp.Skeleton. - * @returns {cc.BlendFunc} - */ - getBlendFunc: function () { - return this._blendFunc; - }, - - /** - * Sets the blendFunc of sp.Skeleton. - * @param {cc.BlendFunc|Number} src - * @param {Number} [dst] - */ - setBlendFunc: function (src, dst) { - var locBlendFunc = this._blendFunc; - if (dst === undefined) { - locBlendFunc.src = src.src; - locBlendFunc.dst = src.dst; - } else { - locBlendFunc.src = src; - locBlendFunc.dst = dst; - } - }, - - /** - * Update will be called automatically every frame if "scheduleUpdate" is called when the node is "live". - * @param {Number} dt Delta time since last update - */ - update: function (dt) { - this._skeleton.update(dt); - } -}); - -/** - * Creates a skeleton object. - * @deprecated since v3.0, please use new sp.Skeleton(skeletonDataFile, atlasFile, scale) instead. - * @param {spine.SkeletonData|String} skeletonDataFile - * @param {String|spine.Atlas|spine.SkeletonData} atlasFile atlas filename or atlas data or owns SkeletonData - * @param {Number} [scale] scale can be specified on the JSON or binary loader which will scale the bone positions, image sizes, and animation translations. - * @returns {sp.Skeleton} - */ -sp.Skeleton.create = function (skeletonDataFile, atlasFile/* or atlas*/, scale) { - return new sp.Skeleton(skeletonDataFile, atlasFile, scale); -}; diff --git a/extensions/spine/CCSkeletonAnimation.js b/extensions/spine/CCSkeletonAnimation.js index f78d56cc89..e69de29bb2 100644 --- a/extensions/spine/CCSkeletonAnimation.js +++ b/extensions/spine/CCSkeletonAnimation.js @@ -1,348 +0,0 @@ -/**************************************************************************** - Copyright (c) 2011-2012 cocos2d-x.org - Copyright (c) 2013-2014 Chukong Technologies Inc. - Copyright (c) 2014 Shengxiang Chen (Nero Chan) - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -/** - * @ignore - */ -sp._atlasPage_createTexture_webGL = function (self, path) { - var texture = cc.textureCache.addImage(path); - self.rendererObject = new cc.TextureAtlas(texture, 128); - self.width = texture.getPixelsWide(); - self.height = texture.getPixelsHigh(); -}; - -sp._atlasPage_createTexture_canvas = function(self, path) { - self._texture = cc.textureCache.addImage(path); -}; - -sp._atlasPage_disposeTexture = function (self) { - self.rendererObject.release(); -}; - -sp._atlasLoader = { - spAtlasFile:null, - setAtlasFile:function(spAtlasFile){ - this.spAtlasFile = spAtlasFile; - }, - load:function(page, line, spAtlas){ - var texturePath = cc.path.join(cc.path.dirname(this.spAtlasFile), line); - if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) - sp._atlasPage_createTexture_webGL(page,texturePath); - else - sp._atlasPage_createTexture_canvas(page,texturePath); - }, - unload:function(obj){ - } -}; - -/** - * The event type of spine skeleton animation. It contains event types: START(0), END(1), COMPLETE(2), EVENT(3). - * @constant - * @type {{START: number, END: number, COMPLETE: number, EVENT: number}} - */ -sp.ANIMATION_EVENT_TYPE = { - START: 0, - END: 1, - COMPLETE: 2, - EVENT: 3 -}; - -sp.TrackEntryListeners = function(startListener, endListener, completeListener, eventListener){ - this.startListener = startListener || null; - this.endListener = endListener || null; - this.completeListener = completeListener || null; - this.eventListener = eventListener || null; -}; - -sp.TrackEntryListeners.getListeners = function(entry){ - if(!entry.rendererObject){ - entry.rendererObject = new sp.TrackEntryListeners(); - entry.listener = sp.trackEntryCallback; - } - return entry.rendererObject; -}; - -sp.trackEntryCallback = function(state, trackIndex, type, event, loopCount) { - state.rendererObject.onTrackEntryEvent(trackIndex, type, event, loopCount); -}; - -/** - * The skeleton animation of spine. It updates animation's state and skeleton's world transform. - * @class - * @extends sp.Skeleton - * @example - * var spineBoy = new sp.SkeletonAnimation('res/skeletons/spineboy.json', 'res/skeletons/spineboy.atlas'); - * this.addChild(spineBoy, 4); - */ -sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ - _state: null, - _target: null, - _callback: null, - - _ownsAnimationStateData: false, - _startListener: null, - _endListener: null, - _completeListener: null, - _eventListener: null, - - /** - * Initializes a sp.SkeletonAnimation. please do not call this function by yourself, you should pass the parameters to constructor to initialize it. - * @override - */ - init: function () { - sp.Skeleton.prototype.init.call(this); - this._ownsAnimationStateData = true; - this.setAnimationStateData(new spine.AnimationStateData(this._skeleton.data)); - }, - - /** - * Sets animation state data to sp.SkeletonAnimation. - * @param {spine.AnimationStateData} stateData - */ - setAnimationStateData: function (stateData) { - var state = new spine.AnimationState(stateData); - state.rendererObject = this; - state.onStart = this._onAnimationStateStart.bind(this); - state.onComplete = this._onAnimationStateComplete.bind(this); - state.onEnd = this._onAnimationStateEnd.bind(this); - state.onEvent = this._onAnimationStateEvent.bind(this); - this._state = state; - }, - - /** - * Mix applies all keyframe values, interpolated for the specified time and mixed with the current values.
- * @param {String} fromAnimation - * @param {String} toAnimation - * @param {Number} duration - */ - setMix: function (fromAnimation, toAnimation, duration) { - this._state.data.setMixByName(fromAnimation, toAnimation, duration); - }, - - /** - * Sets event listener of sp.SkeletonAnimation. - * @param {Object} target - * @param {Function} callback - */ - setAnimationListener: function (target, callback) { - this._target = target; - this._callback = callback; - }, - - /** - * Set the current animation. Any queued animations are cleared. - * @param {Number} trackIndex - * @param {String} name - * @param {Boolean} loop - * @returns {spine.TrackEntry|null} - */ - setAnimation: function (trackIndex, name, loop) { - var animation = this._skeleton.data.findAnimation(name); - if (!animation) { - cc.log("Spine: Animation not found: " + name); - return null; - } - return this._state.setAnimation(trackIndex, animation, loop); - }, - - /** - * Adds an animation to be played delay seconds after the current or last queued animation. - * @param {Number} trackIndex - * @param {String} name - * @param {Boolean} loop - * @param {Number} [delay=0] - * @returns {spine.TrackEntry|null} - */ - addAnimation: function (trackIndex, name, loop, delay) { - delay = delay == null ? 0 : delay; - var animation = this._skeleton.data.findAnimation(name); - if (!animation) { - cc.log("Spine: Animation not found:" + name); - return null; - } - return this._state.addAnimation(trackIndex, animation, loop, delay); - }, - - /** - * Returns track entry by trackIndex. - * @param trackIndex - * @returns {spine.TrackEntry|null} - */ - getCurrent: function (trackIndex) { - return this._state.getCurrent(trackIndex); - }, - - /** - * Clears all tracks of animation state. - */ - clearTracks: function () { - this._state.clearTracks(); - }, - - /** - * Clears track of animation state by trackIndex. - * @param {Number} trackIndex - */ - clearTrack: function (trackIndex) { - this._state.clearTrack(trackIndex); - }, - - /** - * Update will be called automatically every frame if "scheduleUpdate" is called when the node is "live". - * It updates animation's state and skeleton's world transform. - * @param {Number} dt Delta time since last update - * @override - */ - update: function (dt) { - this._super(dt); - dt *= this._timeScale; - this._state.update(dt); - this._state.apply(this._skeleton); - this._skeleton.updateWorldTransform(); - this._renderCmd._updateChild(); - }, - - /** - * Set the start event listener. - * @param {function} listener - */ - setStartListener: function(listener){ - this._startListener = listener; - }, - - /** - * Set the end event listener. - * @param {function} listener - */ - setEndListener: function(listener) { - this._endListener = listener; - }, - - setCompleteListener: function(listener) { - this._completeListener = listener; - }, - - setEventListener: function(listener){ - this._eventListener = listener; - }, - - setTrackStartListener: function(entry, listener){ - sp.TrackEntryListeners.getListeners(entry).startListener = listener; - }, - - setTrackEndListener: function(entry, listener){ - sp.TrackEntryListeners.getListeners(entry).endListener = listener; - }, - - setTrackCompleteListener: function(entry, listener){ - sp.TrackEntryListeners.getListeners(entry).completeListener = listener; - }, - - setTrackEventListener: function(entry, listener){ - sp.TrackEntryListeners.getListeners(entry).eventListener = listener; - }, - - onTrackEntryEvent: function(traceIndex, type, event, loopCount){ - var entry = this._state.getCurrent(traceIndex); - if(!entry.rendererObject) - return; - var listeners = entry.rendererObject; - switch (type){ - case sp.ANIMATION_EVENT_TYPE.START: - if(listeners.startListener) - listeners.startListener(traceIndex); - break; - case sp.ANIMATION_EVENT_TYPE.END: - if(listeners.endListener) - listeners.endListener(traceIndex); - break; - case sp.ANIMATION_EVENT_TYPE.COMPLETE: - if(listeners.completeListener) - listeners.completeListener(traceIndex, loopCount); - break; - case sp.ANIMATION_EVENT_TYPE.EVENT: - if(listeners.eventListener) - listeners.eventListener(traceIndex, event); - break; - } - }, - - onAnimationStateEvent: function(trackIndex, type, event, loopCount) { - switch(type){ - case sp.ANIMATION_EVENT_TYPE.START: - if(this._startListener) - this._startListener(trackIndex); - break; - case sp.ANIMATION_EVENT_TYPE.END: - if(this._endListener) - this._endListener(trackIndex); - break; - case sp.ANIMATION_EVENT_TYPE.COMPLETE: - if(this._completeListener) - this._completeListener(trackIndex, loopCount); - break; - case sp.ANIMATION_EVENT_TYPE.EVENT: - if(this._eventListener) - this._eventListener(trackIndex, event); - break; - } - }, - - getState: function(){ - return this._state; - }, - - _onAnimationStateStart: function (trackIndex) { - this._animationStateCallback(trackIndex, sp.ANIMATION_EVENT_TYPE.START, null, 0); - }, - _onAnimationStateEnd: function (trackIndex) { - this._animationStateCallback(trackIndex, sp.ANIMATION_EVENT_TYPE.END, null, 0); - }, - _onAnimationStateComplete: function (trackIndex, count) { - this._animationStateCallback(trackIndex, sp.ANIMATION_EVENT_TYPE.COMPLETE, null, count); - }, - _onAnimationStateEvent: function (trackIndex, event) { - this._animationStateCallback(trackIndex, sp.ANIMATION_EVENT_TYPE.EVENT, event, 0); - }, - _animationStateCallback: function (trackIndex, type, event, loopCount) { - this.onAnimationStateEvent(trackIndex, type, event, loopCount); - if (this._target && this._callback) { - this._callback.call(this._target, this, trackIndex, type, event, loopCount) - } - } -}); - -/** - * Creates a skeleton animation object. - * @deprecated since v3.0, please use new sp.SkeletonAnimation(skeletonDataFile, atlasFile, scale) instead. - * @param {spine.SkeletonData|String} skeletonDataFile - * @param {String|spine.Atlas|spine.SkeletonData} atlasFile atlas filename or atlas data or owns SkeletonData - * @param {Number} [scale] scale can be specified on the JSON or binary loader which will scale the bone positions, image sizes, and animation translations. - * @returns {sp.Skeleton} - */ -sp.SkeletonAnimation.create = function (skeletonDataFile, atlasFile/* or atlas*/, scale) { - return new sp.SkeletonAnimation(skeletonDataFile, atlasFile, scale); -}; \ No newline at end of file diff --git a/extensions/spine/CCSkeletonWebGLRenderCmd.js b/extensions/spine/CCSkeletonWebGLRenderCmd.js index 51d2184caa..e69de29bb2 100644 --- a/extensions/spine/CCSkeletonWebGLRenderCmd.js +++ b/extensions/spine/CCSkeletonWebGLRenderCmd.js @@ -1,260 +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. - ****************************************************************************/ - -(function(){ - sp.Skeleton.WebGLRenderCmd = function (renderableObject) { - cc.Node.WebGLRenderCmd.call(this, renderableObject); - this._needDraw = true; - this.setShaderProgram(cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURECOLOR)); - this._tmpQuad = new cc.V3F_C4B_T2F_Quad(); - }; - - var proto = sp.Skeleton.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype); - proto.constructor = sp.Skeleton.WebGLRenderCmd; - - proto.rendering = function (ctx) { - var node = this._node, tmpQuad = this._tmpQuad; - var color = node.getColor(), locSkeleton = node._skeleton; - - var blendMode, textureAtlas, attachment, slot, i, n; - var locBlendFunc = node._blendFunc; - var premultiAlpha = node._premultipliedAlpha; - - this._shaderProgram.use(); - this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix); - // cc.glBlendFunc(locBlendFunc.src, locBlendFunc.dst); - locSkeleton.r = color.r / 255; - locSkeleton.g = color.g / 255; - locSkeleton.b = color.b / 255; - locSkeleton.a = node.getOpacity() / 255; - if (premultiAlpha) { - locSkeleton.r *= locSkeleton.a; - locSkeleton.g *= locSkeleton.a; - locSkeleton.b *= locSkeleton.a; - } - - //for (i = 0, n = locSkeleton.slots.length; i < n; i++) { - for (i = 0, n = locSkeleton.drawOrder.length; i < n; i++) { - slot = locSkeleton.drawOrder[i]; - if (!slot.attachment) - continue; - attachment = slot.attachment; - - switch(slot.attachment.type) { - case sp.ATTACHMENT_TYPE.REGION: - this._updateRegionAttachmentQuad(attachment, slot, tmpQuad, premultiAlpha); - break; - case sp.ATTACHMENT_TYPE.MESH: - this._updateMeshAttachmentQuad(attachment, slot, tmpQuad, premultiAlpha); - break; - case sp.ATTACHMENT_TYPE.SKINNED_MESH: - break; - default: - continue; - } - - var regionTextureAtlas = node.getTextureAtlas(attachment); - - if (slot.data.blendMode != blendMode) { - if (textureAtlas) { - textureAtlas.drawQuads(); - textureAtlas.removeAllQuads(); - } - blendMode = slot.data.blendMode; - switch (blendMode) { - case spine.BlendMode.additive: - cc.glBlendFunc(premultiAlpha ? cc.ONE : cc.SRC_ALPHA, cc.ONE); - break; - case spine.BlendMode.multiply: - cc.glBlendFunc(cc.DST_COLOR, cc.ONE_MINUS_SRC_ALPHA); - break; - case spine.BlendMode.screen: - cc.glBlendFunc(cc.ONE, cc.ONE_MINUS_SRC_COLOR); - break; - default: - cc.glBlendFunc(locBlendFunc.src, locBlendFunc.dst); - } - } else if (regionTextureAtlas != textureAtlas && textureAtlas) { - textureAtlas.drawQuads(); - textureAtlas.removeAllQuads(); - } - textureAtlas = regionTextureAtlas; - - var quadCount = textureAtlas.getTotalQuads(); - if (textureAtlas.getCapacity() == quadCount) { - textureAtlas.drawQuads(); - textureAtlas.removeAllQuads(); - if (!textureAtlas.resizeCapacity(textureAtlas.getCapacity() * 2)) - return; - } - - textureAtlas.updateQuad(tmpQuad, quadCount); - } - - if (textureAtlas) { - textureAtlas.drawQuads(); - textureAtlas.removeAllQuads(); - } - - if (node._debugBones || node._debugSlots) { - cc.kmGLMatrixMode(cc.KM_GL_MODELVIEW); - //cc.kmGLPushMatrixWitMat4(this._stackMatrix); - cc.current_stack.stack.push(cc.current_stack.top); - cc.current_stack.top = this._stackMatrix; - var drawingUtil = cc._drawingUtil; - - if (node._debugSlots) { - // Slots. - drawingUtil.setDrawColor(0, 0, 255, 255); - drawingUtil.setLineWidth(1); - - for (i = 0, n = locSkeleton.slots.length; i < n; i++) { - slot = locSkeleton.drawOrder[i]; - if (!slot.attachment || slot.attachment.type != sp.ATTACHMENT_TYPE.REGION) - continue; - attachment = slot.attachment; - this._updateRegionAttachmentQuad(attachment, slot, tmpQuad); - - var points = []; - points.push(cc.p(tmpQuad.bl.vertices.x, tmpQuad.bl.vertices.y)); - points.push(cc.p(tmpQuad.br.vertices.x, tmpQuad.br.vertices.y)); - points.push(cc.p(tmpQuad.tr.vertices.x, tmpQuad.tr.vertices.y)); - points.push(cc.p(tmpQuad.tl.vertices.x, tmpQuad.tl.vertices.y)); - - drawingUtil.drawPoly(points, 4, true); - } - } - - if (node._debugBones) { - // Bone lengths. - var bone; - drawingUtil.setLineWidth(2); - drawingUtil.setDrawColor(255, 0, 0, 255); - - for (i = 0, n = locSkeleton.bones.length; i < n; i++) { - bone = locSkeleton.bones[i]; - var x = bone.data.length * bone.m00 + bone.worldX; - var y = bone.data.length * bone.m10 + bone.worldY; - drawingUtil.drawLine(cc.p(bone.worldX, bone.worldY), cc.p(x, y)); - } - - // Bone origins. - drawingUtil.setPointSize(4); - drawingUtil.setDrawColor(0, 0, 255, 255); // Root bone is blue. - - for (i = 0, n = locSkeleton.bones.length; i < n; i++) { - bone = locSkeleton.bones[i]; - drawingUtil.drawPoint(cc.p(bone.worldX, bone.worldY)); - if (i == 0) { - drawingUtil.setDrawColor(0, 255, 0, 255); - } - } - } - cc.kmGLPopMatrix(); - } - }; - - proto._createChildFormSkeletonData = function(){}; - - proto._updateChild = function(){}; - - proto._updateRegionAttachmentQuad = function(self, slot, quad, premultipliedAlpha) { - var vertices = {}; - self.computeVertices(slot.bone.skeleton.x, slot.bone.skeleton.y, slot.bone, vertices); - var r = slot.bone.skeleton.r * slot.r * 255; - var g = slot.bone.skeleton.g * slot.g * 255; - var b = slot.bone.skeleton.b * slot.b * 255; - var normalizedAlpha = slot.bone.skeleton.a * slot.a; - - if (premultipliedAlpha) { - r *= normalizedAlpha; - g *= normalizedAlpha; - b *= normalizedAlpha; - } - var a = normalizedAlpha * 255; - - quad.bl.colors.r = quad.tl.colors.r = quad.tr.colors.r = quad.br.colors.r = r; - quad.bl.colors.g = quad.tl.colors.g = quad.tr.colors.g = quad.br.colors.g = g; - quad.bl.colors.b = quad.tl.colors.b = quad.tr.colors.b = quad.br.colors.b = b; - quad.bl.colors.a = quad.tl.colors.a = quad.tr.colors.a = quad.br.colors.a = a; - - var VERTEX = sp.VERTEX_INDEX; - quad.bl.vertices.x = vertices[VERTEX.X1]; - quad.bl.vertices.y = vertices[VERTEX.Y1]; - quad.tl.vertices.x = vertices[VERTEX.X2]; - quad.tl.vertices.y = vertices[VERTEX.Y2]; - quad.tr.vertices.x = vertices[VERTEX.X3]; - quad.tr.vertices.y = vertices[VERTEX.Y3]; - quad.br.vertices.x = vertices[VERTEX.X4]; - quad.br.vertices.y = vertices[VERTEX.Y4]; - - quad.bl.texCoords.u = self.uvs[VERTEX.X1]; - quad.bl.texCoords.v = self.uvs[VERTEX.Y1]; - quad.tl.texCoords.u = self.uvs[VERTEX.X2]; - quad.tl.texCoords.v = self.uvs[VERTEX.Y2]; - quad.tr.texCoords.u = self.uvs[VERTEX.X3]; - quad.tr.texCoords.v = self.uvs[VERTEX.Y3]; - quad.br.texCoords.u = self.uvs[VERTEX.X4]; - quad.br.texCoords.v = self.uvs[VERTEX.Y4]; - }; - - proto._updateMeshAttachmentQuad = function(self, slot, quad, premultipliedAlpha) { - var vertices = {}; - self.computeWorldVertices(slot.bone.x, slot.bone.y, slot, vertices); - var r = slot.bone.skeleton.r * slot.r * 255; - var g = slot.bone.skeleton.g * slot.g * 255; - var b = slot.bone.skeleton.b * slot.b * 255; - var normalizedAlpha = slot.bone.skeleton.a * slot.a; - if (premultipliedAlpha) { - r *= normalizedAlpha; - g *= normalizedAlpha; - b *= normalizedAlpha; - } - var a = normalizedAlpha * 255; - - quad.bl.colors.r = quad.tl.colors.r = quad.tr.colors.r = quad.br.colors.r = r; - quad.bl.colors.g = quad.tl.colors.g = quad.tr.colors.g = quad.br.colors.g = g; - quad.bl.colors.b = quad.tl.colors.b = quad.tr.colors.b = quad.br.colors.b = b; - quad.bl.colors.a = quad.tl.colors.a = quad.tr.colors.a = quad.br.colors.a = a; - - var VERTEX = sp.VERTEX_INDEX; - quad.bl.vertices.x = vertices[VERTEX.X1]; - quad.bl.vertices.y = vertices[VERTEX.Y1]; - quad.tl.vertices.x = vertices[VERTEX.X2]; - quad.tl.vertices.y = vertices[VERTEX.Y2]; - quad.tr.vertices.x = vertices[VERTEX.X3]; - quad.tr.vertices.y = vertices[VERTEX.Y3]; - quad.br.vertices.x = vertices[VERTEX.X4]; - quad.br.vertices.y = vertices[VERTEX.Y4]; - - quad.bl.texCoords.u = self.uvs[VERTEX.X1]; - quad.bl.texCoords.v = self.uvs[VERTEX.Y1]; - quad.tl.texCoords.u = self.uvs[VERTEX.X2]; - quad.tl.texCoords.v = self.uvs[VERTEX.Y2]; - quad.tr.texCoords.u = self.uvs[VERTEX.X3]; - quad.tr.texCoords.v = self.uvs[VERTEX.Y3]; - quad.br.texCoords.u = self.uvs[VERTEX.X4]; - quad.br.texCoords.v = self.uvs[VERTEX.Y4]; - }; -})(); diff --git a/extensions/spine/Spine.js b/extensions/spine/Spine.js index d9bd118f59..e69de29bb2 100644 --- a/extensions/spine/Spine.js +++ b/extensions/spine/Spine.js @@ -1,2731 +0,0 @@ -/****************************************************************************** - * Spine Runtimes Software License - * Version 2.3 - * - * Copyright (c) 2013-2015, Esoteric Software - * All rights reserved. - * - * You are granted a perpetual, non-exclusive, non-sublicensable and - * non-transferable license to use, install, execute and perform the Spine - * Runtimes Software (the "Software") and derivative works solely for personal - * or internal use. Without the written permission of Esoteric Software (see - * Section 2 of the Spine Software License Agreement), you may not (a) modify, - * translate, adapt or otherwise create derivative works, improvements of the - * Software or develop new applications using the Software or (b) remove, - * delete, alter or obscure any trademarks or any copyright, trademark, patent - * or other intellectual property or proprietary rights notices on or in the - * Software, including any copy thereof. Redistributions in binary or source - * form must include this license and terms. - * - * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO - * EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - *****************************************************************************/ - -var spine = { - radDeg: 180 / Math.PI, - degRad: Math.PI / 180, - temp: [], - Float32Array: (typeof(Float32Array) === 'undefined') ? Array : Float32Array, - Uint16Array: (typeof(Uint16Array) === 'undefined') ? Array : Uint16Array -}; - -spine.BoneData = function (name, parent) { - this.length = this.x = this.y = this.rotation = 0; - this.scaleX = this.scaleY = 1; - - this.name = name; - this.parent = parent; -}; - -spine.BoneData.prototype = { - length: 0, - x: 0, y: 0, - rotation: 0, - scaleX: 1, scaleY: 1, - inheritScale: true, - inheritRotation: true, - flipX: false, flipY: false -}; - -spine.BlendMode = { - normal: 0, - additive: 1, - multiply: 2, - screen: 3 -}; - -spine.SlotData = function (name, boneData) { - this.r = this.g = this.b = this.a = 1; - this.blendMode = spine.BlendMode.normal; - - this.name = name; - this.boneData = boneData; -}; -spine.SlotData.prototype = { - r: 1, g: 1, b: 1, a: 1, - attachmentName: null, - blendMode: spine.BlendMode.normal -}; - -spine.IkConstraintData = function (name) { - this.bendDirection = this.mix = 1; - - this.name = name; - this.bones = []; -}; -spine.IkConstraintData.prototype = { - target: null, - bendDirection: 1, - mix: 1 -}; - -spine.Bone = function (boneData, skeleton, parent) { - this.x = this.y = this.rotation = this.rotationIK = 0; - this.scaleX = this.scaleY = 1; - this.flipX = this.flipY = false; - this.m00 = this.m01 = this.worldX = 0; // a b x - this.m10 = this.m11= this.worldY = 0; // c d y - this.worldRotation = 0; - this.worldScaleX = this.worldScaleY = 1; - this.worldFlipX = this.worldFlipY = false; - - this.data = boneData; - this.skeleton = skeleton; - this.parent = parent; - this.setToSetupPose(); -}; -spine.Bone.yDown = false; -spine.Bone.prototype = { - x: 0, y: 0, - rotation: 0, rotationIK: 0, - scaleX: 1, scaleY: 1, - flipX: false, flipY: false, - m00: 0, m01: 0, worldX: 0, // a b x - m10: 0, m11: 0, worldY: 0, // c d y - worldRotation: 0, - worldScaleX: 1, worldScaleY: 1, - worldFlipX: false, worldFlipY: false, - updateWorldTransform: function () { - var parent = this.parent; - if (parent) { - this.worldX = this.x * parent.m00 + this.y * parent.m01 + parent.worldX; - this.worldY = this.x * parent.m10 + this.y * parent.m11 + parent.worldY; - if (this.data.inheritScale) { - this.worldScaleX = parent.worldScaleX * this.scaleX; - this.worldScaleY = parent.worldScaleY * this.scaleY; - } else { - this.worldScaleX = this.scaleX; - this.worldScaleY = this.scaleY; - } - this.worldRotation = this.data.inheritRotation ? (parent.worldRotation + this.rotationIK) : this.rotationIK; - this.worldFlipX = parent.worldFlipX != this.flipX; - this.worldFlipY = parent.worldFlipY != this.flipY; - } else { - var skeletonFlipX = this.skeleton.flipX, skeletonFlipY = this.skeleton.flipY; - this.worldX = skeletonFlipX ? -this.x : this.x; - this.worldY = (skeletonFlipY != spine.Bone.yDown) ? -this.y : this.y; - this.worldScaleX = this.scaleX; - this.worldScaleY = this.scaleY; - this.worldRotation = this.rotationIK; - this.worldFlipX = skeletonFlipX != this.flipX; - this.worldFlipY = skeletonFlipY != this.flipY; - } - var radians = this.worldRotation * spine.degRad; - var cos = Math.cos(radians); - var sin = Math.sin(radians); - if (this.worldFlipX) { - this.m00 = -cos * this.worldScaleX; - this.m01 = sin * this.worldScaleY; - } else { - this.m00 = cos * this.worldScaleX; - this.m01 = -sin * this.worldScaleY; - } - if (this.worldFlipY != spine.Bone.yDown) { - this.m10 = -sin * this.worldScaleX; - this.m11 = -cos * this.worldScaleY; - } else { - this.m10 = sin * this.worldScaleX; - this.m11 = cos * this.worldScaleY; - } - }, - setToSetupPose: function () { - var data = this.data; - this.x = data.x; - this.y = data.y; - this.rotation = data.rotation; - this.rotationIK = this.rotation; - this.scaleX = data.scaleX; - this.scaleY = data.scaleY; - this.flipX = data.flipX; - this.flipY = data.flipY; - }, - worldToLocal: function (world) { - var dx = world[0] - this.worldX, dy = world[1] - this.worldY; - var m00 = this.m00, m10 = this.m10, m01 = this.m01, m11 = this.m11; - if (this.worldFlipX != (this.worldFlipY != spine.Bone.yDown)) { - m00 = -m00; - m11 = -m11; - } - var invDet = 1 / (m00 * m11 - m01 * m10); - world[0] = dx * m00 * invDet - dy * m01 * invDet; - world[1] = dy * m11 * invDet - dx * m10 * invDet; - }, - localToWorld: function (local) { - var localX = local[0], localY = local[1]; - local[0] = localX * this.m00 + localY * this.m01 + this.worldX; - local[1] = localX * this.m10 + localY * this.m11 + this.worldY; - } -}; - -spine.Slot = function (slotData, bone) { - this.r = this.g = this.b = this.a = 1; - this._attachmentTime = 0; - - this.data = slotData; - this.bone = bone; - this.setToSetupPose(); -}; -spine.Slot.prototype = { - r: 1, g: 1, b: 1, a: 1, - _attachmentTime: 0, - attachment: null, - attachmentVertices: [], - setAttachment: function (attachment) { - this.attachment = attachment; - this._attachmentTime = this.bone.skeleton.time; - this.attachmentVertices.length = 0; - }, - setAttachmentTime: function (time) { - this._attachmentTime = this.bone.skeleton.time - time; - }, - getAttachmentTime: function () { - return this.bone.skeleton.time - this._attachmentTime; - }, - setToSetupPose: function () { - var data = this.data; - this.r = data.r; - this.g = data.g; - this.b = data.b; - this.a = data.a; - - var slotDatas = this.bone.skeleton.data.slots; - for (var i = 0, n = slotDatas.length; i < n; i++) { - if (slotDatas[i] == data) { - this.setAttachment(!data.attachmentName ? null : this.bone.skeleton.getAttachmentBySlotIndex(i, data.attachmentName)); - break; - } - } - } -}; - -spine.IkConstraint = function (data, skeleton) { - this.data = data; - this.mix = data.mix; - this.bendDirection = data.bendDirection; - - this.bones = []; - for (var i = 0, n = data.bones.length; i < n; i++) - this.bones.push(skeleton.findBone(data.bones[i].name)); - this.target = skeleton.findBone(data.target.name); -}; -spine.IkConstraint.prototype = { - apply: function () { - var target = this.target; - var bones = this.bones; - switch (bones.length) { - case 1: - spine.IkConstraint.apply1(bones[0], target.worldX, target.worldY, this.mix); - break; - case 2: - spine.IkConstraint.apply2(bones[0], bones[1], target.worldX, target.worldY, this.bendDirection, this.mix); - break; - } - } -}; -/** Adjusts the bone rotation so the tip is as close to the target position as possible. The target is specified in the world - * coordinate system. */ -spine.IkConstraint.apply1 = function (bone, targetX, targetY, alpha) { - var parentRotation = (!bone.data.inheritRotation || !bone.parent) ? 0 : bone.parent.worldRotation; - var rotation = bone.rotation; - var rotationIK = Math.atan2(targetY - bone.worldY, targetX - bone.worldX) * spine.radDeg; - if (bone.worldFlipX != (bone.worldFlipY != spine.Bone.yDown)) rotationIK = -rotationIK; - rotationIK -= parentRotation; - bone.rotationIK = rotation + (rotationIK - rotation) * alpha; -}; -/** Adjusts the parent and child bone rotations so the tip of the child is as close to the target position as possible. The - * target is specified in the world coordinate system. - * @param child Any descendant bone of the parent. */ -spine.IkConstraint.apply2 = function (parent, child, targetX, targetY, bendDirection, alpha) { - var childRotation = child.rotation, parentRotation = parent.rotation; - if (!alpha) { - child.rotationIK = childRotation; - parent.rotationIK = parentRotation; - return; - } - var positionX, positionY, tempPosition = spine.temp; - var parentParent = parent.parent; - if (parentParent) { - tempPosition[0] = targetX; - tempPosition[1] = targetY; - parentParent.worldToLocal(tempPosition); - targetX = (tempPosition[0] - parent.x) * parentParent.worldScaleX; - targetY = (tempPosition[1] - parent.y) * parentParent.worldScaleY; - } else { - targetX -= parent.x; - targetY -= parent.y; - } - if (child.parent == parent) { - positionX = child.x; - positionY = child.y; - } else { - tempPosition[0] = child.x; - tempPosition[1] = child.y; - child.parent.localToWorld(tempPosition); - parent.worldToLocal(tempPosition); - positionX = tempPosition[0]; - positionY = tempPosition[1]; - } - var childX = positionX * parent.worldScaleX, childY = positionY * parent.worldScaleY; - var offset = Math.atan2(childY, childX); - var len1 = Math.sqrt(childX * childX + childY * childY), len2 = child.data.length * child.worldScaleX; - // Based on code by Ryan Juckett with permission: Copyright (c) 2008-2009 Ryan Juckett, http://www.ryanjuckett.com/ - var cosDenom = 2 * len1 * len2; - if (cosDenom < 0.0001) { - child.rotationIK = childRotation + (Math.atan2(targetY, targetX) * spine.radDeg - parentRotation - childRotation) * alpha; - return; - } - var cos = (targetX * targetX + targetY * targetY - len1 * len1 - len2 * len2) / cosDenom; - if (cos < -1) - cos = -1; - else if (cos > 1) - cos = 1; - var childAngle = Math.acos(cos) * bendDirection; - var adjacent = len1 + len2 * cos, opposite = len2 * Math.sin(childAngle); - var parentAngle = Math.atan2(targetY * adjacent - targetX * opposite, targetX * adjacent + targetY * opposite); - var rotation = (parentAngle - offset) * spine.radDeg - parentRotation; - if (rotation > 180) - rotation -= 360; - else if (rotation < -180) // - rotation += 360; - parent.rotationIK = parentRotation + rotation * alpha; - rotation = (childAngle + offset) * spine.radDeg - childRotation; - if (rotation > 180) - rotation -= 360; - else if (rotation < -180) // - rotation += 360; - child.rotationIK = childRotation + (rotation + parent.worldRotation - child.parent.worldRotation) * alpha; -}; - -spine.Skin = function (name) { - this.name = name; - this.attachments = {}; -}; -spine.Skin.prototype = { - addAttachment: function (slotIndex, name, attachment) { - this.attachments[slotIndex + ":" + name] = attachment; - }, - getAttachment: function (slotIndex, name) { - return this.attachments[slotIndex + ":" + name]; - }, - _attachAll: function (skeleton, oldSkin) { - for (var key in oldSkin.attachments) { - var colon = key.indexOf(":"); - var slotIndex = parseInt(key.substring(0, colon)); - var name = key.substring(colon + 1); - var slot = skeleton.slots[slotIndex]; - if (slot.attachment && slot.attachment.name == name) { - var attachment = this.getAttachment(slotIndex, name); - if (attachment) slot.setAttachment(attachment); - } - } - } -}; - -spine.Animation = function (name, timelines, duration) { - this.name = name; - this.timelines = timelines; - this.duration = duration; -}; -spine.Animation.prototype = { - apply: function (skeleton, lastTime, time, loop, events) { - if (loop && this.duration != 0) { - time %= this.duration; - lastTime %= this.duration; - } - var timelines = this.timelines; - for (var i = 0, n = timelines.length; i < n; i++) - timelines[i].apply(skeleton, lastTime, time, events, 1); - }, - mix: function (skeleton, lastTime, time, loop, events, alpha) { - if (loop && this.duration != 0) { - time %= this.duration; - lastTime %= this.duration; - } - var timelines = this.timelines; - for (var i = 0, n = timelines.length; i < n; i++) - timelines[i].apply(skeleton, lastTime, time, events, alpha); - } -}; -spine.Animation.binarySearch = function (values, target, step) { - var low = 0; - var high = Math.floor(values.length / step) - 2; - if (!high) return step; - var current = high >>> 1; - while (true) { - if (values[(current + 1) * step] <= target) - low = current + 1; - else - high = current; - if (low == high) return (low + 1) * step; - current = (low + high) >>> 1; - } -}; -spine.Animation.binarySearch1 = function (values, target) { - var low = 0; - var high = values.length - 2; - if (!high) return 1; - var current = high >>> 1; - while (true) { - if (values[current + 1] <= target) - low = current + 1; - else - high = current; - if (low == high) return low + 1; - current = (low + high) >>> 1; - } -}; -spine.Animation.linearSearch = function (values, target, step) { - for (var i = 0, last = values.length - step; i <= last; i += step) - if (values[i] > target) return i; - return -1; -}; - -spine.Curves = function (frameCount) { - this.curves = []; // type, x, y, ... - //this.curves.length = (frameCount - 1) * 19/*BEZIER_SIZE*/; -}; -spine.Curves.prototype = { - setLinear: function (frameIndex) { - this.curves[frameIndex * 19/*BEZIER_SIZE*/] = 0/*LINEAR*/; - }, - setStepped: function (frameIndex) { - this.curves[frameIndex * 19/*BEZIER_SIZE*/] = 1/*STEPPED*/; - }, - /** Sets the control handle positions for an interpolation bezier curve used to transition from this keyframe to the next. - * cx1 and cx2 are from 0 to 1, representing the percent of time between the two keyframes. cy1 and cy2 are the percent of - * the difference between the keyframe's values. */ - setCurve: function (frameIndex, cx1, cy1, cx2, cy2) { - var subdiv1 = 1 / 10/*BEZIER_SEGMENTS*/, subdiv2 = subdiv1 * subdiv1, subdiv3 = subdiv2 * subdiv1; - var pre1 = 3 * subdiv1, pre2 = 3 * subdiv2, pre4 = 6 * subdiv2, pre5 = 6 * subdiv3; - var tmp1x = -cx1 * 2 + cx2, tmp1y = -cy1 * 2 + cy2, tmp2x = (cx1 - cx2) * 3 + 1, tmp2y = (cy1 - cy2) * 3 + 1; - var dfx = cx1 * pre1 + tmp1x * pre2 + tmp2x * subdiv3, dfy = cy1 * pre1 + tmp1y * pre2 + tmp2y * subdiv3; - var ddfx = tmp1x * pre4 + tmp2x * pre5, ddfy = tmp1y * pre4 + tmp2y * pre5; - var dddfx = tmp2x * pre5, dddfy = tmp2y * pre5; - - var i = frameIndex * 19/*BEZIER_SIZE*/; - var curves = this.curves; - curves[i++] = 2/*BEZIER*/; - - var x = dfx, y = dfy; - for (var n = i + 19/*BEZIER_SIZE*/ - 1; i < n; i += 2) { - curves[i] = x; - curves[i + 1] = y; - dfx += ddfx; - dfy += ddfy; - ddfx += dddfx; - ddfy += dddfy; - x += dfx; - y += dfy; - } - }, - getCurvePercent: function (frameIndex, percent) { - percent = percent < 0 ? 0 : (percent > 1 ? 1 : percent); - var curves = this.curves; - var i = frameIndex * 19/*BEZIER_SIZE*/; - var type = curves[i]; - if (type === 0/*LINEAR*/) return percent; - if (type == 1/*STEPPED*/) return 0; - i++; - var x = 0; - for (var start = i, n = i + 19/*BEZIER_SIZE*/ - 1; i < n; i += 2) { - x = curves[i]; - if (x >= percent) { - var prevX, prevY; - if (i == start) { - prevX = 0; - prevY = 0; - } else { - prevX = curves[i - 2]; - prevY = curves[i - 1]; - } - return prevY + (curves[i + 1] - prevY) * (percent - prevX) / (x - prevX); - } - } - var y = curves[i - 1]; - return y + (1 - y) * (percent - x) / (1 - x); // Last point is 1,1. - } -}; - -spine.RotateTimeline = function (frameCount) { - this.boneIndex = 0; - - this.curves = new spine.Curves(frameCount); - this.frames = []; // time, angle, ... - this.frames.length = frameCount * 2; -}; -spine.RotateTimeline.prototype = { - boneIndex: 0, - getFrameCount: function () { - return this.frames.length / 2; - }, - setFrame: function (frameIndex, time, angle) { - frameIndex *= 2; - this.frames[frameIndex] = time; - this.frames[frameIndex + 1] = angle; - }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { - var frames = this.frames; - if (time < frames[0]) return; // Time is before first frame. - - var bone = skeleton.bones[this.boneIndex]; - - if (time >= frames[frames.length - 2]) { // Time is after last frame. - var amount = bone.data.rotation + frames[frames.length - 1] - bone.rotation; - while (amount > 180) - amount -= 360; - while (amount < -180) - amount += 360; - bone.rotation += amount * alpha; - return; - } - - // Interpolate between the previous frame and the current frame. - var frameIndex = spine.Animation.binarySearch(frames, time, 2); - var prevFrameValue = frames[frameIndex - 1]; - var frameTime = frames[frameIndex]; - var percent = 1 - (time - frameTime) / (frames[frameIndex - 2/*PREV_FRAME_TIME*/] - frameTime); - percent = this.curves.getCurvePercent(frameIndex / 2 - 1, percent); - - var amount = frames[frameIndex + 1/*FRAME_VALUE*/] - prevFrameValue; - while (amount > 180) - amount -= 360; - while (amount < -180) - amount += 360; - amount = bone.data.rotation + (prevFrameValue + amount * percent) - bone.rotation; - while (amount > 180) - amount -= 360; - while (amount < -180) - amount += 360; - bone.rotation += amount * alpha; - } -}; - -spine.TranslateTimeline = function (frameCount) { - this.boneIndex = 0; - - this.curves = new spine.Curves(frameCount); - this.frames = []; // time, x, y, ... - this.frames.length = frameCount * 3; -}; -spine.TranslateTimeline.prototype = { - boneIndex: 0, - getFrameCount: function () { - return this.frames.length / 3; - }, - setFrame: function (frameIndex, time, x, y) { - frameIndex *= 3; - this.frames[frameIndex] = time; - this.frames[frameIndex + 1] = x; - this.frames[frameIndex + 2] = y; - }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { - var frames = this.frames; - if (time < frames[0]) return; // Time is before first frame. - - var bone = skeleton.bones[this.boneIndex]; - - if (time >= frames[frames.length - 3]) { // Time is after last frame. - bone.x += (bone.data.x + frames[frames.length - 2] - bone.x) * alpha; - bone.y += (bone.data.y + frames[frames.length - 1] - bone.y) * alpha; - return; - } - - // Interpolate between the previous frame and the current frame. - var frameIndex = spine.Animation.binarySearch(frames, time, 3); - var prevFrameX = frames[frameIndex - 2]; - var prevFrameY = frames[frameIndex - 1]; - var frameTime = frames[frameIndex]; - var percent = 1 - (time - frameTime) / (frames[frameIndex + -3/*PREV_FRAME_TIME*/] - frameTime); - percent = this.curves.getCurvePercent(frameIndex / 3 - 1, percent); - - bone.x += (bone.data.x + prevFrameX + (frames[frameIndex + 1/*FRAME_X*/] - prevFrameX) * percent - bone.x) * alpha; - bone.y += (bone.data.y + prevFrameY + (frames[frameIndex + 2/*FRAME_Y*/] - prevFrameY) * percent - bone.y) * alpha; - } -}; - -spine.ScaleTimeline = function (frameCount) { - this.boneIndex = 0; - - this.curves = new spine.Curves(frameCount); - this.frames = []; // time, x, y, ... - this.frames.length = frameCount * 3; -}; -spine.ScaleTimeline.prototype = { - boneIndex: 0, - getFrameCount: function () { - return this.frames.length / 3; - }, - setFrame: function (frameIndex, time, x, y) { - frameIndex *= 3; - this.frames[frameIndex] = time; - this.frames[frameIndex + 1] = x; - this.frames[frameIndex + 2] = y; - }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { - var frames = this.frames; - if (time < frames[0]) return; // Time is before first frame. - - var bone = skeleton.bones[this.boneIndex]; - - if (time >= frames[frames.length - 3]) { // Time is after last frame. - bone.scaleX += (bone.data.scaleX * frames[frames.length - 2] - bone.scaleX) * alpha; - bone.scaleY += (bone.data.scaleY * frames[frames.length - 1] - bone.scaleY) * alpha; - return; - } - - // Interpolate between the previous frame and the current frame. - var frameIndex = spine.Animation.binarySearch(frames, time, 3); - var prevFrameX = frames[frameIndex - 2]; - var prevFrameY = frames[frameIndex - 1]; - var frameTime = frames[frameIndex]; - var percent = 1 - (time - frameTime) / (frames[frameIndex + -3/*PREV_FRAME_TIME*/] - frameTime); - percent = this.curves.getCurvePercent(frameIndex / 3 - 1, percent); - - bone.scaleX += (bone.data.scaleX * (prevFrameX + (frames[frameIndex + 1/*FRAME_X*/] - prevFrameX) * percent) - bone.scaleX) * alpha; - bone.scaleY += (bone.data.scaleY * (prevFrameY + (frames[frameIndex + 2/*FRAME_Y*/] - prevFrameY) * percent) - bone.scaleY) * alpha; - } -}; - -spine.ColorTimeline = function (frameCount) { - this.boneIndex = 0; - - this.curves = new spine.Curves(frameCount); - this.frames = []; // time, r, g, b, a, ... - this.frames.length = frameCount * 5; -}; -spine.ColorTimeline.prototype = { - slotIndex: 0, - getFrameCount: function () { - return this.frames.length / 5; - }, - setFrame: function (frameIndex, time, r, g, b, a) { - frameIndex *= 5; - this.frames[frameIndex] = time; - this.frames[frameIndex + 1] = r; - this.frames[frameIndex + 2] = g; - this.frames[frameIndex + 3] = b; - this.frames[frameIndex + 4] = a; - }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { - var frames = this.frames; - if (time < frames[0]) return; // Time is before first frame. - - var r, g, b, a; - if (time >= frames[frames.length - 5]) { - // Time is after last frame. - var i = frames.length - 1; - r = frames[i - 3]; - g = frames[i - 2]; - b = frames[i - 1]; - a = frames[i]; - } else { - // Interpolate between the previous frame and the current frame. - var frameIndex = spine.Animation.binarySearch(frames, time, 5); - var prevFrameR = frames[frameIndex - 4]; - var prevFrameG = frames[frameIndex - 3]; - var prevFrameB = frames[frameIndex - 2]; - var prevFrameA = frames[frameIndex - 1]; - var frameTime = frames[frameIndex]; - var percent = 1 - (time - frameTime) / (frames[frameIndex - 5/*PREV_FRAME_TIME*/] - frameTime); - percent = this.curves.getCurvePercent(frameIndex / 5 - 1, percent); - - r = prevFrameR + (frames[frameIndex + 1/*FRAME_R*/] - prevFrameR) * percent; - g = prevFrameG + (frames[frameIndex + 2/*FRAME_G*/] - prevFrameG) * percent; - b = prevFrameB + (frames[frameIndex + 3/*FRAME_B*/] - prevFrameB) * percent; - a = prevFrameA + (frames[frameIndex + 4/*FRAME_A*/] - prevFrameA) * percent; - } - var slot = skeleton.slots[this.slotIndex]; - if (alpha < 1) { - slot.r += (r - slot.r) * alpha; - slot.g += (g - slot.g) * alpha; - slot.b += (b - slot.b) * alpha; - slot.a += (a - slot.a) * alpha; - } else { - slot.r = r; - slot.g = g; - slot.b = b; - slot.a = a; - } - } -}; - -spine.AttachmentTimeline = function (frameCount) { - this.slotIndex = 0; - - this.curves = new spine.Curves(frameCount); - this.frames = []; // time, ... - this.frames.length = frameCount; - this.attachmentNames = []; - this.attachmentNames.length = frameCount; -}; -spine.AttachmentTimeline.prototype = { - slotIndex: 0, - getFrameCount: function () { - return this.frames.length; - }, - setFrame: function (frameIndex, time, attachmentName) { - this.frames[frameIndex] = time; - this.attachmentNames[frameIndex] = attachmentName; - }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { - var frames = this.frames; - if (time < frames[0]) { - if (lastTime > time) this.apply(skeleton, lastTime, Number.MAX_VALUE, null, 0); - return; - } else if (lastTime > time) // - lastTime = -1; - - var frameIndex = time >= frames[frames.length - 1] ? frames.length - 1 : spine.Animation.binarySearch1(frames, time) - 1; - if (frames[frameIndex] < lastTime) return; - - var attachmentName = this.attachmentNames[frameIndex]; - skeleton.slots[this.slotIndex].setAttachment( - !attachmentName ? null : skeleton.getAttachmentBySlotIndex(this.slotIndex, attachmentName)); - } -}; - -spine.EventTimeline = function (frameCount) { - this.frames = []; // time, ... - this.frames.length = frameCount; - this.events = []; - this.events.length = frameCount; -}; -spine.EventTimeline.prototype = { - getFrameCount: function () { - return this.frames.length; - }, - setFrame: function (frameIndex, time, event) { - this.frames[frameIndex] = time; - this.events[frameIndex] = event; - }, - /** Fires events for frames > lastTime and <= time. */ - apply: function (skeleton, lastTime, time, firedEvents, alpha) { - if (!firedEvents) return; - - var frames = this.frames; - var frameCount = frames.length; - - if (lastTime > time) { // Fire events after last time for looped animations. - this.apply(skeleton, lastTime, Number.MAX_VALUE, firedEvents, alpha); - lastTime = -1; - } else if (lastTime >= frames[frameCount - 1]) // Last time is after last frame. - return; - if (time < frames[0]) return; // Time is before first frame. - - var frameIndex; - if (lastTime < frames[0]) - frameIndex = 0; - else { - frameIndex = spine.Animation.binarySearch1(frames, lastTime); - var frame = frames[frameIndex]; - while (frameIndex > 0) { // Fire multiple events with the same frame. - if (frames[frameIndex - 1] != frame) break; - frameIndex--; - } - } - var events = this.events; - for (; frameIndex < frameCount && time >= frames[frameIndex]; frameIndex++) - firedEvents.push(events[frameIndex]); - } -}; - -spine.DrawOrderTimeline = function (frameCount) { - this.frames = []; // time, ... - this.frames.length = frameCount; - this.drawOrders = []; - this.drawOrders.length = frameCount; -}; -spine.DrawOrderTimeline.prototype = { - getFrameCount: function () { - return this.frames.length; - }, - setFrame: function (frameIndex, time, drawOrder) { - this.frames[frameIndex] = time; - this.drawOrders[frameIndex] = drawOrder; - }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { - var frames = this.frames; - if (time < frames[0]) return; // Time is before first frame. - - var frameIndex; - if (time >= frames[frames.length - 1]) // Time is after last frame. - frameIndex = frames.length - 1; - else - frameIndex = spine.Animation.binarySearch1(frames, time) - 1; - - var drawOrder = skeleton.drawOrder; - var slots = skeleton.slots; - var drawOrderToSetupIndex = this.drawOrders[frameIndex]; - if (!drawOrderToSetupIndex) { - for (var i = 0, n = slots.length; i < n; i++) - drawOrder[i] = slots[i]; - } else { - for (var i = 0, n = drawOrderToSetupIndex.length; i < n; i++) - drawOrder[i] = skeleton.slots[drawOrderToSetupIndex[i]]; - } - - } -}; - -spine.FfdTimeline = function (frameCount) { - this.slotIndex = this.attachment = 0; - - this.curves = new spine.Curves(frameCount); - this.frames = []; - this.frames.length = frameCount; - this.frameVertices = []; - this.frameVertices.length = frameCount; -}; -spine.FfdTimeline.prototype = { - slotIndex: 0, - attachment: 0, - getFrameCount: function () { - return this.frames.length; - }, - setFrame: function (frameIndex, time, vertices) { - this.frames[frameIndex] = time; - this.frameVertices[frameIndex] = vertices; - }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { - var slot = skeleton.slots[this.slotIndex]; - if (slot.attachment != this.attachment) return; - - var frames = this.frames; - if (time < frames[0]) return; // Time is before first frame. - - var frameVertices = this.frameVertices; - var vertexCount = frameVertices[0].length; - - var vertices = slot.attachmentVertices; - if (vertices.length != vertexCount) alpha = 1; - vertices.length = vertexCount; - - if (time >= frames[frames.length - 1]) { // Time is after last frame. - var lastVertices = frameVertices[frames.length - 1]; - if (alpha < 1) { - for (var i = 0; i < vertexCount; i++) - vertices[i] += (lastVertices[i] - vertices[i]) * alpha; - } else { - for (var i = 0; i < vertexCount; i++) - vertices[i] = lastVertices[i]; - } - return; - } - - // Interpolate between the previous frame and the current frame. - var frameIndex = spine.Animation.binarySearch1(frames, time); - var frameTime = frames[frameIndex]; - var percent = 1 - (time - frameTime) / (frames[frameIndex - 1] - frameTime); - percent = this.curves.getCurvePercent(frameIndex - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent)); - - var prevVertices = frameVertices[frameIndex - 1]; - var nextVertices = frameVertices[frameIndex]; - - if (alpha < 1) { - for (var i = 0; i < vertexCount; i++) { - var prev = prevVertices[i]; - vertices[i] += (prev + (nextVertices[i] - prev) * percent - vertices[i]) * alpha; - } - } else { - for (var i = 0; i < vertexCount; i++) { - var prev = prevVertices[i]; - vertices[i] = prev + (nextVertices[i] - prev) * percent; - } - } - } -}; - -spine.IkConstraintTimeline = function (frameCount) { - this.ikConstraintIndex = 0; - - 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.boneIndex = 0; - - this.curves = new spine.Curves(frameCount); - this.frames = []; // time, flip, ... - this.frames.length = frameCount * 2; -}; -spine.FlipXTimeline.prototype = { - boneIndex: 0, - getFrameCount: function () { - return this.frames.length / 2; - }, - setFrame: function (frameIndex, time, flip) { - frameIndex *= 2; - this.frames[frameIndex] = time; - this.frames[frameIndex + 1] = flip ? 1 : 0; - }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { - var frames = this.frames; - if (time < frames[0]) { - if (lastTime > time) this.apply(skeleton, lastTime, Number.MAX_VALUE, null, 0); - return; - } else if (lastTime > time) // - lastTime = -1; - var frameIndex = (time >= frames[frames.length - 2] ? frames.length : spine.Animation.binarySearch(frames, time, 2)) - 2; - if (frames[frameIndex] < lastTime) return; - skeleton.bones[this.boneIndex].flipX = frames[frameIndex + 1] != 0; - } -}; - -spine.FlipYTimeline = function (frameCount) { - this.boneIndex = 0; - - this.curves = new spine.Curves(frameCount); - this.frames = []; // time, flip, ... - this.frames.length = frameCount * 2; -}; -spine.FlipYTimeline.prototype = { - boneIndex: 0, - getFrameCount: function () { - return this.frames.length / 2; - }, - setFrame: function (frameIndex, time, flip) { - frameIndex *= 2; - this.frames[frameIndex] = time; - this.frames[frameIndex + 1] = flip ? 1 : 0; - }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { - var frames = this.frames; - if (time < frames[0]) { - if (lastTime > time) this.apply(skeleton, lastTime, Number.MAX_VALUE, null, 0); - return; - } else if (lastTime > time) // - lastTime = -1; - var frameIndex = (time >= frames[frames.length - 2] ? frames.length : spine.Animation.binarySearch(frames, time, 2)) - 2; - if (frames[frameIndex] < lastTime) return; - skeleton.bones[this.boneIndex].flipY = frames[frameIndex + 1] != 0; - } -}; - -spine.SkeletonData = function () { - this.width = this.height = 0; - - this.bones = []; - this.slots = []; - this.skins = []; - this.events = []; - this.animations = []; - this.ikConstraints = []; -}; -spine.SkeletonData.prototype = { - name: null, - defaultSkin: null, - width: 0, height: 0, - version: null, hash: null, - /** @return May be null. */ - findBone: function (boneName) { - var bones = this.bones; - for (var i = 0, n = bones.length; i < n; i++) - if (bones[i].name == boneName) return bones[i]; - return null; - }, - /** @return -1 if the bone was not found. */ - findBoneIndex: function (boneName) { - var bones = this.bones; - for (var i = 0, n = bones.length; i < n; i++) - if (bones[i].name == boneName) return i; - return -1; - }, - /** @return May be null. */ - findSlot: function (slotName) { - var slots = this.slots; - for (var i = 0, n = slots.length; i < n; i++) { - if (slots[i].name == slotName) return slot[i]; - } - return null; - }, - /** @return -1 if the bone was not found. */ - findSlotIndex: function (slotName) { - var slots = this.slots; - for (var i = 0, n = slots.length; i < n; i++) - if (slots[i].name == slotName) return i; - return -1; - }, - /** @return May be null. */ - findSkin: function (skinName) { - var skins = this.skins; - for (var i = 0, n = skins.length; i < n; i++) - if (skins[i].name == skinName) return skins[i]; - return null; - }, - /** @return May be null. */ - findEvent: function (eventName) { - var events = this.events; - for (var i = 0, n = events.length; i < n; i++) - if (events[i].name == eventName) return events[i]; - return null; - }, - /** @return May be null. */ - findAnimation: function (animationName) { - var animations = this.animations; - for (var i = 0, n = animations.length; i < n; i++) - if (animations[i].name == animationName) return animations[i]; - return null; - }, - /** @return May be null. */ - findIkConstraint: function (ikConstraintName) { - var ikConstraints = this.ikConstraints; - for (var i = 0, n = ikConstraints.length; i < n; i++) - if (ikConstraints[i].name == ikConstraintName) return ikConstraints[i]; - return null; - } -}; - -spine.Skeleton = function (skeletonData) { - this.x = this.y = 0; - this.r = this.g = this.b = this.a = 1; - this.time = 0; - this.flipX = this.flipY = false; - - this.data = skeletonData; - - this.bones = []; - for (var i = 0, n = skeletonData.bones.length; i < n; i++) { - var boneData = skeletonData.bones[i]; - var parent = !boneData.parent ? null : this.bones[skeletonData.bones.indexOf(boneData.parent)]; - this.bones.push(new spine.Bone(boneData, this, parent)); - } - - this.slots = []; - this.drawOrder = []; - for (var i = 0, n = skeletonData.slots.length; i < n; i++) { - var slotData = skeletonData.slots[i]; - var bone = this.bones[skeletonData.bones.indexOf(slotData.boneData)]; - var slot = new spine.Slot(slotData, bone); - this.slots.push(slot); - this.drawOrder.push(slot); - } - - this.ikConstraints = []; - for (var i = 0, n = skeletonData.ikConstraints.length; i < n; i++) - this.ikConstraints.push(new spine.IkConstraint(skeletonData.ikConstraints[i], this)); - - this.boneCache = []; - this.updateCache(); -}; -spine.Skeleton.prototype = { - x: 0, y: 0, - skin: null, - r: 1, g: 1, b: 1, a: 1, - time: 0, - flipX: false, flipY: false, - /** Caches information about bones and IK constraints. Must be called if bones or IK constraints are added or removed. */ - updateCache: function () { - var ikConstraints = this.ikConstraints; - var ikConstraintsCount = ikConstraints.length; - - var arrayCount = ikConstraintsCount + 1; - var boneCache = this.boneCache; - if (boneCache.length > arrayCount) boneCache.length = arrayCount; - for (var i = 0, n = boneCache.length; i < n; i++) - boneCache[i].length = 0; - while (boneCache.length < arrayCount) - boneCache[boneCache.length] = []; - - var nonIkBones = boneCache[0]; - var bones = this.bones; - - outer: - for (var i = 0, n = bones.length; i < n; i++) { - var bone = bones[i]; - var current = bone; - do { - for (var ii = 0; ii < ikConstraintsCount; ii++) { - var ikConstraint = ikConstraints[ii]; - var parent = ikConstraint.bones[0]; - var child= ikConstraint.bones[ikConstraint.bones.length - 1]; - while (true) { - if (current == child) { - boneCache[ii].push(bone); - boneCache[ii + 1].push(bone); - continue outer; - } - if (child == parent) break; - child = child.parent; - } - } - current = current.parent; - } while (current); - nonIkBones[nonIkBones.length] = bone; - } - }, - /** Updates the world transform for each bone. */ - updateWorldTransform: function () { - var bones = this.bones; - for (var i = 0, n = bones.length; i < n; i++) { - var bone = bones[i]; - bone.rotationIK = bone.rotation; - } - var i = 0, last = this.boneCache.length - 1; - while (true) { - var cacheBones = this.boneCache[i]; - for (var ii = 0, nn = cacheBones.length; ii < nn; ii++) - cacheBones[ii].updateWorldTransform(); - if (i == last) break; - this.ikConstraints[i].apply(); - i++; - } - }, - /** Sets the bones and slots to their setup pose values. */ - setToSetupPose: function () { - this.setBonesToSetupPose(); - this.setSlotsToSetupPose(); - }, - setBonesToSetupPose: function () { - var bones = this.bones; - for (var i = 0, n = bones.length; i < n; i++) - bones[i].setToSetupPose(); - - var ikConstraints = this.ikConstraints; - for (var i = 0, n = ikConstraints.length; i < n; i++) { - var ikConstraint = ikConstraints[i]; - ikConstraint.bendDirection = ikConstraint.data.bendDirection; - ikConstraint.mix = ikConstraint.data.mix; - } - }, - setSlotsToSetupPose: function () { - var slots = this.slots; - var drawOrder = this.drawOrder; - for (var i = 0, n = slots.length; i < n; i++) { - drawOrder[i] = slots[i]; - slots[i].setToSetupPose(i); - } - }, - /** @return May return null. */ - getRootBone: function () { - return this.bones.length ? this.bones[0] : null; - }, - /** @return May be null. */ - findBone: function (boneName) { - var bones = this.bones; - for (var i = 0, n = bones.length; i < n; i++) - if (bones[i].data.name == boneName) return bones[i]; - return null; - }, - /** @return -1 if the bone was not found. */ - findBoneIndex: function (boneName) { - var bones = this.bones; - for (var i = 0, n = bones.length; i < n; i++) - if (bones[i].data.name == boneName) return i; - return -1; - }, - /** @return May be null. */ - findSlot: function (slotName) { - var slots = this.slots; - for (var i = 0, n = slots.length; i < n; i++) - if (slots[i].data.name == slotName) return slots[i]; - return null; - }, - /** @return -1 if the bone was not found. */ - findSlotIndex: function (slotName) { - var slots = this.slots; - for (var i = 0, n = slots.length; i < n; i++) - if (slots[i].data.name == slotName) return i; - return -1; - }, - setSkinByName: function (skinName) { - var skin = this.data.findSkin(skinName); - if (!skin) throw new Error("Skin not found: " + skinName); - this.setSkin(skin); - }, - /** Sets the skin used to look up attachments before looking in the {@link SkeletonData#getDefaultSkin() default skin}. - * Attachments from the new skin are attached if the corresponding attachment from the old skin was attached. If there was - * no old skin, each slot's setup mode attachment is attached from the new skin. - * @param newSkin May be null. */ - setSkin: function (newSkin) { - if (newSkin) { - if (this.skin) - newSkin._attachAll(this, this.skin); - else { - var slots = this.slots; - for (var i = 0, n = slots.length; i < n; i++) { - var slot = slots[i]; - var name = slot.data.attachmentName; - if (name) { - var attachment = newSkin.getAttachment(i, name); - if (attachment) slot.setAttachment(attachment); - } - } - } - } - this.skin = newSkin; - }, - /** @return May be null. */ - getAttachmentBySlotName: function (slotName, attachmentName) { - return this.getAttachmentBySlotIndex(this.data.findSlotIndex(slotName), attachmentName); - }, - /** @return May be null. */ - getAttachmentBySlotIndex: function (slotIndex, attachmentName) { - if (this.skin) { - var attachment = this.skin.getAttachment(slotIndex, attachmentName); - if (attachment) return attachment; - } - if (this.data.defaultSkin) return this.data.defaultSkin.getAttachment(slotIndex, attachmentName); - return null; - }, - /** @param attachmentName May be null. */ - setAttachment: function (slotName, attachmentName) { - var slots = this.slots; - for (var i = 0, n = slots.length; i < n; i++) { - var slot = slots[i]; - if (slot.data.name == slotName) { - var attachment = null; - if (attachmentName) { - attachment = this.getAttachmentBySlotIndex(i, attachmentName); - if (!attachment) throw new Error("Attachment not found: " + attachmentName + ", for slot: " + slotName); - } - slot.setAttachment(attachment); - return; - } - } - throw new Error("Slot not found: " + slotName); - }, - /** @return May be null. */ - findIkConstraint: function (ikConstraintName) { - var ikConstraints = this.ikConstraints; - for (var i = 0, n = ikConstraints.length; i < n; i++) - if (ikConstraints[i].data.name == ikConstraintName) return ikConstraints[i]; - return null; - }, - update: function (delta) { - this.time += delta; - } -}; - -spine.EventData = function (name) { - this.intValue = this.floatValue = 0; - - this.name = name; -}; -spine.EventData.prototype = { - intValue: 0, - floatValue: 0, - stringValue: null -}; - -spine.Event = function (data) { - this.intValue = this.floatValue = 0; - - this.data = data; -}; -spine.Event.prototype = { - intValue: 0, - floatValue: 0, - stringValue: null -}; - -spine.AttachmentType = { - region: 0, - boundingbox: 1, - mesh: 2, - skinnedmesh: 3 -}; - -spine.RegionAttachment = function (name) { - this.type = spine.AttachmentType.region; - this.x = this.y = this.rotation = 0; - this.scaleX = this.scaleY = 1; - this.width = this.height = 0; - this.r = this.g = this.b = this.a = 1; - this.regionOffsetX = this.regionOffsetY = this.regionWidth = this.regionHeight = this.regionOriginalWidth = this.regionOriginalHeight = 0; - - this.name = name; - this.offset = []; - this.offset.length = 8; - this.uvs = []; - this.uvs.length = 8; -}; -spine.RegionAttachment.prototype = { - x: 0, y: 0, - rotation: 0, - scaleX: 1, scaleY: 1, - width: 0, height: 0, - r: 1, g: 1, b: 1, a: 1, - path: null, - rendererObject: null, - regionOffsetX: 0, regionOffsetY: 0, - regionWidth: 0, regionHeight: 0, - regionOriginalWidth: 0, regionOriginalHeight: 0, - setUVs: function (u, v, u2, v2, rotate) { - var uvs = this.uvs; - if (rotate) { - uvs[2/*X2*/] = u; - uvs[3/*Y2*/] = v2; - uvs[4/*X3*/] = u; - uvs[5/*Y3*/] = v; - uvs[6/*X4*/] = u2; - uvs[7/*Y4*/] = v; - uvs[0/*X1*/] = u2; - uvs[1/*Y1*/] = v2; - } else { - uvs[0/*X1*/] = u; - uvs[1/*Y1*/] = v2; - uvs[2/*X2*/] = u; - uvs[3/*Y2*/] = v; - uvs[4/*X3*/] = u2; - uvs[5/*Y3*/] = v; - uvs[6/*X4*/] = u2; - uvs[7/*Y4*/] = v2; - } - }, - updateOffset: function () { - var regionScaleX = this.width / this.regionOriginalWidth * this.scaleX; - var regionScaleY = this.height / this.regionOriginalHeight * this.scaleY; - var localX = -this.width / 2 * this.scaleX + this.regionOffsetX * regionScaleX; - var localY = -this.height / 2 * this.scaleY + this.regionOffsetY * regionScaleY; - var localX2 = localX + this.regionWidth * regionScaleX; - var localY2 = localY + this.regionHeight * regionScaleY; - var radians = this.rotation * spine.degRad; - var cos = Math.cos(radians); - var sin = Math.sin(radians); - var localXCos = localX * cos + this.x; - var localXSin = localX * sin; - var localYCos = localY * cos + this.y; - var localYSin = localY * sin; - var localX2Cos = localX2 * cos + this.x; - var localX2Sin = localX2 * sin; - var localY2Cos = localY2 * cos + this.y; - var localY2Sin = localY2 * sin; - var offset = this.offset; - offset[0/*X1*/] = localXCos - localYSin; - offset[1/*Y1*/] = localYCos + localXSin; - offset[2/*X2*/] = localXCos - localY2Sin; - offset[3/*Y2*/] = localY2Cos + localXSin; - offset[4/*X3*/] = localX2Cos - localY2Sin; - offset[5/*Y3*/] = localY2Cos + localX2Sin; - offset[6/*X4*/] = localX2Cos - localYSin; - offset[7/*Y4*/] = localYCos + localX2Sin; - }, - computeVertices: function (x, y, bone, vertices) { - x += bone.worldX; - y += bone.worldY; - var m00 = bone.m00, m01 = bone.m01, m10 = bone.m10, m11 = bone.m11; - var offset = this.offset; - vertices[0/*X1*/] = offset[0/*X1*/] * m00 + offset[1/*Y1*/] * m01 + x; - vertices[1/*Y1*/] = offset[0/*X1*/] * m10 + offset[1/*Y1*/] * m11 + y; - vertices[2/*X2*/] = offset[2/*X2*/] * m00 + offset[3/*Y2*/] * m01 + x; - vertices[3/*Y2*/] = offset[2/*X2*/] * m10 + offset[3/*Y2*/] * m11 + y; - vertices[4/*X3*/] = offset[4/*X3*/] * m00 + offset[5/*X3*/] * m01 + x; - vertices[5/*X3*/] = offset[4/*X3*/] * m10 + offset[5/*X3*/] * m11 + y; - vertices[6/*X4*/] = offset[6/*X4*/] * m00 + offset[7/*Y4*/] * m01 + x; - vertices[7/*Y4*/] = offset[6/*X4*/] * m10 + offset[7/*Y4*/] * m11 + y; - } -}; - -spine.MeshAttachment = function (name) { - this.type = spine.AttachmentType.mesh; - this.hullLength = 0; - this.r = this.g = this.b = this.a = 1; - this.regionU = this.regionV = this.regionV2 = 0; - this.regionRotate = false; - this.regionOffsetX = this.regionOffsetY = this.regionWidth = this.regionHeight = this.regionOriginalWidth = this.regionOriginalHeight = 0; - this.width = this.height = 0; - - this.name = name; -}; -spine.MeshAttachment.prototype = { - vertices: null, - uvs: null, - regionUVs: null, - triangles: null, - hullLength: 0, - r: 1, g: 1, b: 1, a: 1, - path: null, - rendererObject: null, - regionU: 0, regionV: 0, regionU2: 0, regionV2: 0, regionRotate: false, - regionOffsetX: 0, regionOffsetY: 0, - regionWidth: 0, regionHeight: 0, - regionOriginalWidth: 0, regionOriginalHeight: 0, - edges: null, - width: 0, height: 0, - updateUVs: function () { - var width = this.regionU2 - this.regionU, height = this.regionV2 - this.regionV; - var n = this.regionUVs.length; - if (!this.uvs || this.uvs.length != n) { - this.uvs = new spine.Float32Array(n); - } - if (this.regionRotate) { - for (var i = 0; i < n; i += 2) { - this.uvs[i] = this.regionU + this.regionUVs[i + 1] * width; - this.uvs[i + 1] = this.regionV + height - this.regionUVs[i] * height; - } - } else { - for (var i = 0; i < n; i += 2) { - this.uvs[i] = this.regionU + this.regionUVs[i] * width; - this.uvs[i + 1] = this.regionV + this.regionUVs[i + 1] * height; - } - } - }, - computeWorldVertices: function (x, y, slot, worldVertices) { - var bone = slot.bone; - x += bone.worldX; - y += bone.worldY; - var m00 = bone.m00, m01 = bone.m01, m10 = bone.m10, m11 = bone.m11; - var vertices = this.vertices; - var verticesCount = vertices.length; - if (slot.attachmentVertices.length == verticesCount) vertices = slot.attachmentVertices; - for (var i = 0; i < verticesCount; i += 2) { - var vx = vertices[i]; - var vy = vertices[i + 1]; - worldVertices[i] = vx * m00 + vy * m01 + x; - worldVertices[i + 1] = vx * m10 + vy * m11 + y; - } - } -}; - -spine.SkinnedMeshAttachment = function (name) { - this.type = spine.AttachmentType.skinnedmesh; - this.hullLength = 0; - this.r = this.g = this.b = this.a = 1; - this.regionU = this.regionV = this.regionU2 = this.regionV2 = 0; - this.regionRotate = false; - this.regionOffsetX = this.regionOffsetY = this.regionWidth = this.regionHeight = this.regionOriginalWidth = this.regionOriginalHeight = 0; - this.width = this.height = 0; - - this.name = name; -}; -spine.SkinnedMeshAttachment.prototype = { - 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.type = spine.AttachmentType.boundingbox; - - this.name = name; - this.vertices = []; -}; -spine.BoundingBoxAttachment.prototype = { - computeWorldVertices: function (x, y, bone, worldVertices) { - x += bone.worldX; - y += bone.worldY; - var m00 = bone.m00, m01 = bone.m01, m10 = bone.m10, m11 = bone.m11; - var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { - var px = vertices[i]; - var py = vertices[i + 1]; - worldVertices[i] = px * m00 + py * m01 + x; - worldVertices[i + 1] = px * m10 + py * m11 + y; - } - } -}; - -spine.AnimationStateData = function (skeletonData) { - this.skeletonData = skeletonData; - this.animationToMixTime = {}; - - this.defaultMix = 0; -}; -spine.AnimationStateData.prototype = { - defaultMix: 0, - setMixByName: function (fromName, toName, duration) { - var from = this.skeletonData.findAnimation(fromName); - if (!from) throw new Error("Animation not found: " + fromName); - var to = this.skeletonData.findAnimation(toName); - if (!to) throw new Error("Animation not found: " + toName); - this.setMix(from, to, duration); - }, - setMix: function (from, to, duration) { - this.animationToMixTime[from.name + ":" + to.name] = duration; - }, - getMix: function (from, to) { - var key = from.name + ":" + to.name; - return this.animationToMixTime.hasOwnProperty(key) ? this.animationToMixTime[key] : this.defaultMix; - } -}; - -spine.TrackEntry = function () { - this.delay = this.time = this.endTime = 0; - this.lastTime = -1; - this.timeScale = 1; - this.mixTime = this.mixDuration = 1; - this.mix = 1; -}; -spine.TrackEntry.prototype = { - next: null, previous: null, - animation: null, - loop: false, - delay: 0, time: 0, lastTime: -1, endTime: 0, - timeScale: 1, - mixTime: 0, mixDuration: 0, mix: 1, - onStart: null, onEnd: null, onComplete: null, onEvent: null -}; - -spine.AnimationState = function (stateData) { - this.timeScale = 1; - - this.data = stateData; - this.tracks = []; - this.events = []; -}; -spine.AnimationState.prototype = { - onStart: null, - onEnd: null, - onComplete: null, - onEvent: null, - timeScale: 1, - update: function (delta) { - delta *= this.timeScale; - for (var i = 0; i < this.tracks.length; i++) { - var current = this.tracks[i]; - if (!current) continue; - - current.time += delta * current.timeScale; - if (current.previous) { - var previousDelta = delta * current.previous.timeScale; - current.previous.time += previousDelta; - current.mixTime += previousDelta; - } - - var next = current.next; - if (next) { - next.time = current.lastTime - next.delay; - if (next.time >= 0) this.setCurrent(i, next); - } else { - // End non-looping animation when it reaches its end time and there is no next entry. - if (!current.loop && current.lastTime >= current.endTime) this.clearTrack(i); - } - } - }, - apply: function (skeleton) { - for (var i = 0; i < this.tracks.length; i++) { - var current = this.tracks[i]; - if (!current) continue; - - this.events.length = 0; - - var time = current.time; - var lastTime = current.lastTime; - var endTime = current.endTime; - var loop = current.loop; - if (!loop && time > endTime) time = endTime; - - var previous = current.previous; - if (!previous) { - if (current.mix == 1) - current.animation.apply(skeleton, current.lastTime, time, loop, this.events); - else - current.animation.mix(skeleton, current.lastTime, time, loop, this.events, current.mix); - } else { - var previousTime = previous.time; - if (!previous.loop && previousTime > previous.endTime) previousTime = previous.endTime; - previous.animation.apply(skeleton, previousTime, previousTime, previous.loop, null); - - var alpha = current.mixTime / current.mixDuration * current.mix; - if (alpha >= 1) { - alpha = 1; - current.previous = null; - } - current.animation.mix(skeleton, current.lastTime, time, loop, this.events, alpha); - } - - for (var ii = 0, nn = this.events.length; ii < nn; ii++) { - var event = this.events[ii]; - if (current.onEvent) current.onEvent(i, event); - if (this.onEvent) this.onEvent(i, event); - } - - // Check if completed the animation or a loop iteration. - if (loop ? (lastTime % endTime > time % endTime) : (lastTime < endTime && time >= endTime)) { - var count = Math.floor(time / endTime); - if (current.onComplete) current.onComplete(i, count); - if (this.onComplete) this.onComplete(i, count); - } - - current.lastTime = current.time; - } - }, - clearTracks: function () { - for (var i = 0, n = this.tracks.length; i < n; i++) - this.clearTrack(i); - this.tracks.length = 0; - }, - clearTrack: function (trackIndex) { - if (trackIndex >= this.tracks.length) return; - var current = this.tracks[trackIndex]; - if (!current) return; - - if (current.onEnd) current.onEnd(trackIndex); - if (this.onEnd) this.onEnd(trackIndex); - - this.tracks[trackIndex] = null; - }, - _expandToIndex: function (index) { - if (index < this.tracks.length) return this.tracks[index]; - while (index >= this.tracks.length) - this.tracks.push(null); - return null; - }, - setCurrent: function (index, entry) { - var current = this._expandToIndex(index); - if (current) { - var previous = current.previous; - current.previous = null; - - if (current.onEnd) current.onEnd(index); - if (this.onEnd) this.onEnd(index); - - entry.mixDuration = this.data.getMix(current.animation, entry.animation); - if (entry.mixDuration > 0) { - entry.mixTime = 0; - // If a mix is in progress, mix from the closest animation. - if (previous && current.mixTime / current.mixDuration < 0.5) - entry.previous = previous; - else - entry.previous = current; - } - } - - this.tracks[index] = entry; - - if (entry.onStart) entry.onStart(index); - if (this.onStart) this.onStart(index); - }, - setAnimationByName: function (trackIndex, animationName, loop) { - var animation = this.data.skeletonData.findAnimation(animationName); - if (!animation) throw new Error("Animation not found: " + animationName); - return this.setAnimation(trackIndex, animation, loop); - }, - /** Set the current animation. Any queued animations are cleared. */ - setAnimation: function (trackIndex, animation, loop) { - var entry = new spine.TrackEntry(); - entry.animation = animation; - entry.loop = loop; - entry.endTime = animation.duration; - this.setCurrent(trackIndex, entry); - return entry; - }, - addAnimationByName: function (trackIndex, animationName, loop, delay) { - var animation = this.data.skeletonData.findAnimation(animationName); - if (!animation) throw new Error("Animation not found: " + animationName); - return this.addAnimation(trackIndex, animation, loop, delay); - }, - /** Adds an animation to be played delay seconds after the current or last queued animation. - * @param delay May be <= 0 to use duration of previous animation minus any mix duration plus the negative delay. */ - addAnimation: function (trackIndex, animation, loop, delay) { - var entry = new spine.TrackEntry(); - entry.animation = animation; - entry.loop = loop; - entry.endTime = animation.duration; - - var last = this._expandToIndex(trackIndex); - if (last) { - while (last.next) - last = last.next; - last.next = entry; - } else - this.tracks[trackIndex] = entry; - - if (delay <= 0) { - if (last) - delay += last.endTime - this.data.getMix(last.animation, animation); - else - delay = 0; - } - entry.delay = delay; - - return entry; - }, - /** May be null. */ - getCurrent: function (trackIndex) { - if (trackIndex >= this.tracks.length) return null; - return this.tracks[trackIndex]; - } -}; - -spine.SkeletonJson = function (attachmentLoader) { - this.scale = 1; - - this.attachmentLoader = attachmentLoader; -}; -spine.SkeletonJson.prototype = { - scale: 1, - readSkeletonData: function (root, name) { - var skeletonData = new spine.SkeletonData(); - skeletonData.name = name; - - // Skeleton. - var skeletonMap = root["skeleton"]; - if (skeletonMap) { - skeletonData.hash = skeletonMap["hash"]; - skeletonData.version = skeletonMap["spine"]; - skeletonData.width = skeletonMap["width"] || 0; - skeletonData.height = skeletonMap["height"] || 0; - } - - // Bones. - var bones = root["bones"]; - for (var i = 0, n = bones.length; i < n; i++) { - var boneMap = bones[i]; - var parent = null; - if (boneMap["parent"]) { - parent = skeletonData.findBone(boneMap["parent"]); - if (!parent) throw new Error("Parent bone not found: " + boneMap["parent"]); - } - var boneData = new spine.BoneData(boneMap["name"], parent); - boneData.length = (boneMap["length"] || 0) * this.scale; - boneData.x = (boneMap["x"] || 0) * this.scale; - boneData.y = (boneMap["y"] || 0) * this.scale; - boneData.rotation = (boneMap["rotation"] || 0); - boneData.scaleX = boneMap.hasOwnProperty("scaleX") ? boneMap["scaleX"] : 1; - boneData.scaleY = boneMap.hasOwnProperty("scaleY") ? boneMap["scaleY"] : 1; - boneData.inheritScale = boneMap.hasOwnProperty("inheritScale") ? boneMap["inheritScale"] : true; - boneData.inheritRotation = boneMap.hasOwnProperty("inheritRotation") ? boneMap["inheritRotation"] : true; - skeletonData.bones.push(boneData); - } - - // IK constraints. - var ik = root["ik"]; - if (ik) { - for (var i = 0, n = ik.length; i < n; i++) { - var ikMap = ik[i]; - var ikConstraintData = new spine.IkConstraintData(ikMap["name"]); - - var bones = ikMap["bones"]; - for (var ii = 0, nn = bones.length; ii < nn; ii++) { - var bone = skeletonData.findBone(bones[ii]); - if (!bone) throw new Error("IK bone not found: " + bones[ii]); - ikConstraintData.bones.push(bone); - } - - ikConstraintData.target = skeletonData.findBone(ikMap["target"]); - if (!ikConstraintData.target) throw new Error("Target bone not found: " + ikMap["target"]); - - ikConstraintData.bendDirection = (!ikMap.hasOwnProperty("bendPositive") || ikMap["bendPositive"]) ? 1 : -1; - ikConstraintData.mix = ikMap.hasOwnProperty("mix") ? ikMap["mix"] : 1; - - skeletonData.ikConstraints.push(ikConstraintData); - } - } - - // Slots. - var slots = root["slots"]; - for (var i = 0, n = slots.length; i < n; i++) { - var slotMap = slots[i]; - var boneData = skeletonData.findBone(slotMap["bone"]); - if (!boneData) throw new Error("Slot bone not found: " + slotMap["bone"]); - var slotData = new spine.SlotData(slotMap["name"], boneData); - - var color = slotMap["color"]; - if (color) { - slotData.r = this.toColor(color, 0); - slotData.g = this.toColor(color, 1); - slotData.b = this.toColor(color, 2); - slotData.a = this.toColor(color, 3); - } - - slotData.attachmentName = slotMap["attachment"]; - slotData.blendMode = spine.AttachmentType[slotMap["blend"] || "normal"]; - - skeletonData.slots.push(slotData); - } - - // Skins. - var skins = root["skins"]; - for (var skinName in skins) { - if (!skins.hasOwnProperty(skinName)) continue; - var skinMap = skins[skinName]; - var skin = new spine.Skin(skinName); - for (var slotName in skinMap) { - if (!skinMap.hasOwnProperty(slotName)) continue; - var slotIndex = skeletonData.findSlotIndex(slotName); - var slotEntry = skinMap[slotName]; - for (var attachmentName in slotEntry) { - if (!slotEntry.hasOwnProperty(attachmentName)) continue; - var attachment = this.readAttachment(skin, attachmentName, slotEntry[attachmentName]); - if (attachment) skin.addAttachment(slotIndex, attachmentName, attachment); - } - } - skeletonData.skins.push(skin); - if (skin.name == "default") skeletonData.defaultSkin = skin; - } - - // Events. - var events = root["events"]; - for (var eventName in events) { - if (!events.hasOwnProperty(eventName)) continue; - var eventMap = events[eventName]; - var eventData = new spine.EventData(eventName); - eventData.intValue = eventMap["int"] || 0; - eventData.floatValue = eventMap["float"] || 0; - eventData.stringValue = eventMap["string"] || null; - skeletonData.events.push(eventData); - } - - // Animations. - var animations = root["animations"]; - for (var animationName in animations) { - if (!animations.hasOwnProperty(animationName)) continue; - this.readAnimation(animationName, animations[animationName], skeletonData); - } - - return skeletonData; - }, - readAttachment: function (skin, name, map) { - name = map["name"] || name; - - var type = spine.AttachmentType[map["type"] || "region"]; - var path = map["path"] || name; - - var scale = this.scale; - if (type == spine.AttachmentType.region) { - var region = this.attachmentLoader.newRegionAttachment(skin, name, path); - if (!region) return null; - region.path = path; - region.x = (map["x"] || 0) * scale; - region.y = (map["y"] || 0) * scale; - region.scaleX = map.hasOwnProperty("scaleX") ? map["scaleX"] : 1; - region.scaleY = map.hasOwnProperty("scaleY") ? map["scaleY"] : 1; - region.rotation = map["rotation"] || 0; - region.width = (map["width"] || 0) * scale; - region.height = (map["height"] || 0) * scale; - - var color = map["color"]; - if (color) { - region.r = this.toColor(color, 0); - region.g = this.toColor(color, 1); - region.b = this.toColor(color, 2); - region.a = this.toColor(color, 3); - } - - region.updateOffset(); - return region; - } else if (type == spine.AttachmentType.mesh) { - var mesh = this.attachmentLoader.newMeshAttachment(skin, name, path); - if (!mesh) return null; - mesh.path = path; - mesh.vertices = this.getFloatArray(map, "vertices", scale); - mesh.triangles = this.getIntArray(map, "triangles"); - mesh.regionUVs = this.getFloatArray(map, "uvs", 1); - mesh.updateUVs(); - - color = map["color"]; - if (color) { - mesh.r = this.toColor(color, 0); - mesh.g = this.toColor(color, 1); - mesh.b = this.toColor(color, 2); - mesh.a = this.toColor(color, 3); - } - - mesh.hullLength = (map["hull"] || 0) * 2; - if (map["edges"]) mesh.edges = this.getIntArray(map, "edges"); - mesh.width = (map["width"] || 0) * scale; - mesh.height = (map["height"] || 0) * scale; - return mesh; - } else if (type == spine.AttachmentType.skinnedmesh) { - var mesh = this.attachmentLoader.newSkinnedMeshAttachment(skin, name, path); - if (!mesh) return null; - mesh.path = path; - - var uvs = this.getFloatArray(map, "uvs", 1); - var vertices = this.getFloatArray(map, "vertices", 1); - var weights = []; - var bones = []; - for (var i = 0, n = vertices.length; i < n; ) { - var boneCount = vertices[i++] | 0; - bones[bones.length] = boneCount; - for (var nn = i + boneCount * 4; i < nn; ) { - bones[bones.length] = vertices[i]; - weights[weights.length] = vertices[i + 1] * scale; - weights[weights.length] = vertices[i + 2] * scale; - weights[weights.length] = vertices[i + 3]; - i += 4; - } - } - mesh.bones = bones; - mesh.weights = weights; - mesh.triangles = this.getIntArray(map, "triangles"); - mesh.regionUVs = uvs; - mesh.updateUVs(); - - color = map["color"]; - if (color) { - mesh.r = this.toColor(color, 0); - mesh.g = this.toColor(color, 1); - mesh.b = this.toColor(color, 2); - mesh.a = this.toColor(color, 3); - } - - mesh.hullLength = (map["hull"] || 0) * 2; - if (map["edges"]) mesh.edges = this.getIntArray(map, "edges"); - mesh.width = (map["width"] || 0) * scale; - mesh.height = (map["height"] || 0) * scale; - return mesh; - } else if (type == spine.AttachmentType.boundingbox) { - var attachment = this.attachmentLoader.newBoundingBoxAttachment(skin, name); - var vertices = map["vertices"]; - for (var i = 0, n = vertices.length; i < n; i++) - attachment.vertices.push(vertices[i] * scale); - return attachment; - } - throw new Error("Unknown attachment type: " + type); - }, - readAnimation: function (name, map, skeletonData) { - var timelines = []; - var duration = 0; - - var slots = map["slots"]; - for (var slotName in slots) { - if (!slots.hasOwnProperty(slotName)) continue; - var slotMap = slots[slotName]; - var slotIndex = skeletonData.findSlotIndex(slotName); - - for (var timelineName in slotMap) { - if (!slotMap.hasOwnProperty(timelineName)) continue; - var values = slotMap[timelineName]; - if (timelineName == "color") { - var timeline = new spine.ColorTimeline(values.length); - timeline.slotIndex = slotIndex; - - var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { - var valueMap = values[i]; - var color = valueMap["color"]; - var r = this.toColor(color, 0); - var g = this.toColor(color, 1); - var b = this.toColor(color, 2); - var a = this.toColor(color, 3); - timeline.setFrame(frameIndex, valueMap["time"], r, g, b, a); - this.readCurve(timeline, frameIndex, valueMap); - frameIndex++; - } - timelines.push(timeline); - duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 5 - 5]); - - } else if (timelineName == "attachment") { - var timeline = new spine.AttachmentTimeline(values.length); - timeline.slotIndex = slotIndex; - - var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { - var valueMap = values[i]; - timeline.setFrame(frameIndex++, valueMap["time"], valueMap["name"]); - } - timelines.push(timeline); - duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]); - - } else - throw new Error("Invalid timeline type for a slot: " + timelineName + " (" + slotName + ")"); - } - } - - var bones = map["bones"]; - for (var boneName in bones) { - if (!bones.hasOwnProperty(boneName)) continue; - var boneIndex = skeletonData.findBoneIndex(boneName); - if (boneIndex == -1) throw new Error("Bone not found: " + boneName); - var boneMap = bones[boneName]; - - for (var timelineName in boneMap) { - if (!boneMap.hasOwnProperty(timelineName)) continue; - var values = boneMap[timelineName]; - if (timelineName == "rotate") { - var timeline = new spine.RotateTimeline(values.length); - timeline.boneIndex = boneIndex; - - var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { - var valueMap = values[i]; - timeline.setFrame(frameIndex, valueMap["time"], valueMap["angle"]); - this.readCurve(timeline, frameIndex, valueMap); - frameIndex++; - } - timelines.push(timeline); - duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 2 - 2]); - - } else if (timelineName == "translate" || timelineName == "scale") { - var timeline; - var timelineScale = 1; - if (timelineName == "scale") - timeline = new spine.ScaleTimeline(values.length); - else { - timeline = new spine.TranslateTimeline(values.length); - timelineScale = this.scale; - } - timeline.boneIndex = boneIndex; - - var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { - var valueMap = values[i]; - var x = (valueMap["x"] || 0) * timelineScale; - var y = (valueMap["y"] || 0) * timelineScale; - timeline.setFrame(frameIndex, valueMap["time"], x, y); - this.readCurve(timeline, frameIndex, valueMap); - frameIndex++; - } - timelines.push(timeline); - duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 3 - 3]); - - } else if (timelineName == "flipX" || timelineName == "flipY") { - var x = timelineName == "flipX"; - var timeline = x ? new spine.FlipXTimeline(values.length) : new spine.FlipYTimeline(values.length); - timeline.boneIndex = boneIndex; - - var field = x ? "x" : "y"; - var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { - var valueMap = values[i]; - timeline.setFrame(frameIndex, valueMap["time"], valueMap[field] || false); - frameIndex++; - } - timelines.push(timeline); - duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 2 - 2]); - } else - throw new Error("Invalid timeline type for a bone: " + timelineName + " (" + boneName + ")"); - } - } - - var ikMap = map["ik"]; - for (var ikConstraintName in ikMap) { - if (!ikMap.hasOwnProperty(ikConstraintName)) continue; - var ikConstraint = skeletonData.findIkConstraint(ikConstraintName); - var values = ikMap[ikConstraintName]; - var timeline = new spine.IkConstraintTimeline(values.length); - timeline.ikConstraintIndex = skeletonData.ikConstraints.indexOf(ikConstraint); - var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { - var valueMap = values[i]; - var mix = valueMap.hasOwnProperty("mix") ? valueMap["mix"] : 1; - var bendDirection = (!valueMap.hasOwnProperty("bendPositive") || valueMap["bendPositive"]) ? 1 : -1; - timeline.setFrame(frameIndex, valueMap["time"], mix, bendDirection); - this.readCurve(timeline, frameIndex, valueMap); - frameIndex++; - } - timelines.push(timeline); - duration = Math.max(duration, timeline.frames[timeline.frameCount * 3 - 3]); - } - - var ffd = map["ffd"]; - for (var skinName in ffd) { - var skin = skeletonData.findSkin(skinName); - var slotMap = ffd[skinName]; - for (slotName in slotMap) { - var slotIndex = skeletonData.findSlotIndex(slotName); - var meshMap = slotMap[slotName]; - for (var meshName in meshMap) { - var values = meshMap[meshName]; - var timeline = new spine.FfdTimeline(values.length); - var attachment = skin.getAttachment(slotIndex, meshName); - if (!attachment) throw new Error("FFD attachment not found: " + meshName); - timeline.slotIndex = slotIndex; - timeline.attachment = attachment; - - var isMesh = attachment.type == spine.AttachmentType.mesh; - var vertexCount; - if (isMesh) - vertexCount = attachment.vertices.length; - else - vertexCount = attachment.weights.length / 3 * 2; - - var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { - var valueMap = values[i]; - var vertices; - if (!valueMap["vertices"]) { - if (isMesh) - vertices = attachment.vertices; - else { - vertices = []; - vertices.length = vertexCount; - } - } else { - var verticesValue = valueMap["vertices"]; - var vertices = []; - vertices.length = vertexCount; - var start = valueMap["offset"] || 0; - var nn = verticesValue.length; - if (this.scale == 1) { - for (var ii = 0; ii < nn; ii++) - vertices[ii + start] = verticesValue[ii]; - } else { - for (var ii = 0; ii < nn; ii++) - vertices[ii + start] = verticesValue[ii] * this.scale; - } - if (isMesh) { - var meshVertices = attachment.vertices; - for (var ii = 0, nn = vertices.length; ii < nn; ii++) - vertices[ii] += meshVertices[ii]; - } - } - - timeline.setFrame(frameIndex, valueMap["time"], vertices); - this.readCurve(timeline, frameIndex, valueMap); - frameIndex++; - } - timelines[timelines.length] = timeline; - duration = Math.max(duration, timeline.frames[timeline.frameCount - 1]); - } - } - } - - var drawOrderValues = map["drawOrder"]; - if (!drawOrderValues) drawOrderValues = map["draworder"]; - if (drawOrderValues) { - var timeline = new spine.DrawOrderTimeline(drawOrderValues.length); - var slotCount = skeletonData.slots.length; - var frameIndex = 0; - for (var i = 0, n = drawOrderValues.length; i < n; i++) { - var drawOrderMap = drawOrderValues[i]; - var drawOrder = null; - if (drawOrderMap["offsets"]) { - drawOrder = []; - drawOrder.length = slotCount; - for (var ii = slotCount - 1; ii >= 0; ii--) - drawOrder[ii] = -1; - var offsets = drawOrderMap["offsets"]; - var unchanged = []; - unchanged.length = slotCount - offsets.length; - var originalIndex = 0, unchangedIndex = 0; - for (var ii = 0, nn = offsets.length; ii < nn; ii++) { - var offsetMap = offsets[ii]; - var slotIndex = skeletonData.findSlotIndex(offsetMap["slot"]); - if (slotIndex == -1) throw new Error("Slot not found: " + offsetMap["slot"]); - // Collect unchanged items. - while (originalIndex != slotIndex) - unchanged[unchangedIndex++] = originalIndex++; - // Set changed items. - drawOrder[originalIndex + offsetMap["offset"]] = originalIndex++; - } - // Collect remaining unchanged items. - while (originalIndex < slotCount) - unchanged[unchangedIndex++] = originalIndex++; - // Fill in unchanged items. - for (var ii = slotCount - 1; ii >= 0; ii--) - if (drawOrder[ii] == -1) drawOrder[ii] = unchanged[--unchangedIndex]; - } - timeline.setFrame(frameIndex++, drawOrderMap["time"], drawOrder); - } - timelines.push(timeline); - duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]); - } - - var events = map["events"]; - if (events) { - var timeline = new spine.EventTimeline(events.length); - var frameIndex = 0; - for (var i = 0, n = events.length; i < n; i++) { - var eventMap = events[i]; - var eventData = skeletonData.findEvent(eventMap["name"]); - if (!eventData) throw new Error("Event not found: " + eventMap["name"]); - var event = new spine.Event(eventData); - event.intValue = eventMap.hasOwnProperty("int") ? eventMap["int"] : eventData.intValue; - event.floatValue = eventMap.hasOwnProperty("float") ? eventMap["float"] : eventData.floatValue; - event.stringValue = eventMap.hasOwnProperty("string") ? eventMap["string"] : eventData.stringValue; - timeline.setFrame(frameIndex++, eventMap["time"], event); - } - timelines.push(timeline); - duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]); - } - - skeletonData.animations.push(new spine.Animation(name, timelines, duration)); - }, - readCurve: function (timeline, frameIndex, valueMap) { - var curve = valueMap["curve"]; - if (!curve) - timeline.curves.setLinear(frameIndex); - else if (curve == "stepped") - timeline.curves.setStepped(frameIndex); - else if (curve instanceof Array) - timeline.curves.setCurve(frameIndex, curve[0], curve[1], curve[2], curve[3]); - }, - toColor: function (hexString, colorIndex) { - if (hexString.length != 8) throw new Error("Color hexidecimal length must be 8, recieved: " + hexString); - return parseInt(hexString.substring(colorIndex * 2, (colorIndex * 2) + 2), 16) / 255; - }, - getFloatArray: function (map, name, scale) { - var list = map[name]; - var values = new spine.Float32Array(list.length); - var i = 0, n = list.length; - if (scale == 1) { - for (; i < n; i++) - values[i] = list[i]; - } else { - for (; i < n; i++) - values[i] = list[i] * scale; - } - return values; - }, - getIntArray: function (map, name) { - var list = map[name]; - var values = new spine.Uint16Array(list.length); - for (var i = 0, n = list.length; i < n; i++) - values[i] = list[i] | 0; - return values; - } -}; - -spine.Atlas = function (atlasText, textureLoader) { - this.textureLoader = textureLoader; - this.pages = []; - this.regions = []; - - var reader = new spine.AtlasReader(atlasText); - var tuple = []; - tuple.length = 4; - var page = null; - while (true) { - var line = reader.readLine(); - if (line === null) break; - line = reader.trim(line); - if (!line.length) - page = null; - else if (!page) { - page = new spine.AtlasPage(); - page.name = line; - - if (reader.readTuple(tuple) == 2) { // size is only optional for an atlas packed with an old TexturePacker. - page.width = parseInt(tuple[0]); - page.height = parseInt(tuple[1]); - reader.readTuple(tuple); - } - page.format = spine.Atlas.Format[tuple[0]]; - - reader.readTuple(tuple); - page.minFilter = spine.Atlas.TextureFilter[tuple[0]]; - page.magFilter = spine.Atlas.TextureFilter[tuple[1]]; - - var direction = reader.readValue(); - page.uWrap = spine.Atlas.TextureWrap.clampToEdge; - page.vWrap = spine.Atlas.TextureWrap.clampToEdge; - if (direction == "x") - page.uWrap = spine.Atlas.TextureWrap.repeat; - else if (direction == "y") - page.vWrap = spine.Atlas.TextureWrap.repeat; - else if (direction == "xy") - page.uWrap = page.vWrap = spine.Atlas.TextureWrap.repeat; - - textureLoader.load(page, line, this); - - this.pages.push(page); - - } else { - var region = new spine.AtlasRegion(); - region.name = line; - region.page = page; - - region.rotate = reader.readValue() == "true"; - - reader.readTuple(tuple); - var x = parseInt(tuple[0]); - var y = parseInt(tuple[1]); - - reader.readTuple(tuple); - var width = parseInt(tuple[0]); - var height = parseInt(tuple[1]); - - region.u = x / page.width; - region.v = y / page.height; - if (region.rotate) { - region.u2 = (x + height) / page.width; - region.v2 = (y + width) / page.height; - } else { - region.u2 = (x + width) / page.width; - region.v2 = (y + height) / page.height; - } - region.x = x; - region.y = y; - region.width = Math.abs(width); - region.height = Math.abs(height); - - if (reader.readTuple(tuple) == 4) { // split is optional - region.splits = [parseInt(tuple[0]), parseInt(tuple[1]), parseInt(tuple[2]), parseInt(tuple[3])]; - - if (reader.readTuple(tuple) == 4) { // pad is optional, but only present with splits - region.pads = [parseInt(tuple[0]), parseInt(tuple[1]), parseInt(tuple[2]), parseInt(tuple[3])]; - - reader.readTuple(tuple); - } - } - - region.originalWidth = parseInt(tuple[0]); - region.originalHeight = parseInt(tuple[1]); - - reader.readTuple(tuple); - region.offsetX = parseInt(tuple[0]); - region.offsetY = parseInt(tuple[1]); - - region.index = parseInt(reader.readValue()); - - this.regions.push(region); - } - } -}; -spine.Atlas.prototype = { - findRegion: function (name) { - var regions = this.regions; - for (var i = 0, n = regions.length; i < n; i++) - if (regions[i].name == name) return regions[i]; - return null; - }, - dispose: function () { - var pages = this.pages; - for (var i = 0, n = pages.length; i < n; i++) - this.textureLoader.unload(pages[i].rendererObject); - }, - updateUVs: function (page) { - var regions = this.regions; - for (var i = 0, n = regions.length; i < n; i++) { - var region = regions[i]; - if (region.page != page) continue; - region.u = region.x / page.width; - region.v = region.y / page.height; - if (region.rotate) { - region.u2 = (region.x + region.height) / page.width; - region.v2 = (region.y + region.width) / page.height; - } else { - region.u2 = (region.x + region.width) / page.width; - region.v2 = (region.y + region.height) / page.height; - } - } - } -}; - -spine.Atlas.Format = { - alpha: 0, - intensity: 1, - luminanceAlpha: 2, - rgb565: 3, - rgba4444: 4, - rgb888: 5, - rgba8888: 6 -}; - -spine.Atlas.TextureFilter = { - nearest: 0, - linear: 1, - mipMap: 2, - mipMapNearestNearest: 3, - mipMapLinearNearest: 4, - mipMapNearestLinear: 5, - mipMapLinearLinear: 6 -}; - -spine.Atlas.TextureWrap = { - mirroredRepeat: 0, - clampToEdge: 1, - repeat: 2 -}; - -spine.AtlasPage = function () { - this.width = this.height = 0; -}; -spine.AtlasPage.prototype = { - name: null, - format: null, - minFilter: null, - magFilter: null, - uWrap: null, - vWrap: null, - rendererObject: null, - width: 0, - height: 0 -}; - -spine.AtlasRegion = function () { - this.x = this.y = this.width = this.height = - this.u = this.v = this.u2 = this.v2 = - this.offsetX = this.offsetY = - this.originalWidth = this.originalHeight = 0; - this.index = 0; -}; -spine.AtlasRegion.prototype = { - page: null, - name: null, - x: 0, y: 0, - width: 0, height: 0, - u: 0, v: 0, u2: 0, v2: 0, - offsetX: 0, offsetY: 0, - originalWidth: 0, originalHeight: 0, - index: 0, - rotate: false, - splits: null, - pads: null -}; - -spine.AtlasReader = function (text) { - this.index = 0; - - this.lines = text.split(/\r\n|\r|\n/); -}; -spine.AtlasReader.prototype = { - index: 0, - trim: function (value) { - return value.replace(/^\s+|\s+$/g, ""); - }, - readLine: function () { - if (this.index >= this.lines.length) return null; - return this.lines[this.index++]; - }, - readValue: function () { - var line = this.readLine(); - var colon = line.indexOf(":"); - if (colon == -1) throw new Error("Invalid line: " + line); - return this.trim(line.substring(colon + 1)); - }, - /** Returns the number of tuple values read (1, 2 or 4). */ - readTuple: function (tuple) { - var line = this.readLine(); - var colon = line.indexOf(":"); - if (colon == -1) throw new Error("Invalid line: " + line); - var i = 0, lastMatch = colon + 1; - for (; i < 3; i++) { - var comma = line.indexOf(",", lastMatch); - if (comma == -1) break; - tuple[i] = this.trim(line.substr(lastMatch, comma - lastMatch)); - lastMatch = comma + 1; - } - tuple[i] = this.trim(line.substring(lastMatch)); - return i + 1; - } -}; - -spine.AtlasAttachmentLoader = function (atlas) { - this.atlas = atlas; -}; -spine.AtlasAttachmentLoader.prototype = { - newRegionAttachment: function (skin, name, path) { - var region = this.atlas.findRegion(path); - if (!region) throw new Error("Region not found in atlas: " + path + " (region attachment: " + name + ")"); - var attachment = new spine.RegionAttachment(name); - attachment.rendererObject = region; - attachment.setUVs(region.u, region.v, region.u2, region.v2, region.rotate); - attachment.regionOffsetX = region.offsetX; - attachment.regionOffsetY = region.offsetY; - attachment.regionWidth = region.width; - attachment.regionHeight = region.height; - attachment.regionOriginalWidth = region.originalWidth; - attachment.regionOriginalHeight = region.originalHeight; - return attachment; - }, - newMeshAttachment: function (skin, name, path) { - var region = this.atlas.findRegion(path); - if (!region) throw new Error("Region not found in atlas: " + path + " (mesh attachment: " + name + ")"); - var attachment = new spine.MeshAttachment(name); - attachment.rendererObject = region; - attachment.regionU = region.u; - attachment.regionV = region.v; - attachment.regionU2 = region.u2; - attachment.regionV2 = region.v2; - attachment.regionRotate = region.rotate; - attachment.regionOffsetX = region.offsetX; - attachment.regionOffsetY = region.offsetY; - attachment.regionWidth = region.width; - attachment.regionHeight = region.height; - attachment.regionOriginalWidth = region.originalWidth; - attachment.regionOriginalHeight = region.originalHeight; - return attachment; - }, - newSkinnedMeshAttachment: function (skin, name, path) { - var region = this.atlas.findRegion(path); - if (!region) throw new Error("Region not found in atlas: " + path + " (skinned mesh attachment: " + name + ")"); - var attachment = new spine.SkinnedMeshAttachment(name); - attachment.rendererObject = region; - attachment.regionU = region.u; - attachment.regionV = region.v; - attachment.regionU2 = region.u2; - attachment.regionV2 = region.v2; - attachment.regionRotate = region.rotate; - attachment.regionOffsetX = region.offsetX; - attachment.regionOffsetY = region.offsetY; - attachment.regionWidth = region.width; - attachment.regionHeight = region.height; - attachment.regionOriginalWidth = region.originalWidth; - attachment.regionOriginalHeight = region.originalHeight; - return attachment; - }, - newBoundingBoxAttachment: function (skin, name) { - return new spine.BoundingBoxAttachment(name); - } -}; - -spine.SkeletonBounds = function () { - this.minX = this.minY = this.maxX = this.maxY = 0; - - this.polygonPool = []; - this.polygons = []; - this.boundingBoxes = []; -}; -spine.SkeletonBounds.prototype = { - minX: 0, minY: 0, maxX: 0, maxY: 0, - update: function (skeleton, updateAabb) { - var slots = skeleton.slots; - var slotCount = slots.length; - var x = skeleton.x, y = skeleton.y; - var boundingBoxes = this.boundingBoxes; - var polygonPool = this.polygonPool; - var polygons = this.polygons; - - boundingBoxes.length = 0; - for (var i = 0, n = polygons.length; i < n; i++) - polygonPool.push(polygons[i]); - polygons.length = 0; - - for (var i = 0; i < slotCount; i++) { - var slot = slots[i]; - var boundingBox = slot.attachment; - if (boundingBox.type != spine.AttachmentType.boundingbox) continue; - boundingBoxes.push(boundingBox); - - var poolCount = polygonPool.length, polygon; - if (poolCount > 0) { - polygon = polygonPool[poolCount - 1]; - polygonPool.splice(poolCount - 1, 1); - } else - polygon = []; - polygons.push(polygon); - - polygon.length = boundingBox.vertices.length; - boundingBox.computeWorldVertices(x, y, slot.bone, polygon); - } - - if (updateAabb) this.aabbCompute(); - }, - aabbCompute: function () { - var polygons = this.polygons; - var minX = Number.MAX_VALUE, minY = Number.MAX_VALUE, maxX = Number.MIN_VALUE, maxY = Number.MIN_VALUE; - for (var i = 0, n = polygons.length; i < n; i++) { - var vertices = polygons[i]; - for (var ii = 0, nn = vertices.length; ii < nn; ii += 2) { - var x = vertices[ii]; - var y = vertices[ii + 1]; - minX = Math.min(minX, x); - minY = Math.min(minY, y); - maxX = Math.max(maxX, x); - maxY = Math.max(maxY, y); - } - } - this.minX = minX; - this.minY = minY; - this.maxX = maxX; - this.maxY = maxY; - }, - /** Returns true if the axis aligned bounding box contains the point. */ - aabbContainsPoint: function (x, y) { - return x >= this.minX && x <= this.maxX && y >= this.minY && y <= this.maxY; - }, - /** Returns true if the axis aligned bounding box intersects the line segment. */ - aabbIntersectsSegment: function (x1, y1, x2, y2) { - var minX = this.minX, minY = this.minY, maxX = this.maxX, maxY = this.maxY; - if ((x1 <= minX && x2 <= minX) || (y1 <= minY && y2 <= minY) || (x1 >= maxX && x2 >= maxX) || (y1 >= maxY && y2 >= maxY)) - return false; - var m = (y2 - y1) / (x2 - x1); - var y = m * (minX - x1) + y1; - if (y > minY && y < maxY) return true; - y = m * (maxX - x1) + y1; - if (y > minY && y < maxY) return true; - var x = (minY - y1) / m + x1; - if (x > minX && x < maxX) return true; - x = (maxY - y1) / m + x1; - if (x > minX && x < maxX) return true; - return false; - }, - /** Returns true if the axis aligned bounding box intersects the axis aligned bounding box of the specified bounds. */ - aabbIntersectsSkeleton: function (bounds) { - return this.minX < bounds.maxX && this.maxX > bounds.minX && this.minY < bounds.maxY && this.maxY > bounds.minY; - }, - /** Returns the first bounding box attachment that contains the point, or null. When doing many checks, it is usually more - * efficient to only call this method if {@link #aabbContainsPoint(float, float)} returns true. */ - containsPoint: function (x, y) { - var polygons = this.polygons; - for (var i = 0, n = polygons.length; i < n; i++) - if (this.polygonContainsPoint(polygons[i], x, y)) return this.boundingBoxes[i]; - return null; - }, - /** Returns the first bounding box attachment that contains the line segment, or null. When doing many checks, it is usually - * more efficient to only call this method if {@link #aabbIntersectsSegment(float, float, float, float)} returns true. */ - intersectsSegment: function (x1, y1, x2, y2) { - var polygons = this.polygons; - for (var i = 0, n = polygons.length; i < n; i++) - if (polygons[i].intersectsSegment(x1, y1, x2, y2)) return this.boundingBoxes[i]; - return null; - }, - /** Returns true if the polygon contains the point. */ - polygonContainsPoint: function (polygon, x, y) { - var nn = polygon.length; - var prevIndex = nn - 2; - var inside = false; - for (var ii = 0; ii < nn; ii += 2) { - var vertexY = polygon[ii + 1]; - var prevY = polygon[prevIndex + 1]; - if ((vertexY < y && prevY >= y) || (prevY < y && vertexY >= y)) { - var vertexX = polygon[ii]; - if (vertexX + (y - vertexY) / (prevY - vertexY) * (polygon[prevIndex] - vertexX) < x) inside = !inside; - } - prevIndex = ii; - } - return inside; - }, - /** Returns true if the polygon contains the line segment. */ - polygonIntersectsSegment: function (polygon, x1, y1, x2, y2) { - var nn = polygon.length; - var width12 = x1 - x2, height12 = y1 - y2; - var det1 = x1 * y2 - y1 * x2; - var x3 = polygon[nn - 2], y3 = polygon[nn - 1]; - for (var ii = 0; ii < nn; ii += 2) { - var x4 = polygon[ii], y4 = polygon[ii + 1]; - var det2 = x3 * y4 - y3 * x4; - var width34 = x3 - x4, height34 = y3 - y4; - var det3 = width12 * height34 - height12 * width34; - var x = (det1 * width34 - width12 * det2) / det3; - if (((x >= x3 && x <= x4) || (x >= x4 && x <= x3)) && ((x >= x1 && x <= x2) || (x >= x2 && x <= x1))) { - var y = (det1 * height34 - height12 * det2) / det3; - if (((y >= y3 && y <= y4) || (y >= y4 && y <= y3)) && ((y >= y1 && y <= y2) || (y >= y2 && y <= y1))) return true; - } - x3 = x4; - y3 = y4; - } - return false; - }, - getPolygon: function (attachment) { - var index = this.boundingBoxes.indexOf(attachment); - return index == -1 ? null : this.polygons[index]; - }, - getWidth: function () { - return this.maxX - this.minX; - }, - getHeight: function () { - return this.maxY - this.minY; - } -}; diff --git a/external/socketio/socket.io.js b/external/socketio/socket.io.js index 16caccfc1d..e69de29bb2 100644 --- a/external/socketio/socket.io.js +++ b/external/socketio/socket.io.js @@ -1,7000 +0,0 @@ -!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.io=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0 && !this.encoding) { - var pack = this.packetBuffer.shift(); - this.packet(pack); - } - }; - - /** - * Clean up transport subscriptions and packet buffer. - * - * @api private - */ - - Manager.prototype.cleanup = function(){ - var sub; - while (sub = this.subs.shift()) sub.destroy(); - - this.packetBuffer = []; - this.encoding = false; - - this.decoder.destroy(); - }; - - /** - * Close the current socket. - * - * @api private - */ - - Manager.prototype.close = - Manager.prototype.disconnect = function(){ - this.skipReconnect = true; - this.backoff.reset(); - this.readyState = 'closed'; - this.engine && this.engine.close(); - }; - - /** - * Called upon engine close. - * - * @api private - */ - - Manager.prototype.onclose = function(reason){ - debug('close'); - this.cleanup(); - this.backoff.reset(); - this.readyState = 'closed'; - this.emit('close', reason); - if (this._reconnection && !this.skipReconnect) { - this.reconnect(); - } - }; - - /** - * Attempt a reconnection. - * - * @api private - */ - - Manager.prototype.reconnect = function(){ - if (this.reconnecting || this.skipReconnect) return this; - - var self = this; - - if (this.backoff.attempts >= this._reconnectionAttempts) { - debug('reconnect failed'); - this.backoff.reset(); - this.emitAll('reconnect_failed'); - this.reconnecting = false; - } else { - var delay = this.backoff.duration(); - debug('will wait %dms before reconnect attempt', delay); - - this.reconnecting = true; - var timer = setTimeout(function(){ - if (self.skipReconnect) return; - - debug('attempting reconnect'); - self.emitAll('reconnect_attempt', self.backoff.attempts); - self.emitAll('reconnecting', self.backoff.attempts); - - // check again for the case socket closed in above events - if (self.skipReconnect) return; - - self.open(function(err){ - if (err) { - debug('reconnect attempt error'); - self.reconnecting = false; - self.reconnect(); - self.emitAll('reconnect_error', err.data); - } else { - debug('reconnect success'); - self.onreconnect(); - } - }); - }, delay); - - this.subs.push({ - destroy: function(){ - clearTimeout(timer); - } - }); - } - }; - - /** - * Called upon successful reconnect. - * - * @api private - */ - - Manager.prototype.onreconnect = function(){ - var attempt = this.backoff.attempts; - this.reconnecting = false; - this.backoff.reset(); - this.updateSocketIds(); - this.emitAll('reconnect', attempt); - }; - -},{"./on":4,"./socket":5,"./url":6,"backo2":7,"component-bind":8,"component-emitter":9,"debug":10,"engine.io-client":11,"indexof":42,"object-component":43,"socket.io-parser":46}],4:[function(_dereq_,module,exports){ - - /** - * Module exports. - */ - - module.exports = on; - - /** - * Helper for subscriptions. - * - * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter` - * @param {String} event name - * @param {Function} callback - * @api public - */ - - function on(obj, ev, fn) { - obj.on(ev, fn); - return { - destroy: function(){ - obj.removeListener(ev, fn); - } - }; - } - -},{}],5:[function(_dereq_,module,exports){ - - /** - * Module dependencies. - */ - - var parser = _dereq_('socket.io-parser'); - var Emitter = _dereq_('component-emitter'); - var toArray = _dereq_('to-array'); - var on = _dereq_('./on'); - var bind = _dereq_('component-bind'); - var debug = _dereq_('debug')('socket.io-client:socket'); - var hasBin = _dereq_('has-binary'); - - /** - * Module exports. - */ - - module.exports = exports = Socket; - - /** - * Internal events (blacklisted). - * These events can't be emitted by the user. - * - * @api private - */ - - var events = { - connect: 1, - connect_error: 1, - connect_timeout: 1, - disconnect: 1, - error: 1, - reconnect: 1, - reconnect_attempt: 1, - reconnect_failed: 1, - reconnect_error: 1, - reconnecting: 1 - }; - - /** - * Shortcut to `Emitter#emit`. - */ - - var emit = Emitter.prototype.emit; - - /** - * `Socket` constructor. - * - * @api public - */ - - function Socket(io, nsp){ - this.io = io; - this.nsp = nsp; - this.json = this; // compat - this.ids = 0; - this.acks = {}; - if (this.io.autoConnect) this.open(); - this.receiveBuffer = []; - this.sendBuffer = []; - this.connected = false; - this.disconnected = true; - } - - /** - * Mix in `Emitter`. - */ - - Emitter(Socket.prototype); - - /** - * Subscribe to open, close and packet events - * - * @api private - */ - - Socket.prototype.subEvents = function() { - if (this.subs) return; - - var io = this.io; - this.subs = [ - on(io, 'open', bind(this, 'onopen')), - on(io, 'packet', bind(this, 'onpacket')), - on(io, 'close', bind(this, 'onclose')) - ]; - }; - - /** - * "Opens" the socket. - * - * @api public - */ - - Socket.prototype.open = - Socket.prototype.connect = function(){ - if (this.connected) return this; - - this.subEvents(); - this.io.open(); // ensure open - if ('open' == this.io.readyState) this.onopen(); - return this; - }; - - /** - * Sends a `message` event. - * - * @return {Socket} self - * @api public - */ - - Socket.prototype.send = function(){ - var args = toArray(arguments); - args.unshift('message'); - this.emit.apply(this, args); - return this; - }; - - /** - * Override `emit`. - * If the event is in `events`, it's emitted normally. - * - * @param {String} event name - * @return {Socket} self - * @api public - */ - - Socket.prototype.emit = function(ev){ - if (events.hasOwnProperty(ev)) { - emit.apply(this, arguments); - return this; - } - - var args = toArray(arguments); - var parserType = parser.EVENT; // default - if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary - var packet = { type: parserType, data: args }; - - // event ack callback - if ('function' == typeof args[args.length - 1]) { - debug('emitting packet with ack id %d', this.ids); - this.acks[this.ids] = args.pop(); - packet.id = this.ids++; - } - - if (this.connected) { - this.packet(packet); - } else { - this.sendBuffer.push(packet); - } - - return this; - }; - - /** - * Sends a packet. - * - * @param {Object} packet - * @api private - */ - - Socket.prototype.packet = function(packet){ - packet.nsp = this.nsp; - this.io.packet(packet); - }; - - /** - * Called upon engine `open`. - * - * @api private - */ - - Socket.prototype.onopen = function(){ - debug('transport is open - connecting'); - - // write connect packet if necessary - if ('/' != this.nsp) { - this.packet({ type: parser.CONNECT }); - } - }; - - /** - * Called upon engine `close`. - * - * @param {String} reason - * @api private - */ - - Socket.prototype.onclose = function(reason){ - debug('close (%s)', reason); - this.connected = false; - this.disconnected = true; - delete this.id; - this.emit('disconnect', reason); - }; - - /** - * Called with socket packet. - * - * @param {Object} packet - * @api private - */ - - Socket.prototype.onpacket = function(packet){ - if (packet.nsp != this.nsp) return; - - switch (packet.type) { - case parser.CONNECT: - this.onconnect(); - break; - - case parser.EVENT: - this.onevent(packet); - break; - - case parser.BINARY_EVENT: - this.onevent(packet); - break; - - case parser.ACK: - this.onack(packet); - break; - - case parser.BINARY_ACK: - this.onack(packet); - break; - - case parser.DISCONNECT: - this.ondisconnect(); - break; - - case parser.ERROR: - this.emit('error', packet.data); - break; - } - }; - - /** - * Called upon a server event. - * - * @param {Object} packet - * @api private - */ - - Socket.prototype.onevent = function(packet){ - var args = packet.data || []; - debug('emitting event %j', args); - - if (null != packet.id) { - debug('attaching ack callback to event'); - args.push(this.ack(packet.id)); - } - - if (this.connected) { - emit.apply(this, args); - } else { - this.receiveBuffer.push(args); - } - }; - - /** - * Produces an ack callback to emit with an event. - * - * @api private - */ - - Socket.prototype.ack = function(id){ - var self = this; - var sent = false; - return function(){ - // prevent double callbacks - if (sent) return; - sent = true; - var args = toArray(arguments); - debug('sending ack %j', args); - - var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK; - self.packet({ - type: type, - id: id, - data: args - }); - }; - }; - - /** - * Called upon a server acknowlegement. - * - * @param {Object} packet - * @api private - */ - - Socket.prototype.onack = function(packet){ - debug('calling ack %s with %j', packet.id, packet.data); - var fn = this.acks[packet.id]; - fn.apply(this, packet.data); - delete this.acks[packet.id]; - }; - - /** - * Called upon server connect. - * - * @api private - */ - - Socket.prototype.onconnect = function(){ - this.connected = true; - this.disconnected = false; - this.emit('connect'); - this.emitBuffered(); - }; - - /** - * Emit buffered events (received and emitted). - * - * @api private - */ - - Socket.prototype.emitBuffered = function(){ - var i; - for (i = 0; i < this.receiveBuffer.length; i++) { - emit.apply(this, this.receiveBuffer[i]); - } - this.receiveBuffer = []; - - for (i = 0; i < this.sendBuffer.length; i++) { - this.packet(this.sendBuffer[i]); - } - this.sendBuffer = []; - }; - - /** - * Called upon server disconnect. - * - * @api private - */ - - Socket.prototype.ondisconnect = function(){ - debug('server disconnect (%s)', this.nsp); - this.destroy(); - this.onclose('io server disconnect'); - }; - - /** - * Called upon forced client/server side disconnections, - * this method ensures the manager stops tracking us and - * that reconnections don't get triggered for this. - * - * @api private. - */ - - Socket.prototype.destroy = function(){ - if (this.subs) { - // clean subscriptions to avoid reconnections - for (var i = 0; i < this.subs.length; i++) { - this.subs[i].destroy(); - } - this.subs = null; - } - - this.io.destroy(this); - }; - - /** - * Disconnects the socket manually. - * - * @return {Socket} self - * @api public - */ - - Socket.prototype.close = - Socket.prototype.disconnect = function(){ - if (this.connected) { - debug('performing disconnect (%s)', this.nsp); - this.packet({ type: parser.DISCONNECT }); - } - - // remove socket from pool - this.destroy(); - - if (this.connected) { - // fire events - this.onclose('io client disconnect'); - } - return this; - }; - -},{"./on":4,"component-bind":8,"component-emitter":9,"debug":10,"has-binary":38,"socket.io-parser":46,"to-array":50}],6:[function(_dereq_,module,exports){ - (function (global){ - - /** - * Module dependencies. - */ - - var parseuri = _dereq_('parseuri'); - var debug = _dereq_('debug')('socket.io-client:url'); - - /** - * Module exports. - */ - - module.exports = url; - - /** - * URL parser. - * - * @param {String} url - * @param {Object} An object meant to mimic window.location. - * Defaults to window.location. - * @api public - */ - - function url(uri, loc){ - var obj = uri; - - // default to window.location - var loc = loc || global.location; - if (null == uri) uri = loc.protocol + '//' + loc.host; - - // relative path support - if ('string' == typeof uri) { - if ('/' == uri.charAt(0)) { - if ('/' == uri.charAt(1)) { - uri = loc.protocol + uri; - } else { - uri = loc.hostname + uri; - } - } - - if (!/^(https?|wss?):\/\//.test(uri)) { - debug('protocol-less url %s', uri); - if ('undefined' != typeof loc) { - uri = loc.protocol + '//' + uri; - } else { - uri = 'https://' + uri; - } - } - - // parse - debug('parse %s', uri); - obj = parseuri(uri); - } - - // make sure we treat `localhost:80` and `localhost` equally - if (!obj.port) { - if (/^(http|ws)$/.test(obj.protocol)) { - obj.port = '80'; - } - else if (/^(http|ws)s$/.test(obj.protocol)) { - obj.port = '443'; - } - } - - obj.path = obj.path || '/'; - - // define unique id - obj.id = obj.protocol + '://' + obj.host + ':' + obj.port; - // define href - obj.href = obj.protocol + '://' + obj.host + (loc && loc.port == obj.port ? '' : (':' + obj.port)); - - return obj; - } - - }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"debug":10,"parseuri":44}],7:[function(_dereq_,module,exports){ - - /** - * Expose `Backoff`. - */ - - module.exports = Backoff; - - /** - * Initialize backoff timer with `opts`. - * - * - `min` initial timeout in milliseconds [100] - * - `max` max timeout [10000] - * - `jitter` [0] - * - `factor` [2] - * - * @param {Object} opts - * @api public - */ - - function Backoff(opts) { - opts = opts || {}; - this.ms = opts.min || 100; - this.max = opts.max || 10000; - this.factor = opts.factor || 2; - this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0; - this.attempts = 0; - } - - /** - * Return the backoff duration. - * - * @return {Number} - * @api public - */ - - Backoff.prototype.duration = function(){ - var ms = this.ms * Math.pow(this.factor, this.attempts++); - if (this.jitter) { - var rand = Math.random(); - var deviation = Math.floor(rand * this.jitter * ms); - ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation; - } - return Math.min(ms, this.max) | 0; - }; - - /** - * Reset the number of attempts. - * - * @api public - */ - - Backoff.prototype.reset = function(){ - this.attempts = 0; - }; - - /** - * Set the minimum duration - * - * @api public - */ - - Backoff.prototype.setMin = function(min){ - this.ms = min; - }; - - /** - * Set the maximum duration - * - * @api public - */ - - Backoff.prototype.setMax = function(max){ - this.max = max; - }; - - /** - * Set the jitter - * - * @api public - */ - - Backoff.prototype.setJitter = function(jitter){ - this.jitter = jitter; - }; - - -},{}],8:[function(_dereq_,module,exports){ - /** - * Slice reference. - */ - - var slice = [].slice; - - /** - * Bind `obj` to `fn`. - * - * @param {Object} obj - * @param {Function|String} fn or string - * @return {Function} - * @api public - */ - - module.exports = function(obj, fn){ - if ('string' == typeof fn) fn = obj[fn]; - if ('function' != typeof fn) throw new Error('bind() requires a function'); - var args = slice.call(arguments, 2); - return function(){ - return fn.apply(obj, args.concat(slice.call(arguments))); - } - }; - -},{}],9:[function(_dereq_,module,exports){ - - /** - * Expose `Emitter`. - */ - - module.exports = Emitter; - - /** - * Initialize a new `Emitter`. - * - * @api public - */ - - function Emitter(obj) { - if (obj) return mixin(obj); - }; - - /** - * Mixin the emitter properties. - * - * @param {Object} obj - * @return {Object} - * @api private - */ - - function mixin(obj) { - for (var key in Emitter.prototype) { - obj[key] = Emitter.prototype[key]; - } - return obj; - } - - /** - * Listen on the given `event` with `fn`. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - - Emitter.prototype.on = - Emitter.prototype.addEventListener = function(event, fn){ - this._callbacks = this._callbacks || {}; - (this._callbacks[event] = this._callbacks[event] || []) - .push(fn); - return this; - }; - - /** - * Adds an `event` listener that will be invoked a single - * time then automatically removed. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - - Emitter.prototype.once = function(event, fn){ - var self = this; - this._callbacks = this._callbacks || {}; - - function on() { - self.off(event, on); - fn.apply(this, arguments); - } - - on.fn = fn; - this.on(event, on); - return this; - }; - - /** - * Remove the given callback for `event` or all - * registered callbacks. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - - Emitter.prototype.off = - Emitter.prototype.removeListener = - Emitter.prototype.removeAllListeners = - Emitter.prototype.removeEventListener = function(event, fn){ - this._callbacks = this._callbacks || {}; - - // all - if (0 == arguments.length) { - this._callbacks = {}; - return this; - } - - // specific event - var callbacks = this._callbacks[event]; - if (!callbacks) return this; - - // remove all handlers - if (1 == arguments.length) { - delete this._callbacks[event]; - return this; - } - - // remove specific handler - var cb; - for (var i = 0; i < callbacks.length; i++) { - cb = callbacks[i]; - if (cb === fn || cb.fn === fn) { - callbacks.splice(i, 1); - break; - } - } - return this; - }; - - /** - * Emit `event` with the given args. - * - * @param {String} event - * @param {Mixed} ... - * @return {Emitter} - */ - - Emitter.prototype.emit = function(event){ - this._callbacks = this._callbacks || {}; - var args = [].slice.call(arguments, 1) - , callbacks = this._callbacks[event]; - - if (callbacks) { - callbacks = callbacks.slice(0); - for (var i = 0, len = callbacks.length; i < len; ++i) { - callbacks[i].apply(this, args); - } - } - - return this; - }; - - /** - * Return array of callbacks for `event`. - * - * @param {String} event - * @return {Array} - * @api public - */ - - Emitter.prototype.listeners = function(event){ - this._callbacks = this._callbacks || {}; - return this._callbacks[event] || []; - }; - - /** - * Check if this emitter has `event` handlers. - * - * @param {String} event - * @return {Boolean} - * @api public - */ - - Emitter.prototype.hasListeners = function(event){ - return !! this.listeners(event).length; - }; - -},{}],10:[function(_dereq_,module,exports){ - - /** - * Expose `debug()` as the module. - */ - - module.exports = debug; - - /** - * Create a debugger with the given `name`. - * - * @param {String} name - * @return {Type} - * @api public - */ - - function debug(name) { - if (!debug.enabled(name)) return function(){}; - - return function(fmt){ - fmt = coerce(fmt); - - var curr = new Date; - var ms = curr - (debug[name] || curr); - debug[name] = curr; - - fmt = name - + ' ' - + fmt - + ' +' + debug.humanize(ms); - - // This hackery is required for IE8 - // where `console.log` doesn't have 'apply' - window.console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); - } - } - - /** - * The currently active debug mode names. - */ - - debug.names = []; - debug.skips = []; - - /** - * Enables a debug mode by name. This can include modes - * separated by a colon and wildcards. - * - * @param {String} name - * @api public - */ - - debug.enable = function(name) { - try { - localStorage.debug = name; - } catch(e){} - - var split = (name || '').split(/[\s,]+/) - , len = split.length; - - for (var i = 0; i < len; i++) { - name = split[i].replace('*', '.*?'); - if (name[0] === '-') { - debug.skips.push(new RegExp('^' + name.substr(1) + '$')); - } - else { - debug.names.push(new RegExp('^' + name + '$')); - } - } - }; - - /** - * Disable debug output. - * - * @api public - */ - - debug.disable = function(){ - debug.enable(''); - }; - - /** - * Humanize the given `ms`. - * - * @param {Number} m - * @return {String} - * @api private - */ - - debug.humanize = function(ms) { - var sec = 1000 - , min = 60 * 1000 - , hour = 60 * min; - - if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; - if (ms >= min) return (ms / min).toFixed(1) + 'm'; - if (ms >= sec) return (ms / sec | 0) + 's'; - return ms + 'ms'; - }; - - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - - debug.enabled = function(name) { - for (var i = 0, len = debug.skips.length; i < len; i++) { - if (debug.skips[i].test(name)) { - return false; - } - } - for (var i = 0, len = debug.names.length; i < len; i++) { - if (debug.names[i].test(name)) { - return true; - } - } - return false; - }; - - /** - * Coerce `val`. - */ - - function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; - } - -// persist - - try { - if (window.localStorage) debug.enable(localStorage.debug); - } catch(e){} - -},{}],11:[function(_dereq_,module,exports){ - - module.exports = _dereq_('./lib/'); - -},{"./lib/":12}],12:[function(_dereq_,module,exports){ - - module.exports = _dereq_('./socket'); - - /** - * Exports parser - * - * @api public - * - */ - module.exports.parser = _dereq_('engine.io-parser'); - -},{"./socket":13,"engine.io-parser":25}],13:[function(_dereq_,module,exports){ - (function (global){ - /** - * Module dependencies. - */ - - var transports = _dereq_('./transports'); - var Emitter = _dereq_('component-emitter'); - var debug = _dereq_('debug')('engine.io-client:socket'); - var index = _dereq_('indexof'); - var parser = _dereq_('engine.io-parser'); - var parseuri = _dereq_('parseuri'); - var parsejson = _dereq_('parsejson'); - var parseqs = _dereq_('parseqs'); - - /** - * Module exports. - */ - - module.exports = Socket; - - /** - * Noop function. - * - * @api private - */ - - function noop(){} - - /** - * Socket constructor. - * - * @param {String|Object} uri or options - * @param {Object} options - * @api public - */ - - function Socket(uri, opts){ - if (!(this instanceof Socket)) return new Socket(uri, opts); - - opts = opts || {}; - - if (uri && 'object' == typeof uri) { - opts = uri; - uri = null; - } - - if (uri) { - uri = parseuri(uri); - opts.host = uri.host; - opts.secure = uri.protocol == 'https' || uri.protocol == 'wss'; - opts.port = uri.port; - if (uri.query) opts.query = uri.query; - } - - this.secure = null != opts.secure ? opts.secure : - (global.location && 'https:' == location.protocol); - - if (opts.host) { - var pieces = opts.host.split(':'); - opts.hostname = pieces.shift(); - if (pieces.length) { - opts.port = pieces.pop(); - } else if (!opts.port) { - // if no port is specified manually, use the protocol default - opts.port = this.secure ? '443' : '80'; - } - } - - this.agent = opts.agent || false; - this.hostname = opts.hostname || - (global.location ? location.hostname : 'localhost'); - this.port = opts.port || (global.location && location.port ? - location.port : - (this.secure ? 443 : 80)); - this.query = opts.query || {}; - if ('string' == typeof this.query) this.query = parseqs.decode(this.query); - this.upgrade = false !== opts.upgrade; - this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/'; - this.forceJSONP = !!opts.forceJSONP; - this.jsonp = false !== opts.jsonp; - this.forceBase64 = !!opts.forceBase64; - this.enablesXDR = !!opts.enablesXDR; - this.timestampParam = opts.timestampParam || 't'; - this.timestampRequests = opts.timestampRequests; - this.transports = opts.transports || ['polling', 'websocket']; - this.readyState = ''; - this.writeBuffer = []; - this.callbackBuffer = []; - this.policyPort = opts.policyPort || 843; - this.rememberUpgrade = opts.rememberUpgrade || false; - this.binaryType = null; - this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades; - - // SSL options for Node.js client - this.pfx = opts.pfx || null; - this.key = opts.key || null; - this.passphrase = opts.passphrase || null; - this.cert = opts.cert || null; - this.ca = opts.ca || null; - this.ciphers = opts.ciphers || null; - this.rejectUnauthorized = opts.rejectUnauthorized || null; - - this.open(); - } - - Socket.priorWebsocketSuccess = false; - - /** - * Mix in `Emitter`. - */ - - Emitter(Socket.prototype); - - /** - * Protocol version. - * - * @api public - */ - - Socket.protocol = parser.protocol; // this is an int - - /** - * Expose deps for legacy compatibility - * and standalone browser access. - */ - - Socket.Socket = Socket; - Socket.Transport = _dereq_('./transport'); - Socket.transports = _dereq_('./transports'); - Socket.parser = _dereq_('engine.io-parser'); - - /** - * Creates transport of the given type. - * - * @param {String} transport name - * @return {Transport} - * @api private - */ - - Socket.prototype.createTransport = function (name) { - debug('creating transport "%s"', name); - var query = clone(this.query); - - // append engine.io protocol identifier - query.EIO = parser.protocol; - - // transport name - query.transport = name; - - // session id if we already have one - if (this.id) query.sid = this.id; - - var transport = new transports[name]({ - agent: this.agent, - hostname: this.hostname, - port: this.port, - secure: this.secure, - path: this.path, - query: query, - forceJSONP: this.forceJSONP, - jsonp: this.jsonp, - forceBase64: this.forceBase64, - enablesXDR: this.enablesXDR, - timestampRequests: this.timestampRequests, - timestampParam: this.timestampParam, - policyPort: this.policyPort, - socket: this, - pfx: this.pfx, - key: this.key, - passphrase: this.passphrase, - cert: this.cert, - ca: this.ca, - ciphers: this.ciphers, - rejectUnauthorized: this.rejectUnauthorized - }); - - return transport; - }; - - function clone (obj) { - var o = {}; - for (var i in obj) { - if (obj.hasOwnProperty(i)) { - o[i] = obj[i]; - } - } - return o; - } - - /** - * Initializes transport to use and starts probe. - * - * @api private - */ - Socket.prototype.open = function () { - var transport; - if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) { - transport = 'websocket'; - } else if (0 == this.transports.length) { - // Emit error on next tick so it can be listened to - var self = this; - setTimeout(function() { - self.emit('error', 'No transports available'); - }, 0); - return; - } else { - transport = this.transports[0]; - } - this.readyState = 'opening'; - - // Retry with the next transport if the transport is disabled (jsonp: false) - var transport; - try { - transport = this.createTransport(transport); - } catch (e) { - this.transports.shift(); - this.open(); - return; - } - - transport.open(); - this.setTransport(transport); - }; - - /** - * Sets the current transport. Disables the existing one (if any). - * - * @api private - */ - - Socket.prototype.setTransport = function(transport){ - debug('setting transport %s', transport.name); - var self = this; - - if (this.transport) { - debug('clearing existing transport %s', this.transport.name); - this.transport.removeAllListeners(); - } - - // set up transport - this.transport = transport; - - // set up transport listeners - transport - .on('drain', function(){ - self.onDrain(); - }) - .on('packet', function(packet){ - self.onPacket(packet); - }) - .on('error', function(e){ - self.onError(e); - }) - .on('close', function(){ - self.onClose('transport close'); - }); - }; - - /** - * Probes a transport. - * - * @param {String} transport name - * @api private - */ - - Socket.prototype.probe = function (name) { - debug('probing transport "%s"', name); - var transport = this.createTransport(name, { probe: 1 }) - , failed = false - , self = this; - - Socket.priorWebsocketSuccess = false; - - function onTransportOpen(){ - if (self.onlyBinaryUpgrades) { - var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary; - failed = failed || upgradeLosesBinary; - } - if (failed) return; - - debug('probe transport "%s" opened', name); - transport.send([{ type: 'ping', data: 'probe' }]); - transport.once('packet', function (msg) { - if (failed) return; - if ('pong' == msg.type && 'probe' == msg.data) { - debug('probe transport "%s" pong', name); - self.upgrading = true; - self.emit('upgrading', transport); - if (!transport) return; - Socket.priorWebsocketSuccess = 'websocket' == transport.name; - - debug('pausing current transport "%s"', self.transport.name); - self.transport.pause(function () { - if (failed) return; - if ('closed' == self.readyState) return; - debug('changing transport and sending upgrade packet'); - - cleanup(); - - self.setTransport(transport); - transport.send([{ type: 'upgrade' }]); - self.emit('upgrade', transport); - transport = null; - self.upgrading = false; - self.flush(); - }); - } else { - debug('probe transport "%s" failed', name); - var err = new Error('probe error'); - err.transport = transport.name; - self.emit('upgradeError', err); - } - }); - } - - function freezeTransport() { - if (failed) return; - - // Any callback called by transport should be ignored since now - failed = true; - - cleanup(); - - transport.close(); - transport = null; - } - - //Handle any error that happens while probing - function onerror(err) { - var error = new Error('probe error: ' + err); - error.transport = transport.name; - - freezeTransport(); - - debug('probe transport "%s" failed because of error: %s', name, err); - - self.emit('upgradeError', error); - } - - function onTransportClose(){ - onerror("transport closed"); - } - - //When the socket is closed while we're probing - function onclose(){ - onerror("socket closed"); - } - - //When the socket is upgraded while we're probing - function onupgrade(to){ - if (transport && to.name != transport.name) { - debug('"%s" works - aborting "%s"', to.name, transport.name); - freezeTransport(); - } - } - - //Remove all listeners on the transport and on self - function cleanup(){ - transport.removeListener('open', onTransportOpen); - transport.removeListener('error', onerror); - transport.removeListener('close', onTransportClose); - self.removeListener('close', onclose); - self.removeListener('upgrading', onupgrade); - } - - transport.once('open', onTransportOpen); - transport.once('error', onerror); - transport.once('close', onTransportClose); - - this.once('close', onclose); - this.once('upgrading', onupgrade); - - transport.open(); - - }; - - /** - * Called when connection is deemed open. - * - * @api public - */ - - Socket.prototype.onOpen = function () { - debug('socket open'); - this.readyState = 'open'; - Socket.priorWebsocketSuccess = 'websocket' == this.transport.name; - this.emit('open'); - this.flush(); - - // we check for `readyState` in case an `open` - // listener already closed the socket - if ('open' == this.readyState && this.upgrade && this.transport.pause) { - debug('starting upgrade probes'); - for (var i = 0, l = this.upgrades.length; i < l; i++) { - this.probe(this.upgrades[i]); - } - } - }; - - /** - * Handles a packet. - * - * @api private - */ - - Socket.prototype.onPacket = function (packet) { - if ('opening' == this.readyState || 'open' == this.readyState) { - debug('socket receive: type "%s", data "%s"', packet.type, packet.data); - - this.emit('packet', packet); - - // Socket is live - any packet counts - this.emit('heartbeat'); - - switch (packet.type) { - case 'open': - this.onHandshake(parsejson(packet.data)); - break; - - case 'pong': - this.setPing(); - break; - - case 'error': - var err = new Error('server error'); - err.code = packet.data; - this.emit('error', err); - break; - - case 'message': - this.emit('data', packet.data); - this.emit('message', packet.data); - break; - } - } else { - debug('packet received with socket readyState "%s"', this.readyState); - } - }; - - /** - * Called upon handshake completion. - * - * @param {Object} handshake obj - * @api private - */ - - Socket.prototype.onHandshake = function (data) { - this.emit('handshake', data); - this.id = data.sid; - this.transport.query.sid = data.sid; - this.upgrades = this.filterUpgrades(data.upgrades); - this.pingInterval = data.pingInterval; - this.pingTimeout = data.pingTimeout; - this.onOpen(); - // In case open handler closes socket - if ('closed' == this.readyState) return; - this.setPing(); - - // Prolong liveness of socket on heartbeat - this.removeListener('heartbeat', this.onHeartbeat); - this.on('heartbeat', this.onHeartbeat); - }; - - /** - * Resets ping timeout. - * - * @api private - */ - - Socket.prototype.onHeartbeat = function (timeout) { - clearTimeout(this.pingTimeoutTimer); - var self = this; - self.pingTimeoutTimer = setTimeout(function () { - if ('closed' == self.readyState) return; - self.onClose('ping timeout'); - }, timeout || (self.pingInterval + self.pingTimeout)); - }; - - /** - * Pings server every `this.pingInterval` and expects response - * within `this.pingTimeout` or closes connection. - * - * @api private - */ - - Socket.prototype.setPing = function () { - var self = this; - clearTimeout(self.pingIntervalTimer); - self.pingIntervalTimer = setTimeout(function () { - debug('writing ping packet - expecting pong within %sms', self.pingTimeout); - self.ping(); - self.onHeartbeat(self.pingTimeout); - }, self.pingInterval); - }; - - /** - * Sends a ping packet. - * - * @api public - */ - - Socket.prototype.ping = function () { - this.sendPacket('ping'); - }; - - /** - * Called on `drain` event - * - * @api private - */ - - Socket.prototype.onDrain = function() { - for (var i = 0; i < this.prevBufferLen; i++) { - if (this.callbackBuffer[i]) { - this.callbackBuffer[i](); - } - } - - this.writeBuffer.splice(0, this.prevBufferLen); - this.callbackBuffer.splice(0, this.prevBufferLen); - - // setting prevBufferLen = 0 is very important - // for example, when upgrading, upgrade packet is sent over, - // and a nonzero prevBufferLen could cause problems on `drain` - this.prevBufferLen = 0; - - if (this.writeBuffer.length == 0) { - this.emit('drain'); - } else { - this.flush(); - } - }; - - /** - * Flush write buffers. - * - * @api private - */ - - Socket.prototype.flush = function () { - if ('closed' != this.readyState && this.transport.writable && - !this.upgrading && this.writeBuffer.length) { - debug('flushing %d packets in socket', this.writeBuffer.length); - this.transport.send(this.writeBuffer); - // keep track of current length of writeBuffer - // splice writeBuffer and callbackBuffer on `drain` - this.prevBufferLen = this.writeBuffer.length; - this.emit('flush'); - } - }; - - /** - * Sends a message. - * - * @param {String} message. - * @param {Function} callback function. - * @return {Socket} for chaining. - * @api public - */ - - Socket.prototype.write = - Socket.prototype.send = function (msg, fn) { - this.sendPacket('message', msg, fn); - return this; - }; - - /** - * Sends a packet. - * - * @param {String} packet type. - * @param {String} data. - * @param {Function} callback function. - * @api private - */ - - Socket.prototype.sendPacket = function (type, data, fn) { - if ('closing' == this.readyState || 'closed' == this.readyState) { - return; - } - - var packet = { type: type, data: data }; - this.emit('packetCreate', packet); - this.writeBuffer.push(packet); - this.callbackBuffer.push(fn); - this.flush(); - }; - - /** - * Closes the connection. - * - * @api private - */ - - Socket.prototype.close = function () { - if ('opening' == this.readyState || 'open' == this.readyState) { - this.readyState = 'closing'; - - var self = this; - - function close() { - self.onClose('forced close'); - debug('socket closing - telling transport to close'); - self.transport.close(); - } - - function cleanupAndClose() { - self.removeListener('upgrade', cleanupAndClose); - self.removeListener('upgradeError', cleanupAndClose); - close(); - } - - function waitForUpgrade() { - // wait for upgrade to finish since we can't send packets while pausing a transport - self.once('upgrade', cleanupAndClose); - self.once('upgradeError', cleanupAndClose); - } - - if (this.writeBuffer.length) { - this.once('drain', function() { - if (this.upgrading) { - waitForUpgrade(); - } else { - close(); - } - }); - } else if (this.upgrading) { - waitForUpgrade(); - } else { - close(); - } - } - - return this; - }; - - /** - * Called upon transport error - * - * @api private - */ - - Socket.prototype.onError = function (err) { - debug('socket error %j', err); - Socket.priorWebsocketSuccess = false; - this.emit('error', err); - this.onClose('transport error', err); - }; - - /** - * Called upon transport close. - * - * @api private - */ - - Socket.prototype.onClose = function (reason, desc) { - if ('opening' == this.readyState || 'open' == this.readyState || 'closing' == this.readyState) { - debug('socket close with reason: "%s"', reason); - var self = this; - - // clear timers - clearTimeout(this.pingIntervalTimer); - clearTimeout(this.pingTimeoutTimer); - - // clean buffers in next tick, so developers can still - // grab the buffers on `close` event - setTimeout(function() { - self.writeBuffer = []; - self.callbackBuffer = []; - self.prevBufferLen = 0; - }, 0); - - // stop event from firing again for transport - this.transport.removeAllListeners('close'); - - // ensure transport won't stay open - this.transport.close(); - - // ignore further transport communication - this.transport.removeAllListeners(); - - // set ready state - this.readyState = 'closed'; - - // clear session id - this.id = null; - - // emit close event - this.emit('close', reason, desc); - } - }; - - /** - * Filters upgrades, returning only those matching client transports. - * - * @param {Array} server upgrades - * @api private - * - */ - - Socket.prototype.filterUpgrades = function (upgrades) { - var filteredUpgrades = []; - for (var i = 0, j = upgrades.length; i