diff --git a/cocos2d/core/components/CCComponentInSG.js b/cocos2d/core/components/CCComponentInSG.js index 98516a32b8..98c69b5330 100644 --- a/cocos2d/core/components/CCComponentInSG.js +++ b/cocos2d/core/components/CCComponentInSG.js @@ -29,14 +29,16 @@ var ComponentInSG = cc.Class({ * @private */ this._sgNode = this._createSgNode(); - // retain immediately - // will be released in SceneGraphHelper.removeSgNode - this._sgNode.retain(); + if (this._sgNode) { + // retain immediately + // will be released in SceneGraphHelper.removeSgNode + this._sgNode.retain(); + } }, onLoad: function () { - var sgNode = this._sgNode; this._initSgNode(); + var sgNode = this._sgNode; this._appendSgNode(sgNode); if ( !this.node._sizeProvider ) { this.node._sizeProvider = sgNode; @@ -78,6 +80,10 @@ var ComponentInSG = cc.Class({ _removeSgNode: SceneGraphHelper.removeSgNode, _appendSgNode: function (sgNode) { + if ( !sgNode ) { + return; + } + var node = this.node; sgNode.setColor(node._color); diff --git a/cocos2d/deprecated.js b/cocos2d/deprecated.js index b2e83104bc..22488525fa 100644 --- a/cocos2d/deprecated.js +++ b/cocos2d/deprecated.js @@ -265,7 +265,7 @@ if (CC_DEV) { function provideClearError (owner, obj) { var className = cc.js.getClassName(owner); - var Info = 'Sorry,' + className + '.%s is removed, please use %s instead.'; + var Info = 'Sorry, ' + className + '.%s is removed, please use %s instead.'; for (var prop in obj) { function define (prop, getset) { function accessor (newProp) { @@ -540,4 +540,22 @@ if (CC_DEV) { 'setFlippedY', 'isFlippedY' ]); + + // SPINE + + if (typeof sp !== 'undefined') { + deprecateEnum(sp, 'sp.ANIMATION_EVENT_TYPE', 'sp.AnimationEventType'); + js.obsolete(sp, 'SkeletonAnimation', 'Skeleton'); + provideClearError(sp.Skeleton, { + create: 'node.addComponent', + }); + provideClearError(sp.Skeleton.prototype, { + '*etDebugSlotsEnabled': 'debugSlots', + '*etDebugBonesEnabled': 'debugBones', + 'setDebugSolots': 'debugSlots', + 'setDebugBones': 'debugBones', + '*etTimeScale': 'timeScale', + }); + } } + diff --git a/extensions/spine/SGSkeleton.js b/extensions/spine/SGSkeleton.js new file mode 100644 index 0000000000..3d03cb320e --- /dev/null +++ b/extensions/spine/SGSkeleton.js @@ -0,0 +1,331 @@ +/**************************************************************************** + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. + Copyright (c) 2014 Shengxiang Chen (Nero Chan) + Copyright (c) 2015-2016 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +var spine = sp.spine; + +sp._SGSkeleton = _ccsg.Node.extend({ + _skeleton: null, + _rootBone: null, + _timeScale: 1, + _debugSlots: false, + _debugBones: false, + _premultipliedAlpha: false, + _ownsSkeletonData: null, + _atlas: null, + _blendFunc: null, + + ctor: function(skeletonDataFile, atlasFile, scale) { + _ccsg.Node.prototype.ctor.call(this); + this._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST}; + + if(arguments.length === 0) + this.init(); + else + this.initWithArgs(skeletonDataFile, atlasFile, scale); + }, + + _createRenderCmd: function () { + if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) + return new sp._SGSkeleton.CanvasRenderCmd(this); + else + return new sp._SGSkeleton.WebGLRenderCmd(this); + }, + + init: function () { + _ccsg.Node.prototype.init.call(this); + //this.setOpacityModifyRGB(true); + this._blendFunc.src = cc.ONE; + this._blendFunc.dst = cc.ONE_MINUS_SRC_ALPHA; + this.scheduleUpdate(); + }, + + /** + * Sets whether open debug slots. + * @param {boolean} 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._SGSkeleton. + * @param {Number} scale + */ + setTimeScale:function(scale){ + this._timeScale = scale; + }, + + getTimeScale: function(){ + return this._timeScale; + }, + + /** + * Initializes sp._SGSkeleton with Data. + * @param {spine.SkeletonData|String} skeletonDataFile + * @param {String|spine.Atlas|spine.SkeletonData} atlasFile atlas filename or atlas data or owns SkeletonData + * @param {Number} [scale] scale can be specified on the JSON or binary loader which will scale the bone positions, image sizes, and animation translations. + */ + initWithArgs: function (skeletonDataFile, atlasFile, scale) { + var argSkeletonFile = skeletonDataFile, argAtlasFile = atlasFile, + skeletonData, atlas, ownsSkeletonData; + + if (cc.js.isString(argSkeletonFile)) { + if (cc.js.isString(argAtlasFile)) { + var data = cc.loader.getRes(argAtlasFile); + sp._atlasLoader.setAtlasFile(argAtlasFile); + atlas = new spine.Atlas(data, sp._atlasLoader); + } else { + atlas = atlasFile; + } + scale = scale || 1 / cc.director.getContentScaleFactor(); + + var attachmentLoader = new spine.AtlasAttachmentLoader(atlas); + var skeletonJsonReader = new spine.SkeletonJson(attachmentLoader); + skeletonJsonReader.scale = scale; + + var skeletonJson = cc.loader.getRes(argSkeletonFile); + skeletonData = skeletonJsonReader.readSkeletonData(skeletonJson); + atlas.dispose(skeletonJsonReader); + ownsSkeletonData = true; + } else { + skeletonData = skeletonDataFile; + ownsSkeletonData = atlasFile; + } + this.setSkeletonData(skeletonData, ownsSkeletonData); + this.init(); + }, + + /** + * Returns the bounding box of sp._SGSkeleton. + * @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._SGSkeleton. + * @param {Number} alpha + */ + setOpacityModifyRGB: function (alpha) { + this._premultipliedAlpha = alpha; + }, + + /** + * Returns whether to enable premultiplied alpha. + * @returns {boolean} + */ + isOpacityModifyRGB: function () { + return this._premultipliedAlpha; + }, + + /** + * Sets skeleton data to sp._SGSkeleton. + * @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 {_ccsg.Node} + */ + getTextureAtlas: function (regionAttachment) { + return regionAttachment.rendererObject.page.rendererObject; + }, + + /** + * Returns the blendFunc of sp._SGSkeleton. + * @returns {cc.BlendFunc} + */ + getBlendFunc: function () { + return this._blendFunc; + }, + + /** + * Sets the blendFunc of sp._SGSkeleton. + * @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); + } +}); diff --git a/extensions/spine/SkeletonAnimation.js b/extensions/spine/SGSkeletonAnimation.js similarity index 80% rename from extensions/spine/SkeletonAnimation.js rename to extensions/spine/SGSkeletonAnimation.js index edfc167f02..05c9388e32 100644 --- a/extensions/spine/SkeletonAnimation.js +++ b/extensions/spine/SGSkeletonAnimation.js @@ -25,11 +25,8 @@ THE SOFTWARE. ****************************************************************************/ -var spine = require('./spine-exported'); - -/** - * @module sp - */ +var spine = sp.spine; +var animEventType = sp.AnimationEventType; sp._atlasPage_createTexture_webGL = function (self, path) { var texture = cc.textureCache.addImage(path); @@ -62,17 +59,6 @@ sp._atlasLoader = { } }; -/** - * 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; @@ -93,15 +79,8 @@ 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# */{ + +sp._SGSkeletonAnimation = sp._SGSkeleton.extend({ _state: null, _target: null, _callback: null, @@ -113,17 +92,17 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ _eventListener: null, /** - * Initializes a sp.SkeletonAnimation. please do not call this function by yourself, you should pass the parameters to constructor to initialize it. + * Initializes a sp._SGSkeletonAnimation. 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); + sp._SGSkeleton.prototype.init.call(this); this._ownsAnimationStateData = true; this.setAnimationStateData(new spine.AnimationStateData(this._skeleton.data)); }, /** - * Sets animation state data to sp.SkeletonAnimation. + * Sets animation state data to sp._SGSkeletonAnimation. * @param {spine.AnimationStateData} stateData */ setAnimationStateData: function (stateData) { @@ -147,7 +126,7 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ }, /** - * Sets event listener of sp.SkeletonAnimation. + * Sets event listener of sp._SGSkeletonAnimation. * @param {Object} target * @param {Function} callback */ @@ -275,19 +254,19 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ return; var listeners = entry.rendererObject; switch (type){ - case sp.ANIMATION_EVENT_TYPE.START: + case animEventType.START: if(listeners.startListener) listeners.startListener(traceIndex); break; - case sp.ANIMATION_EVENT_TYPE.END: + case animEventType.END: if(listeners.endListener) listeners.endListener(traceIndex); break; - case sp.ANIMATION_EVENT_TYPE.COMPLETE: + case animEventType.COMPLETE: if(listeners.completeListener) listeners.completeListener(traceIndex, loopCount); break; - case sp.ANIMATION_EVENT_TYPE.EVENT: + case animEventType.EVENT: if(listeners.eventListener) listeners.eventListener(traceIndex, event); break; @@ -296,19 +275,19 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ onAnimationStateEvent: function(trackIndex, type, event, loopCount) { switch(type){ - case sp.ANIMATION_EVENT_TYPE.START: + case animEventType.START: if(this._startListener) this._startListener(trackIndex); break; - case sp.ANIMATION_EVENT_TYPE.END: + case animEventType.END: if(this._endListener) this._endListener(trackIndex); break; - case sp.ANIMATION_EVENT_TYPE.COMPLETE: + case animEventType.COMPLETE: if(this._completeListener) this._completeListener(trackIndex, loopCount); break; - case sp.ANIMATION_EVENT_TYPE.EVENT: + case animEventType.EVENT: if(this._eventListener) this._eventListener(trackIndex, event); break; @@ -320,16 +299,16 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ }, _onAnimationStateStart: function (trackIndex) { - this._animationStateCallback(trackIndex, sp.ANIMATION_EVENT_TYPE.START, null, 0); + this._animationStateCallback(trackIndex, animEventType.START, null, 0); }, _onAnimationStateEnd: function (trackIndex) { - this._animationStateCallback(trackIndex, sp.ANIMATION_EVENT_TYPE.END, null, 0); + this._animationStateCallback(trackIndex, animEventType.END, null, 0); }, _onAnimationStateComplete: function (trackIndex, count) { - this._animationStateCallback(trackIndex, sp.ANIMATION_EVENT_TYPE.COMPLETE, null, count); + this._animationStateCallback(trackIndex, animEventType.COMPLETE, null, count); }, _onAnimationStateEvent: function (trackIndex, event) { - this._animationStateCallback(trackIndex, sp.ANIMATION_EVENT_TYPE.EVENT, event, 0); + this._animationStateCallback(trackIndex, animEventType.EVENT, event, 0); }, _animationStateCallback: function (trackIndex, type, event, loopCount) { this.onAnimationStateEvent(trackIndex, type, event, loopCount); @@ -338,15 +317,3 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ } } }); - -/** - * 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); -}; diff --git a/extensions/spine/SkeletonCanvasRenderCmd.js b/extensions/spine/SGSkeletonCanvasRenderCmd.js similarity index 96% rename from extensions/spine/SkeletonCanvasRenderCmd.js rename to extensions/spine/SGSkeletonCanvasRenderCmd.js index 5f33707590..c0914c65fa 100644 --- a/extensions/spine/SkeletonCanvasRenderCmd.js +++ b/extensions/spine/SGSkeletonCanvasRenderCmd.js @@ -22,19 +22,15 @@ THE SOFTWARE. ****************************************************************************/ -var spine = require('./spine-exported'); +var spine = sp.spine; -/** - * @module sp - */ - -sp.Skeleton.CanvasRenderCmd = function(renderableObject){ +sp._SGSkeleton.CanvasRenderCmd = function(renderableObject){ _ccsg.Node.CanvasRenderCmd.call(this, renderableObject); this._needDraw = true; }; -var proto = sp.Skeleton.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype); -proto.constructor = sp.Skeleton.CanvasRenderCmd; +var proto = sp._SGSkeleton.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype); +proto.constructor = sp._SGSkeleton.CanvasRenderCmd; proto.rendering = function (wrapper, scaleX, scaleY) { var node = this._node, i, n, slot, slotNode; diff --git a/extensions/spine/SkeletonWebGLRenderCmd.js b/extensions/spine/SGSkeletonWebGLRenderCmd.js similarity index 97% rename from extensions/spine/SkeletonWebGLRenderCmd.js rename to extensions/spine/SGSkeletonWebGLRenderCmd.js index 78a9363775..11355a9b92 100644 --- a/extensions/spine/SkeletonWebGLRenderCmd.js +++ b/extensions/spine/SGSkeletonWebGLRenderCmd.js @@ -22,21 +22,18 @@ THE SOFTWARE. ****************************************************************************/ -var spine = require('./spine-exported'); +var spine = sp.spine; -/** - * @module sp - */ -sp.Skeleton.WebGLRenderCmd = function (renderableObject) { +sp._SGSkeleton.WebGLRenderCmd = function (renderableObject) { _ccsg.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(_ccsg.Node.WebGLRenderCmd.prototype); -proto.constructor = sp.Skeleton.WebGLRenderCmd; +var proto = sp._SGSkeleton.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype); +proto.constructor = sp._SGSkeleton.WebGLRenderCmd; proto.rendering = function (ctx) { var node = this._node, tmpQuad = this._tmpQuad; diff --git a/extensions/spine/Skeleton.js b/extensions/spine/Skeleton.js index 8cadc1f618..149ec6ae15 100644 --- a/extensions/spine/Skeleton.js +++ b/extensions/spine/Skeleton.js @@ -1,8 +1,5 @@ /**************************************************************************** - Copyright (c) 2011-2012 cocos2d-x.org - Copyright (c) 2013-2014 Chukong Technologies Inc. - Copyright (c) 2014 Shengxiang Chen (Nero Chan) - Copyright (c) 2015-2016 Chukong Technologies Inc. + Copyright (c) 2016 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -25,383 +22,687 @@ THE SOFTWARE. ****************************************************************************/ -var spine = require('./spine-exported'); - /** * @module 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 -}; +var DefaultSkinsEnum = cc.Enum({ 'default': -1 }); +var DefaultAnimsEnum = cc.Enum({ '': 0 }); + +function setEnumAttr (obj, propName, enumDef) { + cc.Class.attr(obj, propName, { + type: 'Enum', + enumList: cc.Enum.getList(enumDef) + }); +} /** - * 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}} + * 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 Skeleton + * @extends cc._ComponentInSG + * @constructor */ -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 _ccsg.Node - */ -sp.Skeleton = _ccsg.Node.extend(/** @lends sp.Skeleton# */{ - _skeleton: null, - _rootBone: null, - _timeScale: 1, - _debugSlots: false, - _debugBones: false, - _premultipliedAlpha: false, - _ownsSkeletonData: null, - _atlas: null, - _blendFunc: null, +// 由于 Spine 的 _sgNode 需要参数才能初始化, 所以这里的 _sgNode 不在构造函数中赋值, 每次访问前都要先判断一次是否初始化了 - /** - * 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){ - _ccsg.Node.prototype.ctor.call(this); - this._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST}; - - if(arguments.length === 0) - this.init(); - else - this.initWithArgs(skeletonDataFile, atlasFile, scale); +sp.Skeleton = cc.Class({ + name: 'sp.Skeleton', + extends: cc._ComponentInSG, + editor: CC_EDITOR && { + menu: 'i18n:MAIN_MENU.component.others/Spine Skeleton', + //playOnFocus: true }, - _createRenderCmd:function () { - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) - return new sp.Skeleton.CanvasRenderCmd(this); - else - return new sp.Skeleton.WebGLRenderCmd(this); - }, + properties: { - /** - * Initializes a sp.Skeleton. please do not call this function by yourself, you should pass the parameters to constructor to initialize it. - */ - init: function () { - _ccsg.Node.prototype.init.call(this); - //this.setOpacityModifyRGB(true); - this._blendFunc.src = cc.ONE; - this._blendFunc.dst = cc.ONE_MINUS_SRC_ALPHA; - this.scheduleUpdate(); - }, + /** + * The skeleton data contains the skeleton information (bind pose bones, slots, draw order, + * attachments, skins, etc) and animations but does not hold any state. + * Multiple skeletons can share the same skeleton data. + * @property {sp.SkeletonData} skeletonData + */ + skeletonData: { + default: null, + type: sp.SkeletonData, + notify: function () { + this.defaultSkin = ''; + this.defaultAnimation = ''; + this._refresh(); + }, + }, - /** - * Sets whether open debug slots. - * @param {boolean} enable true to open, false to close. - */ - setDebugSolots:function(enable){ - this._debugSlots = enable; - }, + ///** + // * The url of atlas file. + // * @property {string} file + // */ + //atlasFile: { + // default: '', + // url: cc.TextAsset, + // notify: function () { + // this.defaultSkin = ''; + // this.defaultAnimation = ''; + // this._applyAsset(); + // }, + //}, - /** - * Sets whether open debug bones. - * @param {boolean} enable - */ - setDebugBones:function(enable){ - this._debugBones = enable; - }, + // 由于 spine 的 skin 是无法二次替换的,所以只能设置默认的 skin + /** + * The name of default skin. + * @property {string} defaultSkin + */ + defaultSkin: { + default: '', + visible: false + }, - /** - * Sets whether open debug slots. - * @param {boolean} enabled true to open, false to close. - */ - setDebugSlotsEnabled: function(enabled) { - this._debugSlots = enabled; - }, + /** + * The name of default animation. + * @property {string} defaultAnimation + */ + defaultAnimation: { + default: '', + visible: false + }, - /** - * Gets whether open debug slots. - * @returns {boolean} true to open, false to close. - */ - getDebugSlotsEnabled: function() { - return this._debugSlots; - }, + /** + * The name of current playing animation. + * @property {string} animation + */ + animation: { + get: function () { + var entry = this.getCurrent(0); + return (entry && entry.animation.name) || ""; + }, + set: function (value) { + this.defaultAnimation = value; + if (value) { + this.setAnimation(0, value, this.loop); + } + else { + this.clearTrack(0); + this.setToSetupPose(); + } + }, + visible: false + }, - /** - * Sets whether open debug bones. - * @param {boolean} enabled - */ - setDebugBonesEnabled: function(enabled) { - this._debugBones = enabled; - }, + /** + * @property {number} _defaultSkinIndex + */ + _defaultSkinIndex: { + get: function () { + if (this.skeletonData && this.defaultSkin) { + var skinsEnum = this.skeletonData.getSkinsEnum(); + if (skinsEnum) { + var skinIndex = skinsEnum[this.defaultSkin]; + if (skinIndex !== undefined) { + return skinIndex; + } + } + } + return 0; + }, + set: function (value) { + var skinsEnum; + if (this.skeletonData) { + skinsEnum = this.skeletonData.getSkinsEnum(); + } + if ( !skinsEnum ) { + return cc.error('Failed to set _defaultSkinIndex for "%s" because its skeletonData is invalid.', + this.name); + } + var skinName = skinsEnum[value]; + if (skinName !== undefined) { + this.defaultSkin = skinName; + if (CC_EDITOR && !cc.engine.isPlaying) { + this._refresh(); + } + } + else { + cc.error('Failed to set _defaultSkinIndex for "%s" because the index is out of range.', this.name); + } + }, + type: DefaultSkinsEnum, + visible: true, + displayName: "Default Skin" + }, - /** - * Gets whether open debug bones. - * @returns {boolean} true to open, false to close. - */ - getDebugBonesEnabled: function() { - return this._debugBones; - }, + // value of 0 represents no animation + _animationIndex: { + get: function () { + var animationName = (!CC_EDITOR || cc.engine.isPlaying) ? this.animation : this.defaultAnimation; + if (this.skeletonData && animationName) { + var animsEnum = this.skeletonData.getAnimsEnum(); + if (animsEnum) { + var animIndex = animsEnum[animationName]; + if (animIndex !== undefined) { + return animIndex; + } + } + } + return 0; + }, + set: function (value) { + if (value === 0) { + this.animation = ''; + return; + } + var animsEnum; + if (this.skeletonData) { + animsEnum = this.skeletonData.getAnimsEnum(); + } + if ( !animsEnum ) { + return cc.error('Failed to set _animationIndex for "%s" because its skeletonData is invalid.', this.name); + } + var animName = animsEnum[value]; + if (animName !== undefined) { + this.animation = animName; + } + else { + cc.error('Failed to set _animationIndex for "%s" because the index is out of range.', this.name); + } - /** - * Sets the time scale of sp.Skeleton. - * @param {Number} scale - */ - setTimeScale:function(scale){ - this._timeScale = scale; - }, + }, + type: DefaultAnimsEnum, + visible: true, + displayName: 'Animation' + }, - getTimeScale: function(){ - return this._timeScale; - }, + //// for inspector + //_animationList: { + // default: [], + // type: cc.String, + // serializable: false + //}, + // + //// for inspector + //_skinList: { + // default: [], + // type: cc.String, + // serializable: false + //}, - /** - * 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; + /** + * @property {boolean} loop + * @default false + */ + loop: false, - if (cc.js.isString(argSkeletonFile)) { - if (cc.js.isString(argAtlasFile)) { - var data = cc.loader.getRes(argAtlasFile); - sp._atlasLoader.setAtlasFile(argAtlasFile); - atlas = new spine.Atlas(data, sp._atlasLoader); - } else { - atlas = atlasFile; + /** + * The time scale of this skeleton. + * @property {number} timeScale + * @default 1 + */ + timeScale: { + default: 1, + notify: function () { + if (this._sgNode) { + this._sgNode.setTimeScale(this.timeScale); + } } - scale = scale || 1 / cc.director.getContentScaleFactor(); + }, - var attachmentLoader = new spine.AtlasAttachmentLoader(atlas); - var skeletonJsonReader = new spine.SkeletonJson(attachmentLoader); - skeletonJsonReader.scale = scale; + /** + * Indicates whether open debug slots. + * @property {boolean} debugSlots + * @default false + */ + debugSlots: { + default: false, + notify: function () { + if (this._sgNode) { + this._sgNode.setDebugSlotsEnabled(this.debugSlots); + } + }, + editorOnly: true, + }, - var skeletonJson = cc.loader.getRes(argSkeletonFile); - skeletonData = skeletonJsonReader.readSkeletonData(skeletonJson); - atlas.dispose(skeletonJsonReader); - ownsSkeletonData = true; - } else { - skeletonData = skeletonDataFile; - ownsSkeletonData = atlasFile; + /** + * Indicates whether open debug bones. + * @property {boolean} debugBones + * @default false + */ + debugBones: { + default: false, + notify: function () { + if (this._sgNode) { + this._sgNode.setDebugBonesEnabled(this.debugBones); + } + }, + editorOnly: true, } - 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; + // IMPLEMENT - 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); + onLoad: function () { + this._refresh(); + }, + + //onEnable: function () { + // this._super(); + //}, + + _createSgNode: function () { + if (this.skeletonData/* && self.atlasFile*/) { + var data = this.skeletonData.getRuntimeData(); + if (data) { + return new sp._SGSkeletonAnimation(data, null, this.skeletonData.scale); + } } - var position = this.getPosition(); - return cc.rect(position.x + minX, position.y + minY, maxX - minX, maxY - minY); + return null; }, - _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; + _initSgNode: function () { + var sgNode = this._sgNode; + sgNode.setTimeScale(this.timeScale); + //if (!CC_EDITOR) { + // function animationCallback (ccObj, trackIndex, type, event, loopCount) { + // var eventType = AnimEvents[type];3 + // var detail = { + // trackIndex: trackIndex + // }; + // if (type === sp.ANIMATION_EVENT_TYPE.COMPLETE) { + // detail.loopCount = loopCount; + // } + // else if (type === sp.ANIMATION_EVENT_TYPE.EVENT) { + // detail.event = event; + // } + // //Fire.log("[animationCallback] eventType: %s, time: '%s'", eventType, Fire.Time.time); + // self.entity.emit(eventType, detail); + // } + // sgNode.setAnimationListener(target, animationCallback); + //} + if (this.defaultSkin) { + try { + sgNode.setSkin(this.defaultSkin); + } + catch (e) { + cc._throw(e); + } + } + this.animation = this.defaultAnimation; + if (CC_EDITOR) { + sgNode.setDebugSlotsEnabled(this.debugSlots); + sgNode.setDebugBonesEnabled(this.debugBones); + } }, - /** - * Computes the world SRT from the local SRT for each bone. - */ - updateWorldTransform: function () { - this._skeleton.updateWorldTransform(); - }, + // RENDERER /** * Sets the bones and slots to the setup pose. + * @method setToSetupPose */ setToSetupPose: function () { - this._skeleton.setToSetupPose(); + if (this._sgNode) { + this._sgNode.setToSetupPose(); + } }, /** * Sets the bones to the setup pose, using the values from the `BoneData` list in the `SkeletonData`. + * @method setBonesToSetupPose */ setBonesToSetupPose: function () { - this._skeleton.setBonesToSetupPose(); - }, - - /** - * Sets the slots to the setup pose, using the values from the `SlotData` list in the `SkeletonData`. - */ - setSlotsToSetupPose: function () { - this._skeleton.setSlotsToSetupPose(); - }, - - /** - * Finds a bone by name. This does a string comparison for every bone. - * @param {String} boneName - * @returns {spine.Bone} - */ - findBone: function (boneName) { - return this._skeleton.findBone(boneName); - }, - - /** - * Finds a slot by name. This does a string comparison for every slot. - * @param {String} slotName - * @returns {spine.Slot} - */ - findSlot: function (slotName) { - return this._skeleton.findSlot(slotName); - }, - - /** - * Finds a skin by name and makes it the active skin. This does a string comparison for every skin. Note that setting the skin does not change which attachments are visible. - * @param {string} skinName - * @returns {spine.Skin} - */ - setSkin: function (skinName) { - return this._skeleton.setSkinByName(skinName); - }, - - /** - * Returns the attachment for the slot and attachment name. The skeleton looks first in its skin, then in the skeleton data’s default skin. - * @param {String} slotName - * @param {String} attachmentName - * @returns {spine.RegionAttachment|spine.BoundingBoxAttachment} - */ - getAttachment: function (slotName, attachmentName) { - return this._skeleton.getAttachmentBySlotName(slotName, attachmentName); - }, - - /** - * Sets the attachment for the slot and attachment name. The skeleton looks first in its skin, then in the skeleton data’s default skin. - * @param {String} slotName - * @param {String} attachmentName - */ - setAttachment: function (slotName, attachmentName) { - this._skeleton.setAttachment(slotName, attachmentName); - }, - - /** - * Sets the premultiplied alpha value to sp.Skeleton. - * @param {Number} alpha - */ - setOpacityModifyRGB: function (alpha) { - this._premultipliedAlpha = alpha; - }, - - /** - * Returns whether to enable premultiplied alpha. - * @returns {boolean} - */ - isOpacityModifyRGB: function () { - return this._premultipliedAlpha; - }, - - /** - * Sets skeleton data to sp.Skeleton. - * @param {spine.SkeletonData} skeletonData - * @param {spine.SkeletonData} ownsSkeletonData - */ - setSkeletonData: function (skeletonData, ownsSkeletonData) { - if(skeletonData.width != null && skeletonData.height != null) - this.setContentSize(skeletonData.width / cc.director.getContentScaleFactor(), skeletonData.height / cc.director.getContentScaleFactor()); - - this._skeleton = new spine.Skeleton(skeletonData); - this._skeleton.updateWorldTransform(); - this._rootBone = this._skeleton.getRootBone(); - this._ownsSkeletonData = ownsSkeletonData; - - this._renderCmd._createChildFormSkeletonData(); - }, - - /** - * Return the renderer of attachment. - * @param {spine.RegionAttachment|spine.BoundingBoxAttachment} regionAttachment - * @returns {_ccsg.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; + if (this._sgNode) { + this._sgNode.setBonesToSetupPose(); } }, /** - * Update will be called automatically every frame if "scheduleUpdate" is called when the node is "live". - * @param {Number} dt Delta time since last update + * Sets the slots to the setup pose, using the values from the `SlotData` list in the `SkeletonData`. + * @method setSlotsToSetupPose */ - update: function (dt) { - this._skeleton.update(dt); + setSlotsToSetupPose: function () { + if (this._sgNode) { + this._sgNode.setSlotsToSetupPose(); + } + }, + + /** + * Finds a bone by name. This does a string comparison for every bone. + * @method findBone + * @param {string} boneName + * @return {spine.Bone} + */ + findBone: function (boneName) { + if (this._sgNode) { + return this._sgNode.findBone(boneName); + } + return null; + }, + + /** + * Finds a slot by name. This does a string comparison for every slot. + * @method findSlot + * @param {string} slotName + * @return {spine.Slot} + */ + findSlot: function (slotName) { + if (this._sgNode) { + return this._sgNode.findSlot(slotName); + } + return null; + }, + + /** + * 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. + * @method setSkin + * @param {string} skinName + * @return {spine.Skin} + */ + setSkin: function (skinName) { + if (this._sgNode) { + return this._sgNode.setSkin(skinName); + } + return null; + }, + + /** + * Returns the attachment for the slot and attachment name. The skeleton looks first in its skin, then in the skeleton data’s default skin. + * @method getAttachment + * @param {string} slotName + * @param {string} attachmentName + * @return {spine.RegionAttachment|sp.spine.BoundingBoxAttachment} + */ + getAttachment: function (slotName, attachmentName) { + if (this._sgNode) { + return this._sgNode.getAttachment(slotName, attachmentName); + } + return null; + }, + + /** + * Sets the attachment for the slot and attachment name. The skeleton looks first in its skin, then in the skeleton data’s default skin. + * @method setAttachment + * @param {string} slotName + * @param {string} attachmentName + */ + setAttachment: function (slotName, attachmentName) { + if (this._sgNode) { + this._sgNode.setAttachment(slotName, attachmentName); + } + }, + + /** + * Sets skeleton data to sp.Skeleton. + * @method setSkeletonData + * @param {spine.SkeletonData} skeletonData + * @param {spine.SkeletonData} ownsSkeletonData + */ + setSkeletonData: function (skeletonData, ownsSkeletonData) { + if (this._sgNode) { + this._sgNode.setSkeletonData(skeletonData, ownsSkeletonData); + } + }, + + ///** + // * Return the renderer of attachment. + // * @method getTextureAtlas + // * @param {spine.RegionAttachment|sp.spine.BoundingBoxAttachment} regionAttachment + // * @return {_ccsg.Node} + // */ + //getTextureAtlas: function (regionAttachment) { + // if (this._sgNode) { + // this._sgNode.getTextureAtlas(regionAttachment); + // } + //}, + + // ANIMATION + + /** + * Sets animation state data. + * @method setAnimationStateData + * @param {spine.AnimationStateData} stateData + */ + setAnimationStateData: function (stateData) { + if (this._sgNode) { + return this._sgNode.setAnimationStateData(stateData); + } + }, + + /** + * Mix applies all keyframe values, interpolated for the specified time and mixed with the current values. + * @method setMix + * @param {string} fromAnimation + * @param {string} toAnimation + * @param {number} duration + */ + setMix: function (fromAnimation, toAnimation, duration) { + if (this._sgNode) { + this._sgNode.setMix(fromAnimation, toAnimation, duration); + } + }, + + /** + * Sets event listener. + * @method setAnimationListener + * @param {object} target + * @param {function} callback + */ + setAnimationListener: function (target, callback) { + if (this._sgNode) { + this._sgNode.setAnimationListener(target, callback); + } + }, + + /** + * Set the current animation. Any queued animations are cleared. + * @method setAnimation + * @param {number} trackIndex + * @param {string} name + * @param {boolean} loop + * @return {spine.TrackEntry} + */ + setAnimation: function (trackIndex, name, loop) { + if (this._sgNode) { + var res = this._sgNode.setAnimation(trackIndex, name, loop); + if (CC_EDITOR && !cc.engine.isPlaying) { + this._sample(); + this.clearTrack(trackIndex); + } + return res; + } + return null; + }, + + _sample: function () { + if (this._sgNode) { + this._sgNode.update(0); + } + }, + + /** + * Adds an animation to be played delay seconds after the current or last queued animation. + * @method addAnimation + * @param {number} trackIndex + * @param {string} name + * @param {boolean} loop + * @param {number} [delay=0] + * @return {spine.TrackEntry} + */ + addAnimation: function (trackIndex, name, loop, delay) { + if (this._sgNode) { + return this._sgNode.addAnimation(trackIndex, name, loop, delay); + } + return null; + }, + + /** + * Returns track entry by trackIndex. + * @method getCurrent + * @param trackIndex + * @return {spine.TrackEntry} + */ + getCurrent: function (trackIndex) { + if (this._sgNode) { + return this._sgNode.getCurrent(trackIndex); + } + return null; + }, + + /** + * Clears all tracks of animation state. + * @method clearTracks + */ + clearTracks: function () { + if (this._sgNode) { + this._sgNode.clearTracks(); + } + }, + + /** + * Clears track of animation state by trackIndex. + * @method clearTrack + * @param {number} trackIndex + */ + clearTrack: function (trackIndex) { + if (this._sgNode) { + this._sgNode.clearTrack(trackIndex); + if (CC_EDITOR && !cc.engine.isPlaying) { + this._sample(); + } + } + }, + + // update animation list for editor + _updateAnimEnum: CC_EDITOR && function () { + var animEnum; + if (this.skeletonData) { + animEnum = this.skeletonData.getAnimsEnum(); + } + // change enum + setEnumAttr(this, '_animationIndex', animEnum || DefaultAnimsEnum); + }, + // update skin list for editor + _updateSkinEnum: CC_EDITOR && function () { + var skinEnum; + if (this.skeletonData) { + skinEnum = this.skeletonData.getSkinsEnum(); + } + // change enum + setEnumAttr(this, '_defaultSkinIndex', skinEnum || DefaultSkinsEnum); + }, + // force refresh inspector + _refreshInspector: CC_EDITOR && function () { + var ga = Editor.Selection.curGlobalActivate(); + var inspecting = (ga && ga.id === this.node.uuid && ga.type === 'node'); + if (inspecting) { + Editor.Selection.unselect('node', this.node.uuid); + ga = Editor.Selection.curGlobalActivate(); + var id = this.node.uuid; + var inspectOther = (ga && ga.type === 'node' && ga.id); + if (inspectOther) { + setTimeout(function () { + Editor.Selection.select('node', id, false); + }, 200); + } + else { + Editor.Selection.select('node', id, false); + } + } + }, + + /** + * Set the start event listener. + * @method setStartListener + * @param {function} listener + */ + setStartListener: function (listener) { + if (this._sgNode) { + this._sgNode.setStartListener(listener); + } + }, + + /** + * Set the end event listener. + * @method setEndListener + * @param {function} listener + */ + setEndListener: function (listener) { + if (this._sgNode) { + this._sgNode.setEndListener(listener); + } + }, + + setCompleteListener: function (listener) { + if (this._sgNode) { + this._sgNode.setCompleteListener(listener); + } + }, + + setEventListener: function (listener) { + if (this._sgNode) { + this._sgNode.setEventListener(listener); + } + }, + + setTrackStartListener: function (entry, listener) { + if (this._sgNode) { + this._sgNode.setTrackStartListener(entry, listener); + } + }, + + setTrackEndListener: function (entry, listener) { + if (this._sgNode) { + this._sgNode.setTrackEndListener(entry, listener); + } + }, + + setTrackCompleteListener: function (entry, listener) { + if (this._sgNode) { + this._sgNode.setTrackCompleteListener(entry, listener); + } + }, + + setTrackEventListener: function (entry, listener) { + if (this._sgNode) { + this._sgNode.setTrackEventListener(entry, listener); + } + }, + + // + + getState: function () { + if (this._sgNode) { + return this._sgNode.getState(); + } + }, + + _refresh: function () { + var self = this; + + // discard exists sgNode + if (self._sgNode) { + if ( self.node._sizeProvider === self._sgNode ) { + self.node._sizeProvider = null; + } + self._removeSgNode(); + self._sgNode = null; + } + + // recreate sgNode... + var sgNode = self._sgNode = self._createSgNode(); + if (sgNode) { + sgNode.retain(); + self._initSgNode(); + self._appendSgNode(sgNode); + if ( !self.node._sizeProvider ) { + self.node._sizeProvider = sgNode; + } + } + + if (CC_EDITOR) { + // update inspector + self._updateAnimEnum(); + self._updateSkinEnum(); + self._refreshInspector(); + } } }); - -/** - * 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/SkeletonData.js b/extensions/spine/SkeletonData.js new file mode 100644 index 0000000000..eb3be0c416 --- /dev/null +++ b/extensions/spine/SkeletonData.js @@ -0,0 +1,269 @@ +/**************************************************************************** + Copyright (c) 2016 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. + ****************************************************************************/ + +/** + * @module sp + */ + +// implements a simple texture loader like sp._atlasLoader +var TextureLoader = cc.Class({ + ctor: function () { + // {SkeletonData} + this.asset = arguments[0]; + }, + getTexture: function (line) { + //var name = cc.path.mainFileName(line); + //var textures = this.asset.textures; + //for (var i = 0; i < textures.length; i++) { + // var tex = textures[i]; + // if (tex.name === name) { + // return tex; + // } + //} + var urls = this.asset.textures; + for (var i = 0; i < urls.length; i++) { + var url = urls[i]; + if (url.endsWith(line)) { + return cc.textureCache.addImage(url); + } + } + return null; + }, + load: function (page, line, spAtlas) { + var texture = this.getTexture(line); + if (texture) { + if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { + page.rendererObject = new cc.TextureAtlas(texture, 128); + page.width = texture.getPixelWidth(); + page.height = texture.getPixelHeight(); + } + else { + page._texture = texture; + } + } + else { + cc.error('Failed to load spine atlas "$s"', line); + } + }, + unload: function (obj) { + //page.rendererObject.release(); + } +}); + +/** + * The skeleton data of spine. + * + * @class SkeletonData + * @extends cc.Asset + */ +var SkeletonData = cc.Class({ + name: 'sp.SkeletonData', + extends: cc.Asset, + + ctor: function () { + this.reset(); + }, + + properties: { + + _skeletonJson: null, + + /** + * @see http://en.esotericsoftware.com/spine-json-format + * @property {object} skeletonJson + */ + skeletonJson: { + get: function () { + return this._skeletonJson; + }, + set: function (value) { + this._skeletonJson = value; + this.reset(); + } + }, + + _atlasText: "", + + /** + * @property {string} atlasText + */ + atlasText: { + get: function () { + return this._atlasText; + }, + set: function (value) { + this._atlasText = value; + this.reset(); + } + }, + + /** + * @property {cc.Texture2D} textures + */ + textures: { + default: [], + url: [cc.Texture2D] + }, + + /** + * A scale can be specified on the JSON or binary loader which will scale the bone positions, + * image sizes, and animation translations. + * This can be useful when using different sized images than were used when designing the skeleton + * in Spine. For example, if using images that are half the size than were used in Spine, + * a scale of 0.5 can be used. This is commonly used for games that can run with either low or high + * resolution texture atlases. + * + * @see http://en.esotericsoftware.com/spine-using-runtimes#Scaling + * @property {number} scale + */ + scale: 1 + }, + + // PUBLIC + + createNode: function (callback) { + //var Url = require('fire-url'); + //var node = new cc.Node(Url.basenameNoExt(info.url)); + //var skeleton = node.addComponent(sp.Skeleton); + //skeleton.skeletonFile = info.url; + + var node = new cc.Node(this.name); + var skeleton = node.addComponent(sp.Skeleton); + skeleton.skeletonData = this; + + return callback(null, node); + }, + + reset: function () { + /** + * @property {spine.SkeletonData} _skeletonData + * @private + */ + this._skeletonCache = null; + /** + * @property {spine.Atlas} _atlasCache + * @private + */ + this._atlasCache = null; + if (CC_EDITOR) { + this._skinsEnum = null; + this._animsEnum = null; + } + }, + + /** + * Get the included SkeletonData used in spine runtime. + * @method getRuntimeData + * @param {boolean} [quiet=false] + * @return {spine.SkeletonData} + */ + getRuntimeData: function (quiet) { + if (this._skeletonCache) { + return this._skeletonCache; + } + + + if ( !(this.textures && this.textures.length > 0) ) { + if ( !quiet ) { + cc.error('Please re-import "%s" because its textures is not initialized! (This workflow will be improved in the future.)', this.name); + } + return null; + } + + var atlas = this._getAtlas(quiet); + if (! atlas) { + return null; + } + var attachmentLoader = new sp.spine.AtlasAttachmentLoader(atlas); + var jsonReader = new sp.spine.SkeletonJson(attachmentLoader); + jsonReader.scale = this.scale; + + var json = this.skeletonJson; + this._skeletonCache = jsonReader.readSkeletonData(json); + atlas.dispose(jsonReader); + + return this._skeletonCache; + }, + + // EDITOR + + getSkinsEnum: CC_EDITOR && function () { + if (this._skinsEnum) { + return this._skinsEnum; + } + var sd = this.getRuntimeData(true); + if (sd) { + var skins = sd.skins; + var enumDef = {}; + for (var i = 0; i < skins.length; i++) { + var name = skins[i].name; + enumDef[name] = i; + } + return this._skinsEnum = cc.Enum(enumDef); + } + return null; + }, + + getAnimsEnum: CC_EDITOR && function () { + if (this._animsEnum) { + return this._animsEnum; + } + var sd = this.getRuntimeData(true); + if (sd) { + var enumDef = { '': 0 }; + var anims = sd.animations; + for (var i = 0; i < anims.length; i++) { + var name = anims[i].name; + enumDef[name] = i + 1; + } + return this._animsEnum = cc.Enum(enumDef); + } + return null; + }, + + // PRIVATE + + /** + * @method _getAtlas + * @param {boolean} [quiet=false] + * @return {spine.Atlas} + * @private + */ + _getAtlas: function (quiet) { + if (this._atlasCache) { + return this._atlasCache; + } + + if ( !this.atlasText ) { + if ( !quiet ) { + cc.error('The atlas asset of "%s" is not exists!', this.name); + } + return null; + } + + return this._atlasCache = new sp.spine.Atlas(this.atlasText, new TextureLoader(this)); + } +}); + +sp.SkeletonData = module.exports = SkeletonData; diff --git a/extensions/spine/SpineAsset.js b/extensions/spine/SpineAsset.js deleted file mode 100644 index 9bb126170e..0000000000 --- a/extensions/spine/SpineAsset.js +++ /dev/null @@ -1,40 +0,0 @@ -/**************************************************************************** - Copyright (c) 2016 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. - ****************************************************************************/ - -/** - * @module sp - */ - -/** - * The skeleton data of spine. - * @class SpineAsset - * @extends RawAsset - * @constructor - */ -var SpineAsset = cc.Class({ - name: 'sp.SpineAsset', - extends: cc.RawAsset, -}); - -sp.SpineAsset = module.exports = SpineAsset; diff --git a/extensions/spine/editor/spine-asset.html b/extensions/spine/editor/spine-asset.html new file mode 100644 index 0000000000..81cf2b6d84 --- /dev/null +++ b/extensions/spine/editor/spine-asset.html @@ -0,0 +1,44 @@ + + + + + + + + + diff --git a/extensions/spine/editor/spine-asset.png b/extensions/spine/editor/spine-asset.png new file mode 100644 index 0000000000..5ac8644d95 Binary files /dev/null and b/extensions/spine/editor/spine-asset.png differ diff --git a/extensions/spine/editor/spine-meta.js b/extensions/spine/editor/spine-meta.js new file mode 100644 index 0000000000..5478f38c6d --- /dev/null +++ b/extensions/spine/editor/spine-meta.js @@ -0,0 +1,182 @@ +'use strict'; + +/* + * Reference: + * http://en.esotericsoftware.com/spine-json-format + */ + +const Fs = require('fire-fs'); +const Path = require('fire-path'); +const Spine = require('../lib/spine'); + +const ATLAS_EXTS = ['.atlas', '.txt', '']; +const SPINE_ENCODING = { encoding: 'utf-8' }; + +const CustomAssetMeta = Editor.metas['custom-asset']; + +function searchAtlas (skeletonPath, callback) { + skeletonPath = Path.stripExt(skeletonPath); + + function next (index) { + var suffix = ATLAS_EXTS[index]; + var path = skeletonPath + suffix; + Fs.exists(path, exists => { + if (exists) { + return callback(null, path); + } + else if (index + 1 < ATLAS_EXTS.length) { + next(index + 1); + } + else { + callback(new Error(`Can not find ${skeletonPath + ATLAS_EXTS[0]}`)); + } + }); + } + + next(0); +} + +function loadAtlasText (skeletonPath, callback) { + searchAtlas(skeletonPath, (err, path) => { + if (err) { + return callback(err); + } + Fs.readFile(path, SPINE_ENCODING, (err, data) => { + callback(err, { + data: data, + atlasPath: path + }); + }); + }); +} + +// A dummy texture loader to record all textures in atlas +class TextureParser { + constructor (atlasPath) { + this.atlasPath = atlasPath; + // the loaded texture array + this.textures = []; + } + load (page, line) { + var name = Path.basename(line); + var base = Path.dirname(this.atlasPath); + var path = Path.resolve(base, name); + var uuid = Editor.assetdb.fspathToUuid(path); + if (!uuid) { + return; + } + //if (!uuid) { + // cc.error('Can not find texture "%s" for atlas "%s"', line, this.atlasPath); + // return; + //} + //var texture = Editor.serialize.asAsset(uuid); + var url = Editor.assetdb.uuidToUrl(uuid); + this.textures.push(url); + } + unload () {} +} + +class SpineMeta extends CustomAssetMeta { + constructor (assetdb) { + super(assetdb); + this.textures = []; + this.scale = 1; + } + + // HACK - for inspector + get texture () { + //return this.textures[0]; + return Editor.assetdb.uuidToUrl(this.textures[0]); + } + set texture (value) { + this.textures[0] = Editor.assetdb.urlToUuid(value); + //this.textures[0] = value; + } + + static version () { return '1.0.0'; } + static defaultType () { + return 'spine'; + } + + static validate (assetpath) { + // TODO - import as a folder named '***.spine' + var json; + var text = Fs.readFileSync(assetpath, 'utf8'); + var fastTest = text.slice(0, 30); + var maybe = ( fastTest.indexOf('slots') > 0 || + fastTest.indexOf('skins') > 0 || + fastTest.indexOf('events') > 0 || + fastTest.indexOf('animations') > 0 || + fastTest.indexOf('bones') > 0 || + fastTest.indexOf('skeleton') > 0 || + fastTest.indexOf('\"ik\"') > 0 + ); + if (maybe) { + try { + json = JSON.parse(text); + } + catch (e) { + return false; + } + return Array.isArray(json.bones); + } + return false; + } + + import (fspath, cb) { + var self = this; + + Fs.readFile(fspath, SPINE_ENCODING, (err, data) => { + if (err) { + return cb(err); + } + + var json; + try { + json = JSON.parse(data); + } + catch (e) { + return cb(e); + } + + var asset = new sp.SkeletonData(); + asset.name = Path.basenameNoExt(fspath); + asset.skeletonJson = json; + asset.scale = this.scale; + + loadAtlasText(fspath, (err, res) => { + if (err) { + return cb(err); + } + + // parse atlas textures + var textureParser = new TextureParser(res.atlasPath); + try { + new Spine.Atlas(res.data, textureParser); + } + catch (err) { + return cb(new Error(`Failed to load atlas file: "${res.atlasPath}". ${err.stack || err}`)); + } + if (textureParser.textures.length > 0) { + asset.textures = textureParser.textures; + this.textures = textureParser.textures.map(url => Editor.assetdb.urlToUuid(url)); + } + else { + asset.textures = this.textures.map(uuid => Editor.assetdb.uuidToUrl(uuid)); + } + + // + asset.atlasText = res.data; + + // + self._assetdb.saveAssetToLibrary(self.uuid, asset); + + cb(); + }); + }); + } +} + +SpineMeta.prototype.export = null; + +module.exports = SpineMeta; diff --git a/extensions/spine/index.js b/extensions/spine/index.js index 454cf2e0e6..a84678dc64 100644 --- a/extensions/spine/index.js +++ b/extensions/spine/index.js @@ -28,13 +28,79 @@ * @main sp */ +/* + * Reference: + * http://esotericsoftware.com/spine-runtime-terminology + * http://esotericsoftware.com/files/runtime-diagram.png + * http://en.esotericsoftware.com/spine-using-runtimes + */ + sp = {}; -if (!CC_JSB && (!CC_EDITOR || !Editor.isCoreLevel)) { - require('./Skeleton'); - require('./SkeletonCanvasRenderCmd'); - require('./SkeletonWebGLRenderCmd'); - require('./SkeletonAnimation'); -} +// The vertex index of spine. +sp.VERTEX_INDEX = { + X1: 0, + Y1: 1, + X2: 2, + Y2: 3, + X3: 4, + Y3: 5, + X4: 6, + Y4: 7 +}; -require('./SpineAsset'); +// The attachment type of spine. It contains three type: REGION(0), BOUNDING_BOX(1), MESH(2) and SKINNED_MESH. +sp.ATTACHMENT_TYPE = { + REGION: 0, + BOUNDING_BOX: 1, + MESH: 2, + SKINNED_MESH:3 +}; + +/** + * The event type of spine skeleton animation. + * @enum AnimationEventType + */ +sp.AnimationEventType = cc.Enum({ + /** + * @property {Number} START + */ + START: 0, + /** + * @property {Number} END + */ + END: 1, + /** + * @property {Number} COMPLETE + */ + COMPLETE: 2, + /** + * @property {Number} EVENT + */ + EVENT: 3 +}); + +/** + * @module sp + */ + +if (!CC_JSB && (!CC_EDITOR || !Editor.isCoreLevel)) { + + /** + * The official spine runtime. + * See http://en.esotericsoftware.com/spine-using-runtimes + * @property {object} spine + */ + sp.spine = require('./lib/spine'); + + require('./SGSkeleton'); + require('./SGSkeletonCanvasRenderCmd'); + require('./SGSkeletonWebGLRenderCmd'); + require('./SGSkeletonAnimation'); + + require('./SkeletonData'); + require('./Skeleton'); +} +else { + require('./SkeletonData'); +} diff --git a/extensions/spine/spine-exported.js b/extensions/spine/lib/spine.js similarity index 96% rename from extensions/spine/spine-exported.js rename to extensions/spine/lib/spine.js index 55ca291338..f4e875cf1c 100644 --- a/extensions/spine/spine-exported.js +++ b/extensions/spine/lib/spine.js @@ -1,10 +1,10 @@ /****************************************************************************** * 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 @@ -16,7 +16,7 @@ * 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 @@ -178,6 +178,7 @@ spine.Slot.prototype = { attachment: null, attachmentVertices: [], setAttachment: function (attachment) { + if (this.attachment == attachment) return; this.attachment = attachment; this._attachmentTime = this.bone.skeleton.time; this.attachmentVertices.length = 0; @@ -195,11 +196,16 @@ spine.Slot.prototype = { 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; + if (!data.attachmentName) + this.setAttachment(null); + else { + var slotDatas = this.bone.skeleton.data.slots; + for (var i = 0, n = slotDatas.length; i < n; i++) { + if (slotDatas[i] == data) { + this.attachment = null; + this.setAttachment(this.bone.skeleton.getAttachmentBySlotIndex(i, data.attachmentName)); + break; + } } } } @@ -220,12 +226,12 @@ spine.IkConstraint.prototype = { 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; + 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; } } }; @@ -412,7 +418,7 @@ spine.Curves.prototype = { 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; @@ -1018,7 +1024,7 @@ spine.Skeleton = function (skeletonData) { 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)); @@ -1049,28 +1055,28 @@ spine.Skeleton.prototype = { 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; + 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; } - if (child == parent) break; - child = child.parent; } - } - current = current.parent; - } while (current); - nonIkBones[nonIkBones.length] = bone; - } + current = current.parent; + } while (current); + nonIkBones[nonIkBones.length] = bone; + } }, /** Updates the world transform for each bone. */ updateWorldTransform: function () { @@ -1148,11 +1154,11 @@ spine.Skeleton.prototype = { }, setSkinByName: function (skinName) { var skin = this.data.findSkin(skinName); - if (!skin) throw new Error("Skin not found: " + skinName); + if (!skin) throw "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 + /** 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) { @@ -1195,13 +1201,13 @@ spine.Skeleton.prototype = { var attachment = null; if (attachmentName) { attachment = this.getAttachmentBySlotIndex(i, attachmentName); - if (!attachment) throw new Error("Attachment not found: " + attachmentName + ", for slot: " + slotName); + if (!attachment) throw "Attachment not found: " + attachmentName + ", for slot: " + slotName; } slot.setAttachment(attachment); return; } } - throw new Error("Slot not found: " + slotName); + throw "Slot not found: " + slotName; }, /** @return May be null. */ findIkConstraint: function (ikConstraintName) { @@ -1489,9 +1495,9 @@ 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); + if (!from) throw "Animation not found: " + fromName; var to = this.skeletonData.findAnimation(toName); - if (!to) throw new Error("Animation not found: " + toName); + if (!to) throw "Animation not found: " + toName; this.setMix(from, to, duration); }, setMix: function (from, to, duration) { @@ -1599,7 +1605,7 @@ spine.AnimationState.prototype = { clearTracks: function () { for (var i = 0, n = this.tracks.length; i < n; i++) this.clearTrack(i); - this.tracks.length = 0; + this.tracks.length = 0; }, clearTrack: function (trackIndex) { if (trackIndex >= this.tracks.length) return; @@ -1644,7 +1650,7 @@ spine.AnimationState.prototype = { }, setAnimationByName: function (trackIndex, animationName, loop) { var animation = this.data.skeletonData.findAnimation(animationName); - if (!animation) throw new Error("Animation not found: " + animationName); + if (!animation) throw "Animation not found: " + animationName; return this.setAnimation(trackIndex, animation, loop); }, /** Set the current animation. Any queued animations are cleared. */ @@ -1658,7 +1664,7 @@ spine.AnimationState.prototype = { }, addAnimationByName: function (trackIndex, animationName, loop, delay) { var animation = this.data.skeletonData.findAnimation(animationName); - if (!animation) throw new Error("Animation not found: " + animationName); + if (!animation) throw "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. @@ -1719,7 +1725,7 @@ spine.SkeletonJson.prototype = { var parent = null; if (boneMap["parent"]) { parent = skeletonData.findBone(boneMap["parent"]); - if (!parent) throw new Error("Parent bone not found: " + boneMap["parent"]); + if (!parent) throw "Parent bone not found: " + boneMap["parent"]; } var boneData = new spine.BoneData(boneMap["name"], parent); boneData.length = (boneMap["length"] || 0) * this.scale; @@ -1743,12 +1749,12 @@ spine.SkeletonJson.prototype = { 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]); + if (!bone) throw "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"]); + if (!ikConstraintData.target) throw "Target bone not found: " + ikMap["target"]; ikConstraintData.bendDirection = (!ikMap.hasOwnProperty("bendPositive") || ikMap["bendPositive"]) ? 1 : -1; ikConstraintData.mix = ikMap.hasOwnProperty("mix") ? ikMap["mix"] : 1; @@ -1762,7 +1768,7 @@ spine.SkeletonJson.prototype = { 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"]); + if (!boneData) throw "Slot bone not found: " + slotMap["bone"]; var slotData = new spine.SlotData(slotMap["name"], boneData); var color = slotMap["color"]; @@ -1774,7 +1780,7 @@ spine.SkeletonJson.prototype = { } slotData.attachmentName = slotMap["attachment"]; - slotData.blendMode = spine.AttachmentType[slotMap["blend"] || "normal"]; + slotData.blendMode = spine.BlendMode[slotMap["blend"] || "normal"]; skeletonData.slots.push(slotData); } @@ -1825,7 +1831,7 @@ spine.SkeletonJson.prototype = { var type = spine.AttachmentType[map["type"] || "region"]; var path = map["path"] || name; - + var scale = this.scale; if (type == spine.AttachmentType.region) { var region = this.attachmentLoader.newRegionAttachment(skin, name, path); @@ -1852,7 +1858,7 @@ spine.SkeletonJson.prototype = { } else if (type == spine.AttachmentType.mesh) { var mesh = this.attachmentLoader.newMeshAttachment(skin, name, path); if (!mesh) return null; - mesh.path = path; + mesh.path = path; mesh.vertices = this.getFloatArray(map, "vertices", scale); mesh.triangles = this.getIntArray(map, "triangles"); mesh.regionUVs = this.getFloatArray(map, "uvs", 1); @@ -1896,7 +1902,7 @@ spine.SkeletonJson.prototype = { mesh.triangles = this.getIntArray(map, "triangles"); mesh.regionUVs = uvs; mesh.updateUVs(); - + color = map["color"]; if (color) { mesh.r = this.toColor(color, 0); @@ -1904,7 +1910,7 @@ spine.SkeletonJson.prototype = { mesh.b = this.toColor(color, 2); mesh.a = this.toColor(color, 3); } - + mesh.hullLength = (map["hull"] || 0) * 2; if (map["edges"]) mesh.edges = this.getIntArray(map, "edges"); mesh.width = (map["width"] || 0) * scale; @@ -1917,7 +1923,7 @@ spine.SkeletonJson.prototype = { attachment.vertices.push(vertices[i] * scale); return attachment; } - throw new Error("Unknown attachment type: " + type); + throw "Unknown attachment type: " + type; }, readAnimation: function (name, map, skeletonData) { var timelines = []; @@ -1964,7 +1970,7 @@ spine.SkeletonJson.prototype = { duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]); } else - throw new Error("Invalid timeline type for a slot: " + timelineName + " (" + slotName + ")"); + throw "Invalid timeline type for a slot: " + timelineName + " (" + slotName + ")"; } } @@ -1972,7 +1978,7 @@ spine.SkeletonJson.prototype = { 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); + if (boneIndex == -1) throw "Bone not found: " + boneName; var boneMap = bones[boneName]; for (var timelineName in boneMap) { @@ -2030,7 +2036,7 @@ spine.SkeletonJson.prototype = { 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 + ")"); + throw "Invalid timeline type for a bone: " + timelineName + " (" + boneName + ")"; } } @@ -2065,10 +2071,10 @@ spine.SkeletonJson.prototype = { 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); + if (!attachment) throw "FFD attachment not found: " + meshName; timeline.slotIndex = slotIndex; timeline.attachment = attachment; - + var isMesh = attachment.type == spine.AttachmentType.mesh; var vertexCount; if (isMesh) @@ -2106,7 +2112,7 @@ spine.SkeletonJson.prototype = { vertices[ii] += meshVertices[ii]; } } - + timeline.setFrame(frameIndex, valueMap["time"], vertices); this.readCurve(timeline, frameIndex, valueMap); frameIndex++; @@ -2138,7 +2144,7 @@ spine.SkeletonJson.prototype = { 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"]); + if (slotIndex == -1) throw "Slot not found: " + offsetMap["slot"]; // Collect unchanged items. while (originalIndex != slotIndex) unchanged[unchangedIndex++] = originalIndex++; @@ -2165,7 +2171,7 @@ spine.SkeletonJson.prototype = { 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"]); + if (!eventData) throw "Event not found: " + eventMap["name"]; var event = new spine.Event(eventData); event.intValue = eventMap.hasOwnProperty("int") ? eventMap["int"] : eventData.intValue; event.floatValue = eventMap.hasOwnProperty("float") ? eventMap["float"] : eventData.floatValue; @@ -2180,7 +2186,7 @@ spine.SkeletonJson.prototype = { }, readCurve: function (timeline, frameIndex, valueMap) { var curve = valueMap["curve"]; - if (!curve) + if (!curve) timeline.curves.setLinear(frameIndex); else if (curve == "stepped") timeline.curves.setStepped(frameIndex); @@ -2188,7 +2194,7 @@ spine.SkeletonJson.prototype = { 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); + if (hexString.length != 8) throw "Color hexidecimal length must be 8, recieved: " + hexString; return parseInt(hexString.substring(colorIndex * 2, (colorIndex * 2) + 2), 16) / 255; }, getFloatArray: function (map, name, scale) { @@ -2408,14 +2414,14 @@ spine.AtlasReader.prototype = { readValue: function () { var line = this.readLine(); var colon = line.indexOf(":"); - if (colon == -1) throw new Error("Invalid line: " + line); + if (colon == -1) throw "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); + if (colon == -1) throw "Invalid line: " + line; var i = 0, lastMatch = colon + 1; for (; i < 3; i++) { var comma = line.indexOf(",", lastMatch); @@ -2434,7 +2440,7 @@ spine.AtlasAttachmentLoader = function (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 + ")"); + if (!region) throw "Region not found in atlas: " + path + " (region attachment: " + name + ")"; var attachment = new spine.RegionAttachment(name); attachment.rendererObject = region; attachment.setUVs(region.u, region.v, region.u2, region.v2, region.rotate); @@ -2448,7 +2454,7 @@ spine.AtlasAttachmentLoader.prototype = { }, 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 + ")"); + if (!region) throw "Region not found in atlas: " + path + " (mesh attachment: " + name + ")"; var attachment = new spine.MeshAttachment(name); attachment.rendererObject = region; attachment.regionU = region.u; @@ -2466,7 +2472,7 @@ spine.AtlasAttachmentLoader.prototype = { }, 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 + ")"); + if (!region) throw "Region not found in atlas: " + path + " (skinned mesh attachment: " + name + ")"; var attachment = new spine.SkinnedMeshAttachment(name); attachment.rendererObject = region; attachment.regionU = region.u; @@ -2635,4 +2641,5 @@ spine.SkeletonBounds.prototype = { } }; +// TODO - delete me module.exports = spine; diff --git a/gulpfile.js b/gulpfile.js index 4a862aaf3b..d1c5ef54ab 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -23,11 +23,11 @@ paths = { '../../cocos2d/core/platform/CCLoader', '../../cocos2d/core/platform/CCLoaders', '../../cocos2d/core/event/event', - '../../extensions/spine/Skeleton', - '../../extensions/spine/SkeletonAnimation', - '../../extensions/spine/SkeletonCanvasRenderCmd', - '../../extensions/spine/SkeletonWebGLRenderCmd', - '../../extensions/spine/spine-exported', + '../../extensions/spine/SGSkeleton', + '../../extensions/spine/SGSkeletonAnimation', + '../../extensions/spine/SGSkeletonCanvasRenderCmd', + '../../extensions/spine/SGSkeletonWebGLRenderCmd', + '../../extensions/spine/lib/spine', ], test: { diff --git a/test/visual-tests/src/SpineTest/SpineTest.js b/test/visual-tests/src/SpineTest/SpineTest.js index c8a6353de2..6d9fdb96f2 100644 --- a/test/visual-tests/src/SpineTest/SpineTest.js +++ b/test/visual-tests/src/SpineTest/SpineTest.js @@ -74,7 +74,7 @@ var SpineTestLayer = BaseTestLayer.extend({ } }); -var customSkeletonAnimation = sp.SkeletonAnimation.extend({ +var customSkeletonAnimation = sp._SGSkeletonAnimation.extend({ ctor:function () { this._super.apply(this, arguments); } @@ -100,7 +100,7 @@ var SpineTestLayerNormal = SpineTestLayer.extend({ spineBoy = new customSkeletonAnimation('spine/spineboy.json', 'spine/spineboy.atlas'); } else { - spineBoy = new sp.SkeletonAnimation('spine/spineboy.json', 'spine/spineboy.atlas'); + spineBoy = new sp._SGSkeletonAnimation('spine/spineboy.json', 'spine/spineboy.atlas'); } spineBoy.setPosition(cc.p(size.width / 2, size.height / 2 - 150)); spineBoy.setMix('walk', 'jump', 0.2); @@ -186,16 +186,16 @@ var SpineTestLayerNormal = SpineTestLayer.extend({ var entry = this._spineboy.getCurrent(); var animationName = (entry && entry.animation) ? entry.animation.name : 0; switch(type) { - case sp.ANIMATION_EVENT_TYPE.START: + case sp.AnimationEventType.START: cc.log(trackIndex + " start: " + animationName); break; - case sp.ANIMATION_EVENT_TYPE.END: + case sp.AnimationEventType.END: cc.log(trackIndex + " end:" + animationName); break; - case sp.ANIMATION_EVENT_TYPE.EVENT: + case sp.AnimationEventType.EVENT: cc.log(trackIndex + " event: " + animationName); break; - case sp.ANIMATION_EVENT_TYPE.COMPLETE: + case sp.AnimationEventType.COMPLETE: cc.log(trackIndex + " complete: " + animationName + "," + loopCount); if(this._flipped){ this._flipped = false; @@ -223,7 +223,7 @@ var SpineTestLayerFFD = SpineTestLayer.extend({ ctor: function(){ this._super(cc.color(0,0,0,255), cc.color(98,99,117,255)); - var skeletonNode = new sp.SkeletonAnimation("spine/goblins-ffd.json", "spine/goblins-ffd.atlas", 1.5); + var skeletonNode = new sp._SGSkeletonAnimation("spine/goblins-ffd.json", "spine/goblins-ffd.atlas", 1.5); skeletonNode.setAnimation(0, "walk", true); skeletonNode.setSkin("goblin"); @@ -267,7 +267,7 @@ var SpineTestPerformanceLayer = SpineTestLayer.extend({ event: cc.EventListener.TOUCH_ONE_BY_ONE, onTouchBegan: function(touch, event){ var pos = self.convertToNodeSpace(touch.getLocation()); - var skeletonNode = new sp.SkeletonAnimation("spine/goblins-ffd.json", "spine/goblins-ffd.atlas", 1.5); + var skeletonNode = new sp._SGSkeletonAnimation("spine/goblins-ffd.json", "spine/goblins-ffd.atlas", 1.5); skeletonNode.setAnimation(0, "walk", true); skeletonNode.setSkin("goblin");